Python types.StringTypes() Examples

The following are 30 code examples of types.StringTypes(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module types , or try the search function .
Example #1
Source File: wvlib.py    From link-prediction_with_deep-learning with MIT License 6 votes vote down vote up
def similarity(self, v1, v2):
        """Return cosine similarity of given words or vectors.

        If v1/v2 is a string, look up the corresponding word vector.
        This is not particularly efficient function. Instead of many
        invocations, consider word_similarity() or direct computation.
        """
        
        vs = [v1, v2]
        for i, v in enumerate(vs):
            if isinstance(v, StringTypes):
                v = self.word_to_unit_vector(v)
            else:
                v = v/numpy.linalg.norm(v) # costly but safe
            vs[i] = v
        return numpy.dot(vs[0], vs[1]) 
Example #2
Source File: util.py    From earthengine with MIT License 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #3
Source File: simple_cache_test.py    From cluster-insight with Apache License 2.0 6 votes vote down vote up
def make_fancy_blob(self, name, timestamp_seconds, value):
    """Makes a blob containing "name", "timestamp" and "value" attributes.

    Args:
      name: the name of this object (the value of the 'id' attribute).
      timestamp_seconds: a timestamp in seconds.
      value: a value of any type.

    Returns:
    A dictionary containing 'id', 'timestamp', and 'value' key/value pairs.
    """
    assert isinstance(name, types.StringTypes)
    assert isinstance(timestamp_seconds, float)
    return {'id': name,
            'timestamp': utilities.seconds_to_timestamp(timestamp_seconds),
            'value': value} 
Example #4
Source File: context.py    From cluster-insight with Apache License 2.0 6 votes vote down vote up
def dump(self, output_format):
    """Returns the context graph in the specified format."""
    assert isinstance(output_format, types.StringTypes)

    self._context_resources.sort(key=lambda x: x['id'])
    self._context_relations.sort(key=lambda x: (x['source'], x['target']))

    if output_format == 'dot':
      return self.to_dot_graph()
    elif output_format == 'context_graph':
      return self.to_context_graph()
    elif output_format == 'resources':
      return self.to_context_resources()
    else:
      msg = 'invalid dump() output_format: %s' % output_format
      app.logger.error(msg)
      raise collector_error.CollectorError(msg) 
Example #5
Source File: collector_test.py    From cluster-insight with Apache License 2.0 6 votes vote down vote up
def count_relations(self, output, type_name,
                      source_type=None, target_type=None):
    """Count relations of the specified type (e.g., "contains").

    If the source type and/or target type is specified (e.g., "Node", "Pod",
    etc.), count only relations that additionally match that constraint.
    """
    assert isinstance(output, dict)
    assert isinstance(type_name, types.StringTypes)
    if not isinstance(output.get('relations'), list):
      return 0

    n = 0
    for r in output.get('relations'):
      assert isinstance(r, dict)
      if r['type'] != type_name:
        continue
      if source_type and r['source'].split(':')[0] != source_type:
        continue
      if target_type and r['target'].split(':')[0] != target_type:
        continue
      n += 1

    return n 
Example #6
Source File: util.py    From splunk-ref-pas-code with Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #7
Source File: influx.py    From kotori with GNU Affero General Public License v3.0 6 votes vote down vote up
def data_to_float(self, data):
        return convert_floats(data)

        for key, value in data.iteritems():

            # Sanity checks
            if type(value) in types.StringTypes:
                continue

            if value is None:
                data[key] = None
                continue

            # Convert to float
            try:
                data[key] = float(value)
            except (TypeError, ValueError) as ex:
                log.warn(u'Measurement "{key}: {value}" float conversion failed: {ex}', key=key, value=value, ex=ex) 
Example #8
Source File: util.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #9
Source File: util.py    From billing-export-python with Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #10
Source File: microdom.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
                 nsprefixes={}, namespace=''):
        if self.raw:
            val = self.nodeValue
            if not isinstance(val, StringTypes):
                val = str(self.nodeValue)
        else:
            v = self.nodeValue
            if not isinstance(v, StringTypes):
                v = str(v)
            if strip:
                v = ' '.join(v.split())
            val = escape(v)
        if isinstance(val, UnicodeType):
            val = val.encode('utf8')
        stream.write(val) 
