问:
Can't find user by username or email from database in bundle
I am currently working on two website with Symfony, which has some of each database in common. We created a bundle to contain the database of the main website, and the second one has its own database. Each of the websites have a set of users in their database (not the same), and FOSUserBundle is correctly set up.

I'm trying to create a command that migrates some users of the second website to the main one, and for every user, I want to check if it already exists in the database.

If my database was local, I'd probably do something like $email_exist = $userManager->findUserByEmail($email);, but I don't have acces to the userManager of the other website.
I tried:

```<code>$emBug->getRepository('BugTrackerModelBundle:User')->findByEmail($email)
$emBug->getRepository('BugTrackerModelBundle:User')->findBy(array('email' => $email))
</code>```

I even created a custom function in my repository that did the same thing and everytime I get the error Entity 'BugTracker\ModelBundle\Entity\User' has no field 'email'. You can therefore not call 'findByEmail' on the entities' repository.

I am absolutly positive that I do have an email and a username field in my database (I tried both). I also tried with id instead of email and it worked so the issue is really with that field in particular.

I'm using FOSUserBundle, and my user class extends BaseUser (that's where the username and email come from)

Is there any (simple) way to do this? Without having to add a new user provider.

Please don't tell me "you shouldn't do that" or that I should only have 1 database, it is not usefull and I can't change it anyway.

My user entity:

```<code><?php

namespace BugTracker\ModelBundle\Entity;

use BugTracker\ModelBundle\Entity\Project\ProjectToUser;
use BugTracker\ModelBundle\Entity\Authority\AuthorityToUser;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File as BaseFile;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * Class User
 *
 * @ORM\Table(name="user")
 * @UniqueEntity(fields={"email"}, message="A user with same email already exists")
 * @ORM\Entity(repositoryClass="BugTracker\ModelBundle\Repository\UserRepository")
 * @Vich\Uploadable
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var bool
     * @ORM\Column(type="boolean")
     */
    protected $deleted;

    /**
     * @var bool
     * @ORM\Column(name="notify", type="boolean", options={"default" : 1}, nullable=true)
     */
    protected $notify;

    /**
     * @var string
     * @ORM\Column(name="first_name", type="string", length=255, nullable=true)
     */
    protected $firstName;

    /**
     * @var string
     * @ORM\Column(name="last_name", type="string", length=255, nullable=true)
     */
    protected $lastName;

    /**
     * @var string
     * @ORM\Column(name="job_title", type="string", length=255, nullable=true)
     */
    protected $jobTitle;

    /**
     * @var BaseFile|UploadedFile
     *
     * @Vich\UploadableField(mapping="user_image", fileNameProperty="image")
     */
    protected $userImage;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", nullable=true)
     */
    protected $image;

    /**
     * @var Company
     * @ORM\ManyToOne(targetEntity="BugTracker\ModelBundle\Entity\Company", cascade={"persist"})
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $company;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Project", mappedBy="createdBy")
     */
    protected $projects;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Project\ProjectToUser", mappedBy="user", cascade={"all"})
     */
    protected $assignedProjects;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Authority\AuthorityToUser", mappedBy="user", cascade={"all"})
     */
    protected $assignedAuthorities;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    protected $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     */
    protected $updatedAt;

    /**
     * @var Country
     * @ORM\ManyToOne(targetEntity="BugTracker\ModelBundle\Entity\Country", cascade={"persist"})
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $country;

    /**
     * @var string
     *
     * @ORM\Column(name="time_zone", type="string", nullable=true)
     */
    protected $timeZone;

    /**
     * @var string
     *
     * @ORM\Column(name="user_role", type="string", nullable=false)
     */
    protected $userRole;

    /**
     * User constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->enabled = true;
        $this->deleted = false;
        $this->notify = true;

        $this->createdAt = new \DateTime();
        $this->updatedAt = new \DateTime();

        $this->projects = new ArrayCollection();
        $this->assignedProjects = new ArrayCollection();
        $this->assignedAuthorities = new ArrayCollection();
    }
}
</code>```

the user entity metadata :

```<code>{
"name":"BugTracker\\ModelBundle\\Entity\\User",
"namespace":"BugTracker\\ModelBundle\\Entity",
"rootEntityName":"BugTracker\\ModelBundle\\Entity\\User",
"customGeneratorDefinition":null,
"customRepositoryClassName":"BugTracker\\ModelBundle\\Repository\\UserRepository",
"isMappedSuperclass":false,
"isEmbeddedClass":false,
"parentClasses":[

],
"subClasses":[

],
"embeddedClasses":[

],
"namedQueries":[

],
"namedNativeQueries":[

],
"sqlResultSetMappings":[

],
"identifier":[
    "id"
],
"inheritanceType":1,
"generatorType":4,
"fieldMappings":{
    "id":{
        "fieldName":"id",
        "type":"integer",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "id":true,
        "columnName":"id"
    },
    "deleted":{
        "fieldName":"deleted",
        "type":"boolean",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "columnName":"deleted"
    },
    "notify":{
        "fieldName":"notify",
        "type":"boolean",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "options":{
            "default":1
        },
        "columnName":"notify"
    },
    "firstName":{
        "fieldName":"firstName",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"first_name"
    },
    "lastName":{
        "fieldName":"lastName",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"last_name"
    },
    "jobTitle":{
        "fieldName":"jobTitle",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"job_title"
    },
    "image":{
        "fieldName":"image",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"image"
    },
    "createdAt":{
        "fieldName":"createdAt",
        "type":"datetime",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"created_at"
    },
    "updatedAt":{
        "fieldName":"updatedAt",
        "type":"datetime",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"updated_at"
    },
    "timeZone":{
        "fieldName":"timeZone",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"time_zone"
    },
    "userRole":{
        "fieldName":"userRole",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "columnName":"user_role"
    }
},
"fieldNames":{
    "id":"id",
    "deleted":"deleted",
    "notify":"notify",
    "first_name":"firstName",
    "last_name":"lastName",
    "job_title":"jobTitle",
    "image":"image",
    "created_at":"createdAt",
    "updated_at":"updatedAt",
    "time_zone":"timeZone",
    "user_role":"userRole"
},
"columnNames":{
    "id":"id",
    "deleted":"deleted",
    "notify":"notify",
    "firstName":"first_name",
    "lastName":"last_name",
    "jobTitle":"job_title",
    "image":"image",
    "createdAt":"created_at",
    "updatedAt":"updated_at",
    "timeZone":"time_zone",
    "userRole":"user_role"
},
"discriminatorValue":null,
"discriminatorMap":[

],
"discriminatorColumn":null,
"table":{
    "name":"user"
},
"lifecycleCallbacks":[

],
"entityListeners":[

],
"associationMappings":{
    "company":{
        "fieldName":"company",
        "joinColumns":[
            {
                "name":"company_id",
                "unique":false,
                "nullable":true,
                "onDelete":null,
                "columnDefinition":null,
                "referencedColumnName":"id"
            }
        ],
        "cascade":[
            "persist"
        ],
        "inversedBy":null,
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Company",
        "fetch":2,
        "type":2,
        "mappedBy":null,
        "isOwningSide":true,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":false,
        "isCascadePersist":true,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false,
        "sourceToTargetKeyColumns":{
            "company_id":"id"
        },
        "joinColumnFieldNames":{
            "company_id":"company_id"
        },
        "targetToSourceKeyColumns":{
            "id":"company_id"
        },
        "orphanRemoval":false
    },
    "projects":{
        "fieldName":"projects",
        "mappedBy":"createdBy",
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Project",
        "cascade":[

        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":false,
        "isCascadePersist":false,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false
    },
    "assignedProjects":{
        "fieldName":"assignedProjects",
        "mappedBy":"user",
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Project\\ProjectToUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    },
    "assignedAuthorities":{
        "fieldName":"assignedAuthorities",
        "mappedBy":"user",
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Authority\\AuthorityToUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    },
    "country":{
        "fieldName":"country",
        "joinColumns":[
            {
                "name":"country_id",
                "unique":false,
                "nullable":true,
                "onDelete":null,
                "columnDefinition":null,
                "referencedColumnName":"id"
            }
        ],
        "cascade":[
            "persist"
        ],
        "inversedBy":null,
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Country",
        "fetch":2,
        "type":2,
        "mappedBy":null,
        "isOwningSide":true,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":false,
        "isCascadePersist":true,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false,
        "sourceToTargetKeyColumns":{
            "country_id":"id"
        },
        "joinColumnFieldNames":{
            "country_id":"country_id"
        },
        "targetToSourceKeyColumns":{
            "id":"country_id"
        },
        "orphanRemoval":false
    },
    "groupUsers":{
        "fieldName":"groupUsers",
        "mappedBy":"user",
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Group\\GroupUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    }
},
"isIdentifierComposite":false,
"containsForeignIdentifier":false,
"idGenerator":{

},
"sequenceGeneratorDefinition":null,
"tableGeneratorDefinition":null,
"changeTrackingPolicy":1,
"isVersioned":null,
"versionField":null,
"cache":null,
"reflClass":{
    "name":"BugTracker\\ModelBundle\\Entity\\User"
},
"isReadOnly":false,
"reflFields":{
    "id":{
        "name":"id",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "deleted":{
        "name":"deleted",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "notify":{
        "name":"notify",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "firstName":{
        "name":"firstName",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "lastName":{
        "name":"lastName",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "jobTitle":{
        "name":"jobTitle",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "image":{
        "name":"image",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "createdAt":{
        "name":"createdAt",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "updatedAt":{
        "name":"updatedAt",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "timeZone":{
        "name":"timeZone",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "userRole":{
        "name":"userRole",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "company":{
        "name":"company",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "projects":{
        "name":"projects",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "assignedProjects":{
        "name":"assignedProjects",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "assignedAuthorities":{
        "name":"assignedAuthorities",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "country":{
        "name":"country",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "groupUsers":{
        "name":"groupUsers",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    }
}
}
</code>```

