问:
Create Border around image when clicked in JavaScript?
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

```

答:
Give all your images a class name like class="img" then push them into an array using getElementsByClassName(). Also remember to start your mark(i) i value from 0 when filling in the onclicks.</p>

```<code><script>
var array = document.getElementsByClassName("img"); //pushes all your img
function mark(i,j)                                  //divs into an array
{
    array[i].style.border = "2px solid orange"; //makes the border on click
    for(j = 0; j < array.length ; j++) //this for loop will remove the
     {                                // border of every other img div
        if(j != i)
        {
            array[j].style.border="none";
        }
    }
}
</script>
</code>```

Body:
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}

@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

Body:
Give all your images a class name like class="img" then push them into an array using getElementsByClassName(). Also remember to start your mark(i) i value from 0 when filling in the onclicks.

<script>
var array = document.getElementsByClassName("img"); //pushes all your img
function mark(i,j)                                  //divs into an array
{
    array[i].style.border = "2px solid orange"; //makes the border on click
    for(j = 0; j < array.length ; j++) //this for loop will remove the
     {                                // border of every other img div
        if(j != i)
        {
            array[j].style.border="none";
        }
    }
}
</script>


来源: stackexchange

问:
How to avoid returning user password in Symfony 3 via JSON
I am developing a Symfony app with a REST API integrated but I'm facing a problem, when returning an user entity as JSON through an API request it returns the user password and despite being encrypted I would like to avoid it.

My user entity is:

```<code><?php

namespace AppBundle\Entity;

use AppBundle\Util\Language;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 */
class User implements AdvancedUserInterface, \Serializable
{
    public function __construct()
    {
        $this->isActive = true;
    }

    // Functions and parameters

    /**
     * Set password
     *
     * @param string $password
     *
     * @return User
     */
    public
    function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }

    /**
     * Get password
     *
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    // More functions and parameters

    /** @see \Serializable::serialize() */
    public
    function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->createdAt,
            $this->lastLogin,
        ));
    }

    /** @see \Serializable::unserialize() */
    public
    function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->createdAt,
            $this->lastLogin,
            ) = unserialize($serialized);
    }
}
</code>```

The User repository

```<code><?php
namespace AppBundle\Repository;

use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository implements UserLoaderInterface
{
    public function loadUserByUsername($username)
    {
        return $this->createQueryBuilder('u')
            ->where('u.username = :username OR u.email = :email')
            ->setParameter('username', $username)
            ->setParameter('email', $username)
            ->getQuery()
            ->getOneOrNullResult();
    }
}
</code>```

I have an static method to build API responses

```<code>public static function createSuccessfulresponse($entity, $entityName, $responseCode, $userLocale = "en", $responseMsg = "")
{
    $defResponseMsg = ($responseMsg != "" ? $responseMsg : ApiResponseCode::getMsg($responseCode, $userLocale));
    $responseArray = array();
    $responseArray['responseCode'] = $responseCode;
    $responseArray['responseMsg'] = $defResponseMsg;
    $responseArray['userLocale'] = $userLocale;
    if ($entity != null) {
        $responseArray[$entityName] = $entity;
    }
    return ApiResponseHelper::serializeResponse($responseArray);
}
</code>```

The response serializer

```<code>private static function serializeResponse($responseArray)
{
    $encoders = array(new JsonEncoder());
    $normalizers = array(new ObjectNormalizer());
    $serializer = new Serializer($normalizers, $encoders);
    return $serializer->serialize($responseArray, 'json');
}
</code>```

And one of the API calls which returns an user entity (there are more)

```<code>/**
 * @Route("/api/url/{uid}" )
 * @Method({"GET"})
 */
public function getByUidAction($uid)
{
    $user = $this->get('security.token_storage')->getToken()->getUser();
    $entityManager = $this->getDoctrine()->getManager();
    $entity = $entityManager->getRepository('AppBundle:Workday')->findOneBy(['uid' => $uid, 'user' => $user]);
    if($entity != null){
        return new Response(ApiResponseHelper::createSuccessfulresponse($entity, "workday", ApiResponseCode::SUCCESS_FETCH_WORKDAY, $user->getLocale()));
    }else{
        return new Response(ApiResponseHelper::createSuccessfulresponse(null, "workday", ApiResponseCode::ERROR_EXISTS_WORKDAY, $user->getLocale()));
    }
}
</code>```

This is one JSON response from the above method

```<code>{
    "responseCode": "successfulResponseCode",
    "responseMsg": "Data received",
    "userLocale": "es",
    "workday": {
        "id": 10,
        ... so many data
        "job": {
            "id": 11,
            .. more json data
        },
        "user": {
            "username": "amendez",
            "password": "encrypted_password",
            ... more data
        },
        ... and more data
    }
}
</code>```

As you can see I receive a JSON object with the user which contains its encrypted password and many other data, my goal is to avoid returning the password key and value.

Does somebody know how could I achieve it?

答:
You would need to define the Serializer groups with the desired getters assigned. See: https://symfony.com/doc/current/components/serializer.html#attributes-groups.

The preferred (best-practice) method would be to assign the desired groups.

```<code>use Symfony\Component\Serializer\Annotation\Groups;

class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @Groups({"api"})
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    //...

    /**
     * Get password
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }
}
</code>```

Edited for easier use of Serializer service

In your app/config/config.yml enable annotations, which in-turn enables the serializer service.

```<code>#config.yml
framework:
    #...
    serializer:
        enable_annotations: true
</code>```

Now you can call the Serializer service directly or use DI in your custom services.

```<code>use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\HttpFoundation\JsonResponse;

private static function serializeResponse($responseArray)
{
     $serializer = $this->container->get('serializer');

     return $serializer->serialize($responseArray, JsonEncoder::FORMAT, array(
        'groups' => array('api'),
        'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS
    ));
}
</code>```

To manually use the Serializer Component with groups.

```<code>use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;

private static function serializeResponse($responseArray)
{
    $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));

    $normalizer = new ObjectNormalizer($classMetadataFactory);
    $encoder = new JsonEncoder();
    $serializer = new Serializer(array($normalizer), array($encoder));

    return $serializer->serialize($responseArray, JsonEncoder::FORMAT, array('groups' => array('api')));
}
</code>```

Alternatively you should be able to set it as part of the ignored attributes. See: https://symfony.com/doc/current/components/serializer.html#ignoring-attributes

```<code>private static function serializeResponse($responseArray)
{
    $normalizer = new ObjectNormalizer();
    $normalizer->setIgnoredAttributes(array('password'));

    $encoder = new JsonEncoder();
    $serializer = new Serializer(array($normalizer), array($encoder));

    return $serializer->serialize($responseArray, JsonEncoder::FORMAT);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am developing a Symfony app with a REST API integrated but I'm facing a problem, when returning an user entity as JSON through an API request it returns the user password and despite being encrypted I would like to avoid it.

My user entity is:

<?php

namespace AppBundle\Entity;

use AppBundle\Util\Language;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 */
class User implements AdvancedUserInterface, \Serializable
{
    public function __construct()
    {
        $this->isActive = true;
    }

    // Functions and parameters

    /**
     * Set password
     *
     * @param string $password
     *
     * @return User
     */
    public
    function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }

    /**
     * Get password
     *
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    // More functions and parameters

    /** @see \Serializable::serialize() */
    public
    function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->createdAt,
            $this->lastLogin,
        ));
    }

    /** @see \Serializable::unserialize() */
    public
    function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->createdAt,
            $this->lastLogin,
            ) = unserialize($serialized);
    }
}

The User repository

<?php
namespace AppBundle\Repository;

use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;
use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository implements UserLoaderInterface
{
    public function loadUserByUsername($username)
    {
        return $this->createQueryBuilder('u')
            ->where('u.username = :username OR u.email = :email')
            ->setParameter('username', $username)
            ->setParameter('email', $username)
            ->getQuery()
            ->getOneOrNullResult();
    }
}

I have an static method to build API responses

public static function createSuccessfulresponse($entity, $entityName, $responseCode, $userLocale = "en", $responseMsg = "")
{
    $defResponseMsg = ($responseMsg != "" ? $responseMsg : ApiResponseCode::getMsg($responseCode, $userLocale));
    $responseArray = array();
    $responseArray['responseCode'] = $responseCode;
    $responseArray['responseMsg'] = $defResponseMsg;
    $responseArray['userLocale'] = $userLocale;
    if ($entity != null) {
        $responseArray[$entityName] = $entity;
    }
    return ApiResponseHelper::serializeResponse($responseArray);
}

