Bulk API to associate a tag to multiple entities
197471
@POST
    @Path("/bulk/classification")
    @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON})
    @Produces(Servlets.JSON_MEDIA_TYPE)
    public void addClassification(ClassificationAssociateRequest request) throws AtlasBaseException {
        AtlasPerfTracer perf = null;

        try {
            if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.addClassification(" + request  + ")");
            }

            AtlasClassification classification = request == null ? null : request.getClassification();
            List<String>        entityGuids    = request == null ? null : request.getEntityGuids();

            if (classification == null || StringUtils.isEmpty(classification.getTypeName())) {
                throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "no classification");
            }

            if (CollectionUtils.isEmpty(entityGuids)) {
                throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "empty guid list");
            }

            entitiesStore.addClassification(entityGuids, classification);
        } finally {
            AtlasPerfTracer.log(perf);
        }
    }
1017806
function dummyDataWithAllTags(...tagList){
    if(!is.all.string(tagList)) throw new TypeError('all specified tags must be strings');
    const ans = [];
    for(const td of Object.values(muQUnitUtil.allDummyData)){
        for(const dd of Object.values(td)){
            // make sure every tag is present
            let allPresent = true;
            for(const t of tagList){
                if(!dd.hasTag(t)){
                    allPresent = false;
                    break;
                }
            }
            if(allPresent) ans.push(dd);
        }
    }
    return ans;
}
1012228
private Tag entityToTag(String id, Entity tagEntity) {
    Tag tag = tagFactory.create(id);
    tag.setObjectIri(tagEntity.getString(EMX_TAG_OBJECT_IRI));
    tag.setLabel(tagEntity.getString(EMX_TAG_LABEL));
    tag.setRelationLabel(tagEntity.getString(EMX_TAG_RELATION_LABEL));
    tag.setCodeSystem(tagEntity.getString(EMX_TAG_CODE_SYSTEM));
    tag.setRelationIri(tagEntity.getString(EMX_TAG_RELATION_IRI));

    return tag;
  }
774530
async function many2many (source, model, args = [], t) {
  let pluralModel = pluralize.plural(model)
  let current = []

  if (args.every(arg => _.isObject(arg))) {
    for (let arg of args) {
      let obj = await util.insertOrUpdate(this.models[model], arg, t)

      if (obj) {
        current.push(obj)
      }
    }
  } else {
    current = await this.models[model].findAll({
      where: {id: {[Op.in]: args}},
      transaction: t
    })
  }

  await source[`set${_.upperFirst(this.associations[pluralModel].as)}`](current, {transaction: t})
}
154148
def v1_tag_associations(tags, tag):
    '''
    '''
    tag = tag.decode('utf-8').strip()
    return {'associations': tags.assocs_by_tag(tag)}
906770
def _request_process_json_bulk(self, response_data):
        
        status = 'Failure'
        data = response_data.get(self.request_entity, [])
        if data:
            status = 'Success'
        return data, status
205163
def bulk_fetch(bulk_fetch_ids, odba_caller)
			instances = []
			loaded_ids = []
			bulk_fetch_ids.each { |id|
				if(entry = fetch_cache_entry(id))
					entry.odba_add_reference(odba_caller)
					instances.push(entry.odba_object)
					loaded_ids.push(id)
				end
			}
			bulk_fetch_ids -= loaded_ids
			unless(bulk_fetch_ids.empty?)
				rows = ODBA.storage.bulk_restore(bulk_fetch_ids)
				instances += bulk_restore(rows, odba_caller)
			end
			instances
		end
607379
def load_entities():
    """"""
    path = os.path.join(TOPDIR, 'entities.json')
    entities = json.load(open(path))
    names = [i['name'] for i in entities]

    try:
        assert len(set(names)) == len(entities)
    except AssertionError:
        raise Exception('Entities with same name: %s' % [i for i in names if
                                                         names.count(i) > 1])

    entities = dict((k['name'], c.Entity(name=k['name'],
                                         dimensions=k['dimensions'],
                                         uri=k['URI'])) for k in entities)

    dimensions_ent = defaultdict(list)
    for ent in entities:
        if not entities[ent].dimensions:
            continue
        perms = get_dimension_permutations(entities, entities[ent].dimensions)
        for perm in perms:
            key = get_key_from_dimensions(perm)
            dimensions_ent[key].append(entities[ent])

    return entities, dimensions_ent
1032778
def add_to_many(activity_data, feeds)
      data = {
        :feeds => feeds,
        :activity => activity_data
      }
      signature = Stream::Signer.create_jwt_token('feed', '*', @api_secret, '*')
      make_request(:post, '/feed/add_to_many/', signature, {}, data)
    end
582241
def list_tags(Name,
           region=None, key=None, keyid=None, profile=None):
    '''
    

    '''

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        rid = _get_trail_arn(Name,
                             region=region, key=key, keyid=keyid,
                             profile=profile)
        ret = conn.list_tags(ResourceIdList=[rid])
        tlist = ret.get('ResourceTagList', []).pop().get('TagsList')
        tagdict = {}
        for tag in tlist:
            tagdict[tag.get('Key')] = tag.get('Value')
        return {'tags': tagdict}
    except ClientError as e:
        return {'error': __utils__['boto3.get_error'](e)}
978350
def tagged(*tags: Tags) -> Callable:
    global GREENSIM_TAG_ATTRIBUTE
    
    def hook(event: Callable):
        def wrapper(*args, **kwargs):
            event(*args, **kwargs)
        setattr(wrapper, GREENSIM_TAG_ATTRIBUTE, tags)
        return wrapper
    return hook