doctrine configuration on the second website

```<code>doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                mapping_types:
                     enum: string
                driver: pdo_mysql
                host: '%database_host%'
                port: '%database_port%'
                dbname: '%database_name%'
                user: '%database_user%'
                password: '%database_password%'
                charset: UTF8
            bugtracker:
                mapping_types:
                     enum: string
                driver: pdo_mysql
                host: '%database_host_bugtracker%'
                port: '%database_port_bugtracker%'
                dbname: '%database_name_bugtracker%'
                user: '%database_user_bugtracker%'
                password: '%database_password_bugtracker%'
                charset: UTF8
</code>```

答:
What if you use username instead of email, because according to your posted entity email property exist in parent class FOS\UserBundle\Model\User and your child class sets email like setEmail(){....} in this function it also sets the same value to username parent::setUsername($email); so i guess you can get the user by using username property

```<code>$emBug->getRepository('BugTrackerModelBundle:User')->findBy(array('username' => $email));
</code>```

Or eles define email property in your class like you defined username property

```<code>/**
 * @var string
 * @ORM\Column(type="string" definition....)
 */
protected $email;
</code>```

Body:
I am currently working on two website with Symfony, which has some of each database in common. We created a bundle to contain the database of the main website, and the second one has its own database. Each of the websites have a set of users in their database (not the same), and FOSUserBundle is correctly set up.

I'm trying to create a command that migrates some users of the second website to the main one, and for every user, I want to check if it already exists in the database.

If my database was local, I'd probably do something like $email_exist = $userManager->findUserByEmail($email);, but I don't have acces to the userManager of the other website.
I tried:

$emBug->getRepository('BugTrackerModelBundle:User')->findByEmail($email)
$emBug->getRepository('BugTrackerModelBundle:User')->findBy(array('email' => $email))

I even created a custom function in my repository that did the same thing and everytime I get the error Entity 'BugTracker\ModelBundle\Entity\User' has no field 'email'. You can therefore not call 'findByEmail' on the entities' repository.

I am absolutly positive that I do have an email and a username field in my database (I tried both). I also tried with id instead of email and it worked so the issue is really with that field in particular.

I'm using FOSUserBundle, and my user class extends BaseUser (that's where the username and email come from)

Is there any (simple) way to do this? Without having to add a new user provider.

Please don't tell me "you shouldn't do that" or that I should only have 1 database, it is not usefull and I can't change it anyway.

My user entity:

<?php

namespace BugTracker\ModelBundle\Entity;