The response serializer

private static function serializeResponse($responseArray)
{
    $encoders = array(new JsonEncoder());
    $normalizers = array(new ObjectNormalizer());
    $serializer = new Serializer($normalizers, $encoders);
    return $serializer->serialize($responseArray, 'json');
}

And one of the API calls which returns an user entity (there are more)

/**
 * @Route("/api/url/{uid}" )
 * @Method({"GET"})
 */
public function getByUidAction($uid)
{
    $user = $this->get('security.token_storage')->getToken()->getUser();
    $entityManager = $this->getDoctrine()->getManager();
    $entity = $entityManager->getRepository('AppBundle:Workday')->findOneBy(['uid' => $uid, 'user' => $user]);
    if($entity != null){
        return new Response(ApiResponseHelper::createSuccessfulresponse($entity, "workday", ApiResponseCode::SUCCESS_FETCH_WORKDAY, $user->getLocale()));
    }else{
        return new Response(ApiResponseHelper::createSuccessfulresponse(null, "workday", ApiResponseCode::ERROR_EXISTS_WORKDAY, $user->getLocale()));
    }
}

This is one JSON response from the above method

{
    "responseCode": "successfulResponseCode",
    "responseMsg": "Data received",
    "userLocale": "es",
    "workday": {
        "id": 10,
        ... so many data
        "job": {
            "id": 11,
            .. more json data
        },
        "user": {
            "username": "amendez",
            "password": "encrypted_password",
            ... more data
        },
        ... and more data
    }
}

As you can see I receive a JSON object with the user which contains its encrypted password and many other data, my goal is to avoid returning the password key and value.

Does somebody know how could I achieve it?

Body:
You would need to define the Serializer groups with the desired getters assigned. See: https://symfony.com/doc/current/components/serializer.html#attributes-groups.

The preferred (best-practice) method would be to assign the desired groups.

use Symfony\Component\Serializer\Annotation\Groups;

