问:
Zend sanitizing input
I've sanitized my form's input (textarea field) and when I display it on my view it comes out like this:

I\'m in it to win it!! I\'m looking forward to playing the contest in
Contest Central. He aims to cross-pollinate the stage, screen and stereo
with work that speaks to both the humor and frustrations of modern life.

In my controller I have this:

```<code>public function init(){

 $this->view->setEscape('html_entity_decode');
 $this->view->setEscape('stripslashes');

}
</code>```

But only one works, if I erase one the setEscape then the other works and vice versa. So I can get stripslashes to work if I put it first but html_entity_decode wont work and vice versa

答:
You need to define your own function that should be used for escaping. For example, you can defined a class My_Tools in library/My/Tools.php as follows:

```<code><?php
#Tools.php

class My_Tools {

    /**
     * My custom escape function
     *
     * @param string $str String to be escaped
     * @return string Escaped string
     */
    static function myEscape($str) {
        $str = html_entity_decode($str);
        return stripslashes($str);
    }

}

?>
</code>```

Then, your init() could have the following form:

```<code>public function init() {

    require_once(APPLICATION_PATH . '/../library/My/Tools.php');
    $this->view->setEscape(array('My_Tools', 'myEscape'));

}
</code>```

Off course it would be better to add Tools to Autoloader, but for this is just an example.

Title: Zend sanitizing input

Body:
I've sanitized my form's input (textarea field) and when I display it on my view it comes out like this:

I\'m in it to win it!! I\'m looking forward to playing the contest in
Contest Central. He aims to cross-pollinate the stage, screen and stereo
with work that speaks to both the humor and frustrations of modern life.

In my controller I have this:

public function init(){

 $this->view->setEscape('html_entity_decode');
 $this->view->setEscape('stripslashes');

}

But only one works, if I erase one the setEscape then the other works and vice versa. So I can get stripslashes to work if I put it first but html_entity_decode wont work and vice versa

Body:
You need to define your own function that should be used for escaping. For example, you can defined a class My_Tools in library/My/Tools.php as follows:

<?php
#Tools.php

class My_Tools {

    /**
     * My custom escape function
     *
     * @param string $str String to be escaped
     * @return string Escaped string
     */
    static function myEscape($str) {
        $str = html_entity_decode($str);
        return stripslashes($str);
    }

}

?>

Then, your init() could have the following form:

public function init() {

    require_once(APPLICATION_PATH . '/../library/My/Tools.php');
    $this->view->setEscape(array('My_Tools', 'myEscape'));

}

Off course it would be better to add Tools to Autoloader, but for this is just an example.


来源: stackexchange

问:
Issue when using string operation and pipe together
I have a HTML in a Angular 2.0 template like following:

```<code><span> Total Employee {{employeeCount> 0 ? '(' + employeeCount+ ')' : ''}} ></span>
</code>```

My customFormatter takes a value and format it with coma separator if its a number.

It works fine. Now I want to use a custom pipe to format the employee count and I have used the following code:

```<code><span>
   Total Employee {{employeeCount> 0 ? '(' + employeeCount | customFormatter + ')' : ''}} >
</span>
</code>```

But it gives syntax error: "Error: Template parse errors: Parser Error: Conditional expression..."

The pipe is working when I use as following:

```<code><span> Total Employee {{employeeCount | customFormatter }} ></span>
</code>```

How can I solve my issue?

答:
try this.</p>

```<code><span>
Total Employee {{employeeCount> 0 ? '(' + employeeCount + ')'| customFormatter : ''}}
</span>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a HTML in a Angular 2.0 template like following:

 Total Employee {{employeeCount> 0 ? '(' + employeeCount+ ')' : ''}} >

My customFormatter takes a value and format it with coma separator if its a number.

It works fine. Now I want to use a custom pipe to format the employee count and I have used the following code:

   Total Employee {{employeeCount> 0 ? '(' + employeeCount | customFormatter + ')' : ''}} >

But it gives syntax error: "Error: Template parse errors: Parser Error: Conditional expression..."

The pipe is working when I use as following:

 Total Employee {{employeeCount | customFormatter }} >

How can I solve my issue?

Body:
try this.

<span>
Total Employee {{employeeCount> 0 ? '(' + employeeCount + ')'| customFormatter : ''}}
</span>


问:
In UWP, how can I reset an app’s data?
I know that in order to reset an app’s data, I have to open the Settings app from Start menu. Head to System > Apps & Features, locate the app, then click the "Advance Options" and tap Reset but I want to achieve this by code. I think I have to call this line but I don't know if I have to do something else: Windows.Storage.ApplicationData.Current.ClearAsync()</p>

答:
This will clear all the application data from the local, roaming and temporary folders.</p>

```<code>await ApplicationData.Current.ClearAsync();
</code>```

Title: In UWP, how can I reset an app’s data?

Body:
This will clear all the application data from the local, roaming and temporary folders.

await ApplicationData.Current.ClearAsync();


问:
Producer consumer semaphore value is not correct
I'm trying to implement producer-consumer problem in C using processes and System V IPC and I'm stuck on one thing. This is early version of my code (without implementing queue operations or even producer and consumer executing in loop) that I was using to learn and test how semaphores work:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#include <time.h>
#include "sem.h"
#include "shm.h"

#define BUFFER_SIZE 9

int full;
int empty;
int mutex;

struct buff {
    int queue[BUFFER_SIZE];
} *buffer;

void producer();
void consumer();

int main() {

    int parent_pid, pid, i;

    parent_pid = getpid();

    int shmid = allocate_shared_memory(sizeof(*buffer));
    buffer = (struct buff *) attach_shared_memory(shmid);

    for (i = 0; i < BUFFER_SIZE; i++) {
        buffer->queue[i] = 0;
    }

    full = sem_allocate();
    empty = sem_allocate();
    mutex = sem_allocate();

    printf("Full %d\n", full);
    printf("Empty %d\n", empty);
    printf("Mutex %d\n", mutex);

    sem_init(full, 0);
    sem_init(empty, BUFFER_SIZE);
    sem_init(mutex, 1);

    printf("Full value %d\n", sem_get_val(full));
    printf("Empty value %d\n", sem_get_val(empty));
    printf("Mutex value %d\n", sem_get_val(mutex));

    srand(time(0));

    pid = fork();
    if (!pid) {
        printf("Producer here: %d\n", getpid());
        producer();
        printf("Full value after prod() %d\n", sem_get_val(full));
        return 0;
    } else printf("Created new producent: %d\n", pid);

    sleep(1);

    pid = fork();
    if (!pid) {
        printf("Consumer here: %d\n", getpid());
        printf("Full value before cons() %d\n", sem_get_val(full)); //here I always get 0
        consumer();
        return 0;
    } else printf("Created new consumer: %d\n", pid);

       while (1)
    {
        int status;
        pid_t done = wait(&status);
        if (done == -1)
        {
            if (errno == ECHILD) break; // no more child processes
        }
        else
        {
            if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
                exit(1);
            }
        }
    }

    if (getpid() == parent_pid) {
        sem_deallocate(full);
        sem_deallocate(empty);
        sem_deallocate(mutex);
    }
}

void producer() {

    sem_wait(empty);
    sem_wait(mutex);
    printf("Producer is producing!\n");
    buffer->queue[0]=0;
    sem_post(mutex);
    sem_post(full);
}

void consumer() {

    sem_wait(full);
    sem_wait(mutex);
    printf("Consumer is consuming!\n");
    sem_post(mutex);
    sem_post(empty);

}

int sem_allocate() {
    return semget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
}

void sem_deallocate(int semid) {

        if (semctl(semid, 0, IPC_RMID, NULL) == -1)
    {
        perror("Error releasing semaphore!\n");
        exit(EXIT_FAILURE);
    }
}

int sem_init(int semid, int value) {
    union semun arg;
    arg.val = value;
    if (semctl(semid, 0, SETVAL, arg) == -1) {
        perror("semctl");
        return -1;
    }else return 1;
}

int sem_wait(int semid) {
    printf("Someone is waiting %d\n", semid);
    struct sembuf sem = { 0, -1, SEM_UNDO };
    return semop(semid, &sem, 1);
}

int sem_post(int semid) {
    printf("Someone is posting %d\n", semid);
    struct sembuf sem = { 0, 1, SEM_UNDO };
    return semop(semid, &sem, 1);
}

int sem_get_val(int semid) {
    return semctl(semid, 0, GETVAL, 0);
}

int allocate_shared_memory(int size) {
    return shmget(IPC_PRIVATE, size, IPC_CREAT | SHM_W | SHM_R);
}

void deallocate_shared_memory(const void* addr, int shmid) {
    shmctl(shmid, IPC_RMID, 0);
}

void* attach_shared_memory(int shmid) {
    return shmat(shmid, NULL, 0);
}
</code>```

sem.h:

```<code>#include <sys/types.h>
#include <errno.h>

union semun {
    int val;
    struct semid_ds *buf;
    ushort* array;
};

int sem_post(int);

int sem_wait(int);

int sem_allocate();

void sem_deallocate(int);

int sem_init(int, int);

int sem_get_val(int);
</code>```

shm.h:

```<code>#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>

int allocate_shared_memory(int size);

void deallocate_shared_memory(const void* addr, int shmid);

void* attach_shared_memory(int shmid);
</code>```

Why before executing consumer function value of full semaphore is 0? Even if right after producer finishes his job the value is 1...

I'm new to this kind of topics so maybe there is an obvious explenation of the situation, but I have no idea what can I do and hope you can help me.

答:
You initialize the "full" semaphore to zero.  Your "child" producer, prior to exiting calls your sem_post() function, which calls semop() with a SEM_UNDO argument.

```<code>int sem_post(int semid) {
    printf("Someone is posting %d\n", semid);
    struct sembuf sem = { 0, 1, SEM_UNDO };
    return semop(semid, &sem, 1);
}
</code>```

The Ubuntu Linux man page for semop says the following about SEM_UNDO:

... If  an  operation  specifies SEM_UNDO, it will be automatically
  undone when the process terminates.

This means, "producer" increments "full" prior to exiting, then after it exits the system "undoes" the increment (i.e. it decrements "full") setting it back to zero.

So,for the purposes of the "full" semaphore, you should NOT specify SEM_UNDO.

Body:
I'm trying to implement producer-consumer problem in C using processes and System V IPC and I'm stuck on one thing. This is early version of my code (without implementing queue operations or even producer and consumer executing in loop) that I was using to learn and test how semaphores work:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#include <time.h>
#include "sem.h"
#include "shm.h"

#define BUFFER_SIZE 9

int full;
int empty;
int mutex;

struct buff {
    int queue[BUFFER_SIZE];
} *buffer;

void producer();
void consumer();