use BugTracker\ModelBundle\Entity\Project\ProjectToUser;
use BugTracker\ModelBundle\Entity\Authority\AuthorityToUser;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File as BaseFile;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * Class User
 *
 * @ORM\Table(name="user")
 * @UniqueEntity(fields={"email"}, message="A user with same email already exists")
 * @ORM\Entity(repositoryClass="BugTracker\ModelBundle\Repository\UserRepository")
 * @Vich\Uploadable
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var bool
     * @ORM\Column(type="boolean")
     */
    protected $deleted;

    /**
     * @var bool
     * @ORM\Column(name="notify", type="boolean", options={"default" : 1}, nullable=true)
     */
    protected $notify;

    /**
     * @var string
     * @ORM\Column(name="first_name", type="string", length=255, nullable=true)
     */
    protected $firstName;

    /**
     * @var string
     * @ORM\Column(name="last_name", type="string", length=255, nullable=true)
     */
    protected $lastName;

    /**
     * @var string
     * @ORM\Column(name="job_title", type="string", length=255, nullable=true)
     */
    protected $jobTitle;

    /**
     * @var BaseFile|UploadedFile
     *
     * @Vich\UploadableField(mapping="user_image", fileNameProperty="image")
     */
    protected $userImage;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", nullable=true)
     */
    protected $image;

    /**
     * @var Company
     * @ORM\ManyToOne(targetEntity="BugTracker\ModelBundle\Entity\Company", cascade={"persist"})
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $company;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Project", mappedBy="createdBy")
     */
    protected $projects;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Project\ProjectToUser", mappedBy="user", cascade={"all"})
     */
    protected $assignedProjects;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="BugTracker\ModelBundle\Entity\Authority\AuthorityToUser", mappedBy="user", cascade={"all"})
     */
    protected $assignedAuthorities;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    protected $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     */
    protected $updatedAt;

    /**
     * @var Country
     * @ORM\ManyToOne(targetEntity="BugTracker\ModelBundle\Entity\Country", cascade={"persist"})
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    protected $country;

    /**
     * @var string
     *
     * @ORM\Column(name="time_zone", type="string", nullable=true)
     */
    protected $timeZone;

    /**
     * @var string
     *
     * @ORM\Column(name="user_role", type="string", nullable=false)
     */
    protected $userRole;

    /**
     * User constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->enabled = true;
        $this->deleted = false;
        $this->notify = true;

        $this->createdAt = new \DateTime();
        $this->updatedAt = new \DateTime();

        $this->projects = new ArrayCollection();
        $this->assignedProjects = new ArrayCollection();
        $this->assignedAuthorities = new ArrayCollection();
    }
}

the user entity metadata :

{
"name":"BugTracker\\ModelBundle\\Entity\\User",
"namespace":"BugTracker\\ModelBundle\\Entity",
"rootEntityName":"BugTracker\\ModelBundle\\Entity\\User",
"customGeneratorDefinition":null,
"customRepositoryClassName":"BugTracker\\ModelBundle\\Repository\\UserRepository",
"isMappedSuperclass":false,
"isEmbeddedClass":false,
"parentClasses":[

],
"subClasses":[

],
"embeddedClasses":[

],
"namedQueries":[

],
"namedNativeQueries":[

],
"sqlResultSetMappings":[

],
"identifier":[
    "id"
],
"inheritanceType":1,
"generatorType":4,
"fieldMappings":{
    "id":{
        "fieldName":"id",
        "type":"integer",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "id":true,
        "columnName":"id"
    },
    "deleted":{
        "fieldName":"deleted",
        "type":"boolean",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "columnName":"deleted"
    },
    "notify":{
        "fieldName":"notify",
        "type":"boolean",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "options":{
            "default":1
        },
        "columnName":"notify"
    },
    "firstName":{
        "fieldName":"firstName",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"first_name"
    },
    "lastName":{
        "fieldName":"lastName",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"last_name"
    },
    "jobTitle":{
        "fieldName":"jobTitle",
        "type":"string",
        "scale":0,
        "length":255,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"job_title"
    },
    "image":{
        "fieldName":"image",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"image"
    },
    "createdAt":{
        "fieldName":"createdAt",
        "type":"datetime",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"created_at"
    },
    "updatedAt":{
        "fieldName":"updatedAt",
        "type":"datetime",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"updated_at"
    },
    "timeZone":{
        "fieldName":"timeZone",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":true,
        "precision":0,
        "columnName":"time_zone"
    },
    "userRole":{
        "fieldName":"userRole",
        "type":"string",
        "scale":0,
        "length":null,
        "unique":false,
        "nullable":false,
        "precision":0,
        "columnName":"user_role"
    }
},
"fieldNames":{
    "id":"id",
    "deleted":"deleted",
    "notify":"notify",
    "first_name":"firstName",
    "last_name":"lastName",
    "job_title":"jobTitle",
    "image":"image",
    "created_at":"createdAt",
    "updated_at":"updatedAt",
    "time_zone":"timeZone",
    "user_role":"userRole"
},
"columnNames":{
    "id":"id",
    "deleted":"deleted",
    "notify":"notify",
    "firstName":"first_name",
    "lastName":"last_name",
    "jobTitle":"job_title",
    "image":"image",
    "createdAt":"created_at",
    "updatedAt":"updated_at",
    "timeZone":"time_zone",
    "userRole":"user_role"
},
"discriminatorValue":null,
"discriminatorMap":[

],
"discriminatorColumn":null,
"table":{
    "name":"user"
},
"lifecycleCallbacks":[

],
"entityListeners":[

],
"associationMappings":{
    "company":{
        "fieldName":"company",
        "joinColumns":[
            {
                "name":"company_id",
                "unique":false,
                "nullable":true,
                "onDelete":null,
                "columnDefinition":null,
                "referencedColumnName":"id"
            }
        ],
        "cascade":[
            "persist"
        ],
        "inversedBy":null,
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Company",
        "fetch":2,
        "type":2,
        "mappedBy":null,
        "isOwningSide":true,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":false,
        "isCascadePersist":true,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false,
        "sourceToTargetKeyColumns":{
            "company_id":"id"
        },
        "joinColumnFieldNames":{
            "company_id":"company_id"
        },
        "targetToSourceKeyColumns":{
            "id":"company_id"
        },
        "orphanRemoval":false
    },
    "projects":{
        "fieldName":"projects",
        "mappedBy":"createdBy",
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Project",
        "cascade":[

        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":false,
        "isCascadePersist":false,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false
    },
    "assignedProjects":{
        "fieldName":"assignedProjects",
        "mappedBy":"user",
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Project\\ProjectToUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    },
    "assignedAuthorities":{
        "fieldName":"assignedAuthorities",
        "mappedBy":"user",
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Authority\\AuthorityToUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    },
    "country":{
        "fieldName":"country",
        "joinColumns":[
            {
                "name":"country_id",
                "unique":false,
                "nullable":true,
                "onDelete":null,
                "columnDefinition":null,
                "referencedColumnName":"id"
            }
        ],
        "cascade":[
            "persist"
        ],
        "inversedBy":null,
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Country",
        "fetch":2,
        "type":2,
        "mappedBy":null,
        "isOwningSide":true,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":false,
        "isCascadePersist":true,
        "isCascadeRefresh":false,
        "isCascadeMerge":false,
        "isCascadeDetach":false,
        "sourceToTargetKeyColumns":{
            "country_id":"id"
        },
        "joinColumnFieldNames":{
            "country_id":"country_id"
        },
        "targetToSourceKeyColumns":{
            "id":"country_id"
        },
        "orphanRemoval":false
    },
    "groupUsers":{
        "fieldName":"groupUsers",
        "mappedBy":"user",
        "targetEntity":"BugTracker\\ModelBundle\\Entity\\Group\\GroupUser",
        "cascade":[
            "remove",
            "persist",
            "refresh",
            "merge",
            "detach"
        ],
        "orphanRemoval":false,
        "fetch":2,
        "type":4,
        "inversedBy":null,
        "isOwningSide":false,
        "sourceEntity":"BugTracker\\ModelBundle\\Entity\\User",
        "isCascadeRemove":true,
        "isCascadePersist":true,
        "isCascadeRefresh":true,
        "isCascadeMerge":true,
        "isCascadeDetach":true
    }
},
"isIdentifierComposite":false,
"containsForeignIdentifier":false,
"idGenerator":{

},
"sequenceGeneratorDefinition":null,
"tableGeneratorDefinition":null,
"changeTrackingPolicy":1,
"isVersioned":null,
"versionField":null,
"cache":null,
"reflClass":{
    "name":"BugTracker\\ModelBundle\\Entity\\User"
},
"isReadOnly":false,
"reflFields":{
    "id":{
        "name":"id",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "deleted":{
        "name":"deleted",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "notify":{
        "name":"notify",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "firstName":{
        "name":"firstName",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "lastName":{
        "name":"lastName",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "jobTitle":{
        "name":"jobTitle",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "image":{
        "name":"image",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "createdAt":{
        "name":"createdAt",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "updatedAt":{
        "name":"updatedAt",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "timeZone":{
        "name":"timeZone",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "userRole":{
        "name":"userRole",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "company":{
        "name":"company",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "projects":{
        "name":"projects",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "assignedProjects":{
        "name":"assignedProjects",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "assignedAuthorities":{
        "name":"assignedAuthorities",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "country":{
        "name":"country",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    },
    "groupUsers":{
        "name":"groupUsers",
        "class":"BugTracker\\ModelBundle\\Entity\\User"
    }
}
}

doctrine configuration on the second website

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                mapping_types:
                     enum: string
                driver: pdo_mysql
                host: '%database_host%'
                port: '%database_port%'
                dbname: '%database_name%'
                user: '%database_user%'
                password: '%database_password%'
                charset: UTF8
            bugtracker:
                mapping_types:
                     enum: string
                driver: pdo_mysql
                host: '%database_host_bugtracker%'
                port: '%database_port_bugtracker%'
                dbname: '%database_name_bugtracker%'
                user: '%database_user_bugtracker%'
                password: '%database_password_bugtracker%'
                charset: UTF8

Body:
What if you use username instead of email, because according to your posted entity email property exist in parent class FOS\UserBundle\Model\User and your child class sets email like setEmail(){....} in this function it also sets the same value to username parent::setUsername($email); so i guess you can get the user by using username property

$emBug->getRepository('BugTrackerModelBundle:User')->findBy(array('username' => $email));

Or eles define email property in your class like you defined username property

/**
 * @var string
 * @ORM\Column(type="string" definition....)
 */
protected $email;


来源: stackexchange

问:
Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in

Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in /public_html/header.php on line 35

In the header.php,
Connect to database:

```<code>$connect=mysqli_connect("localhost","$db_name","$password")
$sql_logo="SELECT * FROM `logo`";
$query_logo=mysqli_query($connect,$sql_logo);
</code>```

On line 35:

```<code><?php
   while($result=mysqli_fetch_object($query_logo)){
?>
   <a href="/"><img src="res/img/<?php echo $result->logo_img?>"></a>
<?php } ?>
</code>```

in my database:
the table name is logo and the column name is logo_img.

I don't know what happens, because when I try in XAMPP it's work using that's code.

答:
Please refer the PHP-Manual
http://php.net/manual/en/function.mysqli-connect.php
 for getting the better idea of mysqli syntax.

And for displaying records try to use syntax and code given below:

```<code>$conn = mysqli_connect("127.0.0.1", "db_username", "db_password", "Database_anme");
$limit = 10; //$_POST['limit'];
$start   = 0; //$_POST['start'];
$r = mysqli_query($conn, "SELECT * FROM `TABLE_NAME` DESC LIMIT $start,$limit");
while($quotos = mysqli_fetch_object($r)){
    // Your code goes here
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in /public_html/header.php on line 35

In the header.php,
Connect to database:

$connect=mysqli_connect("localhost","$db_name","$password")
$sql_logo="SELECT * FROM `logo`";
$query_logo=mysqli_query($connect,$sql_logo);

On line 35:

<?php
   while($result=mysqli_fetch_object($query_logo)){
?>
   <img src="res/img/<?php echo $result->logo_img?>">
<?php } ?>

in my database:
the table name is logo and the column name is logo_img.

I don't know what happens, because when I try in XAMPP it's work using that's code.

Body:
Please refer the PHP-Manual
http://php.net/manual/en/function.mysqli-connect.php
 for getting the better idea of mysqli syntax.

And for displaying records try to use syntax and code given below:

$conn = mysqli_connect("127.0.0.1", "db_username", "db_password", "Database_anme");
$limit = 10; //$_POST['limit'];
$start   = 0; //$_POST['start'];
$r = mysqli_query($conn, "SELECT * FROM `TABLE_NAME` DESC LIMIT $start,$limit");
while($quotos = mysqli_fetch_object($r)){
    // Your code goes here
}

ContentLicense: CC BY-SA 3.0


问:
On scroll recyclerview item Background color changed when recylcerview scroll
I want to change Recyclerview item background color on my condition but when I scroll  background color automatically changed   I know    holder.setIsRecyclable(false);  but I don't want to set holder.setIsRecyclable(false);

and I know

```<code> if(item.value == 1){
    // do something
    } else{
      // do something
   }
