问:
Using one sub query result multiple times in the same mysql query
How can we use result set of one subquery multiple times in the same query

```<code>SELECT
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) be ON joa.referred_by = be.id
) AS applicationcount,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bf ON joa.referred_by = bf.id
    AND joa.admin_review = '3'
    AND joa.rejection_reason = 'Admin rejected your game'
) AS admin_reject,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bg ON joa.referred_by = bg.id
    AND joa. STATUS = '5'
    AND joa.admin_review = '2'
) AS employer_reject,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bd ON joa.referred_by = bd.id
    AND joa.admin_review = '1'
) AS admin_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bc ON joa.referred_by = bc.id
    AND joa.admin_review = '5'
) AS accountmanager_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) ba ON joa.referred_by = ba.id
    AND joa.admin_review = '6'
) AS rp_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = 1
    ) bh ON joa.referred_by = bh.id
    AND joa.admin_review = '2'
    AND (
        joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa.    STATUS = 3 || joa. STATUS = 4
    )
) AS other_status
  FROM
game_applied ja
JOIN user_user u ON u.id = ja.applied_recruiter_id
INNER JOIN (
SELECT
    jrmm.id
FROM
    game_refer_to_member jrmm
    JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bn ON ja.referred_by = bn.id
GROUP BY
applicationcount
</code>```

How can we use result set of one subquery multiple times in the same query

the sub query used mulitple times in this query to a single use

```<code>(
SELECT
    jrmm.id
FROM
    game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
  ) bn ON ja.referred_by = bn.id
</code>```

答:
Try this: </p>

```<code>SELECT COUNT(joa.id) AS applicationcount,
         SUM(joa.admin_review = '3' AND joa.rejection_reason = 'Admin Rejected your resume') AS admin_reject,
         SUM(joa.STATUS = '5' AND joa.admin_review = '2') AS employer_reject,
         SUM(joa.admin_review = '1') AS admin_review,
         SUM(joa.admin_review = '5') AS accountmanager_review,
         SUM(joa.admin_review = '6') AS rp_review,
         SUM(joa.admin_review = '2' AND joa.STATUS != '5') AS other_status,
FROM game_refer_to_member jrmm
INNER JOIN game_refer jrr ON jrr.id = jrmm.rid AND jrr.referby_user_id = 2551
INNER JOIN game_applied joa ON jrmm.id  = joa.referred_by
INNER JOIN user_user u ON u.id = joa.applied_recruiter_id
WHERE jrmm.STATUS = '1'
</code>```

Body:
How can we use result set of one subquery multiple times in the same query

SELECT
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) be ON joa.referred_by = be.id
) AS applicationcount,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bf ON joa.referred_by = bf.id
    AND joa.admin_review = '3'
    AND joa.rejection_reason = 'Admin rejected your game'
) AS admin_reject,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bg ON joa.referred_by = bg.id
    AND joa. STATUS = '5'
    AND joa.admin_review = '2'
) AS employer_reject,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bd ON joa.referred_by = bd.id
    AND joa.admin_review = '1'
) AS admin_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bc ON joa.referred_by = bc.id
    AND joa.admin_review = '5'
) AS accountmanager_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) ba ON joa.referred_by = ba.id
    AND joa.admin_review = '6'
) AS rp_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = 1
    ) bh ON joa.referred_by = bh.id
    AND joa.admin_review = '2'
    AND (
        joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa.    STATUS = 3 || joa. STATUS = 4
    )
) AS other_status
  FROM
game_applied ja
JOIN user_user u ON u.id = ja.applied_recruiter_id
INNER JOIN (
SELECT
    jrmm.id
FROM
    game_refer_to_member jrmm
    JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bn ON ja.referred_by = bn.id
GROUP BY
applicationcount

How can we use result set of one subquery multiple times in the same query

the sub query used mulitple times in this query to a single use

(
SELECT
    jrmm.id
FROM
    game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
  ) bn ON ja.referred_by = bn.id

Body:
Try this:

SELECT COUNT(joa.id) AS applicationcount,
         SUM(joa.admin_review = '3' AND joa.rejection_reason = 'Admin Rejected your resume') AS admin_reject,
         SUM(joa.STATUS = '5' AND joa.admin_review = '2') AS employer_reject,
         SUM(joa.admin_review = '1') AS admin_review,
         SUM(joa.admin_review = '5') AS accountmanager_review,
         SUM(joa.admin_review = '6') AS rp_review,
         SUM(joa.admin_review = '2' AND joa.STATUS != '5') AS other_status,
FROM game_refer_to_member jrmm
INNER JOIN game_refer jrr ON jrr.id = jrmm.rid AND jrr.referby_user_id = 2551
INNER JOIN game_applied joa ON jrmm.id  = joa.referred_by
INNER JOIN user_user u ON u.id = joa.applied_recruiter_id
WHERE jrmm.STATUS = '1'


来源: stackexchange

问:
PHP code to generate icons
currently i am working on a huge back-end application in Zend Framework.
A lot of times i end up using wrong icon for some object or action.

My Question
Is there any php code to generate icons automatically????

Ofcourse these icons will not be generated magically, best case scenario is that we have a collection of icons which have the type of.

Object (user,category,product,rss etc)

Action (add,edit,delete,update etc)

This way we can create icons by mixing different types of icons on the fly.

The code for generating a icon to delete user with 32x32 and delete icon in bottom-right corner of the icon.

```
$icon = new Icon();
$icon->object('user')->action('delete');
$icon->action_align('right')->action_valign('bottom');
$icon->action_height(10)->action_width(10);
$icon->height(32)->width(32);
$icon->create();
```

This is just an example that how can we create a icon which was never exited before.

答:
Hey i can suggest you to create filer like this one :

Filter that creates image thumbnail

```<code><?php
/**
 * Class for thumbnailing images
 *
 * @author Michał Bachowski (michal@bachowski.pl)
 * @package JPL
 * @subpackage   Jpl_Filter
 * @version 0.1
 * @uses Zend_Filter_Interface, IMagick
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Jpl_Filter_File_Image_Thumbnail {
    /**
     * Thumbnail width
     *
     * @var integer
     */
    protected $_width   = null;
    /**
     * Thumbnail height
     *
     * @var integer
     */
    protected $_height  = null;
    /**
     * Information whether to keep ratio or not while making thumbnail
     *
     * @var bool
     */
    protected $_bestFit = true;
    /**
     * Information whether crop image or just to resize it
     *
     * @var bool
     */
    protected $_crop    = false;
    /**
     * Method sets destination thumbnail width
     *
     * @param  integer  $width
     * @return Jpl_Filter_File_Image_Thumbnail
     */
    public function setWidth( $width = null ) {
        $this->_width = (int) $width;
        return $this;
    }
    /**
     * Method sets destination thumbnail height
     *
     * @param  integer  $height
     * @return Jpl_Filter_File_Image_Thumbnail
     */
    public function setHeight( $height = null ) {
        $this->_height = (int) $height;
        return $this;
    }
    /**
     * Method changes behaviour of filter.
     * Filter will resize image exactly to given dimensions (false)
     * or resize image to fit given dimensions but keep original dimension ratio (true).
     * Setting bestFit to true both dimensions are become mandatory!
     *
     * @param  bool     $bestFit
     * @return Jpl_Filter_File_Image_Thumbnail
     */
    public function setBestFit( $bestFit = false ) {
        $this->_bestFit = (bool) $bestFit;
        return $this;
    }
    /**
     * Method changes behaviour of filter.
     * Filter either just resizes image (false)
     * or resizes with keeping ratio and crop to best fit given width and height (true)
     * If true ommits self::$_bestFit attribute!
     *
     * @param  bool $crop
     * @return Jpl_Filter_File_Image_Thumbnail
     */
    public function setCrop( $crop = false ) {
        $this->_crop = (bool) $crop;
        return $this;
    }
    /**
     * Method filters given file - makes thumb
     *
     * @param  string   $file   path to file
     * @return string   name of file
     */
    public function filter( $file ) {
        $im = new IMagick( $file );
        if ( $this->_crop ) {
            $im->cropThumbnailImage(
                $this->_width,
                $this->_height
            );
        } else {
            $im->thumbnailImage(
                $this->_width,
                $this->_height,
                $this->_bestFit
            );
        }
        $im->writeImage( $file );
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP code to generate icons

Body:
currently i am working on a huge back-end application in Zend Framework.
A lot of times i end up using wrong icon for some object or action.

My Question
Is there any php code to generate icons automatically????

Ofcourse these icons will not be generated magically, best case scenario is that we have a collection of icons which have the type of.

Object (user,category,product,rss etc)

Action (add,edit,delete,update etc)

This way we can create icons by mixing different types of icons on the fly.

The code for generating a icon to delete user with 32x32 and delete icon in bottom-right corner of the icon.

$icon = new Icon();
$icon->object('user')->action('delete');
$icon->action_align('right')->action_valign('bottom');
$icon->action_height(10)->action_width(10);
$icon->height(32)->width(32);
$icon->create();

This is just an example that how can we create a icon which was never exited before.

Body:
Hey i can suggest you to create filer like this one :

Filter that creates image thumbnail

<?php
/**
 * Class for thumbnailing images
 *
 * @author Michał Bachowski (michal@bachowski.pl)
 * @package JPL
 * @subpackage   Jpl_Filter
 * @version 0.1
 * @uses Zend_Filter_Interface, IMagick
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Jpl_Filter_File_Image_Thumbnail {
    /**
     * Thumbnail width
     *
     * @var integer
     */
    protected $_width   = null;
    /**
     * Thumbnail height
     *
     * @var integer
     */
    protected $_height  = null;
    /**
     * Information whether to keep ratio or not while making thumbnail
     *
     * @var bool
     */
    protected $_bestFit = true;
    /**
     * Information whether crop image or just to resize it
     *
     * @var bool
     */
    protected $_crop    = false;
    /**
     * Method sets destination thumbnail width
     *
     * @param  integer  $width
     * @return Jpl_Filter_File_Image_Thumbnail
     */
    public function setWidth( $width = null ) {
        $this->_width = (int) $width;
        return $this;
    }
    /**
     * Method sets destination thumbnail height
     *
     * @param  integer  $height
     * @return Jpl_Filter_File_Image_Thumbnail
     */
    public function setHeight( $height = null ) {
        $this->_height = (int) $height;
        return $this;
    }
    /**
     * Method changes behaviour of filter.
     * Filter will resize image exactly to given dimensions (false)
     * or resize image to fit given dimensions but keep original dimension ratio (true).
     * Setting bestFit to true both dimensions are become mandatory!
     *
     * @param  bool     $bestFit
     * @return Jpl_Filter_File_Image_Thumbnail
     */
    public function setBestFit( $bestFit = false ) {
        $this->_bestFit = (bool) $bestFit;
        return $this;
    }
    /**
     * Method changes behaviour of filter.
     * Filter either just resizes image (false)
     * or resizes with keeping ratio and crop to best fit given width and height (true)
     * If true ommits self::$_bestFit attribute!
     *
     * @param  bool $crop
     * @return Jpl_Filter_File_Image_Thumbnail
     */
    public function setCrop( $crop = false ) {
        $this->_crop = (bool) $crop;
        return $this;
    }
    /**
     * Method filters given file - makes thumb
     *
     * @param  string   $file   path to file
     * @return string   name of file
     */
    public function filter( $file ) {
        $im = new IMagick( $file );
        if ( $this->_crop ) {
            $im->cropThumbnailImage(
                $this->_width,
                $this->_height
            );
        } else {
            $im->thumbnailImage(
                $this->_width,
                $this->_height,
                $this->_bestFit
            );
        }
        $im->writeImage( $file );
    }
}


问:
C++ application terminates with 143 exit code - what does it mean?
My C++ application crashes periodically. It writes Terminated in terminal and stops. I have no idea what is the reason (gdb is not solution, it is mutithreaded application, and error appears on big amount of threads only that gdb can not process due to its low performance). What does exit code 143 mean on CentOS Linux? Does it contain information about the reason of the crash?

答:
There are some exit codes which have either defined or generally agreed upon meaning.

In case of 143, which is 128 + 15, that means program died with signal 15, which is SIGTERM

According to the above table, exit codes 1 - 2, 126 - 165, and 255 have special meanings, and should therefore be avoided for user-specified exit parameters.

See the table at http://www.tldp.org/LDP/abs/html/exitcodes.html

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Hive Join Query throws Error
If a user_id  has multiple records then keep the latest record as per event_timestamp .

My HIVE query :

```<code>SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;
</code>```

When I try to run this hive query I get the below error

```<code>SemanticException [Error 10002]: Line 8:43 Invalid column reference 'converted_event_timestamp'
</code>```

Can Someone tell me what went wrong on this hive query and how do I fix this ?

答:
SELECT a.user_id,a.user_name, a.user_location from </p>

<p>(SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views ) a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;</p>

Title: Hive Join Query throws Error

Body:
If a user_id  has multiple records then keep the latest record as per event_timestamp .

My HIVE query :

SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;

When I try to run this hive query I get the below error

SemanticException [Error 10002]: Line 8:43 Invalid column reference 'converted_event_timestamp'

Can Someone tell me what went wrong on this hive query and how do I fix this ?

Body:
SELECT a.user_id,a.user_name, a.user_location from

(SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views ) a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;


问:
Create multiple Docker network connections
Monday when I got to work I realized that Docker was something that I had to use to fix some server issues in the company at the moment. So since this week all my work has been studying Docker and try to make it work as soon as possible.

So far I understood the containers / swarm / etc, but I am still stuck with the network. Basically I need to run 3 different networks under Docker with different containers on it.

I need to run 3 different networks which will be assigned to 3 public IPs provided by the hoster (OVH) (I don't even know if it will work since only tomorrow I'll get the VPS to work).

So let's say over the network 1 there will be 3 containers to be used as production, network 2 will be used for development and 3rd network to be used as test.

Is this possible to make with Docker?

ATM I'm running tests on a raspbian (jessie) using Docker engine but like I said, I am still stuck with the whole Docker network interface.

答:
Create the networks

```<code>docker network create net1
docker network create net2
docker network create net3
</code>```

Attach the containers to the desired network

```<code>docker run --net=net1 --name=container1 [opts] [image]
</code>```

or, if the container already exists:

```<code>docker network connect net1 container1
</code>```

if you to attach a host IP to the container you can just bind a port to it.
Let's say a container runs o port 80:

```<code>docker run --name=container1 --net=net1 -p YOU_IP_ADDR:80:80 [image]
</code>```

Body:
Create the networks

docker network create net1
docker network create net2
docker network create net3

Attach the containers to the desired network

docker run --net=net1 --name=container1 [opts] [image]

or, if the container already exists:

docker network connect net1 container1

if you to attach a host IP to the container you can just bind a port to it.
Let's say a container runs o port 80:

docker run --name=container1 --net=net1 -p YOU_IP_ADDR:80:80 [image]


问:
Iphone OpengGL ES: Camera view issue
I am making a kind of first person game but my view seems to be off.  It seems to rotate around a place a bit in front of me.  This causes issues on collision as when I hit a wall and rotate, I can rotate around in to (and behind) the wall.

Setup the view:

```<code>const GLfloat zNear = 0.1, zFar = 1000.0, fieldOfView = 120.0;
GLfloat size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 8.0);

glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);

//Rotate the view
glRotatef(-90,0,0,1);

CGRect rect = self.view.bounds;
glFrustumf(-size, size, -size / (rect.size.width / rect.size.height),
           size / (rect.size.width / rect.size.height), zNear, zFar);

glViewport(0, 0, rect.size.width, rect.size.height);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
</code>```

The actual camera view

```<code>//view : prebaked in to OPenGL Template
gluLookAt(eye[0], eye[1], eye[2],center[0], center[1], center[2], 0.0, 1, 0.0);
</code>```

I guessing I need to review the gluLookAt function

答: Found out it was there glTranslatef(0, 0, -3);</p>

Title: Iphone OpengGL ES: Camera view issue

Body:
I am making a kind of first person game but my view seems to be off.  It seems to rotate around a place a bit in front of me.  This causes issues on collision as when I hit a wall and rotate, I can rotate around in to (and behind) the wall.

Setup the view:

const GLfloat zNear = 0.1, zFar = 1000.0, fieldOfView = 120.0;
GLfloat size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 8.0);

glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);

//Rotate the view
glRotatef(-90,0,0,1);

CGRect rect = self.view.bounds;
glFrustumf(-size, size, -size / (rect.size.width / rect.size.height),
           size / (rect.size.width / rect.size.height), zNear, zFar);

glViewport(0, 0, rect.size.width, rect.size.height);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

The actual camera view

//view : prebaked in to OPenGL Template
gluLookAt(eye[0], eye[1], eye[2],center[0], center[1], center[2], 0.0, 1, 0.0);

I guessing I need to review the gluLookAt function


问:
UILabel centered text CGRect?
I have a UILabel with centered text. Single line, not attributed. I want to get the CGRect for the actual text in the label (it spans the whole width of a iOS device). Some of the text is dynamic in the text, so the width of the text in the label can change from time to time. So I want to get the position of the text so that I can place an image next to the first character.

I did this in the past but can't remember what I did to do it.

答:
Try creating a temporary UILabel just to get the text width:

```<code>let fullWidthLabel: UILabel = ...
let tmpLabel = UILabel()
tmpLabel.text = fullWidthLabel.text
tmpLabel.font = fullWidthLabel.font
tmpLabel.sizeToFit()
let textWidth = tmpLabel.frame.width
</code>```

Use textWidth to solve your original problem.

Title: UILabel centered text CGRect?

Body:
Try creating a temporary UILabel just to get the text width:

let fullWidthLabel: UILabel = ...
let tmpLabel = UILabel()
tmpLabel.text = fullWidthLabel.text
tmpLabel.font = fullWidthLabel.font
tmpLabel.sizeToFit()
let textWidth = tmpLabel.frame.width

Use textWidth to solve your original problem.


问:
php display records not showing
I am trying to show records in php with mysqli. this is my code for php display record which does not gives any error but does  not shows any records as well. insert operation is working but display not working what is missing here ???</p>

```<code>    <!DOCTYPE html>
<html>
<body>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

   movie_name<input type="text" name="movie_name"><br>
   movie_embedded_id<input type="text" name="movie_embedded_id"><br>
   rating_no<input type="text" name="rating_no"><br>
   movie_description<input type="text" name="movie_description"><br>
   <input type="submit" name="submit" value="Submit">

</form>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="mydb";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

        if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
                $sql = "INSERT INTO movies (movie_name, movie_embedded_id, rating_no, movie_description)VALUES ('".$_POST['movie_name']."', '".$_POST['movie_embedded_id']."', '".$_POST['rating_no']."','".$_POST['movie_description']."')";

            if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
            } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
            }

        }

$conn->close();

?>

<?php

      if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
$sql = "select * from movies where movie_id = ".$_GET["id"]."";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "<table><tr><th>ID</th><th>movie_name</th><th>movie_embedded_id</th><th>rating_no</th><th>movie_description</th></tr>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<tr><td>" . $row["id"]. "</td><td>" . $row["movie_name"]. " </td><td>" . $row["movie_embedded_id"]. " </td><td>" . $row["rating_no"]. "</td><td> " . $row["rating_no"]. "</td></tr>";
     }
     echo "</table>";
} else {
     echo "0 results";
}

    }

  ?>

</body>
</html>
</code>```

答:
```<code><?php

$movie = $_POST['movie_name'];
$id = $_GET['id'];

