_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q241000 | attrload | train | def attrload(value: Any, type_: Type[T], **kwargs) -> T:
"""
Quick function call to load data supporting the "attr" module
in addition to the default ones.
"""
from . import dataloader
from .plugins import attrload as loadplugin
loader = dataloader.Loader(**kwargs)
loadplugin.add2loader(... | python | {
"resource": ""
} |
q241001 | attrdump | train | def attrdump(value: Any, **kwargs) -> Any:
"""
Quick function to do a dump that supports the "attr"
module.
"""
from . import datadumper
from .plugins import attrdump as dumpplugin
dumper = datadumper.Dumper(**kwargs)
dumpplugin.add2dumper(dumper)
return dumper.dump(value) | python | {
"resource": ""
} |
q241002 | on_panic | train | def on_panic(etype, value, tb):
"""
Called when there is an unhandled error in a goroutine.
By default, logs and exits the process.
"""
_logging.critical(_traceback.format_exception(etype, value, tb))
_be.propagate_exc(SystemExit, 1) | python | {
"resource": ""
} |
q241003 | stdout_to_results | train | def stdout_to_results(s):
"""Turns the multi-line output of a benchmark process into
a sequence of BenchmarkResult instances."""
results = s.strip().split('\n')
return [BenchmarkResult(*r.split()) for r in results] | python | {
"resource": ""
} |
q241004 | benchmark_process_and_backend | train | def benchmark_process_and_backend(exe, backend):
"""Returns BenchmarkResults for a given executable and backend."""
env = dict(os.environ)
env['GOLESS_BACKEND'] = backend
args = [exe, '-m', 'benchmark']
return get_benchproc_results(args, env=env) | python | {
"resource": ""
} |
q241005 | insert_seperator_results | train | def insert_seperator_results(results):
"""Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference."""
sepbench = BenchmarkResult(*[' ' * w for w in COLUMN_WIDTHS])
last_bm = None
f... | python | {
"resource": ""
} |
q241006 | Byml.parse | train | def parse(self) -> typing.Union[list, dict, None]:
"""Parse the BYML and get the root node with all children."""
root_node_offset = self._read_u32(12)
if root_node_offset == 0:
return None
node_type = self._data[root_node_offset]
if not _is_container_type(node_type):... | python | {
"resource": ""
} |
q241007 | PermissionMixin.check_permission | train | def check_permission(self, request):
"""
Check this field's permissions to determine whether or not it may be
shown.
"""
return all((permission.has_permission(request) for permission in self.permission_classes)) | python | {
"resource": ""
} |
q241008 | build_github_url | train | def build_github_url(
repo,
branch=None,
path='requirements.txt',
token=None
):
"""
Builds a URL to a file inside a Github repository.
"""
repo = re.sub(r"^http(s)?://github.com/", "", repo).strip('/')
# args come is as 'None' instead of not being provided
if not path:
... | python | {
"resource": ""
} |
q241009 | get_default_branch | train | def get_default_branch(repo):
"""returns the name of the default branch of the repo"""
url = "{}/repos/{}".format(GITHUB_API_BASE, repo)
response = requests.get(url)
if response.status_code == 200:
api_response = json.loads(response.text)
return api_response['default_branch']
else:
... | python | {
"resource": ""
} |
q241010 | get_requirements_file_from_url | train | def get_requirements_file_from_url(url):
"""fetches the requiremets from the url"""
response = requests.get(url)
if response.status_code == 200:
return StringIO(response.text)
else:
return StringIO("") | python | {
"resource": ""
} |
q241011 | PermissiveFeatureTable.longest_one_seg_prefix | train | def longest_one_seg_prefix(self, word):
"""Return longest IPA Unicode prefix of `word`
Args:
word (unicode): word as IPA string
Returns:
unicode: longest single-segment prefix of `word`
"""
match = self.seg_regex.match(word)
if match:
... | python | {
"resource": ""
} |
q241012 | PermissiveFeatureTable.filter_segs | train | def filter_segs(self, segs):
"""Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definititions of bases and diacritics... | python | {
"resource": ""
} |
q241013 | Validator.validate_line | train | def validate_line(self, line):
"""Validate Unicode IPA string relative to panphon.
line -- String of IPA characters. Can contain whitespace and limited
punctuation.
"""
line0 = line
pos = 0
while line:
seg_m = self.ft.seg_regex.match(line)
... | python | {
"resource": ""
} |
q241014 | segment_text | train | def segment_text(text, seg_regex=SEG_REGEX):
"""Return an iterator of segments in the text.
Args:
text (unicode): string of IPA Unicode text
seg_regex (_regex.Pattern): compiled regex defining a segment (base +
modifiers)
Return:
generator: segme... | python | {
"resource": ""
} |
q241015 | FeatureTable.fts_match | train | def fts_match(self, features, segment):
"""Answer question "are `ft_mask`'s features a subset of ft_seg?"
This is like `FeatureTable.match` except that it checks whether a
segment is valid and returns None if it is not.
Args:
features (set): pattern defined as set of (value... | python | {
"resource": ""
} |
q241016 | FeatureTable.longest_one_seg_prefix | train | def longest_one_seg_prefix(self, word):
"""Return longest Unicode IPA prefix of a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
unicode: longest single-segment prefix of `word` in database
"""
for i in range(self.longest_seg, 0, -1... | python | {
"resource": ""
} |
q241017 | FeatureTable.validate_word | train | def validate_word(self, word):
"""Returns True if `word` consists exhaustively of valid IPA segments
Args:
word (unicode): input word as Unicode IPA string
Returns:
bool: True if `word` can be divided exhaustively into IPA segments
that exist in the da... | python | {
"resource": ""
} |
q241018 | FeatureTable.segs | train | def segs(self, word):
"""Returns a list of segments from a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
list: list of strings corresponding to segments found in `word`
"""
return [m.group('all') for m in self.seg_regex.finditer(wo... | python | {
"resource": ""
} |
q241019 | FeatureTable.word_fts | train | def word_fts(self, word):
"""Return featural analysis of `word`
Args:
word (unicode): one or more IPA segments
Returns:
list: list of lists (value, feature) tuples where each inner list
corresponds to a segment in `word`
"""
return lis... | python | {
"resource": ""
} |
q241020 | FeatureTable.filter_string | train | def filter_string(self, word):
"""Return a string like the input but containing only legal IPA segments
Args:
word (unicode): input string to be filtered
Returns:
unicode: string identical to `word` but with invalid IPA segments
absent
"""
... | python | {
"resource": ""
} |
q241021 | FeatureTable.fts_intersection | train | def fts_intersection(self, segs):
"""Return the features shared by `segs`
Args:
segs (list): list of Unicode IPA segments
Returns:
set: set of (value, feature) tuples shared by the valid segments in
`segs`
"""
fts_vecs = [self.fts(s) for... | python | {
"resource": ""
} |
q241022 | FeatureTable.fts_match_any | train | def fts_match_any(self, fts, inv):
"""Return `True` if any segment in `inv` matches the features in `fts`
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
... | python | {
"resource": ""
} |
q241023 | FeatureTable.fts_match_all | train | def fts_match_all(self, fts, inv):
"""Return `True` if all segments in `inv` matches the features in fts
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
... | python | {
"resource": ""
} |
q241024 | FeatureTable.fts_contrast2 | train | def fts_contrast2(self, fs, ft_name, inv):
"""Return `True` if there is a segment in `inv` that contrasts in feature
`ft_name`.
Args:
fs (list): feature specifications used to filter `inv`.
ft_name (str): name of the feature where contrast must be present.
in... | python | {
"resource": ""
} |
q241025 | FeatureTable.fts_count | train | def fts_count(self, fts, inv):
"""Return the count of segments in an inventory matching a given
feature mask.
Args:
fts (set): feature mask given as a set of (value, feature) tuples
inv (set): inventory of segments (as Unicode IPA strings)
Returns:
i... | python | {
"resource": ""
} |
q241026 | FeatureTable.match_pattern | train | def match_pattern(self, pat, word):
"""Implements fixed-width pattern matching.
Matches just in case pattern is the same length (in segments) as the
word and each of the segments in the pattern is a featural subset of the
corresponding segment in the word. Matches return the correspondi... | python | {
"resource": ""
} |
q241027 | FeatureTable.compile_regex_from_str | train | def compile_regex_from_str(self, ft_str):
"""Given a string describing features masks for a sequence of segments,
return a regex matching the corresponding strings.
Args:
ft_str (str): feature masks, each enclosed in square brackets, in
which the features are delimited b... | python | {
"resource": ""
} |
q241028 | FeatureTable.segment_to_vector | train | def segment_to_vector(self, seg):
"""Given a Unicode IPA segment, return a list of feature specificiations
in cannonical order.
Args:
seg (unicode): IPA consonant or vowel
Returns:
list: feature specifications ('+'/'-'/'0') in the order from
`Feature... | python | {
"resource": ""
} |
q241029 | FeatureTable.word_to_vector_list | train | def word_to_vector_list(self, word, numeric=False, xsampa=False):
"""Return a list of feature vectors, given a Unicode IPA word.
Args:
word (unicode): string in IPA
numeric (bool): if True, return features as numeric values instead
of strings
... | python | {
"resource": ""
} |
q241030 | ThreatButt.clown_strike_ioc | train | def clown_strike_ioc(self, ioc):
"""Performs Clown Strike lookup on an IoC.
Args:
ioc - An IoC.
"""
r = requests.get('http://threatbutt.io/api', data='ioc={0}'.format(ioc))
self._output(r.text) | python | {
"resource": ""
} |
q241031 | ThreatButt.bespoke_md5 | train | def bespoke_md5(self, md5):
"""Performs Bespoke MD5 lookup on an MD5.
Args:
md5 - A hash.
"""
r = requests.post('http://threatbutt.io/api/md5/{0}'.format(md5))
self._output(r.text) | python | {
"resource": ""
} |
q241032 | Sonority.sonority_from_fts | train | def sonority_from_fts(self, seg):
"""Given a segment as features, returns the sonority on a scale of 1
to 9.
Args:
seg (list): collection of (value, feature) pairs representing
a segment (vowel or consonant)
Returns:
int: sonority of `s... | python | {
"resource": ""
} |
q241033 | CacheSimulator.from_dict | train | def from_dict(cls, d):
"""Create cache hierarchy from dictionary."""
main_memory = MainMemory()
caches = {}
referred_caches = set()
# First pass, create all named caches and collect references
for name, conf in d.items():
caches[name] = Cache(name=name,
... | python | {
"resource": ""
} |
q241034 | CacheSimulator.load | train | def load(self, addr, length=1):
"""
Load one or more addresses.
:param addr: byte address of load location
:param length: All address from addr until addr+length (exclusive) are
loaded (default: 1)
"""
if addr is None:
return
el... | python | {
"resource": ""
} |
q241035 | CacheSimulator.store | train | def store(self, addr, length=1, non_temporal=False):
"""
Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no wri... | python | {
"resource": ""
} |
q241036 | CacheSimulator.loadstore | train | def loadstore(self, addrs, length=1):
"""
Load and store address in order given.
:param addrs: iteratable of address tuples: [(loads, stores), ...]
:param length: will load and store all bytes between addr and
addr+length (for each address)
"""
if ... | python | {
"resource": ""
} |
q241037 | CacheSimulator.print_stats | train | def print_stats(self, header=True, file=sys.stdout):
"""Pretty print stats table."""
if header:
print("CACHE {:*^18} {:*^18} {:*^18} {:*^18} {:*^18}".format(
"HIT", "MISS", "LOAD", "STORE", "EVICT"), file=file)
for s in self.stats():
print("{name:>5} {HIT_... | python | {
"resource": ""
} |
q241038 | CacheSimulator.levels | train | def levels(self, with_mem=True):
"""Return cache levels, optionally including main memory."""
p = self.first_level
while p is not None:
yield p
# FIXME bad hack to include victim caches, need a more general solution, probably
# involving recursive tree walking... | python | {
"resource": ""
} |
q241039 | CacheSimulator.count_invalid_entries | train | def count_invalid_entries(self):
"""Sum of all invalid entry counts from cache levels."""
return sum([c.count_invalid_entries() for c in self.levels(with_mem=False)]) | python | {
"resource": ""
} |
q241040 | Cache.set_load_from | train | def set_load_from(self, load_from):
"""Update load_from in Cache and backend."""
assert load_from is None or isinstance(load_from, Cache), \
"load_from needs to be None or a Cache object."
assert load_from is None or load_from.cl_size <= self.cl_size, \
"cl_size may only ... | python | {
"resource": ""
} |
q241041 | Cache.set_store_to | train | def set_store_to(self, store_to):
"""Update store_to in Cache and backend."""
assert store_to is None or isinstance(store_to, Cache), \
"store_to needs to be None or a Cache object."
assert store_to is None or store_to.cl_size <= self.cl_size, \
"cl_size may only increase... | python | {
"resource": ""
} |
q241042 | Cache.set_victims_to | train | def set_victims_to(self, victims_to):
"""Update victims_to in Cache and backend."""
assert victims_to is None or isinstance(victims_to, Cache), \
"store_to needs to be None or a Cache object."
assert victims_to is None or victims_to.cl_size == self.cl_size, \
"cl_size may... | python | {
"resource": ""
} |
q241043 | MainMemory.load_to | train | def load_to(self, last_level_load):
"""Set level where to load from."""
assert isinstance(last_level_load, Cache), \
"last_level needs to be a Cache object."
assert last_level_load.load_from is None, \
"last_level_load must be a last level cache (.load_from is None)."
... | python | {
"resource": ""
} |
q241044 | MainMemory.store_from | train | def store_from(self, last_level_store):
"""Set level where to store to."""
assert isinstance(last_level_store, Cache), \
"last_level needs to be a Cache object."
assert last_level_store.store_to is None, \
"last_level_store must be a last level cache (.store_to is None)."... | python | {
"resource": ""
} |
q241045 | Key.list | train | def list(self):
'''Returns the `list` representation of this Key.
Note that this method assumes the key is immutable.
'''
if not self._list:
self._list = map(Namespace, self._string.split('/'))
return self._list | python | {
"resource": ""
} |
q241046 | Key.instance | train | def instance(self, other):
'''Returns an instance Key, by appending a name to the namespace.'''
assert '/' not in str(other)
return Key(str(self) + ':' + str(other)) | python | {
"resource": ""
} |
q241047 | Key.isAncestorOf | train | def isAncestorOf(self, other):
'''Returns whether this Key is an ancestor of `other`.
>>> john = Key('/Comedy/MontyPython/Actor:JohnCleese')
>>> Key('/Comedy').isAncestorOf(john)
True
'''
if isinstance(other, Key):
return other._string.startswith(self._string + '/')
raise... | python | {
"resource": ""
} |
q241048 | Key.isDescendantOf | train | def isDescendantOf(self, other):
'''Returns whether this Key is a descendant of `other`.
>>> Key('/Comedy/MontyPython').isDescendantOf(Key('/Comedy'))
True
'''
if isinstance(other, Key):
return other.isAncestorOf(self)
raise TypeError('%s is not of type %s' % (other, Key)) | python | {
"resource": ""
} |
q241049 | ensure_directory_exists | train | def ensure_directory_exists(directory):
'''Ensures `directory` exists. May make `directory` and intermediate dirs.
Raises RuntimeError if `directory` is a file.
'''
if not os.path.exists(directory):
os.makedirs(directory)
elif os.path.isfile(directory):
raise RuntimeError('Path %s is a file, not a dir... | python | {
"resource": ""
} |
q241050 | FileSystemDatastore.relative_path | train | def relative_path(self, key):
'''Returns the relative path for given `key`'''
key = str(key) # stringify
key = key.replace(':', '/') # turn namespace delimiters into slashes
key = key[1:] # remove first slash (absolute)
if not self.case_sensitive:
key = key.low... | python | {
"resource": ""
} |
q241051 | FileSystemDatastore.path | train | def path(self, key):
'''Returns the `path` for given `key`'''
return os.path.join(self.root_path, self.relative_path(key)) | python | {
"resource": ""
} |
q241052 | FileSystemDatastore.object_path | train | def object_path(self, key):
'''return the object path for `key`.'''
return os.path.join(self.root_path, self.relative_object_path(key)) | python | {
"resource": ""
} |
q241053 | FileSystemDatastore._write_object | train | def _write_object(self, path, value):
'''write out `object` to file at `path`'''
ensure_directory_exists(os.path.dirname(path))
with open(path, 'w') as f:
f.write(value) | python | {
"resource": ""
} |
q241054 | FileSystemDatastore._read_object | train | def _read_object(self, path):
'''read in object from file at `path`'''
if not os.path.exists(path):
return None
if os.path.isdir(path):
raise RuntimeError('%s is a directory, not a file.' % path)
with open(path) as f:
file_contents = f.read()
return file_contents | python | {
"resource": ""
} |
q241055 | FileSystemDatastore.get | train | def get(self, key):
'''Return the object named by key or None if it does not exist.
Args:
key: Key naming the object to retrieve
Returns:
object or None
'''
path = self.object_path(key)
return self._read_object(path) | python | {
"resource": ""
} |
q241056 | FileSystemDatastore.query | train | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`
FSDatastore.query queries all the `.obj` files within the directory
specified by the query.key.
Args:
query: Query object describing the objects to return.
Raturns:
Cursor with all objects ... | python | {
"resource": ""
} |
q241057 | FileSystemDatastore.contains | train | def contains(self, key):
'''Returns whether the object named by `key` exists.
Optimized to only check whether the file object exists.
Args:
key: Key naming the object to check.
Returns:
boalean whether the object exists
'''
path = self.object_path(key)
return os.path.exists(pat... | python | {
"resource": ""
} |
q241058 | DictDatastore._collection | train | def _collection(self, key):
'''Returns the namespace collection for `key`.'''
collection = str(key.path)
if not collection in self._items:
self._items[collection] = dict()
return self._items[collection] | python | {
"resource": ""
} |
q241059 | DictDatastore.query | train | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`
Naively applies the query operations on the objects within the namespaced
collection corresponding to ``query.key.path``.
Args:
query: Query object describing the objects to return.
Raturns:
... | python | {
"resource": ""
} |
q241060 | InterfaceMappingDatastore.get | train | def get(self, key):
'''Return the object in `service` named by `key` or None.
Args:
key: Key naming the object to retrieve.
Returns:
object or None
'''
key = self._service_key(key)
return self._service_ops['get'](key) | python | {
"resource": ""
} |
q241061 | InterfaceMappingDatastore.put | train | def put(self, key, value):
'''Stores the object `value` named by `key` in `service`.
Args:
key: Key naming `value`.
value: the object to store.
'''
key = self._service_key(key)
self._service_ops['put'](key, value) | python | {
"resource": ""
} |
q241062 | InterfaceMappingDatastore.delete | train | def delete(self, key):
'''Removes the object named by `key` in `service`.
Args:
key: Key naming the object to remove.
'''
key = self._service_key(key)
self._service_ops['delete'](key) | python | {
"resource": ""
} |
q241063 | CacheShimDatastore.get | train | def get(self, key):
'''Return the object named by key or None if it does not exist.
CacheShimDatastore first checks its ``cache_datastore``.
'''
value = self.cache_datastore.get(key)
return value if value is not None else self.child_datastore.get(key) | python | {
"resource": ""
} |
q241064 | CacheShimDatastore.put | train | def put(self, key, value):
'''Stores the object `value` named by `key`self.
Writes to both ``cache_datastore`` and ``child_datastore``.
'''
self.cache_datastore.put(key, value)
self.child_datastore.put(key, value) | python | {
"resource": ""
} |
q241065 | CacheShimDatastore.delete | train | def delete(self, key):
'''Removes the object named by `key`.
Writes to both ``cache_datastore`` and ``child_datastore``.
'''
self.cache_datastore.delete(key)
self.child_datastore.delete(key) | python | {
"resource": ""
} |
q241066 | CacheShimDatastore.contains | train | def contains(self, key):
'''Returns whether the object named by `key` exists.
First checks ``cache_datastore``.
'''
return self.cache_datastore.contains(key) \
or self.child_datastore.contains(key) | python | {
"resource": ""
} |
q241067 | LoggingDatastore.get | train | def get(self, key):
'''Return the object named by key or None if it does not exist.
LoggingDatastore logs the access.
'''
self.logger.info('%s: get %s' % (self, key))
value = super(LoggingDatastore, self).get(key)
self.logger.debug('%s: %s' % (self, value))
return value | python | {
"resource": ""
} |
q241068 | LoggingDatastore.delete | train | def delete(self, key):
'''Removes the object named by `key`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: delete %s' % (self, key))
super(LoggingDatastore, self).delete(key) | python | {
"resource": ""
} |
q241069 | LoggingDatastore.contains | train | def contains(self, key):
'''Returns whether the object named by `key` exists.
LoggingDatastore logs the access.
'''
self.logger.info('%s: contains %s' % (self, key))
return super(LoggingDatastore, self).contains(key) | python | {
"resource": ""
} |
q241070 | LoggingDatastore.query | train | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: query %s' % (self, query))
return super(LoggingDatastore, self).query(query) | python | {
"resource": ""
} |
q241071 | NestedPathDatastore.nestKey | train | def nestKey(self, key):
'''Returns a nested `key`.'''
nest = self.nest_keyfn(key)
# if depth * length > len(key.name), we need to pad.
mult = 1 + int(self.nest_depth * self.nest_length / len(nest))
nest = nest * mult
pref = Key(self.nestedPath(nest, self.nest_depth, self.nest_length))
ret... | python | {
"resource": ""
} |
q241072 | SymlinkDatastore._link_for_value | train | def _link_for_value(self, value):
'''Returns the linked key if `value` is a link, or None.'''
try:
key = Key(value)
if key.name == self.sentinel:
return key.parent
except:
pass
return None | python | {
"resource": ""
} |
q241073 | SymlinkDatastore._follow_link | train | def _follow_link(self, value):
'''Returns given `value` or, if it is a symlink, the `value` it names.'''
seen_keys = set()
while True:
link_key = self._link_for_value(value)
if not link_key:
return value
assert link_key not in seen_keys, 'circular symlink reference'
seen_key... | python | {
"resource": ""
} |
q241074 | SymlinkDatastore.link | train | def link(self, source_key, target_key):
'''Creates a symbolic link key pointing from `target_key` to `source_key`'''
link_value = self._link_value_for_key(source_key)
# put straight into the child, to avoid following previous links.
self.child_datastore.put(target_key, link_value)
# exercise the l... | python | {
"resource": ""
} |
q241075 | SymlinkDatastore.get | train | def get(self, key):
'''Return the object named by `key. Follows links.'''
value = super(SymlinkDatastore, self).get(key)
return self._follow_link(value) | python | {
"resource": ""
} |
q241076 | SymlinkDatastore.put | train | def put(self, key, value):
'''Stores the object named by `key`. Follows links.'''
# if value is a link, don't follow links
if self._link_for_value(value):
super(SymlinkDatastore, self).put(key, value)
return
# if `key` points to a symlink, need to follow it.
current_value = super(Symlin... | python | {
"resource": ""
} |
q241077 | SymlinkDatastore.query | train | def query(self, query):
'''Returns objects matching criteria expressed in `query`. Follows links.'''
results = super(SymlinkDatastore, self).query(query)
return self._follow_link_gen(results) | python | {
"resource": ""
} |
q241078 | DirectoryDatastore.directory | train | def directory(self, dir_key):
'''Initializes directory at dir_key.'''
dir_items = self.get(dir_key)
if not isinstance(dir_items, list):
self.put(dir_key, []) | python | {
"resource": ""
} |
q241079 | DirectoryDatastore.directoryAdd | train | def directoryAdd(self, dir_key, key):
'''Adds directory entry `key` to directory at `dir_key`.
If the directory `dir_key` does not exist, it is created.
'''
key = str(key)
dir_items = self.get(dir_key) or []
if key not in dir_items:
dir_items.append(key)
self.put(dir_key, dir_items... | python | {
"resource": ""
} |
q241080 | DirectoryDatastore.directoryRemove | train | def directoryRemove(self, dir_key, key):
'''Removes directory entry `key` from directory at `dir_key`.
If either the directory `dir_key` or the directory entry `key` don't exist,
this method is a no-op.
'''
key = str(key)
dir_items = self.get(dir_key) or []
if key in dir_items:
dir_i... | python | {
"resource": ""
} |
q241081 | DirectoryTreeDatastore.put | train | def put(self, key, value):
'''Stores the object `value` named by `key`self.
DirectoryTreeDatastore stores a directory entry.
'''
super(DirectoryTreeDatastore, self).put(key, value)
str_key = str(key)
# ignore root
if str_key == '/':
return
# retrieve directory, to add entry
... | python | {
"resource": ""
} |
q241082 | DirectoryTreeDatastore.delete | train | def delete(self, key):
'''Removes the object named by `key`.
DirectoryTreeDatastore removes the directory entry.
'''
super(DirectoryTreeDatastore, self).delete(key)
str_key = str(key)
# ignore root
if str_key == '/':
return
# retrieve directory, to remove entry
dir_key = ... | python | {
"resource": ""
} |
q241083 | DirectoryTreeDatastore.directory | train | def directory(self, key):
'''Retrieves directory entries for given key.'''
if key.name != 'directory':
key = key.instance('directory')
return self.get(key) or [] | python | {
"resource": ""
} |
q241084 | DirectoryTreeDatastore.directory_values_generator | train | def directory_values_generator(self, key):
'''Retrieve directory values for given key.'''
directory = self.directory(key)
for key in directory:
yield self.get(Key(key)) | python | {
"resource": ""
} |
q241085 | DatastoreCollection.appendDatastore | train | def appendDatastore(self, store):
'''Appends datastore `store` to this collection.'''
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.append(store) | python | {
"resource": ""
} |
q241086 | DatastoreCollection.insertDatastore | train | def insertDatastore(self, index, store):
'''Inserts datastore `store` into this collection at `index`.'''
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.insert(index, store) | python | {
"resource": ""
} |
q241087 | TieredDatastore.get | train | def get(self, key):
'''Return the object named by key. Checks each datastore in order.'''
value = None
for store in self._stores:
value = store.get(key)
if value is not None:
break
# add model to lower stores only
if value is not None:
for store2 in self._stores:
i... | python | {
"resource": ""
} |
q241088 | TieredDatastore.put | train | def put(self, key, value):
'''Stores the object in all underlying datastores.'''
for store in self._stores:
store.put(key, value) | python | {
"resource": ""
} |
q241089 | TieredDatastore.contains | train | def contains(self, key):
'''Returns whether the object is in this datastore.'''
for store in self._stores:
if store.contains(key):
return True
return False | python | {
"resource": ""
} |
q241090 | ShardedDatastore.put | train | def put(self, key, value):
'''Stores the object to the corresponding datastore.'''
self.shardDatastore(key).put(key, value) | python | {
"resource": ""
} |
q241091 | ShardedDatastore.shard_query_generator | train | def shard_query_generator(self, query):
'''A generator that queries each shard in sequence.'''
shard_query = query.copy()
for shard in self._stores:
# yield all items matching within this shard
cursor = shard.query(shard_query)
for item in cursor:
yield item
# update query ... | python | {
"resource": ""
} |
q241092 | monkey_patch_bson | train | def monkey_patch_bson(bson=None):
'''Patch bson in pymongo to use loads and dumps interface.'''
if not bson:
import bson
if not hasattr(bson, 'loads'):
bson.loads = lambda bsondoc: bson.BSON(bsondoc).decode()
if not hasattr(bson, 'dumps'):
bson.dumps = lambda document: bson.BSON.encode(document) | python | {
"resource": ""
} |
q241093 | Stack.loads | train | def loads(self, value):
'''Returns deserialized `value`.'''
for serializer in reversed(self):
value = serializer.loads(value)
return value | python | {
"resource": ""
} |
q241094 | Stack.dumps | train | def dumps(self, value):
'''returns serialized `value`.'''
for serializer in self:
value = serializer.dumps(value)
return value | python | {
"resource": ""
} |
q241095 | map_serializer.loads | train | def loads(cls, value):
'''Returns mapping type deserialized `value`.'''
if len(value) == 1 and cls.sentinel in value:
value = value[cls.sentinel]
return value | python | {
"resource": ""
} |
q241096 | map_serializer.dumps | train | def dumps(cls, value):
'''returns mapping typed serialized `value`.'''
if not hasattr(value, '__getitem__') or not hasattr(value, 'iteritems'):
value = {cls.sentinel: value}
return value | python | {
"resource": ""
} |
q241097 | SerializerShimDatastore.get | train | def get(self, key):
'''Return the object named by key or None if it does not exist.
Retrieves the value from the ``child_datastore``, and de-serializes
it on the way out.
Args:
key: Key naming the object to retrieve
Returns:
object or None
'''
''''''
value = self.child_dat... | python | {
"resource": ""
} |
q241098 | SerializerShimDatastore.put | train | def put(self, key, value):
'''Stores the object `value` named by `key`.
Serializes values on the way in, and stores the serialized data into the
``child_datastore``.
Args:
key: Key naming `value`
value: the object to store.
'''
value = self.serializedValue(value)
self.child_dat... | python | {
"resource": ""
} |
q241099 | _object_getattr | train | def _object_getattr(obj, field):
'''Attribute getter for the objects to operate on.
This function can be overridden in classes or instances of Query, Filter, and
Order. Thus, a custom function to extract values to attributes can be
specified, and the system can remain agnostic to the client's data model,
wit... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.