934023
def insert_many(cls, documents):
        """"""
        from mongoframes.queries import to_refs

        # Ensure all documents have been converted to frames
        frames = cls._ensure_frames(documents)

        # Send insert signal
        signal('insert').send(cls, frames=frames)

        # Prepare the documents to be inserted
        documents = [to_refs(f._document) for f in frames]

        # Bulk insert
        ids = cls.get_collection().insert_many(documents).inserted_ids

        # Apply the Ids to the frames
        for i, id in enumerate(ids):
            frames[i]._id = id

        # Send inserted signal
        signal('inserted').send(cls, frames=frames)

        return frames
38614
def _maybe_init_tags(self, run_id, tag_to_metadata):
    
    cursor = self._db.cursor()
    # TODO: for huge numbers of tags (e.g. 1000+), this is slower than just
    # querying for the known tag names explicitly; find a better tradeoff.
    cursor.execute('SELECT tag_name, tag_id FROM Tags WHERE run_id = ?',
                   (run_id,))
    tag_to_id = {row[0]: row[1] for row in cursor.fetchall()
                 if row[0] in tag_to_metadata}
    new_tag_data = []
    for tag, metadata in six.iteritems(tag_to_metadata):
      if tag not in tag_to_id:
        tag_id = self._create_id()
        tag_to_id[tag] = tag_id
        new_tag_data.append((run_id, tag_id, tag, time.time(),
                             metadata.display_name,
                             metadata.plugin_data.plugin_name,
                             self._make_blob(metadata.plugin_data.content)))
    cursor.executemany(
        """
        INSERT INTO Tags (
          run_id, tag_id, tag_name, inserted_time, display_name, plugin_name,
          plugin_data
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
        """,
        new_tag_data)
    return tag_to_id
1119608
def set_tag(key, value)
      if custom?
        @data[:data][:sdk][:custom] ||= {}
        @data[:data][:sdk][:custom][:tags] ||= {}
        @data[:data][:sdk][:custom][:tags][key] = value

        if key.to_sym == :'span.kind'
          case value.to_sym
          when :server || :consumer
            @data[:data][:sdk][:type] = :entry
          when :client || :producer
            @data[:data][:sdk][:type] = :exit
          end
        end
      else
        if !@data[:data].key?(key)
          @data[:data][key] = value
        elsif value.is_a?(Hash) && self[:data][key].is_a?(Hash)
          @data[:data][key].merge!(value)
        else
          @data[:data][key] = value
        end
      end
      self
    end
1368525
def tag_instance(instance_id, **tags):
    """"""
    logger.debug("Got request to add tags %s to instance %s."
                 % (str(tags), instance_id))
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance(instance_id)

    # Remove None's from `tags`
    filtered_tags = {k: v for k, v in tags.items() if v and k}

    # Check for existing tags
    if instance.tags is not None:
        existing_tags = {tag.get('Key'): tag.get('Value')
                         for tag in instance.tags}
        logger.debug("Ignoring existing tags; %s" % str(existing_tags))
        for tag_key in existing_tags.keys():
            filtered_tags.pop(tag_key, None)

    # If we have new tags to add, add them.
    tag_list = [{'Key': k, 'Value': v} for k, v in filtered_tags.items()]
    if len(tag_list):
        logger.info('Adding project tags "%s" to instance %s'
                    % (filtered_tags, instance_id))
        instance.create_tags(Tags=tag_list)
    else:
        logger.info('No new tags from: %s' % str(tags))
    return
610877
def tagged(self, tag):
        """"""
        return PostCollection([p for p in self if unicode(tag) in p.tags])
687517
public function getAssociatedTags(EntityDefinition $definition, Entity $entity, Context $context): array
    {
        $associations = $definition->getFields()->filterInstance(AssociationField::class);

        $keys = [$this->getEntityTag($entity->getUniqueIdentifier(), $definition)];

        foreach ($context->getLanguageIdChain() as $languageId) {
            $keys[] = $this->getEntityTag($languageId, $this->languageDefinition);
        }

        $translationDefinition = $definition->getTranslationDefinition();

        if ($translationDefinition) {
            /* @var EntityDefinition $translationDefinition */
            $keys[] = $translationDefinition->getEntityName() . '.language_id';
        }

        /** @var AssociationField[] $associations */
        foreach ($associations as $association) {
            if ($association->is(Extension::class)) {
                $value = $entity->getExtension($association->getPropertyName());
            } else {
                try {
                    $value = $entity->get($association->getPropertyName());
                } catch (\Exception $e) {
                    continue;
                }
            }

            if (!$value) {
                continue;
            }

            if ($association instanceof ManyToOneAssociationField || $association instanceof OneToOneAssociationField) {
                /* @var Entity $value */
                $nested = $this->getAssociatedTags($association->getReferenceDefinition(), $value, $context);
                foreach ($nested as $key) {
                    $keys[] = $key;
                }

                continue;
            }

            if ($association instanceof OneToManyAssociationField) {
                /** @var Entity[] $value */
                foreach ($value as $item) {
                    $nested = $this->getAssociatedTags($association->getReferenceDefinition(), $item, $context);
                    foreach ($nested as $key) {
                        $keys[] = $key;
                    }
                }

                continue;
            }

            if ($association instanceof ManyToManyAssociationField) {
                /** @var Entity[] $value */
                foreach ($value as $item) {
                    $nested = $this->getAssociatedTags($association->getToManyReferenceDefinition(), $item, $context);
                    foreach ($nested as $key) {
                        $keys[] = $key;
                    }
                }
            }
        }

        return array_keys(array_flip($keys));
    }