</code>```

but i want to do using nested if else

```<code>           if (feetInt > 0 && feetInt < 4) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_green));
            } else if (feetInt >= 4 && feetInt < 6) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_yellow));
            } else if (feetInt == 0 || feetInt >= 6) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_red));
            }else{
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_grey));
            }
</code>```

答: Instead of changing color on feetInt maintain a flag in your object class and on the basis of particular flag change your background color

Body:
I want to change Recyclerview item background color on my condition but when I scroll  background color automatically changed   I know    holder.setIsRecyclable(false);  but I don't want to set holder.setIsRecyclable(false);

and I know

 if(item.value == 1){
    // do something
    } else{
      // do something
   }

but i want to do using nested if else

           if (feetInt > 0 && feetInt < 4) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_green));
            } else if (feetInt >= 4 && feetInt < 6) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_yellow));
            } else if (feetInt == 0 || feetInt >= 6) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_red));
            }else{
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_grey));
            }


问:
Python: Checking at least two values in a list satisfy a condition
I have a list created in Python, something like a=[1.0,3.7,1.0,3.9].
I need to check a condition with if at least two values in the list have values in the range [3.0,4.0], then do something.

答:
```<code>if sum(1 for e in a if 3.0 <= e < 4.0) >= 2:
    something()
</code>```

1 for e in a if 3.0 <= e < 4.0 will return the iterator (1, 1) (i.e. a value 1 for each e such that it is between 3.0 and 4.0); then summing those ones gets us the count of the elements that satisfies the condition.

will this early exit when the list a is very long?

No. This will, tho, but it makes the logic a bit more complex:

```<code>from itertools import accumulate
if any(n for n in accumulate(1 for e in a if 3.0 <= e < 4.0) if n >= 2):
    something()
</code>```

Body:
if sum(1 for e in a if 3.0 <= e < 4.0) >= 2:
    something()

1 for e in a if 3.0 <= e < 4.0 will return the iterator (1, 1) (i.e. a value 1 for each e such that it is between 3.0 and 4.0); then summing those ones gets us the count of the elements that satisfies the condition.

will this early exit when the list a is very long?

No. This will, tho, but it makes the logic a bit more complex:

from itertools import accumulate
if any(n for n in accumulate(1 for e in a if 3.0 <= e < 4.0) if n >= 2):
    something()


问:
How to get the filenames of all the php files which generates a webpage?
Suppose we have a website at the url http://www.example.com/page/

But that page is generated by many php files (eg. as in Wordpress, index.php, header.php, content.php, footer.php)

How can I get all the filenames and their paths that are required to generate that page? (eg. index.php content.php as in WP)?

For instance, as in Wordpress, different pages will use different themes that are generated from different php files. You have to sift through those files one by one. So my question is how I can do it quickly and programmatically.

Thank you

答: If the page(s) code doesn't stop execution using exit, you could potentially use the php.ini directive auto_append_file in conjunction with get_included_files(). At that point, it would be a matter of how you track what page was viewed, and if you display additional information on the page or log to a text file, etc.


问:
Android Retrofit POST request cache
Which is best way to store retrofit POST request cache ?

I will store response and using that response while user is offline. I was referred this link.

1) Can Retrofit with OKHttp use cache data when offline

2) Cache POST requests with OkHttp

But in this link cache mechanism work only GET method.

- It is possible to store cache in post request using retrofit ?

- Is any library to handle network cache?

Thanks

答:
This is the solution we ended up with

public class OnErrorRetryCache<T> {

    public static <T> Observable<T> from(Observable<T> source) {
         return new OnErrorRetryCache<>(source).deferred;
    }

    private final Observable<T> deferred;
    private final Semaphore singlePermit = new Semaphore(1);

    private Observable<T> cache = null;
    private Observable<T> inProgress = null;

    private OnErrorRetryCache(Observable<T> source) {
        deferred = Observable.defer(() -> createWhenObserverSubscribes(source));
    }

    private Observable<T> createWhenObserverSubscribes(Observable<T> source)
    {
        singlePermit.acquireUninterruptibly();

        Observable<T> cached = cache;
        if (cached != null) {
            singlePermit.release();
            return cached;
        }

        inProgress = source
                .doOnCompleted(this::onSuccess)
                .doOnTerminate(this::onTermination)
                .replay()
                .autoConnect();

        return inProgress;
    }

    private void onSuccess() {
        cache = inProgress;
    }

    private void onTermination() {
        inProgress = null;
        singlePermit.release();
    }
}
```

We needed to cache the result of an HTTP request from Retrofit. So this was created, with an observable that emits a single item in mind.

If an observer subscribed while the HTTP request was being executed, we wanted it to wait and not execute the request twice, unless the in-progress one failed. To do that the semaphore allows single access to the block that creates or returns the cached observable, and if a new observable is created, we wait until that one terminates.

Title: Android Retrofit POST request cache

Body:
This is the solution we ended up with

public class OnErrorRetryCache<T> {

    public static <T> Observable<T> from(Observable<T> source) {
         return new OnErrorRetryCache<>(source).deferred;
    }

    private final Observable<T> deferred;
    private final Semaphore singlePermit = new Semaphore(1);

    private Observable<T> cache = null;
    private Observable<T> inProgress = null;

    private OnErrorRetryCache(Observable<T> source) {
        deferred = Observable.defer(() -> createWhenObserverSubscribes(source));
    }

    private Observable<T> createWhenObserverSubscribes(Observable<T> source)
    {
        singlePermit.acquireUninterruptibly();

        Observable<T> cached = cache;
        if (cached != null) {
            singlePermit.release();
            return cached;
        }

        inProgress = source
                .doOnCompleted(this::onSuccess)
                .doOnTerminate(this::onTermination)
                .replay()
                .autoConnect();

        return inProgress;
    }

    private void onSuccess() {
        cache = inProgress;
    }

    private void onTermination() {
        inProgress = null;
        singlePermit.release();
    }
}

We needed to cache the result of an HTTP request from Retrofit. So this was created, with an observable that emits a single item in mind.

If an observer subscribed while the HTTP request was being executed, we wanted it to wait and not execute the request twice, unless the in-progress one failed. To do that the semaphore allows single access to the block that creates or returns the cached observable, and if a new observable is created, we wait until that one terminates.


问:
"Running two copies of Meteor..." error when trying to launch an IOS/ Android app in Meteor
I get this error when trying to launch an IOS/ Android app in Meteor how can I solve it?

Running two copies of Meteor in the same application directory will
  not work. If something else is using port 3000, you can specify an
  alternative port with --port .

答:
This is because of may be running two copies of Meteor in the same application.

So need to kill the process of node or run in different port for the application

```<code>killall node

meteor --port 3030
</code>```

Body:
This is because of may be running two copies of Meteor in the same application.

So need to kill the process of node or run in different port for the application

killall node

meteor --port 3030


问:
Extracting string from char array specified by prefix and suffix
I want to write a function which extracts data from char array, which contains data specified by prefix (e.g. "type=") and suffix (e.g. ","). I have hard time working with strstr and pointer arythmetics, so I think posting my attempts to write that function is pointless. I want body of function to look like this:

```<code>void extract_string(char input[], char output[], char start[], end[]) {
    ...
}
</code>```

and call of function (with parameters) to look like this:

```<code>// extracting type and nickname
char message[128] = "type=client_information,port=6666,hostname=127.0.0.1,nickname=stack,";
char type[32];
char nickname[32];
extract_string(message, type, "type=", ",");
extract_string(message, nickname, "nickname=", ",");
</code>```

Can you please show me correct way to implement this function? It think this is not too complicated, I just stuck somewhere... Thank you for your concern.

答:
the following proposed code:

assumes that the 'output[]' array is long enough to hold the result+1

assumes that the 'output[]' is not to include the strings 'start[]' nor 'end[]'

Caveat: this is not tested

Caveat: the resulting char array in 'output[]' is not NUL terminated so the calling code (probably) should pre initialize that array to all '\0'

```<code>void extract_string(char input[], char output[], char start[], end[])
{
    char *startPos = strstr( input, start );
    if( !startPos )
    {
        fprintf( stderr, " %s not found in %s\n", start, input );
        return;
    }

    startPos += strlen( start );

    char *stopPos = strstr( startPos, end );
    if( !stopPos )
    {
        fprintf( stderr, " %s not found in %s\n", end, startPos );
        return;
    }

    memcpy( output, startPos, stopPos - startPos +1 );
} // end function: extract_string
</code>```