int main() {

    int parent_pid, pid, i;

    parent_pid = getpid();

    int shmid = allocate_shared_memory(sizeof(*buffer));
    buffer = (struct buff *) attach_shared_memory(shmid);

    for (i = 0; i < BUFFER_SIZE; i++) {
        buffer->queue[i] = 0;
    }

    full = sem_allocate();
    empty = sem_allocate();
    mutex = sem_allocate();

    printf("Full %d\n", full);
    printf("Empty %d\n", empty);
    printf("Mutex %d\n", mutex);

    sem_init(full, 0);
    sem_init(empty, BUFFER_SIZE);
    sem_init(mutex, 1);

    printf("Full value %d\n", sem_get_val(full));
    printf("Empty value %d\n", sem_get_val(empty));
    printf("Mutex value %d\n", sem_get_val(mutex));

    srand(time(0));

    pid = fork();
    if (!pid) {
        printf("Producer here: %d\n", getpid());
        producer();
        printf("Full value after prod() %d\n", sem_get_val(full));
        return 0;
    } else printf("Created new producent: %d\n", pid);

    sleep(1);

    pid = fork();
    if (!pid) {
        printf("Consumer here: %d\n", getpid());
        printf("Full value before cons() %d\n", sem_get_val(full)); //here I always get 0
        consumer();
        return 0;
    } else printf("Created new consumer: %d\n", pid);

       while (1)
    {
        int status;
        pid_t done = wait(&status);
        if (done == -1)
        {
            if (errno == ECHILD) break; // no more child processes
        }
        else
        {
            if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
                exit(1);
            }
        }
    }

    if (getpid() == parent_pid) {
        sem_deallocate(full);
        sem_deallocate(empty);
        sem_deallocate(mutex);
    }
}

void producer() {

    sem_wait(empty);
    sem_wait(mutex);
    printf("Producer is producing!\n");
    buffer->queue[0]=0;
    sem_post(mutex);
    sem_post(full);
}

void consumer() {

    sem_wait(full);
    sem_wait(mutex);
    printf("Consumer is consuming!\n");
    sem_post(mutex);
    sem_post(empty);

}

int sem_allocate() {
    return semget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
}

void sem_deallocate(int semid) {

        if (semctl(semid, 0, IPC_RMID, NULL) == -1)
    {
        perror("Error releasing semaphore!\n");
        exit(EXIT_FAILURE);
    }
}

int sem_init(int semid, int value) {
    union semun arg;
    arg.val = value;
    if (semctl(semid, 0, SETVAL, arg) == -1) {
        perror("semctl");
        return -1;
    }else return 1;
}

int sem_wait(int semid) {
    printf("Someone is waiting %d\n", semid);
    struct sembuf sem = { 0, -1, SEM_UNDO };
    return semop(semid, &sem, 1);
}

int sem_post(int semid) {
    printf("Someone is posting %d\n", semid);
    struct sembuf sem = { 0, 1, SEM_UNDO };
    return semop(semid, &sem, 1);
}

int sem_get_val(int semid) {
    return semctl(semid, 0, GETVAL, 0);
}

int allocate_shared_memory(int size) {
    return shmget(IPC_PRIVATE, size, IPC_CREAT | SHM_W | SHM_R);
}

void deallocate_shared_memory(const void* addr, int shmid) {
    shmctl(shmid, IPC_RMID, 0);
}

void* attach_shared_memory(int shmid) {
    return shmat(shmid, NULL, 0);
}

sem.h:

#include <sys/types.h>
#include <errno.h>

union semun {
    int val;
    struct semid_ds *buf;
    ushort* array;
};

int sem_post(int);

int sem_wait(int);

int sem_allocate();

void sem_deallocate(int);

int sem_init(int, int);

int sem_get_val(int);

shm.h:

#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>

int allocate_shared_memory(int size);

void deallocate_shared_memory(const void* addr, int shmid);

void* attach_shared_memory(int shmid);

Why before executing consumer function value of full semaphore is 0? Even if right after producer finishes his job the value is 1...

I'm new to this kind of topics so maybe there is an obvious explenation of the situation, but I have no idea what can I do and hope you can help me.

Body:
You initialize the "full" semaphore to zero.  Your "child" producer, prior to exiting calls your sem_post() function, which calls semop() with a SEM_UNDO argument.

int sem_post(int semid) {
    printf("Someone is posting %d\n", semid);
    struct sembuf sem = { 0, 1, SEM_UNDO };
    return semop(semid, &sem, 1);
}

The Ubuntu Linux man page for semop says the following about SEM_UNDO:

... If  an  operation  specifies SEM_UNDO, it will be automatically
  undone when the process terminates.

This means, "producer" increments "full" prior to exiting, then after it exits the system "undoes" the increment (i.e. it decrements "full") setting it back to zero.

So,for the purposes of the "full" semaphore, you should NOT specify SEM_UNDO.


问:
How to use Pygame's sprite_collide_mask method to detect direction of collision?
So what I'm trying to do is to create a pool table game using Pygame, with balls bouncing off the edges of the pool table like so.

I have png image of a pool table like so:

The white parts are transparent, and so when a mask is made, and the ball is placed inside the transparent part, it collides using Pygame's sprite.collide_mask(ballsprite, tablesprite) function. The background is a dark-greenish color.

However, the sprite.collide_mask function returns a point of collision, and I don't know how to calculate the resultant direction that the ball should travel in, since I only have the ball's starting point (since the last collision) and the point of collision to work with.

I know I should calculate a normal vector to the surface, but how am I supposed to do this when Pygame's mask collision doesn't provide any functions to do this?

One solution I thought of is to create a rectangular bounding box that approximates the white (transparent) area. But, if I set the rectangle as transparent, then, nothing will ever collide (if I use the mask method), and if I set the rectangle to the same color as my background, then it will always register a collision, since the ball is in the rectangle's 'rect'.

How should I go about handling collision detection, and handling the change of direction for my game?

(I can provide my code if need be)

答:
I think it would be better to create a billiards game with the help of the physics library Pymunk. It can be a bit difficult to get started, but then you don't have to implement the physics on your own.

I've got an example here, just to demonstrate how the code could look like. You'll have to familiarize yourself with the library to understand everything. (Steer the ball with the WASD keys.)

```<code>import math

import pygame as pg
import pymunk as pm
from pymunk import Vec2d

def flipy(p):
    """Convert chipmunk coordinates to pygame coordinates."""
    return Vec2d(p[0], -p[1]+600)

class Ball(pg.sprite.Sprite):

    def __init__(self, pos, space):
        super().__init__()
        self.image = pg.Surface((60, 60), pg.SRCALPHA)
        pg.draw.circle(self.image, pg.Color('steelblue2'), (30, 30), 29)
        pg.draw.circle(self.image, pg.Color('black'), (30, 10), 5)
        self.rect = self.image.get_rect(center=pos)
        self.orig_image = self.image
        # Create the physics body and shape of this object.
        self.body = pm.Body()
        self.shape = pm.Circle(self.body, radius=30)
        self.shape.density = .0001
        self.shape.friction = .1
        self.shape.elasticity = .99
        self.body.position = pos
        # Add them to the Pymunk space.
        self.space = space
        self.space.add(self.body, self.shape)
        print(self.body.mass)

        self.accel_forw = False
        self.accel_back = False
        self.turn_left = False
        self.turn_right = False
        self.topspeed = 1790
        self.angle = 0

    def handle_event(self, event):
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_w:
                self.accel_forw = True
            if event.key == pg.K_a:
                self.turn_left = True
            if event.key == pg.K_d:
                self.turn_right = True
            if event.key == pg.K_s:
                self.accel_back = True
        if event.type == pg.KEYUP:
            if event.key == pg.K_w:
                self.accel_forw = False
            if event.key == pg.K_a:
                self.turn_left = False
            if event.key == pg.K_d:
                self.turn_right = False
            if event.key == pg.K_s:
                self.accel_back = False

    def update(self, dt):
        # Accelerate the pymunk body of this sprite.
        if self.accel_forw and self.body.velocity.length < self.topspeed:
            self.body.apply_force_at_local_point(Vec2d(0, 624), Vec2d(0, 0))
        if self.accel_back and self.body.velocity.length < self.topspeed:
            self.body.apply_force_at_local_point(Vec2d(0, -514), Vec2d(0, 0))
        if self.turn_left and self.body.velocity.length < self.topspeed:
            self.body.angle += .1
            self.body.angular_velocity = 0
        if self.turn_right and self.body.velocity.length < self.topspeed:
            self.body.angle -= .1
            self.body.angular_velocity = 0
        # Rotate the image of the sprite.
        self.angle = self.body.angle
        self.rect.center = flipy(self.body.position)
        self.image = pg.transform.rotozoom(
            self.orig_image, math.degrees(self.body.angle), 1)
        self.rect = self.image.get_rect(center=self.rect.center)

class Wall(pg.sprite.Sprite):

    def __init__(self, pos, verts, space, mass, *sprite_groups):
        super().__init__(*sprite_groups)
        # Determine the width and height of the surface.
        width = max(v[0] for v in verts)
        height = max(v[1] for v in verts)
        self.image = pg.Surface((width, height), pg.SRCALPHA)
        pg.draw.polygon(self.image, pg.Color('sienna1'), verts)
        self.rect = self.image.get_rect(topleft=pos)

        moment = pm.moment_for_poly(mass, verts)
        self.body = pm.Body(mass, moment, pm.Body.STATIC)
        # Need to transform the vertices for the pymunk poly shape,
        # so that they fit to the image vertices.
        verts2 = [(x, -y) for x, y in verts]
        self.shape = pm.Poly(self.body, verts2, radius=2)
        self.shape.friction = 0.1
        self.shape.elasticity = .92
        self.body.position = flipy(pos)
        self.space = space
        self.space.add(self.shape)

class Game:

    def __init__(self):
        self.done = False
        self.screen = pg.display.set_mode((800, 600))
        self.clock = pg.time.Clock()
        self.bg_color = pg.Color(60, 60, 60)

        self.space = pm.Space()
        self.space.gravity = Vec2d(0.0, 0.0)
        self.space.damping = .4

        self.all_sprites = pg.sprite.Group()

        self.ball = Ball((300, 300), self.space)
        self.ball2 = Ball((400, 300), self.space)
        self.all_sprites.add(self.ball, self.ball2)
        # Position and vertices tuples for the walls.
        vertices = [
            ([10, 80], ((0, 0), (200, 0), (90, 500), (0, 500))),
            ([400, 250], ((40, 80), (200, 0), (170, 90), (10, 170))),
            ([600, 450], ((20, 40), (300, 0), (300, 120), (10, 100))),
            ([760, 10], ((0, 0), (30, 0), (30, 420), (0, 400))),
            ([10, 10], ((0, 0), (760, 0), (700, 60), (0, 60))),
            ([10, 580], ((0, 0), (760, 0), (700, 60), (0, 60))),
            ]

        for pos, verts in vertices:
            Wall(pos, verts, self.space, 1, self.all_sprites)

    def run(self):
        while not self.done:
            self.dt = self.clock.tick(30) / 1000
            self.handle_events()
            self.run_logic()
            self.draw()

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True

            self.ball.handle_event(event)

    def run_logic(self):
        self.space.step(1/60)
        self.all_sprites.update(self.dt)

    def draw(self):
        self.screen.fill(self.bg_color)
        self.all_sprites.draw(self.screen)
        pg.display.flip()

if __name__ == '__main__':
    pg.init()
    Game().run()
    pg.quit()
</code>```

Body:
I think it would be better to create a billiards game with the help of the physics library Pymunk. It can be a bit difficult to get started, but then you don't have to implement the physics on your own.

I've got an example here, just to demonstrate how the code could look like. You'll have to familiarize yourself with the library to understand everything. (Steer the ball with the WASD keys.)

import math

