repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
django-cumulus/django-cumulus
cumulus/storage.py
get_content_type
python
def get_content_type(name, content): if hasattr(content, "content_type"): content_type = content.content_type else: mime_type, encoding = mimetypes.guess_type(name) content_type = mime_type return content_type
Checks if the content_type is already set. Otherwise uses the mimetypes library to guess.
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/storage.py#L42-L52
null
import mimetypes import pyrax import re import warnings from gzip import GzipFile import hmac from time import time try: from haslib import sha1 as sha except: import sha try: from cStringIO import StringIO except ImportError: try: from StringIO import StringIO except ImportError: fr...
django-cumulus/django-cumulus
cumulus/storage.py
sync_headers
python
def sync_headers(cloud_obj, headers=None, header_patterns=HEADER_PATTERNS): if headers is None: headers = {} # don't set headers on directories content_type = getattr(cloud_obj, "content_type", None) if content_type == "application/directory": return matched_headers = {} for pat...
Overwrites the given cloud_obj's headers with the ones given as ``headers` and adds additional headers as defined in the HEADERS setting depending on the cloud_obj's file name.
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/storage.py#L67-L90
null
import mimetypes import pyrax import re import warnings from gzip import GzipFile import hmac from time import time try: from haslib import sha1 as sha except: import sha try: from cStringIO import StringIO except ImportError: try: from StringIO import StringIO except ImportError: fr...
django-cumulus/django-cumulus
cumulus/storage.py
get_gzipped_contents
python
def get_gzipped_contents(input_file): zbuf = StringIO() zfile = GzipFile(mode="wb", compresslevel=6, fileobj=zbuf) zfile.write(input_file.read()) zfile.close() return ContentFile(zbuf.getvalue())
Returns a gzipped version of a previously opened file's buffer.
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/storage.py#L93-L101
null
import mimetypes import pyrax import re import warnings from gzip import GzipFile import hmac from time import time try: from haslib import sha1 as sha except: import sha try: from cStringIO import StringIO except ImportError: try: from StringIO import StringIO except ImportError: fr...
django-cumulus/django-cumulus
cumulus/authentication.py
Auth._get_container
python
def _get_container(self): if not hasattr(self, "_container"): if self.use_pyrax: self._container = self.connection.create_container(self.container_name) else: self._container = None return self._container
Gets or creates the container.
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/authentication.py#L101-L110
null
class Auth(object): connection_kwargs = {} use_pyrax = CUMULUS["USE_PYRAX"] use_snet = CUMULUS["SERVICENET"] region = CUMULUS["REGION"] username = CUMULUS["USERNAME"] api_key = CUMULUS["API_KEY"] auth_url = CUMULUS["AUTH_URL"] auth_tenant_id = CUMULUS["AUTH_TENANT_ID"] auth_tenant_na...
django-cumulus/django-cumulus
cumulus/authentication.py
Auth._set_container
python
def _set_container(self, container): if self.use_pyrax: if container.cdn_ttl != self.ttl or not container.cdn_enabled: container.make_public(ttl=self.ttl) if hasattr(self, "_container_public_uri"): delattr(self, "_container_public_uri") self._conta...
Sets the container (and, if needed, the configured TTL on it), making the container publicly available.
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/authentication.py#L112-L122
null
class Auth(object): connection_kwargs = {} use_pyrax = CUMULUS["USE_PYRAX"] use_snet = CUMULUS["SERVICENET"] region = CUMULUS["REGION"] username = CUMULUS["USERNAME"] api_key = CUMULUS["API_KEY"] auth_url = CUMULUS["AUTH_URL"] auth_tenant_id = CUMULUS["AUTH_TENANT_ID"] auth_tenant_na...
django-cumulus/django-cumulus
cumulus/authentication.py
Auth._get_object
python
def _get_object(self, name): if self.use_pyrax: try: return self.container.get_object(name) except pyrax.exceptions.NoSuchObject: return None elif swiftclient: try: return self.container.get_object(name) exce...
Helper function to retrieve the requested Object.
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/authentication.py#L157-L172
null
class Auth(object): connection_kwargs = {} use_pyrax = CUMULUS["USE_PYRAX"] use_snet = CUMULUS["SERVICENET"] region = CUMULUS["REGION"] username = CUMULUS["USERNAME"] api_key = CUMULUS["API_KEY"] auth_url = CUMULUS["AUTH_URL"] auth_tenant_id = CUMULUS["AUTH_TENANT_ID"] auth_tenant_na...
django-cumulus/django-cumulus
cumulus/context_processors.py
cdn_url
python
def cdn_url(request): cdn_url, ssl_url = _get_container_urls(CumulusStorage()) static_url = settings.STATIC_URL return { "CDN_URL": cdn_url + static_url, "CDN_SSL_URL": ssl_url + static_url, }
A context processor that exposes the full CDN URL in templates.
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/context_processors.py#L19-L29
[ "def _get_container_urls(swiftclient_storage):\n cdn_url = swiftclient_storage.container.cdn_uri\n ssl_url = swiftclient_storage.container.cdn_ssl_uri\n\n return cdn_url, ssl_url\n" ]
from urlparse import urlparse from django.conf import settings from cumulus.storage import CumulusStorage, CumulusStaticStorage def _is_ssl_uri(uri): return urlparse(uri).scheme == "https" def _get_container_urls(swiftclient_storage): cdn_url = swiftclient_storage.container.cdn_uri ssl_url = swiftclie...
django-cumulus/django-cumulus
cumulus/context_processors.py
static_cdn_url
python
def static_cdn_url(request): cdn_url, ssl_url = _get_container_urls(CumulusStaticStorage()) static_url = settings.STATIC_URL return { "STATIC_URL": cdn_url + static_url, "STATIC_SSL_URL": ssl_url + static_url, "LOCAL_STATIC_URL": static_url, }
A context processor that exposes the full static CDN URL as static URL in templates.
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/context_processors.py#L32-L44
[ "def _get_container_urls(swiftclient_storage):\n cdn_url = swiftclient_storage.container.cdn_uri\n ssl_url = swiftclient_storage.container.cdn_ssl_uri\n\n return cdn_url, ssl_url\n" ]
from urlparse import urlparse from django.conf import settings from cumulus.storage import CumulusStorage, CumulusStaticStorage def _is_ssl_uri(uri): return urlparse(uri).scheme == "https" def _get_container_urls(swiftclient_storage): cdn_url = swiftclient_storage.container.cdn_uri ssl_url = swiftclie...
marrow/cinje
cinje/inline/comment.py
Comment.match
python
def match(self, context, line): stripped = line.stripped return stripped.startswith('#') and not stripped.startswith('#{')
Match lines prefixed with a hash ("#") mark that don't look like text.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/comment.py#L18-L21
null
class Comment(object): """Line comment handler. This handles not emitting double-hash comments and has a high priority to prevent other processing of commented-out lines. Syntax: # <comment> ## <hidden comment> """ priority = -90 def __call__(self, context): """Emit comments into the final code that ...
marrow/cinje
cinje/util.py
stream
python
def stream(input, encoding=None, errors='strict'): input = (i for i in input if i) # Omits `None` (empty wrappers) and empty chunks. if encoding: # Automatically, and iteratively, encode the text if requested. input = iterencode(input, encoding, errors=errors) return input
Safely iterate a template generator, ignoring ``None`` values and optionally stream encoding. Used internally by ``cinje.flatten``, this allows for easy use of a template generator as a WSGI body.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L71-L82
null
# encoding: utf-8 from __future__ import unicode_literals """Convienent utilities.""" # ## Imports import sys from codecs import iterencode from inspect import isfunction, isclass from operator import methodcaller from collections import deque, namedtuple, Sized, Iterable from pkg_resources import iter_entry_point...
marrow/cinje
cinje/util.py
flatten
python
def flatten(input, file=None, encoding=None, errors='strict'): input = stream(input, encoding, errors) if file is None: # Exit early if we're not writing to a file. return b''.join(input) if encoding else ''.join(input) counter = 0 for chunk in input: file.write(chunk) counter += len(chunk) return...
Return a flattened representation of a cinje chunk stream. This has several modes of operation. If no `file` argument is given, output will be returned as a string. The type of string will be determined by the presence of an `encoding`; if one is given the returned value is a binary string, otherwise the native u...
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L85-L111
[ "def stream(input, encoding=None, errors='strict'):\n\t\"\"\"Safely iterate a template generator, ignoring ``None`` values and optionally stream encoding.\n\n\tUsed internally by ``cinje.flatten``, this allows for easy use of a template generator as a WSGI body.\n\t\"\"\"\n\n\tinput = (i for i in input if i) # Omi...
# encoding: utf-8 from __future__ import unicode_literals """Convienent utilities.""" # ## Imports import sys from codecs import iterencode from inspect import isfunction, isclass from operator import methodcaller from collections import deque, namedtuple, Sized, Iterable from pkg_resources import iter_entry_point...
marrow/cinje
cinje/util.py
fragment
python
def fragment(string, name="anonymous", **context): if isinstance(string, bytes): string = string.decode('utf-8') if ": def" in string or ":def" in string: code = string.encode('utf8').decode('cinje') name = None else: code = ": def {name}\n\n{string}".format( name = name, string = string, ).en...
Translate a template fragment into a callable function. **Note:** Use of this function is discouraged everywhere except tests, as no caching is implemented at this time. Only one function may be declared, either manually, or automatically. If automatic defintition is chosen the resulting function takes no argume...
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L114-L146
null
# encoding: utf-8 from __future__ import unicode_literals """Convienent utilities.""" # ## Imports import sys from codecs import iterencode from inspect import isfunction, isclass from operator import methodcaller from collections import deque, namedtuple, Sized, Iterable from pkg_resources import iter_entry_point...
marrow/cinje
cinje/util.py
iterate
python
def iterate(obj): global next, Iteration next = next Iteration = Iteration total = len(obj) if isinstance(obj, Sized) else None iterator = iter(obj) first = True last = False i = 0 try: value = next(iterator) except StopIteration: return while True: try: next_value = next(iterator) except ...
Loop over an iterable and track progress, including first and last state. On each iteration yield an Iteration named tuple with the first and last flags, current element index, total iterable length (if possible to acquire), and value, in that order. for iteration in iterate(something): iteration.value # Do...
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L159-L211
null
# encoding: utf-8 from __future__ import unicode_literals """Convienent utilities.""" # ## Imports import sys from codecs import iterencode from inspect import isfunction, isclass from operator import methodcaller from collections import deque, namedtuple, Sized, Iterable from pkg_resources import iter_entry_point...
marrow/cinje
cinje/util.py
chunk
python
def chunk(line, mapping={None: 'text', '${': 'escape', '#{': 'bless', '&{': 'args', '%{': 'format', '@{': 'json'}): skipping = 0 # How many closing parenthesis will we need to skip? start = None # Starting position of current match. last = 0 i = 0 text = line.line while i < len(text): if start is not ...
Chunkify and "tag" a block of text into plain text and code sections. The first delimeter is blank to represent text sections, and keep the indexes aligned with the tags. Values are yielded in the form (tag, text).
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L253-L294
[ "def clone(self, **kw):\n\tvalues = dict(\n\t\t\tnumber = self.number,\n\t\t\tline = self.line,\n\t\t\tscope = self.scope,\n\t\t\tkind = self.kind,\n\t\t)\n\n\tvalues.update(kw)\n\n\tinstance = self.__class__(**values)\n\n\treturn instance\n" ]
# encoding: utf-8 from __future__ import unicode_literals """Convienent utilities.""" # ## Imports import sys from codecs import iterencode from inspect import isfunction, isclass from operator import methodcaller from collections import deque, namedtuple, Sized, Iterable from pkg_resources import iter_entry_point...
marrow/cinje
cinje/util.py
Context.prepare
python
def prepare(self): self.scope = 0 self.mapping = deque([0]) self._handler = [i() for i in sorted(self.handlers, key=lambda handler: handler.priority)]
Prepare the ordered list of transformers and reset context state to initial.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L468-L472
null
class Context(object): """The processing context for translating cinje source into Python source. This is the primary entry point for translation. """ __slots__ = ('input', 'scope', 'flag', '_handler', 'templates', 'handlers', 'mapping') def __init__(self, input): self.input = Lines(input.decode('utf8') if is...
marrow/cinje
cinje/util.py
Context.stream
python
def stream(self): if 'init' not in self.flag: root = True self.prepare() else: root = False # Track which lines were generated in response to which lines of source code. # The end result is that there is one entry here for every line emitted, each integer representing the source # line number t...
The workhorse of cinje: transform input lines and emit output lines. After constructing an instance with a set of input lines iterate this property to generate the template.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L475-L511
[ "def prepare(self):\n\t\"\"\"Prepare the ordered list of transformers and reset context state to initial.\"\"\"\n\tself.scope = 0\n\tself.mapping = deque([0])\n\tself._handler = [i() for i in sorted(self.handlers, key=lambda handler: handler.priority)]\n", "def classify(self, line):\n\t\"\"\"Identify the correct ...
class Context(object): """The processing context for translating cinje source into Python source. This is the primary entry point for translation. """ __slots__ = ('input', 'scope', 'flag', '_handler', 'templates', 'handlers', 'mapping') def __init__(self, input): self.input = Lines(input.decode('utf8') if is...
marrow/cinje
cinje/util.py
Context.classify
python
def classify(self, line): for handler in self._handler: if handler.match(self, line): return handler
Identify the correct handler for a given line of input.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L513-L518
null
class Context(object): """The processing context for translating cinje source into Python source. This is the primary entry point for translation. """ __slots__ = ('input', 'scope', 'flag', '_handler', 'templates', 'handlers', 'mapping') def __init__(self, input): self.input = Lines(input.decode('utf8') if is...
marrow/cinje
cinje/block/module.py
red
python
def red(numbers): line = 0 deltas = [] for value in numbers: deltas.append(value - line) line = value return b64encode(compress(b''.join(chr(i).encode('latin1') for i in deltas))).decode('latin1')
Encode the deltas to reduce entropy.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/block/module.py#L12-L22
null
# encoding: utf-8 from __future__ import unicode_literals from zlib import compress from base64 import b64encode from collections import deque from ..util import py, Line def red(numbers): """Encode the deltas to reduce entropy.""" line = 0 deltas = [] for value in numbers: deltas.append(value - line) li...
marrow/cinje
cinje/block/generic.py
Generic.match
python
def match(self, context, line): return line.kind == 'code' and line.partitioned[0] in self._both
Match code lines prefixed with a variety of keywords.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/block/generic.py#L56-L59
null
class Generic(object): """Block-level passthrough. Blocks must be terminated by ": end" markers. Support is included for chains of blocks of the expected types, without requiring ": end" markers between them. This block-level transformer handles: "if", "elif", and "else" conditional scopes; "while" and "for" loop...
marrow/cinje
cinje/inline/flush.py
flush_template
python
def flush_template(context, declaration=None, reconstruct=True): if declaration is None: declaration = Line(0, '') if {'text', 'dirty'}.issubset(context.flag): yield declaration.clone(line='yield "".join(_buffer)') context.flag.remove('text') # This will force a new buffer to be constructed. context.f...
Emit the code needed to flush the buffer. Will only emit the yield and clear if the buffer is known to be dirty.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/flush.py#L6-L26
[ "def ensure_buffer(context, separate=True):\n\tif 'text' in context.flag or 'buffer' not in context.flag:\n\t\treturn\n\n\tif separate: yield Line(0, \"\")\n\tyield Line(0, \"_buffer = []\")\n\n\tif not pypy:\n\t\tyield Line(0, \"__w, __ws = _buffer.extend, _buffer.append\")\n\n\tyield Line(0, \"\")\n\n\tcontext.fl...
# encoding: utf-8 from ..util import Line, ensure_buffer def flush_template(context, declaration=None, reconstruct=True): """Emit the code needed to flush the buffer. Will only emit the yield and clear if the buffer is known to be dirty. """ if declaration is None: declaration = Line(0, '') if {'text', 'di...
marrow/cinje
cinje/block/function.py
Function._optimize
python
def _optimize(self, context, argspec): argspec = argspec.strip() optimization = ", ".join(i + "=" + i for i in self.OPTIMIZE) split = None prefix = '' suffix = '' if argspec: matches = list(self.STARARGS.finditer(argspec)) if matches: split = matches[-1].span()[1] # Inject after, a la "...
Inject speedup shortcut bindings into the argument specification for a function. This assigns these labels to the local scope, avoiding a cascade through to globals(), saving time. This also has some unfortunate side-effects for using these sentinels in argument default values!
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/block/function.py#L33-L76
null
class Function(object): """Proces function declarations within templates. Syntax: : def <name> <arguments> : end """ priority = -50 # Patterns to search for bare *, *args, or **kwargs declarations. STARARGS = re.compile(r'(^|,\s*)\*([^*\s,]+|\s*,|$)') STARSTARARGS = re.compile(r'(^|,\s*)\*\*\S+') # Au...
marrow/cinje
cinje/inline/text.py
Text.wrap
python
def wrap(scope, lines, format=BARE_FORMAT): for line in iterate(lines): prefix = suffix = '' if line.first and line.last: prefix = format.single.prefix suffix = format.single.suffix else: prefix = format.multiple.prefix if line.first else format.intra.prefix suffix = format.multiple.su...
Wrap a stream of lines in armour. Takes a stream of lines, for example, the following single line: Line(1, "Lorem ipsum dolor.") Or the following multiple lines: Line(1, "Lorem ipsum") Line(2, "dolor") Line(3, "sit amet.") Provides a generator of wrapped lines. For a single line, the f...
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L36-L70
[ "def iterate(obj):\n\t\"\"\"Loop over an iterable and track progress, including first and last state.\n\n\tOn each iteration yield an Iteration named tuple with the first and last flags, current element index, total\n\titerable length (if possible to acquire), and value, in that order.\n\n\t\tfor iteration in itera...
class Text(object): """Identify and process contiguous blocks of template text.""" UNBUFFERED = UNBUFFERED_FORMAT BUFFERED = BUFFERED_FORMAT priority = -25 def match(self, context, line): """Identify if a line to be processed can be processed by this transformer.""" return line.kind == 'text' # This is co...
marrow/cinje
cinje/inline/text.py
Text.gather
python
def gather(input): try: line = input.next() except StopIteration: return lead = True buffer = [] # Gather contiguous (uninterrupted) lines of template text. while line.kind == 'text': value = line.line.rstrip().rstrip('\\') + ('' if line.continued else '\n') if lead and line.strippe...
Collect contiguous lines of text, preserving line numbers.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L73-L110
null
class Text(object): """Identify and process contiguous blocks of template text.""" UNBUFFERED = UNBUFFERED_FORMAT BUFFERED = BUFFERED_FORMAT priority = -25 def match(self, context, line): """Identify if a line to be processed can be processed by this transformer.""" return line.kind == 'text' # This is co...
marrow/cinje
cinje/inline/text.py
Text.process
python
def process(self, context, lines): handler = None for line in lines: for chunk in chunk_(line): if 'strip' in context.flag: chunk.line = chunk.stripped if not chunk.line: continue # Eliminate empty chunks, i.e. trailing text segments, ${}, etc. if not handler or handler[0] != ch...
Chop up individual lines into static and dynamic parts. Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different chunk types. The processor protocol here requires the method to accept values by yielding resulting lines while accepting sent chunks. Defer...
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L112-L162
[ "def chunk(line, mapping={None: 'text', '${': 'escape', '#{': 'bless', '&{': 'args', '%{': 'format', '@{': 'json'}):\n\t\"\"\"Chunkify and \"tag\" a block of text into plain text and code sections.\n\n\tThe first delimeter is blank to represent text sections, and keep the indexes aligned with the tags.\n\n\tValues ...
class Text(object): """Identify and process contiguous blocks of template text.""" UNBUFFERED = UNBUFFERED_FORMAT BUFFERED = BUFFERED_FORMAT priority = -25 def match(self, context, line): """Identify if a line to be processed can be processed by this transformer.""" return line.kind == 'text' # This is co...
marrow/cinje
cinje/inline/text.py
Text.process_text
python
def process_text(self, kind, context): result = None while True: chunk = yield None if chunk is None: if result: yield result.clone(line=repr(result.line)) return if not result: result = chunk continue result.line += chunk.line
Combine multiple lines of bare text and emit as a Python string literal.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L164-L182
null
class Text(object): """Identify and process contiguous blocks of template text.""" UNBUFFERED = UNBUFFERED_FORMAT BUFFERED = BUFFERED_FORMAT priority = -25 def match(self, context, line): """Identify if a line to be processed can be processed by this transformer.""" return line.kind == 'text' # This is co...
marrow/cinje
cinje/inline/text.py
Text.process_generic
python
def process_generic(self, kind, context): result = None while True: chunk = yield result if chunk is None: return result = chunk.clone(line='_' + kind + '(' + chunk.line + ')')
Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L185-L196
null
class Text(object): """Identify and process contiguous blocks of template text.""" UNBUFFERED = UNBUFFERED_FORMAT BUFFERED = BUFFERED_FORMAT priority = -25 def match(self, context, line): """Identify if a line to be processed can be processed by this transformer.""" return line.kind == 'text' # This is co...
marrow/cinje
cinje/inline/text.py
Text.process_format
python
def process_format(self, kind, context): result = None while True: chunk = yield result if chunk is None: return # We need to split the expression defining the format string from the values to pass when formatting. # We want to allow any Python expression, so we'll need to piggyback on...
Handle transforming format string + arguments into Python code.
train
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/inline/text.py#L198-L220
null
class Text(object): """Identify and process contiguous blocks of template text.""" UNBUFFERED = UNBUFFERED_FORMAT BUFFERED = BUFFERED_FORMAT priority = -25 def match(self, context, line): """Identify if a line to be processed can be processed by this transformer.""" return line.kind == 'text' # This is co...
KyleJamesWalker/yamlsettings
yamlsettings/extensions/base.py
YamlSettingsExtension.conform_query
python
def conform_query(cls, query): query = parse_qs(query, keep_blank_values=True) # Load yaml of passed values for key, vals in query.items(): # Multiple values of the same name could be passed use first # Also params without strings will be treated as true values ...
Converts the query string from a target uri, uses cls.default_query to populate default arguments. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.default_query will be set if not passe...
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/base.py#L15-L38
null
class YamlSettingsExtension: """Extension Interface""" protocols = () # Dictionary of expected kwargs and flag for json loading values (bool/int) default_query = {} not_found_exception = IOError @classmethod @classmethod def load_target(cls, scheme, path, fragment, username, ...
KyleJamesWalker/yamlsettings
yamlsettings/extensions/base.py
YamlSettingsExtension.load_target
python
def load_target(cls, scheme, path, fragment, username, password, hostname, port, query, load_method, **kwargs): raise NotImplementedError("load_target must be overridden")
Override this method to use values from the parsed uri to initialize the expected target.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/base.py#L41-L48
null
class YamlSettingsExtension: """Extension Interface""" protocols = () # Dictionary of expected kwargs and flag for json loading values (bool/int) default_query = {} not_found_exception = IOError @classmethod def conform_query(cls, query): """Converts the query string from a target u...
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry._discover
python
def _discover(self): for ep in pkg_resources.iter_entry_points('yamlsettings10'): ext = ep.load() if callable(ext): ext = ext() self.add(ext)
Find and install all extensions
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L39-L45
[ "def add(self, extension):\n \"\"\"Adds an extension to the registry\n\n :param extension: Extension object\n :type extension: yamlsettings.extensions.base.YamlSettingsExtension\n\n \"\"\"\n index = len(self.extensions)\n self.extensions[index] = extension\n for protocol in extension.protocols:...
class ExtensionRegistry(object): def __init__(self, extensions): """A registry that stores extensions to open and parse Target URIs :param extensions: A list of extensions. :type extensions: yamlsettings.extensions.base.YamlSettingsExtension """ self.registry = {} ...
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry.get_extension
python
def get_extension(self, protocol): if protocol not in self.registry: raise NoProtocolError("No protocol for %s" % protocol) index = self.registry[protocol] return self.extensions[index]
Retrieve extension for the given protocol :param protocol: name of the protocol :type protocol: string :raises NoProtocolError: no extension registered for protocol
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L47-L58
null
class ExtensionRegistry(object): def __init__(self, extensions): """A registry that stores extensions to open and parse Target URIs :param extensions: A list of extensions. :type extensions: yamlsettings.extensions.base.YamlSettingsExtension """ self.registry = {} ...
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry.add
python
def add(self, extension): index = len(self.extensions) self.extensions[index] = extension for protocol in extension.protocols: self.registry[protocol] = index
Adds an extension to the registry :param extension: Extension object :type extension: yamlsettings.extensions.base.YamlSettingsExtension
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L60-L70
null
class ExtensionRegistry(object): def __init__(self, extensions): """A registry that stores extensions to open and parse Target URIs :param extensions: A list of extensions. :type extensions: yamlsettings.extensions.base.YamlSettingsExtension """ self.registry = {} ...
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry._load_first
python
def _load_first(self, target_uris, load_method, **kwargs): if isinstance(target_uris, string_types): target_uris = [target_uris] # TODO: Move the list logic into the extension, otherwise a # load will always try all missing files first. # TODO: How would multiple protocols w...
Load first yamldict target found in uri list. :param target_uris: Uris to try and open :param load_method: load callback :type target_uri: list or string :type load_method: callback :returns: yamldict
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L72-L112
[ "def get_extension(self, protocol):\n \"\"\"Retrieve extension for the given protocol\n\n :param protocol: name of the protocol\n :type protocol: string\n :raises NoProtocolError: no extension registered for protocol\n\n \"\"\"\n if protocol not in self.registry:\n raise NoProtocolError(\"N...
class ExtensionRegistry(object): def __init__(self, extensions): """A registry that stores extensions to open and parse Target URIs :param extensions: A list of extensions. :type extensions: yamlsettings.extensions.base.YamlSettingsExtension """ self.registry = {} ...
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry.load
python
def load(self, target_uris, fields=None, **kwargs): yaml_dict = self._load_first( target_uris, yamlsettings.yamldict.load, **kwargs ) # TODO: Move this into the extension, otherwise every load from # a persistant location will refilter fields. if fields: y...
Load first yamldict target found in uri. :param target_uris: Uris to try and open :param fields: Fields to filter. Default: None :type target_uri: list or string :type fields: list :returns: yamldict
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L114-L133
[ "def _load_first(self, target_uris, load_method, **kwargs):\n \"\"\"Load first yamldict target found in uri list.\n\n :param target_uris: Uris to try and open\n :param load_method: load callback\n :type target_uri: list or string\n :type load_method: callback\n\n :returns: yamldict\n\n \"\"\"\n...
class ExtensionRegistry(object): def __init__(self, extensions): """A registry that stores extensions to open and parse Target URIs :param extensions: A list of extensions. :type extensions: yamlsettings.extensions.base.YamlSettingsExtension """ self.registry = {} ...
KyleJamesWalker/yamlsettings
yamlsettings/extensions/registry.py
ExtensionRegistry.load_all
python
def load_all(self, target_uris, **kwargs): ''' Load *all* YAML settings from a list of file paths given. - File paths in the list gets the priority by their orders of the list. ''' yaml_series = self._load_first( target_uris, yamlsettings.yamldict.loa...
Load *all* YAML settings from a list of file paths given. - File paths in the list gets the priority by their orders of the list.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/extensions/registry.py#L135-L149
[ "def _load_first(self, target_uris, load_method, **kwargs):\n \"\"\"Load first yamldict target found in uri list.\n\n :param target_uris: Uris to try and open\n :param load_method: load callback\n :type target_uri: list or string\n :type load_method: callback\n\n :returns: yamldict\n\n \"\"\"\n...
class ExtensionRegistry(object): def __init__(self, extensions): """A registry that stores extensions to open and parse Target URIs :param extensions: A list of extensions. :type extensions: yamlsettings.extensions.base.YamlSettingsExtension """ self.registry = {} ...
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
load_all
python
def load_all(stream): loader = YAMLDictLoader(stream) try: while loader.check_data(): yield loader.get_data() finally: loader.dispose()
Parse all YAML documents in a stream and produce corresponding YAMLDict objects.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L192-L202
null
"""Order-preserved, attribute-accessible dictionary object for YAML files """ # -*- coding: utf-8 -*- import yaml import yaml.constructor import collections class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https:...
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
dump
python
def dump(data, stream=None, **kwargs): return yaml.dump_all( [data], stream=stream, Dumper=YAMLDictDumper, **kwargs )
Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L263-L273
null
"""Order-preserved, attribute-accessible dictionary object for YAML files """ # -*- coding: utf-8 -*- import yaml import yaml.constructor import collections class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https:...
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
dump_all
python
def dump_all(data_list, stream=None, **kwargs): return yaml.dump_all( data_list, stream=stream, Dumper=YAMLDictDumper, **kwargs )
Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L276-L286
null
"""Order-preserved, attribute-accessible dictionary object for YAML files """ # -*- coding: utf-8 -*- import yaml import yaml.constructor import collections class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https:...
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
YAMLDict.traverse
python
def traverse(self, callback): ''' Traverse through all keys and values (in-order) and replace keys and values with the return values from the callback function. ''' def _traverse_node(path, node, callback): ret_val = callback(path, node) if ret_val...
Traverse through all keys and values (in-order) and replace keys and values with the return values from the callback function.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L46-L69
[ "def _traverse_node(path, node, callback):\n ret_val = callback(path, node)\n if ret_val is not None:\n # replace node with the return value\n node = ret_val\n else:\n # traverse deep into the hierarchy\n if isinstance(node, YAMLDict):\n for k, v in node.items():\n ...
class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https://github.com/mk-fg/layered-yaml-attrdict-config ''' def __init__(self, *args, **kwargs): super(YAMLDict, self).__init__(*args, **kwargs) ...
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
YAMLDict.update
python
def update(self, yaml_dict): ''' Update the content (i.e. keys and values) with yaml_dict. ''' def _update_node(base_node, update_node): if isinstance(update_node, YAMLDict) or \ isinstance(update_node, dict): if not (isinstance(base_node, YAMLDict...
Update the content (i.e. keys and values) with yaml_dict.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L71-L101
[ "def _update_node(base_node, update_node):\n if isinstance(update_node, YAMLDict) or \\\n isinstance(update_node, dict):\n if not (isinstance(base_node, YAMLDict)):\n # NOTE: A regular dictionary is replaced by a new\n # YAMLDict object.\n new_node = YAMLD...
class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https://github.com/mk-fg/layered-yaml-attrdict-config ''' def __init__(self, *args, **kwargs): super(YAMLDict, self).__init__(*args, **kwargs) ...
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
YAMLDict.rebase
python
def rebase(self, yaml_dict): ''' Use yaml_dict as self's new base and update with existing reverse of update. ''' base = yaml_dict.clone() base.update(self) self.clear() self.update(base)
Use yaml_dict as self's new base and update with existing reverse of update.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L110-L117
[ "def update(self, yaml_dict):\n ''' Update the content (i.e. keys and values) with yaml_dict.\n '''\n def _update_node(base_node, update_node):\n if isinstance(update_node, YAMLDict) or \\\n isinstance(update_node, dict):\n if not (isinstance(base_node, YAMLDict)):\n ...
class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https://github.com/mk-fg/layered-yaml-attrdict-config ''' def __init__(self, *args, **kwargs): super(YAMLDict, self).__init__(*args, **kwargs) ...
KyleJamesWalker/yamlsettings
yamlsettings/yamldict.py
YAMLDict.limit
python
def limit(self, keys): ''' Remove all keys other than the keys specified. ''' if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in remove_keys: self.pop(k)
Remove all keys other than the keys specified.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/yamldict.py#L119-L126
null
class YAMLDict(collections.OrderedDict): ''' Order-preserved, attribute-accessible dictionary object for YAML settings Improved from: https://github.com/mk-fg/layered-yaml-attrdict-config ''' def __init__(self, *args, **kwargs): super(YAMLDict, self).__init__(*args, **kwargs) ...
KyleJamesWalker/yamlsettings
yamlsettings/helpers.py
save
python
def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
Save YAML settings to the specified file path.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/helpers.py#L13-L17
[ "def dump(data, stream=None, **kwargs):\n \"\"\"\n Serialize YAMLDict into a YAML stream.\n If stream is None, return the produced string instead.\n \"\"\"\n return yaml.dump_all(\n [data],\n stream=stream,\n Dumper=YAMLDictDumper,\n **kwargs\n )\n" ]
"""Helper functions """ # -*- coding: utf-8 -*- from __future__ import print_function import os from yamlsettings import yamldict from yamlsettings.extensions import registry def save_all(yaml_dicts, filepath): ''' Save *all* YAML settings to the specified file path. ''' yamldict.dump_all(yaml_dic...
KyleJamesWalker/yamlsettings
yamlsettings/helpers.py
save_all
python
def save_all(yaml_dicts, filepath): ''' Save *all* YAML settings to the specified file path. ''' yamldict.dump_all(yaml_dicts, open(filepath, 'w'), default_flow_style=False)
Save *all* YAML settings to the specified file path.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/helpers.py#L20-L25
[ "def dump_all(data_list, stream=None, **kwargs):\n \"\"\"\n Serialize YAMLDict into a YAML stream.\n If stream is None, return the produced string instead.\n \"\"\"\n return yaml.dump_all(\n data_list,\n stream=stream,\n Dumper=YAMLDictDumper,\n **kwargs\n )\n" ]
"""Helper functions """ # -*- coding: utf-8 -*- from __future__ import print_function import os from yamlsettings import yamldict from yamlsettings.extensions import registry def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath...
KyleJamesWalker/yamlsettings
yamlsettings/helpers.py
update_from_file
python
def update_from_file(yaml_dict, filepaths): ''' Override YAML settings with loaded values from filepaths. - File paths in the list gets the priority by their orders of the list. ''' # load YAML settings with only fields in yaml_dict yaml_dict.update(registry.load(filepaths, list(yaml_dict))...
Override YAML settings with loaded values from filepaths. - File paths in the list gets the priority by their orders of the list.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/helpers.py#L28-L35
[ "def load(self, target_uris, fields=None, **kwargs):\n \"\"\"Load first yamldict target found in uri.\n\n :param target_uris: Uris to try and open\n :param fields: Fields to filter. Default: None\n :type target_uri: list or string\n :type fields: list\n\n :returns: yamldict\n\n \"\"\"\n yaml...
"""Helper functions """ # -*- coding: utf-8 -*- from __future__ import print_function import os from yamlsettings import yamldict from yamlsettings.extensions import registry def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath...
KyleJamesWalker/yamlsettings
yamlsettings/helpers.py
update_from_env
python
def update_from_env(yaml_dict, prefix=None): ''' Override YAML settings with values from the environment variables. - The letter '_' is delimit the hierarchy of the YAML settings such that the value of 'config.databases.local' will be overridden by CONFIG_DATABASES_LOCAL. ''' ...
Override YAML settings with values from the environment variables. - The letter '_' is delimit the hierarchy of the YAML settings such that the value of 'config.databases.local' will be overridden by CONFIG_DATABASES_LOCAL.
train
https://github.com/KyleJamesWalker/yamlsettings/blob/ddd7df2ca995ddf191b24c4d35e9dd28186e4535/yamlsettings/helpers.py#L38-L63
null
"""Helper functions """ # -*- coding: utf-8 -*- from __future__ import print_function import os from yamlsettings import yamldict from yamlsettings.extensions import registry def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath...
fmenabe/python-dokuwiki
dokuwiki.py
date
python
def date(date): date = date.value return (datetime.strptime(date[:-5], '%Y-%m-%dT%H:%M:%S') if len(date) == 24 else datetime.strptime(date, '%Y%m%dT%H:%M:%S'))
DokuWiki returns dates of `xmlrpclib`/`xmlrpc.client` ``DateTime`` type and the format changes between DokuWiki versions ... This function convert *date* to a `datetime` object.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L36-L44
null
# -*- coding: utf-8 -*- """This python module aims to manage `DokuWiki <https://www.dokuwiki.org/dokuwiki>`_ wikis by using the provided `XML-RPC API <https://www.dokuwiki.org/devel:xmlrpc>`_. It is compatible with python2.7 and python3+. Installation ------------ It is on `PyPi <https://pypi.python.org/pypi/dokuwik...
fmenabe/python-dokuwiki
dokuwiki.py
utc2local
python
def utc2local(date): date_offset = (datetime.now() - datetime.utcnow()) # Python < 2.7 don't have the 'total_seconds' method so calculate it by hand! date_offset = (date_offset.microseconds + (date_offset.seconds + date_offset.days * 24 * 3600) * 1e6) / 1e6 date_offset = int(round(dat...
DokuWiki returns date with a +0000 timezone. This function convert *date* to the local time.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L46-L55
null
# -*- coding: utf-8 -*- """This python module aims to manage `DokuWiki <https://www.dokuwiki.org/dokuwiki>`_ wikis by using the provided `XML-RPC API <https://www.dokuwiki.org/devel:xmlrpc>`_. It is compatible with python2.7 and python3+. Installation ------------ It is on `PyPi <https://pypi.python.org/pypi/dokuwik...
fmenabe/python-dokuwiki
dokuwiki.py
CookiesTransport.parse_response
python
def parse_response(self, response): try: for header in response.msg.get_all("Set-Cookie"): cookie = header.split(";", 1)[0] cookieKey, cookieValue = cookie.split("=", 1) self._cookies[cookieKey] = cookieValue finally: return Transpo...
parse and store cookie
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L74-L82
null
class CookiesTransport(Transport): """A Python3 xmlrpc.client.Transport subclass that retains cookies.""" def __init__(self): Transport.__init__(self) self._cookies = dict() def send_headers(self, connection, headers): if self._cookies: cookies = map(lambda x: x[0] + '='...
fmenabe/python-dokuwiki
dokuwiki.py
CookiesTransport2.parse_response
python
def parse_response(self, response): try: for header in response.getheader("set-cookie").split(", "): # filter 'expire' information if not header.startswith("D"): continue cookie = header.split(";", 1)[0] cookieKey, c...
parse and store cookie
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L97-L108
null
class CookiesTransport2(Transport): """A Python2 xmlrpclib.Transport subclass that retains cookies.""" def __init__(self): Transport.__init__(self) self._cookies = dict() def send_request(self, connection, handler, request_body): Transport.send_request(self, connection, handler, req...
fmenabe/python-dokuwiki
dokuwiki.py
DokuWiki.send
python
def send(self, command, *args, **kwargs): args = list(args) if kwargs: args.append(kwargs) method = self.proxy for elt in command.split('.'): method = getattr(method, elt) try: return method(*args) except Fault as err: if ...
Generic method for executing an XML-RPC *command*. *args* and *kwargs* are the arguments and parameters needed by the command.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L163-L185
null
class DokuWiki(object): """Initialize a connection to a DokuWiki wiki. *url*, *user* and *password* are respectively the URL, the login and the password for connecting to the wiki. *kwargs* are `xmlrpclib`/`xmlrpc.client` **ServerProxy** parameters. The exception `DokuWikiError` is raised if the au...
fmenabe/python-dokuwiki
dokuwiki.py
DokuWiki.add_acl
python
def add_acl(self, scope, user, permission): return self.send('plugin.acl.addAcl', scope, user, permission)
Add an `ACL <https://www.dokuwiki.org/acl>`_ rule that restricts the page/namespace *scope* to *user* (use *@group* syntax for groups) with *permission* level. It returns a boolean that indicate if the rule was correctly added.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L221-L227
[ "def send(self, command, *args, **kwargs):\n \"\"\"Generic method for executing an XML-RPC *command*. *args* and\n *kwargs* are the arguments and parameters needed by the command.\n \"\"\"\n args = list(args)\n if kwargs:\n args.append(kwargs)\n\n method = self.proxy\n for elt in command...
class DokuWiki(object): """Initialize a connection to a DokuWiki wiki. *url*, *user* and *password* are respectively the URL, the login and the password for connecting to the wiki. *kwargs* are `xmlrpclib`/`xmlrpc.client` **ServerProxy** parameters. The exception `DokuWikiError` is raised if the au...
fmenabe/python-dokuwiki
dokuwiki.py
_Pages.info
python
def info(self, page, version=None): return (self._dokuwiki.send('wiki.getPageInfoVersion', page, version) if version is not None else self._dokuwiki.send('wiki.getPageInfo', page))
Returns informations of *page*. Informations of the last version is returned if *version* is not set.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L281-L287
null
class _Pages(object): """This object regroup methods for managing pages of a DokuWiki. This object is accessible from the ``pages`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.pages.list() """ def __init__(self, dokuwiki): self....
fmenabe/python-dokuwiki
dokuwiki.py
_Pages.get
python
def get(self, page, version=None): return (self._dokuwiki.send('wiki.getPageVersion', page, version) if version is not None else self._dokuwiki.send('wiki.getPage', page))
Returns the content of *page*. The content of the last version is returned if *version* is not set.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L289-L295
null
class _Pages(object): """This object regroup methods for managing pages of a DokuWiki. This object is accessible from the ``pages`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.pages.list() """ def __init__(self, dokuwiki): self....
fmenabe/python-dokuwiki
dokuwiki.py
_Pages.append
python
def append(self, page, content, **options): return self._dokuwiki.send('dokuwiki.appendPage', page, content, options)
Appends *content* text to *page*. Valid *options* are: * *sum*: (str) change summary * *minor*: (bool) whether this is a minor change
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L298-L306
null
class _Pages(object): """This object regroup methods for managing pages of a DokuWiki. This object is accessible from the ``pages`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.pages.list() """ def __init__(self, dokuwiki): self....
fmenabe/python-dokuwiki
dokuwiki.py
_Pages.html
python
def html(self, page, version=None): return (self._dokuwiki.send('wiki.getPageHTMLVersion', page, version) if version is not None else self._dokuwiki.send('wiki.getPageHTML', page))
Returns HTML content of *page*. The HTML content of the last version of the page is returned if *version* is not set.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L308-L314
null
class _Pages(object): """This object regroup methods for managing pages of a DokuWiki. This object is accessible from the ``pages`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.pages.list() """ def __init__(self, dokuwiki): self....
fmenabe/python-dokuwiki
dokuwiki.py
_Pages.set
python
def set(self, page, content, **options): try: return self._dokuwiki.send('wiki.putPage', page, content, options) except ExpatError as err: # Sometime the first line of the XML response is blank which raise # the 'ExpatError' exception although the change has been done...
Set/replace the *content* of *page*. Valid *options* are: * *sum*: (str) change summary * *minor*: (bool) whether this is a minor change
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L316-L331
null
class _Pages(object): """This object regroup methods for managing pages of a DokuWiki. This object is accessible from the ``pages`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.pages.list() """ def __init__(self, dokuwiki): self....
fmenabe/python-dokuwiki
dokuwiki.py
_Pages.lock
python
def lock(self, page): result = self._dokuwiki.send('dokuwiki.setLocks', lock=[page], unlock=[]) if result['lockfail']: raise DokuWikiError('unable to lock page')
Locks *page*.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L337-L342
null
class _Pages(object): """This object regroup methods for managing pages of a DokuWiki. This object is accessible from the ``pages`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.pages.list() """ def __init__(self, dokuwiki): self....
fmenabe/python-dokuwiki
dokuwiki.py
_Medias.get
python
def get(self, media, dirpath=None, filename=None, overwrite=False, b64decode=False): import os data = self._dokuwiki.send('wiki.getAttachment', media) data = base64.b64decode(data) if b64decode else data.data if dirpath is None: return data if filename is None: ...
Returns the binary data of *media* or save it to a file. If *dirpath* is not set the binary data is returned, otherwise the data is saved to a file. By default, the filename is the name of the media but it can be changed with *filename* parameter. *overwrite* parameter allow to overwrite...
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L397-L419
null
class _Medias(object): """This object regroup methods for managing medias of a DokuWiki. This object is accessible from the ``medias`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.medias.list() """ def __init__(self, dokuwiki): ...
fmenabe/python-dokuwiki
dokuwiki.py
_Medias.add
python
def add(self, media, filepath, overwrite=True): with open(filepath, 'rb') as fhandler: self._dokuwiki.send('wiki.putAttachment', media, Binary(fhandler.read()), ow=overwrite)
Set *media* from local file *filepath*. *overwrite* parameter specify if the media must be overwrite if it exists remotely.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L425-L431
null
class _Medias(object): """This object regroup methods for managing medias of a DokuWiki. This object is accessible from the ``medias`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.medias.list() """ def __init__(self, dokuwiki): ...
fmenabe/python-dokuwiki
dokuwiki.py
_Medias.set
python
def set(self, media, _bytes, overwrite=True, b64encode=False): data = base64.b64encode(_bytes) if b64encode else Binary(_bytes) self._dokuwiki.send('wiki.putAttachment', media, data, ow=overwrite)
Set *media* from *_bytes*. *overwrite* parameter specify if the media must be overwrite if it exists remotely.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L433-L438
null
class _Medias(object): """This object regroup methods for managing medias of a DokuWiki. This object is accessible from the ``medias`` property of an `DokuWiki` instance:: wiki = dokuwiki.DokuWiki('URL', 'User', 'Password') wiki.medias.list() """ def __init__(self, dokuwiki): ...
fmenabe/python-dokuwiki
dokuwiki.py
Dataentry.get
python
def get(content, keep_order=False): if keep_order: from collections import OrderedDict dataentry = OrderedDict() else: dataentry = {} found = False for line in content.split('\n'): if line.strip().startswith('---- dataentry'): ...
Get dataentry from *content*. *keep_order* indicates whether to return an ordered dictionnay.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L449-L475
null
class Dataentry(object): """Object that manage `data entries <https://www.dokuwiki.org/plugin:data>`_.""" @staticmethod @staticmethod def gen(name, data): """Generate dataentry *name* from *data*.""" return '---- dataentry %s ----\n%s\n----' % (name, '\n'.join( '%s:%s' % (...
fmenabe/python-dokuwiki
dokuwiki.py
Dataentry.gen
python
def gen(name, data): return '---- dataentry %s ----\n%s\n----' % (name, '\n'.join( '%s:%s' % (attr, value) for attr, value in data.items()))
Generate dataentry *name* from *data*.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L478-L481
null
class Dataentry(object): """Object that manage `data entries <https://www.dokuwiki.org/plugin:data>`_.""" @staticmethod def get(content, keep_order=False): """Get dataentry from *content*. *keep_order* indicates whether to return an ordered dictionnay.""" if keep_order: ...
fmenabe/python-dokuwiki
dokuwiki.py
Dataentry.ignore
python
def ignore(content): page_content = [] start = False for line in content.split('\n'): if line == '----' and not start: start = True continue if start: page_content.append(line) return '\n'.join(page_content) if page_...
Remove dataentry from *content*.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/dokuwiki.py#L484-L494
null
class Dataentry(object): """Object that manage `data entries <https://www.dokuwiki.org/plugin:data>`_.""" @staticmethod def get(content, keep_order=False): """Get dataentry from *content*. *keep_order* indicates whether to return an ordered dictionnay.""" if keep_order: ...
fmenabe/python-dokuwiki
doc/source/conf.py
linkcode_resolve
python
def linkcode_resolve(domain, info): module_name = info['module'] fullname = info['fullname'] attribute_name = fullname.split('.')[-1] base_url = 'https://github.com/fmenabe/python-dokuwiki/blob/' if release.endswith('-dev'): base_url += 'master/' else: base_url += version + '/' ...
A simple function to find matching source code.
train
https://github.com/fmenabe/python-dokuwiki/blob/7b5b13b764912b36f49a03a445c88f0934260eb1/doc/source/conf.py#L48-L96
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # dokuwiki documentation build configuration file, created by # sphinx-quickstart on Sat Feb 6 14:16:16 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # a...
deep-compute/deeputil
deeputil/timer.py
FunctionTimer
python
def FunctionTimer(on_done=None): ''' To check execution time of a function borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d >>> def logger(details, args, kwargs): #some function that uses the time output ... print(details) .....
To check execution time of a function borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d >>> def logger(details, args, kwargs): #some function that uses the time output ... print(details) ... >>> @FunctionTimer(on_done= logger) ...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/timer.py#L5-L47
null
import time class FunctionTimerTerminate(Exception): pass FunctionTimer.terminate = FunctionTimerTerminate class BlockTimer: ''' To check execution time of a code. borrowed from: http://preshing.com/20110924/timing-your-code-using-pythons-with-statement/ >>> with Timer.block() as t: ... ...
deep-compute/deeputil
deeputil/priority_dict.py
PriorityDict.smallest
python
def smallest(self): heap = self._heap v, k = heap[0] while k not in self or self[k] != v: heappop(heap) v, k = heap[0] return k
Return the item with the lowest priority. Raises IndexError if the object is empty.
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/priority_dict.py#L76-L88
null
class PriorityDict(dict): """Dictionary that can be used as a priority queue. Keys of the dictionary are items to be put into the queue, and values are their respective priorities. All dictionary methods work as expected. The advantage over a standard heapq-based priority queue is that priorities o...
deep-compute/deeputil
deeputil/priority_dict.py
PriorityDict.pop_smallest
python
def pop_smallest(self): heap = self._heap v, k = heappop(heap) while k not in self or self[k] != v: v, k = heappop(heap) del self[k] return k
Return the item with the lowest priority and remove it. Raises IndexError if the object is empty.
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/priority_dict.py#L90-L101
null
class PriorityDict(dict): """Dictionary that can be used as a priority queue. Keys of the dictionary are items to be put into the queue, and values are their respective priorities. All dictionary methods work as expected. The advantage over a standard heapq-based priority queue is that priorities o...
deep-compute/deeputil
deeputil/streamcounter.py
StreamCounter.add
python
def add(self, item, count=1): ''' When we receive stream of data, we add them in the chunk which has limit on the no. of items that it will store. >>> s = StreamCounter(5,5) >>> data_stream = ['a','b','c','d'] >>> for item in data_stream: ... s.add(item) ...
When we receive stream of data, we add them in the chunk which has limit on the no. of items that it will store. >>> s = StreamCounter(5,5) >>> data_stream = ['a','b','c','d'] >>> for item in data_stream: ... s.add(item) >>> s.chunk_size 5 >>> s.n_item...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/streamcounter.py#L47-L105
[ "def _drop_oldest_chunk(self):\n '''\n To handle the case when the items comming in the chunk\n is more than the maximum capacity of the chunk. Our intent\n behind is to remove the oldest chunk. So that the items come\n flowing in.\n >>> s = StreamCounter(5,5)\n >>> data_stream = ['a','b','c','...
class StreamCounter(object): ''' A class whose responsibility is to get the count of items in data comming as a stream. ''' #TODO Doctests and examples # When we receive a stream of data, we fix the max size of chunk # Think of chunk as a container, which can only fit a fixed no. of items ...
deep-compute/deeputil
deeputil/streamcounter.py
StreamCounter._drop_oldest_chunk
python
def _drop_oldest_chunk(self): ''' To handle the case when the items comming in the chunk is more than the maximum capacity of the chunk. Our intent behind is to remove the oldest chunk. So that the items come flowing in. >>> s = StreamCounter(5,5) >>> data_stream ...
To handle the case when the items comming in the chunk is more than the maximum capacity of the chunk. Our intent behind is to remove the oldest chunk. So that the items come flowing in. >>> s = StreamCounter(5,5) >>> data_stream = ['a','b','c','d'] >>> for item in data_s...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/streamcounter.py#L107-L135
null
class StreamCounter(object): ''' A class whose responsibility is to get the count of items in data comming as a stream. ''' #TODO Doctests and examples # When we receive a stream of data, we fix the max size of chunk # Think of chunk as a container, which can only fit a fixed no. of items ...
deep-compute/deeputil
deeputil/streamcounter.py
StreamCounter.get
python
def get(self, item, default=0, normalized=False): ''' When we have the stream of data pushed in the chunk we can retrive count of an item using this method. >>> stream_counter_obj = StreamCounter(5,5) >>> data_stream = ['a','b','c'] >>> for item in data_stream: .....
When we have the stream of data pushed in the chunk we can retrive count of an item using this method. >>> stream_counter_obj = StreamCounter(5,5) >>> data_stream = ['a','b','c'] >>> for item in data_stream: ... stream_counter_obj.add(item) >>> stream_counter_obj.get(...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/streamcounter.py#L137-L173
null
class StreamCounter(object): ''' A class whose responsibility is to get the count of items in data comming as a stream. ''' #TODO Doctests and examples # When we receive a stream of data, we fix the max size of chunk # Think of chunk as a container, which can only fit a fixed no. of items ...
deep-compute/deeputil
deeputil/misc.py
generate_random_string
python
def generate_random_string(length=6): ''' Returns a random string of a specified length. >>> len(generate_random_string(length=25)) 25 Test randomness. Try N times and observe no duplicaton >>> N = 100 >>> len(set(generate_random_string(10) for i in range(N))) == N True ''' n =...
Returns a random string of a specified length. >>> len(generate_random_string(length=25)) 25 Test randomness. Try N times and observe no duplicaton >>> N = 100 >>> len(set(generate_random_string(10) for i in range(N))) == N True
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L16-L31
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def get_timestamp(dt=None): ''' Return current timestamp if @dt i...
deep-compute/deeputil
deeputil/misc.py
get_timestamp
python
def get_timestamp(dt=None): ''' Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21) >>> get_timestamp(t) 1432166400 ''' if dt is None: dt = datetime.datetime.utcnow() t = dt.utctimetuple() return calendar.timegm(t)
Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21) >>> get_timestamp(t) 1432166400
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L33-L46
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
get_datetime
python
def get_datetime(epoch): ''' get datetime from an epoch timestamp >>> get_datetime(1432188772) datetime.datetime(2015, 5, 21, 6, 12, 52) ''' t = time.gmtime(epoch) dt = datetime.datetime(*t[:6]) return dt
get datetime from an epoch timestamp >>> get_datetime(1432188772) datetime.datetime(2015, 5, 21, 6, 12, 52)
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L48-L59
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
convert_ts
python
def convert_ts(tt): ''' tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1) >>> tt = time.strptime("23.10.2012", "%d.%m.%Y") >>> convert_ts(tt) 1350950400 tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_ho...
tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1) >>> tt = time.strptime("23.10.2012", "%d.%m.%Y") >>> convert_ts(tt) 1350950400 tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L61-L90
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
xcode
python
def xcode(text, encoding='utf8', mode='ignore'): ''' Converts unicode encoding to str >>> xcode(b'hello') b'hello' >>> xcode('hello') b'hello' ''' return text.encode(encoding, mode) if isinstance(text, str) else text
Converts unicode encoding to str >>> xcode(b'hello') b'hello' >>> xcode('hello') b'hello'
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L93-L102
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
parse_location
python
def parse_location(loc, default_port): ''' loc can be of the format http://<ip/domain>[:<port>] eg: http://localhost:8888 http://localhost/ return ip (str), port (int) >>> parse_location('http://localhost/', 6379) ('localhost', 6379) >>> parse_location('http://localhost:8888'...
loc can be of the format http://<ip/domain>[:<port>] eg: http://localhost:8888 http://localhost/ return ip (str), port (int) >>> parse_location('http://localhost/', 6379) ('localhost', 6379) >>> parse_location('http://localhost:8888', 6379) ('localhost', 8888)
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L111-L132
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
serialize_dict_keys
python
def serialize_dict_keys(d, prefix=""): keys = [] for k, v in d.items(): fqk = '{}{}'.format(prefix, k) keys.append(fqk) if isinstance(v, dict): keys.extend(serialize_dict_keys(v, prefix="{}.".format(fqk))) return keys
returns all the keys in nested a dictionary. >>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } })) ['a', 'a.b', 'a.b.b', 'a.b.c']
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L172-L184
[ "def serialize_dict_keys(d, prefix=\"\"):\n \"\"\"returns all the keys in nested a dictionary.\n >>> sorted(serialize_dict_keys({\"a\": {\"b\": {\"c\": 1, \"b\": 2} } }))\n ['a', 'a.b', 'a.b.b', 'a.b.c']\n \"\"\"\n keys = []\n for k, v in d.items():\n fqk = '{}{}'.format(prefix, k)\n ...
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
flatten_dict
python
def flatten_dict(d, parent_key='', sep='.', ignore_under_prefixed=True, mark_value=True): ''' Flattens a nested dictionary >>> from pprint import pprint >>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } } >>> fd = flatten_dict(d...
Flattens a nested dictionary >>> from pprint import pprint >>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } } >>> fd = flatten_dict(d) >>> pprint(fd) {'a.b._e': "'mark'", 'a.b.b': 2, 'a.b.c': 1}
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L192-L221
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
deepgetattr
python
def deepgetattr(obj, attr, default=AttributeError): try: return reduce(getattr, attr.split('.'), obj) except AttributeError: if default is not AttributeError: return default raise
Recurses through an attribute chain to get the ultimate value (obj/data/member/value) from: http://pingfive.typepad.com/blog/2010/04/deep-getattr-python-function.html >>> class Universe(object): ... def __init__(self, galaxy): ... self.galaxy = galaxy ... >>> class Galaxy(objec...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L223-L259
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
set_file_limits
python
def set_file_limits(n): ''' Set the limit on number of file descriptors that this process can open. ''' try: resource.setrlimit(resource.RLIMIT_NOFILE, (n, n)) return True except ValueError: return False
Set the limit on number of file descriptors that this process can open.
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L473-L484
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
memoize
python
def memoize(f): ''' Caches result of a function From: https://goo.gl/aXt4Qy >>> import time >>> @memoize ... def test(msg): ... # Processing for result that takes time ... time.sleep(1) ... return msg >>> >>> for i in range(5): ... start = time.time(...
Caches result of a function From: https://goo.gl/aXt4Qy >>> import time >>> @memoize ... def test(msg): ... # Processing for result that takes time ... time.sleep(1) ... return msg >>> >>> for i in range(5): ... start = time.time() ... test('calling ...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L546-L588
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/misc.py
load_object
python
def load_object(imp_path): ''' Given a python import path, load the object For dynamic imports in a program >>> isdir = load_object('os.path.isdir') >>> isdir('/tmp') True >>> num = load_object('numbers.Number') >>> isinstance('x', num) False >>> isinstance(777, num) True ...
Given a python import path, load the object For dynamic imports in a program >>> isdir = load_object('os.path.isdir') >>> isdir('/tmp') True >>> num = load_object('numbers.Number') >>> isinstance('x', num) False >>> isinstance(777, num) True
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L592-L611
null
import time import datetime import calendar import os import inspect import random import string import itertools from six import iteritems as items import sys from operator import attrgetter import binascii from functools import reduce, wraps def generate_random_string(length=6): ''' Returns a random string ...
deep-compute/deeputil
deeputil/keep_running.py
keeprunning
python
def keeprunning(wait_secs=0, exit_on_success=False, on_success=None, on_error=None, on_done=None): ''' Example 1: dosomething needs to run until completion condition without needing to have a loop in its code. Also, when error happens, we should NOT terminate execution >>> from deep...
Example 1: dosomething needs to run until completion condition without needing to have a loop in its code. Also, when error happens, we should NOT terminate execution >>> from deeputil import AttrDict >>> @keeprunning(wait_secs=1) ... def dosomething(state): ... state.i += 1 ... pri...
train
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/keep_running.py#L10-L171
null
'''Keeps running a function running even on error ''' import time import inspect class KeepRunningTerminate(Exception): pass keeprunning.terminate = KeepRunningTerminate
OCHA-DAP/hdx-python-country
setup.py
script_dir
python
def script_dir(pyobject, follow_symlinks=True): if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze path = abspath(sys.executable) else: path = inspect.getabsfile(pyobject) if follow_symlinks: path = realpath(path) return dirname(path)
Get current script's directory Args: pyobject (Any): Any Python object in the script follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True. Returns: str: Current script's directory
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/setup.py#L11-L27
null
# -*- coding: utf-8 -*- import inspect import sys from codecs import open from os.path import join, abspath, realpath, dirname from setuptools import setup, find_packages # Sadly we cannot use the location here because of the typing module which isn't in Python < 3.5 def script_dir_plus_file(filename, pyobject, f...
OCHA-DAP/hdx-python-country
setup.py
script_dir_plus_file
python
def script_dir_plus_file(filename, pyobject, follow_symlinks=True): return join(script_dir(pyobject, follow_symlinks), filename)
Get current script's directory and then append a filename Args: filename (str): Filename to append to directory path pyobject (Any): Any Python object in the script follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True. Returns: str: Current script's direct...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/setup.py#L30-L41
[ "def script_dir(pyobject, follow_symlinks=True):\n \"\"\"Get current script's directory\n\n Args:\n pyobject (Any): Any Python object in the script\n follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.\n\n Returns:\n str: Current script's directory\n \"\"\"\n...
# -*- coding: utf-8 -*- import inspect import sys from codecs import open from os.path import join, abspath, realpath, dirname from setuptools import setup, find_packages # Sadly we cannot use the location here because of the typing module which isn't in Python < 3.5 def script_dir(pyobject, follow_symlinks=True): ...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country._add_countriesdata
python
def _add_countriesdata(cls, iso3, country): # type: (str, hxl.Row) -> None countryname = country.get('#country+name+preferred') cls._countriesdata['countrynames2iso3'][countryname.upper()] = iso3 iso2 = country.get('#country+code+v_iso2') if iso2: cls._countriesdata['...
Set up countries data from data in form provided by UNStats and World Bank Args: iso3 (str): ISO3 code for country country (hxl.Row): Country information Returns: None
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L45-L104
null
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.set_countriesdata
python
def set_countriesdata(cls, countries): # type: (str) -> None cls._countriesdata = dict() cls._countriesdata['countries'] = dict() cls._countriesdata['iso2iso3'] = dict() cls._countriesdata['m49iso3'] = dict() cls._countriesdata['countrynames2iso3'] = dict() cls._c...
Set up countries data from data in form provided by UNStats and World Bank Args: countries (str): Countries data in HTML format provided by UNStats Returns: None
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L107-L141
[ "def _add_countriesdata(cls, iso3, country):\n # type: (str, hxl.Row) -> None\n \"\"\"\n Set up countries data from data in form provided by UNStats and World Bank\n\n Args:\n iso3 (str): ISO3 code for country\n country (hxl.Row): Country information\n\n Returns:\n None\n \"\"...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.countriesdata
python
def countriesdata(cls, use_live=True): # type: (bool) -> List[Dict[Dict]] if cls._countriesdata is None: countries = None if use_live: try: countries = hxl.data(cls._ochaurl) except IOError: logger.exception(...
Read countries data from OCHA countries feed (falling back to file) Args: use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. Returns: List[Dict[Dict]]: Countries dictionaries
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L144-L167
[ "def set_countriesdata(cls, countries):\n # type: (str) -> None\n \"\"\"\n Set up countries data from data in form provided by UNStats and World Bank\n\n Args:\n countries (str): Countries data in HTML format provided by UNStats\n\n Returns:\n None\n \"\"\"\n cls._countriesdata = ...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.set_ocha_url
python
def set_ocha_url(cls, url=None): # type: (str) -> None if url is None: url = cls._ochaurl_int cls._ochaurl = url
Set World Bank url from which to retrieve countries data Args: url (str): World Bank url from which to retrieve countries data. Defaults to internal value. Returns: None
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L170-L183
null
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_country_info_from_iso3
python
def get_country_info_from_iso3(cls, iso3, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]] countriesdata = cls.countriesdata(use_live=use_live) country = countriesdata['countries'].get(iso3.upper()) if country is not None: ...
Get country information from ISO3 code Args: iso3 (str): ISO3 code for which to get country information use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if cou...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L186-L205
[ "def countriesdata(cls, use_live=True):\n # type: (bool) -> List[Dict[Dict]]\n \"\"\"\n Read countries data from OCHA countries feed (falling back to file)\n\n Args:\n use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n\n Returns:\n List...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_country_name_from_iso3
python
def get_country_name_from_iso3(cls, iso3, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str] countryinfo = cls.get_country_info_from_iso3(iso3, use_live=use_live, exception=exception) if countryinfo is not None: return countryinfo.get(...
Get country name from ISO3 code Args: iso3 (str): ISO3 code for which to get country name use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if country not found...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L208-L223
[ "def get_country_info_from_iso3(cls, iso3, use_live=True, exception=None):\n # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]\n \"\"\"Get country information from ISO3 code\n\n Args:\n iso3 (str): ISO3 code for which to get country information\n use_live (bool): Try t...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_iso2_from_iso3
python
def get_iso2_from_iso3(cls, iso3, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str] countriesdata = cls.countriesdata(use_live=use_live) iso2 = countriesdata['iso2iso3'].get(iso3.upper()) if iso2 is not None: return iso2 ...
Get ISO2 from ISO3 code Args: iso3 (str): ISO3 code for which to get ISO2 code use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults ...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L226-L245
[ "def countriesdata(cls, use_live=True):\n # type: (bool) -> List[Dict[Dict]]\n \"\"\"\n Read countries data from OCHA countries feed (falling back to file)\n\n Args:\n use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n\n Returns:\n List...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_country_info_from_iso2
python
def get_country_info_from_iso2(cls, iso2, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]] iso3 = cls.get_iso3_from_iso2(iso2, use_live=use_live, exception=exception) if iso3 is not None: return cls.get_country_info_from_iso3(i...
Get country name from ISO2 code Args: iso2 (str): ISO2 code for which to get country information use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if country no...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L270-L285
[ "def get_country_info_from_iso3(cls, iso3, use_live=True, exception=None):\n # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]\n \"\"\"Get country information from ISO3 code\n\n Args:\n iso3 (str): ISO3 code for which to get country information\n use_live (bool): Try t...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_country_name_from_iso2
python
def get_country_name_from_iso2(cls, iso2, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str] iso3 = cls.get_iso3_from_iso2(iso2, use_live=use_live, exception=exception) if iso3 is not None: return cls.get_country_name_from_iso3(iso3, e...
Get country name from ISO2 code Args: iso2 (str): ISO2 code for which to get country name use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if country not found...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L288-L303
[ "def get_country_name_from_iso3(cls, iso3, use_live=True, exception=None):\n # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]\n \"\"\"Get country name from ISO3 code\n\n Args:\n iso3 (str): ISO3 code for which to get country name\n use_live (bool): Try to get use latest dat...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_m49_from_iso3
python
def get_m49_from_iso3(cls, iso3, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[int] countriesdata = cls.countriesdata(use_live=use_live) m49 = countriesdata['m49iso3'].get(iso3) if m49 is not None: return m49 if except...
Get M49 from ISO3 code Args: iso3 (str): ISO3 code for which to get M49 code use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L306-L325
[ "def countriesdata(cls, use_live=True):\n # type: (bool) -> List[Dict[Dict]]\n \"\"\"\n Read countries data from OCHA countries feed (falling back to file)\n\n Args:\n use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\n\n Returns:\n List...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_country_info_from_m49
python
def get_country_info_from_m49(cls, m49, use_live=True, exception=None): # type: (int, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]] iso3 = cls.get_iso3_from_m49(m49, use_live=use_live, exception=exception) if iso3 is not None: return cls.get_country_info_from_iso3(iso3,...
Get country name from M49 code Args: m49 (int): M49 numeric code for which to get country information use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if count...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L350-L365
[ "def get_country_info_from_iso3(cls, iso3, use_live=True, exception=None):\n # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]\n \"\"\"Get country information from ISO3 code\n\n Args:\n iso3 (str): ISO3 code for which to get country information\n use_live (bool): Try t...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.get_country_name_from_m49
python
def get_country_name_from_m49(cls, m49, use_live=True, exception=None): # type: (int, bool, Optional[ExceptionUpperBound]) -> Optional[str] iso3 = cls.get_iso3_from_m49(m49, use_live=use_live, exception=exception) if iso3 is not None: return cls.get_country_name_from_iso3(iso3, excep...
Get country name from M49 code Args: m49 (int): M49 numeric code for which to get country name use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True. exception (Optional[ExceptionUpperBound]): An exception to raise if country not ...
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L368-L383
[ "def get_country_name_from_iso3(cls, iso3, use_live=True, exception=None):\n # type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]\n \"\"\"Get country name from ISO3 code\n\n Args:\n iso3 (str): ISO3 code for which to get country name\n use_live (bool): Try to get use latest dat...
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.expand_countryname_abbrevs
python
def expand_countryname_abbrevs(cls, country): # type: (str) -> List[str] def replace_ensure_space(word, replace, replacement): return word.replace(replace, '%s ' % replacement).replace(' ', ' ').strip() countryupper = country.upper() for abbreviation in cls.abbreviations: ...
Expands abbreviation(s) in country name in various ways (eg. FED -> FEDERATED, FEDERAL etc.) Args: country (str): Country with abbreviation(s)to expand Returns: List[str]: Uppercase country name with abbreviation(s) expanded in various ways
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L386-L406
[ "def replace_ensure_space(word, replace, replacement):\n return word.replace(replace, '%s ' % replacement).replace(' ', ' ').strip()\n" ]
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...
OCHA-DAP/hdx-python-country
src/hdx/location/country.py
Country.simplify_countryname
python
def simplify_countryname(cls, country): # type: (str) -> (str, List[str]) countryupper = country.upper() words = get_words_in_sentence(countryupper) index = countryupper.find(',') if index != -1: countryupper = countryupper[:index] index = countryupper.find(':...
Simplifies country name by removing descriptive text eg. DEMOCRATIC, REPUBLIC OF etc. Args: country (str): Country name to simplify Returns: Tuple[str, List[str]]: Uppercase simplified country name and list of removed words
train
https://github.com/OCHA-DAP/hdx-python-country/blob/e86a0b5f182a5d010c4cd7faa36a213cfbcc01f6/src/hdx/location/country.py#L409-L446
null
class Country(object): """Location class with various methods to help with countries and regions. Uses OCHA countries feed which supplies data in form: :: ID,HRinfo ID,RW ID,m49 numerical code,FTS API ID,Appears in UNTERM list,Appears in DGACM list,ISO 3166-1 Alpha 2-Codes,ISO 3166-1 Alpha 3-Codes,x...