Affiliate unique identities.

        This method enrolls unique identities to organizations using email
        addresses and top/sub domains data. Only new enrollments will be created.
358477
def affiliate(self):
        
        try:
            uidentities = api.unique_identities(self.db)

            for uid in uidentities:
                uid.identities.sort(key=lambda x: x.id)

                for identity in uid.identities:
                    # Only check email address to find new affiliations
                    if not identity.email:
                        continue
                    if not EMAIL_ADDRESS_PATTERN.match(identity.email):
                        continue

                    domain = identity.email.split('@')[-1]

                    try:
                        doms = api.domains(self.db, domain=domain, top=True)
                    except NotFoundError as e:
                        continue

                    if len(doms) > 1:
                        doms.sort(key=lambda d: len(d.domain), reverse=True)

                        msg = "multiple top domains for %s sub-domain. Domain %s selected."
                        msg = msg % (domain, doms[0].domain)
                        self.warning(msg)

                    organization = doms[0].organization.name

                    # Check enrollments to avoid insert affiliation twice
                    enrollments = api.enrollments(self.db, uid.uuid,
                                                  organization)

                    if enrollments:
                        continue

                    api.add_enrollment(self.db, uid.uuid, organization)

                    self.display('affiliate.tmpl', id=uid.uuid,
                                 email=identity.email, organization=organization)
        except (NotFoundError, InvalidValueError) as e:
            self.error(str(e))
            return e.code

        return CMD_SUCCESS
639220
def __parse_identities(self, aliases, email_to_employer):
        """"""

        # Parse streams
        self.__parse_aliases_stream(aliases)
        self.__parse_email_to_employer_stream(email_to_employer)

        # Create unique identities from aliases list
        for alias, email in self.__raw_aliases.items():
            uid = self._identities.get(email, None)

            if not uid:
                uid = UniqueIdentity(uuid=email)

                e = re.match(self.EMAIL_ADDRESS_REGEX, email, re.UNICODE)
                if e:
                    identity = Identity(email=email, source=self.source)
                else:
                    identity = Identity(username=email, source=self.source)

                uid.identities.append(identity)

                self._identities[email] = uid

            e = re.match(self.EMAIL_ADDRESS_REGEX, alias, re.UNICODE)
            if e:
                identity = Identity(email=alias, source=self.source)
            else:
                identity = Identity(username=alias, source=self.source)

            uid.identities.append(identity)

        # Create unique identities from enrollments list
        for email in self.__raw_identities:

            # Do we have it from aliases?
            if email in self._identities:
                uid = self._identities[email]
            elif email in self.__raw_aliases:
                canonical = self.__raw_aliases[email]
                uid = self._identities[canonical]
            else:
                uid = UniqueIdentity(uuid=email)

                identity = Identity(email=email, source=self.source)
                uid.identities.append(identity)

                self._identities[email] = uid

            # Assign enrollments
            enrs = self.__raw_identities[email]
            enrs.sort(key=lambda r: r[1])

            start_date = MIN_PERIOD_DATE

            for rol in enrs:
                name = rol[0]
                org = self._organizations.get(name, None)

                if not org:
                    org = Organization(name=name)
                    self._organizations[name] = org

                end_date = rol[1]

                enrollment = Enrollment(start=start_date, end=end_date,
                                        organization=org)
                uid.enrollments.append(enrollment)

                if end_date != MAX_PERIOD_DATE:
                    start_date = end_date
52896
def generate_subid(self, token=None, return_user=False):
    '''
    '''    
    from expfactory.database.models import Participant
    if not token:
        p = Participant()
    else:
        p = Participant(token=token)
    self.session.add(p)
    self.session.commit()
    if return_user is True:
        return p
    return p.id
1067373
public Response create(String username, String password, String organization, String email, String phone, String countryCode, String firstName, String lastName) {
        Response op = new Response();
        if (userDAO.hasUser(username) == false) {
            if (userDAO.hasUserWithEmail(email) == false) {
                if (organizationDAO.hasOrganization(organization) == true) {
                    PersistedUser user = new PersistedUser(username, null, Arrays.asList("ROLE_USER"), organization, email, phone, countryCode);
                    user.firstName = firstName;
                    user.lastName = lastName;
                    user.has2FAEnabled = Boolean.parseBoolean(authyEnabled);
                    createPasswordHash(user, password);
                    com.authy.api.User authyUser = client.getUsers().createUser(user.email, user.phone, user.countryCode);
                    user.authProviderId = authyUser.getId();
                    userDAO.create(user);
                    op.setPayload(true);
                    sendAccountVerificationMessage(user, null);
                    notifyOperator(user);
                } else {
                    op.addError(new Error(11));
                }
            } else {
                op.addError(new Error(Error.USER_BY_EMAIL_FOUND));
            }
        } else {
            op.addError(new Error(7));
        }
        return op;
    }
383063
def create_subscription(request):
    ""
    
    if request.POST:
        form = NewSubscriptionForm(request.POST)
        if form.is_valid():
            unverified = form.save()

            body = """Please confirm your email address to subscribe to status updates from %(name)s:\n\n%(link)s""" % dict(
                name=conf.NAME,
                link=urlparse.urljoin(conf.BASE_URL, reverse('overseer:verify_subscription', args=[unverified.ident]))
            )

            # Send verification email
            from_mail = conf.FROM_EMAIL
            if not from_mail:
                from_mail = 'overseer@%s' % request.get_host().split(':', 1)[0]
            
            send_mail('Confirm Subscription', body, from_mail, [unverified.email],
                      fail_silently=True)
            
            # Show success page
            return respond('overseer/create_subscription_complete.html', {
                'subscription': unverified,
            }, request)
    else:
        form = NewSubscriptionForm()

    context = csrf(request)
    context.update({
        'form': form,
        'service_list': Service.objects.all(),
    })

    return respond('overseer/create_subscription.html', context, request)