import pygame as pg
import pymunk as pm
from pymunk import Vec2d

def flipy(p):
    """Convert chipmunk coordinates to pygame coordinates."""
    return Vec2d(p[0], -p[1]+600)

class Ball(pg.sprite.Sprite):

    def __init__(self, pos, space):
        super().__init__()
        self.image = pg.Surface((60, 60), pg.SRCALPHA)
        pg.draw.circle(self.image, pg.Color('steelblue2'), (30, 30), 29)
        pg.draw.circle(self.image, pg.Color('black'), (30, 10), 5)
        self.rect = self.image.get_rect(center=pos)
        self.orig_image = self.image
        # Create the physics body and shape of this object.
        self.body = pm.Body()
        self.shape = pm.Circle(self.body, radius=30)
        self.shape.density = .0001
        self.shape.friction = .1
        self.shape.elasticity = .99
        self.body.position = pos
        # Add them to the Pymunk space.
        self.space = space
        self.space.add(self.body, self.shape)
        print(self.body.mass)

        self.accel_forw = False
        self.accel_back = False
        self.turn_left = False
        self.turn_right = False
        self.topspeed = 1790
        self.angle = 0

    def handle_event(self, event):
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_w:
                self.accel_forw = True
            if event.key == pg.K_a:
                self.turn_left = True
            if event.key == pg.K_d:
                self.turn_right = True
            if event.key == pg.K_s:
                self.accel_back = True
        if event.type == pg.KEYUP:
            if event.key == pg.K_w:
                self.accel_forw = False
            if event.key == pg.K_a:
                self.turn_left = False
            if event.key == pg.K_d:
                self.turn_right = False
            if event.key == pg.K_s:
                self.accel_back = False

    def update(self, dt):
        # Accelerate the pymunk body of this sprite.
        if self.accel_forw and self.body.velocity.length < self.topspeed:
            self.body.apply_force_at_local_point(Vec2d(0, 624), Vec2d(0, 0))
        if self.accel_back and self.body.velocity.length < self.topspeed:
            self.body.apply_force_at_local_point(Vec2d(0, -514), Vec2d(0, 0))
        if self.turn_left and self.body.velocity.length < self.topspeed:
            self.body.angle += .1
            self.body.angular_velocity = 0
        if self.turn_right and self.body.velocity.length < self.topspeed:
            self.body.angle -= .1
            self.body.angular_velocity = 0
        # Rotate the image of the sprite.
        self.angle = self.body.angle
        self.rect.center = flipy(self.body.position)
        self.image = pg.transform.rotozoom(
            self.orig_image, math.degrees(self.body.angle), 1)
        self.rect = self.image.get_rect(center=self.rect.center)

class Wall(pg.sprite.Sprite):

    def __init__(self, pos, verts, space, mass, *sprite_groups):
        super().__init__(*sprite_groups)
        # Determine the width and height of the surface.
        width = max(v[0] for v in verts)
        height = max(v[1] for v in verts)
        self.image = pg.Surface((width, height), pg.SRCALPHA)
        pg.draw.polygon(self.image, pg.Color('sienna1'), verts)
        self.rect = self.image.get_rect(topleft=pos)

        moment = pm.moment_for_poly(mass, verts)
        self.body = pm.Body(mass, moment, pm.Body.STATIC)
        # Need to transform the vertices for the pymunk poly shape,
        # so that they fit to the image vertices.
        verts2 = [(x, -y) for x, y in verts]
        self.shape = pm.Poly(self.body, verts2, radius=2)
        self.shape.friction = 0.1
        self.shape.elasticity = .92
        self.body.position = flipy(pos)
        self.space = space
        self.space.add(self.shape)

class Game:

    def __init__(self):
        self.done = False
        self.screen = pg.display.set_mode((800, 600))
        self.clock = pg.time.Clock()
        self.bg_color = pg.Color(60, 60, 60)

        self.space = pm.Space()
        self.space.gravity = Vec2d(0.0, 0.0)
        self.space.damping = .4

        self.all_sprites = pg.sprite.Group()

        self.ball = Ball((300, 300), self.space)
        self.ball2 = Ball((400, 300), self.space)
        self.all_sprites.add(self.ball, self.ball2)
        # Position and vertices tuples for the walls.
        vertices = [
            ([10, 80], ((0, 0), (200, 0), (90, 500), (0, 500))),
            ([400, 250], ((40, 80), (200, 0), (170, 90), (10, 170))),
            ([600, 450], ((20, 40), (300, 0), (300, 120), (10, 100))),
            ([760, 10], ((0, 0), (30, 0), (30, 420), (0, 400))),
            ([10, 10], ((0, 0), (760, 0), (700, 60), (0, 60))),
            ([10, 580], ((0, 0), (760, 0), (700, 60), (0, 60))),
            ]

        for pos, verts in vertices:
            Wall(pos, verts, self.space, 1, self.all_sprites)

    def run(self):
        while not self.done:
            self.dt = self.clock.tick(30) / 1000
            self.handle_events()
            self.run_logic()
            self.draw()

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True

            self.ball.handle_event(event)

    def run_logic(self):
        self.space.step(1/60)
        self.all_sprites.update(self.dt)

    def draw(self):
        self.screen.fill(self.bg_color)
        self.all_sprites.draw(self.screen)
        pg.display.flip()

if __name__ == '__main__':
    pg.init()
    Game().run()
    pg.quit()


问:
Verify public key matches signature of private key
I'm new to openssl API.

my goal is to verify that my public key is "related" to my hidden private key.

solution using openssl cli:

I have a certificate , the private key is hidden (in HSM)
I have a buffer:

```<code>echo "hello world!!!!" > sign.txt
</code>```

using following commands I create sha256 signature of my buffer similar to what my HSM will do :

```<code>openssl dgst -sha256 -sign myrootca.key.insecure -out sign.sha256 sign.txt
</code>```

extract public key:

```<code>openssl x509 -pubkey -noout -in myrootca.crt  > myrootca.publicKey.pem
</code>```

verify public key :

```<code>openssl dgst -sha256 -verify myrootca.publicKey.pem -signature sign.sha256 sign.txt
</code>```

I think I know how to represent my public key and signature file correctly

```<code>sigkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL,
                                 e, "key file");
sigbio = BIO_new_file(sigfile, "rb");
</code>```

but can't find a proper API to continue from here

答:
Issue I've encountered was figuring out what is the signature length before hand to allocate place for the signature that must have prior knowledge on RSA key size and type of hash

```<code>sha256 + RSA1024 ~ 128byte
sha256 + RSA2048 ~ 256byte
</code>```

using openssl API based of this guide I've managed to verify signature using following code :

```<code>Verifyx509VsPrivKeySig(X509* x509Cert,char* signature,size_t sigLen,char* message,size_t messageLen)
{
        int rc;
        EVP_PKEY* pPubkey = NULL;
        EVP_MD_CTX* ctx = NULL;

        rc = getX509Publickey(x509Cert, &pPubkey);
        if (rc != SSL_OK)
        {
                goto err_verify;
        }

        ctx = EVP_MD_CTX_create();
        if(ctx == NULL) {
                PRINT_LOG_ERR("EVP_MD_CTX_create failed, error 0x%lx\n", ERR_get_error());
                /* failed */
                goto err_verify;
        }

        rc = EVP_DigestVerifyInit(ctx, NULL, EVP_sha256(), NULL, pPubkey);
        if(rc != 1) {
                PRINT_LOG_ERR("EVP_DigestVerifyInit failed, error 0x%lx\n", ERR_get_error());
                goto err_EVP_XTX_destroy; /* failed */
        }

        rc = EVP_DigestVerifyUpdate(ctx, message, messageLen);
        if(rc != 1) {
                PRINT_LOG_ERR("EVP_DigestVerifyUpdate failed, error 0x%lx\n", ERR_get_error());
                goto err_EVP_XTX_destroy; /* failed */
        }

        /* Clear any errors for the call below */
        ERR_clear_error();

        rc = EVP_DigestVerifyFinal(ctx,(const unsigned char*) signature, sigLen);
        if(rc != 1) {
                PRINT_LOG_ERR("EVP_DigestVerifyFinal failed, error 0x%lx\n", ERR_get_error());
                goto err_EVP_XTX_destroy; /* failed */
        }

        /*if we got to here , verify sig finished with good result!!*/
    if(ctx) {
        EVP_MD_CTX_destroy(ctx);
        ctx = NULL;
    }

    return true;
    //////////////////// ERROR HANDLING ///////////////////////////
err_EVP_XTX_destroy:
        EVP_MD_CTX_destroy(ctx);
err_verify:
        return false;
}
</code>```

Body:
I'm new to openssl API.

my goal is to verify that my public key is "related" to my hidden private key.

solution using openssl cli:

I have a certificate , the private key is hidden (in HSM)
I have a buffer:

echo "hello world!!!!" > sign.txt

using following commands I create sha256 signature of my buffer similar to what my HSM will do :

openssl dgst -sha256 -sign myrootca.key.insecure -out sign.sha256 sign.txt

extract public key:

openssl x509 -pubkey -noout -in myrootca.crt  > myrootca.publicKey.pem

verify public key :

openssl dgst -sha256 -verify myrootca.publicKey.pem -signature sign.sha256 sign.txt

I think I know how to represent my public key and signature file correctly

sigkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL,
                                 e, "key file");
sigbio = BIO_new_file(sigfile, "rb");

but can't find a proper API to continue from here

Body:
Issue I've encountered was figuring out what is the signature length before hand to allocate place for the signature that must have prior knowledge on RSA key size and type of hash

sha256 + RSA1024 ~ 128byte
sha256 + RSA2048 ~ 256byte

using openssl API based of this guide I've managed to verify signature using following code :

Verifyx509VsPrivKeySig(X509* x509Cert,char* signature,size_t sigLen,char* message,size_t messageLen)
{
        int rc;
        EVP_PKEY* pPubkey = NULL;
        EVP_MD_CTX* ctx = NULL;

        rc = getX509Publickey(x509Cert, &pPubkey);
        if (rc != SSL_OK)
        {
                goto err_verify;
        }

        ctx = EVP_MD_CTX_create();
        if(ctx == NULL) {
                PRINT_LOG_ERR("EVP_MD_CTX_create failed, error 0x%lx\n", ERR_get_error());
                /* failed */
                goto err_verify;
        }

        rc = EVP_DigestVerifyInit(ctx, NULL, EVP_sha256(), NULL, pPubkey);
        if(rc != 1) {
                PRINT_LOG_ERR("EVP_DigestVerifyInit failed, error 0x%lx\n", ERR_get_error());
                goto err_EVP_XTX_destroy; /* failed */
        }

        rc = EVP_DigestVerifyUpdate(ctx, message, messageLen);
        if(rc != 1) {
                PRINT_LOG_ERR("EVP_DigestVerifyUpdate failed, error 0x%lx\n", ERR_get_error());
                goto err_EVP_XTX_destroy; /* failed */
        }

        /* Clear any errors for the call below */
        ERR_clear_error();

        rc = EVP_DigestVerifyFinal(ctx,(const unsigned char*) signature, sigLen);
        if(rc != 1) {
                PRINT_LOG_ERR("EVP_DigestVerifyFinal failed, error 0x%lx\n", ERR_get_error());
                goto err_EVP_XTX_destroy; /* failed */
        }

        /*if we got to here , verify sig finished with good result!!*/
    if(ctx) {
        EVP_MD_CTX_destroy(ctx);
        ctx = NULL;
    }

    return true;
    //////////////////// ERROR HANDLING ///////////////////////////
err_EVP_XTX_destroy:
        EVP_MD_CTX_destroy(ctx);
err_verify:
        return false;
}