/* I wonder why POST and GET method in the same form : where do $vars come from ? */

echo"[ id is ($id) / movie is ($movie) ]";

/* then if $id isn't empty it should do the trick */

$sql = " SELECT * FROM movies WHERE movie_id=$id ";

?>
</code>```

Title: php display records not showing

Body:
I am trying to show records in php with mysqli. this is my code for php display record which does not gives any error but does  not shows any records as well. insert operation is working but display not working what is missing here ???

    <!DOCTYPE html>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

   movie_name<input type="text" name="movie_name">

   movie_embedded_id<input type="text" name="movie_embedded_id">

   rating_no<input type="text" name="rating_no">

   movie_description<input type="text" name="movie_description">

   <input type="submit" name="submit" value="Submit">

</form>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="mydb";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

        if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
                $sql = "INSERT INTO movies (movie_name, movie_embedded_id, rating_no, movie_description)VALUES ('".$_POST['movie_name']."', '".$_POST['movie_embedded_id']."', '".$_POST['rating_no']."','".$_POST['movie_description']."')";

            if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
            } else {
            echo "Error: " . $sql . "
" . $conn->error;
            }

        }

$conn->close();

?>

<?php

      if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
$sql = "select * from movies where movie_id = ".$_GET["id"]."";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "

ID	movie_name	movie_embedded_id	rating_no	movie_description
";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "
" . $row["id"]. "	" . $row["movie_name"]. " 	" . $row["movie_embedded_id"]. " 	" . $row["rating_no"]. "	 " . $row["rating_no"]. "
";
     }
     echo "
";
} else {
     echo "0 results";
}

    }

  ?>


问:
ManifestPlaceholder convert NumericString to actual number?
I'm using ManifestPlaceholder to store some Key in my gradle.build, that could be then use in AndroidManifest.xml eventually. It works fine for my Fabric.io key, but not for my Facebook Key.

The reason is, in my Fabric.io key, it contacts numbers and alphabets. So it is preserved as a String. But since the Facebook key is all number (although it's String), it get converted to some other random number.

More clearer illustration below.

As expected if I set the ManifestPlaceholder as below

```<code>    manifestPlaceholders = [facebook_app_id: "12345678901234G"]
</code>```

And in my AndroidManifest.xml as

```<code>    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="${facebook_app_id}" />
</code>```

I will get my ID retained in generated AndroidManifest.xml

```<code>    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="12345678901234G" />
</code>```

However if I set something that is fully numeric as below

```<code>    manifestPlaceholders = [facebook_app_id: "123456789012345"]
</code>```

While my AndroidManifest.xml is the same

```<code>    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="${facebook_app_id}" />
</code>```

It becomes something as below in my generated AndroidManifest.xml.

```<code>    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="1457557760.000000" />
</code>```

Why did it change my numerical String? How could I preserve it as a String?

答: I verify this works as expected with Android gradle plugin 2.3.0 and Gradle plugin version 3.4.1.

Body:
I'm using ManifestPlaceholder to store some Key in my gradle.build, that could be then use in AndroidManifest.xml eventually. It works fine for my Fabric.io key, but not for my Facebook Key.

The reason is, in my Fabric.io key, it contacts numbers and alphabets. So it is preserved as a String. But since the Facebook key is all number (although it's String), it get converted to some other random number.

More clearer illustration below.

As expected if I set the ManifestPlaceholder as below

    manifestPlaceholders = [facebook_app_id: "12345678901234G"]

And in my AndroidManifest.xml as

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="${facebook_app_id}" />

I will get my ID retained in generated AndroidManifest.xml

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="12345678901234G" />

However if I set something that is fully numeric as below

    manifestPlaceholders = [facebook_app_id: "123456789012345"]

While my AndroidManifest.xml is the same

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="${facebook_app_id}" />

It becomes something as below in my generated AndroidManifest.xml.

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="1457557760.000000" />

Why did it change my numerical String? How could I preserve it as a String?


问:
How to make an a tag border wrap around an image
I need the border to be applied to the a tag but when I do this the border doesn't wrap around the image how can I make this happen?

```<code><div>
  <a href="#">
    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">
  </a>
</div>
</code>```

css:

```<code>a{
  border: 5px solid blue;
}
</code>```

https://jsfiddle.net/b7qdcub1/

答:
If you want to know about Why anchor tag does not take height and width of its containing element Read This Answer.  Instead of border property I'm using css outline.

N.B: There are lots of technique  you can solve this  this.  like Set the border for img element or set display inline-block on anchor tag. Check this Fiddle for more solution

div a{
outline:5px solid blue;
}
div a img{
 vertical-align:bottom; /* Need this to clear white-space */

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">

</div>
   </code>```

Body:
I need the border to be applied to the a tag but when I do this the border doesn't wrap around the image how can I make this happen?

css:

a{
  border: 5px solid blue;
}

https://jsfiddle.net/b7qdcub1/

Body:
If you want to know about Why anchor tag does not take height and width of its containing element Read This Answer.  Instead of border property I'm using css outline.

N.B: There are lots of technique  you can solve this  this.  like Set the border for img element or set display inline-block on anchor tag. Check this Fiddle for more solution

div a{
outline:5px solid blue;
}
div a img{
 vertical-align:bottom; /* Need this to clear white-space */

}

<div>
 <a href="#">
    <img src="https://cdn.pixabay.com/photo/2015/04/23/17/41/javascript-736400_960_720.png">
  </a>
</div>


问:
C#: Have my whole program run in the background
I am working on an app that creates a mock location. Now, after I start it - everything seems to work here - and then go into maps, I always get set right to where I actually am - not where my fake coordinates are. So im thinking, this is due to my program immediately stopping as soon as i push it into the background of the android phone im debugging with.

1) Would u say so too?
2) So, how do I get my program to continue mocking the location, even though its in the background? I already set up a timer, that mocks a new location every 5 seconds. Here is my main activity (which happens to be a bit long, excuse me..)

Any help would be AWESOME!

```<code>  public static double GlobalLongitude = 0.0; // global, cause i need to pull string from void method
    public static double GlobalLatitude = 0.0;

    static readonly string TAG = "X:" + typeof(Activity1).Name;
    Location _currentLocation;
    LocationManager _locationManager;

    string _locationProvider;
    TextView _locationText;
    static TextView txtAdded;
    static Button btnMain;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        _locationText = FindViewById<TextView>(Resource.Id.GpsTest);
        txtAdded = FindViewById<TextView>(Resource.Id.AddedCoordinates);
        btnMain = FindViewById<Button>(Resource.Id.startbutton);

        CountDown();
        InitializeLocationManager();
    } // start here! :D

    private void CountDown()
    {

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 5000;
        timer.Elapsed += OnTimedEvent;
        timer.Enabled = true;

    }

    private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e) // txt.Added is here!
    {
         txtAdded.Text = SetMockLocation();
    }

    public void OnLocationChanged(Location location)
    {
        string test = "Null";
        string test2 = "Null";
        bool waitforresult = false;

        _currentLocation = location;
        if (_currentLocation == null)
        {
            _locationText.Text = "Unable to determine your location. Try again in a short while.";
        }
        else
        {
            _locationText.Text = string.Format("Unchanged: {0:f5} {1:f5}", _currentLocation.Latitude, _currentLocation.Longitude);// hh: 53, 10
            //das her wird ausgegeben bei button.click

            test = string.Format("{0:f5}", _currentLocation.Latitude); // to format
            test2 = string.Format("{0:f5}", _currentLocation.Longitude);

            double.TryParse(test, out GlobalLatitude);
            double.TryParse(test2, out GlobalLongitude);

            if (test != "Null")
            {
                waitforresult = true;
            }

            if (waitforresult == true)
            {
                Add700ToCoordinates();
            }
        }

    } // ausgabe der koordinaten

    void InitializeLocationManager()
    {
        _locationManager = (LocationManager)GetSystemService(LocationService);
        Criteria criteriaForLocationService = new Criteria
        {
            Accuracy = Accuracy.Fine
        };
        IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);

        if (acceptableLocationProviders.Any())
        {
            _locationProvider = acceptableLocationProviders.First();
        }
        else
        {
            _locationProvider = string.Empty;
        }
        Log.Debug(TAG, "Using " + _locationProvider + ".");

    }

    protected override void OnResume()
    {
        base.OnResume();
        _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
        Log.Debug(TAG, "Listening for location updates using " + _locationProvider + ".");
    }

    protected override void OnPause()
    {
        base.OnPause();
        _locationManager.RemoveUpdates(this);
        Log.Debug(TAG, "No longer listening for location updates.");
    }

    public static double Add700ToCoordinates()
    {
        string xy = "Null";

        double FinalCoordinates = (GlobalLatitude + 0.01065);

        btnMain.Click += (sender, e) =>
        {

            xy = FinalCoordinates.ToString();
            xy = xy + " " + GlobalLongitude.ToString();

        };

        return FinalCoordinates;
    }

    public static string SetMockLocation()
    {

        var context = Android.App.Application.Context;
        var locationManager = context.GetSystemService(LocationService) as LocationManager;

        locationManager.AddTestProvider("Test09", false, false, false, false, false, false, false, Power.Low, Android.Hardware.SensorStatus.AccuracyHigh);
        locationManager.SetTestProviderEnabled("Test09", true);

        var location = new Location("Test09");
        location.Latitude = Add700ToCoordinates();
        location.Longitude = GlobalLongitude;
        location.Accuracy = 0; // ob das geht?... ja, aber was beduetet es?
        location.Time = DateTime.Now.Ticks;
        location.ElapsedRealtimeNanos = 100;  // hier das gleiche... was hießt es? :D
        locationManager.SetTestProviderLocation("Test09", location);

        //Check if your event reacted the right way

        locationManager.RemoveTestProvider("Test09");

        return location.Latitude.ToString();
    }

}
</code>```

}