class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @Groups({"api"})
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    //...

    /**
     * Get password
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }
}

Edited for easier use of Serializer service

In your app/config/config.yml enable annotations, which in-turn enables the serializer service.

#config.yml
framework:
    #...
    serializer:
        enable_annotations: true

Now you can call the Serializer service directly or use DI in your custom services.

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\HttpFoundation\JsonResponse;

private static function serializeResponse($responseArray)
{
     $serializer = $this->container->get('serializer');

     return $serializer->serialize($responseArray, JsonEncoder::FORMAT, array(
        'groups' => array('api'),
        'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS
    ));
}

To manually use the Serializer Component with groups.

use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;

private static function serializeResponse($responseArray)
{
    $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));

    $normalizer = new ObjectNormalizer($classMetadataFactory);
    $encoder = new JsonEncoder();
    $serializer = new Serializer(array($normalizer), array($encoder));

    return $serializer->serialize($responseArray, JsonEncoder::FORMAT, array('groups' => array('api')));
}

Alternatively you should be able to set it as part of the ignored attributes. See: https://symfony.com/doc/current/components/serializer.html#ignoring-attributes

private static function serializeResponse($responseArray)
{
    $normalizer = new ObjectNormalizer();
    $normalizer->setIgnoredAttributes(array('password'));

    $encoder = new JsonEncoder();
    $serializer = new Serializer(array($normalizer), array($encoder));

    return $serializer->serialize($responseArray, JsonEncoder::FORMAT);
}


问:
removing path from url on redirect from previous site using .htaccess redirect
My situation is as follows, and I'm sorry if this seems simple enough:

we have created a new site, and combined 9 previous domains to one site.

my previous first sites URL was http://www.example.com

the url example.com has been forwarded to my new site, with a page for each previous domain, eg: http://www.newsite.com/location/example

on visiting a previous page on example.com, eg: http://www.example.com/oldpage/ , you get dropped onto http://www.newsite.com/location/example/oldpage/.

I would like to get some assistance on getting a redirect or rewrite rule in my .htaccess file that will allow me to remove the /oldpage/ from the URL on my new site.

I understand SEO practices, and practicality of this, I just need assistance in the .htaccess rule.

答: i found my answer in the following: RewriteRule ^location/example/. /location/example/ [R=301,L]


问:
Can I consolidate all deposited ether to one wallet address without additional transactions?
I am making an application in which I am creating a different Ethereum wallet address for a user in the Ethereum blockchain using web3J.

I have also created one address say as my organisation wallet. When a user deposits some ether in their respective address, I want all the ether to be deposited into my organisation wallet. What I understand that to do this I have to do an another transaction from user account to organisation wallet, which leads to the deduction of transaction fee from user account and not all the ether will go to organisation wallet.

Is there any another approach to do this?

答:
Is there any another approach to do this?

No.

That is what blockchain transactions are all about.

ContentLicense: CC BY-SA 4.0


问:
Resharper ctrl click not working Visual Studio 2015
Resharper has suddenly decided that ctrl alt click and ctrl click are no longer a thing.

I've applied the resharper scheme again

Cleared the resharper cache

Reset the visual studio keyboard Tools > Environment -> Keyboard

Any suggestions?

答:
Thank you @SmartK8 for your answer.  I have Visual Studio 2017 (15.4.4) and ReSharper 2017.2.1.  I have found that CTRL-Click will actually navigate twice in this scenario.  It is super annoying and depending on where your mouse is and where you land you can actually navigate twice.

You can tell this is happening because of the "double underline" on the navigation UI hint.  Check it out:

To turn off Visual Studio's navigate option, go to: Tools > Options > Text Editor > General.  And vote up @SmartK8's answer for this wisdom!  Now only ReSharper's navigation will remain.

Alternately, you can turn off ReSharper's navigation by going to ReSharper > Options > Search & Navigation.  Uncheck Rich mouse navigation in the editor.

I have decided to keep ReSharper's navigation since I can go to definition or implementation.  (Going to implementation is nice when a method is declared in an interface).

Haha, and for the double underline?  The underline that is 1 pixel below is the Visual Studio one.  The underline that is 3 pixels below is the ReSharper one!


问:
Counting records in a SQL subquery
I'm having difficult with a subquery. In plain English I'm trying to pick a random userID from the QCUsers table that has less than 20 records from the QCTier1_Assignments table.  The problem is that my query below is only picking users where it meets the criteria of the inner query when I need it to pick any user from QCUsers table even if the user does not have any records at all in the QCTier1_Assignments table. I need something like this

AND (Sub.QCCount < 20 OR Sub.QCCount = 0 )

```<code>DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
JOIN (SELECT
  QCA.UserID,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  WHERE QCA.ReviewPeriodMonth = @ReviewPeriodMonth
  AND QCA.ReviewPeriodYear = @ReviewPeriodYear
  GROUP BY QCA.UserID
  ) Sub
 ON E1.UserID = Sub.UserID
 WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
 ORDER BY NEWID()
</code>```

I also tried it this way with no luck

```<code>DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
RIGHT JOIN (SELECT
  QCA.UserID,
  ReviewPeriodMonth,
  ReviewPeriodYear,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  GROUP BY
    QCA.UserID,
    ReviewPeriodMonth,
    ReviewPeriodYear
  ) Sub
ON E1.UserID = Sub.UserID
WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
  AND Sub.ReviewPeriodMonth = @ReviewPeriodMonth
  AND Sub.ReviewPeriodYear = @ReviewPeriodYear
ORDER BY NEWID()
</code>```

答:
You should use LEFT JOIN instead of JOIN(INNER JOIN), And you'd better to put the predicate to the outer query based on your practice, but I recommend the following way:

```<code>SELECT TOP1 ABC.UserID,ABC.QCCount
FROM
(
    SELECT E1.UserID, COUNT(*) as QCCount
    FROM QCUsers as E1
    LEFT JOIN QCTier1_Assignments as QCA
    ON QCA.UserID = E1.UserID
    WHERE QCA.ReviewPeriodMonth = @ReviewPeriodMonth
    AND QCA.ReviewPeriodYear = @ReviewPeriodYear
    AND Active = 1
    AND Grade = 12
    GROUP BY E1.UserID
 ) as ABC
WHERE ABC.QCCount <20
ORDER BY NEWID()
</code>```

Title: Counting records in a SQL subquery

Body:
I'm having difficult with a subquery. In plain English I'm trying to pick a random userID from the QCUsers table that has less than 20 records from the QCTier1_Assignments table.  The problem is that my query below is only picking users where it meets the criteria of the inner query when I need it to pick any user from QCUsers table even if the user does not have any records at all in the QCTier1_Assignments table. I need something like this

AND (Sub.QCCount < 20 OR Sub.QCCount = 0 )

DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
JOIN (SELECT
  QCA.UserID,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  WHERE QCA.ReviewPeriodMonth = @ReviewPeriodMonth
  AND QCA.ReviewPeriodYear = @ReviewPeriodYear
  GROUP BY QCA.UserID
  ) Sub
 ON E1.UserID = Sub.UserID
 WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
 ORDER BY NEWID()

I also tried it this way with no luck

DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
RIGHT JOIN (SELECT
  QCA.UserID,
  ReviewPeriodMonth,
  ReviewPeriodYear,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  GROUP BY
    QCA.UserID,
    ReviewPeriodMonth,
    ReviewPeriodYear
  ) Sub
ON E1.UserID = Sub.UserID
WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
  AND Sub.ReviewPeriodMonth = @ReviewPeriodMonth
  AND Sub.ReviewPeriodYear = @ReviewPeriodYear
ORDER BY NEWID()

Body:
You should use LEFT JOIN instead of JOIN(INNER JOIN), And you'd better to put the predicate to the outer query based on your practice, but I recommend the following way:

SELECT TOP1 ABC.UserID,ABC.QCCount
FROM
(
    SELECT E1.UserID, COUNT(*) as QCCount
    FROM QCUsers as E1
    LEFT JOIN QCTier1_Assignments as QCA
    ON QCA.UserID = E1.UserID
    WHERE QCA.ReviewPeriodMonth = @ReviewPeriodMonth
    AND QCA.ReviewPeriodYear = @ReviewPeriodYear
    AND Active = 1
    AND Grade = 12
    GROUP BY E1.UserID
 ) as ABC
WHERE ABC.QCCount <20
ORDER BY NEWID()


问:
Mapping data with ajax returns zero
I've been working with ajax to get input values from a form when it's submitted, but when I look into the console it comes back as 0. I'm not too familiar with ajax overall, so I'm not sure if I'm not using this correctly or if I have an error somewhere else.

Here's what I have:

JS:

```<code>jQuery(this).find(".form-item").on("submit", function(e) {
    var $this = jQuery(this);
    if (this.checkValidity()) {
      e.preventDefault();
      $.ajax({
        url: Config.ajaxurl,
        type: 'POST',
        dataType: 'json',
        accepts: 'application/json',
        context: this,
        data: {
          action: 'process_form',
          form_info: {
            "input_18_16": $(this).parents('.form-item').find('#input_18_16').val() || '',
            "input_18_17": $(this).parents('.form-item').find('#input_18_17').val() || '',
            "input_18_3": $(this).parents('.form-item').find('#input_18_3').val() || '',
            "input_18_2": $(this).parents('.form-item').find('#input_18_2').val() || ''
          },
        },
        success: function(data, status, xhr) {
          console.log('Response:\n', data)
          console.log('successful trigger');
          console.log($(this).find('#input_18_16').val());
        },
        error: function(xhr, code, error) {
          console.log(error)
        }
      })
    }
  });
</code>```

The crazy thing is that I can get the data correctly from this:
console.log($(this).find('#input_18_16').val());
In the console. Which but for some reason the console.log('Response:\n', data) comes back as Response:0 so I'm not sure why it's successful but not able to return anything?

答:
Check the missing ";" on the line  console.log('Response:\n', data).
And I think the "\n" not affects the console.log mensage.

EGG: After this, checkout it https://api.jquery.com/serialize/ may be make your life more easy

Title: Mapping data with ajax returns zero

Body:
I've been working with ajax to get input values from a form when it's submitted, but when I look into the console it comes back as 0. I'm not too familiar with ajax overall, so I'm not sure if I'm not using this correctly or if I have an error somewhere else.

Here's what I have:

JS:

jQuery(this).find(".form-item").on("submit", function(e) {
    var $this = jQuery(this);
    if (this.checkValidity()) {
      e.preventDefault();
      $.ajax({
        url: Config.ajaxurl,
        type: 'POST',
        dataType: 'json',
        accepts: 'application/json',
        context: this,
        data: {
          action: 'process_form',
          form_info: {
            "input_18_16": $(this).parents('.form-item').find('#input_18_16').val() || '',
            "input_18_17": $(this).parents('.form-item').find('#input_18_17').val() || '',
            "input_18_3": $(this).parents('.form-item').find('#input_18_3').val() || '',
            "input_18_2": $(this).parents('.form-item').find('#input_18_2').val() || ''
          },
        },
        success: function(data, status, xhr) {
          console.log('Response:\n', data)
          console.log('successful trigger');
          console.log($(this).find('#input_18_16').val());
        },
        error: function(xhr, code, error) {
          console.log(error)
        }
      })
    }
  });

The crazy thing is that I can get the data correctly from this:
console.log($(this).find('#input_18_16').val());
In the console. Which but for some reason the console.log('Response:\n', data) comes back as Response:0 so I'm not sure why it's successful but not able to return anything?


问:
Vue method not firing
I am working on a project that uses Vue2 (2.5.3) along with Vue Tables 2. All I am trying to do is add an anchor around each row, as the  linked example shows, and invoke the edit() function. However, it doesn't seem to fire at all and I am not getting any errors. Any idea why this is?

.vue file

```<code>  <template>
    <div class="col-md-8 col-md-offset-2">
        <div id="people">
            <v-client-table :data="tableData" :columns="columns">
                <template slot="edit" slot-scope="props">
                    <div>
                        <a class="fa fa-edit" :href="edit(props.row.id)"></a>
                    </div>
                </template>
            </v-client-table>
        </div>
    </div>
</template>

<script>
    import {ServerTable, ClientTable, Event} from 'vue-tables-2';
    import Vue from 'vue';
    import axios from 'axios';

    Vue.use(ClientTable, {
        perPage: 3
    }, false);

    export default {
        methods: {
          edit: function(id){
              console.log("OK", id);
          }
        },
        data() {
            return {
                columns: ['id','name','age'],
                tableData: [
                    {id:1, name:"John",age:"20"},
                    {id:2, name:"Jane",age:"24"},
                    {id:3, name:"Susan",age:"16"},
                    {id:4, name:"Chris",age:"55"},
                    {id:5, name:"Dan",age:"40"}
                ]
            };
        }
    }
</script>

<style lang="scss">
.VuePagination__count {
    display:none;
}
</style>
</code>```

答:
Dont use the href on the anchor tag to trigger your click event. Do it like this

```<code><a class="fa fa-edit" href="#" v-on:click="edit(props.row.id)"></a>
</code>```

Also, the way you had it with :href="edit(props.row.id)" vue is trying to bind a value to your href attribute. But what you are calling is a function that is not returning any value. I wonder if you check the developers console you might get an error related to compiling the template. Anyways ":" means bind, and i dont think binding is what you want to do here.

Title: Vue method not firing

Body:
I am working on a project that uses Vue2 (2.5.3) along with Vue Tables 2. All I am trying to do is add an anchor around each row, as the  linked example shows, and invoke the edit() function. However, it doesn't seem to fire at all and I am not getting any errors. Any idea why this is?

.vue file

  <template>

            <v-client-table :data="tableData" :columns="columns">
                <template slot="edit" slot-scope="props">

                </template>
            </v-client-table>

</template>

Body:
Dont use the href on the anchor tag to trigger your click event. Do it like this

<a class="fa fa-edit" href="#" v-on:click="edit(props.row.id)"></a>

Also, the way you had it with :href="edit(props.row.id)" vue is trying to bind a value to your href attribute. But what you are calling is a function that is not returning any value. I wonder if you check the developers console you might get an error related to compiling the template. Anyways ":" means bind, and i dont think binding is what you want to do here.


问:
CSS style effect involving z-index and transparency
I'm trying to achieve a design close to the snippet here. My problem is that I can't find a way to replace the blue background of .title by a simple transparency (so that the container's background stays visible). If I simply remove the blue background, the border becomes visible where .title is.

Also the "title" is generated by JS so I can't reliably predict the length of div as it may slightly vary depending on the situation.

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title span {
  display: inline-flex;
 align-items: center;
 justify-content: center;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
 background: hsla(200, 70%, 55%, 1);
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border: 0.1rem solid hsla(200, 70%, 20%, 1);
 border-radius: 0rem;
 margin-top: 10px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="zone">
    <div class="title">
      <span>Text Title</span>
    </div>
    <div class="content"></div>
  </div>
</div></code>```

Does anyone have an idea how to achieve what I'm trying to do ? Please let me know if my explanation is too brief or unclear.

Thank you !

答:
You could try to use a fieldset with a legend instead of a div:

https://jsfiddle.net/v9p60p6g/1/

```<code><html>

<head>
  <style>
    .container {
      width: 350px;
      height: 250px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
    }

    fieldset {
      border: solid black 2px;
    }

    legend {

    }

  </style>
</head>

<body>
  <div class="container">
    <fieldset>
      <legend>Testtitel</legend>
      Content
    </fieldset>
  </div>

</body>

</html>
</code>```

Body:
I'm trying to achieve a design close to the snippet here. My problem is that I can't find a way to replace the blue background of .title by a simple transparency (so that the container's background stays visible). If I simply remove the blue background, the border becomes visible where .title is.

Also the "title" is generated by JS so I can't reliably predict the length of div as it may slightly vary depending on the situation.

.container {
  width: 350px;
  height: 250px;
  display: flex;
 justify-content: center;
 align-items: center;
  position: relative;
  background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
}

.zone {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  margin: 0 0 20px 0;
  text-align: center;
}

.title {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  position: absolute;
 top: 0;
 left: 0;
 right: 0;
 z-index: 10;
}

.title span {
  display: inline-flex;
 align-items: center;
 justify-content: center;
 padding: 0 10px;
 height: 20px;
 color: hsla(200, 70%, 20%, 1);
 cursor: default;
 background: hsla(200, 70%, 55%, 1);
}

.content {
  position: relative;
  display: flex;
 justify-content: center;
 align-items: center;
  padding: 30px 30px 20px 30px;
 width: 200px;
 border: 0.1rem solid hsla(200, 70%, 20%, 1);
 border-radius: 0rem;
 margin-top: 10px;
 }

      Text Title

Does anyone have an idea how to achieve what I'm trying to do ? Please let me know if my explanation is too brief or unclear.

Thank you !

Body:
You could try to use a fieldset with a legend instead of a div:

https://jsfiddle.net/v9p60p6g/1/

<html>

<head>
  <style>
    .container {
      width: 350px;
      height: 250px;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      background: url('https://i.pinimg.com/736x/94/90/19/9490199f30fc9db039de091205e73be6--backgrounds-wallpapers-phone-backgrounds.jpg');
    }

    fieldset {
      border: solid black 2px;
    }

    legend {

    }

  </style>
</head>

<body>
  <div class="container">
    <fieldset>
      <legend>Testtitel</legend>
      Content
    </fieldset>
  </div>

</body>

</html>


问:
How to Go to home screen when pressed on navbar button
I want to add a rightbar button on navigation bar as home button..

When ever i tap on that button i want to go to firstcontroller,that is my home screen

Please help me in this

Thanks in advance

答:
Use This to go to HomeScreen in navBar, first create rightBar button </p>

```<code>{
    UIBarButtonItem *Button = [[UIBarButtonItem alloc]
                                   initWithTitle:@"Home"
                                   style:UIBarButtonItemStylePlain
                                   target:self
                                   action:@selector(Button_Action)];
    self.navigationItem.rightBarButtonItem = Button;
    [Button release];
}

-(void) Button_Action
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Use This to go to HomeScreen in navBar, first create rightBar button

{
    UIBarButtonItem *Button = [[UIBarButtonItem alloc]
                                   initWithTitle:@"Home"
                                   style:UIBarButtonItemStylePlain
                                   target:self
                                   action:@selector(Button_Action)];
    self.navigationItem.rightBarButtonItem = Button;
    [Button release];
}

-(void) Button_Action
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}


问:
<<From csv to array to database issue: not loading entire fail or failing
I need some help over here... what I try to do is to read a csv file (which is already converted from xls) then get all lines and put every field of a line into db

```<code>name,lastname,idprod
name,lastname,idprod
name,lastname,idprod
</code>```

the issue might be that some fields are empty,
but after launching the script it starts working for like 1883 lines and put them in database, then the

$row["productid"] ." - ". $productid ."";
 starts outputting empty value

here -

for the rest of the lines

Sorry for code in pastebin, this editor won't allow me to post this question with code saying some issues...

```<code><?php
$rowe = 0;
$exploded;
$data;
$ass = 0;
$hardcore[0][0];
$swag = 0;
if (($handle = fopen("price_list_EN.csv", "r")) !== FALSE) {
    $ass = 0;
    $swag++;
    while (($linebyline = fgetcsv($handle, 1000, ",")) !== FALSE) {

        //$linebyline = explode(",", $linebyline);

        $hardcore[$rowe][$ass] = $linebyline[$ass];
        //echo $linebyline[$ass];
        $exploded[$rowe][$ass] = $hardcore[$rowe][$ass];
        //echo $exploded[$rowe][$ass];

        //while (($explode = fgetcsv($linebyline, 1000, ",")) !== FALSE)
        {
            $num = count($data);
            if ($ass == count($linebyline)){
                echo "<br>";
                $ass = 0;
                $rowe++;
            }else{
                $ass++;
            }
        }
        //}
        fclose($handle);
    }
    //$linebyline = explode("\n", $_POST['message']);
    //$linebyline = explode("\n", $data2);
    //echo count($data2);
    $imo=0;
    $normovalue=0;
    $normovalue2=0;
    $normovalue3=0;
    for ($i=0;$i<30000;$i++){
        if ($exploded[$i][0] == ''){
            $imo = $i;
        }
    }

    for ($rowe=0;$rowe<$imo;$rowe++){
        for ($ass=0;$ass<9;$ass++){
            //$exploded = explode(";", $linebyline[$i]);
            $link = mysql_connect('localhost', 'root', '');
            if (!$link) {
                die('Not connected : ' . mysql_error());
            }

            // make foo the current db
            $db_selected = mysql_select_db('moday', $link);
            if (!$db_selected) {
                die ('Can\'t use foo : ' . mysql_error());
            }
        }
        if ($exploded[$rowe][0] !== "" || $exploded[$rowe][4] !== "" ||
            $exploded[$rowe][3] !== "" || $exploded[$rowe][1] !== ""){
            $productid = $exploded[$rowe][0];
            $price = round($exploded[$rowe][4],2);
            $disponibilita = $exploded[$rowe][3];
            $indir = "null";
            $descrizione = $exploded[$rowe][1];

            $conn = new mysqli("localhost", "root", "", "moday");

            $sql = "SELECT productid from data where productid='$productid'";
            $result = $conn->query($sql);

            if ($result->num_rows == 0) {
                mysql_query("INSERT INTO
         data(productid,price,disponibilita,indir,descrizione)
         values('$productid','$price','$disponibilita','$indir','$descrizione')")
                    or die("Query non valida: " . mysql_error());
                $normovalue++;
            }else{

                // output data of each row
                while($row = $result->fetch_assoc()) {
                    if ($row["productid"] == $productid){
                        echo "here ". $row["productid"] ." - ". $productid ."";
                        if ("$exploded[$rowe][0] == '' || $exploded[$rowe][1] ==
             '' || $exploded[$rowe][3] == '' || $exploded[$rowe][4] == '' ||
           $exploded[$rowe][2] == ''|| $exploded[$rowe][5] hh "){
                            echo $exploded[$rowe][0];
                            echo $rowe;

                        }
                        echo "<br /> \n";
                        $sql2 = "UPDATE data SET price='$price',
             disponibilita='$disponibilita' where productid='$productid'";
                        $normovalue2++;
                        $result2 = $conn->query($sql2);

                    }else{
                    }
                }
            }

            /*$risultato = mysql_query("INSERT INTO
              data(productid,price,disponibilita,indir,descrizione)
              values('$productid','$price','$disponibilita','$indir','$descrizione')")
              or die("Query non valida: " . mysql_error());
            */
            //echo "<br /> \n"
        }
    }
    $normovalue3 = $normovalue + $normovalue2;
    echo "N.1 is $normovalue 2 is $normovalue2 3 is $normovalue3";
    ?>
