Generate pretty content IDs.
185218
def generateUniqueId(context, **kw):
    

    # get the config for this portal type from the system setup
    config = get_config(context, **kw)

    # get the variables map for later string interpolation
    variables = get_variables(context, **kw)

    # The new generate sequence number
    number = 0

    # get the sequence type from the global config
    sequence_type = config.get("sequence_type", "generated")

    # Sequence Type is "Counter", so we use the length of the backreferences or
    # contained objects of the evaluated "context" defined in the config
    if sequence_type in ["counter"]:
        number = get_counted_number(context, config, variables, **kw)

    # Sequence Type is "Generated", so the ID is constructed according to the
    # configured split length
    if sequence_type in ["generated"]:
        number = get_generated_number(context, config, variables, **kw)

    # store the new sequence number to the variables map for str interpolation
    if isinstance(number, Alphanumber):
        variables["alpha"] = number
    variables["seq"] = to_int(number)

    # The ID formatting template from user config, e.g. {sampleId}-R{seq:02d}
    id_template = config.get("form", "")

    # Interpolate the ID template
    try:
        new_id = id_template.format(**variables)
    except KeyError, e:
        logger.error('KeyError: {} not in id_template {}'.format(
            e, id_template))
        raise
    normalized_id = api.normalize_filename(new_id)
    logger.info("generateUniqueId: {}".format(normalized_id))

    return normalized_id
740883
def generate(self, id_or_uri):
        
        uri = self._client.build_uri(id_or_uri) + "/generate"
        return self._client.get(uri)
459376
def generate(self):
        """"""
        payload = {
            'algorithm': 'HMAC-SHA256'
        }

        if self.data:
            payload['app_data'] = self.data

        if self.page:
            payload['page'] = {}

            if self.page.id:
                payload['page']['id'] = self.page.id

            if self.page.is_liked:
                payload['page']['liked'] = self.page.is_liked

            if self.page.is_admin:
                payload['page']['admin'] = self.page.is_admin

        if self.user:
            payload['user'] = {}

            if self.user.country:
                payload['user']['country'] = self.user.country

            if self.user.locale:
                payload['user']['locale'] = self.user.locale

            if self.user.age:
                payload['user']['age'] = {
                    'min': self.user.age[0],
                    'max': self.user.age[-1]
                }

            if self.user.oauth_token:

                if self.user.oauth_token.token:
                    payload['oauth_token'] = self.user.oauth_token.token

                if self.user.oauth_token.expires_at is None:
                    payload['expires_in'] = 0
                else:
                    payload['expires_in'] = int(time.mktime(self.user.oauth_token.expires_at.timetuple()))

                if self.user.oauth_token.issued_at:
                    payload['issued_at'] = int(time.mktime(self.user.oauth_token.issued_at.timetuple()))

        if self.user.id:
            payload['user_id'] = self.user.id

        encoded_payload = base64.urlsafe_b64encode(
            json.dumps(payload, separators=(',', ':')).encode('utf-8')
        )

        encoded_signature = base64.urlsafe_b64encode(hmac.new(
            self.application_secret_key.encode('utf-8'),
            encoded_payload,
            hashlib.sha256
        ).digest())

        return '%(signature)s.%(payload)s' % {
            'signature': encoded_signature,
            'payload': encoded_payload
        }
267007
def to_representation(self, value):
        """"""
        content_type = ContentType.objects.get_for_id(value)
        return "_".join(content_type.natural_key())
17823
protected function generateFiles()
    {
        foreach ($this->files as $key => $file) {
            $file = $this->formatContent($file);

            $this->makeFile($key, $file);
        }
    }
890341
def generate_index_file(filename):
    """"""
    with open(filename, 'w') as file:
        content = open(os.path.join(os.path.dirname(__file__), 'templates/index_page.html'), 'r').read()
        file.write(content)
1038117
function generateId () {
    var now = Date.now()
    if (now <= this.lastTime) {
      now = this.lastTime
      this.sequence += 1
    } else {
      this.lastTime = now
      this.sequence = 0
    }
    return now + ' ' + this.nodeId + ' ' + this.sequence
  }
1261605
def generate_security_data(self):
        """"""
        timestamp = int(time.time())
        security_dict = {
            'content_type': str(self.target_object._meta),
            'object_pk': str(self.target_object._get_pk_val()),
            'timestamp': str(timestamp),
            'security_hash': self.initial_security_hash(timestamp),
        }
        return security_dict