答:
First you need to create native implementation for services for each platform.

For Android:

You need to wrap your service into Android Service to have capability work in background. Please see this references https://developer.android.com/guide/components/services.html
https://developer.xamarin.com/guides/android/application_fundamentals/services/

For iOS:

It's little beat harder. First read this reference, especially "Declaring Your App’s Supported Background Tasks" part.(https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html)
So you can use "Location updates" background mode and inject your mock-generator service into "locations updates" service.
Below example for xamarin iOS:

```<code>    private void StartAccelerometerUpdates()
    {
        if (_motionManager.AccelerometerAvailable)
            _motionManager.AccelerometerUpdateInterval = ACCEL_UPDATE_INTERVAL;
        _motionManager.StartAccelerometerUpdates (NSOperationQueue.MainQueue, AccelerometerDataUpdatedHandler);
    }

    public void AccelerometerDataUpdatedHandler(CMAccelerometerData data, NSError error)
    { //your mock-generator code }
</code>```

Body:
I am working on an app that creates a mock location. Now, after I start it - everything seems to work here - and then go into maps, I always get set right to where I actually am - not where my fake coordinates are. So im thinking, this is due to my program immediately stopping as soon as i push it into the background of the android phone im debugging with.

1) Would u say so too?
2) So, how do I get my program to continue mocking the location, even though its in the background? I already set up a timer, that mocks a new location every 5 seconds. Here is my main activity (which happens to be a bit long, excuse me..)

Any help would be AWESOME!

  public static double GlobalLongitude = 0.0; // global, cause i need to pull string from void method
    public static double GlobalLatitude = 0.0;

    static readonly string TAG = "X:" + typeof(Activity1).Name;
    Location _currentLocation;
    LocationManager _locationManager;

    string _locationProvider;
    TextView _locationText;
    static TextView txtAdded;
    static Button btnMain;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        _locationText = FindViewById<TextView>(Resource.Id.GpsTest);
        txtAdded = FindViewById<TextView>(Resource.Id.AddedCoordinates);
        btnMain = FindViewById<Button>(Resource.Id.startbutton);

        CountDown();
        InitializeLocationManager();
    } // start here! :D

    private void CountDown()
    {

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 5000;
        timer.Elapsed += OnTimedEvent;
        timer.Enabled = true;

    }

    private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e) // txt.Added is here!
    {
         txtAdded.Text = SetMockLocation();
    }

    public void OnLocationChanged(Location location)
    {
        string test = "Null";
        string test2 = "Null";
        bool waitforresult = false;

        _currentLocation = location;
        if (_currentLocation == null)
        {
            _locationText.Text = "Unable to determine your location. Try again in a short while.";
        }
        else
        {
            _locationText.Text = string.Format("Unchanged: {0:f5} {1:f5}", _currentLocation.Latitude, _currentLocation.Longitude);// hh: 53, 10
            //das her wird ausgegeben bei button.click

            test = string.Format("{0:f5}", _currentLocation.Latitude); // to format
            test2 = string.Format("{0:f5}", _currentLocation.Longitude);

            double.TryParse(test, out GlobalLatitude);
            double.TryParse(test2, out GlobalLongitude);

            if (test != "Null")
            {
                waitforresult = true;
            }

            if (waitforresult == true)
            {
                Add700ToCoordinates();
            }
        }

    } // ausgabe der koordinaten

    void InitializeLocationManager()
    {
        _locationManager = (LocationManager)GetSystemService(LocationService);
        Criteria criteriaForLocationService = new Criteria
        {
            Accuracy = Accuracy.Fine
        };
        IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);

        if (acceptableLocationProviders.Any())
        {
            _locationProvider = acceptableLocationProviders.First();
        }
        else
        {
            _locationProvider = string.Empty;
        }
        Log.Debug(TAG, "Using " + _locationProvider + ".");

    }

    protected override void OnResume()
    {
        base.OnResume();
        _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
        Log.Debug(TAG, "Listening for location updates using " + _locationProvider + ".");
    }

    protected override void OnPause()
    {
        base.OnPause();
        _locationManager.RemoveUpdates(this);
        Log.Debug(TAG, "No longer listening for location updates.");
    }

    public static double Add700ToCoordinates()
    {
        string xy = "Null";

        double FinalCoordinates = (GlobalLatitude + 0.01065);

        btnMain.Click += (sender, e) =>
        {

            xy = FinalCoordinates.ToString();
            xy = xy + " " + GlobalLongitude.ToString();

        };

        return FinalCoordinates;
    }

    public static string SetMockLocation()
    {

        var context = Android.App.Application.Context;
        var locationManager = context.GetSystemService(LocationService) as LocationManager;

        locationManager.AddTestProvider("Test09", false, false, false, false, false, false, false, Power.Low, Android.Hardware.SensorStatus.AccuracyHigh);
        locationManager.SetTestProviderEnabled("Test09", true);

        var location = new Location("Test09");
        location.Latitude = Add700ToCoordinates();
        location.Longitude = GlobalLongitude;
        location.Accuracy = 0; // ob das geht?... ja, aber was beduetet es?
        location.Time = DateTime.Now.Ticks;
        location.ElapsedRealtimeNanos = 100;  // hier das gleiche... was hießt es? :D
        locationManager.SetTestProviderLocation("Test09", location);

        //Check if your event reacted the right way

        locationManager.RemoveTestProvider("Test09");

        return location.Latitude.ToString();
    }

}

}

Body:
First you need to create native implementation for services for each platform.

For Android:

You need to wrap your service into Android Service to have capability work in background. Please see this references https://developer.android.com/guide/components/services.html
https://developer.xamarin.com/guides/android/application_fundamentals/services/

For iOS:

It's little beat harder. First read this reference, especially "Declaring Your App’s Supported Background Tasks" part.(https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html)
So you can use "Location updates" background mode and inject your mock-generator service into "locations updates" service.
Below example for xamarin iOS:

    private void StartAccelerometerUpdates()
    {
        if (_motionManager.AccelerometerAvailable)
            _motionManager.AccelerometerUpdateInterval = ACCEL_UPDATE_INTERVAL;
        _motionManager.StartAccelerometerUpdates (NSOperationQueue.MainQueue, AccelerometerDataUpdatedHandler);
    }

    public void AccelerometerDataUpdatedHandler(CMAccelerometerData data, NSError error)
    { //your mock-generator code }


问:
New-Item executed even though it's within an 'if' statement
I created a script to pull JPEG snapshots from 2 IP cameras. For me to keep them organized I added some lines to check the date and create a folder matching it. The script also checks if the folder exists and if it does, should skip to the snapshot capture.

Everything works fine as intended but it seems for one reason or another the script still tries to create the folder and shows and error in my PS console that the directory exists.

```<code>$chk_path = Test-Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$Make_SnapShot_Folder = New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$Camera_A = (new-object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))\Camera_A$((Get-Date).ToString('HH-mm-ss')).jpeg")
$Camera_B = (new-object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))\Camera_B$((Get-Date).ToString('HH-mm-ss')).jpeg")
if (-not ($chk_path) ) {
write-host "C:\SnapShots doesn't exist, creating it"
$Make_ScrapShot_Folder
} else {
write-host "C:\SnapShots exists, Saving SnapShots"
}
Camera_A
Camera_B
</code>```

答:
The following code snippet should work:</p>

```<code>$str_path = "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$chk_path = Test-Path $str_path
if ($chk_path) {
    $Make_SnapShot_Folder = Get-Item -Path $str_path
} else {
    $Make_SnapShot_Folder = New-Item -ItemType Directory -Path $str_path
}
$Make_SnapShot_Folder      ### this outputs a DirectoryInfo
</code>```

Body:
I created a script to pull JPEG snapshots from 2 IP cameras. For me to keep them organized I added some lines to check the date and create a folder matching it. The script also checks if the folder exists and if it does, should skip to the snapshot capture.

Everything works fine as intended but it seems for one reason or another the script still tries to create the folder and shows and error in my PS console that the directory exists.

$chk_path = Test-Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$Make_SnapShot_Folder = New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$Camera_A = (new-object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))\Camera_A$((Get-Date).ToString('HH-mm-ss')).jpeg")
$Camera_B = (new-object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))\Camera_B$((Get-Date).ToString('HH-mm-ss')).jpeg")
if (-not ($chk_path) ) {
write-host "C:\SnapShots doesn't exist, creating it"
$Make_ScrapShot_Folder
} else {
write-host "C:\SnapShots exists, Saving SnapShots"
}
Camera_A
Camera_B

Body:
The following code snippet should work:

$str_path = "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$chk_path = Test-Path $str_path
if ($chk_path) {
    $Make_SnapShot_Folder = Get-Item -Path $str_path
} else {
    $Make_SnapShot_Folder = New-Item -ItemType Directory -Path $str_path
}
$Make_SnapShot_Folder      ### this outputs a DirectoryInfo


问:
Individual Labels for different languages in apex 4.11
for example I have a textfield and I want to show the labelname in different languages. I create a text message with the key "label_password" for english and german.

How can I configure the the textfield to use the text message "label_password"?

I found nothing in the web.

Bye,
Christian

答:
thanks for your answer, but I have a problem with point 3.

First I make a label field ("P201_LABEL") with the source "APEX_LANG.MESSAGE('LABEL_PASSWORD', V('APP_USER'));". And it works fine. Then I change the type to hidden item. Last step is to configure a text field, but what is the value in the field "Label"? When I put in "&P201_LABEL." the label is empty.

Where is the problem?

Thanks for help,
Christian


问:
Can't build MariaDB on OSX
I'm trying to build MariaDB on the latest OSX with trace enabled but it keeps failing. First, it can't find lz4:

```<code>[ 95%] Building CXX object storage/spider/CMakeFiles/spider.dir/hs_client/socket.cpp.o
ld: library not found for -llz4
[ 95%] Built target simple_password_check
clang: error: linker command failed with exit code 1 (use -v to see invocation)
gmake[2]: *** [storage/mroonga/CMakeFiles/mroonga.dir/build.make:702: storage/mroonga/ha_mroonga.so] Error 1
[ 95%] Building CXX object storage/spider/CMakeFiles/spider.dir/hs_client/string_util.cpp.o
gmake[1]: *** [CMakeFiles/Makefile2:4031: storage/mroonga/CMakeFiles/mroonga.dir/all] Error 2
gmake[1]: *** Waiting for unfinished jobs....
</code>```

Then it fails on an install step:

```<code>libtool: link: ranlib .libs/liblzma.a
libtool: link: ( cd ".libs" && rm -f "liblzma.la" && ln -s "../liblzma.la" "liblzma.la" )
[ 95%] Performing install step for 'build_lzma'
Making install in api
/bin/sh: /Users/ruihpacheco/Desktop/server/storage/tokudb/PerconaFT/xz/src/build_lzma/build-aux/install-sh: Permission denied
gmake[5]: *** [Makefile:292: install-nobase_includeHEADERS] Error 126
gmake[4]: *** [Makefile:409: install-am] Error 2
gmake[3]: *** [Makefile:1391: install-recursive] Error 1
gmake[2]: *** [storage/tokudb/PerconaFT/CMakeFiles/build_lzma.dir/build.make:75: storage/tokudb/PerconaFT/xz/src/build_lzma-stamp/build_lzma-install] Error 2
gmake[1]: *** [CMakeFiles/Makefile2:6161: storage/tokudb/PerconaFT/CMakeFiles/build_lzma.dir/all] Error 2
gmake: *** [Makefile:161: all] Error 2
</code>```

I've installed lz4 from macports and used the command sudo ./BUILD/compile-pentium64-debug-max to build the library.

答: The only way I could get this to build was with the undocumented option -DWITHOUT_DYNAMIC_PLUGINS=1. I did try everything that was suggested in the comments.

Title: Can't build MariaDB on OSX

Body:
I'm trying to build MariaDB on the latest OSX with trace enabled but it keeps failing. First, it can't find lz4:

[ 95%] Building CXX object storage/spider/CMakeFiles/spider.dir/hs_client/socket.cpp.o
ld: library not found for -llz4
[ 95%] Built target simple_password_check
clang: error: linker command failed with exit code 1 (use -v to see invocation)
gmake[2]: *** [storage/mroonga/CMakeFiles/mroonga.dir/build.make:702: storage/mroonga/ha_mroonga.so] Error 1
[ 95%] Building CXX object storage/spider/CMakeFiles/spider.dir/hs_client/string_util.cpp.o
gmake[1]: *** [CMakeFiles/Makefile2:4031: storage/mroonga/CMakeFiles/mroonga.dir/all] Error 2
gmake[1]: *** Waiting for unfinished jobs....

Then it fails on an install step:

libtool: link: ranlib .libs/liblzma.a
libtool: link: ( cd ".libs" && rm -f "liblzma.la" && ln -s "../liblzma.la" "liblzma.la" )
[ 95%] Performing install step for 'build_lzma'
Making install in api
/bin/sh: /Users/ruihpacheco/Desktop/server/storage/tokudb/PerconaFT/xz/src/build_lzma/build-aux/install-sh: Permission denied
gmake[5]: *** [Makefile:292: install-nobase_includeHEADERS] Error 126
gmake[4]: *** [Makefile:409: install-am] Error 2
gmake[3]: *** [Makefile:1391: install-recursive] Error 1
gmake[2]: *** [storage/tokudb/PerconaFT/CMakeFiles/build_lzma.dir/build.make:75: storage/tokudb/PerconaFT/xz/src/build_lzma-stamp/build_lzma-install] Error 2
gmake[1]: *** [CMakeFiles/Makefile2:6161: storage/tokudb/PerconaFT/CMakeFiles/build_lzma.dir/all] Error 2
gmake: *** [Makefile:161: all] Error 2

I've installed lz4 from macports and used the command sudo ./BUILD/compile-pentium64-debug-max to build the library.


问:
permutation using regular expression in php
Is there any way to get permutation of all words in a string using only regular expression in php.

For example:

for input like "How to remove pain in human knee"

I want output as:

"How To", "How","pain knee","remove knee","knee pain","in remove","human pain knee", etc.

答:
Using regex will only serve to slow down the process.

I have written a function based on the powerSet() function posted by Yada @ https://stackoverflow.com/a/27968556/2943403)

Code: (Demo)

```<code>function permStacker($array){
    $stack=[[]];  // declare intitial empty element
    foreach($array as $element){
        foreach($stack as $combination){
            foreach(array_diff($array,$combination) as $left){
                $merge=array_merge($combination,[$left]);
                $stack[implode(' ',$merge)]=$merge;  // keys hold desired strings, values hold subarray of combinations for iterated referencing
            }
        }
    }
    unset($stack[0]); // remove initial empty element
    return array_keys($stack);  // return array of permutations as space delimited strings
}

$string='How to remove pain in human knee';
$permutations=permStacker(explode(' ',$string));
echo 'Total Permutations: ',sizeof($permutations),"\n";
var_export($permutations);
</code>```

Output:

```<code>Total Permutations: 13699
array (
  0 => 'How',
  1 => 'to',
  2 => 'remove',
  3 => 'pain',
  4 => 'in',
  5 => 'human',
  6 => 'knee',
  7 => 'How to',
  8 => 'How remove',
  9 => 'How pain',
  10 => 'How in',
  11 => 'How human',
  12 => 'How knee',
  13 => 'to How',
  14 => 'to remove',
  15 => 'to pain',
  16 => 'to in',
  17 => 'to human',
  18 => 'to knee',
  19 => 'remove How',
  20 => 'remove to',
  21 => 'remove pain',
  22 => 'remove in',
  23 => 'remove human',
  24 => 'remove knee',
  25 => 'pain How',
  26 => 'pain to',
  27 => 'pain remove',
  28 => 'pain in',
  29 => 'pain human',
  30 => 'pain knee',
  31 => 'in How',
  32 => 'in to',
  33 => 'in remove',
  34 => 'in pain',
  35 => 'in human',
  36 => 'in knee',
  37 => 'human How',
  38 => 'human to',
  39 => 'human remove',
  40 => 'human pain',
  41 => 'human in',
  42 => 'human knee',
  43 => 'knee How',
  44 => 'knee to',
  45 => 'knee remove',
  46 => 'knee pain',
  47 => 'knee in',
  48 => 'knee human',
  49 => 'How to remove',
  50 => 'How to pain',
  51 => 'How to in',
</code>```

Here is a post by bob at math.stackexchange which confirms that 13699 is the expected size of the returned array when given 7 words in the input string.  Furthermore, bob's breakdown should serve as a warning about how the permutations ramp up rather fast -- be careful with your big strings.

Body:
Using regex will only serve to slow down the process.

I have written a function based on the powerSet() function posted by Yada @ https://stackoverflow.com/a/27968556/2943403)

Code: (Demo)

function permStacker($array){
    $stack=[[]];  // declare intitial empty element
    foreach($array as $element){
        foreach($stack as $combination){
            foreach(array_diff($array,$combination) as $left){
                $merge=array_merge($combination,[$left]);
                $stack[implode(' ',$merge)]=$merge;  // keys hold desired strings, values hold subarray of combinations for iterated referencing
            }
        }
    }
    unset($stack[0]); // remove initial empty element
    return array_keys($stack);  // return array of permutations as space delimited strings
}

$string='How to remove pain in human knee';
$permutations=permStacker(explode(' ',$string));
echo 'Total Permutations: ',sizeof($permutations),"\n";
var_export($permutations);

Output:

Total Permutations: 13699
array (
  0 => 'How',
  1 => 'to',
  2 => 'remove',
  3 => 'pain',
  4 => 'in',
  5 => 'human',
  6 => 'knee',
  7 => 'How to',
  8 => 'How remove',
  9 => 'How pain',
  10 => 'How in',
  11 => 'How human',
  12 => 'How knee',
  13 => 'to How',
  14 => 'to remove',
  15 => 'to pain',
  16 => 'to in',
  17 => 'to human',
  18 => 'to knee',
  19 => 'remove How',
  20 => 'remove to',
  21 => 'remove pain',
  22 => 'remove in',
  23 => 'remove human',
  24 => 'remove knee',
  25 => 'pain How',
  26 => 'pain to',
  27 => 'pain remove',
  28 => 'pain in',
  29 => 'pain human',
  30 => 'pain knee',
  31 => 'in How',
  32 => 'in to',
  33 => 'in remove',
  34 => 'in pain',
  35 => 'in human',
  36 => 'in knee',
  37 => 'human How',
  38 => 'human to',
  39 => 'human remove',
  40 => 'human pain',
  41 => 'human in',
  42 => 'human knee',
  43 => 'knee How',
  44 => 'knee to',
  45 => 'knee remove',
  46 => 'knee pain',
  47 => 'knee in',
  48 => 'knee human',
  49 => 'How to remove',
  50 => 'How to pain',
  51 => 'How to in',

Here is a post by bob at math.stackexchange which confirms that 13699 is the expected size of the returned array when given 7 words in the input string.  Furthermore, bob's breakdown should serve as a warning about how the permutations ramp up rather fast -- be careful with your big strings.


问:
Creating and clearing rectangles in Flash CS5
I have an XML document that I am reading in and drawing a bunch of rectangles from the data that I get.  This bit of code is inserted in one frame.  Buttons are used to navigate through the frames. A button on the main screen takes you to the frame that draws the rectangles.  I have a Back button on the frame that draws the rectangles that takes you back to the main screen and that works fine but when I click Back, the rectangles that I drew still remain on the scene.  Is there anyway that I can erase all of the rectangles at once?

Thanks

答:
That would depend on how you draw the rectangles, if you use the graphics API, you could simply do:

```<code>    this.graphics.clear();
</code>```

if you add DisplayObjects, do:

```<code>   while( this.numChildren > 0 )
      this.removeChildAt( 0 );
</code>```

You can of course call these methods on any container MovieClip :

```<code>     //for instance...
     mc.graphics.clear();

     //or
     while( mc.numChildren > 0 )
         mc.removeChildAt( 0 );
</code>```

Body:
That would depend on how you draw the rectangles, if you use the graphics API, you could simply do:

    this.graphics.clear();

if you add DisplayObjects, do:

   while( this.numChildren > 0 )
      this.removeChildAt( 0 );

You can of course call these methods on any container MovieClip :

     //for instance...
     mc.graphics.clear();

     //or
     while( mc.numChildren > 0 )
         mc.removeChildAt( 0 );


答:
Move this line:

```<code>$Make_SnapShot_Folder =
    New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
</code>```

To here:

```<code>if (-not ($chk_path) ) {
<-- Here
write-host "C:\SnapShots doesn't exist, creating it"
$Make_ScrapShot_Folder <-- Remove this line
</code>```

Title: New-Item executed even though it's within an 'if' statement

Body:
Move this line:

$Make_SnapShot_Folder =
    New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"

To here:

if (-not ($chk_path) ) {
<-- Here
write-host "C:\SnapShots doesn't exist, creating it"
$Make_ScrapShot_Folder <-- Remove this line


问:
Rewriting URL and hiding Subpage Name
I have a rewrite in my .htaccess file that sends people from example.com to example.com/home

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^$ home [L,R=301]
</code>```

How do I do this but then strip the string "home" from the url bar so that it appears to be example.com? I'm not interested in any subdirectories after home as the rest of the site lives in the root.

Full Context

```<code># Perch Runway
<IfModule mod_rewrite.c>

# Turn on RewriteEngine
RewriteEngine On

# When user goes to the home page send to .com/home and strip /home
RewriteBase /
RewriteRule ^$ home [L,R=301]

# Cache Busting
RewriteRule (assets[/])([^.]*).min.+.(css|js)$ $1$2.min.$3

# Perch Runway
RewriteCond %{REQUEST_URI} !^/login
RewriteCond %{REQUEST_URI} !(/sub-directory-one|/sub-directory-two) [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /login/core/runway/start.php [L]
</IfModule>
</code>```

答:
When you use the R|redirect flag, Apache sends a redirect status to the client. The client then requests the new URL (e.g. http://www.example.com/home) and displays the new URL.

To avoid this behaviour, you do not send a redirect (e.g. R), but silently rewrite internally to the new URL. This way Apache sends the contents of the target without notifying the client.

To just rewrite internally from / to /home, keep the existing rule, but remove the R flag

```<code>RewriteRule ^$ /home [L]
</code>```

Title: Rewriting URL and hiding Subpage Name

Body:
I have a rewrite in my .htaccess file that sends people from example.com to example.com/home

RewriteEngine On
RewriteBase /
RewriteRule ^$ home [L,R=301]

How do I do this but then strip the string "home" from the url bar so that it appears to be example.com? I'm not interested in any subdirectories after home as the rest of the site lives in the root.

Full Context

# Perch Runway
<IfModule mod_rewrite.c>

# Turn on RewriteEngine
RewriteEngine On

# When user goes to the home page send to .com/home and strip /home
RewriteBase /
RewriteRule ^$ home [L,R=301]

# Cache Busting
RewriteRule (assets[/])([^.]*).min.+.(css|js)$ $1$2.min.$3

# Perch Runway
RewriteCond %{REQUEST_URI} !^/login
RewriteCond %{REQUEST_URI} !(/sub-directory-one|/sub-directory-two) [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /login/core/runway/start.php [L]
</IfModule>

Body:
When you use the R|redirect flag, Apache sends a redirect status to the client. The client then requests the new URL (e.g. http://www.example.com/home) and displays the new URL.

To avoid this behaviour, you do not send a redirect (e.g. R), but silently rewrite internally to the new URL. This way Apache sends the contents of the target without notifying the client.

To just rewrite internally from / to /home, keep the existing rule, but remove the R flag

RewriteRule ^$ /home [L]


答:
Unlike other languages probably you've used, PowerShell will execute the code when you assign it to a variable not when the variable is called.

So you're actually creating the folder with this line:

```<code>$Make_SnapShot_Folder = New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
</code>```

You just can re-arrange your code to make it do what you want, and to be more efficient:

```<code>$day = Get-Date -Format 'yyyy-MM-dd'
$snapshots_dir = "C:\SnapShots\$day"

if (Test-Path $snapshots_dir) {
    Write-Host "$snapshots_dir exists, Saving SnapShots"
} else {
    Write-Host "$snapshots_dir doesn't exist, creating it"
    New-Item -ItemType Directory -Path $snapshots_dir
}

$timestamp = Get-Date -Format 'HH-mm-ss'

(New-Object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"$snapshots_dir\Camera_A$timestamp.jpeg")
(New-Object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"$snapshots_dir\Camera_B$timestamp.jpeg")
</code>```

Body:
Unlike other languages probably you've used, PowerShell will execute the code when you assign it to a variable not when the variable is called.

So you're actually creating the folder with this line:

$Make_SnapShot_Folder = New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"

You just can re-arrange your code to make it do what you want, and to be more efficient:

$day = Get-Date -Format 'yyyy-MM-dd'
$snapshots_dir = "C:\SnapShots\$day"

if (Test-Path $snapshots_dir) {
    Write-Host "$snapshots_dir exists, Saving SnapShots"
} else {
    Write-Host "$snapshots_dir doesn't exist, creating it"
    New-Item -ItemType Directory -Path $snapshots_dir
}

$timestamp = Get-Date -Format 'HH-mm-ss'

(New-Object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"$snapshots_dir\Camera_A$timestamp.jpeg")
(New-Object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"$snapshots_dir\Camera_B$timestamp.jpeg")


问:
Complex group regex pattern in Java
I have developed regex pattern to parse bibliography in scientific articles. We use AMA citation style, for journal citations it is can look like this:

```<code>"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24(7): 3057-3067."
</code>```

or without issue number:

```<code>"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24: 3057-3067."
</code>```

or with only first page (electronic number).

```<code>"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24(7): 3057."
</code>```

or simply with only volume number (if ahead of print):

```<code>"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24."
</code>```

My pattern matches all this situations and groups all the data (escape with 2 slashes because of Java):

```<code>(.*?)\\.(.*?)\\.(.*?)(?<year>\\d+)\\s*?;?\\s*?(?:(?<volume>\\d+))?(?:\\((?<issue>\\d+)\\))?\\s*?(?::\\s*?(?<fpage>\\d+|[A-Za-z]+\\d+))?(?:[\\-\\–](?<lpage>\\d+))?\\.
</code>```

The problem is that authors consistently put whitespace between first and last page number. I think maybe this pattern can be changed also to match this?

```<code>"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24(7): 3057 - 3067."
</code>```

here is an example, where can be seen that pattern matches this incorrectly.

Title: Complex group regex pattern in Java

Body:
I have developed regex pattern to parse bibliography in scientific articles. We use AMA citation style, for journal citations it is can look like this:

"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24(7): 3057-3067."

or without issue number:

"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24: 3057-3067."

or with only first page (electronic number).

"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24(7): 3057."

or simply with only volume number (if ahead of print):

"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24."

My pattern matches all this situations and groups all the data (escape with 2 slashes because of Java):

(.*?)\\.(.*?)\\.(.*?)(?<year>\\d+)\\s*?;?\\s*?(?:(?<volume>\\d+))?(?:\\((?<issue>\\d+)\\))?\\s*?(?::\\s*?(?<fpage>\\d+|[A-Za-z]+\\d+))?(?:[\\-\\–](?<lpage>\\d+))?\\.

The problem is that authors consistently put whitespace between first and last page number. I think maybe this pattern can be changed also to match this?

"Nielsen MK, Neergaard MA, Jensen AB, Bro F, Guldin MB. Psychological distress, health, and socio-economic factors in caregivers of terminally ill patients: a nationwide population-based cohort study. Support Care Cancer. 2016; 24(7): 3057 - 3067."

here is an example, where can be seen that pattern matches this incorrectly.

Body:
The Proper regex is

(.*?)\.(.*?)\.(.*?)(?<year>\d+)\s*?;?\s*?(?:(?<volume>\d+))?(?:\((?<issue>\d+)\))?\s*?(?::\s*?(?<fpage>\d+|[A-Za-z]+\d+))?(?:[ ]*[\-|\–][ ]*(?<lpage>\d+))?\.

This one https://regex101.com/r/RAdNgb/2 fixes your issue. please check it.


问:
Cordova: 'Windows is undefined' on UWP app
I'm trying to migrate a Win/WinPhone 8.1 app to a Win10 (UWP) package.

So far the app is building fine and running, but crashes on first reference on Windows component:

Windows is undefined

(e.g. on accessing Windows.Storage.ApplicationData.current)

Some facts:

WinJS (base.js) is loaded before cordova.js

WinJS is available in global namespace - Windows is not

UseDotNetNativeToolchain property is set to true on *.jsproj

using Cordova Windows v.4.4.3 / WinJS 4.4.0

On Try-And-Error I also added some references like Windows Mobile Extensions for the UWP or Microsoft .NET Native Runtime Package for Windows , but that wasn't the reason.

Any ideas what is missing?

答:
Found the error on the appxmanifest definition:

```<code>    <uap:ApplicationContentUriRules>
        <uap:Rule Match="ms-appx-web:///" Type="include" WindowsRuntimeAccess="all" />
    </uap:ApplicationContentUriRules>
</code>```

wasn't set which caused that the Windows Runtime was not accessible.

Body:
Found the error on the appxmanifest definition:

    <uap:ApplicationContentUriRules>
        <uap:Rule Match="ms-appx-web:///" Type="include" WindowsRuntimeAccess="all" />
    </uap:ApplicationContentUriRules>

wasn't set which caused that the Windows Runtime was not accessible.


问:
How to create a base Ext.app.ViewController common to other view controllers?
I want to create an base ViewController for all other controllers used in an ExtJS app.

The problem is that ExtJs is looking for the base class in /classic/src/view instead of /app/view....

Here is an example:
in /app/view/base/BaseController.js

```<code>Ext.define('myApp.view.base.BaseController', {
    extend: 'Ext.app.ViewController',

    doStuff: function(msg) {
        alert(msg);
    }
});
</code>```

in /app/view/another/AnotherController.js

```<code>Ext.define('myApp.view.another.AnotherController', {
    extend: 'myApp.view.base.BaseController',

    onButtonClick: function() {
        doStuff('Button clicked');
    }
});
</code>```

in /app/classic/src/view/another/Another.js

```<code>Ext.define('myApp.view.another.Another', {
    extend: 'Ext.panel.Panel',
    xtype: 'another',
    alias: 'view.another',
    id: 'panel_another',

    controller: 'another',
    items: [{
        xtype: 'button',
        text: 'The Button',
        handler: onButtonClick
    }]
});
</code>```

However when i run the app, ExtJs throws an error saying that /classic/src/view/base/BaseController.js was not found!

What am i doing wrong here?

Thank you for your time, and for your help!

答: Yes, agree above answer.You can also perform sencha app refresh.You can try this in DEV mode.Please try this also.

Body:
I want to create an base ViewController for all other controllers used in an ExtJS app.

The problem is that ExtJs is looking for the base class in /classic/src/view instead of /app/view....

Here is an example:
in /app/view/base/BaseController.js

Ext.define('myApp.view.base.BaseController', {
    extend: 'Ext.app.ViewController',

    doStuff: function(msg) {
        alert(msg);
    }
});

in /app/view/another/AnotherController.js

Ext.define('myApp.view.another.AnotherController', {
    extend: 'myApp.view.base.BaseController',

    onButtonClick: function() {
        doStuff('Button clicked');
    }
});

in /app/classic/src/view/another/Another.js

Ext.define('myApp.view.another.Another', {
    extend: 'Ext.panel.Panel',
    xtype: 'another',
    alias: 'view.another',
    id: 'panel_another',

    controller: 'another',
    items: [{
        xtype: 'button',
        text: 'The Button',
        handler: onButtonClick
    }]
});

However when i run the app, ExtJs throws an error saying that /classic/src/view/base/BaseController.js was not found!

What am i doing wrong here?

Thank you for your time, and for your help!


问:
Execute a query for all tables and fill in data in new one
I need to get the result table with there fields
 - table_name, min_date, max_date

Here is my query, which I should execute for all tables

```<code>SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM testTable
GROUP BY  short_date
HAVING COUNT(*) > 1) as Duplicates
</code>```

Then I found out how to get all table names
I do it in this way

```<code>SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%'
</code>```

But I don't know how to execute it for all table and fill in the result in a new table.

I tried to do it in this way

```<code>DECLARE @DB_Name varchar(50)
DECLARE @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END

CLOSE database_cursor
DEALLOCATE database_cursor
</code>```

But I got this error

Syntax error or access violation: 1064 You have an error in your SQL
  syntax; check the manual that corresponds to your MySQL server version
  for the right syntax to use near 'DECLARE @DB_Name varchar(50) DECLARE
  @Command varchar(100)' at line 1

UPD

```<code>CREATE PROCEDURE GetData()
BEGIN

DECLARE @DB_Name varchar(50), @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%_') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END;

CLOSE database_cursor
DEALLOCATE database_cursor

END;

CALL GetData()
</code>```

答:
As far as my knowledge concern this error is due to ,DELIMETER and one more thing that you have to apply cursor properly to iterate whole rowset.Here in below code i had wrote down procedure with CURSOR.Make dynamic query and execute that dynamic query using

```<code>PREPARE stmt FROM @VAR_QRY; EXECUTE stmt;
</code>```

That dynamic query will returns exact output you want.Here i had assuming that you have basic knowledge about trigger,loop and Cursor

Try below code.
Hope this will helps.

```<code>DROP PROCEDURE IF EXISTS ITERATEALLTABLE;
DELIMITER $$
CREATE PROCEDURE ITERATEALLTABLE()
BEGIN
DECLARE VAR_TABLE varchar(100);
DECLARE VAR_QRY varchar(100);
DECLARE VAR_FINISHED INT(11) DEFAULT 0;
DECLARE DATABASE_CURSOR CURSOR FOR
                SELECT name AS TableNames
                FROM (
                    SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
                    WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
                    AND `TABLES`.`TABLE_NAME` LIKE 'test%'
                )Z ;

                DECLARE CONTINUE HANDLER FOR NOT FOUND SET VAR_FINISHED = 1;

                OPEN DATABASE_CURSOR;
                GET_NEXTRECORD: LOOP

                        FETCH DATABASE_CURSOR INTO VAR_TABLE;

                            IF VAR_FINISHED = 1 THEN
                            LEAVE GET_NEXTRECORD;
                            END IF;

                            SET @VAR_QRY = CONCAT("SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
                            FROM (SELECT  short_date, type, value,  count(*) as cnt
                            FROM " , VAR_TABLE , " WHERE type = 'test'
                            GROUP BY  short_date, type, value
                            HAVING COUNT(*) > 1) as Duplicates");

                            PREPARE stmt FROM @VAR_QRY;
                            EXECUTE stmt;

                END LOOP GET_NEXTRECORD;

                CLOSE DATABASE_CURSOR;

END;

CALL ITERATEALLTABLE;
</code>```

Body:
I need to get the result table with there fields
 - table_name, min_date, max_date

Here is my query, which I should execute for all tables

SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM testTable
GROUP BY  short_date
HAVING COUNT(*) > 1) as Duplicates

Then I found out how to get all table names
I do it in this way

SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%'

But I don't know how to execute it for all table and fill in the result in a new table.

I tried to do it in this way

DECLARE @DB_Name varchar(50)
DECLARE @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END

CLOSE database_cursor
DEALLOCATE database_cursor

But I got this error

Syntax error or access violation: 1064 You have an error in your SQL
  syntax; check the manual that corresponds to your MySQL server version
  for the right syntax to use near 'DECLARE @DB_Name varchar(50) DECLARE
  @Command varchar(100)' at line 1

UPD

CREATE PROCEDURE GetData()
BEGIN

DECLARE @DB_Name varchar(50), @Command varchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM (SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
AND `TABLES`.`TABLE_NAME` LIKE 'test%_') as TableNames

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0
BEGIN
     SELECT @Command = 'SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
FROM (SELECT  short_date, type, value,  count(*) as cnt
FROM ' + @DB_Name + '
WHERE type = ''test''
GROUP BY  short_date, type, value
HAVING COUNT(*) > 1) as Duplicates'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name
END;

CLOSE database_cursor
DEALLOCATE database_cursor

END;

CALL GetData()

Body:
As far as my knowledge concern this error is due to ,DELIMETER and one more thing that you have to apply cursor properly to iterate whole rowset.Here in below code i had wrote down procedure with CURSOR.Make dynamic query and execute that dynamic query using

PREPARE stmt FROM @VAR_QRY; EXECUTE stmt;

That dynamic query will returns exact output you want.Here i had assuming that you have basic knowledge about trigger,loop and Cursor

Try below code.
Hope this will helps.

DROP PROCEDURE IF EXISTS ITERATEALLTABLE;
DELIMITER $$
CREATE PROCEDURE ITERATEALLTABLE()
BEGIN
DECLARE VAR_TABLE varchar(100);
DECLARE VAR_QRY varchar(100);
DECLARE VAR_FINISHED INT(11) DEFAULT 0;
DECLARE DATABASE_CURSOR CURSOR FOR
                SELECT name AS TableNames
                FROM (
                    SELECT TABLE_NAME as name FROM `information_schema`.`TABLES`
                    WHERE `TABLES`.`TABLE_SCHEMA` = 'test'
                    AND `TABLES`.`TABLE_NAME` LIKE 'test%'
                )Z ;

                DECLARE CONTINUE HANDLER FOR NOT FOUND SET VAR_FINISHED = 1;

                OPEN DATABASE_CURSOR;
                GET_NEXTRECORD: LOOP

                        FETCH DATABASE_CURSOR INTO VAR_TABLE;

                            IF VAR_FINISHED = 1 THEN
                            LEAVE GET_NEXTRECORD;
                            END IF;

                            SET @VAR_QRY = CONCAT("SELECT MIN(short_date) as FirstDuplicatedDate, MAX(short_date) as LastDuplicatedDate
                            FROM (SELECT  short_date, type, value,  count(*) as cnt
                            FROM " , VAR_TABLE , " WHERE type = 'test'
                            GROUP BY  short_date, type, value
                            HAVING COUNT(*) > 1) as Duplicates");

                            PREPARE stmt FROM @VAR_QRY;
                            EXECUTE stmt;

                END LOOP GET_NEXTRECORD;

                CLOSE DATABASE_CURSOR;

END;

CALL ITERATEALLTABLE;


问:
kivy+gspread crashes while trying in an android phone, but works fine in my laptop
I am using gspread and oauth2client in a very simple kivy app, I just want to update one cell in my google sheet. The code works just fine in my PC but when I build the apk file using buildozer and upload it to my android phone it crashes. Is there any conflict between gspread and kivy ???? The code is shown below;</p>

```<code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('cl_sec.json', scope)
client = gspread.authorize(creds)
sheet = client.open('project2').sheet1

class bxlayout(BoxLayout):
    def __init__(self, **kwargs):
        super(bxlayout, self).__init__(**kwargs)

        btn1 = Button(text='ON')
        btn1.bind(on_press=self.clk1)
        self.add_widget(btn1)
        btn2 = Button(text='OFF')
        btn2.bind(on_press=self.clk2)
        self.add_widget(btn2)

    def clk1(self, obj):
        self.background_color = [0,0,1,1]
        sheet.update_cell(2,1, '1')
        self.background_color = [1,1,1,1]

    def clk2(self, obj):
        self.background_color = [0,0,1,1]
        sheet.update_cell(2,1, '0')
        self.background_color = [1,1,1,1]

class appfile(App):
    def build(self):
        ml = bxlayout()
        return ml

if __name__ == "__main__":
    appfile().run()
</code>```

答:
Without logcat any question like this pretty much tells nothing about the problem because:

the code obviously works (laptop)

the packaging apparently too (you can install and launch the app)

so as Eugene suggested, the problem is most likely with you not including the package either in the buildozer's .spec file - the important part looks like this:

```<code>requirements = kivy
</code>```

and for you to use a third-party library you have to mention its name in that particular line:

```<code>requirements = kivy,gspread
</code>```

or with similar python-for-android console switch.

Depending on if it's pure-python or C-extension it will or will not throw an error during packaging now. If it's an extension, you need to write a recipe for it.

Body:
I am using gspread and oauth2client in a very simple kivy app, I just want to update one cell in my google sheet. The code works just fine in my PC but when I build the apk file using buildozer and upload it to my android phone it crashes. Is there any conflict between gspread and kivy ???? The code is shown below;

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('cl_sec.json', scope)
client = gspread.authorize(creds)
sheet = client.open('project2').sheet1

class bxlayout(BoxLayout):
    def __init__(self, **kwargs):
        super(bxlayout, self).__init__(**kwargs)

        btn1 = Button(text='ON')
        btn1.bind(on_press=self.clk1)
        self.add_widget(btn1)
        btn2 = Button(text='OFF')
        btn2.bind(on_press=self.clk2)
        self.add_widget(btn2)

    def clk1(self, obj):
        self.background_color = [0,0,1,1]
        sheet.update_cell(2,1, '1')
        self.background_color = [1,1,1,1]

    def clk2(self, obj):
        self.background_color = [0,0,1,1]
        sheet.update_cell(2,1, '0')
        self.background_color = [1,1,1,1]

class appfile(App):
    def build(self):
        ml = bxlayout()
        return ml

if __name__ == "__main__":
    appfile().run()

Body:
Without logcat any question like this pretty much tells nothing about the problem because:

the code obviously works (laptop)

the packaging apparently too (you can install and launch the app)

so as Eugene suggested, the problem is most likely with you not including the package either in the buildozer's .spec file - the important part looks like this:

requirements = kivy

and for you to use a third-party library you have to mention its name in that particular line:

requirements = kivy,gspread

or with similar python-for-android console switch.

Depending on if it's pure-python or C-extension it will or will not throw an error during packaging now. If it's an extension, you need to write a recipe for it.


问:
where to find source code link
i want to dowmload android source  as repo init -u git://android.git.kernel.org/platform/manifest.git -b android-2.2_r1,i know the method of downloads ,but i donot know  where to find "android-2.2_r1" ,if i want to find 2.1, how to modify the  parameter after -b,could you give a link that tell me which versions may be download. thanks </p>

答: Clone the entire project using the repo tool and let git show you all available branches using git branch. That way you can fund out how the 2.1 branch is called and the just issue a git checkout [thebranch] to switch to the desired branch.

Title: where to find source code link


问:
How I can hide and show tabs conditionally - Ionic 2?
The case is the following: I have a ion-tabs container with several ion-tab elements, and different users that logs into my application. What I need to do is to show or hide the ion-tab elements depending on the user type logged.

The problem is that I need to do this dynamically, and if I use a directive like [show]="variable", it does not work.

tabs.ts

```<code>import { Component } from '@angular/core';

import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any;
  tab2Root: any;
  tab3Root: any;
  tab4Root: any;
  tab5Root: any;
  variable: any;

  constructor(public userData: UserData) {
   // get variable from local storage
    this.userData.getUser().then((value) => {
      if(value.typeLabel == 'Expert') {
        this.variable = true;
        console.log('1->',value.typeLabel);
      }else if(value.typeLabel == 'Client'){
        this.variable = false;
        console.log('2->',value.typeLabel);
      }
    });

    this.tab1Root = this.variable?Page1:Page2; <-- i want to show specify tabs depending on variable value
    this.tab2Root = NotificationsPage;
    this.tab3Root = MessagesPage;
    this.tab4Root = InstructionsPage;
    this.tab5Root = ExpertsPage;
  }
}
</code>```

tabs.html

```<code><ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="tab_title" tabIcon="notifications"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
</ion-tabs>
</code>```

But always this.tab1Root return Page1;

What am I doing wrong? Can somebody help me?

答:
Create a tabs array in your component and use this to dynamically load your template. You can then easily manipulate the tabs array in your component:

tabs.ts

```<code>import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {

  tabs: any[] = [
    { title: "Home", root: Page2, icon: "home" },
    { title: "tab_title", root: NotificationsPage, icon: "notifications" },
    { title: "tab_title", root: MessagesPage, icon: "home" },
    { title: "tab_title", root: InstructionsPage, icon: "home" },
    { title: "tab_title", root: ExpertsPage, icon: "home" }
  ];

  constructor(public userData: UserData) {
    // get variable from local storage
    this.userData.getUser().then((value) => {
      if(value.typeLabel == 'Expert') {
        this.tabs[0].root = Page1;
        console.log('1->',value.typeLabel);
      } else if(value.typeLabel == 'Client'){
        this.tabs[0].root = Page2;
        console.log('2->',value.typeLabel);
      }
    });
  }
}
</code>```

tabs.html

```<code><ion-tabs>
  <ion-tab *ngFor="let tab of tabs" [root]="tab.root" [tabTitle]="tab.title" [tabIcon]="tab.icon"></ion-tab>
</ion-tabs>
</code>```

Body:
The case is the following: I have a ion-tabs container with several ion-tab elements, and different users that logs into my application. What I need to do is to show or hide the ion-tab elements depending on the user type logged.

The problem is that I need to do this dynamically, and if I use a directive like [show]="variable", it does not work.

tabs.ts

import { Component } from '@angular/core';

import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any;
  tab2Root: any;
  tab3Root: any;
  tab4Root: any;
  tab5Root: any;
  variable: any;

  constructor(public userData: UserData) {
   // get variable from local storage
    this.userData.getUser().then((value) => {
      if(value.typeLabel == 'Expert') {
        this.variable = true;
        console.log('1->',value.typeLabel);
      }else if(value.typeLabel == 'Client'){
        this.variable = false;
        console.log('2->',value.typeLabel);
      }
    });

    this.tab1Root = this.variable?Page1:Page2; <-- i want to show specify tabs depending on variable value
    this.tab2Root = NotificationsPage;
    this.tab3Root = MessagesPage;
    this.tab4Root = InstructionsPage;
    this.tab5Root = ExpertsPage;
  }
}

tabs.html

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="tab_title" tabIcon="notifications"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
</ion-tabs>

But always this.tab1Root return Page1;

What am I doing wrong? Can somebody help me?

Body:
Create a tabs array in your component and use this to dynamically load your template. You can then easily manipulate the tabs array in your component:

tabs.ts

import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {

  tabs: any[] = [
    { title: "Home", root: Page2, icon: "home" },
    { title: "tab_title", root: NotificationsPage, icon: "notifications" },
    { title: "tab_title", root: MessagesPage, icon: "home" },
    { title: "tab_title", root: InstructionsPage, icon: "home" },
    { title: "tab_title", root: ExpertsPage, icon: "home" }
  ];

  constructor(public userData: UserData) {
    // get variable from local storage
    this.userData.getUser().then((value) => {
      if(value.typeLabel == 'Expert') {
        this.tabs[0].root = Page1;
        console.log('1->',value.typeLabel);
      } else if(value.typeLabel == 'Client'){
        this.tabs[0].root = Page2;
        console.log('2->',value.typeLabel);
      }
    });
  }
}

tabs.html

<ion-tabs>
  <ion-tab *ngFor="let tab of tabs" [root]="tab.root" [tabTitle]="tab.title" [tabIcon]="tab.icon"></ion-tab>
</ion-tabs>


问:
How does 'parseInt(String, radix)' work?
I understand that the parseInt method is used to convert strings to int, but I do not know how. I understand that if you say:

```<code>System.out.println(Integer.parseInt("52", 10));
</code>```

will give you 52 in base 10. What I am unaware of is if you say replace base 10 with 15, how does it exactly compute. From some research, I found people saying that you must use ASCII values. If it helps, I am trying to be able to solve this on paper solely, without the work of any more code.

答:
The string you are parsing could be in a specific base which you supply with the radix command to parse to an int.  The int is a numerical value and doesn't have a specific base per se.

Examples

```<code>Integer.parseInt("52", 10) returns 52
Integer.parseInt("52", 8) returns the numerical value 42 (8*5+2)
Integer.parseInt("A2", 16) returns the base 10 value 162
</code>```

Body:
I understand that the parseInt method is used to convert strings to int, but I do not know how. I understand that if you say:

System.out.println(Integer.parseInt("52", 10));

will give you 52 in base 10. What I am unaware of is if you say replace base 10 with 15, how does it exactly compute. From some research, I found people saying that you must use ASCII values. If it helps, I am trying to be able to solve this on paper solely, without the work of any more code.

Body:
The string you are parsing could be in a specific base which you supply with the radix command to parse to an int.  The int is a numerical value and doesn't have a specific base per se.

Examples

Integer.parseInt("52", 10) returns 52
Integer.parseInt("52", 8) returns the numerical value 42 (8*5+2)
Integer.parseInt("A2", 16) returns the base 10 value 162