</code>```

答:
Put the $result into the database, as you desire:

```<code><?php
$csv = "Chris,Garcia,1\nJohn,Doe,2\nJames,Smith,3";

foreach(explode("\n", $csv) as $key => $value) {
    $result = explode(",", $value);

    echo "Name: " . $result[0] . ", Lastname: " . $result[1] . ", ID: " . $result[2] . "\n";
}

exit();
?>
</code>```

Body:
I need some help over here... what I try to do is to read a csv file (which is already converted from xls) then get all lines and put every field of a line into db

name,lastname,idprod
name,lastname,idprod
name,lastname,idprod

the issue might be that some fields are empty,
but after launching the script it starts working for like 1883 lines and put them in database, then the

$row["productid"] ." - ". $productid ."";
 starts outputting empty value

here -

for the rest of the lines

Sorry for code in pastebin, this editor won't allow me to post this question with code saying some issues...

<?php
$rowe = 0;
$exploded;
$data;
$ass = 0;
$hardcore[0][0];
$swag = 0;
if (($handle = fopen("price_list_EN.csv", "r")) !== FALSE) {
    $ass = 0;
    $swag++;
    while (($linebyline = fgetcsv($handle, 1000, ",")) !== FALSE) {

        //$linebyline = explode(",", $linebyline);

        $hardcore[$rowe][$ass] = $linebyline[$ass];
        //echo $linebyline[$ass];
        $exploded[$rowe][$ass] = $hardcore[$rowe][$ass];
        //echo $exploded[$rowe][$ass];

        //while (($explode = fgetcsv($linebyline, 1000, ",")) !== FALSE)
        {
            $num = count($data);
            if ($ass == count($linebyline)){
                echo "
";
                $ass = 0;
                $rowe++;
            }else{
                $ass++;
            }
        }
        //}
        fclose($handle);
    }
    //$linebyline = explode("\n", $_POST['message']);
    //$linebyline = explode("\n", $data2);
    //echo count($data2);
    $imo=0;
    $normovalue=0;
    $normovalue2=0;
    $normovalue3=0;
    for ($i=0;$i<30000;$i++){
        if ($exploded[$i][0] == ''){
            $imo = $i;
        }
    }

    for ($rowe=0;$rowe<$imo;$rowe++){
        for ($ass=0;$ass<9;$ass++){
            //$exploded = explode(";", $linebyline[$i]);
            $link = mysql_connect('localhost', 'root', '');
            if (!$link) {
                die('Not connected : ' . mysql_error());
            }

            // make foo the current db
            $db_selected = mysql_select_db('moday', $link);
            if (!$db_selected) {
                die ('Can\'t use foo : ' . mysql_error());
            }
        }
        if ($exploded[$rowe][0] !== "" || $exploded[$rowe][4] !== "" ||
            $exploded[$rowe][3] !== "" || $exploded[$rowe][1] !== ""){
            $productid = $exploded[$rowe][0];
            $price = round($exploded[$rowe][4],2);
            $disponibilita = $exploded[$rowe][3];
            $indir = "null";
            $descrizione = $exploded[$rowe][1];

            $conn = new mysqli("localhost", "root", "", "moday");

            $sql = "SELECT productid from data where productid='$productid'";
            $result = $conn->query($sql);

            if ($result->num_rows == 0) {
                mysql_query("INSERT INTO
         data(productid,price,disponibilita,indir,descrizione)
         values('$productid','$price','$disponibilita','$indir','$descrizione')")
                    or die("Query non valida: " . mysql_error());
                $normovalue++;
            }else{

                // output data of each row
                while($row = $result->fetch_assoc()) {
                    if ($row["productid"] == $productid){
                        echo "here ". $row["productid"] ." - ". $productid ."";
                        if ("$exploded[$rowe][0] == '' || $exploded[$rowe][1] ==
             '' || $exploded[$rowe][3] == '' || $exploded[$rowe][4] == '' ||
           $exploded[$rowe][2] == ''|| $exploded[$rowe][5] hh "){
                            echo $exploded[$rowe][0];
                            echo $rowe;

                        }
                        echo "
 \n";
                        $sql2 = "UPDATE data SET price='$price',
             disponibilita='$disponibilita' where productid='$productid'";
                        $normovalue2++;
                        $result2 = $conn->query($sql2);

                    }else{
                    }
                }
            }

            /*$risultato = mysql_query("INSERT INTO
              data(productid,price,disponibilita,indir,descrizione)
              values('$productid','$price','$disponibilita','$indir','$descrizione')")
              or die("Query non valida: " . mysql_error());
            */
            //echo "
 \n"
        }
    }
    $normovalue3 = $normovalue + $normovalue2;
    echo "N.1 is $normovalue 2 is $normovalue2 3 is $normovalue3";
    ?>

Body:
Put the $result into the database, as you desire:

<?php
$csv = "Chris,Garcia,1\nJohn,Doe,2\nJames,Smith,3";

foreach(explode("\n", $csv) as $key => $value) {
    $result = explode(",", $value);

    echo "Name: " . $result[0] . ", Lastname: " . $result[1] . ", ID: " . $result[2] . "\n";
}

exit();
?>


问:
Validate form ignoring Required validations
I need to submit a form in 2 different ways (possibly with 2 differents buttons).

One of them is a normal button: it validates all the inputs with all of their rules in the normal way.

The second button is a little strange: it must validate all the conditions EXCEPT for "Required" conditions. In other words, it have to ignore the Required conditions but doesn't ignore other conditions.

How can I overwrite the validation method for one of the submits?

EDIT: I use ModelState.IsValid to check if validation is correct or not. Is there any way to overwrite ModelState method to doesn't check [Required] attributes?

In short words: Is there a way that ModelState.IsValid ignore only [Required] attributes?

答:
If I were building it, I'd put a pair of radio buttons on the form to set a bool that'd determine whether I enfoced non-blank entries in the required fields. Then, on button click, if enforceReqs check that the required fields aren't blank, then follow it with a verification block that validates either data is valid OR blank. Something like:

```<code>bool enforce = radioEnfoce.Checked
string name = //set name
string phone = //set phone
string address = //set address
string email = //set email