Body:
I want to write a function which extracts data from char array, which contains data specified by prefix (e.g. "type=") and suffix (e.g. ","). I have hard time working with strstr and pointer arythmetics, so I think posting my attempts to write that function is pointless. I want body of function to look like this:

void extract_string(char input[], char output[], char start[], end[]) {
    ...
}

and call of function (with parameters) to look like this:

// extracting type and nickname
char message[128] = "type=client_information,port=6666,hostname=127.0.0.1,nickname=stack,";
char type[32];
char nickname[32];
extract_string(message, type, "type=", ",");
extract_string(message, nickname, "nickname=", ",");

Can you please show me correct way to implement this function? It think this is not too complicated, I just stuck somewhere... Thank you for your concern.

Body:
the following proposed code:

assumes that the 'output[]' array is long enough to hold the result+1

assumes that the 'output[]' is not to include the strings 'start[]' nor 'end[]'

Caveat: this is not tested

Caveat: the resulting char array in 'output[]' is not NUL terminated so the calling code (probably) should pre initialize that array to all '\0'

void extract_string(char input[], char output[], char start[], end[])
{
    char *startPos = strstr( input, start );
    if( !startPos )
    {
        fprintf( stderr, " %s not found in %s\n", start, input );
        return;
    }

    startPos += strlen( start );

    char *stopPos = strstr( startPos, end );
    if( !stopPos )
    {
        fprintf( stderr, " %s not found in %s\n", end, startPos );
        return;
    }

    memcpy( output, startPos, stopPos - startPos +1 );
} // end function: extract_string


问:
Xcode Application Loader upload error
When I upload my app to the App Store, an error occurred.

So I tried uploading it with the Application Loader. I got the same error again.

My XCode version is Version 9.1 (9B55).

Here is the detailed error message:

Does anyone know how to solve it?

答:
emmm. I found a way and tried. it worked.

open the Teminal and run

```<code>cd ~
mv .itmstransporter/ .old_itmstransporter/
"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"
</code>```

you can view https://forums.developer.apple.com/thread/76803

Title: Xcode Application Loader upload error

Body:
emmm. I found a way and tried. it worked.

open the Teminal and run

cd ~
mv .itmstransporter/ .old_itmstransporter/
"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"

you can view https://forums.developer.apple.com/thread/76803


问:
What should be the order of filters in query to optimize queries to use Indexing
I have few doubts. I have heard from some of my colleagues that, if we have created composite Nonclustured index on following table order of all the filters should be in order of Indexed column then Filter.

MyTable (T1, T2, T3, T4, T5)

  Non
  Clustured index(T1, T2) in the order
  T1 then T2

Questions

Which of the queries works faster ?

Does order of Indexed column affects
performance ?

Should Indexed Columns
come first to optimize queries ?

What is the order of processing a
query. Which filter is taken first
while processing a query ? Does it
starts from Last filter and goes on
to first filter ?

Query 1

```<code>Select * from MyTable WHERE T1=1 AND T2=2 AND T3=1
--(Indexing will be used) Fastest as T3 has been included after indexed columns
</code>```

Query 2

```<code>Select * from MyTable WHERE T2=1 AND T1=2 AND T3=1
--(No Indexing will be used)
</code>```

Query 3

```<code>Select * from MyTable WHERE T3=1 AND T1=1 AND T2=2
--(Indexing will be used) slower than Query 1 as indexed columns included afterwards
</code>```

Query 4

```<code>Select * from MyTable WHERE T3=1 AND T2=1 AND T1=2
--(No Indexing will be used) slower than Query 2 as indexed columns occurs after non indexed column condition
</code>```

EDIT :

Query 5

```<code>Select * from MyTable WHERE T3=1 AND T2=1
</code>```

Query 6

```<code>Select * from MyTable WHERE T3=1 AND T1=1
</code>```

Query 7

```<code>Select * from MyTable WHERE T3=1 AND T2=1 OR T1=2
</code>```

Query 8

What does the following order in SSMS index creation means i.e. which filter should come first ?

When I tried to shuffle the order of columns shown in index columns. I saw Bookmark lookups were increasing and Clustured index scan was being used.
But when I uses the same order as shown in image. Then bookmark lookup got removed and also got Index Seek. So I can see order of Columns in index is playing some vital role here but could not sense how.

答:
The order of the predicates in the query makes no difference!

The usual analogy when considering column order in composite indexes is that of a phone book. This is ordered by (surname, firstname). This makes look ups by surname straightforward but doesn't help you looking up numbers by forename.

If you have an index on (T1, T2) it can be used to efficiently answer

```<code>Select * from MyTable WHERE T1=2
</code>```

Or

```<code>Select * from MyTable WHERE T2=1 AND T1=2
</code>```

But not to efficiently answer

```<code>Select * from MyTable WHERE T2=1
</code>```

(That is not to say this index is always going to be entirely useless for this query. If the index is narrow compared to the size of the table and the statistics indicate that few matching rows will be returned the query optimiser might still opt to scan this index and do key lookups in preference to a clustered index scan that might need to cover a lot more pages.)

Example Script as per comments

```<code>CREATE TABLE MyTable  (
ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
T1 INT NOT NULL,
T2 INT NOT NULL,
Filler CHAR(8000) NOT NULL /*Just to make sure that the table is very wide!*/);

CREATE NONCLUSTERED INDEX IX ON MyTable (T1,T2);

   WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
        E02(N) AS (SELECT 1 FROM E00 a, E00 b),
        E04(N) AS (SELECT 1 FROM E02 a, E02 b),
        E08(N) AS (SELECT 1 FROM E04 a, E04 b),
        E16(N) AS (SELECT 1 FROM E08 a, E08 b),
        E32(N) AS (SELECT 1 FROM E16 a, E16 b),
   cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)
 INSERT INTO MyTable
 SELECT N, N-1,''
   FROM cteTally
  WHERE N <= 1000;

 SET STATISTICS IO ON
 Select * from MyTable  WHERE T2=1
 /*
 Table 'MyTable'. Scan count 1, logical reads 9, physical reads 0,
 read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
 */

 /*Force a clustered index scan just to compare...*/
 Select * from MyTable   WITH( INDEX (1) ) WHERE T2=1
/*
Table 'MyTable'. Scan count 1, logical reads 1005, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.*/
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have few doubts. I have heard from some of my colleagues that, if we have created composite Nonclustured index on following table order of all the filters should be in order of Indexed column then Filter.

MyTable (T1, T2, T3, T4, T5)

  Non
  Clustured index(T1, T2) in the order
  T1 then T2

Questions

Which of the queries works faster ?

Does order of Indexed column affects
performance ?

Should Indexed Columns
come first to optimize queries ?

What is the order of processing a
query. Which filter is taken first
while processing a query ? Does it
starts from Last filter and goes on
to first filter ?

Query 1

Select * from MyTable WHERE T1=1 AND T2=2 AND T3=1
--(Indexing will be used) Fastest as T3 has been included after indexed columns

Query 2

Select * from MyTable WHERE T2=1 AND T1=2 AND T3=1
--(No Indexing will be used)

Query 3

Select * from MyTable WHERE T3=1 AND T1=1 AND T2=2
--(Indexing will be used) slower than Query 1 as indexed columns included afterwards

Query 4

Select * from MyTable WHERE T3=1 AND T2=1 AND T1=2
--(No Indexing will be used) slower than Query 2 as indexed columns occurs after non indexed column condition

EDIT :

Query 5

Select * from MyTable WHERE T3=1 AND T2=1

Query 6

Select * from MyTable WHERE T3=1 AND T1=1

Query 7

Select * from MyTable WHERE T3=1 AND T2=1 OR T1=2

Query 8

What does the following order in SSMS index creation means i.e. which filter should come first ?

When I tried to shuffle the order of columns shown in index columns. I saw Bookmark lookups were increasing and Clustured index scan was being used.
But when I uses the same order as shown in image. Then bookmark lookup got removed and also got Index Seek. So I can see order of Columns in index is playing some vital role here but could not sense how.

Body:
The order of the predicates in the query makes no difference!

The usual analogy when considering column order in composite indexes is that of a phone book. This is ordered by (surname, firstname). This makes look ups by surname straightforward but doesn't help you looking up numbers by forename.

If you have an index on (T1, T2) it can be used to efficiently answer

Select * from MyTable WHERE T1=2

Or

Select * from MyTable WHERE T2=1 AND T1=2

But not to efficiently answer

Select * from MyTable WHERE T2=1

(That is not to say this index is always going to be entirely useless for this query. If the index is narrow compared to the size of the table and the statistics indicate that few matching rows will be returned the query optimiser might still opt to scan this index and do key lookups in preference to a clustered index scan that might need to cover a lot more pages.)

Example Script as per comments

CREATE TABLE MyTable  (
ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
T1 INT NOT NULL,
T2 INT NOT NULL,
Filler CHAR(8000) NOT NULL /*Just to make sure that the table is very wide!*/);

CREATE NONCLUSTERED INDEX IX ON MyTable (T1,T2);

   WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1),
        E02(N) AS (SELECT 1 FROM E00 a, E00 b),
        E04(N) AS (SELECT 1 FROM E02 a, E02 b),
        E08(N) AS (SELECT 1 FROM E04 a, E04 b),
        E16(N) AS (SELECT 1 FROM E08 a, E08 b),
        E32(N) AS (SELECT 1 FROM E16 a, E16 b),
   cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY N) FROM E32)
 INSERT INTO MyTable
 SELECT N, N-1,''
   FROM cteTally
  WHERE N <= 1000;

 SET STATISTICS IO ON
 Select * from MyTable  WHERE T2=1
 /*
 Table 'MyTable'. Scan count 1, logical reads 9, physical reads 0,
 read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
 */

 /*Force a clustered index scan just to compare...*/
 Select * from MyTable   WITH( INDEX (1) ) WHERE T2=1
/*
Table 'MyTable'. Scan count 1, logical reads 1005, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.*/


问:
EventBus event between two fragments not fired
Problem: I am using EventBus by greenrobot to pass some events.
It is working for me unfortunately for the scenario of passing data between two fragments it does not. So the event does not get fired.

Question: Do I misunderstand the concept? Or is there a mistake in my code?

Note: Both Fragments exist at the time of sending the event. One fragment is the parent and the other one the child to display details.

detail fragment:

```<code>public class DetailFragment extends Fragment {
(...)

refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
EventBus.getDefault().post(new IntentRefresh());
            }
        });