问:
Load More Functionality for

 tag using jQuery
I have

 in foreach loop. I have to put load more link in mega menu.

from above image , I want to put load more link in all li tags if have more than 5 li,

I put below jQuery for that, but it not work. can any one help me?

```<code><script type="text/javascript">
jQuery(document).ready(function () {

    size_li = jQuery(".level1 li").size();
    x=5;
    jQuery('.level1 li":lt('+x+')').show();
    jQuery('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        jQuery('.level1 li":lt('+x+')').show();
    });
});
</script>
</code>```

also add css

```<code><style type="text/css">
.level1 li{
     display:none;
}
</style>
</code>```

Getting Below output

答:
Based on .size() manual

.size() version is deprecated: 1.8, removed: 3.0. So use .length
  instead –

But you can change your code to this (better way):-

```<code>jQuery(document).ready(function () {
    jQuery('ul.level1').each(function(){
      if(jQuery(this).children('li').length>5){
        jQuery(this).children('li:lt(5)').show();
        jQuery(this).append('<button class="loadMore">LoadMore</button>');
      }
    });
    jQuery('ul.level1').on("click",'.loadMore',function (){
        jQuery(this).parent('.level1').children('li:gt(4)').show(); // use gt instead of lt
        jQuery(this).removeClass('loadMore').addClass('loadLess').text('LoadLess');
    });
    jQuery('ul.level1').on("click",'.loadLess',function () {
        jQuery(this).parent('.level1').children('li:gt(4)').hide(); // use gt instead of lt
        jQuery(this).removeClass('loadLess').addClass('loadMore').text('LoadMore');
    });
});
</code>```

Working example code:-

jQuery(document).ready(function () {
    jQuery('ul.level1').each(function(){
      if(jQuery(this).children('li').length>5){
        jQuery(this).children('li:lt(5)').show();
        jQuery(this).append('<button class="loadMore">LoadMore</button>');
      }
    });
    jQuery('ul.level1').on("click",'.loadMore',function (){
        jQuery(this).parent('.level1').children('li:gt(4)').show(); // use gt instead of lt
        jQuery(this).removeClass('loadMore').addClass('loadLess').text('LoadLess');
    });
    jQuery('ul.level1').on("click",'.loadLess',function () {
        jQuery(this).parent('.level1').children('li:gt(4)').hide(); // use gt instead of lt
        jQuery(this).removeClass('loadLess').addClass('loadMore').text('LoadMore');
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.level1{
float:left;
width:25%;
}
.level1 li{
  display:none;
}</code>```

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

```
</div>
</div>
</p>

<p><strong><em>After seeing your website HTML, replace your code with below given code:-</em></strong></p>

```jQuery(document).ready(function () {
    jQuery('ul.level1').each(function(){
      if(jQuery(this).children('li').length){
        jQuery(this).children('li:lt(5)').show();
        jQuery(this).append('<button class="loadMore">LoadMore</button>');
      }
    });
    jQuery('.loadMore').click(function () {
        jQuery(this).parent('ul.level1').children('li:gt(5)').show(); // use gt instead of lt
    });
});
```

Title: Load More Functionality for <li> <ul> <li> tag using jQuery

Body:
I have

 in foreach loop. I have to put load more link in mega menu.

from above image , I want to put load more link in all li tags if have more than 5 li,

I put below jQuery for that, but it not work. can any one help me?

also add css

Getting Below output

Body:
Based on .size() manual

.size() version is deprecated: 1.8, removed: 3.0. So use .length
  instead –

But you can change your code to this (better way):-

jQuery(document).ready(function () {
    jQuery('ul.level1').each(function(){
      if(jQuery(this).children('li').length>5){
        jQuery(this).children('li:lt(5)').show();
        jQuery(this).append('<button class="loadMore">LoadMore</button>');
      }
    });
    jQuery('ul.level1').on("click",'.loadMore',function (){
        jQuery(this).parent('.level1').children('li:gt(4)').show(); // use gt instead of lt
        jQuery(this).removeClass('loadMore').addClass('loadLess').text('LoadLess');
    });
    jQuery('ul.level1').on("click",'.loadLess',function () {
        jQuery(this).parent('.level1').children('li:gt(4)').hide(); // use gt instead of lt
        jQuery(this).removeClass('loadLess').addClass('loadMore').text('LoadMore');
    });
});

Working example code:-

jQuery(document).ready(function () {
    jQuery('ul.level1').each(function(){
      if(jQuery(this).children('li').length>5){
        jQuery(this).children('li:lt(5)').show();
        jQuery(this).append('<button class="loadMore">LoadMore</button>');
      }
    });
    jQuery('ul.level1').on("click",'.loadMore',function (){
        jQuery(this).parent('.level1').children('li:gt(4)').show(); // use gt instead of lt
        jQuery(this).removeClass('loadMore').addClass('loadLess').text('LoadLess');
    });
    jQuery('ul.level1').on("click",'.loadLess',function () {
        jQuery(this).parent('.level1').children('li:gt(4)').hide(); // use gt instead of lt
        jQuery(this).removeClass('loadLess').addClass('loadMore').text('LoadMore');
    });
});

.level1{
float:left;
width:25%;
}
.level1 li{
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="float:left:width:100%">
  <ul class="level1">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
  </ul>
   <ul class="level1">
    <li>11</li>
    <li>12</li>
    <li>13</li>
    <li>14</li>
    <li>15</li>
    <li>16</li>
    <li>17</li>
    <li>18</li>
    <li>19</li>
    <li>20</li>
  </ul>
  <ul class="level1">
    <li>21</li>
    <li>22</li>
    <li>23</li>
    <li>24</li>
    <li>25</li>
    <li>26</li>
    <li>27</li>
    <li>28</li>
    <li>29</li>
    <li>30</li>
  </ul>
</div>

After seeing your website HTML, replace your code with below given code:-

jQuery(document).ready(function () {
    jQuery('ul.level1').each(function(){
      if(jQuery(this).children('li').length){
        jQuery(this).children('li:lt(5)').show();
        jQuery(this).append('<button class="loadMore">LoadMore</button>');
      }
    });
    jQuery('.loadMore').click(function () {
        jQuery(this).parent('ul.level1').children('li:gt(5)').show(); // use gt instead of lt
    });
});


问:
Bootstrap Automatically Hiding my images in my Webpage Php
I'm showing my data in an inline manner using bootstrap like this
for example,

But when I add some bootstrap classed, then my images are not showing.
My Code is :

```<code><div class="container">
    <h3>Teachers:</h3>
    <div class="row">
        <?php
            $queryTeachers = "SELECT places.PLACE_NAME,teacher_status.PERSON_NAME,DATE_FORMAT(teacher_status.STATUS_DATE,'%d-%m-%Y') as STATUS_DATE,DATE_FORMAT(teacher_status.STATUS_TIME,'%h:%i:%s %p') as STATUS_TIME, teachers.IMAGE_FOLDER AS IMAGE_FOLDER,teachers.IMAGE_NAME as IMAGE_NAME FROM places,teacher_status,teachers WHERE places.PLACE_ID=teacher_status.PERSON_CURRENT_PLACE AND teachers.TEACHER_ID=teacher_status.TEACHER_ID;";
            $resultTeachers = mysqli_query($conn,$queryTeachers) or die("Unable to select status". mysqli_error($conn));
            while($row=mysqli_fetch_assoc($resultTeachers)) {
                echo '<div class="col-lg-3">';
                echo '<img src="'."../".$row['IMAGE_FOLDER'].$row['IMAGE_NAME'].'" width="130" height="150"/>';
                echo "<br>";
                echo "Persone Name : ".ucwords($row['PERSON_NAME']);
                echo "<br>";
                echo "Current Place : ".ucwords($row['PLACE_NAME']);
                echo "<br>";
                echo "Status Date : ".$row['STATUS_DATE'];
                echo "<br>";
                echo "Status Time : ".$row['STATUS_TIME'];
                echo "<br><br>";
                echo '</div>';
            }
        ?>
    </div>
</div>
</code>```

I'm completely new to bootstrap and only know the basics.

答:
Don't use fixed height and width in images just use a class ie : img-responsive

eg:- class="img-responsive" in img tag

Body:
I'm showing my data in an inline manner using bootstrap like this
for example,

But when I add some bootstrap classed, then my images are not showing.
My Code is :

Teachers:

        <?php
            $queryTeachers = "SELECT places.PLACE_NAME,teacher_status.PERSON_NAME,DATE_FORMAT(teacher_status.STATUS_DATE,'%d-%m-%Y') as STATUS_DATE,DATE_FORMAT(teacher_status.STATUS_TIME,'%h:%i:%s %p') as STATUS_TIME, teachers.IMAGE_FOLDER AS IMAGE_FOLDER,teachers.IMAGE_NAME as IMAGE_NAME FROM places,teacher_status,teachers WHERE places.PLACE_ID=teacher_status.PERSON_CURRENT_PLACE AND teachers.TEACHER_ID=teacher_status.TEACHER_ID;";
            $resultTeachers = mysqli_query($conn,$queryTeachers) or die("Unable to select status". mysqli_error($conn));
            while($row=mysqli_fetch_assoc($resultTeachers)) {
                echo '
';
                echo '';
                echo "
";
                echo "Persone Name : ".ucwords($row['PERSON_NAME']);
                echo "
";
                echo "Current Place : ".ucwords($row['PLACE_NAME']);
                echo "
";
                echo "Status Date : ".$row['STATUS_DATE'];
                echo "
";
                echo "Status Time : ".$row['STATUS_TIME'];
                echo "

";
                echo '
';
            }
        ?>

I'm completely new to bootstrap and only know the basics.


问:
Complexity of recursive code
I came across this question in a review for my class and I am having a difficult time understanding the professors justification and explanation of the solution. The question:
The following code computes 2^n for given n. Determine total number of lines executed. Justify your answer.

```<code>    Power2(int n)
    1) if(n=0)
    2)     return 1
    3) else
    4)     k=Power2(n/2)
    5)     k=k*k;
    6)     if(k is even)
    7)       return k
    8)     else
    9)       return 2*k
</code>```

The justification

I don't understand from the "hence" part on. If someone could break these steps down for me a little more and describe how these steps are equivalent, it would be a great help.

答:
```<code>t(2^k) =                //this is because 2^k is even so
[t(2^(k-1))] + 1        //you apply the first rule for t(n)
</code>```

```<code>t(2^(k-1)) + 1 =        //note that 2^(k-1) is also even
[t(2^(k-2)) + 1] + 1    //so you apply the same t(n) rule
</code>```

each 2^(i = 0...k) will be even (except 2^0), so that you can apply the first t(n) rule for all steps, coming to the end of the recursion after k-1 steps.

then, you note that if you want to evaluate t(2^k), you must do about k operations, and k = lg(2^k), so Power2 is a logarithmic-time function,

Title: Complexity of recursive code

Body:
I came across this question in a review for my class and I am having a difficult time understanding the professors justification and explanation of the solution. The question:
The following code computes 2^n for given n. Determine total number of lines executed. Justify your answer.

    Power2(int n)
    1) if(n=0)
    2)     return 1
    3) else
    4)     k=Power2(n/2)
    5)     k=k*k;
    6)     if(k is even)
    7)       return k
    8)     else
    9)       return 2*k