if (enforce)
{
    if (string.IsNullOrEmpty(name) || //Keep checking all required fields.)
    {
        //some error message
        //return?
    }//if required entry is empty.

    //Repeat for all required fields.

}//if enforcing

if ( (!string.IsNullOrEmpty(phone) && !phoneIsValid())
{
    //Do stuff. Entry isn't valid.
}
//Repeat for all input data.
</code>```

This way you don't have to copy/paste the verification block, since it allows blank entries, and it can because you already checked for blanks (if you care to catch them this run).

Body:
If I were building it, I'd put a pair of radio buttons on the form to set a bool that'd determine whether I enfoced non-blank entries in the required fields. Then, on button click, if enforceReqs check that the required fields aren't blank, then follow it with a verification block that validates either data is valid OR blank. Something like:

bool enforce = radioEnfoce.Checked
string name = //set name
string phone = //set phone
string address = //set address
string email = //set email

if (enforce)
{
    if (string.IsNullOrEmpty(name) || //Keep checking all required fields.)
    {
        //some error message
        //return?
    }//if required entry is empty.

    //Repeat for all required fields.

}//if enforcing

if ( (!string.IsNullOrEmpty(phone) && !phoneIsValid())
{
    //Do stuff. Entry isn't valid.
}
//Repeat for all input data.

This way you don't have to copy/paste the verification block, since it allows blank entries, and it can because you already checked for blanks (if you care to catch them this run).


问:
Extract nodal coordinates from the deformed testsubject (abaqus-python)
I am trying to make a python script to extract the nodal coordinates from the ODB file (from abaqus).
So far i have come up with the code attached below (don't mind the extra information i put behind the #, sometimes it's just so i can keep track of what i'm doing)

The problem is that the coordinates i extract are those from the undeformed test subject. and i need the coordinates of the nodes from the deformed test subject.
Can somebody help me with how i reach this information using python code?

```<code>from abaqus import *
from abaqusConstants import *
import __main__
import section
import regionToolset
import displayGroupMdbToolset as dgm
import part
import material
import assembly
import step
import interaction
import load
import mesh
import optimization
import job
import sketch
import visualization
import xyPlot
import displayGroupOdbToolset as dgo
import connectorBehavior
import shutil
import os

import sys
from odbAccess import openOdb

for ODBname in os.listdir("D:/r0333338/Documents/MP/nodal_files_genereren/OBD"): # this is where all your ODB files are located #t hier wordt ook de odb file gekozen die geopend zal worden
    SUBname = ODBname[1:3]  # My subject ID is saved in the ODB name - this helps me create the file #woerdt er hier de 3e tot6e letter van de ODBname gepakt ?
    print 'Current File: '+ODBname #voor check welke file er gebruikt wordt #t (ZIT '.odb' hier bij in ?)
    ODBnamefull = 'D:/r0333338/Documents/MP/nodal_files_genereren/OBD/'+ODBname   # Full path to the ODB file, otherwise abaqus tries to find it in default work directory
    odb = openOdb(path=ODBnamefull)  #open the ODB file

    assembly = odb.rootAssembly     #t declareren van assembly?

    session.viewports['Viewport: 1'].odbDisplay.setFrame(step=0, frame=1)
    numNodes = 0   #t num nodes op nul zetten
    f = open("D:/r0333338/Documents/MP/nodal_files_genereren/ODBoutput/nodal.txt", "w") #indien het bestand al bestaat moet er "a" staan ipv "w"
    for name, instance in assembly.instances.items(): #t 'name' is naam van elke part van in de assembly ?
        n = len(instance.nodes) #t tellen van hoeveelheid nodes
        print 'Number of nodes of instance %s: %d' % (name, n) #moet niet in de file staan, kan eigenlijk weggelaten worden. (maar is een goede check?)
        numNodes = numNodes + n #tellen van totaal aantal nodes (globaal over alle parts) maar is eigenlijk niet nodig?
        f.write( "*Part, name=Part-1" + "\n")#moet erin staan volgens de MatchId regels
        f.write( "*Nodes" + "\n")            #moet erin staan volgens de MatchId regels

        if instance.embeddedSpace == THREE_D: #indien het 3D is
            print ' X Y Z' #moet niet in de file staan, maar is een goede check om te zien waar we zitten
            for node in instance.nodes:
                #print node #printen van node
                f.write( str(node.label) + ";" ) #schrijven van nodenummer
                f.write(str(node.coordinates[0]) + ";" + str(node.coordinates[1]) + ";" + str(node.coordinates[2]) + "\n") #schrijven van coordinaten [X;Y;Z] en enter
        else: #indien het 2D is
            print ' X Y' ';0' #moet niet in de file staan, maar is een goede check om te zien waar we zitten
            for node in instance.nodes:
                #print node #printen van node
                f.write( str(node.label) + ";" )
                f.write(str(node.coordinates[0]) + ";" + str(node.coordinates[1]) + ";" + str(node.coordinates[2]) + "\n") #schrijven van coordinaten [X;Y;Z] en enter
        f.write( "*End Part" ) #moet erin staan volgens de MatchId regels
    f.close()
</code>```

答:
get the displacement field:

```<code> u=odb.steps['Step-1'].frames[-1].fieldOutputs['U']
</code>```

then u.values is a list of all nodal values:

```<code> u.values[i].data -> array of (ux,uy,uz)
 u.values[i].nodeLabel  -> node label
</code>```

then you grab the original position like this:

```<code> instance.getNodeFromLabel(u.values[i].nodeLabel).coordinates
</code>```

You can also directly get the deformed coordinate as a field output, but you need to request COORD output when you run the analysis.

Body:
I am trying to make a python script to extract the nodal coordinates from the ODB file (from abaqus).
So far i have come up with the code attached below (don't mind the extra information i put behind the #, sometimes it's just so i can keep track of what i'm doing)

The problem is that the coordinates i extract are those from the undeformed test subject. and i need the coordinates of the nodes from the deformed test subject.
Can somebody help me with how i reach this information using python code?

from abaqus import *
from abaqusConstants import *
import __main__
import section
import regionToolset
import displayGroupMdbToolset as dgm
import part
import material
import assembly
import step
import interaction
import load
import mesh
import optimization
import job
import sketch
import visualization
import xyPlot
import displayGroupOdbToolset as dgo
import connectorBehavior
import shutil
import os

import sys
from odbAccess import openOdb

for ODBname in os.listdir("D:/r0333338/Documents/MP/nodal_files_genereren/OBD"): # this is where all your ODB files are located #t hier wordt ook de odb file gekozen die geopend zal worden
    SUBname = ODBname[1:3]  # My subject ID is saved in the ODB name - this helps me create the file #woerdt er hier de 3e tot6e letter van de ODBname gepakt ?
    print 'Current File: '+ODBname #voor check welke file er gebruikt wordt #t (ZIT '.odb' hier bij in ?)
    ODBnamefull = 'D:/r0333338/Documents/MP/nodal_files_genereren/OBD/'+ODBname   # Full path to the ODB file, otherwise abaqus tries to find it in default work directory
    odb = openOdb(path=ODBnamefull)  #open the ODB file

    assembly = odb.rootAssembly     #t declareren van assembly?

    session.viewports['Viewport: 1'].odbDisplay.setFrame(step=0, frame=1)
    numNodes = 0   #t num nodes op nul zetten
    f = open("D:/r0333338/Documents/MP/nodal_files_genereren/ODBoutput/nodal.txt", "w") #indien het bestand al bestaat moet er "a" staan ipv "w"
    for name, instance in assembly.instances.items(): #t 'name' is naam van elke part van in de assembly ?
        n = len(instance.nodes) #t tellen van hoeveelheid nodes
        print 'Number of nodes of instance %s: %d' % (name, n) #moet niet in de file staan, kan eigenlijk weggelaten worden. (maar is een goede check?)
        numNodes = numNodes + n #tellen van totaal aantal nodes (globaal over alle parts) maar is eigenlijk niet nodig?
        f.write( "*Part, name=Part-1" + "\n")#moet erin staan volgens de MatchId regels
        f.write( "*Nodes" + "\n")            #moet erin staan volgens de MatchId regels

        if instance.embeddedSpace == THREE_D: #indien het 3D is
            print ' X Y Z' #moet niet in de file staan, maar is een goede check om te zien waar we zitten
            for node in instance.nodes:
                #print node #printen van node
                f.write( str(node.label) + ";" ) #schrijven van nodenummer
                f.write(str(node.coordinates[0]) + ";" + str(node.coordinates[1]) + ";" + str(node.coordinates[2]) + "\n") #schrijven van coordinaten [X;Y;Z] en enter
        else: #indien het 2D is
            print ' X Y' ';0' #moet niet in de file staan, maar is een goede check om te zien waar we zitten
            for node in instance.nodes:
                #print node #printen van node
                f.write( str(node.label) + ";" )
                f.write(str(node.coordinates[0]) + ";" + str(node.coordinates[1]) + ";" + str(node.coordinates[2]) + "\n") #schrijven van coordinaten [X;Y;Z] en enter
        f.write( "*End Part" ) #moet erin staan volgens de MatchId regels
    f.close()

Body:
get the displacement field:

 u=odb.steps['Step-1'].frames[-1].fieldOutputs['U']

then u.values is a list of all nodal values:

 u.values[i].data -> array of (ux,uy,uz)
 u.values[i].nodeLabel  -> node label

then you grab the original position like this:

 instance.getNodeFromLabel(u.values[i].nodeLabel).coordinates

You can also directly get the deformed coordinate as a field output, but you need to request COORD output when you run the analysis.


问:
How to check if a variable has characters that are not allowed in?
I am writing a password program where it will display a score if certain requirements are met. But I am stuck on how to check if some characters are not allowed. If they are not allowed it should notify the reader.
Here is my code:

```<code>user_password = input("\nEnter your password:")
user_score = 0
user_length = len(user_password)
symbols = "$%^&*()_-+="

if len(user_password)>24:
    print("Your password is too long! It must be between 6 and 24")
elif len(user_password)<6:
    print("Your password is too short! It must be between 6 and 24")
elif len(user_password) >=6 and len(user_password) <= 24:
    lower = sum([int(c.islower()) for c in user_password])
    if lower > 0:
            user_score = user_score + 5
    upper = sum([int(c.isupper()) for c in user_password])
    if upper > 0:
            user_score = user_score + 5
    integer = sum([int(c.isdigit()) for c  in user_password])
    if integer > 0:
            user_score = user_score + 5
    for c in symbols:
            if c in user_password:
                    user_score = user_score + 5
    for c in user_password:
            if c not in symbols:
                    print("Some symbols you entered are not allowed")
                    break
</code>```

I want it so that the program will end if a symbol is wrongly entered it. However when a wrong symbol is entered it displays the message the amount of times the symbol is entered. Any help will be appreciated.

答:
Change if c not in symbols: to if c in symbols:

```<code>user_password = input("\nEnter your password:")
user_score = 0
user_length = len(user_password)
symbols = "$%^&*()_-+="

if len(user_password)>24:
    print("Your password is too long! It must be between 6 and 24")
elif len(user_password)<6:
    print("Your password is too short! It must be between 6 and 24")
elif len(user_password) >=6 and len(user_password) <= 24:
    lower = sum([int(c.islower()) for c in user_password])
    if lower > 0:
            user_score = user_score + 5
    upper = sum([int(c.isupper()) for c in user_password])
    if upper > 0:
            user_score = user_score + 5
    integer = sum([int(c.isdigit()) for c  in user_password])
    if integer > 0:
            user_score = user_score + 5
    for c in symbols:
            if c in user_password:
                    user_score = user_score + 5
    for c in user_password:
            if c in symbols:
                    print("Some symbols you entered are not allowed")
                    break
</code>```

Hope this helps and welcome to SO!

Body:
I am writing a password program where it will display a score if certain requirements are met. But I am stuck on how to check if some characters are not allowed. If they are not allowed it should notify the reader.
Here is my code:

user_password = input("\nEnter your password:")
user_score = 0
user_length = len(user_password)
symbols = "$%^&*()_-+="

if len(user_password)>24:
    print("Your password is too long! It must be between 6 and 24")
elif len(user_password)<6:
    print("Your password is too short! It must be between 6 and 24")
elif len(user_password) >=6 and len(user_password) <= 24:
    lower = sum([int(c.islower()) for c in user_password])
    if lower > 0:
            user_score = user_score + 5
    upper = sum([int(c.isupper()) for c in user_password])
    if upper > 0:
            user_score = user_score + 5
    integer = sum([int(c.isdigit()) for c  in user_password])
    if integer > 0:
            user_score = user_score + 5
    for c in symbols:
            if c in user_password:
                    user_score = user_score + 5
    for c in user_password:
            if c not in symbols:
                    print("Some symbols you entered are not allowed")
                    break

I want it so that the program will end if a symbol is wrongly entered it. However when a wrong symbol is entered it displays the message the amount of times the symbol is entered. Any help will be appreciated.

Body:
Change if c not in symbols: to if c in symbols:

user_password = input("\nEnter your password:")
user_score = 0
user_length = len(user_password)
symbols = "$%^&*()_-+="

if len(user_password)>24:
    print("Your password is too long! It must be between 6 and 24")
elif len(user_password)<6:
    print("Your password is too short! It must be between 6 and 24")
elif len(user_password) >=6 and len(user_password) <= 24:
    lower = sum([int(c.islower()) for c in user_password])
    if lower > 0:
            user_score = user_score + 5
    upper = sum([int(c.isupper()) for c in user_password])
    if upper > 0:
            user_score = user_score + 5
    integer = sum([int(c.isdigit()) for c  in user_password])
    if integer > 0:
            user_score = user_score + 5
    for c in symbols:
            if c in user_password:
                    user_score = user_score + 5
    for c in user_password:
            if c in symbols:
                    print("Some symbols you entered are not allowed")
                    break

Hope this helps and welcome to SO!


问:
Firebase quick start throws NoClassDefFoundError
I added the app to Firebase console and added google json file to app folder.
Then when I try to launch the app it crashes with the following message.

Thanks in Advance.

Error:

07-27 13:18:21.000 26362-26362/? E/AndroidRuntime: FATAL EXCEPTION:
  main
                                                     Process: com.google.samples.quickstart.config, PID: 26362
                                                     java.lang.NoClassDefFoundError: Failed resolution of:
  Lcom/google/android/gms/R$string;
                                                         at com.google.android.gms.common.internal.zzby.(Unknown Source)
                                                         at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                                                         at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                         at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown
  Source)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown
  Source)
                                                         at android.app.ActivityThread.installProvider(ActivityThread.java:5855)
                                                         at android.app.ActivityThread.installContentProviders(ActivityThread.java:5447)
                                                         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5386)
                                                         at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                      Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.google.android.gms.R$string" on path: DexPathList[[zip file
  "/data/app/com.google.samples.quickstart.config-1/base.apk", zip file
  "/data/app/com.google.samples.quickstart.config-1/split_lib_dependencies_apk.apk"],nativeLibraryDirectories=[/data/app/com.google.samples.quickstart.config-1/lib/arm64,
  /system/lib64, /vendor/lib64]]
                                                         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                                                         at com.google.android.gms.common.internal.zzby.(Unknown Source)
                                                         at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                                                         at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                         at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown
  Source)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown
  Source)
                                                         at android.app.ActivityThread.installProvider(ActivityThread.java:5855)
                                                         at android.app.ActivityThread.installContentProviders(ActivityThread.java:5447)
                                                         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5386)
                                                         at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Gradle

```<code>apply plugin: 'com.android.application'
check.dependsOn 'assembleDebugAndroidTest'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.google.samples.quickstart.config"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:25.4.0'
}

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

    compile 'com.google.firebase:firebase-config:11.0.1'

    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
}

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

Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.samples.quickstart.config" >

    <application
        android:allowBackup="true"
        android:name="android.support.multidex.MultiDexApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答: It works for me in Android Studio 3 Beta 5, but not in Android Studio 3 and preview 3.1</p>