578561
def generate_help():
  """"""
  help_text = '\nAvailable recipes:\n\n'
  recipes = config.Config.get_registered_recipes()
  for contents, _, _ in sorted(recipes, key=lambda k: k[0]['name']):
    help_text += ' {0:<35s}{1:s}\n'.format(
        contents['name'], contents.get('short_description', 'No description'))
  return help_text
474657
def _handle_content(self, relpath, params):
    """"""
    abspath = os.path.normpath(os.path.join(self._root, relpath))
    if os.path.isfile(abspath):
      with open(abspath, 'rb') as infile:
        content = infile.read()
    else:
      content = 'No file found at {}'.format(abspath).encode('utf-8')
    content_type = mimetypes.guess_type(abspath)[0] or 'text/plain'
    if not content_type.startswith('text/') and not content_type == 'application/xml':
      # Binary file. Display it as hex, split into lines.
      n = 120  # Display lines of this max size.
      content = repr(content)[1:-1]  # Will escape non-printables etc, dropping surrounding quotes.
      content = '\n'.join([content[i:i + n] for i in range(0, len(content), n)])
      prettify = False
      prettify_extra_langs = []
    else:
      prettify = True
      if self._settings.assets_dir:
        prettify_extra_dir = os.path.join(self._settings.assets_dir, 'js', 'prettify_extra_langs')
        prettify_extra_langs = [{'name': x} for x in os.listdir(prettify_extra_dir)]
      else:
        # TODO: Find these from our package, somehow.
        prettify_extra_langs = []
    linenums = True
    args = {'prettify_extra_langs': prettify_extra_langs, 'content': content,
            'prettify': prettify, 'linenums': linenums}
    content = self._renderer.render_name('file_content.html', args).encode("utf-8")
    self._send_content(content, 'text/html')
995451
def generate_id(self, obj):
        """"""
        object_type = type(obj).__name__.lower()
        return '{}_{}'.format(object_type, self.get_object_id(obj))
26922
def _ids(self):
        """"""
        for pk in self._pks:
            yield getattr(self, pk)

        for pk in self._pks:

            try:
                yield str(getattr(self, pk))
            except ValueError:
                pass
140633
def pretty(self):
        """"""
        lines = list()
        for index, record in enumerate(self._records):
            lines.append(("record {0}".format(index+1),))
            lines.append(("  type", repr(record.type)))
            lines.append(("  name", repr(record.name)))
            lines.append(("  data", repr(record.data)))
        lwidth = max([len(line[0]) for line in lines])
        lines = [(line[0].ljust(lwidth),) + line[1:] for line in lines]
        lines = [" = ".join(line) for line in lines]
        return ("\n").join([line for line in lines])
1121906
def generate_id(self, portal_type, batch_size = None):
        
        plone = getSite()
        portal_id = plone.getId()

        if portal_type == 'News Item':
            portal_type = 'NewsItem'

        idserver_url = os.environ.get('IDServerURL')
        try:
            if batch_size:
                # GET
                f = urllib.urlopen('%s/%s%s?%s' % (
                        idserver_url,
                        portal_id,
                        portal_type,
                        urllib.urlencode({'batch_size': batch_size}))
                        )
            else:
                f = urllib.urlopen('%s/%s%s' % (
                    idserver_url, portal_id, portal_type
                    )
                )
            id = f.read()
            f.close()
        except:
            from sys import exc_info
            info = exc_info()
            import zLOG; zLOG.LOG('INFO', 0, '', 'generate_id raised exception: %s, %s \n idserver_url: %s' % (info[0], info[1], idserver_url))
            raise IDServerUnavailable(_('ID Server unavailable'))
        return id
1279275
function getContentUid(content) {
    var id = content.id_;
    if (!id)
      id = content.id_ = contentUidCounter++;
    return id;
  }
570895
def _htmlify_text(self, s):
    """"""
    colored = self._handle_ansi_color_codes(html.escape(s))
    return linkify(self._buildroot, colored, self._linkify_memo).replace('\n', '</br>')
876235
def flatten_tree_to_ident_hashes(item_or_tree,
                                 lucent_id=TRANSLUCENT_BINDER_ID):
    """"""
    if 'contents' in item_or_tree:
        tree = item_or_tree
        if tree['id'] != lucent_id:
            yield tree['id']
        for i in tree['contents']:
            # yield from flatten_tree_to_ident_hashs(i, lucent_id)
            for x in flatten_tree_to_ident_hashes(i, lucent_id):
                yield x
    else:
        item = item_or_tree
        yield item['id']