880563
public void addIdentities(Collection<Identity> identitiesToAdd) {
        if (identitiesToAdd == null) return;
        for (Identity identity : identitiesToAdd) {
            addIdentity(identity);
        }
    }
863566
def __load_unique_identities(self, uidentities, matcher, match_new,
                                 reset, verbose):
        """"""

        self.new_uids.clear()

        n = 0

        if reset:
            self.__reset_unique_identities()

        self.log("Loading unique identities...")

        for uidentity in uidentities:
            self.log("\n=====", verbose)
            self.log("+ Processing %s" % uidentity.uuid, verbose)

            try:
                stored_uuid = self.__load_unique_identity(uidentity, verbose)
            except LoadError as e:
                self.error("%s Skipping." % str(e))
                self.log("=====", verbose)
                continue

            stored_uuid = self.__load_identities(uidentity.identities, stored_uuid,
                                                 verbose)

            try:
                self.__load_profile(uidentity.profile, stored_uuid, verbose)
            except Exception as e:
                self.error("%s. Loading %s profile. Skipping profile." %
                           (str(e), stored_uuid))

            self.__load_enrollments(uidentity.enrollments, stored_uuid,
                                    verbose)

            if matcher and (not match_new or stored_uuid in self.new_uids):
                stored_uuid = self._merge_on_matching(stored_uuid, matcher,
                                                      verbose)

            self.log("+ %s (old %s) loaded" % (stored_uuid, uidentity.uuid),
                     verbose)
            self.log("=====", verbose)
            n += 1

        self.log("%d/%d unique identities loaded" % (n, len(uidentities)))
1028074
def add_subscriber(self, connection_id, subscriptions,
                       last_known_block_id):
        
        with self._subscribers_cv:
            self._subscribers[connection_id] = \
                EventSubscriber(
                    connection_id, subscriptions, last_known_block_id)

        LOGGER.debug(
            'Added Subscriber %s for %s', connection_id, subscriptions)
645874
def add_unique_id(self):
        
        
        uid = 0
        for feature in self._data["features"]:
            if feature["properties"].get("id"):
                raise Exception("one of the features already had an id field")
            feature["properties"]["id"] = uid
            uid += 1
838804
protected void addSubscription(SIBUuid12 topicSpace, String topic, MESubscription subscription)
  {
    // Generate a key for the topicSpace/topic
    final String key = BusGroup.subscriptionKey(topicSpace, topic);

    iProxies.put(key, subscription);
  }
656757
public Optional<PartnerSubscription> show(long partnerId, long accountId, long subscriptionId)
    {
        return HTTP.GET(String.format("/v2/partners/%d/accounts/%d/subscriptions/%d", partnerId, accountId, subscriptionId), PARTNER_SUBSCRIPTION);
    }
1039295
function Subscription(name, topic) {
            this._pattern = "%s://%s.mns.%s.aliyuncs.com/topics/%s/subscriptions/%s";
            this._name = name;
            this._topic = topic;
            // make url
            this._urlAttr = this.makeAttrURL();
            // create the OpenStack object
            this._openStack = new AliMNS.OpenStack(topic.getAccount());
        }
387383
function createApplication() {

  var app = {
    name: unique('My Awesome Application'),
    description: ('No, Srsly. It\'s Awesome')
  };

  return client.createApplication(app, {createDirectory: true}, function(err, app) {
    if (err) throw err;
    application = app;
    console.log('Created application:');
    console.log(application);
    return createAccount(); //next quickstart step
  });
}
67885
public void setMailFromDomainAttributes(java.util.Map<String, IdentityMailFromDomainAttributes> mailFromDomainAttributes) {
        this.mailFromDomainAttributes = mailFromDomainAttributes == null ? null
                : new com.amazonaws.internal.SdkInternalMap<String, IdentityMailFromDomainAttributes>(mailFromDomainAttributes);
    }
1313507
private void createAllOrganizations(Map<String, JsonObject> foundCertificateAuthorities) throws NetworkConfigurationException {

        // Sanity check
        if (organizations != null) {
            throw new NetworkConfigurationException("INTERNAL ERROR: organizations has already been initialized!");
        }

        organizations = new HashMap<>();

        // organizations is a JSON object containing a nested object for each Org
        JsonObject jsonOrganizations = getJsonObject(jsonConfig, "organizations");

        if (jsonOrganizations != null) {

            for (Entry<String, JsonValue> entry : jsonOrganizations.entrySet()) {
                String orgName = entry.getKey();

                JsonObject jsonOrg = getJsonValueAsObject(entry.getValue());
                if (jsonOrg == null) {
                    throw new NetworkConfigurationException(format("Error loading config. Invalid Organization entry: %s", orgName));
                }

                OrgInfo org = createOrg(orgName, jsonOrg, foundCertificateAuthorities);
                organizations.put(orgName, org);
            }
        }

    }
835898
public boolean containsDuplicateIdentities() {
        List<Identity> checkedIdentities = new LinkedList<>();
        for (Identity i : identities) {
            for (Identity i2 : checkedIdentities) {
                if (i.equals(i2))
                    return true;
            }
            checkedIdentities.add(i);
        }
        return false;
    }
933716
@Override
    public InstagramSingleObjectResponse createUserSubscription(String clientId,
                                                                String clientSecret,
                                                                String callbackUrl) throws InstagramError {
        return instagramRealtime.createUserSubscription(clientId, clientSecret, callbackUrl,
                                                        InstagramSubscriptionObjectTypes.USER.getObject(), SUBSCRIPTION_ASPECT);
    }