Body:
I added the app to Firebase console and added google json file to app folder.
Then when I try to launch the app it crashes with the following message.

Thanks in Advance.

Error:

07-27 13:18:21.000 26362-26362/? E/AndroidRuntime: FATAL EXCEPTION:
  main
                                                     Process: com.google.samples.quickstart.config, PID: 26362
                                                     java.lang.NoClassDefFoundError: Failed resolution of:
  Lcom/google/android/gms/R$string;
                                                         at com.google.android.gms.common.internal.zzby.(Unknown Source)
                                                         at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                                                         at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                         at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown
  Source)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown
  Source)
                                                         at android.app.ActivityThread.installProvider(ActivityThread.java:5855)
                                                         at android.app.ActivityThread.installContentProviders(ActivityThread.java:5447)
                                                         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5386)
                                                         at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                      Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.google.android.gms.R$string" on path: DexPathList[[zip file
  "/data/app/com.google.samples.quickstart.config-1/base.apk", zip file
  "/data/app/com.google.samples.quickstart.config-1/split_lib_dependencies_apk.apk"],nativeLibraryDirectories=[/data/app/com.google.samples.quickstart.config-1/lib/arm64,
  /system/lib64, /vendor/lib64]]
                                                         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                                                         at com.google.android.gms.common.internal.zzby.(Unknown Source)
                                                         at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                                                         at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                         at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown
  Source)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown
  Source)
                                                         at android.app.ActivityThread.installProvider(ActivityThread.java:5855)
                                                         at android.app.ActivityThread.installContentProviders(ActivityThread.java:5447)
                                                         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5386)
                                                         at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Gradle

