repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
pypa/pipenv
pipenv/vendor/jinja2/filters.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/filters.py#L701-L734
def do_slice(value, slices, fill_with=None): """Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration. """ seq = list(value) length = len(seq) items_per_slice = length // slices slices_with_extra = length % slices offset = 0 for slice_number in range(slices): start = offset + slice_number * items_per_slice if slice_number < slices_with_extra: offset += 1 end = offset + (slice_number + 1) * items_per_slice tmp = seq[start:end] if fill_with is not None and slice_number >= slices_with_extra: tmp.append(fill_with) yield tmp
[ "def", "do_slice", "(", "value", ",", "slices", ",", "fill_with", "=", "None", ")", ":", "seq", "=", "list", "(", "value", ")", "length", "=", "len", "(", "seq", ")", "items_per_slice", "=", "length", "//", "slices", "slices_with_extra", "=", "length", ...
Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns: .. sourcecode:: html+jinja <div class="columwrapper"> {%- for column in items|slice(3) %} <ul class="column-{{ loop.index }}"> {%- for item in column %} <li>{{ item }}</li> {%- endfor %} </ul> {%- endfor %} </div> If you pass it a second argument it's used to fill missing values on the last iteration.
[ "Slice", "an", "iterator", "and", "return", "a", "list", "of", "lists", "containing", "those", "items", ".", "Useful", "if", "you", "want", "to", "create", "a", "div", "containing", "three", "ul", "tags", "that", "represent", "columns", ":" ]
python
train
obriencj/python-javatools
javatools/jarutil.py
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/jarutil.py#L221-L240
def create_jar(jar_file, entries): """ Create JAR from given entries. :param jar_file: filename of the created JAR :type jar_file: str :param entries: files to put into the JAR :type entries: list[str] :return: None """ # 'jar' adds separate entries for directories, also for empty ones. with ZipFile(jar_file, "w") as jar: jar.writestr("META-INF/", "") jar.writestr("META-INF/MANIFEST.MF", Manifest().get_data()) for entry in entries: jar.write(entry) if os.path.isdir(entry): for root, dirs, files in os.walk(entry): for filename in dirs + files: jar.write(os.path.join(root, filename))
[ "def", "create_jar", "(", "jar_file", ",", "entries", ")", ":", "# 'jar' adds separate entries for directories, also for empty ones.", "with", "ZipFile", "(", "jar_file", ",", "\"w\"", ")", "as", "jar", ":", "jar", ".", "writestr", "(", "\"META-INF/\"", ",", "\"\"",...
Create JAR from given entries. :param jar_file: filename of the created JAR :type jar_file: str :param entries: files to put into the JAR :type entries: list[str] :return: None
[ "Create", "JAR", "from", "given", "entries", ".", ":", "param", "jar_file", ":", "filename", "of", "the", "created", "JAR", ":", "type", "jar_file", ":", "str", ":", "param", "entries", ":", "files", "to", "put", "into", "the", "JAR", ":", "type", "ent...
python
train
guaix-ucm/numina
numina/types/datatype.py
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/types/datatype.py#L50-L66
def validate(self, obj): """Validate convertibility to internal representation Returns ------- bool True if 'obj' matches the data type Raises ------- ValidationError If the validation fails """ if not isinstance(obj, self.internal_type): raise ValidationError(obj, self.internal_type) return True
[ "def", "validate", "(", "self", ",", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "self", ".", "internal_type", ")", ":", "raise", "ValidationError", "(", "obj", ",", "self", ".", "internal_type", ")", "return", "True" ]
Validate convertibility to internal representation Returns ------- bool True if 'obj' matches the data type Raises ------- ValidationError If the validation fails
[ "Validate", "convertibility", "to", "internal", "representation" ]
python
train
tehmaze/diagram
diagram.py
https://github.com/tehmaze/diagram/blob/1701526a91c14dc8ebc6452c45c8ec9a563a56db/diagram.py#L79-L97
def size(self): """Get the current terminal size.""" for fd in range(3): cr = self._ioctl_GWINSZ(fd) if cr: break if not cr: try: fd = os.open(os.ctermid(), os.O_RDONLY) cr = self._ioctl_GWINSZ(fd) os.close(fd) except Exception: pass if not cr: env = os.environ cr = (env.get('LINES', 25), env.get('COLUMNS', 80)) return int(cr[1]), int(cr[0])
[ "def", "size", "(", "self", ")", ":", "for", "fd", "in", "range", "(", "3", ")", ":", "cr", "=", "self", ".", "_ioctl_GWINSZ", "(", "fd", ")", "if", "cr", ":", "break", "if", "not", "cr", ":", "try", ":", "fd", "=", "os", ".", "open", "(", ...
Get the current terminal size.
[ "Get", "the", "current", "terminal", "size", "." ]
python
valid
the01/paps-settings
paps_settings/plugin.py
https://github.com/the01/paps-settings/blob/48fb65eb0fa7929a0bb381c6dad28d0197b44c83/paps_settings/plugin.py#L116-L249
def handle_msg(self, payload): """ Handle message for network plugin protocol :param payload: Received message :type payload: dict :return: Response to send (if set) :rtype: None | dict """ self.debug(u"\n{}".format(pformat(payload))) msg = payload['msg'] res = { 'msg': msg, 'error': "" } if msg == "plugin_list": res['plugin_names'] = [] # Generate list of plugins available for frontend for plugin in self.controller.plugins: # Limit to plugins that work with this if isinstance(plugin, SettablePlugin): res['plugin_names'].append(plugin.name) return res elif msg == "plugin_get": res['plugin'] = {} plugin_name = payload.get('plugin_name') plugin, err = self._plugin_get(plugin_name) if not plugin: res['error'] = err return res res['plugin_name'] = plugin_name res['plugin'] = plugin.get_info() return res elif msg == "plugin_resource_list": res['resource_names'] = [] plugin_name = payload.get('plugin_name') plugin, err = self._plugin_get(plugin_name) if not plugin: res['error'] = err return res res['plugin_name'] = plugin_name try: res['resource_names'] = plugin.resource_get_list() except PluginException as e: if str(e) == "No resource path set": self.debug( u"Plugin '{}' has no resources".format(plugin.name) ) else: self.exception( u"Failed to get resource list for plugin '{}'".format( plugin.name ) ) return res elif msg == "plugin_resource_get": res['resource'] = {} plugin_name = payload.get('plugin_name') resource_name = payload.get('resource_name') if not resource_name: res['error'] = "Resource name not set" return res plugin, err = self._plugin_get(plugin_name) if not plugin: res['error'] = err return res res['plugin_name'] = plugin_name res['resource_name'] = resource_name res['resource'] = dict(plugin.resource_get(resource_name)) if "path" in res['resource']: del res['resource']['path'] return res elif msg == "plugin_resource_load": res['resource_data'] = "" plugin_name = payload.get('plugin_name') resource_name = payload.get('resource_name') if not resource_name: res['error'] = "Resource name not set" return res plugin, err = self._plugin_get(plugin_name) if not plugin: res['error'] = err return res res['plugin_name'] = plugin_name res['resource_name'] = resource_name resource_dict = plugin.resource_get(resource_name) if not resource_dict: res['error'] = u"Resource '{}' not found".format(resource_name) return res self.debug(u"Resource {}".format(resource_dict)) try: with open(resource_dict['path'], 'rb') as f: res['resource_data'] = base64.b64encode(f.read()) except: self.exception( u"Failed to load '{}'".format(resource_dict['path']) ) res['error'] = u"Failed to load" return res elif msg == "plugin_data_get": plugin_name = payload.get('plugin_name') plugin, err = self._plugin_get(plugin_name) if not plugin: res['error'] = err return res res['plugin_name'] = plugin_name res['data'] = plugin.get_data() return res elif msg == "plugin_data_set": plugin_name = payload.get('plugin_name') plugin, err = self._plugin_get(plugin_name) if not plugin: res['error'] = err return res res['plugin_name'] = plugin_name data = payload.get('data') if not data: res['error'] = u"No data provided" return res try: plugin.on_config(data) except NotImplementedError: res['error'] = u"Plugin does not support setting data" return res except: self.exception( u"Failed to set data for {}".format(plugin_name) ) res['error'] = "Failed to set data" return res return {} else: self.error(u"Unknown cmd '{}'\n{}".format(msg, payload)) return {}
[ "def", "handle_msg", "(", "self", ",", "payload", ")", ":", "self", ".", "debug", "(", "u\"\\n{}\"", ".", "format", "(", "pformat", "(", "payload", ")", ")", ")", "msg", "=", "payload", "[", "'msg'", "]", "res", "=", "{", "'msg'", ":", "msg", ",", ...
Handle message for network plugin protocol :param payload: Received message :type payload: dict :return: Response to send (if set) :rtype: None | dict
[ "Handle", "message", "for", "network", "plugin", "protocol" ]
python
train
aliyun/aliyun-odps-python-sdk
odps/tunnel/pb/wire_format.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/tunnel/pb/wire_format.py#L210-L220
def _var_uint64_byte_size_no_tag(uint64): """Returns the bytes required to serialize a single varint. uint64 must be unsigned. """ if uint64 > UINT64_MAX: raise errors.EncodeError('Value out of range: %d' % uint64) bytes = 1 while uint64 > 0x7f: bytes += 1 uint64 >>= 7 return bytes
[ "def", "_var_uint64_byte_size_no_tag", "(", "uint64", ")", ":", "if", "uint64", ">", "UINT64_MAX", ":", "raise", "errors", ".", "EncodeError", "(", "'Value out of range: %d'", "%", "uint64", ")", "bytes", "=", "1", "while", "uint64", ">", "0x7f", ":", "bytes",...
Returns the bytes required to serialize a single varint. uint64 must be unsigned.
[ "Returns", "the", "bytes", "required", "to", "serialize", "a", "single", "varint", ".", "uint64", "must", "be", "unsigned", "." ]
python
train
workforce-data-initiative/skills-utils
skills_utils/iteration.py
https://github.com/workforce-data-initiative/skills-utils/blob/4cf9b7c2938984f34bbcc33d45482d23c52c7539/skills_utils/iteration.py#L23-L33
def group(self): """Yield a group from the iterable""" yield self.current # start enumerate at 1 because we already yielded the last saved item for num, item in enumerate(self.iterator, 1): self.current = item if num == self.limit: break yield item else: self.on_going = False
[ "def", "group", "(", "self", ")", ":", "yield", "self", ".", "current", "# start enumerate at 1 because we already yielded the last saved item", "for", "num", ",", "item", "in", "enumerate", "(", "self", ".", "iterator", ",", "1", ")", ":", "self", ".", "current...
Yield a group from the iterable
[ "Yield", "a", "group", "from", "the", "iterable" ]
python
train
mitsei/dlkit
dlkit/handcar/learning/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/sessions.py#L897-L911
def can_delete_objectives(self): """Tests if this user can delete Objectives. A return of true does not guarantee successful authorization. A return of false indicates that it is known deleting an Objective will result in a PermissionDenied. This is intended as a hint to an application that may opt not to offer delete operations to an unauthorized user. return: (boolean) - false if Objective deletion is not authorized, true otherwise compliance: mandatory - This method must be implemented. """ url_path = construct_url('authorization', bank_id=self._catalog_idstr) return self._get_request(url_path)['objectiveHints']['canDelete']
[ "def", "can_delete_objectives", "(", "self", ")", ":", "url_path", "=", "construct_url", "(", "'authorization'", ",", "bank_id", "=", "self", ".", "_catalog_idstr", ")", "return", "self", ".", "_get_request", "(", "url_path", ")", "[", "'objectiveHints'", "]", ...
Tests if this user can delete Objectives. A return of true does not guarantee successful authorization. A return of false indicates that it is known deleting an Objective will result in a PermissionDenied. This is intended as a hint to an application that may opt not to offer delete operations to an unauthorized user. return: (boolean) - false if Objective deletion is not authorized, true otherwise compliance: mandatory - This method must be implemented.
[ "Tests", "if", "this", "user", "can", "delete", "Objectives", ".", "A", "return", "of", "true", "does", "not", "guarantee", "successful", "authorization", ".", "A", "return", "of", "false", "indicates", "that", "it", "is", "known", "deleting", "an", "Objecti...
python
train
jtwhite79/pyemu
pyemu/mat/mat_handler.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/mat/mat_handler.py#L860-L872
def as_2d(self): """ get a 2D representation of x. If not self.isdiagonal, simply return reference to self.x, otherwise, constructs and returns a 2D, diagonal ndarray Returns ------- numpy.ndarray : numpy.ndarray """ if not self.isdiagonal: return self.x return np.diag(self.x.flatten())
[ "def", "as_2d", "(", "self", ")", ":", "if", "not", "self", ".", "isdiagonal", ":", "return", "self", ".", "x", "return", "np", ".", "diag", "(", "self", ".", "x", ".", "flatten", "(", ")", ")" ]
get a 2D representation of x. If not self.isdiagonal, simply return reference to self.x, otherwise, constructs and returns a 2D, diagonal ndarray Returns ------- numpy.ndarray : numpy.ndarray
[ "get", "a", "2D", "representation", "of", "x", ".", "If", "not", "self", ".", "isdiagonal", "simply", "return", "reference", "to", "self", ".", "x", "otherwise", "constructs", "and", "returns", "a", "2D", "diagonal", "ndarray" ]
python
train
napalm-automation/napalm-yang
interactive_demo/ansible/callback/selective.py
https://github.com/napalm-automation/napalm-yang/blob/998e8a933171d010b8544bcc5dc448e2b68051e2/interactive_demo/ansible/callback/selective.py#L264-L288
def v2_runner_on_skipped(self, result, **kwargs): """Run when a task is skipped.""" if self._display.verbosity > 1: self._print_task() self.last_skipped = False line_length = 120 spaces = " " * (31 - len(result._host.name) - 4) line = " * {}{}- {}".format( colorize(result._host.name, "not_so_bold"), spaces, colorize("skipped", "skipped"), ) reason = result._result.get("skipped_reason", "") or result._result.get( "skip_reason", "" ) if len(reason) < 50: line += " -- {}".format(reason) print("{} {}---------".format(line, "-" * (line_length - len(line)))) else: print("{} {}".format(line, "-" * (line_length - len(line)))) print(self._indent_text(reason, 8)) print(reason)
[ "def", "v2_runner_on_skipped", "(", "self", ",", "result", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_display", ".", "verbosity", ">", "1", ":", "self", ".", "_print_task", "(", ")", "self", ".", "last_skipped", "=", "False", "line_length", ...
Run when a task is skipped.
[ "Run", "when", "a", "task", "is", "skipped", "." ]
python
test
MacHu-GWU/superjson-project
superjson/pkg/dateutil/zoneinfo/__init__.py
https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/zoneinfo/__init__.py#L166-L186
def gettz_db_metadata(): """ Get the zonefile metadata See `zonefile_metadata`_ :returns: A dictionary with the database metadata .. deprecated:: 2.6 See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, query the attribute ``zoneinfo.ZoneInfoFile.metadata``. """ warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future " "versions, to use the dateutil-provided zoneinfo files, " "ZoneInfoFile object and query the 'metadata' attribute " "instead. See the documentation for details.", DeprecationWarning) if len(_CLASS_ZONE_INSTANCE) == 0: _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) return _CLASS_ZONE_INSTANCE[0].metadata
[ "def", "gettz_db_metadata", "(", ")", ":", "warnings", ".", "warn", "(", "\"zoneinfo.gettz_db_metadata() will be removed in future \"", "\"versions, to use the dateutil-provided zoneinfo files, \"", "\"ZoneInfoFile object and query the 'metadata' attribute \"", "\"instead. See the documentat...
Get the zonefile metadata See `zonefile_metadata`_ :returns: A dictionary with the database metadata .. deprecated:: 2.6 See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, query the attribute ``zoneinfo.ZoneInfoFile.metadata``.
[ "Get", "the", "zonefile", "metadata" ]
python
valid
ibm-watson-iot/iot-python
src/wiotp/sdk/api/services/__init__.py
https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/services/__init__.py#L207-L232
def find(self, nameFilter=None, typeFilter=None, bindingModeFilter=None, boundFilter=None): """ Gets the list of services that the Watson IoT Platform can connect to. The list can include a mixture of services that are either bound or unbound. Parameters: - nameFilter(string) - Filter the results by the specified name - typeFilter(string) - Filter the results by the specified type, Available values : cloudant, eventstreams - bindingModeFilter(string) - Filter the results by the specified binding mode, Available values : automatic, manual - boundFilter(boolean) - Filter the results by the bound flag Throws APIException on failure. """ queryParms = {} if nameFilter: queryParms["name"] = nameFilter if typeFilter: queryParms["type"] = typeFilter if bindingModeFilter: queryParms["bindingMode"] = bindingModeFilter if boundFilter: queryParms["bound"] = boundFilter return IterableServiceBindingsList(self._apiClient, filters=queryParms)
[ "def", "find", "(", "self", ",", "nameFilter", "=", "None", ",", "typeFilter", "=", "None", ",", "bindingModeFilter", "=", "None", ",", "boundFilter", "=", "None", ")", ":", "queryParms", "=", "{", "}", "if", "nameFilter", ":", "queryParms", "[", "\"name...
Gets the list of services that the Watson IoT Platform can connect to. The list can include a mixture of services that are either bound or unbound. Parameters: - nameFilter(string) - Filter the results by the specified name - typeFilter(string) - Filter the results by the specified type, Available values : cloudant, eventstreams - bindingModeFilter(string) - Filter the results by the specified binding mode, Available values : automatic, manual - boundFilter(boolean) - Filter the results by the bound flag Throws APIException on failure.
[ "Gets", "the", "list", "of", "services", "that", "the", "Watson", "IoT", "Platform", "can", "connect", "to", ".", "The", "list", "can", "include", "a", "mixture", "of", "services", "that", "are", "either", "bound", "or", "unbound", ".", "Parameters", ":", ...
python
test
elsampsa/valkka-live
valkka/mvision/yolo3/base.py
https://github.com/elsampsa/valkka-live/blob/218bb2ecf71c516c85b1b6e075454bba13090cd8/valkka/mvision/yolo3/base.py#L162-L169
def postActivate_(self): """Whatever you need to do after creating the shmem client """ if (self.requiredGPU_MB(self.required_mb)): self.analyzer = YoloV3Analyzer(verbose = self.verbose) else: self.warning_message = "WARNING: not enough GPU memory!" self.analyzer = None
[ "def", "postActivate_", "(", "self", ")", ":", "if", "(", "self", ".", "requiredGPU_MB", "(", "self", ".", "required_mb", ")", ")", ":", "self", ".", "analyzer", "=", "YoloV3Analyzer", "(", "verbose", "=", "self", ".", "verbose", ")", "else", ":", "sel...
Whatever you need to do after creating the shmem client
[ "Whatever", "you", "need", "to", "do", "after", "creating", "the", "shmem", "client" ]
python
train
aliyun/aliyun-odps-python-sdk
odps/df/expr/merge.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/merge.py#L1048-L1110
def intersect(left, *rights, **kwargs): """ Calc intersection among datasets, :param left: collection :param rights: collection or list of collections :param distinct: whether to preserve duolicate entries :return: collection :Examples: >>> import pandas as pd >>> df1 = DataFrame(pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, 3, 3, 3]})) >>> df2 = DataFrame(pd.DataFrame({'a': [1, 3, 3], 'b': [1, 3, 3]})) >>> df1.intersect(df2) a b 0 1 1 1 3 3 2 3 3 >>> df1.intersect(df2, distinct=True) a b 0 1 1 1 3 3 """ import time from ..utils import output distinct = kwargs.get('distinct', False) if isinstance(rights[0], list): rights = rights[0] cols = [n for n in left.schema.names] types = [n for n in left.schema.types] collections = (left, ) + rights idx_col_name = 'idx_%d' % int(time.time()) counter_col_name = 'exc_counter_%d' % int(time.time()) collections = [c[c, Scalar(idx).rename(idx_col_name)] for idx, c in enumerate(collections)] unioned = reduce(lambda a, b: a.union(b), collections) src_agg = unioned.groupby(*(cols + [idx_col_name])) \ .agg(**{counter_col_name: unioned.count()}) aggregators = { idx_col_name: src_agg[idx_col_name].nunique(), counter_col_name: src_agg[counter_col_name].min(), } final_agg = src_agg.groupby(*cols).agg(**aggregators) final_agg = final_agg.filter(final_agg[idx_col_name] == len(collections)) if distinct: return final_agg.filter(final_agg[counter_col_name] > 0).select(*cols) else: @output(cols, types) def exploder(row): import sys irange = xrange if sys.version_info[0] < 3 else range for _ in irange(getattr(row, counter_col_name)): yield row[:-2] return final_agg.map_reduce(mapper=exploder).select(*cols)
[ "def", "intersect", "(", "left", ",", "*", "rights", ",", "*", "*", "kwargs", ")", ":", "import", "time", "from", ".", ".", "utils", "import", "output", "distinct", "=", "kwargs", ".", "get", "(", "'distinct'", ",", "False", ")", "if", "isinstance", ...
Calc intersection among datasets, :param left: collection :param rights: collection or list of collections :param distinct: whether to preserve duolicate entries :return: collection :Examples: >>> import pandas as pd >>> df1 = DataFrame(pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, 3, 3, 3]})) >>> df2 = DataFrame(pd.DataFrame({'a': [1, 3, 3], 'b': [1, 3, 3]})) >>> df1.intersect(df2) a b 0 1 1 1 3 3 2 3 3 >>> df1.intersect(df2, distinct=True) a b 0 1 1 1 3 3
[ "Calc", "intersection", "among", "datasets" ]
python
train
pyviz/param
param/version.py
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/version.py#L231-L244
def _output_from_file(self, entry='git_describe'): """ Read the version from a .version file that may exist alongside __init__.py. This file can be generated by piping the following output to file: git describe --long --match v*.* """ try: vfile = os.path.join(os.path.dirname(self.fpath), '.version') with open(vfile, 'r') as f: return json.loads(f.read()).get(entry, None) except: # File may be missing if using pip + git archive return None
[ "def", "_output_from_file", "(", "self", ",", "entry", "=", "'git_describe'", ")", ":", "try", ":", "vfile", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "fpath", ")", ",", "'.version'", ")", "with", ...
Read the version from a .version file that may exist alongside __init__.py. This file can be generated by piping the following output to file: git describe --long --match v*.*
[ "Read", "the", "version", "from", "a", ".", "version", "file", "that", "may", "exist", "alongside", "__init__", ".", "py", "." ]
python
train
Yubico/python-pyhsm
examples/yhsm-password-auth.py
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/examples/yhsm-password-auth.py#L108-L120
def generate_aead(hsm, args, password): """ Generate an AEAD using the YubiHSM. """ try: pw = password.ljust(args.min_len, chr(0x0)) return hsm.generate_aead_simple(args.nonce.decode('hex'), args.key_handle, pw) except pyhsm.exception.YHSM_CommandFailed, e: if e.status_str == 'YHSM_FUNCTION_DISABLED': print "ERROR: The key handle %s is not permitted to YSM_AEAD_GENERATE." % (args.key_handle) return None else: print "ERROR: %s" % (e.reason)
[ "def", "generate_aead", "(", "hsm", ",", "args", ",", "password", ")", ":", "try", ":", "pw", "=", "password", ".", "ljust", "(", "args", ".", "min_len", ",", "chr", "(", "0x0", ")", ")", "return", "hsm", ".", "generate_aead_simple", "(", "args", "."...
Generate an AEAD using the YubiHSM.
[ "Generate", "an", "AEAD", "using", "the", "YubiHSM", "." ]
python
train
hyperledger/indy-plenum
plenum/server/replica.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L1581-L1595
def addToPrePrepares(self, pp: PrePrepare) -> None: """ Add the specified PRE-PREPARE to this replica's list of received PRE-PREPAREs and try sending PREPARE :param pp: the PRE-PREPARE to add to the list """ key = (pp.viewNo, pp.ppSeqNo) self.prePrepares[key] = pp self.lastPrePrepareSeqNo = pp.ppSeqNo self.last_accepted_pre_prepare_time = pp.ppTime self.dequeue_prepares(*key) self.dequeue_commits(*key) self.stats.inc(TPCStat.PrePrepareRcvd) self.tryPrepare(pp)
[ "def", "addToPrePrepares", "(", "self", ",", "pp", ":", "PrePrepare", ")", "->", "None", ":", "key", "=", "(", "pp", ".", "viewNo", ",", "pp", ".", "ppSeqNo", ")", "self", ".", "prePrepares", "[", "key", "]", "=", "pp", "self", ".", "lastPrePrepareSe...
Add the specified PRE-PREPARE to this replica's list of received PRE-PREPAREs and try sending PREPARE :param pp: the PRE-PREPARE to add to the list
[ "Add", "the", "specified", "PRE", "-", "PREPARE", "to", "this", "replica", "s", "list", "of", "received", "PRE", "-", "PREPAREs", "and", "try", "sending", "PREPARE" ]
python
train
adamhadani/python-yelp
yelp/api.py
https://github.com/adamhadani/python-yelp/blob/7694ccb7274cc3c5783250ed0c3396cda2fcfa1a/yelp/api.py#L104-L131
def by_bounding_box(self, tl_lat, tl_long, br_lat, br_long, term=None, num_biz_requested=None, category=None): """ Perform a Yelp Review Search based on a map bounding box. Args: tl_lat - bounding box top left latitude tl_long - bounding box top left longitude br_lat - bounding box bottom right latitude br_long - bounding box bottom right longitude term - Search term to filter by (Optional) num_biz_requested - Maximum number of matching results to return (Optional) category - '+'-seperated list of categories to filter by. See http://www.yelp.com/developers/documentation/category_list for list of valid categories. (Optional) """ header, content = self._http_request( self.BASE_URL, tl_lat = tl_lat, tl_long = tl_long, br_lat = br_lat, br_long = br_long, term = term, category = category, num_biz_requested = num_biz_requested ) return json.loads(content)
[ "def", "by_bounding_box", "(", "self", ",", "tl_lat", ",", "tl_long", ",", "br_lat", ",", "br_long", ",", "term", "=", "None", ",", "num_biz_requested", "=", "None", ",", "category", "=", "None", ")", ":", "header", ",", "content", "=", "self", ".", "_...
Perform a Yelp Review Search based on a map bounding box. Args: tl_lat - bounding box top left latitude tl_long - bounding box top left longitude br_lat - bounding box bottom right latitude br_long - bounding box bottom right longitude term - Search term to filter by (Optional) num_biz_requested - Maximum number of matching results to return (Optional) category - '+'-seperated list of categories to filter by. See http://www.yelp.com/developers/documentation/category_list for list of valid categories. (Optional)
[ "Perform", "a", "Yelp", "Review", "Search", "based", "on", "a", "map", "bounding", "box", "." ]
python
train
saltstack/salt
salt/cloud/clouds/msazure.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L113-L136
def get_conn(): ''' Return a conn object for the passed VM data ''' certificate_path = config.get_cloud_config_value( 'certificate_path', get_configured_provider(), __opts__, search_global=False ) subscription_id = salt.utils.stringutils.to_str( config.get_cloud_config_value( 'subscription_id', get_configured_provider(), __opts__, search_global=False ) ) management_host = config.get_cloud_config_value( 'management_host', get_configured_provider(), __opts__, search_global=False, default='management.core.windows.net' ) return azure.servicemanagement.ServiceManagementService( subscription_id, certificate_path, management_host )
[ "def", "get_conn", "(", ")", ":", "certificate_path", "=", "config", ".", "get_cloud_config_value", "(", "'certificate_path'", ",", "get_configured_provider", "(", ")", ",", "__opts__", ",", "search_global", "=", "False", ")", "subscription_id", "=", "salt", ".", ...
Return a conn object for the passed VM data
[ "Return", "a", "conn", "object", "for", "the", "passed", "VM", "data" ]
python
train
coursera/courseraoauth2client
courseraoauth2client/oauth2.py
https://github.com/coursera/courseraoauth2client/blob/4edd991defe26bfc768ab28a30368cace40baf44/courseraoauth2client/oauth2.py#L105-L151
def _make_handler(state_token, done_function): ''' Makes a a handler class to use inside the basic python HTTP server. state_token is the expected state token. done_function is a function that is called, with the code passed to it. ''' class LocalServerHandler(BaseHTTPServer.BaseHTTPRequestHandler): def error_response(self, msg): logging.warn( 'Error response: %(msg)s. %(path)s', msg=msg, path=self.path) self.send_response(400) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(msg) def do_GET(self): parsed = urlparse.urlparse(self.path) if len(parsed.query) == 0 or parsed.path != '/callback': self.error_response( 'We encountered a problem with your request.') return params = urlparse.parse_qs(parsed.query) if params['state'] != [state_token]: self.error_response( 'Attack detected: state tokens did not match!') return if len(params['code']) != 1: self.error_response('Wrong number of "code" query parameters.') return self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write( "courseraoauth2client: we have captured Coursera's response " "code. Feel free to close this browser window now and return " "to your terminal. Thanks!") done_function(params['code'][0]) return LocalServerHandler
[ "def", "_make_handler", "(", "state_token", ",", "done_function", ")", ":", "class", "LocalServerHandler", "(", "BaseHTTPServer", ".", "BaseHTTPRequestHandler", ")", ":", "def", "error_response", "(", "self", ",", "msg", ")", ":", "logging", ".", "warn", "(", ...
Makes a a handler class to use inside the basic python HTTP server. state_token is the expected state token. done_function is a function that is called, with the code passed to it.
[ "Makes", "a", "a", "handler", "class", "to", "use", "inside", "the", "basic", "python", "HTTP", "server", "." ]
python
train
romanz/trezor-agent
libagent/device/interface.py
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L26-L31
def string_to_identity(identity_str): """Parse string into Identity dictionary.""" m = _identity_regexp.match(identity_str) result = m.groupdict() log.debug('parsed identity: %s', result) return {k: v for k, v in result.items() if v}
[ "def", "string_to_identity", "(", "identity_str", ")", ":", "m", "=", "_identity_regexp", ".", "match", "(", "identity_str", ")", "result", "=", "m", ".", "groupdict", "(", ")", "log", ".", "debug", "(", "'parsed identity: %s'", ",", "result", ")", "return",...
Parse string into Identity dictionary.
[ "Parse", "string", "into", "Identity", "dictionary", "." ]
python
train
openstax/cnx-archive
cnxarchive/views/in_book_search.py
https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/views/in_book_search.py#L89-L149
def in_book_search_highlighted_results(request): """In-book search - returns a highlighted version of the HTML.""" results = {} args = request.matchdict ident_hash = args['ident_hash'] page_ident_hash = args['page_ident_hash'] try: page_uuid, _ = split_ident_hash(page_ident_hash) except IdentHashShortId as e: page_uuid = get_uuid(e.id) except IdentHashMissingVersion as e: page_uuid = e.id args['page_uuid'] = page_uuid args['search_term'] = request.params.get('q', '') query_type = request.params.get('query_type', '') combiner = '' if query_type: if query_type.lower() == 'or': combiner = '_or' # Get version from URL params id, version = split_ident_hash(ident_hash) args['uuid'] = id args['version'] = version with db_connect() as db_connection: with db_connection.cursor() as cursor: cursor.execute(SQL['get-collated-state'], args) res = cursor.fetchall() if res and res[0][0]: statement = SQL['get-in-collated-book-search-full-page'] else: statement = SQL['get-in-book-search-full-page'] cursor.execute(statement.format(combiner=combiner), args) res = cursor.fetchall() results['results'] = {'query': [], 'total': len(res), 'items': []} results['results']['query'] = { 'search_term': args['search_term'], 'collection_id': ident_hash, } for uuid, version, title, headline, rank in res: results['results']['items'].append({ 'rank': '{}'.format(rank), 'id': '{}'.format(page_ident_hash), 'title': '{}'.format(title), 'html': '{}'.format(headline), }) resp = request.response resp.status = '200 OK' resp.content_type = 'application/json' resp.body = json.dumps(results) return resp
[ "def", "in_book_search_highlighted_results", "(", "request", ")", ":", "results", "=", "{", "}", "args", "=", "request", ".", "matchdict", "ident_hash", "=", "args", "[", "'ident_hash'", "]", "page_ident_hash", "=", "args", "[", "'page_ident_hash'", "]", "try", ...
In-book search - returns a highlighted version of the HTML.
[ "In", "-", "book", "search", "-", "returns", "a", "highlighted", "version", "of", "the", "HTML", "." ]
python
train
klen/makesite
makesite/modules/django/main/utils/models.py
https://github.com/klen/makesite/blob/f6f77a43a04a256189e8fffbeac1ffd63f35a10c/makesite/modules/django/main/utils/models.py#L40-L67
def update(instance, full_clean=True, post_save=False, **kwargs): "Atomically update instance, setting field/value pairs from kwargs" # apply the updated args to the instance to mimic the change # note that these might slightly differ from the true database values # as the DB could have been updated by another thread. callers should # retrieve a new copy of the object if up-to-date values are required for k, v in kwargs.iteritems(): if isinstance(v, ExpressionNode): v = resolve_expression_node(instance, v) setattr(instance, k, v) # clean instance before update if full_clean: instance.full_clean() # fields that use auto_now=True should be updated corrected, too! for field in instance._meta.fields: if hasattr(field, 'auto_now') and field.auto_now and field.name not in kwargs: kwargs[field.name] = field.pre_save(instance, False) rows_affected = instance.__class__._default_manager.filter( pk=instance.pk).update(**kwargs) if post_save: signals.post_save.send(sender=instance.__class__, instance=instance) return rows_affected
[ "def", "update", "(", "instance", ",", "full_clean", "=", "True", ",", "post_save", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# apply the updated args to the instance to mimic the change", "# note that these might slightly differ from the true database values", "# as ...
Atomically update instance, setting field/value pairs from kwargs
[ "Atomically", "update", "instance", "setting", "field", "/", "value", "pairs", "from", "kwargs" ]
python
train
cogniteev/docido-python-sdk
docido_sdk/toolbox/date_ext.py
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/date_ext.py#L117-L156
def from_str(cls, timestr, shaked=False): """Use `dateutil` module to parse the give string :param basestring timestr: string representing a date to parse :param bool shaked: whether the input parameter been already cleaned or not. """ orig = timestr if not shaked: timestr = cls.fix_timezone_separator(timestr) try: date = parser.parse(timestr) except ValueError: if not shaked: shaked = False for shaker in [ cls.fix_mispelled_day, cls.remove_parenthesis_around_tz, cls.remove_quotes_around_tz]: new_timestr = shaker(timestr) if new_timestr is not None: timestr = new_timestr shaked = True if shaked: try: return cls.from_str(timestr, shaked=True) except ValueError: # raise ValueError below with proper message pass msg = u"Unknown string format: {!r}".format(orig) raise ValueError(msg), None, sys.exc_info()[2] else: try: return cls.from_datetime(date) except ValueError: new_str = cls.remove_timezone(orig) if new_str is not None: return cls.from_str(new_str) else: raise
[ "def", "from_str", "(", "cls", ",", "timestr", ",", "shaked", "=", "False", ")", ":", "orig", "=", "timestr", "if", "not", "shaked", ":", "timestr", "=", "cls", ".", "fix_timezone_separator", "(", "timestr", ")", "try", ":", "date", "=", "parser", ".",...
Use `dateutil` module to parse the give string :param basestring timestr: string representing a date to parse :param bool shaked: whether the input parameter been already cleaned or not.
[ "Use", "dateutil", "module", "to", "parse", "the", "give", "string" ]
python
train
wrobstory/vincent
vincent/data.py
https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L433-L460
def _numpy_to_values(data): '''Convert a NumPy array to values attribute''' def to_list_no_index(xvals, yvals): return [{"x": x, "y": np.asscalar(y)} for x, y in zip(xvals, yvals)] if len(data.shape) == 1 or data.shape[1] == 1: xvals = range(data.shape[0] + 1) values = to_list_no_index(xvals, data) elif len(data.shape) == 2: if data.shape[1] == 2: # NumPy arrays and matrices have different iteration rules. if isinstance(data, np.matrix): xidx = (0, 0) yidx = (0, 1) else: xidx = 0 yidx = 1 xvals = [np.asscalar(row[xidx]) for row in data] yvals = [np.asscalar(row[yidx]) for row in data] values = [{"x": x, "y": y} for x, y in zip(xvals, yvals)] else: raise ValueError('arrays with > 2 columns not supported') else: raise ValueError('invalid dimensions for ndarray') return values
[ "def", "_numpy_to_values", "(", "data", ")", ":", "def", "to_list_no_index", "(", "xvals", ",", "yvals", ")", ":", "return", "[", "{", "\"x\"", ":", "x", ",", "\"y\"", ":", "np", ".", "asscalar", "(", "y", ")", "}", "for", "x", ",", "y", "in", "z...
Convert a NumPy array to values attribute
[ "Convert", "a", "NumPy", "array", "to", "values", "attribute" ]
python
train
ElevenPaths/AtomShields
atomshields/checkers/dsstore.py
https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/checkers/dsstore.py#L22-L48
def run(self): """ Finds .DS_Store files into path """ filename = ".DS_Store" command = "find {path} -type f -name \"{filename}\" ".format(path = self.path, filename = filename) cmd = CommandHelper(command) cmd.execute() files = cmd.output.split("\n") for f in files: if not f.endswith(filename): continue # Ignore paths excluded rel_path = f.replace(self.path, "") if rel_path.startswith(tuple(self.CONFIG['exclude_paths'])): continue issue = Issue() issue.name = "File .DS_Store detected" issue.potential = False issue.severity = Issue.SEVERITY_LOW # Get only relative path issue.file = rel_path self.saveIssue(issue)
[ "def", "run", "(", "self", ")", ":", "filename", "=", "\".DS_Store\"", "command", "=", "\"find {path} -type f -name \\\"{filename}\\\" \"", ".", "format", "(", "path", "=", "self", ".", "path", ",", "filename", "=", "filename", ")", "cmd", "=", "CommandHelper", ...
Finds .DS_Store files into path
[ "Finds", ".", "DS_Store", "files", "into", "path" ]
python
valid
saltstack/salt
salt/states/grafana_dashboard.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana_dashboard.py#L452-L466
def _update(dashboard, profile): '''Update a specific dashboard.''' payload = { 'dashboard': dashboard, 'overwrite': True } request_url = "{0}/api/dashboards/db".format(profile.get('grafana_url')) response = requests.post( request_url, headers={ "Authorization": "Bearer {0}".format(profile.get('grafana_token')) }, json=payload ) return response.json()
[ "def", "_update", "(", "dashboard", ",", "profile", ")", ":", "payload", "=", "{", "'dashboard'", ":", "dashboard", ",", "'overwrite'", ":", "True", "}", "request_url", "=", "\"{0}/api/dashboards/db\"", ".", "format", "(", "profile", ".", "get", "(", "'grafa...
Update a specific dashboard.
[ "Update", "a", "specific", "dashboard", "." ]
python
train
fboender/ansible-cmdb
src/ansible-cmdb.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansible-cmdb.py#L96-L122
def get_cust_cols(path): """ Load custom column definitions. """ required_keys = ["title", "id", "sType", "visible"] with open(path, 'r') as f: try: cust_cols = ast.literal_eval(f.read()) except Exception as err: sys.stderr.write("Invalid custom columns file: {}\n".format(path)) sys.stderr.write("{}\n".format(err)) sys.exit(1) # Validate for col in cust_cols: for required_key in required_keys: if required_key not in col: sys.stderr.write("Missing required key '{}' in custom " "column {}\n".format(required_key, col)) sys.exit(1) if "jsonxs" not in col and "tpl" not in col: sys.stderr.write("You need to specify 'jsonxs' or 'tpl' " "for custom column {}\n".format(col)) sys.exit(1) return cust_cols
[ "def", "get_cust_cols", "(", "path", ")", ":", "required_keys", "=", "[", "\"title\"", ",", "\"id\"", ",", "\"sType\"", ",", "\"visible\"", "]", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "try", ":", "cust_cols", "=", "ast", ".", "...
Load custom column definitions.
[ "Load", "custom", "column", "definitions", "." ]
python
train
blockstack/blockstack-core
blockstack/lib/atlas.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1015-L1095
def atlasdb_add_peer( peer_hostport, discovery_time=None, peer_table=None, con=None, path=None, ping_on_evict=True ): """ Add a peer to the peer table. If the peer conflicts with another peer, ping it first, and only insert the new peer if the old peer is dead. Keep the in-RAM peer table cache-coherent as well. Return True if this peer was added to the table (or preserved) Return False if not """ # bound the number of peers we add to PEER_MAX_DB assert len(peer_hostport) > 0 sk = random.randint(0, 2**32) peer_host, peer_port = url_to_host_port( peer_hostport ) assert len(peer_host) > 0 peer_slot = int( hashlib.sha256("%s%s" % (sk, peer_host)).hexdigest(), 16 ) % PEER_MAX_DB with AtlasDBOpen(con=con, path=path) as dbcon: if discovery_time is None: discovery_time = int(time.time()) do_evict_and_ping = False with AtlasPeerTableLocked(peer_table) as ptbl: # if the peer is already present, then we're done if peer_hostport in ptbl.keys(): log.debug("%s already in the peer table" % peer_hostport) return True # not in the table yet. See if we can evict someone if ping_on_evict: do_evict_and_ping = True if do_evict_and_ping: # evict someone # don't hold the peer table lock across network I/O sql = "SELECT peer_hostport FROM peers WHERE peer_slot = ?;" args = (peer_slot,) cur = dbcon.cursor() res = atlasdb_query_execute( cur, sql, args ) old_hostports = [] for row in res: old_hostport = res['peer_hostport'] old_hostports.append( old_hostport ) for old_hostport in old_hostports: # is this other peer still alive? # is this other peer part of the same mainnet history? # res = atlas_peer_ping( old_hostport ) res = atlas_peer_getinfo(old_hostport) if res: log.debug("Peer %s is still alive; will not replace" % (old_hostport)) return False # insert new peer with AtlasPeerTableLocked(peer_table) as ptbl: log.debug("Add peer '%s' discovered at %s (slot %s)" % (peer_hostport, discovery_time, peer_slot)) # peer is dead (or we don't care). Can insert or update sql = "INSERT OR REPLACE INTO peers (peer_hostport, peer_slot, discovery_time) VALUES (?,?,?);" args = (peer_hostport, peer_slot, discovery_time) cur = dbcon.cursor() res = atlasdb_query_execute( cur, sql, args ) dbcon.commit() # add to peer table as well atlas_init_peer_info( ptbl, peer_hostport, blacklisted=False, whitelisted=False ) return True
[ "def", "atlasdb_add_peer", "(", "peer_hostport", ",", "discovery_time", "=", "None", ",", "peer_table", "=", "None", ",", "con", "=", "None", ",", "path", "=", "None", ",", "ping_on_evict", "=", "True", ")", ":", "# bound the number of peers we add to PEER_MAX_DB"...
Add a peer to the peer table. If the peer conflicts with another peer, ping it first, and only insert the new peer if the old peer is dead. Keep the in-RAM peer table cache-coherent as well. Return True if this peer was added to the table (or preserved) Return False if not
[ "Add", "a", "peer", "to", "the", "peer", "table", ".", "If", "the", "peer", "conflicts", "with", "another", "peer", "ping", "it", "first", "and", "only", "insert", "the", "new", "peer", "if", "the", "old", "peer", "is", "dead", "." ]
python
train
edx/i18n-tools
i18n/transifex.py
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L103-L111
def clean_translated_locales(configuration, langs=None): """ Strips out the warning from all translated po files about being an English source file. """ if not langs: langs = configuration.translated_locales for locale in langs: clean_locale(configuration, locale)
[ "def", "clean_translated_locales", "(", "configuration", ",", "langs", "=", "None", ")", ":", "if", "not", "langs", ":", "langs", "=", "configuration", ".", "translated_locales", "for", "locale", "in", "langs", ":", "clean_locale", "(", "configuration", ",", "...
Strips out the warning from all translated po files about being an English source file.
[ "Strips", "out", "the", "warning", "from", "all", "translated", "po", "files", "about", "being", "an", "English", "source", "file", "." ]
python
train
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/directory.py
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L3713-L3747
def del_ostype(self, ostype, sync=True): """ delete OS type from this company :param ostype: the OS type to be deleted from this company :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the OS type object on list to be removed on next save(). :return: """ LOGGER.debug("Company.del_ostype") if not sync: self.ost_2_rm.append(ostype) else: if ostype.id is None: ostype.sync() if self.id is not None and ostype.id is not None: params = { 'id': self.id, 'ostypeID': ostype.id } args = {'http_operation': 'GET', 'operation_path': 'update/ostypes/delete', 'parameters': params} response = CompanyService.requester.call(args) if response.rc != 0: LOGGER.warning( 'Company.del_ostype - Problem while updating company ' + self.name + '. Reason: ' + str(response.response_content) + '-' + str(response.error_message) + " (" + str(response.rc) + ")" ) else: self.ost_ids.remove(ostype.id) ostype.sync() else: LOGGER.warning( 'Company.del_ostype - Problem while updating company ' + self.name + '. Reason: ostype ' + ostype.name + ' id is None or self.id is None' )
[ "def", "del_ostype", "(", "self", ",", "ostype", ",", "sync", "=", "True", ")", ":", "LOGGER", ".", "debug", "(", "\"Company.del_ostype\"", ")", "if", "not", "sync", ":", "self", ".", "ost_2_rm", ".", "append", "(", "ostype", ")", "else", ":", "if", ...
delete OS type from this company :param ostype: the OS type to be deleted from this company :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, add the OS type object on list to be removed on next save(). :return:
[ "delete", "OS", "type", "from", "this", "company", ":", "param", "ostype", ":", "the", "OS", "type", "to", "be", "deleted", "from", "this", "company", ":", "param", "sync", ":", "If", "sync", "=", "True", "(", "default", ")", "synchronize", "with", "Ar...
python
train
ornlneutronimaging/ImagingReso
ImagingReso/_utilities.py
https://github.com/ornlneutronimaging/ImagingReso/blob/2da5cd1f565b3128f59d86bcedfd9adc2b02218b/ImagingReso/_utilities.py#L623-L668
def set_distance_units(value=np.NaN, from_units='mm', to_units='cm'): """convert distance into new units Parameters: =========== value: float. value to convert from_units: string. Must be 'mm', 'cm' or 'm' to_units: string. must be 'mm','cm' or 'm' Returns: ======== converted value Raises: ======= ValueError if from_units is not a valid unit (see above) ValueError if to_units is not a valid unit """ if from_units == to_units: return value if from_units == 'cm': if to_units == 'mm': coeff = 10 elif to_units == 'm': coeff = 0.01 else: raise ValueError("to_units not supported ['cm','m','mm']!") elif from_units == 'mm': if to_units == 'cm': coeff = 0.1 elif to_units == 'm': coeff = 0.001 else: raise ValueError("to_units not supported ['cm','m','mm']!") elif from_units == 'm': if to_units == 'mm': coeff = 1000 elif to_units == 'cm': coeff = 100 else: raise ValueError("to_units not supported ['cm','m','mm']!") else: raise ValueError("to_units not supported ['cm','m','mm']!") return coeff * value
[ "def", "set_distance_units", "(", "value", "=", "np", ".", "NaN", ",", "from_units", "=", "'mm'", ",", "to_units", "=", "'cm'", ")", ":", "if", "from_units", "==", "to_units", ":", "return", "value", "if", "from_units", "==", "'cm'", ":", "if", "to_units...
convert distance into new units Parameters: =========== value: float. value to convert from_units: string. Must be 'mm', 'cm' or 'm' to_units: string. must be 'mm','cm' or 'm' Returns: ======== converted value Raises: ======= ValueError if from_units is not a valid unit (see above) ValueError if to_units is not a valid unit
[ "convert", "distance", "into", "new", "units", "Parameters", ":", "===========", "value", ":", "float", ".", "value", "to", "convert", "from_units", ":", "string", ".", "Must", "be", "mm", "cm", "or", "m", "to_units", ":", "string", ".", "must", "be", "m...
python
train
saltstack/salt
salt/modules/zonecfg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zonecfg.py#L393-L443
def _property(methode, zone, key, value): ''' internal handler for set and clear_property methode : string either set, add, or clear zone : string name of zone key : string name of property value : string value of property ''' ret = {'status': True} # generate update script cfg_file = None if methode not in ['set', 'clear']: ret['status'] = False ret['message'] = 'unkown methode {0}!'.format(methode) else: cfg_file = salt.utils.files.mkstemp() with salt.utils.files.fpopen(cfg_file, 'w+', mode=0o600) as fp_: if methode == 'set': if isinstance(value, dict) or isinstance(value, list): value = _sanitize_value(value) value = six.text_type(value).lower() if isinstance(value, bool) else six.text_type(value) fp_.write("{0} {1}={2}\n".format(methode, key, _sanitize_value(value))) elif methode == 'clear': fp_.write("{0} {1}\n".format(methode, key)) # update property if cfg_file: _dump_cfg(cfg_file) res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format( zone=zone, path=cfg_file, )) ret['status'] = res['retcode'] == 0 ret['message'] = res['stdout'] if ret['status'] else res['stderr'] if ret['message'] == '': del ret['message'] else: ret['message'] = _clean_message(ret['message']) # cleanup config file if __salt__['file.file_exists'](cfg_file): __salt__['file.remove'](cfg_file) return ret
[ "def", "_property", "(", "methode", ",", "zone", ",", "key", ",", "value", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# generate update script", "cfg_file", "=", "None", "if", "methode", "not", "in", "[", "'set'", ",", "'clear'", "]", ":...
internal handler for set and clear_property methode : string either set, add, or clear zone : string name of zone key : string name of property value : string value of property
[ "internal", "handler", "for", "set", "and", "clear_property" ]
python
train
dhermes/bezier
docs/make_images.py
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L194-L206
def helper_parallel_lines(start0, end0, start1, end1, filename): """Image for :func:`.parallel_lines_parameters` docstring.""" if NO_IMAGES: return figure = plt.figure() ax = figure.gca() points = stack1d(start0, end0, start1, end1) ax.plot(points[0, :2], points[1, :2], marker="o") ax.plot(points[0, 2:], points[1, 2:], marker="o") ax.axis("scaled") _plot_helpers.add_plot_boundary(ax) save_image(figure, filename)
[ "def", "helper_parallel_lines", "(", "start0", ",", "end0", ",", "start1", ",", "end1", ",", "filename", ")", ":", "if", "NO_IMAGES", ":", "return", "figure", "=", "plt", ".", "figure", "(", ")", "ax", "=", "figure", ".", "gca", "(", ")", "points", "...
Image for :func:`.parallel_lines_parameters` docstring.
[ "Image", "for", ":", "func", ":", ".", "parallel_lines_parameters", "docstring", "." ]
python
train
inspirehep/refextract
refextract/references/engine.py
https://github.com/inspirehep/refextract/blob/d70e3787be3c495a3a07d1517b53f81d51c788c7/refextract/references/engine.py#L134-L144
def format_volume(citation_elements): """format volume number (roman numbers to arabic) When the volume number is expressed in roman numbers (CXXII), they are converted to their equivalent in arabic numbers (42) """ re_roman = re.compile(re_roman_numbers + u'$', re.UNICODE) for el in citation_elements: if el['type'] == 'JOURNAL' and re_roman.match(el['volume']): el['volume'] = str(roman2arabic(el['volume'].upper())) return citation_elements
[ "def", "format_volume", "(", "citation_elements", ")", ":", "re_roman", "=", "re", ".", "compile", "(", "re_roman_numbers", "+", "u'$'", ",", "re", ".", "UNICODE", ")", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'type'", "]", "==", "'...
format volume number (roman numbers to arabic) When the volume number is expressed in roman numbers (CXXII), they are converted to their equivalent in arabic numbers (42)
[ "format", "volume", "number", "(", "roman", "numbers", "to", "arabic", ")" ]
python
train
DarkEnergySurvey/ugali
ugali/utils/plotting.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L74-L101
def twoDimensionalHistogram(title, title_x, title_y, z, bins_x, bins_y, lim_x=None, lim_y=None, vmin=None, vmax=None): """ Create a two-dimension histogram plot or binned map. If using the outputs of np.histogram2d, remember to transpose the histogram. INPUTS """ plt.figure() mesh_x, mesh_y = np.meshgrid(bins_x, bins_y) if vmin != None and vmin == vmax: plt.pcolor(mesh_x, mesh_y, z) else: plt.pcolor(mesh_x, mesh_y, z, vmin=vmin, vmax=vmax) plt.xlabel(title_x) plt.ylabel(title_y) plt.title(title) plt.colorbar() if lim_x: plt.xlim(lim_x[0], lim_x[1]) if lim_y: plt.ylim(lim_y[0], lim_y[1])
[ "def", "twoDimensionalHistogram", "(", "title", ",", "title_x", ",", "title_y", ",", "z", ",", "bins_x", ",", "bins_y", ",", "lim_x", "=", "None", ",", "lim_y", "=", "None", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "plt", ".", ...
Create a two-dimension histogram plot or binned map. If using the outputs of np.histogram2d, remember to transpose the histogram. INPUTS
[ "Create", "a", "two", "-", "dimension", "histogram", "plot", "or", "binned", "map", "." ]
python
train
thiagopbueno/pyrddl
pyrddl/parser.py
https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/parser.py#L419-L426
def p_action_precond_section(self, p): '''action_precond_section : ACTION_PRECONDITIONS LCURLY action_precond_list RCURLY SEMI | ACTION_PRECONDITIONS LCURLY RCURLY SEMI''' if len(p) == 6: p[0] = ('preconds', p[3]) elif len(p) == 5: p[0] = ('preconds', []) self._print_verbose('action-preconditions')
[ "def", "p_action_precond_section", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "6", ":", "p", "[", "0", "]", "=", "(", "'preconds'", ",", "p", "[", "3", "]", ")", "elif", "len", "(", "p", ")", "==", "5", ":", "p", "["...
action_precond_section : ACTION_PRECONDITIONS LCURLY action_precond_list RCURLY SEMI | ACTION_PRECONDITIONS LCURLY RCURLY SEMI
[ "action_precond_section", ":", "ACTION_PRECONDITIONS", "LCURLY", "action_precond_list", "RCURLY", "SEMI", "|", "ACTION_PRECONDITIONS", "LCURLY", "RCURLY", "SEMI" ]
python
train
titusjan/argos
argos/application.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/application.py#L191-L197
def deleteProfile(self, profile): """ Removes a profile from the persistent settings """ profGroupName = self.profileGroupName(profile) logger.debug("Resetting profile settings: {}".format(profGroupName)) settings = QtCore.QSettings() settings.remove(profGroupName)
[ "def", "deleteProfile", "(", "self", ",", "profile", ")", ":", "profGroupName", "=", "self", ".", "profileGroupName", "(", "profile", ")", "logger", ".", "debug", "(", "\"Resetting profile settings: {}\"", ".", "format", "(", "profGroupName", ")", ")", "settings...
Removes a profile from the persistent settings
[ "Removes", "a", "profile", "from", "the", "persistent", "settings" ]
python
train
gem/oq-engine
openquake/commonlib/oqzip.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqzip.py#L67-L77
def zip_exposure(exposure_xml, archive_zip='', log=logging.info): """ Zip an exposure.xml file with all its .csv subfiles (if any) """ archive_zip = archive_zip or exposure_xml[:-4] + '.zip' if os.path.exists(archive_zip): sys.exit('%s exists already' % archive_zip) [exp] = Exposure.read_headers([exposure_xml]) files = [exposure_xml] + exp.datafiles general.zipfiles(files, archive_zip, log=log, cleanup=True) return archive_zip
[ "def", "zip_exposure", "(", "exposure_xml", ",", "archive_zip", "=", "''", ",", "log", "=", "logging", ".", "info", ")", ":", "archive_zip", "=", "archive_zip", "or", "exposure_xml", "[", ":", "-", "4", "]", "+", "'.zip'", "if", "os", ".", "path", ".",...
Zip an exposure.xml file with all its .csv subfiles (if any)
[ "Zip", "an", "exposure", ".", "xml", "file", "with", "all", "its", ".", "csv", "subfiles", "(", "if", "any", ")" ]
python
train
Opentrons/opentrons
api/src/opentrons/simulate.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/simulate.py#L93-L164
def simulate(protocol_file, propagate_logs=False, log_level='warning') -> List[Mapping[str, Any]]: """ Simulate the protocol itself. This is a one-stop function to simulate a protocol, whether python or json, no matter the api version, from external (i.e. not bound up in other internal server infrastructure) sources. To simulate an opentrons protocol from other places, pass in a file like object as protocol_file; this function either returns (if the simulation has no problems) or raises an exception. To call from the command line use either the autogenerated entrypoint ``opentrons_simulate`` (``opentrons_simulate.exe``, on windows) or ``python -m opentrons.simulate``. The return value is the run log, a list of dicts that represent the commands executed by the robot. Each dict has the following keys: - ``level``: The depth at which this command is nested - if this an aspirate inside a mix inside a transfer, for instance, it would be 3. - ``payload``: The command, its arguments, and how to format its text. For more specific details see :py:mod:`opentrons.commands`. To format a message from a payload do ``payload['text'].format(**payload)``. - ``logs``: Any log messages that occurred during execution of this command, as a logging.LogRecord :param file-like protocol_file: The protocol file to simulate. :param propagate_logs: Whether this function should allow logs from the Opentrons stack to propagate up to the root handler. This can be useful if you're integrating this function in a larger application, but most logs that occur during protocol simulation are best associated with the actions in the protocol that cause them. :type propagate_logs: bool :param log_level: The level of logs to capture in the runlog :type log_level: 'debug', 'info', 'warning', or 'error' :returns List[Dict[str, Dict[str, Any]]]: A run log for user output. """ stack_logger = logging.getLogger('opentrons') stack_logger.propagate = propagate_logs contents = protocol_file.read() if opentrons.config.feature_flags.use_protocol_api_v2(): try: execute_args = {'protocol_json': json.loads(contents)} except json.JSONDecodeError: execute_args = {'protocol_code': contents} context = opentrons.protocol_api.contexts.ProtocolContext() context.home() scraper = CommandScraper(stack_logger, log_level, context.broker) execute_args.update({'simulate': True, 'context': context}) opentrons.protocol_api.execute.run_protocol(**execute_args) else: try: proto = json.loads(contents) except json.JSONDecodeError: proto = contents opentrons.robot.disconnect() scraper = CommandScraper(stack_logger, log_level, opentrons.robot.broker) if isinstance(proto, dict): opentrons.protocols.execute_protocol(proto) else: exec(proto, {}) return scraper.commands
[ "def", "simulate", "(", "protocol_file", ",", "propagate_logs", "=", "False", ",", "log_level", "=", "'warning'", ")", "->", "List", "[", "Mapping", "[", "str", ",", "Any", "]", "]", ":", "stack_logger", "=", "logging", ".", "getLogger", "(", "'opentrons'"...
Simulate the protocol itself. This is a one-stop function to simulate a protocol, whether python or json, no matter the api version, from external (i.e. not bound up in other internal server infrastructure) sources. To simulate an opentrons protocol from other places, pass in a file like object as protocol_file; this function either returns (if the simulation has no problems) or raises an exception. To call from the command line use either the autogenerated entrypoint ``opentrons_simulate`` (``opentrons_simulate.exe``, on windows) or ``python -m opentrons.simulate``. The return value is the run log, a list of dicts that represent the commands executed by the robot. Each dict has the following keys: - ``level``: The depth at which this command is nested - if this an aspirate inside a mix inside a transfer, for instance, it would be 3. - ``payload``: The command, its arguments, and how to format its text. For more specific details see :py:mod:`opentrons.commands`. To format a message from a payload do ``payload['text'].format(**payload)``. - ``logs``: Any log messages that occurred during execution of this command, as a logging.LogRecord :param file-like protocol_file: The protocol file to simulate. :param propagate_logs: Whether this function should allow logs from the Opentrons stack to propagate up to the root handler. This can be useful if you're integrating this function in a larger application, but most logs that occur during protocol simulation are best associated with the actions in the protocol that cause them. :type propagate_logs: bool :param log_level: The level of logs to capture in the runlog :type log_level: 'debug', 'info', 'warning', or 'error' :returns List[Dict[str, Dict[str, Any]]]: A run log for user output.
[ "Simulate", "the", "protocol", "itself", "." ]
python
train
PonteIneptique/collatinus-python
pycollatinus/modele.py
https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/modele.py#L180-L190
def desinences(self, d=None): """ Renvoie la liste des désinence de morpho d du modèle. :param d: Identifant de morphologie :type d: int :return: Liste des désinence de morpho d du modèle ou toutes les désinences du modèle (Applaties en python, doute sur original) :rtype: list of Desinence """ if d: return self._desinences[d] return [x for morpho_values in self._desinences.values() for x in morpho_values]
[ "def", "desinences", "(", "self", ",", "d", "=", "None", ")", ":", "if", "d", ":", "return", "self", ".", "_desinences", "[", "d", "]", "return", "[", "x", "for", "morpho_values", "in", "self", ".", "_desinences", ".", "values", "(", ")", "for", "x...
Renvoie la liste des désinence de morpho d du modèle. :param d: Identifant de morphologie :type d: int :return: Liste des désinence de morpho d du modèle ou toutes les désinences du modèle (Applaties en python, doute sur original) :rtype: list of Desinence
[ "Renvoie", "la", "liste", "des", "désinence", "de", "morpho", "d", "du", "modèle", "." ]
python
train
softlayer/softlayer-python
SoftLayer/managers/file.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/file.py#L287-L314
def order_modified_volume(self, volume_id, new_size=None, new_iops=None, new_tier_level=None): """Places an order for modifying an existing file volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new IOPS for the volume :param new_tier_level: The new tier level for the volume :return: Returns a SoftLayer_Container_Product_Order_Receipt """ mask_items = [ 'id', 'billingItem', 'storageType[keyName]', 'capacityGb', 'provisionedIops', 'storageTierLevel', 'staasVersion', 'hasEncryptionAtRest', ] file_mask = ','.join(mask_items) volume = self.get_file_volume_details(volume_id, mask=file_mask) order = storage_utils.prepare_modify_order_object( self, volume, new_iops, new_tier_level, new_size ) return self.client.call('Product_Order', 'placeOrder', order)
[ "def", "order_modified_volume", "(", "self", ",", "volume_id", ",", "new_size", "=", "None", ",", "new_iops", "=", "None", ",", "new_tier_level", "=", "None", ")", ":", "mask_items", "=", "[", "'id'", ",", "'billingItem'", ",", "'storageType[keyName]'", ",", ...
Places an order for modifying an existing file volume. :param volume_id: The ID of the volume to be modified :param new_size: The new size/capacity for the volume :param new_iops: The new IOPS for the volume :param new_tier_level: The new tier level for the volume :return: Returns a SoftLayer_Container_Product_Order_Receipt
[ "Places", "an", "order", "for", "modifying", "an", "existing", "file", "volume", "." ]
python
train
coleifer/walrus
walrus/containers.py
https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L491-L503
def unionstore(self, dest, *others): """ Store the union of the current set and one or more others in a new key. :param dest: the name of the key to store union :param others: One or more :py:class:`Set` instances :returns: A :py:class:`Set` referencing ``dest``. """ keys = [self.key] keys.extend([other.key for other in others]) self.database.sunionstore(dest, keys) return self.database.Set(dest)
[ "def", "unionstore", "(", "self", ",", "dest", ",", "*", "others", ")", ":", "keys", "=", "[", "self", ".", "key", "]", "keys", ".", "extend", "(", "[", "other", ".", "key", "for", "other", "in", "others", "]", ")", "self", ".", "database", ".", ...
Store the union of the current set and one or more others in a new key. :param dest: the name of the key to store union :param others: One or more :py:class:`Set` instances :returns: A :py:class:`Set` referencing ``dest``.
[ "Store", "the", "union", "of", "the", "current", "set", "and", "one", "or", "more", "others", "in", "a", "new", "key", "." ]
python
train
jcrist/skein
skein/utils.py
https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/utils.py#L177-L201
def format_table(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i in r) for r in rows] columns = tuple(str(i).upper() for i in columns) if rows: widths = tuple(max(max(map(len, x)), len(c)) for x, c in zip(zip(*rows), columns)) else: widths = tuple(map(len, columns)) row_template = (' '.join('%%-%ds' for _ in columns)) % widths header = (row_template % tuple(columns)).strip() if rows: data = '\n'.join((row_template % r).strip() for r in rows) return '\n'.join([header, data]) else: return header
[ "def", "format_table", "(", "columns", ",", "rows", ")", ":", "rows", "=", "[", "tuple", "(", "str", "(", "i", ")", "for", "i", "in", "r", ")", "for", "r", "in", "rows", "]", "columns", "=", "tuple", "(", "str", "(", "i", ")", ".", "upper", "...
Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``.
[ "Formats", "an", "ascii", "table", "for", "given", "columns", "and", "rows", "." ]
python
train
SUSE-Enceladus/ipa
ipa/ipa_cloud.py
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L212-L240
def _log_info(self): """Output test run information to top of log file.""" if self.cloud == 'ssh': self.results['info'] = { 'platform': self.cloud, 'distro': self.distro_name, 'image': self.instance_ip, 'timestamp': self.time_stamp, 'log_file': self.log_file, 'results_file': self.results_file } else: self.results['info'] = { 'platform': self.cloud, 'region': self.region, 'distro': self.distro_name, 'image': self.image_id, 'instance': self.running_instance_id, 'timestamp': self.time_stamp, 'log_file': self.log_file, 'results_file': self.results_file } self._write_to_log( '\n'.join( '%s: %s' % (key, val) for key, val in self.results['info'].items() ) )
[ "def", "_log_info", "(", "self", ")", ":", "if", "self", ".", "cloud", "==", "'ssh'", ":", "self", ".", "results", "[", "'info'", "]", "=", "{", "'platform'", ":", "self", ".", "cloud", ",", "'distro'", ":", "self", ".", "distro_name", ",", "'image'"...
Output test run information to top of log file.
[ "Output", "test", "run", "information", "to", "top", "of", "log", "file", "." ]
python
train
gabrielelanaro/chemview
chemview/utils.py
https://github.com/gabrielelanaro/chemview/blob/2c9768dd23db99e59e27adff2a953bb8ee795fa3/chemview/utils.py#L7-L18
def encode_numpy(array): '''Encode a numpy array as a base64 encoded string, to be JSON serialized. :return: a dictionary containing the fields: - *data*: the base64 string - *type*: the array type - *shape*: the array shape ''' return {'data' : base64.b64encode(array.data).decode('utf8'), 'type' : array.dtype.name, 'shape': array.shape}
[ "def", "encode_numpy", "(", "array", ")", ":", "return", "{", "'data'", ":", "base64", ".", "b64encode", "(", "array", ".", "data", ")", ".", "decode", "(", "'utf8'", ")", ",", "'type'", ":", "array", ".", "dtype", ".", "name", ",", "'shape'", ":", ...
Encode a numpy array as a base64 encoded string, to be JSON serialized. :return: a dictionary containing the fields: - *data*: the base64 string - *type*: the array type - *shape*: the array shape
[ "Encode", "a", "numpy", "array", "as", "a", "base64", "encoded", "string", "to", "be", "JSON", "serialized", "." ]
python
train
pytroll/satpy
satpy/readers/viirs_compact.py
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/viirs_compact.py#L159-L199
def read_geo(self, key, info): """Read angles. """ pairs = {('satellite_azimuth_angle', 'satellite_zenith_angle'): ("SatelliteAzimuthAngle", "SatelliteZenithAngle"), ('solar_azimuth_angle', 'solar_zenith_angle'): ("SolarAzimuthAngle", "SolarZenithAngle"), ('dnb_solar_azimuth_angle', 'dnb_solar_zenith_angle'): ("SolarAzimuthAngle", "SolarZenithAngle"), ('dnb_lunar_azimuth_angle', 'dnb_lunar_zenith_angle'): ("LunarAzimuthAngle", "LunarZenithAngle"), } for pair, fkeys in pairs.items(): if key.name in pair: if (self.cache.get(pair[0]) is None or self.cache.get(pair[1]) is None): angles = self.angles(*fkeys) self.cache[pair[0]], self.cache[pair[1]] = angles if key.name == pair[0]: return xr.DataArray(self.cache[pair[0]], name=key.name, attrs=self.mda, dims=('y', 'x')) else: return xr.DataArray(self.cache[pair[1]], name=key.name, attrs=self.mda, dims=('y', 'x')) if info.get('standard_name') in ['latitude', 'longitude']: if self.lons is None or self.lats is None: self.lons, self.lats = self.navigate() mda = self.mda.copy() mda.update(info) if info['standard_name'] == 'longitude': return xr.DataArray(self.lons, attrs=mda, dims=('y', 'x')) else: return xr.DataArray(self.lats, attrs=mda, dims=('y', 'x')) if key.name == 'dnb_moon_illumination_fraction': mda = self.mda.copy() mda.update(info) return xr.DataArray(self.geostuff["MoonIllumFraction"].value, attrs=info)
[ "def", "read_geo", "(", "self", ",", "key", ",", "info", ")", ":", "pairs", "=", "{", "(", "'satellite_azimuth_angle'", ",", "'satellite_zenith_angle'", ")", ":", "(", "\"SatelliteAzimuthAngle\"", ",", "\"SatelliteZenithAngle\"", ")", ",", "(", "'solar_azimuth_ang...
Read angles.
[ "Read", "angles", "." ]
python
train
theislab/scanpy
scanpy/preprocessing/_combat.py
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/preprocessing/_combat.py#L136-L266
def combat(adata: AnnData, key: str = 'batch', covariates: Optional[Collection[str]] = None, inplace: bool = True): """ComBat function for batch effect correction [Johnson07]_ [Leek12]_ [Pedersen12]_. Corrects for batch effects by fitting linear models, gains statistical power via an EB framework where information is borrowed across genes. This uses the implementation of `ComBat <https://github.com/brentp/combat.py>`__ [Pedersen12]_. Parameters ---------- adata : :class:`~anndata.AnnData` Annotated data matrix key: `str`, optional (default: `"batch"`) Key to a categorical annotation from adata.obs that will be used for batch effect removal covariates Additional covariates such as adjustment variables or biological condition. Note that not including covariates may introduce bias or lead to the removal of biological signal in unbalanced designs. inplace: bool, optional (default: `True`) Wether to replace adata.X or to return the corrected data Returns ------- Depending on the value of inplace, either returns an updated AnnData object or modifies the passed one. """ # check the input if key not in adata.obs_keys(): raise ValueError('Could not find the key {!r} in adata.obs'.format(key)) if covariates is not None: cov_exist = np.isin(covariates, adata.obs_keys()) if np.any(~cov_exist): missing_cov = np.array(covariates)[~cov_exist].tolist() raise ValueError('Could not find the covariate(s) {!r} in adata.obs'.format(missing_cov)) if key in covariates: raise ValueError('Batch key and covariates cannot overlap') if len(covariates) != len(set(covariates)): raise ValueError('Covariates must be unique') # only works on dense matrices so far if issparse(adata.X): X = adata.X.A.T else: X = adata.X.T data = pd.DataFrame( data=X, index=adata.var_names, columns=adata.obs_names, ) sanitize_anndata(adata) # construct a pandas series of the batch annotation model = adata.obs[[key] + (covariates if covariates else [])] batch_info = model.groupby(key).groups.values() n_batch = len(batch_info) n_batches = np.array([len(v) for v in batch_info]) n_array = float(sum(n_batches)) # standardize across genes using a pooled variance estimator logg.info("Standardizing Data across genes.\n") s_data, design, var_pooled, stand_mean = _standardize_data(model, data, key) # fitting the parameters on the standardized data logg.info("Fitting L/S model and finding priors\n") batch_design = design[design.columns[:n_batch]] # first estimate of the additive batch effect gamma_hat = np.dot(np.dot(la.inv(np.dot(batch_design.T, batch_design)), batch_design.T), s_data.T) delta_hat = [] # first estimate for the multiplicative batch effect for i, batch_idxs in enumerate(batch_info): delta_hat.append(s_data[batch_idxs].var(axis=1)) # empirically fix the prior hyperparameters gamma_bar = gamma_hat.mean(axis=1) t2 = gamma_hat.var(axis=1) # a_prior and b_prior are the priors on lambda and theta from Johnson and Li (2006) a_prior = list(map(_aprior, delta_hat)) b_prior = list(map(_bprior, delta_hat)) logg.info("Finding parametric adjustments\n") # gamma star and delta star will be our empirical bayes (EB) estimators # for the additive and multiplicative batch effect per batch and cell gamma_star, delta_star = [], [] for i, batch_idxs in enumerate(batch_info): # temp stores our estimates for the batch effect parameters. # temp[0] is the additive batch effect # temp[1] is the multiplicative batch effect gamma, delta = _it_sol( s_data[batch_idxs].values, gamma_hat[i], delta_hat[i].values, gamma_bar[i], t2[i], a_prior[i], b_prior[i], ) gamma_star.append(gamma) delta_star.append(delta) logg.info("Adjusting data\n") bayesdata = s_data gamma_star = np.array(gamma_star) delta_star = np.array(delta_star) # we now apply the parametric adjustment to the standardized data from above # loop over all batches in the data for j, batch_idxs in enumerate(batch_info): # we basically substract the additive batch effect, rescale by the ratio # of multiplicative batch effect to pooled variance and add the overall gene # wise mean dsq = np.sqrt(delta_star[j,:]) dsq = dsq.reshape((len(dsq), 1)) denom = np.dot(dsq, np.ones((1, n_batches[j]))) numer = np.array(bayesdata[batch_idxs] - np.dot(batch_design.loc[batch_idxs], gamma_star).T) bayesdata[batch_idxs] = numer / denom vpsq = np.sqrt(var_pooled).reshape((len(var_pooled), 1)) bayesdata = bayesdata * np.dot(vpsq, np.ones((1, int(n_array)))) + stand_mean # put back into the adata object or return if inplace: adata.X = bayesdata.values.transpose() else: return bayesdata.values.transpose()
[ "def", "combat", "(", "adata", ":", "AnnData", ",", "key", ":", "str", "=", "'batch'", ",", "covariates", ":", "Optional", "[", "Collection", "[", "str", "]", "]", "=", "None", ",", "inplace", ":", "bool", "=", "True", ")", ":", "# check the input", ...
ComBat function for batch effect correction [Johnson07]_ [Leek12]_ [Pedersen12]_. Corrects for batch effects by fitting linear models, gains statistical power via an EB framework where information is borrowed across genes. This uses the implementation of `ComBat <https://github.com/brentp/combat.py>`__ [Pedersen12]_. Parameters ---------- adata : :class:`~anndata.AnnData` Annotated data matrix key: `str`, optional (default: `"batch"`) Key to a categorical annotation from adata.obs that will be used for batch effect removal covariates Additional covariates such as adjustment variables or biological condition. Note that not including covariates may introduce bias or lead to the removal of biological signal in unbalanced designs. inplace: bool, optional (default: `True`) Wether to replace adata.X or to return the corrected data Returns ------- Depending on the value of inplace, either returns an updated AnnData object or modifies the passed one.
[ "ComBat", "function", "for", "batch", "effect", "correction", "[", "Johnson07", "]", "_", "[", "Leek12", "]", "_", "[", "Pedersen12", "]", "_", "." ]
python
train
tanghaibao/goatools
goatools/gosubdag/gosubdag_init.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/gosubdag_init.py#L94-L106
def _init_go_sources(self, go_sources_arg, go2obj_arg): """Return GO sources which are present in GODag.""" gos_user = set(go_sources_arg) if 'children' in self.kws and self.kws['children']: gos_user |= get_leaf_children(gos_user, go2obj_arg) gos_godag = set(go2obj_arg) gos_source = gos_user.intersection(gos_godag) gos_missing = gos_user.difference(gos_godag) if not gos_missing: return gos_source sys.stdout.write("{N} GO IDs NOT FOUND IN GO DAG: {GOs}\n".format( N=len(gos_missing), GOs=" ".join([str(e) for e in gos_missing]))) return gos_source
[ "def", "_init_go_sources", "(", "self", ",", "go_sources_arg", ",", "go2obj_arg", ")", ":", "gos_user", "=", "set", "(", "go_sources_arg", ")", "if", "'children'", "in", "self", ".", "kws", "and", "self", ".", "kws", "[", "'children'", "]", ":", "gos_user"...
Return GO sources which are present in GODag.
[ "Return", "GO", "sources", "which", "are", "present", "in", "GODag", "." ]
python
train
bokeh/bokeh
bokeh/protocol/message.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L204-L225
def write_buffers(self, conn, locked=True): ''' Write any buffer headers and payloads to the given connection. Args: conn (object) : May be any object with a ``write_message`` method. Typically, a Tornado ``WSHandler`` or ``WebSocketClientConnection`` locked (bool) : Returns: int : number of bytes sent ''' if conn is None: raise ValueError("Cannot write_buffers to connection None") sent = 0 for header, payload in self._buffers: yield conn.write_message(header, locked=locked) yield conn.write_message(payload, binary=True, locked=locked) sent += (len(header) + len(payload)) raise gen.Return(sent)
[ "def", "write_buffers", "(", "self", ",", "conn", ",", "locked", "=", "True", ")", ":", "if", "conn", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot write_buffers to connection None\"", ")", "sent", "=", "0", "for", "header", ",", "payload", "in", ...
Write any buffer headers and payloads to the given connection. Args: conn (object) : May be any object with a ``write_message`` method. Typically, a Tornado ``WSHandler`` or ``WebSocketClientConnection`` locked (bool) : Returns: int : number of bytes sent
[ "Write", "any", "buffer", "headers", "and", "payloads", "to", "the", "given", "connection", "." ]
python
train
Varkal/chuda
chuda/shell.py
https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/shell.py#L259-L271
def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """ Create an instance of :class:`~ShellCommand` and run it Args: command (str): :class:`~ShellCommand` block (bool): See :class:`~ShellCommand` cwd (str): Override the runner cwd. Useb by the :class:`~ShellCommand` instance """ if cwd is None: cwd = self.cwd return ShellCommand(command=command, logger=self.logger, block=block, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr).run()
[ "def", "run", "(", "self", ",", "command", ",", "block", "=", "True", ",", "cwd", "=", "None", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", ":", "if...
Create an instance of :class:`~ShellCommand` and run it Args: command (str): :class:`~ShellCommand` block (bool): See :class:`~ShellCommand` cwd (str): Override the runner cwd. Useb by the :class:`~ShellCommand` instance
[ "Create", "an", "instance", "of", ":", "class", ":", "~ShellCommand", "and", "run", "it" ]
python
train
HPAC/matchpy
matchpy/matching/bipartite.py
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/bipartite.py#L144-L174
def find_matching(self) -> Dict[TLeft, TRight]: """Finds a matching in the bipartite graph. This is done using the Hopcroft-Karp algorithm with an implementation from the `hopcroftkarp` package. Returns: A dictionary where each edge of the matching is represented by a key-value pair with the key being from the left part of the graph and the value from te right part. """ # The directed graph is represented as a dictionary of edges # The key is the tail of all edges which are represented by the value # The value is a set of heads for the all edges originating from the tail (key) # In addition, the graph stores which part of the bipartite graph a node originated from # to avoid problems when a value exists in both halfs. # Only one direction of the undirected edge is needed for the HopcroftKarp class directed_graph = {} # type: Dict[Tuple[int, TLeft], Set[Tuple[int, TRight]]] for (left, right) in self._edges: tail = (LEFT, left) head = (RIGHT, right) if tail not in directed_graph: directed_graph[tail] = {head} else: directed_graph[tail].add(head) matching = HopcroftKarp(directed_graph).maximum_matching() # Filter out the partitions (LEFT and RIGHT) and only return the matching edges # that go from LEFT to RIGHT return dict((tail[1], head[1]) for tail, head in matching.items() if tail[0] == LEFT)
[ "def", "find_matching", "(", "self", ")", "->", "Dict", "[", "TLeft", ",", "TRight", "]", ":", "# The directed graph is represented as a dictionary of edges", "# The key is the tail of all edges which are represented by the value", "# The value is a set of heads for the all edges origi...
Finds a matching in the bipartite graph. This is done using the Hopcroft-Karp algorithm with an implementation from the `hopcroftkarp` package. Returns: A dictionary where each edge of the matching is represented by a key-value pair with the key being from the left part of the graph and the value from te right part.
[ "Finds", "a", "matching", "in", "the", "bipartite", "graph", "." ]
python
train
google/grr
grr/server/grr_response_server/aff4_objects/user_managers.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/user_managers.py#L247-L291
def CheckAccess(self, subject, token): """Checks for access to given subject with a given token. CheckAccess runs given subject through all "allow" clauses that were previously registered with Allow() calls. It returns True on first match and raises access_control.UnauthorizedAccess if there are no matches or if any of the additional checks fails. Args: subject: RDFURN of the subject that will be checked for access. token: User credentials token. Returns: True if access is granted. Raises: access_control.UnauthorizedAccess if access is rejected. """ subject = rdfvalue.RDFURN(subject) subject_str = subject.SerializeToString() for check_tuple in self.checks: regex_text, regex, require, require_args, require_kwargs = check_tuple match = regex.match(subject_str) if not match: continue if require: # If require() fails, it raises access_control.UnauthorizedAccess. require(subject, token, *require_args, **require_kwargs) logging.debug( u"Datastore access granted to %s on %s by pattern: %s " u"with reason: %s (require=%s, require_args=%s, " u"require_kwargs=%s, helper_name=%s)", utils.SmartUnicode(token.username), utils.SmartUnicode(subject_str), utils.SmartUnicode(regex_text), utils.SmartUnicode(token.reason), require, require_args, require_kwargs, self.helper_name) return True logging.warning("Datastore access denied to %s (no matched rules)", subject_str) raise access_control.UnauthorizedAccess( "Access to %s rejected: (no matched rules)." % subject, subject=subject)
[ "def", "CheckAccess", "(", "self", ",", "subject", ",", "token", ")", ":", "subject", "=", "rdfvalue", ".", "RDFURN", "(", "subject", ")", "subject_str", "=", "subject", ".", "SerializeToString", "(", ")", "for", "check_tuple", "in", "self", ".", "checks",...
Checks for access to given subject with a given token. CheckAccess runs given subject through all "allow" clauses that were previously registered with Allow() calls. It returns True on first match and raises access_control.UnauthorizedAccess if there are no matches or if any of the additional checks fails. Args: subject: RDFURN of the subject that will be checked for access. token: User credentials token. Returns: True if access is granted. Raises: access_control.UnauthorizedAccess if access is rejected.
[ "Checks", "for", "access", "to", "given", "subject", "with", "a", "given", "token", "." ]
python
train
gccxml/pygccxml
pygccxml/declarations/type_traits_classes.py
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits_classes.py#L708-L785
def is_noncopyable(class_, already_visited_cls_vars=None): """ Checks if class is non copyable Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. In general you can ignore this argument, it is mainly used during recursive calls of is_noncopyable() done by pygccxml. Returns: bool: if the class is non copyable """ logger = utils.loggers.cxx_parser class_decl = class_traits.get_declaration(class_) true_header = "is_noncopyable(TRUE) - %s - " % class_.decl_string if is_union(class_): return False if class_decl.is_abstract: logger.debug(true_header + "abstract client") return True # if class has public, user defined copy constructor, than this class is # copyable copy_ = find_copy_constructor(class_decl) if copy_ and copy_.access_type == 'public' and not copy_.is_artificial: return False if already_visited_cls_vars is None: already_visited_cls_vars = [] for base_desc in class_decl.recursive_bases: assert isinstance(base_desc, class_declaration.hierarchy_info_t) if base_desc.related_class.decl_string in \ ('::boost::noncopyable', '::boost::noncopyable_::noncopyable'): logger.debug(true_header + "derives from boost::noncopyable") return True if not has_copy_constructor(base_desc.related_class): base_copy_ = find_copy_constructor(base_desc.related_class) if base_copy_ and base_copy_.access_type == 'private': logger.debug( true_header + "there is private copy constructor") return True elif __is_noncopyable_single( base_desc.related_class, already_visited_cls_vars): logger.debug( true_header + "__is_noncopyable_single returned True") return True if __is_noncopyable_single( base_desc.related_class, already_visited_cls_vars): logger.debug( true_header + "__is_noncopyable_single returned True") return True if not has_copy_constructor(class_decl): logger.debug(true_header + "does not have trivial copy constructor") return True elif not has_public_constructor(class_decl): logger.debug(true_header + "does not have a public constructor") return True elif has_destructor(class_decl) and not has_public_destructor(class_decl): logger.debug(true_header + "has private destructor") return True return __is_noncopyable_single(class_decl, already_visited_cls_vars)
[ "def", "is_noncopyable", "(", "class_", ",", "already_visited_cls_vars", "=", "None", ")", ":", "logger", "=", "utils", ".", "loggers", ".", "cxx_parser", "class_decl", "=", "class_traits", ".", "get_declaration", "(", "class_", ")", "true_header", "=", "\"is_no...
Checks if class is non copyable Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars that should not be checked a second time, to prevent infinite recursions. In general you can ignore this argument, it is mainly used during recursive calls of is_noncopyable() done by pygccxml. Returns: bool: if the class is non copyable
[ "Checks", "if", "class", "is", "non", "copyable" ]
python
train
Erotemic/utool
utool/experimental/euler_tour_tree_avl.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L921-L1016
def avl_split(root, node): """ O(log(n)) Args: root (Node): tree root node (Node): node to split at Returns: puple: (tl, tr, node) tl contains all keys in the tree less than node tr contains all keys in the tree greater than node node is the node we split out CommandLine: python -m utool.experimental.euler_tour_tree_avl avl_split Example: >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> self = EulerTourTree(ut.chr_range(10)) >>> self.print_tree() >>> node = self.get_node(5) >>> part1, part2, bnode = avl_split(self.root, node) >>> ascii_tree(part1) >>> ascii_tree(part2) >>> ascii_tree(bnode) Example: >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> test_avl_split(verbose=2) """ DEBUG_SPLIT = 0 # Get the backtrace to the root rpath = backtrace_root(node) if len(rpath) > 0: assert rpath[-1][0] is root if DEBUG_SPLIT: print('======== SPLIT (PY)') print('rpath = %s' % (rpath,)) print('node = %s' % (node,)) # We start by knowing where the node is # This is the base case of the recursive function bnode, part1, part2 = avl_release_kids(node) assert bnode is node if DEBUG_SPLIT: print('bnode = %s' % (bnode,)) print(' * part1 = %s' % (part1,)) print(' * part2 = %s' % (part2,)) avl_release_parent(bnode) # We have split out the node we care about. # Now, we need to recombine the tree in an ordered fashion # Retrace the the stack that would have been # generated by the old recursive key-based split for count, (node, direction) in enumerate(rpath): if DEBUG_SPLIT: print('+--- Iter {}'.format(count)) print(' * node = %s' % (node,)) print(' * direction = %r' % (direction,)) node, left, right = avl_release_kids(node) avl_release_parent(node) if DEBUG_SPLIT: print(' * left = %s' % (left,)) print(' * right = %s' % (right,)) # At `node` we would have decided to go `direction` if direction == 0: # left is case 1 if DEBUG_SPLIT: print(' * Case 1') print(' * Join %s + %s + %s' % (part2, node, right)) new_right = avl_join(part2, right, node) part1 = part1 part2 = new_right elif direction == 1: # right is case 1 if DEBUG_SPLIT: print(' * Case 2') print(' * Join %s + %s + %s' % (left, node, part1)) new_left = avl_join(left, part1, node) part1 = new_left part2 = part2 else: raise AssertionError('impossible state') if DEBUG_SPLIT: print(' * part1 = %s' % (part1,)) print(' * part2 = %s' % (part2,)) print('+--- End Iter {}'.format(count)) if DEBUG_SPLIT: print('RETURN') print(' * part1 = %s' % (part1,)) print(' * part2 = %s' % (part2,)) print(' * bnode = %s' % (bnode,)) return (part1, part2, bnode)
[ "def", "avl_split", "(", "root", ",", "node", ")", ":", "DEBUG_SPLIT", "=", "0", "# Get the backtrace to the root", "rpath", "=", "backtrace_root", "(", "node", ")", "if", "len", "(", "rpath", ")", ">", "0", ":", "assert", "rpath", "[", "-", "1", "]", ...
O(log(n)) Args: root (Node): tree root node (Node): node to split at Returns: puple: (tl, tr, node) tl contains all keys in the tree less than node tr contains all keys in the tree greater than node node is the node we split out CommandLine: python -m utool.experimental.euler_tour_tree_avl avl_split Example: >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> self = EulerTourTree(ut.chr_range(10)) >>> self.print_tree() >>> node = self.get_node(5) >>> part1, part2, bnode = avl_split(self.root, node) >>> ascii_tree(part1) >>> ascii_tree(part2) >>> ascii_tree(bnode) Example: >>> from utool.experimental.euler_tour_tree_avl import * # NOQA >>> test_avl_split(verbose=2)
[ "O", "(", "log", "(", "n", "))" ]
python
train
annayqho/TheCannon
code/lamost/mass_age/paper_plots/cn_features.py
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/mass_age/paper_plots/cn_features.py#L55-L75
def gen_cannon_grad_spec(base_labels, choose, low, high, coeffs, pivots): """ Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're varying high: highest val of cfe or nfe, whatever you're varying """ # Generate Cannon gradient spectra low_lab = copy.copy(base_labels) low_lab[choose] = low lvec = (train_model._get_lvec(np.array([low_lab]), pivots))[0] model_low = np.dot(coeffs, lvec) high_lab = copy.copy(base_labels) high_lab[choose] = high lvec = (train_model._get_lvec(np.array([high_lab]), pivots))[0] model_high = np.dot(coeffs, lvec) grad_spec = (model_high - model_low) / (high - low) return grad_spec
[ "def", "gen_cannon_grad_spec", "(", "base_labels", ",", "choose", ",", "low", ",", "high", ",", "coeffs", ",", "pivots", ")", ":", "# Generate Cannon gradient spectra", "low_lab", "=", "copy", ".", "copy", "(", "base_labels", ")", "low_lab", "[", "choose", "]"...
Generate Cannon gradient spectra Parameters ---------- labels: default values for [teff, logg, feh, cfe, nfe, afe, ak] choose: val of cfe or nfe, whatever you're varying low: lowest val of cfe or nfe, whatever you're varying high: highest val of cfe or nfe, whatever you're varying
[ "Generate", "Cannon", "gradient", "spectra" ]
python
train
SheffieldML/GPy
GPy/core/gp.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/core/gp.py#L384-L405
def predict_quantiles(self, X, quantiles=(2.5, 97.5), Y_metadata=None, kern=None, likelihood=None): """ Get the predictive quantiles around the prediction at X :param X: The points at which to make a prediction :type X: np.ndarray (Xnew x self.input_dim) :param quantiles: tuple of quantiles, default is (2.5, 97.5) which is the 95% interval :type quantiles: tuple :param kern: optional kernel to use for prediction :type predict_kw: dict :returns: list of quantiles for each X and predictive quantiles for interval combination :rtype: [np.ndarray (Xnew x self.output_dim), np.ndarray (Xnew x self.output_dim)] """ m, v = self._raw_predict(X, full_cov=False, kern=kern) if likelihood is None: likelihood = self.likelihood quantiles = likelihood.predictive_quantiles(m, v, quantiles, Y_metadata=Y_metadata) if self.normalizer is not None: quantiles = [self.normalizer.inverse_mean(q) for q in quantiles] return quantiles
[ "def", "predict_quantiles", "(", "self", ",", "X", ",", "quantiles", "=", "(", "2.5", ",", "97.5", ")", ",", "Y_metadata", "=", "None", ",", "kern", "=", "None", ",", "likelihood", "=", "None", ")", ":", "m", ",", "v", "=", "self", ".", "_raw_predi...
Get the predictive quantiles around the prediction at X :param X: The points at which to make a prediction :type X: np.ndarray (Xnew x self.input_dim) :param quantiles: tuple of quantiles, default is (2.5, 97.5) which is the 95% interval :type quantiles: tuple :param kern: optional kernel to use for prediction :type predict_kw: dict :returns: list of quantiles for each X and predictive quantiles for interval combination :rtype: [np.ndarray (Xnew x self.output_dim), np.ndarray (Xnew x self.output_dim)]
[ "Get", "the", "predictive", "quantiles", "around", "the", "prediction", "at", "X" ]
python
train
tagcubeio/tagcube-cli
tagcube_cli/main.py
https://github.com/tagcubeio/tagcube-cli/blob/709e4b0b11331a4d2791dc79107e5081518d75bf/tagcube_cli/main.py#L6-L26
def main(): """ Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit. """ cmd_args = TagCubeCLI.parse_args() try: tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args) except ValueError, ve: # We get here when there are no credentials configured print '%s' % ve sys.exit(1) try: sys.exit(tagcube_cli.run()) except ValueError, ve: # We get here when the configured credentials had some issue (invalid) # or there was some error (such as invalid profile name) with the params print '%s' % ve sys.exit(2)
[ "def", "main", "(", ")", ":", "cmd_args", "=", "TagCubeCLI", ".", "parse_args", "(", ")", "try", ":", "tagcube_cli", "=", "TagCubeCLI", ".", "from_cmd_args", "(", "cmd_args", ")", "except", "ValueError", ",", "ve", ":", "# We get here when there are no credentia...
Project's main method which will parse the command line arguments, run a scan using the TagCubeClient and exit.
[ "Project", "s", "main", "method", "which", "will", "parse", "the", "command", "line", "arguments", "run", "a", "scan", "using", "the", "TagCubeClient", "and", "exit", "." ]
python
train
yougov/librarypaste
librarypaste/pmxbot.py
https://github.com/yougov/librarypaste/blob/740fafcb260f493ca5bbd24afd59d49444c2b2ae/librarypaste/pmxbot.py#L14-L23
def paste(client, event, channel, nick, rest): "Drop a link to your latest paste" path = '/last/{nick}'.format(**locals()) paste_root = pmxbot.config.get('librarypaste', 'http://paste.jaraco.com') url = urllib.parse.urljoin(paste_root, path) auth = pmxbot.config.get('librarypaste auth') resp = requests.head(url, auth=_request_friendly(auth)) if not resp.ok: return "I couldn't resolve a recent paste of yours. Maybe try " + url return resp.headers['location']
[ "def", "paste", "(", "client", ",", "event", ",", "channel", ",", "nick", ",", "rest", ")", ":", "path", "=", "'/last/{nick}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "paste_root", "=", "pmxbot", ".", "config", ".", "get", "(", "'li...
Drop a link to your latest paste
[ "Drop", "a", "link", "to", "your", "latest", "paste" ]
python
train
LonamiWebs/Telethon
telethon/tl/custom/button.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/button.py#L134-L143
def request_phone(cls, text, *, resize=None, single_use=None, selective=None): """ Creates a new button that will request the user's phone number upon being clicked. ``resize``, ``single_use`` and ``selective`` are documented in `text`. """ return cls(types.KeyboardButtonRequestPhone(text), resize=resize, single_use=single_use, selective=selective)
[ "def", "request_phone", "(", "cls", ",", "text", ",", "*", ",", "resize", "=", "None", ",", "single_use", "=", "None", ",", "selective", "=", "None", ")", ":", "return", "cls", "(", "types", ".", "KeyboardButtonRequestPhone", "(", "text", ")", ",", "re...
Creates a new button that will request the user's phone number upon being clicked. ``resize``, ``single_use`` and ``selective`` are documented in `text`.
[ "Creates", "a", "new", "button", "that", "will", "request", "the", "user", "s", "phone", "number", "upon", "being", "clicked", "." ]
python
train
gem/oq-engine
openquake/hazardlib/gsim/edwards_fah_2013a.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/edwards_fah_2013a.py#L183-L190
def _compute_term_2(self, C, mag, R): """ (a8 + a9.*M + a10.*M.*M + a11.*M.*M.*M).*d(r) """ return ( (C['a8'] + C['a9'] * mag + C['a10'] * np.power(mag, 2) + C['a11'] * np.power(mag, 3)) * R )
[ "def", "_compute_term_2", "(", "self", ",", "C", ",", "mag", ",", "R", ")", ":", "return", "(", "(", "C", "[", "'a8'", "]", "+", "C", "[", "'a9'", "]", "*", "mag", "+", "C", "[", "'a10'", "]", "*", "np", ".", "power", "(", "mag", ",", "2", ...
(a8 + a9.*M + a10.*M.*M + a11.*M.*M.*M).*d(r)
[ "(", "a8", "+", "a9", ".", "*", "M", "+", "a10", ".", "*", "M", ".", "*", "M", "+", "a11", ".", "*", "M", ".", "*", "M", ".", "*", "M", ")", ".", "*", "d", "(", "r", ")" ]
python
train
zeroSteiner/AdvancedHTTPServer
advancedhttpserver.py
https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1162-L1204
def check_authorization(self): """ Check for the presence of a basic auth Authorization header and if the credentials contained within in are valid. :return: Whether or not the credentials are valid. :rtype: bool """ try: store = self.__config.get('basic_auth') if store is None: return True auth_info = self.headers.get('Authorization') if not auth_info: return False auth_info = auth_info.split() if len(auth_info) != 2 or auth_info[0] != 'Basic': return False auth_info = base64.b64decode(auth_info[1]).decode(sys.getdefaultencoding()) username = auth_info.split(':')[0] password = ':'.join(auth_info.split(':')[1:]) password_bytes = password.encode(sys.getdefaultencoding()) if hasattr(self, 'custom_authentication'): if self.custom_authentication(username, password): self.basic_auth_user = username return True return False if not username in store: self.server.logger.warning('received invalid username: ' + username) return False password_data = store[username] if password_data['type'] == 'plain': if password == password_data['value']: self.basic_auth_user = username return True elif hashlib.new(password_data['type'], password_bytes).digest() == password_data['value']: self.basic_auth_user = username return True self.server.logger.warning('received invalid password from user: ' + username) except Exception: pass return False
[ "def", "check_authorization", "(", "self", ")", ":", "try", ":", "store", "=", "self", ".", "__config", ".", "get", "(", "'basic_auth'", ")", "if", "store", "is", "None", ":", "return", "True", "auth_info", "=", "self", ".", "headers", ".", "get", "(",...
Check for the presence of a basic auth Authorization header and if the credentials contained within in are valid. :return: Whether or not the credentials are valid. :rtype: bool
[ "Check", "for", "the", "presence", "of", "a", "basic", "auth", "Authorization", "header", "and", "if", "the", "credentials", "contained", "within", "in", "are", "valid", "." ]
python
train
marrow/WebCore
web/server/gevent_.py
https://github.com/marrow/WebCore/blob/38d50f8022ca62976a1e5ff23f7714bd647b6532/web/server/gevent_.py#L14-L18
def serve(application, host='127.0.0.1', port=8080): """Gevent-based WSGI-HTTP server.""" # Instantiate the server with a host/port configuration and our application. WSGIServer((host, int(port)), application).serve_forever()
[ "def", "serve", "(", "application", ",", "host", "=", "'127.0.0.1'", ",", "port", "=", "8080", ")", ":", "# Instantiate the server with a host/port configuration and our application.", "WSGIServer", "(", "(", "host", ",", "int", "(", "port", ")", ")", ",", "applic...
Gevent-based WSGI-HTTP server.
[ "Gevent", "-", "based", "WSGI", "-", "HTTP", "server", "." ]
python
train
klmitch/turnstile
turnstile/limits.py
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L993-L1023
def format(self, status, headers, environ, bucket, delay): """ Formats a response entity. Returns a tuple of the desired status code and the formatted entity. The default status code is passed in, as is a dictionary of headers. :param status: The default status code. Should be returned to the caller, or an alternate selected. The status code should include both the number and the message, separated by a single space. :param headers: A dictionary of headers for the response. Should update the 'Content-Type' header at a minimum. :param environ: The WSGI environment for the request. :param bucket: The bucket containing the data which caused the delay decision to be made. This can be used to obtain such information as the next time the request can be made. :param delay: The number of seconds by which the request should be delayed. """ # This is a default response entity, which can be overridden # by limit subclasses. entity = ("This request was rate-limited. " "Please retry your request after %s." % time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(bucket.next))) headers['Content-Type'] = 'text/plain' return status, entity
[ "def", "format", "(", "self", ",", "status", ",", "headers", ",", "environ", ",", "bucket", ",", "delay", ")", ":", "# This is a default response entity, which can be overridden", "# by limit subclasses.", "entity", "=", "(", "\"This request was rate-limited. \"", "\"Ple...
Formats a response entity. Returns a tuple of the desired status code and the formatted entity. The default status code is passed in, as is a dictionary of headers. :param status: The default status code. Should be returned to the caller, or an alternate selected. The status code should include both the number and the message, separated by a single space. :param headers: A dictionary of headers for the response. Should update the 'Content-Type' header at a minimum. :param environ: The WSGI environment for the request. :param bucket: The bucket containing the data which caused the delay decision to be made. This can be used to obtain such information as the next time the request can be made. :param delay: The number of seconds by which the request should be delayed.
[ "Formats", "a", "response", "entity", ".", "Returns", "a", "tuple", "of", "the", "desired", "status", "code", "and", "the", "formatted", "entity", ".", "The", "default", "status", "code", "is", "passed", "in", "as", "is", "a", "dictionary", "of", "headers"...
python
train
mongodb/mongo-python-driver
pymongo/mongo_client.py
https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/mongo_client.py#L1879-L1895
def database_names(self, session=None): """**DEPRECATED**: Get a list of the names of all databases on the connected server. :Parameters: - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. .. versionchanged:: 3.7 Deprecated. Use :meth:`list_database_names` instead. .. versionchanged:: 3.6 Added ``session`` parameter. """ warnings.warn("database_names is deprecated. Use list_database_names " "instead.", DeprecationWarning, stacklevel=2) return self.list_database_names(session)
[ "def", "database_names", "(", "self", ",", "session", "=", "None", ")", ":", "warnings", ".", "warn", "(", "\"database_names is deprecated. Use list_database_names \"", "\"instead.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "self", "....
**DEPRECATED**: Get a list of the names of all databases on the connected server. :Parameters: - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. .. versionchanged:: 3.7 Deprecated. Use :meth:`list_database_names` instead. .. versionchanged:: 3.6 Added ``session`` parameter.
[ "**", "DEPRECATED", "**", ":", "Get", "a", "list", "of", "the", "names", "of", "all", "databases", "on", "the", "connected", "server", "." ]
python
train
mwouts/jupytext
jupytext/jupytext.py
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/jupytext.py#L92-L178
def writes(self, nb, metadata=None, **kwargs): """Return the text representation of the notebook""" if self.fmt.get('format_name') == 'pandoc': metadata = insert_jupytext_info_and_filter_metadata(metadata, self.ext, self.implementation) cells = [] for cell in nb.cells: cell_metadata = filter_metadata(copy(cell.metadata), self.fmt.get('cell_metadata_filter'), _IGNORE_CELL_METADATA) if cell.cell_type == 'code': cells.append(new_code_cell(source=cell.source, metadata=cell_metadata)) else: cells.append(NotebookNode(source=cell.source, metadata=cell_metadata, cell_type=cell.cell_type)) return notebook_to_md(new_notebook(metadata=metadata, cells=cells)) # Copy the notebook, in order to be sure we do not modify the original notebook nb = new_notebook(cells=nb.cells, metadata=deepcopy(metadata or nb.metadata)) metadata = nb.metadata default_language = default_language_from_metadata_and_ext(metadata, self.implementation.extension) self.update_fmt_with_notebook_options(nb.metadata) if 'main_language' in metadata.get('jupytext', {}): del metadata['jupytext']['main_language'] header = encoding_and_executable(nb, metadata, self.ext) header_content, header_lines_to_next_cell = metadata_and_cell_to_header(nb, metadata, self.implementation, self.ext) header.extend(header_content) cell_exporters = [] looking_for_first_markdown_cell = (self.implementation.format_name and self.implementation.format_name.startswith('sphinx')) split_at_heading = self.fmt.get('split_at_heading', False) for cell in nb.cells: if looking_for_first_markdown_cell and cell.cell_type == 'markdown': cell.metadata.setdefault('cell_marker', '"""') looking_for_first_markdown_cell = False cell_exporters.append(self.implementation.cell_exporter_class(cell, default_language, self.fmt)) texts = [cell.cell_to_text() for cell in cell_exporters] lines = [] # concatenate cells in reverse order to determine how many blank lines (pep8) for i, cell in reversed(list(enumerate(cell_exporters))): text = cell.remove_eoc_marker(texts[i], lines) if i == 0 and self.implementation.format_name and \ self.implementation.format_name.startswith('sphinx') and \ (text in [['%matplotlib inline'], ['# %matplotlib inline']]): continue lines_to_next_cell = cell.lines_to_next_cell if lines_to_next_cell is None: lines_to_next_cell = pep8_lines_between_cells(text, lines, self.implementation.extension) text.extend([''] * lines_to_next_cell) # two blank lines between markdown cells in Rmd when those do not have explicit region markers if self.ext in ['.Rmd', '.md'] and not cell.is_code(): if (i + 1 < len(cell_exporters) and not cell_exporters[i + 1].is_code() and not texts[i][0].startswith('<!-- #region') and not texts[i + 1][0].startswith('<!-- #region') and (not split_at_heading or not (texts[i + 1] and texts[i + 1][0].startswith('#')))): text.append('') # "" between two consecutive code cells in sphinx if self.implementation.format_name.startswith('sphinx') and cell.is_code(): if i + 1 < len(cell_exporters) and cell_exporters[i + 1].is_code(): text.append('""') if i + 1 < len(cell_exporters): lines = cell_exporters[i + 1].simplify_soc_marker(lines, text) lines = text + lines if header_lines_to_next_cell is None: header_lines_to_next_cell = pep8_lines_between_cells(header_content, lines, self.implementation.extension) header.extend([''] * header_lines_to_next_cell) if cell_exporters: lines = cell_exporters[0].simplify_soc_marker(lines, header) return '\n'.join(header + lines)
[ "def", "writes", "(", "self", ",", "nb", ",", "metadata", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "fmt", ".", "get", "(", "'format_name'", ")", "==", "'pandoc'", ":", "metadata", "=", "insert_jupytext_info_and_filter_metadata", ...
Return the text representation of the notebook
[ "Return", "the", "text", "representation", "of", "the", "notebook" ]
python
train
hollenstein/maspy
maspy/core.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/core.py#L53-L71
def _getArrays(items, attr, defaultValue): """Return arrays with equal size of item attributes from a list of sorted "items" for fast and convenient data processing. :param attr: list of item attributes that should be added to the returned array. :param defaultValue: if an item is missing an attribute, the "defaultValue" is added to the array instead. :returns: {'attribute1': numpy.array([attributeValue1, ...]), ...} """ arrays = dict([(key, []) for key in attr]) for item in items: for key in attr: arrays[key].append(getattr(item, key, defaultValue)) for key in [_ for _ in viewkeys(arrays)]: arrays[key] = numpy.array(arrays[key]) return arrays
[ "def", "_getArrays", "(", "items", ",", "attr", ",", "defaultValue", ")", ":", "arrays", "=", "dict", "(", "[", "(", "key", ",", "[", "]", ")", "for", "key", "in", "attr", "]", ")", "for", "item", "in", "items", ":", "for", "key", "in", "attr", ...
Return arrays with equal size of item attributes from a list of sorted "items" for fast and convenient data processing. :param attr: list of item attributes that should be added to the returned array. :param defaultValue: if an item is missing an attribute, the "defaultValue" is added to the array instead. :returns: {'attribute1': numpy.array([attributeValue1, ...]), ...}
[ "Return", "arrays", "with", "equal", "size", "of", "item", "attributes", "from", "a", "list", "of", "sorted", "items", "for", "fast", "and", "convenient", "data", "processing", "." ]
python
train
openearth/mmi-python
mmi/tracker.py
https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/tracker.py#L165-L173
def post(self): """Register a new model (models)""" self.set_header("Content-Type", "application/json") key = uuid.uuid4().hex metadata = json.loads(self.request.body.decode()) metadata["uuid"] = key self.database[key] = metadata result = json.dumps({"uuid": key}) self.write(result)
[ "def", "post", "(", "self", ")", ":", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "key", "=", "uuid", ".", "uuid4", "(", ")", ".", "hex", "metadata", "=", "json", ".", "loads", "(", "self", ".", "request", ".",...
Register a new model (models)
[ "Register", "a", "new", "model", "(", "models", ")" ]
python
train
inveniosoftware-contrib/invenio-classifier
invenio_classifier/reader.py
https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L58-L91
def get_cache(taxonomy_id): """Return cache for the given taxonomy id. :param taxonomy_id: identifier of the taxonomy :type taxonomy_id: str :return: dictionary object (empty if no taxonomy_id is found), you must not change anything inside it. Create a new dictionary and use set_cache if you want to update the cache! """ if taxonomy_id in _CACHE: ctime, taxonomy = _CACHE[taxonomy_id] # check it is fresh version onto_name, onto_path, onto_url = _get_ontology(taxonomy_id) cache_path = _get_cache_path(onto_name) # if source exists and is newer than the cache hold in memory if os.path.isfile(onto_path) and os.path.getmtime(onto_path) > ctime: current_app.logger.info( 'Forcing taxonomy rebuild as cached version is newer/updated.' ) return {} # force cache rebuild # if cache exists and is newer than the cache hold in memory if os.path.isfile(cache_path) and os.path.getmtime(cache_path) > ctime: current_app.logger.info( 'Forcing taxonomy rebuild as source file is newer/updated.' ) return {} current_app.logger.info('Taxonomy retrieved from cache') return taxonomy return {}
[ "def", "get_cache", "(", "taxonomy_id", ")", ":", "if", "taxonomy_id", "in", "_CACHE", ":", "ctime", ",", "taxonomy", "=", "_CACHE", "[", "taxonomy_id", "]", "# check it is fresh version", "onto_name", ",", "onto_path", ",", "onto_url", "=", "_get_ontology", "("...
Return cache for the given taxonomy id. :param taxonomy_id: identifier of the taxonomy :type taxonomy_id: str :return: dictionary object (empty if no taxonomy_id is found), you must not change anything inside it. Create a new dictionary and use set_cache if you want to update the cache!
[ "Return", "cache", "for", "the", "given", "taxonomy", "id", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Executor.py#L448-L469
def get_contents(self): """Fetch the signature contents. This is the main reason this class exists, so we can compute this once and cache it regardless of how many target or source Nodes there are. """ try: return self._memo['get_contents'] except KeyError: pass env = self.get_build_env() action_list = self.get_action_list() all_targets = self.get_all_targets() all_sources = self.get_all_sources() result = bytearray("",'utf-8').join([action.get_contents(all_targets, all_sources, env) for action in action_list]) self._memo['get_contents'] = result return result
[ "def", "get_contents", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_memo", "[", "'get_contents'", "]", "except", "KeyError", ":", "pass", "env", "=", "self", ".", "get_build_env", "(", ")", "action_list", "=", "self", ".", "get_action_list",...
Fetch the signature contents. This is the main reason this class exists, so we can compute this once and cache it regardless of how many target or source Nodes there are.
[ "Fetch", "the", "signature", "contents", ".", "This", "is", "the", "main", "reason", "this", "class", "exists", "so", "we", "can", "compute", "this", "once", "and", "cache", "it", "regardless", "of", "how", "many", "target", "or", "source", "Nodes", "there...
python
train
smarter-travel-media/stac
stac/http.py
https://github.com/smarter-travel-media/stac/blob/cdb29a17ede0924b122b3905a500442c62ae53b7/stac/http.py#L69-L102
def get_most_recent_versions(self, group, artifact, limit, remote=False, integration=False): """Get a list of the version numbers of the most recent artifacts (integration or non-integration), ordered by the version number, for a particular group and artifact combination. :param str group: Group of the artifact to get versions of :param str artifact: Name of the artifact to get versions of :param int limit: Fetch only this many of the most recent releases :param bool remote: Should remote repositories be searched to find the latest versions? Note this can make the request much slower. Default is false. :param bool integration: If true, fetch only "integration versions", otherwise fetch only non-integration versions. :return: Version numbers of the most recent artifacts :rtype: list :raises requests.exceptions.HTTPError: For any non-success HTTP responses from the Artifactory API. :raises ValueError: If limit is 0 or negative. """ if limit < 1: raise ValueError("Releases limit must be positive") url = self._base_url + '/api/search/versions' params = {'g': group, 'a': artifact, 'repos': self._repo, 'remote': int(remote)} self._logger.debug("Using all version API at %s - params %s", url, params) response = self._session.get(url, params=params) response.raise_for_status() json = response.json() versions = [ item['version'] for item in json['results'] if item['integration'] is integration] # pylint: disable=no-member versions.sort(key=distutils.version.LooseVersion, reverse=True) return versions[:limit]
[ "def", "get_most_recent_versions", "(", "self", ",", "group", ",", "artifact", ",", "limit", ",", "remote", "=", "False", ",", "integration", "=", "False", ")", ":", "if", "limit", "<", "1", ":", "raise", "ValueError", "(", "\"Releases limit must be positive\"...
Get a list of the version numbers of the most recent artifacts (integration or non-integration), ordered by the version number, for a particular group and artifact combination. :param str group: Group of the artifact to get versions of :param str artifact: Name of the artifact to get versions of :param int limit: Fetch only this many of the most recent releases :param bool remote: Should remote repositories be searched to find the latest versions? Note this can make the request much slower. Default is false. :param bool integration: If true, fetch only "integration versions", otherwise fetch only non-integration versions. :return: Version numbers of the most recent artifacts :rtype: list :raises requests.exceptions.HTTPError: For any non-success HTTP responses from the Artifactory API. :raises ValueError: If limit is 0 or negative.
[ "Get", "a", "list", "of", "the", "version", "numbers", "of", "the", "most", "recent", "artifacts", "(", "integration", "or", "non", "-", "integration", ")", "ordered", "by", "the", "version", "number", "for", "a", "particular", "group", "and", "artifact", ...
python
train
DistrictDataLabs/yellowbrick
yellowbrick/contrib/missing/dispersion.py
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/contrib/missing/dispersion.py#L132-L146
def draw_multi_dispersion_chart(self, nan_locs): """Draws a multi dimensional dispersion chart, each color corresponds to a different target variable. """ for index, nan_values in enumerate(nan_locs): label, nan_locations = nan_values # if features passed in then, label as such if self.classes_ is not None: label = self.classes_[index] color = self.colors[index] x_, y_ = list(zip(*nan_locations)) self.ax.scatter(x_, y_, alpha=self.alpha, marker=self.marker, color=color, label=label)
[ "def", "draw_multi_dispersion_chart", "(", "self", ",", "nan_locs", ")", ":", "for", "index", ",", "nan_values", "in", "enumerate", "(", "nan_locs", ")", ":", "label", ",", "nan_locations", "=", "nan_values", "# if features passed in then, label as such", "if", "sel...
Draws a multi dimensional dispersion chart, each color corresponds to a different target variable.
[ "Draws", "a", "multi", "dimensional", "dispersion", "chart", "each", "color", "corresponds", "to", "a", "different", "target", "variable", "." ]
python
train
MonashBI/arcana
arcana/repository/xnat.py
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/repository/xnat.py#L727-L758
def _get_labels(self, frequency, subject_id=None, visit_id=None): """ Returns the labels for the XNAT subject and sessions given the frequency and provided IDs. """ if frequency == 'per_session': subj_label = '{}_{}'.format(self.project_id, subject_id) sess_label = '{}_{}_{}'.format(self.project_id, subject_id, visit_id) elif frequency == 'per_subject': subj_label = '{}_{}'.format(self.project_id, subject_id) sess_label = '{}_{}_{}'.format(self.project_id, subject_id, self.SUMMARY_NAME) elif frequency == 'per_visit': subj_label = '{}_{}'.format(self.project_id, self.SUMMARY_NAME) sess_label = '{}_{}_{}'.format(self.project_id, self.SUMMARY_NAME, visit_id) elif frequency == 'per_study': subj_label = '{}_{}'.format(self.project_id, self.SUMMARY_NAME) sess_label = '{}_{}_{}'.format(self.project_id, self.SUMMARY_NAME, self.SUMMARY_NAME) else: assert False return (subj_label, sess_label)
[ "def", "_get_labels", "(", "self", ",", "frequency", ",", "subject_id", "=", "None", ",", "visit_id", "=", "None", ")", ":", "if", "frequency", "==", "'per_session'", ":", "subj_label", "=", "'{}_{}'", ".", "format", "(", "self", ".", "project_id", ",", ...
Returns the labels for the XNAT subject and sessions given the frequency and provided IDs.
[ "Returns", "the", "labels", "for", "the", "XNAT", "subject", "and", "sessions", "given", "the", "frequency", "and", "provided", "IDs", "." ]
python
train
PyCQA/astroid
astroid/inference.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/inference.py#L526-L531
def infer_unaryop(self, context=None): """Infer what an UnaryOp should return when evaluated.""" yield from _filter_operation_errors( self, _infer_unaryop, context, util.BadUnaryOperationMessage ) return dict(node=self, context=context)
[ "def", "infer_unaryop", "(", "self", ",", "context", "=", "None", ")", ":", "yield", "from", "_filter_operation_errors", "(", "self", ",", "_infer_unaryop", ",", "context", ",", "util", ".", "BadUnaryOperationMessage", ")", "return", "dict", "(", "node", "=", ...
Infer what an UnaryOp should return when evaluated.
[ "Infer", "what", "an", "UnaryOp", "should", "return", "when", "evaluated", "." ]
python
train
ronaldguillen/wave
wave/fields.py
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/fields.py#L547-L554
def root(self): """ Returns the top-level serializer for this field. """ root = self while root.parent is not None: root = root.parent return root
[ "def", "root", "(", "self", ")", ":", "root", "=", "self", "while", "root", ".", "parent", "is", "not", "None", ":", "root", "=", "root", ".", "parent", "return", "root" ]
Returns the top-level serializer for this field.
[ "Returns", "the", "top", "-", "level", "serializer", "for", "this", "field", "." ]
python
train
richardchien/nonebot
nonebot/command/__init__.py
https://github.com/richardchien/nonebot/blob/13ed9e4e87d9824b61592520aabda6d2737c8848/nonebot/command/__init__.py#L671-L680
def kill_current_session(ctx: Context_T) -> None: """ Force kill current session of the given context, despite whether it is running or not. :param ctx: message context """ ctx_id = context_id(ctx) if ctx_id in _sessions: del _sessions[ctx_id]
[ "def", "kill_current_session", "(", "ctx", ":", "Context_T", ")", "->", "None", ":", "ctx_id", "=", "context_id", "(", "ctx", ")", "if", "ctx_id", "in", "_sessions", ":", "del", "_sessions", "[", "ctx_id", "]" ]
Force kill current session of the given context, despite whether it is running or not. :param ctx: message context
[ "Force", "kill", "current", "session", "of", "the", "given", "context", "despite", "whether", "it", "is", "running", "or", "not", "." ]
python
train
pyQode/pyqode.core
pyqode/core/panels/checker.py
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/checker.py#L34-L48
def marker_for_line(self, line): """ Returns the marker that is displayed at the specified line number if any. :param line: The marker line. :return: Marker of None :rtype: pyqode.core.Marker """ block = self.editor.document().findBlockByNumber(line) try: return block.userData().messages except AttributeError: return []
[ "def", "marker_for_line", "(", "self", ",", "line", ")", ":", "block", "=", "self", ".", "editor", ".", "document", "(", ")", ".", "findBlockByNumber", "(", "line", ")", "try", ":", "return", "block", ".", "userData", "(", ")", ".", "messages", "except...
Returns the marker that is displayed at the specified line number if any. :param line: The marker line. :return: Marker of None :rtype: pyqode.core.Marker
[ "Returns", "the", "marker", "that", "is", "displayed", "at", "the", "specified", "line", "number", "if", "any", "." ]
python
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/plugin.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/plugin.py#L1129-L1143
def tunnel_to_kernel(self, connection_info, hostname, sshkey=None, password=None, timeout=10): """ Tunnel connections to a kernel via ssh. Remote ports are specified in the connection info ci. """ lports = zmqtunnel.select_random_ports(4) rports = (connection_info['shell_port'], connection_info['iopub_port'], connection_info['stdin_port'], connection_info['hb_port']) remote_ip = connection_info['ip'] for lp, rp in zip(lports, rports): self.ssh_tunnel(lp, rp, hostname, remote_ip, sshkey, password, timeout) return tuple(lports)
[ "def", "tunnel_to_kernel", "(", "self", ",", "connection_info", ",", "hostname", ",", "sshkey", "=", "None", ",", "password", "=", "None", ",", "timeout", "=", "10", ")", ":", "lports", "=", "zmqtunnel", ".", "select_random_ports", "(", "4", ")", "rports",...
Tunnel connections to a kernel via ssh. Remote ports are specified in the connection info ci.
[ "Tunnel", "connections", "to", "a", "kernel", "via", "ssh", ".", "Remote", "ports", "are", "specified", "in", "the", "connection", "info", "ci", "." ]
python
train
vmalloc/dessert
dessert/rewrite.py
https://github.com/vmalloc/dessert/blob/fa86b39da4853f2c35f0686942db777c7cc57728/dessert/rewrite.py#L371-L387
def _saferepr(obj): """Get a safe repr of an object for assertion error messages. The assertion formatting (util.format_explanation()) requires newlines to be escaped since they are a special character for it. Normally assertion.util.format_explanation() does this but for a custom repr it is possible to contain one of the special escape sequences, especially '\n{' and '\n}' are likely to be present in JSON reprs. """ repr = py.io.saferepr(obj) if py.builtin._istext(repr): t = py.builtin.text else: t = py.builtin.bytes return repr.replace(t("\n"), t("\\n"))
[ "def", "_saferepr", "(", "obj", ")", ":", "repr", "=", "py", ".", "io", ".", "saferepr", "(", "obj", ")", "if", "py", ".", "builtin", ".", "_istext", "(", "repr", ")", ":", "t", "=", "py", ".", "builtin", ".", "text", "else", ":", "t", "=", "...
Get a safe repr of an object for assertion error messages. The assertion formatting (util.format_explanation()) requires newlines to be escaped since they are a special character for it. Normally assertion.util.format_explanation() does this but for a custom repr it is possible to contain one of the special escape sequences, especially '\n{' and '\n}' are likely to be present in JSON reprs.
[ "Get", "a", "safe", "repr", "of", "an", "object", "for", "assertion", "error", "messages", "." ]
python
train
tapanpandita/pocket
pocket.py
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L190-L198
def bulk_add( self, item_id, ref_id=None, tags=None, time=None, title=None, url=None, wait=True ): ''' Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add '''
[ "def", "bulk_add", "(", "self", ",", "item_id", ",", "ref_id", "=", "None", ",", "tags", "=", "None", ",", "time", "=", "None", ",", "title", "=", "None", ",", "url", "=", "None", ",", "wait", "=", "True", ")", ":" ]
Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add
[ "Add", "a", "new", "item", "to", "the", "user", "s", "list", "http", ":", "//", "getpocket", ".", "com", "/", "developer", "/", "docs", "/", "v3", "/", "modify#action_add" ]
python
train
evonove/django-stored-messages
stored_messages/backends/redis/backend.py
https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/backends/redis/backend.py#L48-L55
def _list_key(self, key): """ boilerplate """ ret = [] for msg_json in self.client.lrange(key, 0, -1): ret.append(self._fromJSON(msg_json)) return ret
[ "def", "_list_key", "(", "self", ",", "key", ")", ":", "ret", "=", "[", "]", "for", "msg_json", "in", "self", ".", "client", ".", "lrange", "(", "key", ",", "0", ",", "-", "1", ")", ":", "ret", ".", "append", "(", "self", ".", "_fromJSON", "(",...
boilerplate
[ "boilerplate" ]
python
valid
tensorflow/datasets
tensorflow_datasets/scripts/create_new_dataset.py
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/scripts/create_new_dataset.py#L155-L164
def create_dataset_file(root_dir, data): """Create a new dataset from a template.""" file_path = os.path.join(root_dir, '{dataset_type}', '{dataset_name}.py') context = ( _HEADER + _DATASET_DEFAULT_IMPORTS + _CITATION + _DESCRIPTION + _DATASET_DEFAULTS ) with gfile.GFile(file_path.format(**data), 'w') as f: f.write(context.format(**data))
[ "def", "create_dataset_file", "(", "root_dir", ",", "data", ")", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'{dataset_type}'", ",", "'{dataset_name}.py'", ")", "context", "=", "(", "_HEADER", "+", "_DATASET_DEFAULT_IMPORTS", ...
Create a new dataset from a template.
[ "Create", "a", "new", "dataset", "from", "a", "template", "." ]
python
train
scnerd/miniutils
miniutils/timing.py
https://github.com/scnerd/miniutils/blob/fe927e26afc5877416dead28dabdf6604387f42c/miniutils/timing.py#L29-L63
def tic(log_level='DEBUG', fmt="{file}:{line} - {message} - {diff:0.6f}s (total={total:0.1f}s)", verbose=True): """A minimalistic ``printf``-type timing utility. Call this function to start timing individual sections of code :param log_level: The level at which to log block run times :param fmt: The format string to use when logging times. Available arguments include: - file, line, func, code_text: The stack frame information which called this timer - diff: The time since the last timer printout was called - total: The time since this timing block was started - message: The message passed to this timing printout :param verbose: If False, suppress printing messages :return: A function that reports run times when called """ first_time = last_time = time() def toc(message=None): """A function that reports run times :param message: The message to print with this particular runtime :return: The time difference (in seconds) since the last tic or toc """ nonlocal last_time now = time() diff = now - last_time total = now - first_time if verbose: file, line, func, code_text = traceback.extract_stack(limit=2)[0] log(log_level, fmt.format(**locals())) last_time = time() return diff return toc
[ "def", "tic", "(", "log_level", "=", "'DEBUG'", ",", "fmt", "=", "\"{file}:{line} - {message} - {diff:0.6f}s (total={total:0.1f}s)\"", ",", "verbose", "=", "True", ")", ":", "first_time", "=", "last_time", "=", "time", "(", ")", "def", "toc", "(", "message", "="...
A minimalistic ``printf``-type timing utility. Call this function to start timing individual sections of code :param log_level: The level at which to log block run times :param fmt: The format string to use when logging times. Available arguments include: - file, line, func, code_text: The stack frame information which called this timer - diff: The time since the last timer printout was called - total: The time since this timing block was started - message: The message passed to this timing printout :param verbose: If False, suppress printing messages :return: A function that reports run times when called
[ "A", "minimalistic", "printf", "-", "type", "timing", "utility", ".", "Call", "this", "function", "to", "start", "timing", "individual", "sections", "of", "code" ]
python
train
sprockets/sprockets.http
examples.py
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/examples.py#L10-L27
def get(self, status_code): """ Returns the requested status. :param int status_code: the status code to return :queryparam str reason: optional reason phrase """ status_code = int(status_code) if status_code >= 400: kwargs = {'status_code': status_code} if self.get_query_argument('reason', None): kwargs['reason'] = self.get_query_argument('reason') if self.get_query_argument('log_message', None): kwargs['log_message'] = self.get_query_argument('log_message') self.send_error(**kwargs) else: self.set_status(status_code)
[ "def", "get", "(", "self", ",", "status_code", ")", ":", "status_code", "=", "int", "(", "status_code", ")", "if", "status_code", ">=", "400", ":", "kwargs", "=", "{", "'status_code'", ":", "status_code", "}", "if", "self", ".", "get_query_argument", "(", ...
Returns the requested status. :param int status_code: the status code to return :queryparam str reason: optional reason phrase
[ "Returns", "the", "requested", "status", "." ]
python
train
faide/py3o.template
py3o/template/main.py
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L49-L66
def detect_keep_boundary(start, end, namespaces): """a helper to inspect a link and see if we should keep the link boundary """ result_start, result_end = False, False parent_start = start.getparent() parent_end = end.getparent() if parent_start.tag == "{%s}p" % namespaces['text']: # more than one child in the containing paragraph ? # we keep the boundary result_start = len(parent_start.getchildren()) > 1 if parent_end.tag == "{%s}p" % namespaces['text']: # more than one child in the containing paragraph ? # we keep the boundary result_end = len(parent_end.getchildren()) > 1 return result_start, result_end
[ "def", "detect_keep_boundary", "(", "start", ",", "end", ",", "namespaces", ")", ":", "result_start", ",", "result_end", "=", "False", ",", "False", "parent_start", "=", "start", ".", "getparent", "(", ")", "parent_end", "=", "end", ".", "getparent", "(", ...
a helper to inspect a link and see if we should keep the link boundary
[ "a", "helper", "to", "inspect", "a", "link", "and", "see", "if", "we", "should", "keep", "the", "link", "boundary" ]
python
train
mlperf/training
translation/tensorflow/transformer/utils/tokenizer.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L574-L616
def _generate_subtokens( token_counts, alphabet, min_count, num_iterations=4, reserved_tokens=None): """Create a list of subtokens in decreasing order of frequency. Args: token_counts: dict mapping str tokens -> int count alphabet: set of characters min_count: int minimum number of times a subtoken must appear before it is added to the vocabulary. num_iterations: int number of iterations to generate new tokens. reserved_tokens: list of tokens that will be added to the beginning to the returned subtoken list. Returns: Sorted list of subtokens (most frequent first) """ if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS # Use alphabet set to create initial list of subtokens subtoken_list = reserved_tokens + list(alphabet) max_subtoken_length = 1 # On each iteration, segment all words using the subtokens defined in # subtoken_dict, count how often the resulting subtokens appear, and update # the dictionary with subtokens w/ high enough counts. for i in xrange(num_iterations): tf.logging.info("\tGenerating subtokens: iteration %d" % i) # Generate new subtoken->id dictionary using the new subtoken list. subtoken_dict = _list_to_index_dict(subtoken_list) # Create dict mapping subtoken->count, with additional subtokens created # from substrings taken from the tokens. subtoken_counts = _count_and_gen_subtokens( token_counts, alphabet, subtoken_dict, max_subtoken_length) # Generate new list of subtokens sorted by subtoken count. subtoken_list, max_subtoken_length = _gen_new_subtoken_list( subtoken_counts, min_count, alphabet, reserved_tokens) tf.logging.info("\tVocab size: %d" % len(subtoken_list)) return subtoken_list
[ "def", "_generate_subtokens", "(", "token_counts", ",", "alphabet", ",", "min_count", ",", "num_iterations", "=", "4", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":", "reserved_tokens", "=", "RESERVED_TOKENS", "# Use alph...
Create a list of subtokens in decreasing order of frequency. Args: token_counts: dict mapping str tokens -> int count alphabet: set of characters min_count: int minimum number of times a subtoken must appear before it is added to the vocabulary. num_iterations: int number of iterations to generate new tokens. reserved_tokens: list of tokens that will be added to the beginning to the returned subtoken list. Returns: Sorted list of subtokens (most frequent first)
[ "Create", "a", "list", "of", "subtokens", "in", "decreasing", "order", "of", "frequency", "." ]
python
train
ElevenPaths/AtomShields
atomshields/scanner.py
https://github.com/ElevenPaths/AtomShields/blob/e75f25393b4a7a315ec96bf9b8e654cb2200866a/atomshields/scanner.py#L294-L309
def _addConfig(instance, config, parent_section): """ Writes a section for a plugin. Args: instance (object): Class instance for plugin config (object): Object (ConfigParser) which the current config parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports' """ try: section_name = "{p}/{n}".format(p = parent_section, n=instance.NAME.lower()) config.add_section(section_name) for k in instance.CONFIG.keys(): config.set(section_name, k, instance.CONFIG[k]) except Exception as e: print "[!] %s" % e
[ "def", "_addConfig", "(", "instance", ",", "config", ",", "parent_section", ")", ":", "try", ":", "section_name", "=", "\"{p}/{n}\"", ".", "format", "(", "p", "=", "parent_section", ",", "n", "=", "instance", ".", "NAME", ".", "lower", "(", ")", ")", "...
Writes a section for a plugin. Args: instance (object): Class instance for plugin config (object): Object (ConfigParser) which the current config parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports'
[ "Writes", "a", "section", "for", "a", "plugin", "." ]
python
valid
tomi77/django-extra-tools
django_extra_tools/db/__init__.py
https://github.com/tomi77/django-extra-tools/blob/fb6d226bc5cf3fc0eb8abe61a512c3f5c7dcc8a8/django_extra_tools/db/__init__.py#L12-L26
def pg_version(using=None): """ Return tuple with PostgreSQL version of a specific connection :type using: str :param using: Connection name :rtype: tuple :return: PostgreSQL version """ connection = get_connection(using) cursor = connection.cursor() cursor.execute('SHOW server_version') row = cursor.fetchone() return tuple([int(i) for i in row[0].split('.')])
[ "def", "pg_version", "(", "using", "=", "None", ")", ":", "connection", "=", "get_connection", "(", "using", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "'SHOW server_version'", ")", "row", "=", "cursor", ".", ...
Return tuple with PostgreSQL version of a specific connection :type using: str :param using: Connection name :rtype: tuple :return: PostgreSQL version
[ "Return", "tuple", "with", "PostgreSQL", "version", "of", "a", "specific", "connection", ":", "type", "using", ":", "str", ":", "param", "using", ":", "Connection", "name", ":", "rtype", ":", "tuple", ":", "return", ":", "PostgreSQL", "version" ]
python
train
ioam/lancet
lancet/core.py
https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/core.py#L812-L840
def _decompose_pattern(self, pattern): """ Given a path pattern with format declaration, generates a four-tuple (glob_pattern, regexp pattern, fields, type map) """ sep = '~lancet~sep~' float_codes = ['e','E','f', 'F','g', 'G', 'n'] typecodes = dict([(k,float) for k in float_codes] + [('b',bin), ('d',int), ('o',oct), ('x',hex)]) parse = list(string.Formatter().parse(pattern)) text, fields, codes, _ = zip(*parse) # Finding the field types from format string types = [] for (field, code) in zip(fields, codes): if code in ['', None]: continue constructor = typecodes.get(code[-1], None) if constructor: types += [(field, constructor)] stars = ['' if not f else '*' for f in fields] globpat = ''.join(text+star for (text,star) in zip(text,stars)) refields = ['' if not f else sep+('(?P<%s>.*?)'% f)+sep for f in fields] parts = ''.join(text+group for (text,group) in zip(text, refields)).split(sep) for i in range(0, len(parts), 2): parts[i] = re.escape(parts[i]) regexp_pattern = ''.join(parts).replace('\\*','.*') fields = list(f for f in fields if f) return globpat, regexp_pattern , fields, dict(types)
[ "def", "_decompose_pattern", "(", "self", ",", "pattern", ")", ":", "sep", "=", "'~lancet~sep~'", "float_codes", "=", "[", "'e'", ",", "'E'", ",", "'f'", ",", "'F'", ",", "'g'", ",", "'G'", ",", "'n'", "]", "typecodes", "=", "dict", "(", "[", "(", ...
Given a path pattern with format declaration, generates a four-tuple (glob_pattern, regexp pattern, fields, type map)
[ "Given", "a", "path", "pattern", "with", "format", "declaration", "generates", "a", "four", "-", "tuple", "(", "glob_pattern", "regexp", "pattern", "fields", "type", "map", ")" ]
python
valid
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L20926-L20950
def seek(self, offset, whence): """Changes the current file position of this file. The file current position always applies to the :py:func:`IFile.read` method. Same for the :py:func:`IFile.write` method it except when the :py:func:`IFile.access_mode` is :py:attr:`FileAccessMode.append_only` or :py:attr:`FileAccessMode.append_read` . in offset of type int Offset to seek relative to the position specified by @a whence. in whence of type :class:`FileSeekOrigin` One of the :py:class:`FileSeekOrigin` seek starting points. return new_offset of type int The new file offset after the seek operation. """ if not isinstance(offset, baseinteger): raise TypeError("offset can only be an instance of type baseinteger") if not isinstance(whence, FileSeekOrigin): raise TypeError("whence can only be an instance of type FileSeekOrigin") new_offset = self._call("seek", in_p=[offset, whence]) return new_offset
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", ")", ":", "if", "not", "isinstance", "(", "offset", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"offset can only be an instance of type baseinteger\"", ")", "if", "not", "isinstance", "(", ...
Changes the current file position of this file. The file current position always applies to the :py:func:`IFile.read` method. Same for the :py:func:`IFile.write` method it except when the :py:func:`IFile.access_mode` is :py:attr:`FileAccessMode.append_only` or :py:attr:`FileAccessMode.append_read` . in offset of type int Offset to seek relative to the position specified by @a whence. in whence of type :class:`FileSeekOrigin` One of the :py:class:`FileSeekOrigin` seek starting points. return new_offset of type int The new file offset after the seek operation.
[ "Changes", "the", "current", "file", "position", "of", "this", "file", ".", "The", "file", "current", "position", "always", "applies", "to", "the", ":", "py", ":", "func", ":", "IFile", ".", "read", "method", ".", "Same", "for", "the", ":", "py", ":", ...
python
train
Pytwitcher/pytwitcherapi
src/pytwitcherapi/chat/client.py
https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/client.py#L68-L77
def shutdown(self): """Disconnect all connections and end the loop :returns: None :rtype: None :raises: None """ log.debug('Shutting down %s' % self) self.disconnect_all() self._looping.clear()
[ "def", "shutdown", "(", "self", ")", ":", "log", ".", "debug", "(", "'Shutting down %s'", "%", "self", ")", "self", ".", "disconnect_all", "(", ")", "self", ".", "_looping", ".", "clear", "(", ")" ]
Disconnect all connections and end the loop :returns: None :rtype: None :raises: None
[ "Disconnect", "all", "connections", "and", "end", "the", "loop" ]
python
train
tutorcruncher/pydf
pydf/wkhtmltopdf.py
https://github.com/tutorcruncher/pydf/blob/53dd030f02f112593ed6e2655160a40b892a23c0/pydf/wkhtmltopdf.py#L160-L171
def get_version(): """ Get version of pydf and wkhtmltopdf binary :return: version string """ try: wk_version = _string_execute('-V') except Exception as e: # we catch all errors here to make sure we get a version no matter what wk_version = '%s: %s' % (e.__class__.__name__, e) return 'pydf version: %s\nwkhtmltopdf version: %s' % (VERSION, wk_version)
[ "def", "get_version", "(", ")", ":", "try", ":", "wk_version", "=", "_string_execute", "(", "'-V'", ")", "except", "Exception", "as", "e", ":", "# we catch all errors here to make sure we get a version no matter what", "wk_version", "=", "'%s: %s'", "%", "(", "e", "...
Get version of pydf and wkhtmltopdf binary :return: version string
[ "Get", "version", "of", "pydf", "and", "wkhtmltopdf", "binary" ]
python
train
Erotemic/utool
utool/util_alg.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_alg.py#L1365-L1382
def number_of_decimals(num): r""" Args: num (float): References: stackoverflow.com/questions/6189956/finding-decimal-places Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> num = 15.05 >>> result = number_of_decimals(num) >>> print(result) 2 """ exp = decimal.Decimal(str(num)).as_tuple().exponent return max(0, -exp)
[ "def", "number_of_decimals", "(", "num", ")", ":", "exp", "=", "decimal", ".", "Decimal", "(", "str", "(", "num", ")", ")", ".", "as_tuple", "(", ")", ".", "exponent", "return", "max", "(", "0", ",", "-", "exp", ")" ]
r""" Args: num (float): References: stackoverflow.com/questions/6189956/finding-decimal-places Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> num = 15.05 >>> result = number_of_decimals(num) >>> print(result) 2
[ "r", "Args", ":", "num", "(", "float", ")", ":" ]
python
train
pachyderm/python-pachyderm
src/python_pachyderm/pfs_client.py
https://github.com/pachyderm/python-pachyderm/blob/1c58cf91d30e03716a4f45213989e890f7b8a78c/src/python_pachyderm/pfs_client.py#L434-L444
def inspect_file(self, commit, path): """ Returns info about a specific file. Params: * commit: A tuple, string, or Commit object representing the commit. * path: Path to file. """ req = proto.InspectFileRequest(file=proto.File(commit=commit_from(commit), path=path)) res = self.stub.InspectFile(req, metadata=self.metadata) return res
[ "def", "inspect_file", "(", "self", ",", "commit", ",", "path", ")", ":", "req", "=", "proto", ".", "InspectFileRequest", "(", "file", "=", "proto", ".", "File", "(", "commit", "=", "commit_from", "(", "commit", ")", ",", "path", "=", "path", ")", ")...
Returns info about a specific file. Params: * commit: A tuple, string, or Commit object representing the commit. * path: Path to file.
[ "Returns", "info", "about", "a", "specific", "file", "." ]
python
train
WebarchivCZ/WA-KAT
src/wa_kat/templates/static/js/Lib/site-packages/components/conspect_handler.py
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/templates/static/js/Lib/site-packages/components/conspect_handler.py#L227-L237
def init(cls): """ Bind elements to callbacks. """ for el in cls.switcher_els: el.checked = False cls.bind_switcher() cls._draw_conspects() cls._create_searchable_typeahead()
[ "def", "init", "(", "cls", ")", ":", "for", "el", "in", "cls", ".", "switcher_els", ":", "el", ".", "checked", "=", "False", "cls", ".", "bind_switcher", "(", ")", "cls", ".", "_draw_conspects", "(", ")", "cls", ".", "_create_searchable_typeahead", "(", ...
Bind elements to callbacks.
[ "Bind", "elements", "to", "callbacks", "." ]
python
train
maweigert/gputools
gputools/transforms/transformations.py
https://github.com/maweigert/gputools/blob/6ab26efeb05dceef74cf13aadeeeb9b009b529dd/gputools/transforms/transformations.py#L88-L125
def shift(data, shift=(0, 0, 0), mode="constant", interpolation="linear"): """ translates 3d data by given amount Parameters ---------- data: ndarray 3d array shift : float or sequence The shift along the axes. If a float, `shift` is the same for each axis. If a sequence, `shift` should contain one value for each axis. mode: string boundary mode, one of the following: 'constant' pads with zeros 'edge' pads with edge values 'wrap' pads with the repeated version of the input interpolation, string interpolation mode, one of the following 'linear' 'nearest' Returns ------- res: ndarray shifted array (same shape as input) """ if np.isscalar(shift): shift = (shift,) * 3 if len(shift) != 3: raise ValueError("shift (%s) should be of length 3!") shift = -np.array(shift) return affine(data, mat4_translate(*shift), mode=mode, interpolation=interpolation)
[ "def", "shift", "(", "data", ",", "shift", "=", "(", "0", ",", "0", ",", "0", ")", ",", "mode", "=", "\"constant\"", ",", "interpolation", "=", "\"linear\"", ")", ":", "if", "np", ".", "isscalar", "(", "shift", ")", ":", "shift", "=", "(", "shift...
translates 3d data by given amount Parameters ---------- data: ndarray 3d array shift : float or sequence The shift along the axes. If a float, `shift` is the same for each axis. If a sequence, `shift` should contain one value for each axis. mode: string boundary mode, one of the following: 'constant' pads with zeros 'edge' pads with edge values 'wrap' pads with the repeated version of the input interpolation, string interpolation mode, one of the following 'linear' 'nearest' Returns ------- res: ndarray shifted array (same shape as input)
[ "translates", "3d", "data", "by", "given", "amount", "Parameters", "----------", "data", ":", "ndarray", "3d", "array", "shift", ":", "float", "or", "sequence", "The", "shift", "along", "the", "axes", ".", "If", "a", "float", "shift", "is", "the", "same", ...
python
train
lepture/otpauth
otpauth.py
https://github.com/lepture/otpauth/blob/49914d83d36dbcd33c9e26f65002b21ce09a6303/otpauth.py#L105-L131
def to_uri(self, type, label, issuer, counter=None): """Generate the otpauth protocal string. :param type: Algorithm type, hotp or totp. :param label: Label of the identifier. :param issuer: The company, the organization or something else. :param counter: Counter of the HOTP algorithm. """ type = type.lower() if type not in ('hotp', 'totp'): raise ValueError('type must be hotp or totp') if type == 'hotp' and not counter: raise ValueError('HOTP type authentication need counter') # https://code.google.com/p/google-authenticator/wiki/KeyUriFormat url = ('otpauth://%(type)s/%(label)s?secret=%(secret)s' '&issuer=%(issuer)s') dct = dict( type=type, label=label, issuer=issuer, secret=self.encoded_secret, counter=counter ) ret = url % dct if type == 'hotp': ret = '%s&counter=%s' % (ret, counter) return ret
[ "def", "to_uri", "(", "self", ",", "type", ",", "label", ",", "issuer", ",", "counter", "=", "None", ")", ":", "type", "=", "type", ".", "lower", "(", ")", "if", "type", "not", "in", "(", "'hotp'", ",", "'totp'", ")", ":", "raise", "ValueError", ...
Generate the otpauth protocal string. :param type: Algorithm type, hotp or totp. :param label: Label of the identifier. :param issuer: The company, the organization or something else. :param counter: Counter of the HOTP algorithm.
[ "Generate", "the", "otpauth", "protocal", "string", "." ]
python
train
Neurita/boyle
boyle/nifti/sets.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/sets.py#L274-L317
def to_file(self, output_file, smooth_fwhm=0, outdtype=None): """Save the Numpy array created from to_matrix function to the output_file. Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want) data: Numpy array with shape N x prod(vol.shape) containing the N files as flat vectors. mask_indices: matrix with indices of the voxels in the mask vol_shape: Tuple with shape of the volumes, for reshaping. Parameters ---------- output_file: str Path to the output file. The extension of the file will be taken into account for the file format. Choices of extensions: '.pyshelf' or '.shelf' (Python shelve) '.mat' (Matlab archive), '.hdf5' or '.h5' (HDF5 file) smooth_fwhm: int Integer indicating the size of the FWHM Gaussian smoothing kernel to smooth the subject volumes before creating the data matrix outdtype: dtype Type of the elements of the array, if None will obtain the dtype from the first nifti file. """ outmat, mask_indices, mask_shape = self.to_matrix(smooth_fwhm, outdtype) exporter = ExportData() content = {'data': outmat, 'labels': self.labels, 'mask_indices': mask_indices, 'mask_shape': mask_shape, } if self.others: content.update(self.others) log.debug('Creating content in file {}.'.format(output_file)) try: exporter.save_variables(output_file, content) except Exception as exc: raise Exception('Error saving variables to file {}.'.format(output_file)) from exc
[ "def", "to_file", "(", "self", ",", "output_file", ",", "smooth_fwhm", "=", "0", ",", "outdtype", "=", "None", ")", ":", "outmat", ",", "mask_indices", ",", "mask_shape", "=", "self", ".", "to_matrix", "(", "smooth_fwhm", ",", "outdtype", ")", "exporter", ...
Save the Numpy array created from to_matrix function to the output_file. Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want) data: Numpy array with shape N x prod(vol.shape) containing the N files as flat vectors. mask_indices: matrix with indices of the voxels in the mask vol_shape: Tuple with shape of the volumes, for reshaping. Parameters ---------- output_file: str Path to the output file. The extension of the file will be taken into account for the file format. Choices of extensions: '.pyshelf' or '.shelf' (Python shelve) '.mat' (Matlab archive), '.hdf5' or '.h5' (HDF5 file) smooth_fwhm: int Integer indicating the size of the FWHM Gaussian smoothing kernel to smooth the subject volumes before creating the data matrix outdtype: dtype Type of the elements of the array, if None will obtain the dtype from the first nifti file.
[ "Save", "the", "Numpy", "array", "created", "from", "to_matrix", "function", "to", "the", "output_file", "." ]
python
valid
noahbenson/neuropythy
neuropythy/util/core.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/util/core.py#L275-L295
def to_dataframe(d, **kw): ''' to_dataframe(d) attempts to coerce the object d to a pandas DataFrame object. If d is a tuple of 2 items whose second argument is a dictionary, then the dictionary will be taken as arguments for the dataframe constructor. These arguments may alternately be given as standard keyword arguments. ''' import pandas if pimms.is_itable(d): d = d.dataframe if is_dataframe(d): return d if len(kw) == 0 else pandas.DataFrame(d, **kw) if is_tuple(d) and len(d) == 2 and pimms.is_map(d[1]): try: return to_dataframe(d[0], **pimms.merge(d[1], kw)) except Exception: pass # try various options: try: return pandas.DataFrame(d, **kw) except Exception: pass try: return pandas.DataFrame.from_records(d, **kw) except Exception: pass try: return pandas.DataFrame.from_dict(d, **kw) except Exception: pass raise ValueError('Coersion to dataframe failed for object %s' % d)
[ "def", "to_dataframe", "(", "d", ",", "*", "*", "kw", ")", ":", "import", "pandas", "if", "pimms", ".", "is_itable", "(", "d", ")", ":", "d", "=", "d", ".", "dataframe", "if", "is_dataframe", "(", "d", ")", ":", "return", "d", "if", "len", "(", ...
to_dataframe(d) attempts to coerce the object d to a pandas DataFrame object. If d is a tuple of 2 items whose second argument is a dictionary, then the dictionary will be taken as arguments for the dataframe constructor. These arguments may alternately be given as standard keyword arguments.
[ "to_dataframe", "(", "d", ")", "attempts", "to", "coerce", "the", "object", "d", "to", "a", "pandas", "DataFrame", "object", ".", "If", "d", "is", "a", "tuple", "of", "2", "items", "whose", "second", "argument", "is", "a", "dictionary", "then", "the", ...
python
train
lambdamusic/Ontospy
ontospy/extras/hacks/matcher.py
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/hacks/matcher.py#L156-L210
def main(): """ command line script """ print("Ontospy " + ontospy.VERSION) ontospy.get_or_create_home_repo() opts, args = parse_options() if len(args) < 2: printDebug("Please provide two arguments, or use -h for more options.") sys.exit(0) var = input("Match classes or properties? [c|p, c=default]:") if var == "c": class_or_prop = "classes" elif var == "p": class_or_prop = "properties" else: class_or_prop = "classes" print(class_or_prop) var = input("Degree of confidence? [1-10, 5=default]: ") try: confidence = int(var) if not (confidence <= 10 and confidence >= 1): confidence = 5 except: confidence = 5 print(confidence) confidence = confidence / (10 * 1.0) #transform in decimal sTime = time.time() # automatically name the file unless a name is provided with -o option if not opts.outputfile: try: opts.outputfile = "%s_%s_matching_%s.csv" % (os.path.splitext(args[0])[0].split("/")[-1], os.path.splitext(args[1])[0].split("/")[-1], class_or_prop) except: opts.outputfile = "ontospy_matching_%s.csv" % (class_or_prop) g1 = ontospy.Ontospy(args[0]) g2 = ontospy.Ontospy(args[1]) matcher(g1, g2, confidence, opts.outputfile, class_or_prop, opts.verbose) # finally: # print(some stats....) eTime = time.time() tTime = eTime - sTime printDebug("-" * 10) printDebug("Time: %0.2fs" % tTime)
[ "def", "main", "(", ")", ":", "print", "(", "\"Ontospy \"", "+", "ontospy", ".", "VERSION", ")", "ontospy", ".", "get_or_create_home_repo", "(", ")", "opts", ",", "args", "=", "parse_options", "(", ")", "if", "len", "(", "args", ")", "<", "2", ":", "...
command line script
[ "command", "line", "script" ]
python
train