(...)

}
</code>```

EventBus class:

```<code>public class IntentRefresh {

    public IntentRefresh (){}

    public void refreshParent() {

    }

}
</code>```

parent fragment:

```<code>public class ParentFragment extends Fragment {

    (...)

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateList(IntentRefresh intentRefresh) {
        Toast.makeText(getActivity(), "LUEEEEPT", Toast.LENGTH_SHORT).show();
    }

    (...)
}
</code>```

答:
I use @CaseyB's answer. its working for me perfectly.Like below </p>

```<code>@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (!EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().register(this);
}

@Override
public void onDetach() {
    super.onDetach();
    EventBus.getDefault().unregister(this);
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(CallbackModel event) {

}
</code>```

Body:
Problem: I am using EventBus by greenrobot to pass some events.
It is working for me unfortunately for the scenario of passing data between two fragments it does not. So the event does not get fired.

Question: Do I misunderstand the concept? Or is there a mistake in my code?

Note: Both Fragments exist at the time of sending the event. One fragment is the parent and the other one the child to display details.

detail fragment:

public class DetailFragment extends Fragment {
(...)

refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
EventBus.getDefault().post(new IntentRefresh());
            }
        });
(...)

}

EventBus class:

public class IntentRefresh {

    public IntentRefresh (){}

    public void refreshParent() {

    }

}

parent fragment:

public class ParentFragment extends Fragment {

    (...)

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateList(IntentRefresh intentRefresh) {
        Toast.makeText(getActivity(), "LUEEEEPT", Toast.LENGTH_SHORT).show();
    }

    (...)
}

Body:
I use @CaseyB's answer. its working for me perfectly.Like below

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (!EventBus.getDefault().isRegistered(this))
        EventBus.getDefault().register(this);
}

@Override
public void onDetach() {
    super.onDetach();
    EventBus.getDefault().unregister(this);
}

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(CallbackModel event) {

}


问:
Troubles using fragment with RecyclerView and Retrofit
I have this error, actually I don't know about fragments.

CreatView

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_inicio, container,
                false);
        getActivity().setTitle(R.string.inicio);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
        return rootView;
    }
</code>```

loadJSON void

```<code>private void loadJSON(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.42:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface request = retrofit.create(RequestInterface.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
            adapter = new CuponAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error", t.getMessage());
        }
    });
}
</code>```

Adapter

```<code>public class CuponAdapter extends RecyclerView.Adapter<CuponAdapter.ViewHolder> {
private ArrayList<Cupon> cupon;

public CuponAdapter(ArrayList<Cupon> cupon) {
    this.cupon = cupon;
}

@Override
public CuponAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int i) {
    holder.tv_titulo.setText(cupon.get(i).getTitulo());
    holder.tv_empresa.setText(cupon.get(i).getEmpresa());
    holder.tv_descripcion.setText(cupon.get(i).getDescripcion());
}

@Override
public int getItemCount() {
    return cupon.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView tv_titulo, tv_descripcion, tv_empresa;

    public ViewHolder(View view) {
        super(view);
        tv_titulo = (TextView) view.findViewById(R.id.tv_titulo);
        tv_descripcion = (TextView) view.findViewById(R.id.tv_descripcion);
        tv_empresa = (TextView) view.findViewById(R.id.tv_empresa);
    }
}
}
</code>```

The Error

12-08 00:00:05.727 1784-1784/com.mighty.cupoferta E/RecyclerView: No
  adapter attached; skipping layout

This code is based on this link .
But he explains how to put in an activity, how can I put in a fragment?

答:
set your adapter in the onCreateView function and use .notifyDataSetChanged() in the loadJSON function to notifiy the adapter about the changes in the data like the code below.

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_inicio, container,
            false);
    getActivity().setTitle(R.string.inicio);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);
    loadJSON();
    return rootView;
 }
</code>```

and in your adapter class write this

```<code>private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://192.168.1.42:3000/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
    @Override
    public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
        JSONResponse jsonResponse = response.body();
        data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
        adapter = new CuponAdapter(data);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onFailure(Call<JSONResponse> call, Throwable t) {
        Log.d("Error", t.getMessage());
    }
});
}
</code>```

Body:
I have this error, actually I don't know about fragments.

CreatView

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_inicio, container,
                false);
        getActivity().setTitle(R.string.inicio);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
        return rootView;
    }

loadJSON void

private void loadJSON(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.42:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface request = retrofit.create(RequestInterface.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
            adapter = new CuponAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error", t.getMessage());
        }
    });
}

Adapter

public class CuponAdapter extends RecyclerView.Adapter<CuponAdapter.ViewHolder> {
private ArrayList<Cupon> cupon;

public CuponAdapter(ArrayList<Cupon> cupon) {
    this.cupon = cupon;
}

@Override
public CuponAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int i) {
    holder.tv_titulo.setText(cupon.get(i).getTitulo());
    holder.tv_empresa.setText(cupon.get(i).getEmpresa());
    holder.tv_descripcion.setText(cupon.get(i).getDescripcion());
}

@Override
public int getItemCount() {
    return cupon.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView tv_titulo, tv_descripcion, tv_empresa;

    public ViewHolder(View view) {
        super(view);
        tv_titulo = (TextView) view.findViewById(R.id.tv_titulo);
        tv_descripcion = (TextView) view.findViewById(R.id.tv_descripcion);
        tv_empresa = (TextView) view.findViewById(R.id.tv_empresa);
    }
}
}

The Error

12-08 00:00:05.727 1784-1784/com.mighty.cupoferta E/RecyclerView: No
  adapter attached; skipping layout

This code is based on this link .
But he explains how to put in an activity, how can I put in a fragment?

Body:
set your adapter in the onCreateView function and use .notifyDataSetChanged() in the loadJSON function to notifiy the adapter about the changes in the data like the code below.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_inicio, container,
            false);
    getActivity().setTitle(R.string.inicio);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);
    loadJSON();
    return rootView;
 }

and in your adapter class write this

private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://192.168.1.42:3000/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
    @Override
    public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
        JSONResponse jsonResponse = response.body();
        data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
        adapter = new CuponAdapter(data);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onFailure(Call<JSONResponse> call, Throwable t) {
        Log.d("Error", t.getMessage());
    }
});
}


问:
What is the fastest way to return a range of numbers from a sorted array of numbers?
For C++ language, what's the fastest way in processing run-time (in multi core processors), from an algorithm design viewpoint, to search numbers (e.g. between 100 and 1000) that are within an array (or splice or whatever faster data structures for the purpose of this) and return the range of numbers limited to only 10 items returned? e.g. pseudocode in golang:

```<code>var listofnums := []uint64
var numcounter := 1
// splice of [1,2,3,4,5,31,32 .. 932536543] this list has 1 billion numeric items.
// the listofnums are already sorted each time an item is added but we do not know the lower_bound or upper_bound of the item list.
// I know I can use binary search to find listofnums[i] where it is smallest at [i] too... I'm asking for suggestions.
for i:=uint(0); i < len(listofnums); i++ {
    if listofnums[i] > 100 && listofnums[i] < 1000 {
         if listofnums[i]> 1000 || numcounter == 10 {
             return
         }
         fmt.Println("%d",listofnums[i])
         numcounter++
    }
}
</code>```

is this the fastest way? I saw bitmap structures in C++ but not sure if can be applied here.

I've come across this question, which is perfectly fine for veteran programmers to ask but I have no idea why it's down voted.
What is the fastest search method for array?

Can someone please not remove this question but let me rephrase it? Thanks in advance. I hope to find the most optimum way to return a range of numbers from a large array of numeric items.

答:
If I understand your problem correctly you need to find two positions in your array, the first of which all numbers are greater than or equal to 100 and the second of which all numbers are less than or equal to 1000.

The functions std::lower_bound and std::upper_bound do binary searches designed to find such a range.

For arrays, in C++ we usually use a std::vector and denote the beginning and end of ranges using a pair of iterators.

So something like this may be what you need:

```<code>std::pair<std::vector<int>::iterator, std::vector<int>::iterator>
    find_range(std::vector<int>& v, int min, int max)
{
    auto begin = std::lower_bound(std::begin(v), std::end(v), min);

    // start searching after the previously found value
    auto end = std::upper_bound(begin, std::end(v), max);

    return {begin, end};
}
</code>```

You can iterate over that range like this:

```<code>auto range = find_range(v, 100, 1000);