Example #11
Source File: zkutil.py    From pykit with MIT License 6 votes vote down vote up
def parse_lock_id(data_str):
    """
    Parse string generated by lock_id()
    """

    node_id, ip, process_id, _uuid = (
        data_str.split('-', 3) + ([None] * 4))[:4]

    if type(process_id) in types.StringTypes and process_id.isdigit():
        process_id = int(process_id)
    else:
        process_id = None

    rst = {
        'node_id': node_id,
        'ip': ip,
        'process_id': process_id,
        'uuid': _uuid,
        'txid': None
    }

    if node_id.startswith('txid:'):
        rst['txid'] = node_id.split(':', 1)[1]

    return rst 
Example #12
Source File: net.py    From pykit with MIT License 6 votes vote down vote up
def is_ip4(ip):

    if type(ip) not in types.StringTypes:
        return False

    ip = ip.split('.')

    for s in ip:

        if not s.isdigit():
            return False

        i = int(s)
        if i < 0 or i > 255:
            return False

    return len(ip) == 4 
Example #13
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):

        """This is similar to expect(), but uses plain string matching instead
        of compiled regular expressions in 'pattern_list'. The 'pattern_list'
        may be a string; a list or other sequence of strings; or TIMEOUT and
        EOF.

        This call might be faster than expect() for two reasons: string
        searching is faster than RE matching and it is possible to limit the
        search to just the end of the input buffer.

        This method is also useful when you don't want to have to worry about
        escaping regular expression characters that you want to match."""

        if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF):
            pattern_list = [pattern_list]
        return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize) 
Example #14
Source File: util.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example #15
Source File: recipe-580623.py    From code with MIT License 6 votes vote down vote up
def getint(v):
    import types
    # extract digits from a string to form an integer
    try:
        return int(v)
    except ValueError:
        pass
    if not isinstance(v, types.StringTypes):
        return 0
    a = "0"
    for d in v:
        if d in "0123456789":
            a += d
    return int(a)

#==============================================================================
# define scale factor for displaying page images (20% larger)
#============================================================================== 
Example #16
Source File: wvlib.py    From link-prediction_with_deep-learning with MIT License 5 votes vote down vote up
def approximate_similarity(self, v1, v2, bits=None):
        """Return approximate cosine similarity of given words or vectors.

        Uses random hyperplane-based locality sensitive hashing (LSH)
        with given number of bits. If bits is None, estimate number of
        bits to use.

        LSH is initialized on the first invocation, which may take
        long for large numbers of word vectors. For a small number of
        invocations, similarity() may be more efficient.
        """

        if self._w2h_lsh is None or (bits is not None and bits != self._w2h_lsh.bits):
            if not with_gmpy:
                logging.warning('gmpy not available, approximate similarity '
                                'may be slow.')
            self._w2h_lsh = self._initialize_lsh(bits, fill=False)
            self._w2h_map = {}
            logging.info('init word-to-hash map: start')
            for w, v in self:
                self._w2h_map[w] = self._w2h_lsh.hash(v)
            logging.info('init word-to-hash map: done')            

        hashes = []
        for v in (v1, v2):
            if isinstance(v, StringTypes):
                h = self._w2h_map[v]
            else:
                h = self._w2h_lsh.hash(v)
            hashes.append(h)

        return self._w2h_lsh.hash_similarity(hashes[0], hashes[1]) 
Example #17
Source File: wvlib.py    From link-prediction_with_deep-learning with MIT License 5 votes vote down vote up
def nearest(self, v, n=10, exclude=None, candidates=None):
        """Return nearest n words and similarities for given word or vector,
        excluding given words.

        If v is a string, look up the corresponding word vector.
        If exclude is None and v is a string, exclude v.
        If candidates is not None, only consider (word, vector)
        values from iterable candidates.
        Return value is a list of (word, similarity) pairs.
        """

        if isinstance(v, StringTypes):
            v, w = self.word_to_unit_vector(v), v
        else:
            v, w = v/numpy.linalg.norm(v), None
        if exclude is None:
            exclude = [] if w is None else set([w])
        if not self._normalized:
            sim = partial(self._item_similarity, v=v)
        else:
            sim = partial(self._item_similarity_normalized, v=v)
        if candidates is None:
            candidates = self.word_to_vector_mapping().iteritems()
        nearest = heapq.nlargest(n+len(exclude), candidates, sim)
        wordsim = [(p[0], sim(p)) for p in nearest if p[0] not in exclude]
        return wordsim[:n] 