The justification

I don't understand from the "hence" part on. If someone could break these steps down for me a little more and describe how these steps are equivalent, it would be a great help.

Body:
t(2^k) =                //this is because 2^k is even so
[t(2^(k-1))] + 1        //you apply the first rule for t(n)

t(2^(k-1)) + 1 =        //note that 2^(k-1) is also even
[t(2^(k-2)) + 1] + 1    //so you apply the same t(n) rule

each 2^(i = 0...k) will be even (except 2^0), so that you can apply the first t(n) rule for all steps, coming to the end of the recursion after k-1 steps.

then, you note that if you want to evaluate t(2^k), you must do about k operations, and k = lg(2^k), so Power2 is a logarithmic-time function,


问:
.deps/*.Po: No such file or directory compiler error
My configure.ac looks like

```<code>AC_PREREQ(2.61)
AC_INIT(MyProject, 1.0.0, BUG-REPORT-ADDRESS)
AM_INIT_AUTOMAKE([1.10 no-define foreign])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR(configure.ac)
AC_CONFIG_HEADER([config.h])
AC_CONFIG_FILES([obj/threading/Makefile])
#AC_OUTPUT([Makefile obj/Makefile obj/threading/Makefile])

AC_USE_SYSTEM_EXTENSIONS
AC_LANG([C++])
AC_PROG_CXX([clang++ g++])

AX_CXX_COMPILE_STDCXX_11()
AS_IF([test "x$HAVE_CXX11" != "x1"],
      [AC_MSG_ERROR([** A compiler with C++11 language features is required.])])

CXXFLAGS='-Wall -std=c++11'
AC_SUBST(CXXFLAGS)

AC_OUTPUT
</code>```

My Makefile.am looks like

```<code>AUTOMAKE_OPTIONS = subdir-objects

SRCDIR = $(top_srcdir)/src/threading

bin_PROGRAMS = node

node_SOURCES  = $(SRCDIR)/UnitTests/node.cpp
node_CPPFLAGS =
node_LDFLAGS  =
node_CXXFLAGS = $( CXXFLAGS )
</code>```

I get following error

```<code>Makefile:394: ../../src/threading/UnitTests/.deps/node-node.Po: No such file or directory
</code>```

答:
I encountered the same problem got it resolved by calling autoreconf -if in the project root directory

```<code>Makefile:577: .deps/testAll-bar_test.Po: No such file or directory
Makefile:579: .deps/testAll-main_testall.Po: No such file or directory
make[3]: *** No rule to make target '.deps/testAll-main_testall.Po'.  Stop.

autoreconf -if
./configure
make # no more problem
</code>```

I am using gtest for my C++ project.  The Makefile.am file is straightforward, nothing unusual.

Body:
My configure.ac looks like

AC_PREREQ(2.61)
AC_INIT(MyProject, 1.0.0, BUG-REPORT-ADDRESS)
AM_INIT_AUTOMAKE([1.10 no-define foreign])
AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_SRCDIR(configure.ac)
AC_CONFIG_HEADER([config.h])
AC_CONFIG_FILES([obj/threading/Makefile])
#AC_OUTPUT([Makefile obj/Makefile obj/threading/Makefile])

AC_USE_SYSTEM_EXTENSIONS
AC_LANG([C++])
AC_PROG_CXX([clang++ g++])

AX_CXX_COMPILE_STDCXX_11()
AS_IF([test "x$HAVE_CXX11" != "x1"],
      [AC_MSG_ERROR([** A compiler with C++11 language features is required.])])

CXXFLAGS='-Wall -std=c++11'
AC_SUBST(CXXFLAGS)

AC_OUTPUT

My Makefile.am looks like

AUTOMAKE_OPTIONS = subdir-objects

SRCDIR = $(top_srcdir)/src/threading

bin_PROGRAMS = node

node_SOURCES  = $(SRCDIR)/UnitTests/node.cpp
node_CPPFLAGS =
node_LDFLAGS  =
node_CXXFLAGS = $( CXXFLAGS )

I get following error

Makefile:394: ../../src/threading/UnitTests/.deps/node-node.Po: No such file or directory

Body:
I encountered the same problem got it resolved by calling autoreconf -if in the project root directory

Makefile:577: .deps/testAll-bar_test.Po: No such file or directory
Makefile:579: .deps/testAll-main_testall.Po: No such file or directory
make[3]: *** No rule to make target '.deps/testAll-main_testall.Po'.  Stop.

autoreconf -if
./configure
make # no more problem

I am using gtest for my C++ project.  The Makefile.am file is straightforward, nothing unusual.


答:
This is not a direct solution to your problem, but one option would be to just make the entire  and its contents render only when there is a greater than zero employee count:

```<code><span>
    Total Employee
    <span ng-show="employeeCount > 0">{{employeeCount | customFormatter}}</span>
</span>
</code>```

When the count is zero then the span would not be visible, but would still take up the same space in the DOM, which presumably would be equivalent to rendering that span with just an empty string as content.

Title: Issue when using string operation and pipe together

Body:
This is not a direct solution to your problem, but one option would be to just make the entire <span> and its contents render only when there is a greater than zero employee count:

<span>
    Total Employee
    <span ng-show="employeeCount > 0">{{employeeCount | customFormatter}}</span>
</span>

When the count is zero then the span would not be visible, but would still take up the same space in the DOM, which presumably would be equivalent to rendering that span with just an empty string as content.


问:
Is there way to save trained model after overfitting occurs in CatBoost?
I am using CatBoostRegressor in Python version of the Catboost library.

According to documentation, it's possible to use overfitting detector, which I am doing, like this:

```<code>model = CatBoostRegressor(iterations=iters, learning_rate=0.03, depth=depth, verbose=True, od_pval=1, od_type='IncToDec', od_wait=20)
model.fit(train_pool, eval_set=validation_pool)

# this code didn't executed
model.save_model(model_name)
</code>```

However, after the overfitting occurs, I've got my Python script interrupted, prematurely stopped, pick any phrase you want, and save model part didn't get executed, which leads to a lot of waisted time and no results in the end. I didn't get any stacktrace.

Is there any possibility to handle it in CatBoost and save hours of fitting work?

答:
You can do it with pickle, just train your module and dump it using pickle.

```<code> pickle.dump(regr, open("models/svrrbf.sav",'wb'))
</code>```

Further you can use that module to test your inputs.
Hope it helps

Body:
I am using CatBoostRegressor in Python version of the Catboost library.

According to documentation, it's possible to use overfitting detector, which I am doing, like this:

model = CatBoostRegressor(iterations=iters, learning_rate=0.03, depth=depth, verbose=True, od_pval=1, od_type='IncToDec', od_wait=20)
model.fit(train_pool, eval_set=validation_pool)

# this code didn't executed
model.save_model(model_name)

However, after the overfitting occurs, I've got my Python script interrupted, prematurely stopped, pick any phrase you want, and save model part didn't get executed, which leads to a lot of waisted time and no results in the end. I didn't get any stacktrace.

Is there any possibility to handle it in CatBoost and save hours of fitting work?

Body:
You can do it with pickle, just train your module and dump it using pickle.

 pickle.dump(regr, open("models/svrrbf.sav",'wb'))

Further you can use that module to test your inputs.
Hope it helps


问:
Call to undefined method error in Laravel
I have the following function:

```<code>public function addSubject(Request $request) {
    $student=User::find($request->invisible);
    $classsubjects = $request['classsubjects'];
    $student->classSubjects()->attach($cclasssubjects);
}
</code>```

This gives me an error saying:

BadMethodCallException
  Call to undefined method Illuminate\Database\Query\Builder::attach()

答:
The function classSubjects() in your Package model has to return a BelongsToMany relationship in order to use attach().</p>

```<code>public function classSubjects() {
  return $this->belongsToMany('classSubjects');
}
</code>```

Body:
I have the following function:

public function addSubject(Request $request) {
    $student=User::find($request->invisible);
    $classsubjects = $request['classsubjects'];
    $student->classSubjects()->attach($cclasssubjects);
}

This gives me an error saying:

BadMethodCallException
  Call to undefined method Illuminate\Database\Query\Builder::attach()

Body:
The function classSubjects() in your Package model has to return a BelongsToMany relationship in order to use attach().

public function classSubjects() {
  return $this->belongsToMany('classSubjects');
}


问:
Unable to switch on Install via USB on Redmi Note 4
MI Note 4

```<code>Android version: 7.0

MIUI Version: 9.0
</code>```

I'm unable to switch on Install via USB option for debugging purpose. I have tried switching to mobile data and using MI account . Also, tried turning off MIUI optimization. Nothing worked till now.

I always get the error that says "The device is temporarily restricted"

I'm stuck for 2 days now.

Could anyone here help in resolving this?

Note: It was working fine till I updated the device to Nougat. Kindly help if you're using Nougat along with MIUI 9.0

Edit: Using VPN helped.

答:
Try this to turn off Instant Run

Unlock your phone and go to main Settings on your Xiaomi Redmi devices

Scroll down to find About Device and tap on it.

Locate MIUI Version and tap several times on it.

you will get a message "You're now a developer!" on your device screen.

Go back to main Settings.

Run Additional Settings, and tap Developer options to enable it from there.

Scroll down to find USB Debugging option and enable it.

If you need to turn off Instant Run in android studio , go to

File → Settings → Build, Execution, Deployment → Instant Run and uncheck Enable Instant Run.

Body:
MI Note 4

Android version: 7.0

MIUI Version: 9.0

I'm unable to switch on Install via USB option for debugging purpose. I have tried switching to mobile data and using MI account . Also, tried turning off MIUI optimization. Nothing worked till now.

I always get the error that says "The device is temporarily restricted"

I'm stuck for 2 days now.

Could anyone here help in resolving this?

Note: It was working fine till I updated the device to Nougat. Kindly help if you're using Nougat along with MIUI 9.0

Edit: Using VPN helped.


问:
Is there an Open File dialog for Access 2010 64bit?
How do I get an Open File dialog for Access 2010 64bit?  Normally I would use the common dialog control but that is 32bit and cannot be used with Access 2010 64 bit.</p>

答:
You can use the built in file dialog. It been there since access 2003.

```<code>Dim f    As FileDialog
Set f = Application.FileDialog(msoFileDialogFilePicker)
f.Show
MsgBox "file choose was " & f.SelectedItems(1)
</code>```

You can late bind if you wish:

above needs: Microsoft Office 14.0 Object library

If you remove the reference to the 14.0 object library, then the following
code will work without any references:

```<code>Dim f    As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = True
f.Show

MsgBox "file choosen = " & f.SelectedItems.Count
</code>```

So, above works in runtime or regular edition from 2003 onwards, and also works for either 32 or 64 bit editions of access 2010.

ContentLicense: CC BY-SA 2.5

Body:
You can use the built in file dialog. It been there since access 2003.

Dim f    As FileDialog
Set f = Application.FileDialog(msoFileDialogFilePicker)
f.Show
MsgBox "file choose was " & f.SelectedItems(1)

You can late bind if you wish:

above needs: Microsoft Office 14.0 Object library

If you remove the reference to the 14.0 object library, then the following
code will work without any references:

Dim f    As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = True
f.Show

MsgBox "file choosen = " & f.SelectedItems.Count

So, above works in runtime or regular edition from 2003 onwards, and also works for either 32 or 64 bit editions of access 2010.


问:
Android: save a file from an existing URI
How to save a media file (say .mp3) from an existing URI, which I am getting from an Implicit Intent?</p>

答:
If Uri is received from Google Drive, it can be a Virtual File Uri too. Check this article from CommonsWare for more information. So you have to consider that condition too while saving file from Uri.

To find if file Uri is virtual or not you can use

```<code>private static boolean isVirtualFile(Context context, Uri uri) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (!DocumentsContract.isDocumentUri(context, uri)) {
            return false;
        }
        Cursor cursor = context.getContentResolver().query(
                uri,
                new String[]{DocumentsContract.Document.COLUMN_FLAGS},
                null, null, null);
        int flags = 0;
        if (cursor.moveToFirst()) {
            flags = cursor.getInt(0);
        }
        cursor.close();
        return (flags & DocumentsContract.Document.FLAG_VIRTUAL_DOCUMENT) != 0;
    } else {
        return false;
    }
}
</code>```

You can get the stream data from this virtual file like this:

```<code>private static InputStream getInputStreamForVirtualFile(Context context, Uri uri, String mimeTypeFilter)
        throws IOException {

    ContentResolver resolver = context.getContentResolver();
    String[] openableMimeTypes = resolver.getStreamTypes(uri, mimeTypeFilter);
    if (openableMimeTypes == null || openableMimeTypes.length < 1) {
        throw new FileNotFoundException();
    }
    return resolver
            .openTypedAssetFileDescriptor(uri, openableMimeTypes[0], null)
            .createInputStream();
}
</code>```

For finding MIME type try

```<code>private static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}
</code>```

Overall, you can use

```<code>public static boolean saveFile(Context context, String name, Uri sourceuri, String destinationDir, String destFileName) {

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    InputStream input = null;
    boolean hasError = false;

    try {
        if (isVirtualFile(context, sourceuri)) {
            input = getInputStreamForVirtualFile(context, sourceuri, getMimeType(name));
        } else {
            input = context.getContentResolver().openInputStream(sourceuri);
        }

        boolean directorySetupResult;
        File destDir = new File(destinationDir);
        if (!destDir.exists()) {
            directorySetupResult = destDir.mkdirs();
        } else if (!destDir.isDirectory()) {
            directorySetupResult = replaceFileWithDir(destinationDir);
        } else {
            directorySetupResult = true;
        }

        if (!directorySetupResult) {
            hasError = true;
        } else {
            String destination = destinationDir + File.separator + destFileName;
            int originalsize = input.available();

            bis = new BufferedInputStream(input);
            bos = new BufferedOutputStream(new FileOutputStream(destination));
            byte[] buf = new byte[originalsize];
            bis.read(buf);
            do {
                bos.write(buf);
            } while (bis.read(buf) != -1);
        }
    } catch (Exception e) {
        e.printStackTrace();
        hasError = true;
    } finally {
        try {
            if (bos != null) {
                bos.flush();
                bos.close();
            }
        } catch (Exception ignored) {
        }
    }

    return !hasError;
}

private static boolean replaceFileWithDir(String path) {
    File file = new File(path);
    if (!file.exists()) {
        if (file.mkdirs()) {
            return true;
        }
    } else if (file.delete()) {
        File folder = new File(path);
        if (folder.mkdirs()) {
            return true;
        }
    }
    return false;
}
</code>```

Call this method from an AsycTask. Let me know if this helps.

Body:
If Uri is received from Google Drive, it can be a Virtual File Uri too. Check this article from CommonsWare for more information. So you have to consider that condition too while saving file from Uri.

To find if file Uri is virtual or not you can use

private static boolean isVirtualFile(Context context, Uri uri) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (!DocumentsContract.isDocumentUri(context, uri)) {
            return false;
        }
        Cursor cursor = context.getContentResolver().query(
                uri,
                new String[]{DocumentsContract.Document.COLUMN_FLAGS},
                null, null, null);
        int flags = 0;
        if (cursor.moveToFirst()) {
            flags = cursor.getInt(0);
        }
        cursor.close();
        return (flags & DocumentsContract.Document.FLAG_VIRTUAL_DOCUMENT) != 0;
    } else {
        return false;
    }
}

You can get the stream data from this virtual file like this:

private static InputStream getInputStreamForVirtualFile(Context context, Uri uri, String mimeTypeFilter)
        throws IOException {

    ContentResolver resolver = context.getContentResolver();
    String[] openableMimeTypes = resolver.getStreamTypes(uri, mimeTypeFilter);
    if (openableMimeTypes == null || openableMimeTypes.length < 1) {
        throw new FileNotFoundException();
    }
    return resolver
            .openTypedAssetFileDescriptor(uri, openableMimeTypes[0], null)
            .createInputStream();
}

For finding MIME type try

private static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}

Overall, you can use

public static boolean saveFile(Context context, String name, Uri sourceuri, String destinationDir, String destFileName) {

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    InputStream input = null;
    boolean hasError = false;

    try {
        if (isVirtualFile(context, sourceuri)) {
            input = getInputStreamForVirtualFile(context, sourceuri, getMimeType(name));
        } else {
            input = context.getContentResolver().openInputStream(sourceuri);
        }

        boolean directorySetupResult;
        File destDir = new File(destinationDir);
        if (!destDir.exists()) {
            directorySetupResult = destDir.mkdirs();
        } else if (!destDir.isDirectory()) {
            directorySetupResult = replaceFileWithDir(destinationDir);
        } else {
            directorySetupResult = true;
        }

        if (!directorySetupResult) {
            hasError = true;
        } else {
            String destination = destinationDir + File.separator + destFileName;
            int originalsize = input.available();

            bis = new BufferedInputStream(input);
            bos = new BufferedOutputStream(new FileOutputStream(destination));
            byte[] buf = new byte[originalsize];
            bis.read(buf);
            do {
                bos.write(buf);
            } while (bis.read(buf) != -1);
        }
    } catch (Exception e) {
        e.printStackTrace();
        hasError = true;
    } finally {
        try {
            if (bos != null) {
                bos.flush();
                bos.close();
            }
        } catch (Exception ignored) {
        }
    }

    return !hasError;
}

private static boolean replaceFileWithDir(String path) {
    File file = new File(path);
    if (!file.exists()) {
        if (file.mkdirs()) {
            return true;
        }
    } else if (file.delete()) {
        File folder = new File(path);
        if (folder.mkdirs()) {
            return true;
        }
    }
    return false;
}

Call this method from an AsycTask. Let me know if this helps.


问:
HTTP Status 500 - Error instantiating servlet class pkg.coreServlet
I am creating simple servlet and deploying it in tomcat server but I am getting the following error:

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

File Structure on the tomcat server:

```<code>webapps
|
- aarya
  |
  - WEB-INF
    |
     -web.xml
     -src(folder)
       |
       -pkg
         |
         -coreServlet.class
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<servlet>
    <servlet-name>aaryaservlet</servlet-name>
    <servlet-class>pkg.coreServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>aaryaservlet</servlet-name>
        <url-pattern>/coreServlet</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

coreServlet.java:

```<code>package pkg;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class coreServlet extends HttpServlet
{
    /**
     *
     */
    private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest req,HttpServletResponse res)
 throws ServletException,IOException

   {
        PrintWriter out = res.getWriter();
        res.setContentType("text/html");
        out.println("this is First servlet Example ");
    }
}
</code>```

url I am giving is http://localhost:8080/aarya/coreServlet
I try by restarting tomcat but I am getting same error. Where I am doing wrong?

答:
Try This:)

before:-

```<code><servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>TestServlet</servlet-class>
</servlet>
</code>```

After:-

```<code> <servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>operation.TestServlet</servlet-class>
 </servlet>