for(auto i = range.first; i != range.second; ++i)
    std::cout << *i << '\n';
</code>```

You can create a new vector from the range (slow) like this:

```<code>std::vector<int> selection{range.first, range.second};
</code>```

Body:
For C++ language, what's the fastest way in processing run-time (in multi core processors), from an algorithm design viewpoint, to search numbers (e.g. between 100 and 1000) that are within an array (or splice or whatever faster data structures for the purpose of this) and return the range of numbers limited to only 10 items returned? e.g. pseudocode in golang:

var listofnums := []uint64
var numcounter := 1
// splice of [1,2,3,4,5,31,32 .. 932536543] this list has 1 billion numeric items.
// the listofnums are already sorted each time an item is added but we do not know the lower_bound or upper_bound of the item list.
// I know I can use binary search to find listofnums[i] where it is smallest at [i] too... I'm asking for suggestions.
for i:=uint(0); i < len(listofnums); i++ {
    if listofnums[i] > 100 && listofnums[i] < 1000 {
         if listofnums[i]> 1000 || numcounter == 10 {
             return
         }
         fmt.Println("%d",listofnums[i])
         numcounter++
    }
}

is this the fastest way? I saw bitmap structures in C++ but not sure if can be applied here.

I've come across this question, which is perfectly fine for veteran programmers to ask but I have no idea why it's down voted.
What is the fastest search method for array?

Can someone please not remove this question but let me rephrase it? Thanks in advance. I hope to find the most optimum way to return a range of numbers from a large array of numeric items.

Body:
If I understand your problem correctly you need to find two positions in your array, the first of which all numbers are greater than or equal to 100 and the second of which all numbers are less than or equal to 1000.

The functions std::lower_bound and std::upper_bound do binary searches designed to find such a range.

For arrays, in C++ we usually use a std::vector and denote the beginning and end of ranges using a pair of iterators.

So something like this may be what you need:

std::pair<std::vector<int>::iterator, std::vector<int>::iterator>
    find_range(std::vector<int>& v, int min, int max)
{
    auto begin = std::lower_bound(std::begin(v), std::end(v), min);

    // start searching after the previously found value
    auto end = std::upper_bound(begin, std::end(v), max);

    return {begin, end};
}

You can iterate over that range like this:

auto range = find_range(v, 100, 1000);

for(auto i = range.first; i != range.second; ++i)
    std::cout << *i << '\n';

You can create a new vector from the range (slow) like this:

std::vector<int> selection{range.first, range.second};


问:
Effective way of pattern matching on multiple Options Scala
I have below function which returns a flag based on some conditions.

Trying to see if there is a better Scala way to achieve the same?

Basically based on the status of the person there are different rules to be applied finally to derive on the pass_ind flag.

If person status is Student or Unemployment there are some rules on income and if the person status is not in Student or Unemployment there are different rules to be applied on score & income

```<code>def IncomeScreenStatus(status_cd: Option[String],
                                   score: Option[Int],
                                 income: Option[Double]) : String  = {

 var pass_ind : String = "F"

 if (score.isDefined && income.isDefined && status_cd.isDefined) {

        val score : Int = score.get
        val income : Double = income.get
        val status_cd : String = status_cd.get

        if (status_cd == "STUDENT" || status_cd == "UNEMPLOYMENT") {
          pass_ind = (status_cd, income) match {
            case ("UNEMPLOYMENT", income) if income <= 7000 => "P"
            case ("STUDENT", income) if income <= 18000 => "P"
            case _ => "F"
          }
        }
        else {
          pass_ind = (income, score) match {
            case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
            case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
            case _ => "F"
          }
        }

      }

    pass_ind

}
</code>```

答:
Maybe something like this? (I haven't tried it, no guarantess it's correct.)</p>

```<code>def IncomeScreenStatus( mb_status_cd : Option[String], mb_score : Option[Int], mb_income : Option[Double]) : String  = {

  def nsu( score : Int, income : Double ) = { // neither student nor unemployed
    if ( (score < 100 || score > 150) && income <= 8500 )         "P"
    else if ( (score <= 167 && score >= 100) && income <= 10500 ) "P"
    else                                                          "F"
  }

  ( mb_status_cd, mb_score, mb_income ) match {
    case ( Some( "STUDENT"                  ), Some( score ), Some( income ) ) if ( income <= 18000 ) => "P"
    case ( Some( "UNEMPLOYMENT"             ), Some( score ), Some( income ) ) if ( income <=  7000 ) => "P"
    case ( Some( "STUDENT" | "UNEMPLOYMENT" ), Some( _     ), Some( _      ) )                        => "F"
    case ( Some( _                          ), Some( score ), Some( income ) )                        => nsu( score, income )
    case _                                                                                => "F"
  }
}
</code>```

Body:
I have below function which returns a flag based on some conditions.

Trying to see if there is a better Scala way to achieve the same?

Basically based on the status of the person there are different rules to be applied finally to derive on the pass_ind flag.

If person status is Student or Unemployment there are some rules on income and if the person status is not in Student or Unemployment there are different rules to be applied on score & income

def IncomeScreenStatus(status_cd: Option[String],
                                   score: Option[Int],
                                 income: Option[Double]) : String  = {

 var pass_ind : String = "F"

 if (score.isDefined && income.isDefined && status_cd.isDefined) {

        val score : Int = score.get
        val income : Double = income.get
        val status_cd : String = status_cd.get

        if (status_cd == "STUDENT" || status_cd == "UNEMPLOYMENT") {
          pass_ind = (status_cd, income) match {
            case ("UNEMPLOYMENT", income) if income <= 7000 => "P"
            case ("STUDENT", income) if income <= 18000 => "P"
            case _ => "F"
          }
        }
        else {
          pass_ind = (income, score) match {
            case (income, score) if (score < 100 || score > 150) && income <= 8500 => "P"
            case (income, score) if (score <= 167 && score >= 100) && income <= 10500 => "P"
            case _ => "F"
          }
        }

      }

    pass_ind

}

Body:
Maybe something like this? (I haven't tried it, no guarantess it's correct.)

def IncomeScreenStatus( mb_status_cd : Option[String], mb_score : Option[Int], mb_income : Option[Double]) : String  = {

  def nsu( score : Int, income : Double ) = { // neither student nor unemployed
    if ( (score < 100 || score > 150) && income <= 8500 )         "P"
    else if ( (score <= 167 && score >= 100) && income <= 10500 ) "P"
    else                                                          "F"
  }

  ( mb_status_cd, mb_score, mb_income ) match {
    case ( Some( "STUDENT"                  ), Some( score ), Some( income ) ) if ( income <= 18000 ) => "P"
    case ( Some( "UNEMPLOYMENT"             ), Some( score ), Some( income ) ) if ( income <=  7000 ) => "P"
    case ( Some( "STUDENT" | "UNEMPLOYMENT" ), Some( _     ), Some( _      ) )                        => "F"
    case ( Some( _                          ), Some( score ), Some( income ) )                        => nsu( score, income )
    case _                                                                                => "F"
  }
}


问:
How to get updated msql database value to be saved in PHP session?
I established database connection at the very beginning of my code by using PHP. In another JavaScript method, I updated some values in the database and would like to save it in session, but I can't connect to database and get the updated data that I need outside of the first PHP section. I tried to establish another db connection in the middle part of my code, but it doesn't seem to work.

The code is 300+ lines long so I can't show it here, I just need to know how can I query outside of connection class/retain connection throughout the same webpage/update session data whenever a function changes db value.

Please help! Thank you!

答:
You can just use 'include' or 'require' statement inside your query/php code, for you to call your database connection in every php file you created.

```<code><?php
include 'connection.php';
?>
</code>```

or

```<code><?php
require 'connection.php';
?>
</code>```

Body:
You can just use 'include' or 'require' statement inside your query/php code, for you to call your database connection in every php file you created.

<?php
include 'connection.php';
?>

or

<?php
require 'connection.php';
?>


问:
Images Could not load
I use this code for endcodeURLString.

```<code>url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
</code>```

Before keyword is use for without using stringByAddingPercentEscapesUsingEncoding,

and after keyword is after using stringByAddingPercentEscapesUsingEncoding.

It adds 52 to URL 2(not working), but in URL 1 is(it's working)

URL 1. before =>

https://images-na.ssl-images-amazon.com/images/I/41e3n4R8cUL._SL160_.jpg

URL 1. After =>

https://images-na.ssl-images-amazon.com/images/I/41e3n4R8cUL._SL160_.jpg

URL 2. before =>

https://images-na.ssl-images-amazon.com/images/I/41T%2BHZfQPsL._SL160_.jpg

URL 2. After =>

https://images-na.ssl-images-amazon.com/images/I/41T%252BHZfQPsL._SL160_.jpg

You can see in the second url, after %2, it added %252. I have no idea why this happens or what the solution is for this.

Bellow code is use in cellForItemAtIndexPath

```<code>[Common loadPostImg:a_cell.imgProduct :[dictImage valueForKey:@"url"]];