Example #18
Source File: datastore_viewer.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def format(self, value):
    if isinstance(value, types.StringTypes):
      return value
    else:
      return str(value) 
Example #19
Source File: file_watcher.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def get_file_watcher(directories, use_mtime_file_watcher):
  """Returns an instance that monitors a hierarchy of directories.

  Args:
    directories: A list representing the paths of the directories to monitor.
    use_mtime_file_watcher: A bool containing whether to use mtime polling to
        monitor file changes even if other options are available on the current
        platform.

  Returns:
    A FileWatcher appropriate for the current platform. start() must be called
    before has_changes().
  """
  assert not isinstance(directories, types.StringTypes), 'expected list got str'
  if len(directories) != 1:
    return _MultipleFileWatcher(directories, use_mtime_file_watcher)

  directory = directories[0]
  if use_mtime_file_watcher:
    return mtime_file_watcher.MtimeFileWatcher(directory)
  elif sys.platform.startswith('linux'):
    return inotify_file_watcher.InotifyFileWatcher(directory)
  elif sys.platform.startswith('win'):
    return win32_file_watcher.Win32FileWatcher(directory)
  return mtime_file_watcher.MtimeFileWatcher(directory)

  # NOTE: The Darwin-specific watcher implementation (found in the deleted file
  # fsevents_file_watcher.py) was incorrect - the Mac OS X FSEvents
  # implementation does not detect changes in symlinked files or directories. It
  # also does not provide file-level change precision before Mac OS 10.7.
  #
  # It is still possible to provide an efficient implementation by watching all
  # symlinked directories and using mtime checking for symlinked files. On any
  # change in a directory, it would have to be rescanned to see if a new
  # symlinked file or directory was added. It also might be possible to use
  # kevents instead of the Carbon API to detect files changes. 
Example #20
Source File: kano_combobox.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def set_items(self, items):
        # use this to set a list of string items for the dropdown menu
        # it makes sure the parameter is actually a List which contains Strings
        if not isinstance(items, types.ListType):
            raise TypeError("KanoComboBox: set_items(): You must supply a List when setting items")

        for item in items:
            if not isinstance(item, types.StringTypes):
                raise TypeError("KanoComboBox: append(): You must supply a String when appending text")

        self.items = list(items)
        self.update_dropdown() 
Example #21
Source File: kano_combobox.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def append(self, text):
        # use this to append items to the dropdown menu
        if not isinstance(text, types.StringTypes):
            raise TypeError("KanoComboBox: append(): You must supply a String when appending text")
        self.items.append(text)
        self.update_dropdown() 
Example #22
Source File: optparse.py    From meddle with MIT License 5 votes vote down vote up
def add_option(self, *args, **kwargs):
        """add_option(Option)
           add_option(opt_str, ..., kwarg=val, ...)
        """
        if type(args[0]) in types.StringTypes:
            option = self.option_class(*args, **kwargs)
        elif len(args) == 1 and not kwargs:
            option = args[0]
            if not isinstance(option, Option):
                raise TypeError, "not an Option instance: %r" % option
        else:
            raise TypeError, "invalid arguments"

        self._check_conflict(option)

        self.option_list.append(option)
        option.container = self
        for opt in option._short_opts:
            self._short_opt[opt] = option
        for opt in option._long_opts:
            self._long_opt[opt] = option

        if option.dest is not None:     # option has a dest, we need a default
            if option.default is not NO_DEFAULT:
                self.defaults[option.dest] = option.default
            elif option.dest not in self.defaults:
                self.defaults[option.dest] = None

        return option 
Example #23
Source File: inspect.py    From meddle with MIT License 5 votes vote down vote up
def getdoc(object):
    """Get the documentation string for an object.

    All tabs are expanded to spaces.  To clean up docstrings that are
    indented to line up with blocks of code, any whitespace than can be
    uniformly removed from the second line onwards is removed."""
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, types.StringTypes):
        return None
    return cleandoc(doc) 