apply plugin: 'com.android.application'
check.dependsOn 'assembleDebugAndroidTest'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.google.samples.quickstart.config"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:25.4.0'
}

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

    compile 'com.google.firebase:firebase-config:11.0.1'

    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
}

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

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.samples.quickstart.config" >

    <application
        android:allowBackup="true"
        android:name="android.support.multidex.MultiDexApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
Retrieving Dictionary Item value based on wildcard - VBA Excel
At the moment I am running over a dictionary so that I can fill missing values in a table based on the stored keys within it. The problem is that my table has more values (keys) than the ones stored in the dictionary. In some cases the information in my table is similar to the a certain key in the Dictionary and i was wondering if it is possible to use a wildcard to retrieve the items. Example below:

Example records in dictionary:

Mercedes (key) car   (item)

Kawasaki (key) motor (item)

Lets assume my table has the following entry:

Merc (key) but is missing the item, which should be "car" in this case.

Is it possible to make this happen? I am sorry if the example is bad, but I hope any of you can help me.

I found several articles on the topic:

Wildcard search of dictionary

How to search for a part of a dictionary key? - VB.Net

Thank you in advance!

答:
Left field answer: Don't use a Dictionary, and don't use like because the approach is just too slow and doesn't scale well. Try one of these instead:

Use the Advanced Filter, which accepts wildcards. You'll have to dump the data into Excel. But then I assume the data is already in the grid somewhere. But the Advanced Filter is fast, and I actually use it behind the scenes in a PivotTable Filtering app I've built that lets users quicky filter PivotTables on multiple wildcards and complicated exclusions.