+(void)loadPostImg :(UIImageView *)imgView :(NSString *)strUrl{
if (strUrl)
{
    if (strUrl.length !=0)
    {
        strUrl = [Common appendURL:strUrl];

        [imgView setShowActivityIndicatorView:NO];
        imgView.backgroundColor = [UIColor clearColor];
        NSLog(@"before => %@",strUrl);
        strUrl = [Common endcodeURLString:strUrl];
        NSLog(@"After => %@",strUrl);
        [imgView sd_setImageWithURL:[NSURL URLWithString:strUrl] placeholderImage:[UIImage imageNamed:@"DefaultBanner"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
         {
             [imgView stopAnimating];
         }];

    }
    else
    {
        imgView.image = [UIImage imageNamed:@"DefaultBanner"];
    }
}
else
{
    imgView.image = [UIImage imageNamed:@"DefaultBanner"];
}}

+(NSString *)endcodeURLString :(NSString *)url{
url = [url stringByReplacingOccurrencesOfString:@"%20" withString:@" "];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return url;}
</code>```

答:
You can do like this

```<code>UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:<Your original URL without percentage escaping>]]];
[self.view addSubview:imageView];
</code>```

Hope this helps

Title: Images Could not load

Body:
I use this code for endcodeURLString.

url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

Before keyword is use for without using stringByAddingPercentEscapesUsingEncoding,

and after keyword is after using stringByAddingPercentEscapesUsingEncoding.

It adds 52 to URL 2(not working), but in URL 1 is(it's working)

URL 1. before =>

https://images-na.ssl-images-amazon.com/images/I/41e3n4R8cUL._SL160_.jpg

URL 1. After =>

https://images-na.ssl-images-amazon.com/images/I/41e3n4R8cUL._SL160_.jpg

URL 2. before =>

https://images-na.ssl-images-amazon.com/images/I/41T%2BHZfQPsL._SL160_.jpg

URL 2. After =>

https://images-na.ssl-images-amazon.com/images/I/41T%252BHZfQPsL._SL160_.jpg

You can see in the second url, after %2, it added %252. I have no idea why this happens or what the solution is for this.

Bellow code is use in cellForItemAtIndexPath

[Common loadPostImg:a_cell.imgProduct :[dictImage valueForKey:@"url"]];

+(void)loadPostImg :(UIImageView *)imgView :(NSString *)strUrl{
if (strUrl)
{
    if (strUrl.length !=0)
    {
        strUrl = [Common appendURL:strUrl];

        [imgView setShowActivityIndicatorView:NO];
        imgView.backgroundColor = [UIColor clearColor];
        NSLog(@"before => %@",strUrl);
        strUrl = [Common endcodeURLString:strUrl];
        NSLog(@"After => %@",strUrl);
        [imgView sd_setImageWithURL:[NSURL URLWithString:strUrl] placeholderImage:[UIImage imageNamed:@"DefaultBanner"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
         {
             [imgView stopAnimating];
         }];

    }
    else
    {
        imgView.image = [UIImage imageNamed:@"DefaultBanner"];
    }
}
else
{
    imgView.image = [UIImage imageNamed:@"DefaultBanner"];
}}

+(NSString *)endcodeURLString :(NSString *)url{
url = [url stringByReplacingOccurrencesOfString:@"%20" withString:@" "];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return url;}

Body:
You can do like this

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:<Your original URL without percentage escaping>]]];
[self.view addSubview:imageView];

Hope this helps


问:
About IB,init,load view and view did load?
this is a quite general question but i want to understand this please -

I usually build my apps without using IB.

what are, the cons and pros of using IB vs. creating interface programmatically?

what oppressions/code fits the init method and what is for the loadView method?

is there any difference between loadView an ViewDidLoad or do i need to use only one of them?

thanks
shani

答:
Pros are it's quicker to get off the ground, you can adjust the positions of subviews usually quicker and definitely easier. Cons: You are limited to what you can do in Interface Builder, which is less than you can achieve in code almost always. Plus the interaction between how some views behave out of IB can catch new users.

init and its namesakes should only be used for setting sane defaults of ivars. loadView is used for setting up the view hierarchy, starting with the backing view of your view controller. I.e., a special note; don't reference the self.view property unless you are setting it, this will cause an infinite loop. Just a friendly protip.

As mentioned before loadView is used to set up your backing view (it must be created by you if you override it), and viewDidLoad is called after the view has been loaded (after loadView is called). You do the appropriate items in the appropriate spots.


问:
Button background as transparent
I have a button. When I press the button I have to make text as bold otherwise normal. So I wrote styles for bold & normal.

```<code><style name="textbold" parent="@android:style/TextAppearance">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textStyle">bold</item>
</style>
<style name="textregular" parent="@android:style/TextAppearance">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textStyle">normal</item>
</style>
</code>```

Now I have a button_states.xml as:

```<code><?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true"
    style="@style/textbold" />
<item android:state_focused="false" android:state_pressed="true"
    style="@style/textregular" />

<item style="@style/textregular" />
</selector>
</code>```

In my layout for this button, I have to make the background as transparent too...How will I do it? My layout code is :

```<code><Button android:id="@+id/Btn" android:background="@drawable/button_states" />
</code>```

How will I include background as transparent in my style?

答:
I achieved this with in XML with </p>

```<code>android:background="@android:color/transparent"
</code>```

Title: Button background as transparent

Body:
I have a button. When I press the button I have to make text as bold otherwise normal. So I wrote styles for bold & normal.

Now I have a button_states.xml as:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true"
    style="@style/textbold" />
<item android:state_focused="false" android:state_pressed="true"
    style="@style/textregular" />

<item style="@style/textregular" />
</selector>

In my layout for this button, I have to make the background as transparent too...How will I do it? My layout code is :

<Button android:id="@+id/Btn" android:background="@drawable/button_states" />

How will I include background as transparent in my style?

Body:
I achieved this with in XML with

android:background="@android:color/transparent"