</code>```

Body:
I am creating simple servlet and deploying it in tomcat server but I am getting the following error:

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

File Structure on the tomcat server:

webapps
|
- aarya
  |
  - WEB-INF
    |
     -web.xml
     -src(folder)
       |
       -pkg
         |
         -coreServlet.class

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<servlet>
    <servlet-name>aaryaservlet</servlet-name>
    <servlet-class>pkg.coreServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>aaryaservlet</servlet-name>
        <url-pattern>/coreServlet</url-pattern>
    </servlet-mapping>
</web-app>

coreServlet.java:

package pkg;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class coreServlet extends HttpServlet
{
    /**
     *
     */
    private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest req,HttpServletResponse res)
 throws ServletException,IOException

   {
        PrintWriter out = res.getWriter();
        res.setContentType("text/html");
        out.println("this is First servlet Example ");
    }
}

url I am giving is http://localhost:8080/aarya/coreServlet
I try by restarting tomcat but I am getting same error. Where I am doing wrong?

Body:
Try This:)

before:-

<servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>TestServlet</servlet-class>
</servlet>

After:-

 <servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>operation.TestServlet</servlet-class>
 </servlet>


问:
Replacing View using ng-view in angularjs
When the view change its replace the previous view in ng-view. but its not changing. it showing the template data which is "context".

var app = angular.module("myapp", ["ngRoute"]);

app.service('datapass', function () {

    this.name = "name";

});

app.config(function ($routeProvider) {

    $routeProvider
    .when("/name", {

        template: 'Context',
        controller: 'front_controller'
    })
    .when("/detail", {
        template: 'My Name is Awais Saleem',
        controller: 'main_controller'
    })
    .otherwise("/name");

});

app.controller("front_controller", function ($scope, datapass,$location) {
    $scope.url = datapass.name;
    $scope.changeView = function () {

        $scope.url = datapass.name = (datapass.name == "name") ? "detail" : "name";

    };

});

app.controller("main_controller", function ($scope, datapass,$location) {
    $scope.url = datapass.name;

    $scope.changeView = function () {

        $scope.url = datapass.name = (datapass.name == "name") ? "detail" : "name";

    };

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

<body ng-app="myapp">

        <div ng-view></div>

</body></code>```

When i click on the "context" then it should show the other page data, like "My Name is Awais Saleem" and i click on "My name is..." then it show the "Context".
Basically i want to replace the previous view.

答:
The controller defined are only accessible inside the

 element, however, you are trying to use it in the parent tag (). Therefore the controllers and its function are not recognized in the parent tag. Hence, here the  tag should be inside the template.

Also Instead of using a href, the better way would be to use $location.path().

var app = angular.module("myapp", ["ngRoute"]);

app.service('datapass', function() {

  this.name = "name";

});

app.config(function($routeProvider) {

  $routeProvider
    .when("/name", {

      template: 'Context',
      controller: 'front_controller'
    })
    .when("/detail", {
      template: 'My Name is Awais Saleem',
      controller: 'main_controller'
    })
    .otherwise("/name");

});

app.controller("front_controller", function($scope, datapass, $location) {
  $scope.changeView = function() {

    datapass.name = (datapass.name == "name") ? "detail" : "name";

    $location.path("/"+datapass.name);

  };

});