Use a Binary Search algorithm on sorted data. I often find it
easiest to do this in Excel by dumping the two lists to Excel,
sorting them there, and then using the Double VLOOKUP trick I talk
about here:
http://dailydoseofexcel.com/archives/2015/04/23/how-much-faster-is-the-double-vlookup-trick/

Charles Williams has a great post here that might be useful, and should be read regardless:
https://fastexcel.wordpress.com/2012/07/10/comparing-two-lists-vba-udf-shootout-between-linear-search-binary-search-collection-and-dictionary/


问:
Consume a std::future by connecting a QObject
I have some existing code that uses std::future/std::promise that I'd like to integrate with a Qt GUI cleanly.

Ideally, one could just:

```<code>std::future<int> future{do_something()};
connect(future, this, &MyObject::resultOfFuture);
</code>```

and then implement resultOfFuture as a slot that gets one argument: the int value that came out of the std::future<int>. I've added this suggestion as a comment on QTBUG-50676.  I like this best because most of my future/promises are not concurrent anyway, so I'd like to avoid firing up a thread just to wait on them. Also, type inference could then work between the future and the slot's parameter.

But it seems to me that this shouldn't be hard to implement using a wrapper Qt object (e.g., a version of QFutureWatcher that takes a std::future<int>). The two issues with a wrapper are:

the wrapper will have to be concrete in its result type.

the watcher would have to be concurrent in a thread?

Is there a best-practice to implement this sort of connection? Is there another way that can hook into the Qt main loop and avoid thread creation?

答:
std::future is missing continuations.  The only way to turn the result of a std::future asynchronously into a function call delivering the result is to launch a thread watching it, and if you want to avoid busy-waiting you need one such thread per std::future, as there is no way to lazy-wait on multiple futures at once.

There are plans to create a future with continuation (a then operation), but they are not in C++ as of c++17 let alone c++11.

You could write your own system of future/promise that mimics the interface of std::future and std::promise that does support continuations, or find a library that already did that.

A busy-wait solution that regularly checked if the future was ready could avoid launching a new thread.

In any case, std::experimental::then would make your problem trivial.

```<code>future.then( [some_state](auto future){
  try {
    auto x = future.get();
    // send message with x
  } catch( ... ) {
    // deal with exception
  }
} );
</code>```

you can write your own std::experimetnal::future or find an implementation to use yourself, but this functionality cannot be provided without using an extra thread with a std::future.

Body:
I have some existing code that uses std::future/std::promise that I'd like to integrate with a Qt GUI cleanly.

Ideally, one could just:

std::future<int> future{do_something()};
connect(future, this, &MyObject::resultOfFuture);

and then implement resultOfFuture as a slot that gets one argument: the int value that came out of the std::future<int>. I've added this suggestion as a comment on QTBUG-50676.  I like this best because most of my future/promises are not concurrent anyway, so I'd like to avoid firing up a thread just to wait on them. Also, type inference could then work between the future and the slot's parameter.

But it seems to me that this shouldn't be hard to implement using a wrapper Qt object (e.g., a version of QFutureWatcher that takes a std::future<int>). The two issues with a wrapper are:

the wrapper will have to be concrete in its result type.

the watcher would have to be concurrent in a thread?

Is there a best-practice to implement this sort of connection? Is there another way that can hook into the Qt main loop and avoid thread creation?

Body:
std::future is missing continuations.  The only way to turn the result of a std::future asynchronously into a function call delivering the result is to launch a thread watching it, and if you want to avoid busy-waiting you need one such thread per std::future, as there is no way to lazy-wait on multiple futures at once.

There are plans to create a future with continuation (a then operation), but they are not in C++ as of c++17 let alone c++11.

You could write your own system of future/promise that mimics the interface of std::future and std::promise that does support continuations, or find a library that already did that.

A busy-wait solution that regularly checked if the future was ready could avoid launching a new thread.

In any case, std::experimental::then would make your problem trivial.

future.then( [some_state](auto future){
  try {
    auto x = future.get();
    // send message with x
  } catch( ... ) {
    // deal with exception
  }
} );

you can write your own std::experimetnal::future or find an implementation to use yourself, but this functionality cannot be provided without using an extra thread with a std::future.


问:
UI best practice question: Cancel button or Cancel link
I have a discussion with a colleague about what the "web standard" is for canceling in an form. In our discussion we have a "change password" page as example. We have a designed "send" button and "cancel" button. Both the same design.

He claims that in web standard a cancel button is no longer a button but a link transferring the user to another page. In my opinion, for those pages including a cancel button it actually is a cancel button which either resets the form and/or send the user to the prevision page.

Who is correct? Link or button... or both? And why? Any links to where this kind of standard is decided?

Br,

Paul Peelen

EDIT
I guess the answer with most votes will be the "correct answer"?

答:
I would say a link and button are exactly the same thing. A button can be a link and text can be a link.

Where the difference lies is between the focus of the default action and it's counterpart.

The default option should always be in focus and the counter option should always be relatively close by.

By in focus I mean the "Send" button could be bigger or brighter as long as its more noticeable then the "cancel" button.

Your friend probably thinks you should use a text link for this reason as it does follow this method.   But a CSS button can be colorized to be less prominent in the same way.


问:
Batch file to copy a single folder - not just the contents
I am struggling to create a batch file that I can use in any folder, which will copy the current folder and all its contents to another location. The objective is to allow me to make very quick backups of any current folder by running the batch file. Batch files are new to me, but programming isn't. Here is my code.

```<code>@echo off
title Copy This Directory
:: get current directory
 set startdir=%cd%
 echo.startdir = %startdir%
:: copy the test folder
 xcopy "%startdir%" "F:\Temp Backup\" /s /y
 pause
</code>```

This copies the files and folders that are inside the source folder to the new destination, but I want to copy the folder itself together with its contents. ie if the batch file is in a folder called "FromFolder", I want "FromFolder" to appear as a folder in "F:\Temp Backup\" and all its contents in "F:\Temp Backup\FromFolder". I've found lots of info about copying files, but nothing about copying a single directory. I can copy a single file, but when I use the same code and change the file name to a folder name, it copies the folder's contents and not the folder itself. Could someone let me know what I have missed please.

答:
I decided to go with creating a new folder at the destination and as a second step copying the contents to it.  Here's what I did.</p>

```<code>@setlocal enableextensions enabledelayedexpansion
@echo off
title Copy This Directory
:: get current directory
@echo off
set startdir=%cd%
set temp=%startdir%
set folder=
:loop
if not "x%temp:~-1%"=="x\" (
    set folder=!temp:~-1!!folder!
    set temp=!temp:~0,-1!
    goto :loop
)
echo.startdir = %startdir%
echo.folder   = %folder%
:: Create new folder if needed
md "F:\Temp Backup\%folder%"
:: copy the contents
xcopy "%startdir%\*.*" "F:\Temp Backup\%folder%\" /s /y
pause
endlocal && set folder=%folder%
</code>```

Body:
I am struggling to create a batch file that I can use in any folder, which will copy the current folder and all its contents to another location. The objective is to allow me to make very quick backups of any current folder by running the batch file. Batch files are new to me, but programming isn't. Here is my code.

@echo off
title Copy This Directory
:: get current directory
 set startdir=%cd%
 echo.startdir = %startdir%
:: copy the test folder
 xcopy "%startdir%" "F:\Temp Backup\" /s /y
 pause

This copies the files and folders that are inside the source folder to the new destination, but I want to copy the folder itself together with its contents. ie if the batch file is in a folder called "FromFolder", I want "FromFolder" to appear as a folder in "F:\Temp Backup\" and all its contents in "F:\Temp Backup\FromFolder". I've found lots of info about copying files, but nothing about copying a single directory. I can copy a single file, but when I use the same code and change the file name to a folder name, it copies the folder's contents and not the folder itself. Could someone let me know what I have missed please.

Body:
I decided to go with creating a new folder at the destination and as a second step copying the contents to it.  Here's what I did.

@setlocal enableextensions enabledelayedexpansion
@echo off
title Copy This Directory
:: get current directory
@echo off
set startdir=%cd%
set temp=%startdir%
set folder=
:loop
if not "x%temp:~-1%"=="x\" (
    set folder=!temp:~-1!!folder!
    set temp=!temp:~0,-1!
    goto :loop
)
echo.startdir = %startdir%
echo.folder   = %folder%
:: Create new folder if needed
md "F:\Temp Backup\%folder%"
:: copy the contents
xcopy "%startdir%\*.*" "F:\Temp Backup\%folder%\" /s /y
pause
endlocal && set folder=%folder%