Example #24
Source File: simple_cache.py    From cluster-insight with Apache License 2.0 5 votes vote down vote up
def lookup(self, label, now=None):
    """Lookup the data with the given label in the cache.

    Args:
      label: the label of the data. must be a string. may be empty.
      now: current time in seconds. If 'now' is None, the cached entry is
        compared with the current wallclock time. Otherwise the cached entry
        is compared with the value of 'now'.

    Returns:
    When the given label has recent data in the cache ('update_timestamp'
    less than self._max_data_age_seconds seconds old), returns a tuple
    (deep copy of cached value, create_timestamp_of_cached_data).
    When the given label was not found in the cache or its data is too old,
    returns the tuple (None, None).
    """
    assert isinstance(label, types.StringTypes)
    assert (now is None) or isinstance(now, float)

    self._lock.acquire()
    ts_seconds = time.time() if now is None else now
    if ((label in self._label_to_tuple) and
        (ts_seconds < (self._label_to_tuple[label].update_timestamp +
                       self._max_data_age_seconds))):
      # a cache hit
      assert self._label_to_tuple[label].value is not None
      value, timestamp = (copy.deepcopy(self._label_to_tuple[label].value),
                          self._label_to_tuple[label].create_timestamp)

    else:
      value, timestamp = (None, None)

    self._lock.release()
    return (value, timestamp) 
Example #25
Source File: collector_error.py    From cluster-insight with Apache License 2.0 5 votes vote down vote up
def __init__(self, message):
    Exception.__init__(self)
    assert isinstance(message, types.StringTypes)
    self._message = message 
Example #26
Source File: utilities.py    From cluster-insight with Apache License 2.0 5 votes vote down vote up
def get_attribute(obj, names_list):
  """Applies the attribute names in 'names_list' on 'obj' to get a value.

  get_attribute() is an extension of the get() function.
  If applies get() successively on a given initial object.
  If any of the intermediate attributes is missing or the object is no
  longer a dictionary, this function returns None.

  For example, calling get_attributes(container, ['Config', 'Image'])
  will attempt to fetch container['Config']['Image'] and return None
  if this attribute or any of its parents is not found.

  Args:
    obj: the object to fetch the attributes from.
    names_list: a list of strings specifying the name of the attributes to
      fetch successively from 'obj'.

  Returns:
  The attribute value or None if any of the intermediate values is not a
  dictionary of any of the attributes in 'names_list' was not found.
  """
  assert isinstance(names_list, list)
  v = obj
  for name in names_list:
    assert isinstance(name, types.StringTypes)
    if isinstance(v, dict) and (name in v):
      v = v[name]
    else:
      return None

  return v 
Example #27
Source File: collector_test.py    From cluster-insight with Apache License 2.0 5 votes vote down vote up
def count_resources(self, output, type_name):
    assert isinstance(output, dict)
    assert isinstance(type_name, types.StringTypes)
    if not isinstance(output.get('resources'), list):
      return 0

    n = 0
    for r in output.get('resources'):
      assert utilities.is_wrapped_object(r)
      if r.get('type') == type_name:
        n += 1

    return n 
Example #28
Source File: collector_test.py    From cluster-insight with Apache License 2.0 5 votes vote down vote up
def test_healthz(self):
    """Test the '/healthz' endpoint."""
    ret_value = self.app.get('/healthz')
    result = json.loads(ret_value.data)
    self.assertTrue(result.get('success'))
    health = result.get('health')
    self.assertTrue(isinstance(health, types.StringTypes))
    self.assertEqual('OK', health) 
Example #29
Source File: optparse.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def add_option(self, *args, **kwargs):
        """add_option(Option)
           add_option(opt_str, ..., kwarg=val, ...)
        """
        if type(args[0]) in types.StringTypes:
            option = self.option_class(*args, **kwargs)
        elif len(args) == 1 and not kwargs:
            option = args[0]
            if not isinstance(option, Option):
                raise TypeError, "not an Option instance: %r" % option
        else:
            raise TypeError, "invalid arguments"

        self._check_conflict(option)

        self.option_list.append(option)
        option.container = self
        for opt in option._short_opts:
            self._short_opt[opt] = option
        for opt in option._long_opts:
            self._long_opt[opt] = option

        if option.dest is not None:     # option has a dest, we need a default
            if option.default is not NO_DEFAULT:
                self.defaults[option.dest] = option.default
            elif option.dest not in self.defaults:
                self.defaults[option.dest] = None

        return option 
Example #30
Source File: inspect.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def getdoc(object):
    """Get the documentation string for an object.

    All tabs are expanded to spaces.  To clean up docstrings that are
    indented to line up with blocks of code, any whitespace than can be
    uniformly removed from the second line onwards is removed."""
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, types.StringTypes):
        return None
    return cleandoc(doc)