app.controller("main_controller", function($scope, datapass, $location) {

  $scope.changeView = function() {

    datapass.name = (datapass.name == "name") ? "detail" :"name";

    $location.path("/"+datapass.name);

  };

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

<body ng-app="myapp">

    <div ng-view></div>

</body></code>```

Body:
When the view change its replace the previous view in ng-view. but its not changing. it showing the template data which is "context".

var app = angular.module("myapp", ["ngRoute"]);

app.service('datapass', function () {

    this.name = "name";

});

app.config(function ($routeProvider) {

    $routeProvider
    .when("/name", {

        template: 'Context',
        controller: 'front_controller'
    })
    .when("/detail", {
        template: 'My Name is Awais Saleem',
        controller: 'main_controller'
    })
    .otherwise("/name");

});

app.controller("front_controller", function ($scope, datapass,$location) {
    $scope.url = datapass.name;
    $scope.changeView = function () {

        $scope.url = datapass.name = (datapass.name == "name") ? "detail" : "name";

    };

});

app.controller("main_controller", function ($scope, datapass,$location) {
    $scope.url = datapass.name;

    $scope.changeView = function () {

        $scope.url = datapass.name = (datapass.name == "name") ? "detail" : "name";

    };

});

When i click on the "context" then it should show the other page data, like "My Name is Awais Saleem" and i click on "My name is..." then it show the "Context".
Basically i want to replace the previous view.

Body:
The controller defined are only accessible inside the <div ng-view></div> element, however, you are trying to use it in the parent tag (<a>). Therefore the controllers and its function are not recognized in the parent tag. Hence, here the <a> tag should be inside the template.

Also Instead of using a href, the better way would be to use $location.path().

var app = angular.module("myapp", ["ngRoute"]);

app.service('datapass', function() {

  this.name = "name";

});

app.config(function($routeProvider) {

  $routeProvider
    .when("/name", {

      template: '<a ng-click="changeView()" href="">Context</a>',
      controller: 'front_controller'
    })
    .when("/detail", {
      template: '<a ng-click = "changeView()" href="">My Name is Awais Saleem</a>',
      controller: 'main_controller'
    })
    .otherwise("/name");

});

app.controller("front_controller", function($scope, datapass, $location) {
  $scope.changeView = function() {

    datapass.name = (datapass.name == "name") ? "detail" : "name";

    $location.path("/"+datapass.name);

  };

});

app.controller("main_controller", function($scope, datapass, $location) {

  $scope.changeView = function() {

    datapass.name = (datapass.name == "name") ? "detail" :"name";

    $location.path("/"+datapass.name);

  };

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

<body ng-app="myapp">

    <div ng-view></div>

</body>


问:
Calling HTML coding in JavaScript function using Spring framework
Can anyone tell me how can I call all my html coding using JavaScript in Spring framework without using any template engine such as Thymeleaf?</p>

答:
First you have to create request mapping for that the HTML page.

```<code>@RequestMapping(value="/hello", method = RequestMethod.GET)
public ModelAndView product_save(){
    ModelAndView model = new ModelAndView();
    model.setViewName("hello"); // HTML page name
    return model;
}
</code>```

Your hello.html

```<code><!DOCTYPE html>
<html>
    <head>
        <title>hello</title>
    </head>
    <body>
        <h1>Welcome!</h1>
    </body>
</html>
</code>```

And your js

```<code>window.location = "hello";
</code>```

Body:
First you have to create request mapping for that the HTML page.

@RequestMapping(value="/hello", method = RequestMethod.GET)
public ModelAndView product_save(){
    ModelAndView model = new ModelAndView();
    model.setViewName("hello"); // HTML page name
    return model;
}

Your hello.html

<!DOCTYPE html>
<html>
    <head>
        <title>hello</title>
    </head>
    <body>
        <h1>Welcome!</h1>
    </body>
</html>

And your js

window.location = "hello";


答:
Hello Try following code that is for demo only </p>

```<code><div class="container">
  <h3>Teachers:</h3>
  <div class="row">
    <?php for($i=1;$i<=4;$i++) {?>
    <div class="col-lg-3">
        <div class="img-responsive"><img src="http://via.placeholder.com/150x150"></div>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
    </div>
    <?php } ?>

</div>
</code>```

Title: Bootstrap Automatically Hiding my images in my Webpage Php

Body:
I'm showing my data in an inline manner using bootstrap like this
for example,

But when I add some bootstrap classed, then my images are not showing.
My Code is :

Teachers:

        <?php
            $queryTeachers = "SELECT places.PLACE_NAME,teacher_status.PERSON_NAME,DATE_FORMAT(teacher_status.STATUS_DATE,'%d-%m-%Y') as STATUS_DATE,DATE_FORMAT(teacher_status.STATUS_TIME,'%h:%i:%s %p') as STATUS_TIME, teachers.IMAGE_FOLDER AS IMAGE_FOLDER,teachers.IMAGE_NAME as IMAGE_NAME FROM places,teacher_status,teachers WHERE places.PLACE_ID=teacher_status.PERSON_CURRENT_PLACE AND teachers.TEACHER_ID=teacher_status.TEACHER_ID;";
            $resultTeachers = mysqli_query($conn,$queryTeachers) or die("Unable to select status". mysqli_error($conn));
            while($row=mysqli_fetch_assoc($resultTeachers)) {
                echo '
';
                echo '';
                echo "
";
                echo "Persone Name : ".ucwords($row['PERSON_NAME']);
                echo "
";
                echo "Current Place : ".ucwords($row['PLACE_NAME']);
                echo "
";
                echo "Status Date : ".$row['STATUS_DATE'];
                echo "
";
                echo "Status Time : ".$row['STATUS_TIME'];
                echo "

";
                echo '
';
            }
        ?>

I'm completely new to bootstrap and only know the basics.

Body:
Hello Try following code that is for demo only

<div class="container">
  <h3>Teachers:</h3>
  <div class="row">
    <?php for($i=1;$i<=4;$i++) {?>
    <div class="col-lg-3">
        <div class="img-responsive"><img src="http://via.placeholder.com/150x150"></div>
        <p>This is some text.</p>
        <p>This is some text.</p>
        <p>This is some text.</p>
    </div>
    <?php } ?>

</div>


问:
Can I watch Multiple directories for changes using ReadDirectoryChangesW() in c++?
I am trying to monitor different directories for changes using ReadDirectoryChangesW and I succeed in monitoring a single directory with it. But when it comes to monitoring multiple directories, I am having problems that the first directory is assigned to the handle and it looks for changes only in that directory and then only goes to watch the next directory if the first directory condition is satisfied. But I want to watch multiple directories simultaneously. Can I help me with this problem?

I am attaching the code below for the reference.

```<code>#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <mutex>
#include "sys/stat.h"
#include <dirent.h>

using namespace std;

mutex m1;

int main()
{
    HANDLE hDir[20];
    vector <string> directory_list;
    string f_path;
    string temp1;
    ifstream pfile;

    pfile.open("C:\\Users\\sathish-pt1608\\Desktop\\path_file.txt");

    if (!pfile.is_open())
        cout << "Unable to open the Requested File...";

    while(pfile.good())
    {
        getline(pfile,f_path);
        struct stat path_stat;
        stat(f_path.c_str(),&path_stat);

        if (S_ISREG(path_stat.st_mode))
        {
            int a = f_path.find_last_of('\\');
            directory_list.push_back(f_path.substr(0, a - 1));
        }
        else if(S_ISDIR(path_stat.st_mode))
        {
            DIR *dir;
            struct dirent *ent;

            dir = opendir(f_path.c_str());

            if (dir != NULL)
            {
                directory_list.push_back(f_path);
                while ( (ent = readdir(dir)) != NULL)
                {
                    temp1 = ent->d_name;
                }
                closedir(dir);
            }
            else
            {
                perror("Please Check the Directory Path...");
                EXIT_FAILURE;
            }
        }
    }

    for (int i = 0; i < directory_list.size();)
    {
        LPCTSTR DirName = directory_list[i].c_str();

        hDir[i] = CreateFile(DirName, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

        FILE_NOTIFY_INFORMATION Buffer[1024];
        DWORD BytesReturned;

        if (!ReadDirectoryChangesW(hDir[i], &Buffer, sizeof(Buffer), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE,  &BytesReturned, NULL, NULL))
        {
            cout << DirName << endl;
        }
        else
            cout << "THE DIRECTORY HAS BEEN MODIFIED..." << endl;

        if (i == directory_list.size() - 1)
            i = 0;
        else
            i++;
    }
}
</code>```

答:
You can use windows feature called journals to detect deleted/changed/created files/folders on a drive. You need to open the drive using CreateFile() then use DeviceIoControl() to read the changed buffer from time to time. You will get file details like size, name, attributes etc. Files are considered as records and record size is obtained using the buffer returned by DeviceIoControl() and bytecount.

Journals in windows are created to find changes in a volume in a fast/easier way since multiple changes can happen from time to time. You can use the parameter FSCTL_QUERY_USN_JOURNAL to create the journal and FSCTL_ENUM_USN_DATA to find the required records.

To know more about journals you need to refer msdn link https://msdn.microsoft.com/en-us/library/windows/desktop/aa363798(v=vs.85).aspx

Dummy source code,

```<code>    ///C drive
    HANDLE drive;
    drive = CreateFile(L"\\\\?\\c:", GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_FLAG_NO_BUFFERING, NULL);
    if (INVALID_HANDLE_VALUE == drive)
    {
        printf("CreateFile: %u\n", GetLastError());
        return 0;
    }

    if (!DeviceIoControl(drive, FSCTL_QUERY_USN_JOURNAL, NULL, 0, buffer, BUFFER_SIZE, &bytecount, NULL))
    {
        printf("FSCTL_QUERY_USN_JOURNAL: %u\n", GetLastError());
        return 0;
    }

    USN_JOURNAL_DATA* journal = (USN_JOURNAL_DATA *)buffer;
    MFT_ENUM_DATA mft_enum_data = {0};
    mft_enum_data.StartFileReferenceNumber = 0;
    mft_enum_data.LowUsn = 0;
    mft_enum_data.HighUsn = journal->MaxUsn;

    for(;;)
    {
        if (!DeviceIoControl(drive, FSCTL_ENUM_USN_DATA, &mft_enum_data, sizeof(mft_enum_data), buffer, BUFFER_SIZE, &bytecount, NULL))
        {
            printf("FSCTL_ENUM_USN_DATA: %u\n", GetLastError());
            return 0;
        }

        USN_RECORD* record;
        USN_RECORD* recordend;
        record = (USN_RECORD *)((USN *)buffer + 1);
        recordend = (USN_RECORD *)(((BYTE *)buffer) + bytecount);

        DWORDLONG filecount = 0;
        while (record < recordend)
        {
            filecount++;

            printf("FileAttributes: %x\n", record->FileAttributes);
            printf("FileNameLength: %u\n", (DWORD)record->FileNameLength);
            printf("RecordLength: %u\n", record->RecordLength);

            WCHAR * filename;
            WCHAR * filenameend;
            filename = (WCHAR *)(((BYTE *)record) + record->FileNameOffset);
            filenameend= (WCHAR *)(((BYTE *)record) + record->FileNameOffset + record->FileNameLength);

            printf("FileName: %s\n", filename);

            record = (USN_RECORD *)(((BYTE *)record) + record->RecordLength);
        }

        mft_enum_data.StartFileReferenceNumber = *((DWORDLONG *)buffer);
    }
</code>```

Body:
I am trying to monitor different directories for changes using ReadDirectoryChangesW and I succeed in monitoring a single directory with it. But when it comes to monitoring multiple directories, I am having problems that the first directory is assigned to the handle and it looks for changes only in that directory and then only goes to watch the next directory if the first directory condition is satisfied. But I want to watch multiple directories simultaneously. Can I help me with this problem?

I am attaching the code below for the reference.

#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <vector>
#include <fstream>
#include <mutex>
#include "sys/stat.h"
#include <dirent.h>

using namespace std;

mutex m1;

int main()
{
    HANDLE hDir[20];
    vector <string> directory_list;
    string f_path;
    string temp1;
    ifstream pfile;

    pfile.open("C:\\Users\\sathish-pt1608\\Desktop\\path_file.txt");

    if (!pfile.is_open())
        cout << "Unable to open the Requested File...";

    while(pfile.good())
    {
        getline(pfile,f_path);
        struct stat path_stat;
        stat(f_path.c_str(),&path_stat);

        if (S_ISREG(path_stat.st_mode))
        {
            int a = f_path.find_last_of('\\');
            directory_list.push_back(f_path.substr(0, a - 1));
        }
        else if(S_ISDIR(path_stat.st_mode))
        {
            DIR *dir;
            struct dirent *ent;

            dir = opendir(f_path.c_str());

            if (dir != NULL)
            {
                directory_list.push_back(f_path);
                while ( (ent = readdir(dir)) != NULL)
                {
                    temp1 = ent->d_name;
                }
                closedir(dir);
            }
            else
            {
                perror("Please Check the Directory Path...");
                EXIT_FAILURE;
            }
        }
    }

    for (int i = 0; i < directory_list.size();)
    {
        LPCTSTR DirName = directory_list[i].c_str();

        hDir[i] = CreateFile(DirName, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

        FILE_NOTIFY_INFORMATION Buffer[1024];
        DWORD BytesReturned;

        if (!ReadDirectoryChangesW(hDir[i], &Buffer, sizeof(Buffer), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE,  &BytesReturned, NULL, NULL))
        {
            cout << DirName << endl;
        }
        else
            cout << "THE DIRECTORY HAS BEEN MODIFIED..." << endl;

        if (i == directory_list.size() - 1)
            i = 0;
        else
            i++;
    }
}

Body:
You can use windows feature called journals to detect deleted/changed/created files/folders on a drive. You need to open the drive using CreateFile() then use DeviceIoControl() to read the changed buffer from time to time. You will get file details like size, name, attributes etc. Files are considered as records and record size is obtained using the buffer returned by DeviceIoControl() and bytecount.

Journals in windows are created to find changes in a volume in a fast/easier way since multiple changes can happen from time to time. You can use the parameter FSCTL_QUERY_USN_JOURNAL to create the journal and FSCTL_ENUM_USN_DATA to find the required records.

To know more about journals you need to refer msdn link https://msdn.microsoft.com/en-us/library/windows/desktop/aa363798(v=vs.85).aspx

Dummy source code,

    ///C drive
    HANDLE drive;
    drive = CreateFile(L"\\\\?\\c:", GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_FLAG_NO_BUFFERING, NULL);
    if (INVALID_HANDLE_VALUE == drive)
    {
        printf("CreateFile: %u\n", GetLastError());
        return 0;
    }

    if (!DeviceIoControl(drive, FSCTL_QUERY_USN_JOURNAL, NULL, 0, buffer, BUFFER_SIZE, &bytecount, NULL))
    {
        printf("FSCTL_QUERY_USN_JOURNAL: %u\n", GetLastError());
        return 0;
    }

    USN_JOURNAL_DATA* journal = (USN_JOURNAL_DATA *)buffer;
    MFT_ENUM_DATA mft_enum_data = {0};
    mft_enum_data.StartFileReferenceNumber = 0;
    mft_enum_data.LowUsn = 0;
    mft_enum_data.HighUsn = journal->MaxUsn;

    for(;;)
    {
        if (!DeviceIoControl(drive, FSCTL_ENUM_USN_DATA, &mft_enum_data, sizeof(mft_enum_data), buffer, BUFFER_SIZE, &bytecount, NULL))
        {
            printf("FSCTL_ENUM_USN_DATA: %u\n", GetLastError());
            return 0;
        }

        USN_RECORD* record;
        USN_RECORD* recordend;
        record = (USN_RECORD *)((USN *)buffer + 1);
        recordend = (USN_RECORD *)(((BYTE *)buffer) + bytecount);

        DWORDLONG filecount = 0;
        while (record < recordend)
        {
            filecount++;

            printf("FileAttributes: %x\n", record->FileAttributes);
            printf("FileNameLength: %u\n", (DWORD)record->FileNameLength);
            printf("RecordLength: %u\n", record->RecordLength);

            WCHAR * filename;
            WCHAR * filenameend;
            filename = (WCHAR *)(((BYTE *)record) + record->FileNameOffset);
            filenameend= (WCHAR *)(((BYTE *)record) + record->FileNameOffset + record->FileNameLength);

            printf("FileName: %s\n", filename);

            record = (USN_RECORD *)(((BYTE *)record) + record->RecordLength);
        }

        mft_enum_data.StartFileReferenceNumber = *((DWORDLONG *)buffer);
    }


问:
calling function on Picker item Selection react native
I am trying to call a function whenever i select an item from picker and display the selected item with alert.

Here's what i am doing :-

```<code>import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
   constructor(props) {
  super(props);
  this.state = {
    isLoading: true,
    throttlemode:'',
  }
}
GetSelectedThrottleModeItem=(throttlemode)=>{
Alert.alert(this.state.throttlemode)
}
render() {
return (
    <View style={styles.MainContainerAddCamp}>
    <Text style={{fontSize: 12}}> Throttle Mode</Text>
    <Picker style={styles.PickerStyleClass}
  selectedValue={this.state.throttlemode}
  onValueChange={(throttlemodeValue, throttlemodeIndex) => this.GetSelectedThrottleModeItem(this.setState({throttlemode:throttlemodeValue}))}>
    <Picker.Item label="Asap" value="asap" />
    <Picker.Item label="Even" value="even" />
    </Picker>
   </View>
  );
}
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
    backgroundColor:'#87ceeb',
    paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
 borderColor: '#FF5722',
}
});
</code>```

This code is displaying the previously selected value. How can i make it to display current selected value.

Please suggest where i have missed.

答:
First of all setState method returns nothing. Second after calling setState method, you can't know whether state is changed or not, it's because of setState method is asynchronous. You can assign a callback to second argument of setState method to understand state changes.

```<code>import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
   constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      throttlemode:'',
    }
  }
  onPickerValueChange=(value, index)=>{
    this.setState(
      {
        "throttlemode": value
      },
      () => {
        // here is our callback that will be fired after state change.
        Alert.alert("Throttlemode", this.state.throttlemode);
      }
    );
  }
  render() {
    return (
        <View style={styles.MainContainerAddCamp}>
        <Text style={{fontSize: 12}}> Throttle Mode</Text>
        <Picker style={styles.PickerStyleClass}
        selectedValue={this.state.throttlemode}
        onValueChange={this.onPickerValueChange}>
          <Picker.Item label="Asap" value="asap" />
          <Picker.Item label="Even" value="even" />
        </Picker>
       </View>
      );
  }
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
    backgroundColor:'#87ceeb',
    paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
 borderColor: '#FF5722',
}
});
</code>```

Body:
I am trying to call a function whenever i select an item from picker and display the selected item with alert.

Here's what i am doing :-

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
   constructor(props) {
  super(props);
  this.state = {
    isLoading: true,
    throttlemode:'',
  }
}
GetSelectedThrottleModeItem=(throttlemode)=>{
Alert.alert(this.state.throttlemode)
}
render() {
return (
    <View style={styles.MainContainerAddCamp}>
    <Text style={{fontSize: 12}}> Throttle Mode</Text>
    <Picker style={styles.PickerStyleClass}
  selectedValue={this.state.throttlemode}
  onValueChange={(throttlemodeValue, throttlemodeIndex) => this.GetSelectedThrottleModeItem(this.setState({throttlemode:throttlemodeValue}))}>
    <Picker.Item label="Asap" value="asap" />
    <Picker.Item label="Even" value="even" />
    </Picker>
   </View>
  );
}
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
    backgroundColor:'#87ceeb',
    paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
 borderColor: '#FF5722',
}
});

This code is displaying the previously selected value. How can i make it to display current selected value.

Please suggest where i have missed.

Body:
First of all setState method returns nothing. Second after calling setState method, you can't know whether state is changed or not, it's because of setState method is asynchronous. You can assign a callback to second argument of setState method to understand state changes.

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
   constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      throttlemode:'',
    }
  }
  onPickerValueChange=(value, index)=>{
    this.setState(
      {
        "throttlemode": value
      },
      () => {
        // here is our callback that will be fired after state change.
        Alert.alert("Throttlemode", this.state.throttlemode);
      }
    );
  }
  render() {
    return (
        <View style={styles.MainContainerAddCamp}>
        <Text style={{fontSize: 12}}> Throttle Mode</Text>
        <Picker style={styles.PickerStyleClass}
        selectedValue={this.state.throttlemode}
        onValueChange={this.onPickerValueChange}>
          <Picker.Item label="Asap" value="asap" />
          <Picker.Item label="Even" value="even" />
        </Picker>
       </View>
      );
  }
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
    backgroundColor:'#87ceeb',
    paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
 borderColor: '#FF5722',
}
});


问:
How to check whether some variable returns something in predicate
Lets assume I have facts as follows:

```<code>airport(nyc,'newyork').
</code>```

I want want to display a message if the user inputs an airport that doesn't exist.

My Attempt:

```<code>isAirport(Air)  :-
      airport(Air,T),
     (var(T) -> true
      ;
       write('Airport not found'),
       fail
      ).
</code>```

However, this doesn't seem to work.

答:
In the code below you are making false assumption that T will remain unbound in case if airport will not be found in database:

```<code>airport(Air, T)
</code>```

What happens actually is that call to airport(Air, T) will make isAirport(Air) to fail immediately and your var(T) and other parts will not be executed at all.

Try this code instead:

```<code>isAirport(Air) :-
    airport(Air, _T), ! ; write('Airport not found'), fail.
</code>```

Body:
Lets assume I have facts as follows:

airport(nyc,'newyork').

I want want to display a message if the user inputs an airport that doesn't exist.

My Attempt:

isAirport(Air)  :-
      airport(Air,T),
     (var(T) -> true
      ;
       write('Airport not found'),
       fail
      ).

However, this doesn't seem to work.

Body:
In the code below you are making false assumption that T will remain unbound in case if airport will not be found in database:

airport(Air, T)

What happens actually is that call to airport(Air, T) will make isAirport(Air) to fail immediately and your var(T) and other parts will not be executed at all.

Try this code instead:

isAirport(Air) :-
    airport(Air, _T), ! ; write('Airport not found'), fail.