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
GoogleCloudPlatform/compute-image-packages
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L130-L149
def _AddUser(self, user): """Configure a Linux user account. Args: user: string, the name of the Linux user account to create. Returns: bool, True if user creation succeeded. """ self.logger.info('Creating a new user account for %s.', user) command = self.useradd_cmd.format(user=user) try: subprocess.check_call(command.split(' ')) except subprocess.CalledProcessError as e: self.logger.warning('Could not create user %s. %s.', user, str(e)) return False else: self.logger.info('Created user account %s.', user) return True
[ "def", "_AddUser", "(", "self", ",", "user", ")", ":", "self", ".", "logger", ".", "info", "(", "'Creating a new user account for %s.'", ",", "user", ")", "command", "=", "self", ".", "useradd_cmd", ".", "format", "(", "user", "=", "user", ")", "try", ":...
Configure a Linux user account. Args: user: string, the name of the Linux user account to create. Returns: bool, True if user creation succeeded.
[ "Configure", "a", "Linux", "user", "account", "." ]
python
train
fishtown-analytics/dbt
core/dbt/api/object.py
https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/core/dbt/api/object.py#L76-L92
def validate(self): """ Using the SCHEMA property, validate the attributes of this instance. If any attributes are missing or invalid, raise a ValidationException. """ validator = Draft7Validator(self.SCHEMA) errors = set() # make errors a set to avoid duplicates for error in validator.iter_errors(self.serialize()): errors.add('.'.join( list(map(str, error.path)) + [error.message] )) if errors: raise JSONValidationException(type(self).__name__, errors)
[ "def", "validate", "(", "self", ")", ":", "validator", "=", "Draft7Validator", "(", "self", ".", "SCHEMA", ")", "errors", "=", "set", "(", ")", "# make errors a set to avoid duplicates", "for", "error", "in", "validator", ".", "iter_errors", "(", "self", ".", ...
Using the SCHEMA property, validate the attributes of this instance. If any attributes are missing or invalid, raise a ValidationException.
[ "Using", "the", "SCHEMA", "property", "validate", "the", "attributes", "of", "this", "instance", ".", "If", "any", "attributes", "are", "missing", "or", "invalid", "raise", "a", "ValidationException", "." ]
python
train
ereOn/azmq
azmq/crypto.py
https://github.com/ereOn/azmq/blob/9f40d6d721eea7f7659ec6cc668811976db59854/azmq/crypto.py#L68-L79
def requires_libsodium(func): """ Mark a function as requiring libsodium. If no libsodium support is detected, a `RuntimeError` is thrown. """ @wraps(func) def wrapper(*args, **kwargs): libsodium_check() return func(*args, **kwargs) return wrapper
[ "def", "requires_libsodium", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "libsodium_check", "(", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")"...
Mark a function as requiring libsodium. If no libsodium support is detected, a `RuntimeError` is thrown.
[ "Mark", "a", "function", "as", "requiring", "libsodium", "." ]
python
train
coleifer/irc
irc.py
https://github.com/coleifer/irc/blob/f9d2bd6369aafe6cb0916c9406270ca8ecea2080/irc.py#L246-L270
def enter_event_loop(self): """\ Main loop of the IRCConnection - reads from the socket and dispatches based on regex matching """ patterns = self.dispatch_patterns() self.logger.debug('entering receive loop') while 1: try: data = self._sock_file.readline() except socket.error: data = None if not data: self.logger.info('server closed connection') self.close() return True data = data.rstrip() for pattern, callback in patterns: match = pattern.match(data) if match: callback(**match.groupdict())
[ "def", "enter_event_loop", "(", "self", ")", ":", "patterns", "=", "self", ".", "dispatch_patterns", "(", ")", "self", ".", "logger", ".", "debug", "(", "'entering receive loop'", ")", "while", "1", ":", "try", ":", "data", "=", "self", ".", "_sock_file", ...
\ Main loop of the IRCConnection - reads from the socket and dispatches based on regex matching
[ "\\", "Main", "loop", "of", "the", "IRCConnection", "-", "reads", "from", "the", "socket", "and", "dispatches", "based", "on", "regex", "matching" ]
python
test
sixty-north/cosmic-ray
src/cosmic_ray/operators/comparison_operator_replacement.py
https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/operators/comparison_operator_replacement.py#L97-L105
def _allowed(to_op, from_op, rhs): "Determine if a mutation from `from_op` to `to_op` is allowed given a particular `rhs` node." if is_none(rhs): return to_op in _RHS_IS_NONE_OPS.get(from_op, ()) if is_number(rhs): return to_op in _RHS_IS_INTEGER_OPS return True
[ "def", "_allowed", "(", "to_op", ",", "from_op", ",", "rhs", ")", ":", "if", "is_none", "(", "rhs", ")", ":", "return", "to_op", "in", "_RHS_IS_NONE_OPS", ".", "get", "(", "from_op", ",", "(", ")", ")", "if", "is_number", "(", "rhs", ")", ":", "ret...
Determine if a mutation from `from_op` to `to_op` is allowed given a particular `rhs` node.
[ "Determine", "if", "a", "mutation", "from", "from_op", "to", "to_op", "is", "allowed", "given", "a", "particular", "rhs", "node", "." ]
python
train
sys-git/certifiable
certifiable/utils.py
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/utils.py#L33-L65
def make_certifier(): """ Decorator that can wrap raw functions to create a certifier function. Certifier functions support partial application. If a function wrapped by `make_certifier` is called with a value as its first argument it will be certified immediately. If no value is passed, then it will return a function that can be called at a later time. Assuming that `certify_something` has been decorated by `make_certifier`: >>> certify_something(value, foo=1, bar=2) Is equivalent to: >>> certifier = certify_something(foo=1, bar=2) >>> certifier(value) """ def decorator(func): @six.wraps(func) def wrapper(value=_undefined, **kwargs): def certify(val): if is_enabled(): exec_func(func, val, **kwargs) return val if value is not _undefined: return certify(value) else: return certify return wrapper return decorator
[ "def", "make_certifier", "(", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "six", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "value", "=", "_undefined", ",", "*", "*", "kwargs", ")", ":", "def", "certify", "(", "val", ")", ...
Decorator that can wrap raw functions to create a certifier function. Certifier functions support partial application. If a function wrapped by `make_certifier` is called with a value as its first argument it will be certified immediately. If no value is passed, then it will return a function that can be called at a later time. Assuming that `certify_something` has been decorated by `make_certifier`: >>> certify_something(value, foo=1, bar=2) Is equivalent to: >>> certifier = certify_something(foo=1, bar=2) >>> certifier(value)
[ "Decorator", "that", "can", "wrap", "raw", "functions", "to", "create", "a", "certifier", "function", "." ]
python
train
edx/edx-lint
edx_lint/pylint/common.py
https://github.com/edx/edx-lint/blob/d87ccb51a48984806b6442a36992c5b45c3d4d58/edx_lint/pylint/common.py#L25-L31
def usable_class_name(node): """Make a reasonable class name for a class node.""" name = node.qname() for prefix in ["__builtin__.", "builtins.", "."]: if name.startswith(prefix): name = name[len(prefix):] return name
[ "def", "usable_class_name", "(", "node", ")", ":", "name", "=", "node", ".", "qname", "(", ")", "for", "prefix", "in", "[", "\"__builtin__.\"", ",", "\"builtins.\"", ",", "\".\"", "]", ":", "if", "name", ".", "startswith", "(", "prefix", ")", ":", "nam...
Make a reasonable class name for a class node.
[ "Make", "a", "reasonable", "class", "name", "for", "a", "class", "node", "." ]
python
valid
relekang/python-semantic-release
semantic_release/settings.py
https://github.com/relekang/python-semantic-release/blob/76123f410180599a19e7c48da413880185bbea20/semantic_release/settings.py#L24-L35
def current_commit_parser() -> Callable: """Current commit parser :raises ImproperConfigurationError: if ImportError or AttributeError is raised """ try: parts = config.get('semantic_release', 'commit_parser').split('.') module = '.'.join(parts[:-1]) return getattr(importlib.import_module(module), parts[-1]) except (ImportError, AttributeError) as error: raise ImproperConfigurationError('Unable to import parser "{}"'.format(error))
[ "def", "current_commit_parser", "(", ")", "->", "Callable", ":", "try", ":", "parts", "=", "config", ".", "get", "(", "'semantic_release'", ",", "'commit_parser'", ")", ".", "split", "(", "'.'", ")", "module", "=", "'.'", ".", "join", "(", "parts", "[", ...
Current commit parser :raises ImproperConfigurationError: if ImportError or AttributeError is raised
[ "Current", "commit", "parser" ]
python
train
xtuml/pyxtuml
bridgepoint/ooaofooa.py
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/bridgepoint/ooaofooa.py#L506-L519
def filename_input(self, path_or_filename): ''' Open and read input from a *path or filename*, and parse its content. If the filename is a directory, files that ends with .xtuml located somewhere in the directory or sub directories will be loaded as well. ''' if os.path.isdir(path_or_filename): for path, _, files in os.walk(path_or_filename): for name in files: if name.endswith('.xtuml'): xtuml.ModelLoader.filename_input(self, os.path.join(path, name)) else: xtuml.ModelLoader.filename_input(self, path_or_filename)
[ "def", "filename_input", "(", "self", ",", "path_or_filename", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path_or_filename", ")", ":", "for", "path", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "path_or_filename", ")", ":", "for",...
Open and read input from a *path or filename*, and parse its content. If the filename is a directory, files that ends with .xtuml located somewhere in the directory or sub directories will be loaded as well.
[ "Open", "and", "read", "input", "from", "a", "*", "path", "or", "filename", "*", "and", "parse", "its", "content", ".", "If", "the", "filename", "is", "a", "directory", "files", "that", "ends", "with", ".", "xtuml", "located", "somewhere", "in", "the", ...
python
test
geophysics-ubonn/reda
lib/reda/plotters/plots2d.py
https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/plots2d.py#L72-L227
def plot_pseudodepths(configs, nr_electrodes, spacing=1, grid=None, ctypes=None, dd_merge=False, **kwargs): """Plot pseudodepths for the measurements. If grid is given, then the actual electrode positions are used, and the parameter 'spacing' is ignored' Parameters ---------- configs: :class:`numpy.ndarray` Nx4 array containing the quadrupoles for different measurements nr_electrodes: int The overall number of electrodes of the dataset. This is used to plot the surface electrodes spacing: float, optional assumed distance between electrodes. Default=1 grid: crtomo.grid.crt_grid instance, optional grid instance. Used to infer real electrode positions ctypes: list of strings, optional a list of configuration types that will be plotted. All configurations that can not be sorted into these types will not be plotted! Possible types: * dd * schlumberger dd_merge: bool, optional if True, merge all skips. Otherwise, generate individual plots for each skip Returns ------- figs: matplotlib.figure.Figure instance or list of Figure instances if only one type was plotted, then the figure instance is returned. Otherwise, return a list of figure instances. axes: axes object or list of axes ojects plot axes Examples -------- .. plot:: :include-source: from reda.plotters.plots2d import plot_pseudodepths # define a few measurements import numpy as np configs = np.array(( (1, 2, 4, 3), (1, 2, 5, 4), (1, 2, 6, 5), (2, 3, 5, 4), (2, 3, 6, 5), (3, 4, 6, 5), )) # plot fig, axes = plot_pseudodepths(configs, nr_electrodes=6, spacing=1, ctypes=['dd', ]) .. plot:: :include-source: from reda.plotters.plots2d import plot_pseudodepths # define a few measurements import numpy as np configs = np.array(( (4, 7, 5, 6), (3, 8, 5, 6), (2, 9, 5, 6), (1, 10, 5, 6), )) # plot fig, axes = plot_pseudodepths(configs, nr_electrodes=10, spacing=1, ctypes=['schlumberger', ]) """ # for each configuration type we have different ways of computing # pseudodepths pseudo_d_functions = { 'dd': _pseudodepths_dd_simple, 'schlumberger': _pseudodepths_schlumberger, 'wenner': _pseudodepths_wenner, } titles = { 'dd': 'dipole-dipole configurations', 'schlumberger': 'Schlumberger configurations', 'wenner': 'Wenner configurations', } # sort the configurations into the various types of configurations only_types = ctypes or ['dd', ] results = fT.filter(configs, settings={'only_types': only_types, }) # loop through all measurement types figs = [] axes = [] for key in sorted(results.keys()): print('plotting: ', key) if key == 'not_sorted': continue index_dict = results[key] # it is possible that we want to generate multiple plots for one # type of measurement, i.e., to separate skips of dipole-dipole # measurements. Therefore we generate two lists: # 1) list of list of indices to plot # 2) corresponding labels if key == 'dd' and not dd_merge: plot_list = [] labels_add = [] for skip in sorted(index_dict.keys()): plot_list.append(index_dict[skip]) labels_add.append(' - skip {0}'.format(skip)) else: # merge all indices plot_list = [np.hstack(index_dict.values()), ] print('schlumberger', plot_list) labels_add = ['', ] grid = None # generate plots for indices, label_add in zip(plot_list, labels_add): if len(indices) == 0: continue ddc = configs[indices] px, pz = pseudo_d_functions[key](ddc, spacing, grid) fig, ax = plt.subplots(figsize=(15 / 2.54, 5 / 2.54)) ax.scatter(px, pz, color='k', alpha=0.5) # plot electrodes if grid is not None: electrodes = grid.get_electrode_positions() ax.scatter( electrodes[:, 0], electrodes[:, 1], color='b', label='electrodes', ) else: ax.scatter( np.arange(0, nr_electrodes) * spacing, np.zeros(nr_electrodes), color='b', label='electrodes', ) ax.set_title(titles[key] + label_add) ax.set_aspect('equal') ax.set_xlabel('x [m]') ax.set_ylabel('x [z]') fig.tight_layout() figs.append(fig) axes.append(ax) if len(figs) == 1: return figs[0], axes[0] else: return figs, axes
[ "def", "plot_pseudodepths", "(", "configs", ",", "nr_electrodes", ",", "spacing", "=", "1", ",", "grid", "=", "None", ",", "ctypes", "=", "None", ",", "dd_merge", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# for each configuration type we have different...
Plot pseudodepths for the measurements. If grid is given, then the actual electrode positions are used, and the parameter 'spacing' is ignored' Parameters ---------- configs: :class:`numpy.ndarray` Nx4 array containing the quadrupoles for different measurements nr_electrodes: int The overall number of electrodes of the dataset. This is used to plot the surface electrodes spacing: float, optional assumed distance between electrodes. Default=1 grid: crtomo.grid.crt_grid instance, optional grid instance. Used to infer real electrode positions ctypes: list of strings, optional a list of configuration types that will be plotted. All configurations that can not be sorted into these types will not be plotted! Possible types: * dd * schlumberger dd_merge: bool, optional if True, merge all skips. Otherwise, generate individual plots for each skip Returns ------- figs: matplotlib.figure.Figure instance or list of Figure instances if only one type was plotted, then the figure instance is returned. Otherwise, return a list of figure instances. axes: axes object or list of axes ojects plot axes Examples -------- .. plot:: :include-source: from reda.plotters.plots2d import plot_pseudodepths # define a few measurements import numpy as np configs = np.array(( (1, 2, 4, 3), (1, 2, 5, 4), (1, 2, 6, 5), (2, 3, 5, 4), (2, 3, 6, 5), (3, 4, 6, 5), )) # plot fig, axes = plot_pseudodepths(configs, nr_electrodes=6, spacing=1, ctypes=['dd', ]) .. plot:: :include-source: from reda.plotters.plots2d import plot_pseudodepths # define a few measurements import numpy as np configs = np.array(( (4, 7, 5, 6), (3, 8, 5, 6), (2, 9, 5, 6), (1, 10, 5, 6), )) # plot fig, axes = plot_pseudodepths(configs, nr_electrodes=10, spacing=1, ctypes=['schlumberger', ])
[ "Plot", "pseudodepths", "for", "the", "measurements", ".", "If", "grid", "is", "given", "then", "the", "actual", "electrode", "positions", "are", "used", "and", "the", "parameter", "spacing", "is", "ignored" ]
python
train
NuGrid/NuGridPy
nugridpy/utils.py
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1075-L1088
def strictly_monotonic(bb): ''' bb is an index array which may have numerous double or triple occurrences of indices, such as for example the decay_index_pointer. This method removes all entries <= -, then all dublicates and finally returns a sorted list of indices. ''' cc=bb[np.where(bb>=0)] cc.sort() dc=cc[1:]-cc[:-1] # subsequent equal entries have 0 in db dc=np.insert(dc,0,1) # the first element is always unique (the second occurence is the dublicate) dc_mask=np.ma.masked_equal(dc,0) return np.ma.array(cc,mask=dc_mask.mask).compressed()
[ "def", "strictly_monotonic", "(", "bb", ")", ":", "cc", "=", "bb", "[", "np", ".", "where", "(", "bb", ">=", "0", ")", "]", "cc", ".", "sort", "(", ")", "dc", "=", "cc", "[", "1", ":", "]", "-", "cc", "[", ":", "-", "1", "]", "# subsequent ...
bb is an index array which may have numerous double or triple occurrences of indices, such as for example the decay_index_pointer. This method removes all entries <= -, then all dublicates and finally returns a sorted list of indices.
[ "bb", "is", "an", "index", "array", "which", "may", "have", "numerous", "double", "or", "triple", "occurrences", "of", "indices", "such", "as", "for", "example", "the", "decay_index_pointer", ".", "This", "method", "removes", "all", "entries", "<", "=", "-",...
python
train
googleapis/oauth2client
oauth2client/_pycrypto_crypt.py
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pycrypto_crypt.py#L53-L75
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. """ if is_x509_cert: key_pem = _helpers._to_bytes(key_pem) pemLines = key_pem.replace(b' ', b'').split() certDer = _helpers._urlsafe_b64decode(b''.join(pemLines[1:-1])) certSeq = DerSequence() certSeq.decode(certDer) tbsSeq = DerSequence() tbsSeq.decode(certSeq[0]) pubkey = RSA.importKey(tbsSeq[6]) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
[ "def", "from_string", "(", "key_pem", ",", "is_x509_cert", ")", ":", "if", "is_x509_cert", ":", "key_pem", "=", "_helpers", ".", "_to_bytes", "(", "key_pem", ")", "pemLines", "=", "key_pem", ".", "replace", "(", "b' '", ",", "b''", ")", ".", "split", "("...
Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance.
[ "Construct", "a", "Verified", "instance", "from", "a", "string", "." ]
python
valid
blockstack/blockstack-core
blockstack/lib/operations/transfer.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/transfer.py#L290-L361
def tx_extract( payload, senders, inputs, outputs, block_id, vtxindex, txid ): """ Extract and return a dict of fields from the underlying blockchain transaction data that are useful to this operation. Required: sender: the script_pubkey (as a hex string) of the principal that sent the transfer transaction address: the address from the sender script recipient: the script_pubkey (as a hex string) of the principal that is meant to receive the name recipient_address: the address from the recipient script Optional: sender_pubkey_hex: the public key of the sender """ sender = None sender_address = None sender_pubkey_hex = None recipient = None recipient_address = None try: # first two outputs matter to us (op_return, new recipient) assert check_tx_output_types(outputs[:2], block_id) recipient = get_transfer_recipient_from_outputs( outputs ) recipient_address = virtualchain.script_hex_to_address( recipient ) assert recipient is not None assert recipient_address is not None # by construction, the first input comes from the principal # who sent the registration transaction... assert len(senders) > 0 assert 'script_pubkey' in senders[0].keys() assert 'addresses' in senders[0].keys() sender = str(senders[0]['script_pubkey']) sender_address = str(senders[0]['addresses'][0]) assert sender is not None assert sender_address is not None if str(senders[0]['script_type']) == 'pubkeyhash': sender_pubkey_hex = get_public_key_hex_from_tx( inputs, sender_address ) except Exception, e: log.exception(e) raise Exception("Failed to extract") parsed_payload = parse( payload, recipient ) assert parsed_payload is not None ret = { "sender": sender, "address": sender_address, "recipient": recipient, "recipient_address": recipient_address, "vtxindex": vtxindex, "txid": txid, "op": NAME_TRANSFER } ret.update( parsed_payload ) if sender_pubkey_hex is not None: ret['sender_pubkey'] = sender_pubkey_hex else: ret['sender_pubkey'] = None return ret
[ "def", "tx_extract", "(", "payload", ",", "senders", ",", "inputs", ",", "outputs", ",", "block_id", ",", "vtxindex", ",", "txid", ")", ":", "sender", "=", "None", "sender_address", "=", "None", "sender_pubkey_hex", "=", "None", "recipient", "=", "None", "...
Extract and return a dict of fields from the underlying blockchain transaction data that are useful to this operation. Required: sender: the script_pubkey (as a hex string) of the principal that sent the transfer transaction address: the address from the sender script recipient: the script_pubkey (as a hex string) of the principal that is meant to receive the name recipient_address: the address from the recipient script Optional: sender_pubkey_hex: the public key of the sender
[ "Extract", "and", "return", "a", "dict", "of", "fields", "from", "the", "underlying", "blockchain", "transaction", "data", "that", "are", "useful", "to", "this", "operation", "." ]
python
train
dslackw/slpkg
slpkg/pkg/manager.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/pkg/manager.py#L68-L82
def upgrade(self, flag): """Upgrade Slackware binary packages with new """ for pkg in self.binary: try: subprocess.call("upgradepkg {0} {1}".format(flag, pkg), shell=True) check = pkg[:-4].split("/")[-1] if os.path.isfile(self.meta.pkg_path + check): print("Completed!\n") else: raise SystemExit() except subprocess.CalledProcessError: self._not_found("Can't upgrade", self.binary, pkg) raise SystemExit(1)
[ "def", "upgrade", "(", "self", ",", "flag", ")", ":", "for", "pkg", "in", "self", ".", "binary", ":", "try", ":", "subprocess", ".", "call", "(", "\"upgradepkg {0} {1}\"", ".", "format", "(", "flag", ",", "pkg", ")", ",", "shell", "=", "True", ")", ...
Upgrade Slackware binary packages with new
[ "Upgrade", "Slackware", "binary", "packages", "with", "new" ]
python
train
rocky/python-uncompyle6
uncompyle6/scanners/scanner2.py
https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/scanners/scanner2.py#L125-L131
def unmangle_name(name, classname): """Remove __ from the end of _name_ if it starts with __classname__ return the "unmangled" name. """ if name.startswith(classname) and name[-2:] != '__': return name[len(classname) - 2:] return name
[ "def", "unmangle_name", "(", "name", ",", "classname", ")", ":", "if", "name", ".", "startswith", "(", "classname", ")", "and", "name", "[", "-", "2", ":", "]", "!=", "'__'", ":", "return", "name", "[", "len", "(", "classname", ")", "-", "2", ":", ...
Remove __ from the end of _name_ if it starts with __classname__ return the "unmangled" name.
[ "Remove", "__", "from", "the", "end", "of", "_name_", "if", "it", "starts", "with", "__classname__", "return", "the", "unmangled", "name", "." ]
python
train
mikedh/trimesh
trimesh/transformations.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/transformations.py#L1693-L1703
def arcball_nearest_axis(point, axes): """Return axis, which arc is nearest to point.""" point = np.array(point, dtype=np.float64, copy=False) nearest = None mx = -1.0 for axis in axes: t = np.dot(arcball_constrain_to_axis(point, axis), point) if t > mx: nearest = axis mx = t return nearest
[ "def", "arcball_nearest_axis", "(", "point", ",", "axes", ")", ":", "point", "=", "np", ".", "array", "(", "point", ",", "dtype", "=", "np", ".", "float64", ",", "copy", "=", "False", ")", "nearest", "=", "None", "mx", "=", "-", "1.0", "for", "axis...
Return axis, which arc is nearest to point.
[ "Return", "axis", "which", "arc", "is", "nearest", "to", "point", "." ]
python
train
oscarbranson/latools
latools/filtering/signal_optimiser.py
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/filtering/signal_optimiser.py#L75-L85
def median_scaler(s): """ Remove median, divide by IQR. """ if sum(~np.isnan(s)) > 2: ss = s[~np.isnan(s)] median = np.median(ss) IQR = np.diff(np.percentile(ss, [25, 75])) return (s - median) / IQR else: return np.full(s.shape, np.nan)
[ "def", "median_scaler", "(", "s", ")", ":", "if", "sum", "(", "~", "np", ".", "isnan", "(", "s", ")", ")", ">", "2", ":", "ss", "=", "s", "[", "~", "np", ".", "isnan", "(", "s", ")", "]", "median", "=", "np", ".", "median", "(", "ss", ")"...
Remove median, divide by IQR.
[ "Remove", "median", "divide", "by", "IQR", "." ]
python
test
edeposit/edeposit.amqp.ftp
src/edeposit/amqp/ftp/passwd_reader.py
https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/passwd_reader.py#L115-L133
def set_permissions(filename, uid=None, gid=None, mode=0775): """ Set pemissions for given `filename`. Args: filename (str): name of the file/directory uid (int, default proftpd): user ID - if not set, user ID of `proftpd` is used gid (int): group ID, if not set, it is not changed mode (int, default 0775): unix access mode """ if uid is None: uid = get_ftp_uid() if gid is None: gid = -1 os.chown(filename, uid, gid) os.chmod(filename, mode)
[ "def", "set_permissions", "(", "filename", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "mode", "=", "0775", ")", ":", "if", "uid", "is", "None", ":", "uid", "=", "get_ftp_uid", "(", ")", "if", "gid", "is", "None", ":", "gid", "=", "-",...
Set pemissions for given `filename`. Args: filename (str): name of the file/directory uid (int, default proftpd): user ID - if not set, user ID of `proftpd` is used gid (int): group ID, if not set, it is not changed mode (int, default 0775): unix access mode
[ "Set", "pemissions", "for", "given", "filename", "." ]
python
train
ensime/ensime-vim
ensime_shared/client.py
https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L438-L445
def usages(self): """Request usages of whatever at cursor.""" row, col = self.editor.cursor() self.log.debug('usages: in') self.call_options[self.call_id] = { "word_under_cursor": self.editor.current_word(), "false_resp_msg": "Not a valid symbol under the cursor"} self.send_at_point("UsesOfSymbol", row, col)
[ "def", "usages", "(", "self", ")", ":", "row", ",", "col", "=", "self", ".", "editor", ".", "cursor", "(", ")", "self", ".", "log", ".", "debug", "(", "'usages: in'", ")", "self", ".", "call_options", "[", "self", ".", "call_id", "]", "=", "{", "...
Request usages of whatever at cursor.
[ "Request", "usages", "of", "whatever", "at", "cursor", "." ]
python
train
jldantas/libmft
libmft/attribute.py
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/attribute.py#L1451-L1462
def _get_next_empty_bitmap(self): """Returns the next empty entry. Returns: int: The value of the empty entry """ #TODO probably not the best way, redo for i, byte in enumerate(self._bitmap): if byte != 255: for offset in range(8): if not byte & (1 << offset): return (i * 8) + offset
[ "def", "_get_next_empty_bitmap", "(", "self", ")", ":", "#TODO probably not the best way, redo", "for", "i", ",", "byte", "in", "enumerate", "(", "self", ".", "_bitmap", ")", ":", "if", "byte", "!=", "255", ":", "for", "offset", "in", "range", "(", "8", ")...
Returns the next empty entry. Returns: int: The value of the empty entry
[ "Returns", "the", "next", "empty", "entry", "." ]
python
train
jangler/readlike
readlike.py
https://github.com/jangler/readlike/blob/2901260c50bd1aecfb981c3990e0c6333de8aac8/readlike.py#L126-L135
def _forward_word(text, pos): """ Move pos forward to the end of the next word. Words are composed of alphanumeric characters (letters and digits). """ while pos < len(text) and not text[pos].isalnum(): pos += 1 while pos < len(text) and text[pos].isalnum(): pos += 1 return text, pos
[ "def", "_forward_word", "(", "text", ",", "pos", ")", ":", "while", "pos", "<", "len", "(", "text", ")", "and", "not", "text", "[", "pos", "]", ".", "isalnum", "(", ")", ":", "pos", "+=", "1", "while", "pos", "<", "len", "(", "text", ")", "and"...
Move pos forward to the end of the next word. Words are composed of alphanumeric characters (letters and digits).
[ "Move", "pos", "forward", "to", "the", "end", "of", "the", "next", "word", ".", "Words", "are", "composed", "of", "alphanumeric", "characters", "(", "letters", "and", "digits", ")", "." ]
python
train
janpipek/physt
physt/plotting/plotly.py
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/plotly.py#L173-L181
def map(h2: Histogram2D, **kwargs): """Heatmap. """ data = [go.Heatmap(z=h2.frequencies, **kwargs)] layout = go.Layout() figure = go.Figure(data=data, layout=layout) return figure
[ "def", "map", "(", "h2", ":", "Histogram2D", ",", "*", "*", "kwargs", ")", ":", "data", "=", "[", "go", ".", "Heatmap", "(", "z", "=", "h2", ".", "frequencies", ",", "*", "*", "kwargs", ")", "]", "layout", "=", "go", ".", "Layout", "(", ")", ...
Heatmap.
[ "Heatmap", "." ]
python
train
coin-or/GiMPy
src/gimpy/graph.py
https://github.com/coin-or/GiMPy/blob/51853122a50eb6019d06bbdedbfc396a833b5a22/src/gimpy/graph.py#L2959-L2999
def simplex_identify_cycle(self, t, k, l): ''' API: identify_cycle(self, t, k, l) Description: Identifies and returns to the pivot cycle, which is a list of nodes. Pre: (1) t is spanning tree solution, (k,l) is the entering arc. Input: t: current spanning tree solution k: tail of the entering arc l: head of the entering arc Returns: List of nodes in the cycle. ''' i = k j = l cycle = [] li = [k] lj = [j] while i is not j: depth_i = t.get_node(i).get_attr('depth') depth_j = t.get_node(j).get_attr('depth') if depth_i > depth_j: i = t.get_node(i).get_attr('pred') li.append(i) elif depth_i < depth_j: j = t.get_node(j).get_attr('pred') lj.append(j) else: i = t.get_node(i).get_attr('pred') li.append(i) j = t.get_node(j).get_attr('pred') lj.append(j) cycle.extend(lj) li.pop() li.reverse() cycle.extend(li) # l is beginning k is end return cycle
[ "def", "simplex_identify_cycle", "(", "self", ",", "t", ",", "k", ",", "l", ")", ":", "i", "=", "k", "j", "=", "l", "cycle", "=", "[", "]", "li", "=", "[", "k", "]", "lj", "=", "[", "j", "]", "while", "i", "is", "not", "j", ":", "depth_i", ...
API: identify_cycle(self, t, k, l) Description: Identifies and returns to the pivot cycle, which is a list of nodes. Pre: (1) t is spanning tree solution, (k,l) is the entering arc. Input: t: current spanning tree solution k: tail of the entering arc l: head of the entering arc Returns: List of nodes in the cycle.
[ "API", ":", "identify_cycle", "(", "self", "t", "k", "l", ")", "Description", ":", "Identifies", "and", "returns", "to", "the", "pivot", "cycle", "which", "is", "a", "list", "of", "nodes", ".", "Pre", ":", "(", "1", ")", "t", "is", "spanning", "tree"...
python
train
gwpy/gwpy
gwpy/timeseries/core.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/timeseries/core.py#L721-L739
def to_lal(self): """Convert this `TimeSeries` into a LAL TimeSeries. """ import lal from ..utils.lal import (find_typed_function, to_lal_unit) # map unit try: unit = to_lal_unit(self.unit) except ValueError as e: warnings.warn("%s, defaulting to lal.DimensionlessUnit" % str(e)) unit = lal.DimensionlessUnit # create TimeSeries create = find_typed_function(self.dtype, 'Create', 'TimeSeries') lalts = create(self.name, lal.LIGOTimeGPS(self.epoch.gps), 0, self.dt.value, unit, self.shape[0]) lalts.data.data = self.value return lalts
[ "def", "to_lal", "(", "self", ")", ":", "import", "lal", "from", ".", ".", "utils", ".", "lal", "import", "(", "find_typed_function", ",", "to_lal_unit", ")", "# map unit", "try", ":", "unit", "=", "to_lal_unit", "(", "self", ".", "unit", ")", "except", ...
Convert this `TimeSeries` into a LAL TimeSeries.
[ "Convert", "this", "TimeSeries", "into", "a", "LAL", "TimeSeries", "." ]
python
train
stuaxo/vext
vext/gatekeeper/__init__.py
https://github.com/stuaxo/vext/blob/fa98a21ecfbbc1c3d1b84085d69ec42defdd2f69/vext/gatekeeper/__init__.py#L377-L406
def install_importer(): """ If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook. """ logging.debug('install_importer') if not in_venv(): logging.debug('No virtualenv active py:[%s]', sys.executable) return False if disable_vext: logging.debug('Vext disabled by environment variable') return False if GatekeeperFinder.PATH_TRIGGER not in sys.path: try: load_specs() sys.path.append(GatekeeperFinder.PATH_TRIGGER) sys.path_hooks.append(GatekeeperFinder) except Exception as e: """ Dont kill other programmes because of a vext error """ logger.info(str(e)) if logger.getEffectiveLevel() == logging.DEBUG: raise logging.debug("importer installed") return True
[ "def", "install_importer", "(", ")", ":", "logging", ".", "debug", "(", "'install_importer'", ")", "if", "not", "in_venv", "(", ")", ":", "logging", ".", "debug", "(", "'No virtualenv active py:[%s]'", ",", "sys", ".", "executable", ")", "return", "False", "...
If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook.
[ "If", "in", "a", "virtualenv", "then", "load", "spec", "files", "to", "decide", "which", "modules", "can", "be", "imported", "from", "system", "site", "-", "packages", "and", "install", "path", "hook", "." ]
python
train
numenta/htmresearch
htmresearch/support/expsuite.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/expsuite.py#L295-L307
def get_histories_fix_params(self, exp, rep, tag, **kwargs): """ this function uses get_history(..) but returns all histories where the subexperiments match the additional kwargs arguments. if alpha=1.0, beta = 0.01 is given, then only those experiment histories are returned, as a list. """ subexps = self.get_exps(exp) tagvalues = [re.sub("0+$", '0', '%s%f'%(k, kwargs[k])) for k in kwargs] histories = [self.get_history(se, rep, tag) for se in subexps if all(map(lambda tv: tv in se, tagvalues))] params = [self.get_params(se) for se in subexps if all(map(lambda tv: tv in se, tagvalues))] return histories, params
[ "def", "get_histories_fix_params", "(", "self", ",", "exp", ",", "rep", ",", "tag", ",", "*", "*", "kwargs", ")", ":", "subexps", "=", "self", ".", "get_exps", "(", "exp", ")", "tagvalues", "=", "[", "re", ".", "sub", "(", "\"0+$\"", ",", "'0'", ",...
this function uses get_history(..) but returns all histories where the subexperiments match the additional kwargs arguments. if alpha=1.0, beta = 0.01 is given, then only those experiment histories are returned, as a list.
[ "this", "function", "uses", "get_history", "(", "..", ")", "but", "returns", "all", "histories", "where", "the", "subexperiments", "match", "the", "additional", "kwargs", "arguments", ".", "if", "alpha", "=", "1", ".", "0", "beta", "=", "0", ".", "01", "...
python
train
GeorgeArgyros/symautomata
symautomata/pywrapfstdfa.py
https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/pywrapfstdfa.py#L322-L335
def complement(self, alphabet): """ Returns the complement of DFA Args: alphabet (list): The input alphabet Returns: None """ self._addsink(alphabet) for state in self.automaton.states(): if self.automaton.final(state) == fst.Weight.One(self.automaton.weight_type()): self.automaton.set_final(state, fst.Weight.Zero(self.automaton.weight_type())) else: self.automaton.set_final(state, fst.Weight.One(self.automaton.weight_type()))
[ "def", "complement", "(", "self", ",", "alphabet", ")", ":", "self", ".", "_addsink", "(", "alphabet", ")", "for", "state", "in", "self", ".", "automaton", ".", "states", "(", ")", ":", "if", "self", ".", "automaton", ".", "final", "(", "state", ")",...
Returns the complement of DFA Args: alphabet (list): The input alphabet Returns: None
[ "Returns", "the", "complement", "of", "DFA", "Args", ":", "alphabet", "(", "list", ")", ":", "The", "input", "alphabet", "Returns", ":", "None" ]
python
train
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7454-L7470
def xpathCompareValues(self, inf, strict): """Implement the compare operation on XPath objects: @arg1 < @arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 > @arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When neither object to be compared is a node-set and the operator is <=, <, >=, >, then the objects are compared by converted both objects to numbers and comparing the numbers according to IEEE 754. The < comparison will be true if and only if the first number is less than the second number. The <= comparison will be true if and only if the first number is less than or equal to the second number. The > comparison will be true if and only if the first number is greater than the second number. The >= comparison will be true if and only if the first number is greater than or equal to the second number. """ ret = libxml2mod.xmlXPathCompareValues(self._o, inf, strict) return ret
[ "def", "xpathCompareValues", "(", "self", ",", "inf", ",", "strict", ")", ":", "ret", "=", "libxml2mod", ".", "xmlXPathCompareValues", "(", "self", ".", "_o", ",", "inf", ",", "strict", ")", "return", "ret" ]
Implement the compare operation on XPath objects: @arg1 < @arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 > @arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When neither object to be compared is a node-set and the operator is <=, <, >=, >, then the objects are compared by converted both objects to numbers and comparing the numbers according to IEEE 754. The < comparison will be true if and only if the first number is less than the second number. The <= comparison will be true if and only if the first number is less than or equal to the second number. The > comparison will be true if and only if the first number is greater than the second number. The >= comparison will be true if and only if the first number is greater than or equal to the second number.
[ "Implement", "the", "compare", "operation", "on", "XPath", "objects", ":" ]
python
train
jason-weirather/pythologist
pythologist/__init__.py
https://github.com/jason-weirather/pythologist/blob/6eb4082be9dffa9570e4ceaa06d97845eac4c006/pythologist/__init__.py#L724-L751
def scored_to_phenotype(self,phenotypes): """ Convert binary pehnotypes to mutually exclusive phenotypes. If none of the phenotypes are set, then phenotype_label becomes nan If any of the phenotypes are multiply set then it throws a fatal error. Args: phenotypes (list): a list of scored_names to convert to phenotypes Returns: CellDataFrame """ def _apply_score(scored_calls,phenotypes): present = sorted(list(set(phenotypes)&set(scored_calls.keys()))) total = sum([scored_calls[x] for x in present]) if total > 1: raise ValueError("You cant extract phenotypes from scores if they are not mutually exclusive") if total == 0: return np.nan for label in present: if scored_calls[label] == 1: return label raise ValueError("Should have hit an exit criteria already") output = self.copy() output['phenotype_label'] = output.apply(lambda x: _apply_score(x['scored_calls'],phenotypes),1) # now update the phenotypes with these output['phenotype_calls'] = output.apply(lambda x: dict([(y,1 if x['phenotype_label']==y else 0) for y in phenotypes]) ,1) return output
[ "def", "scored_to_phenotype", "(", "self", ",", "phenotypes", ")", ":", "def", "_apply_score", "(", "scored_calls", ",", "phenotypes", ")", ":", "present", "=", "sorted", "(", "list", "(", "set", "(", "phenotypes", ")", "&", "set", "(", "scored_calls", "."...
Convert binary pehnotypes to mutually exclusive phenotypes. If none of the phenotypes are set, then phenotype_label becomes nan If any of the phenotypes are multiply set then it throws a fatal error. Args: phenotypes (list): a list of scored_names to convert to phenotypes Returns: CellDataFrame
[ "Convert", "binary", "pehnotypes", "to", "mutually", "exclusive", "phenotypes", ".", "If", "none", "of", "the", "phenotypes", "are", "set", "then", "phenotype_label", "becomes", "nan", "If", "any", "of", "the", "phenotypes", "are", "multiply", "set", "then", "...
python
train
RI-imaging/qpimage
qpimage/integrity_check.py
https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/integrity_check.py#L70-L115
def check_background(qpi): """Check QPimage background data Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails """ for imdat in [qpi._amp, qpi._pha]: try: fit, attrs = imdat.get_bg(key="fit", ret_attrs=True) except KeyError: # No bg correction performed pass else: kwargs = dict(attrs) # check if we have a user-defined mask image binkey = "estimate_bg_from_mask" if binkey in imdat.h5: kwargs["from_mask"] = imdat.h5[binkey][:] else: kwargs["from_mask"] = None # compute background correction with h5py.File("check.h5", driver="core", backing_store=False) as h5: # imdat.__class__ is "Amplitude" or "Phase" testimdat = imdat.__class__(h5) testimdat["raw"] = imdat.raw # Set experimental bg data if given try: bg = imdat.get_bg("data") except KeyError: pass else: testimdat.set_bg(bg, key="data") # fit bg testimdat.estimate_bg(**kwargs) # compare if not np.allclose(testimdat.get_bg(key="fit"), fit): msg = "Wrong estimated (fitted) background!" raise IntegrityCheckError(msg)
[ "def", "check_background", "(", "qpi", ")", ":", "for", "imdat", "in", "[", "qpi", ".", "_amp", ",", "qpi", ".", "_pha", "]", ":", "try", ":", "fit", ",", "attrs", "=", "imdat", ".", "get_bg", "(", "key", "=", "\"fit\"", ",", "ret_attrs", "=", "T...
Check QPimage background data Parameters ---------- qpi: qpimage.core.QPImage Raises ------ IntegrityCheckError if the check fails
[ "Check", "QPimage", "background", "data" ]
python
train
eandersson/amqpstorm
amqpstorm/basic.py
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L279-L298
def _consume_rpc_request(self, arguments, consumer_tag, exclusive, no_ack, no_local, queue): """Create a Consume Frame and execute a RPC request. :param str queue: Queue name :param str consumer_tag: Consumer tag :param bool no_local: Do not deliver own messages :param bool no_ack: No acknowledgement needed :param bool exclusive: Request exclusive access :param dict arguments: Consume key/value arguments :rtype: dict """ consume_frame = specification.Basic.Consume(queue=queue, consumer_tag=consumer_tag, exclusive=exclusive, no_local=no_local, no_ack=no_ack, arguments=arguments) return self._channel.rpc_request(consume_frame)
[ "def", "_consume_rpc_request", "(", "self", ",", "arguments", ",", "consumer_tag", ",", "exclusive", ",", "no_ack", ",", "no_local", ",", "queue", ")", ":", "consume_frame", "=", "specification", ".", "Basic", ".", "Consume", "(", "queue", "=", "queue", ",",...
Create a Consume Frame and execute a RPC request. :param str queue: Queue name :param str consumer_tag: Consumer tag :param bool no_local: Do not deliver own messages :param bool no_ack: No acknowledgement needed :param bool exclusive: Request exclusive access :param dict arguments: Consume key/value arguments :rtype: dict
[ "Create", "a", "Consume", "Frame", "and", "execute", "a", "RPC", "request", "." ]
python
train
UniversalDevicesInc/polyglot-v2-python-interface
polyinterface/polyinterface.py
https://github.com/UniversalDevicesInc/polyglot-v2-python-interface/blob/fe613135b762731a41a081222e43d2a8ae4fc53f/polyinterface/polyinterface.py#L519-L542
def save_typed_params(self, data): """ Send custom parameters descriptions to Polyglot to be used in front end UI configuration screen Accepts list of objects with the followin properties name - used as a key when data is sent from UI title - displayed in UI defaultValue - optionanl type - optional, can be 'NUMBER', 'STRING' or 'BOOLEAN'. Defaults to 'STRING' desc - optional, shown in tooltip in UI isRequired - optional, True/False, when set, will not validate UI input if it's empty isList - optional, True/False, if set this will be treated as list of values or objects by UI params - optional, can contain a list of objects. If present, then this (parent) is treated as object / list of objects by UI, otherwise, it's treated as a single / list of single values """ LOGGER.info('Sending typed parameters to Polyglot.') if type(data) is not list: data = [ data ] message = { 'typedparams': data } self.send(message)
[ "def", "save_typed_params", "(", "self", ",", "data", ")", ":", "LOGGER", ".", "info", "(", "'Sending typed parameters to Polyglot.'", ")", "if", "type", "(", "data", ")", "is", "not", "list", ":", "data", "=", "[", "data", "]", "message", "=", "{", "'ty...
Send custom parameters descriptions to Polyglot to be used in front end UI configuration screen Accepts list of objects with the followin properties name - used as a key when data is sent from UI title - displayed in UI defaultValue - optionanl type - optional, can be 'NUMBER', 'STRING' or 'BOOLEAN'. Defaults to 'STRING' desc - optional, shown in tooltip in UI isRequired - optional, True/False, when set, will not validate UI input if it's empty isList - optional, True/False, if set this will be treated as list of values or objects by UI params - optional, can contain a list of objects. If present, then this (parent) is treated as object / list of objects by UI, otherwise, it's treated as a single / list of single values
[ "Send", "custom", "parameters", "descriptions", "to", "Polyglot", "to", "be", "used", "in", "front", "end", "UI", "configuration", "screen", "Accepts", "list", "of", "objects", "with", "the", "followin", "properties", "name", "-", "used", "as", "a", "key", "...
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/markers.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/markers.py#L502-L573
def set_data(self, pos=None, symbol='o', size=10., edge_width=1., edge_width_rel=None, edge_color='black', face_color='white', scaling=False): """ Set the data used to display this visual. Parameters ---------- pos : array The array of locations to display each symbol. symbol : str The style of symbol to draw (see Notes). size : float or array The symbol size in px. edge_width : float | None The width of the symbol outline in pixels. edge_width_rel : float | None The width as a fraction of marker size. Exactly one of `edge_width` and `edge_width_rel` must be supplied. edge_color : Color | ColorArray The color used to draw each symbol outline. face_color : Color | ColorArray The color used to draw each symbol interior. scaling : bool If set to True, marker scales when rezooming. Notes ----- Allowed style strings are: disc, arrow, ring, clobber, square, diamond, vbar, hbar, cross, tailed_arrow, x, triangle_up, triangle_down, and star. """ assert (isinstance(pos, np.ndarray) and pos.ndim == 2 and pos.shape[1] in (2, 3)) if (edge_width is not None) + (edge_width_rel is not None) != 1: raise ValueError('exactly one of edge_width and edge_width_rel ' 'must be non-None') if edge_width is not None: if edge_width < 0: raise ValueError('edge_width cannot be negative') else: if edge_width_rel < 0: raise ValueError('edge_width_rel cannot be negative') self.symbol = symbol self.scaling = scaling edge_color = ColorArray(edge_color).rgba if len(edge_color) == 1: edge_color = edge_color[0] face_color = ColorArray(face_color).rgba if len(face_color) == 1: face_color = face_color[0] n = len(pos) data = np.zeros(n, dtype=[('a_position', np.float32, 3), ('a_fg_color', np.float32, 4), ('a_bg_color', np.float32, 4), ('a_size', np.float32, 1), ('a_edgewidth', np.float32, 1)]) data['a_fg_color'] = edge_color data['a_bg_color'] = face_color if edge_width is not None: data['a_edgewidth'] = edge_width else: data['a_edgewidth'] = size*edge_width_rel data['a_position'][:, :pos.shape[1]] = pos data['a_size'] = size self.shared_program['u_antialias'] = self.antialias # XXX make prop self._data = data self._vbo.set_data(data) self.shared_program.bind(self._vbo) self.update()
[ "def", "set_data", "(", "self", ",", "pos", "=", "None", ",", "symbol", "=", "'o'", ",", "size", "=", "10.", ",", "edge_width", "=", "1.", ",", "edge_width_rel", "=", "None", ",", "edge_color", "=", "'black'", ",", "face_color", "=", "'white'", ",", ...
Set the data used to display this visual. Parameters ---------- pos : array The array of locations to display each symbol. symbol : str The style of symbol to draw (see Notes). size : float or array The symbol size in px. edge_width : float | None The width of the symbol outline in pixels. edge_width_rel : float | None The width as a fraction of marker size. Exactly one of `edge_width` and `edge_width_rel` must be supplied. edge_color : Color | ColorArray The color used to draw each symbol outline. face_color : Color | ColorArray The color used to draw each symbol interior. scaling : bool If set to True, marker scales when rezooming. Notes ----- Allowed style strings are: disc, arrow, ring, clobber, square, diamond, vbar, hbar, cross, tailed_arrow, x, triangle_up, triangle_down, and star.
[ "Set", "the", "data", "used", "to", "display", "this", "visual", "." ]
python
train
TomasTomecek/sen
sen/net.py
https://github.com/TomasTomecek/sen/blob/239b4868125814e8bf5527708119fc08b35f6cc0/sen/net.py#L7-L27
def extract_data_from_inspect(network_name, network_data): """ :param network_name: str :param network_data: dict :return: dict: { "ip_address4": "12.34.56.78" "ip_address6": "ff:fa:..." } """ a4 = None if network_name == "host": a4 = "127.0.0.1" n = {} a4 = graceful_chain_get(network_data, "IPAddress") or a4 if a4: n["ip_address4"] = a4 a6 = graceful_chain_get(network_data, "GlobalIPv6Address") if a6: n["ip_address4"] = a6 return n
[ "def", "extract_data_from_inspect", "(", "network_name", ",", "network_data", ")", ":", "a4", "=", "None", "if", "network_name", "==", "\"host\"", ":", "a4", "=", "\"127.0.0.1\"", "n", "=", "{", "}", "a4", "=", "graceful_chain_get", "(", "network_data", ",", ...
:param network_name: str :param network_data: dict :return: dict: { "ip_address4": "12.34.56.78" "ip_address6": "ff:fa:..." }
[ ":", "param", "network_name", ":", "str", ":", "param", "network_data", ":", "dict", ":", "return", ":", "dict", ":", "{", "ip_address4", ":", "12", ".", "34", ".", "56", ".", "78", "ip_address6", ":", "ff", ":", "fa", ":", "...", "}" ]
python
train
Parsl/parsl
parsl/channels/ssh/ssh.py
https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/channels/ssh/ssh.py#L97-L122
def execute_wait(self, cmd, walltime=2, envs={}): ''' Synchronously execute a commandline string on the shell. Args: - cmd (string) : Commandline string to execute - walltime (int) : walltime in seconds Kwargs: - envs (dict) : Dictionary of env variables Returns: - retcode : Return code from the execution, -1 on fail - stdout : stdout string - stderr : stderr string Raises: None. ''' # Execute the command stdin, stdout, stderr = self.ssh_client.exec_command( self.prepend_envs(cmd, envs), bufsize=-1, timeout=walltime ) # Block on exit status from the command exit_status = stdout.channel.recv_exit_status() return exit_status, stdout.read().decode("utf-8"), stderr.read().decode("utf-8")
[ "def", "execute_wait", "(", "self", ",", "cmd", ",", "walltime", "=", "2", ",", "envs", "=", "{", "}", ")", ":", "# Execute the command", "stdin", ",", "stdout", ",", "stderr", "=", "self", ".", "ssh_client", ".", "exec_command", "(", "self", ".", "pre...
Synchronously execute a commandline string on the shell. Args: - cmd (string) : Commandline string to execute - walltime (int) : walltime in seconds Kwargs: - envs (dict) : Dictionary of env variables Returns: - retcode : Return code from the execution, -1 on fail - stdout : stdout string - stderr : stderr string Raises: None.
[ "Synchronously", "execute", "a", "commandline", "string", "on", "the", "shell", "." ]
python
valid
hsolbrig/pyjsg
pyjsg/jsglib/jsg_strings.py
https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/jsglib/jsg_strings.py#L23-L33
def matches(self, txt: str) -> bool: """Determine whether txt matches pattern :param txt: text to check :return: True if match """ # rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape') if r'\\u' in self.pattern_re.pattern: txt = txt.encode('utf-8').decode('unicode-escape') match = self.pattern_re.match(txt) return match is not None and match.end() == len(txt)
[ "def", "matches", "(", "self", ",", "txt", ":", "str", ")", "->", "bool", ":", "# rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape')", "if", "r'\\\\u'", "in", "self", ".", "pattern_re", ".", "pattern", ":", "txt", "=", "txt", ".", "encode", "(",...
Determine whether txt matches pattern :param txt: text to check :return: True if match
[ "Determine", "whether", "txt", "matches", "pattern" ]
python
train
googleapis/google-cloud-python
storage/google/cloud/storage/bucket.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/bucket.py#L831-L893
def delete(self, force=False, client=None): """Delete this bucket. The bucket **must** be empty in order to submit a delete request. If ``force=True`` is passed, this will first attempt to delete all the objects / blobs in the bucket (i.e. try to empty the bucket). If the bucket doesn't exist, this will raise :class:`google.cloud.exceptions.NotFound`. If the bucket is not empty (and ``force=False``), will raise :class:`google.cloud.exceptions.Conflict`. If ``force=True`` and the bucket contains more than 256 objects / blobs this will cowardly refuse to delete the objects (or the bucket). This is to prevent accidental bucket deletion and to prevent extremely long runtime of this method. If :attr:`user_project` is set, bills the API request to that project. :type force: bool :param force: If True, empties the bucket's objects then deletes it. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :raises: :class:`ValueError` if ``force`` is ``True`` and the bucket contains more than 256 objects / blobs. """ client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project if force: blobs = list( self.list_blobs( max_results=self._MAX_OBJECTS_FOR_ITERATION + 1, client=client ) ) if len(blobs) > self._MAX_OBJECTS_FOR_ITERATION: message = ( "Refusing to delete bucket with more than " "%d objects. If you actually want to delete " "this bucket, please delete the objects " "yourself before calling Bucket.delete()." ) % (self._MAX_OBJECTS_FOR_ITERATION,) raise ValueError(message) # Ignore 404 errors on delete. self.delete_blobs(blobs, on_error=lambda blob: None, client=client) # We intentionally pass `_target_object=None` since a DELETE # request has no response value (whether in a standard request or # in a batch request). client._connection.api_request( method="DELETE", path=self.path, query_params=query_params, _target_object=None, )
[ "def", "delete", "(", "self", ",", "force", "=", "False", ",", "client", "=", "None", ")", ":", "client", "=", "self", ".", "_require_client", "(", "client", ")", "query_params", "=", "{", "}", "if", "self", ".", "user_project", "is", "not", "None", ...
Delete this bucket. The bucket **must** be empty in order to submit a delete request. If ``force=True`` is passed, this will first attempt to delete all the objects / blobs in the bucket (i.e. try to empty the bucket). If the bucket doesn't exist, this will raise :class:`google.cloud.exceptions.NotFound`. If the bucket is not empty (and ``force=False``), will raise :class:`google.cloud.exceptions.Conflict`. If ``force=True`` and the bucket contains more than 256 objects / blobs this will cowardly refuse to delete the objects (or the bucket). This is to prevent accidental bucket deletion and to prevent extremely long runtime of this method. If :attr:`user_project` is set, bills the API request to that project. :type force: bool :param force: If True, empties the bucket's objects then deletes it. :type client: :class:`~google.cloud.storage.client.Client` or ``NoneType`` :param client: Optional. The client to use. If not passed, falls back to the ``client`` stored on the current bucket. :raises: :class:`ValueError` if ``force`` is ``True`` and the bucket contains more than 256 objects / blobs.
[ "Delete", "this", "bucket", "." ]
python
train
sebp/scikit-survival
sksurv/io/arffwrite.py
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L60-L85
def _write_header(data, fp, relation_name, index): """Write header containing attribute names and types""" fp.write("@relation {0}\n\n".format(relation_name)) if index: data = data.reset_index() attribute_names = _sanitize_column_names(data) for column, series in data.iteritems(): name = attribute_names[column] fp.write("@attribute {0}\t".format(name)) if is_categorical_dtype(series) or is_object_dtype(series): _write_attribute_categorical(series, fp) elif numpy.issubdtype(series.dtype, numpy.floating): fp.write("real") elif numpy.issubdtype(series.dtype, numpy.integer): fp.write("integer") elif numpy.issubdtype(series.dtype, numpy.datetime64): fp.write("date 'yyyy-MM-dd HH:mm:ss'") else: raise TypeError('unsupported type %s' % series.dtype) fp.write("\n") return data
[ "def", "_write_header", "(", "data", ",", "fp", ",", "relation_name", ",", "index", ")", ":", "fp", ".", "write", "(", "\"@relation {0}\\n\\n\"", ".", "format", "(", "relation_name", ")", ")", "if", "index", ":", "data", "=", "data", ".", "reset_index", ...
Write header containing attribute names and types
[ "Write", "header", "containing", "attribute", "names", "and", "types" ]
python
train
RRZE-HPC/kerncraft
kerncraft/kerncraft.py
https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/kerncraft.py#L126-L186
def create_parser(): """Return argparse parser.""" parser = argparse.ArgumentParser( description='Analytical performance modelling and benchmarking toolkit.', epilog='For help, examples, documentation and bug reports go to:\nhttps://github.com' '/RRZE-HPC/kerncraft\nLicense: AGPLv3') parser.add_argument('--version', action='version', version='%(prog)s {}'.format(__version__)) parser.add_argument('--machine', '-m', type=argparse.FileType('r'), required=True, help='Path to machine description yaml file.') parser.add_argument('--pmodel', '-p', choices=models.__all__, required=True, action='append', default=[], help='Performance model to apply') parser.add_argument('-D', '--define', nargs=2, metavar=('KEY', 'VALUE'), default=[], action=AppendStringRange, help='Define constant to be used in C code. Values must be integer or ' 'match start-stop[:num[log[base]]]. If range is given, all ' 'permutation s will be tested. Overwrites constants from testcase ' 'file.') parser.add_argument('--verbose', '-v', action='count', default=0, help='Increases verbosity level.') parser.add_argument('code_file', metavar='FILE', type=argparse.FileType(), help='File with loop kernel C code') parser.add_argument('--asm-block', metavar='BLOCK', default='auto', help='Number of ASM block to mark for IACA, "auto" for automatic ' 'selection or "manual" for interactiv selection.') parser.add_argument('--pointer-increment', metavar='INCR', default='auto', type=int_or_str, help='Increment of store pointer within one ASM block in bytes. If "auto": ' 'automatic detection, error on failure to detect, if ' '"auto_with_manual_fallback": fallback to manual input, or if ' '"manual": always prompt user.') parser.add_argument('--store', metavar='PICKLE', type=argparse.FileType('a+b'), help='Addes results to PICKLE file for later processing.') parser.add_argument('--unit', '-u', choices=['cy/CL', 'cy/It', 'It/s', 'FLOP/s'], help='Select the output unit, defaults to model specific if not given.') parser.add_argument('--cores', '-c', metavar='CORES', type=int, default=1, help='Number of cores to be used in parallel. (default: 1) ' 'ECM model will consider the scaling of the last level cache and ' 'predict the overall performance in addition to single-core behavior. ' 'The benchmark mode will run the code with OpenMP on as many physical ' 'cores.') parser.add_argument('--kernel-description', action='store_true', help='Use kernel description instead of analyzing the kernel code.') parser.add_argument('--clean-intermediates', action='store_true', help='If set, will delete all intermediate files after completion.') # Needed for ECM, ECMData and Roofline model: parser.add_argument('--cache-predictor', '-P', choices=['LC', 'SIM'], default='SIM', help='Change cache predictor to use, options are LC (layer conditions) and ' 'SIM (cache simulation with pycachesim), default is SIM.') # Needed for ECM, RooflineIACA and Benchmark model: parser.add_argument('--compiler', '-C', type=str, default=None, help='Compiler to use, default is first in machine description file.') parser.add_argument('--compiler-flags', type=str, default=None, help='Compiler flags to use. If not set, flags are taken from machine ' 'description file (-std=c99 is always added).') for m in models.__all__: ag = parser.add_argument_group('arguments for ' + m + ' model', getattr(models, m).name) getattr(models, m).configure_arggroup(ag) return parser
[ "def", "create_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Analytical performance modelling and benchmarking toolkit.'", ",", "epilog", "=", "'For help, examples, documentation and bug reports go to:\\nhttps://github.com'", ...
Return argparse parser.
[ "Return", "argparse", "parser", "." ]
python
test
a1ezzz/wasp-general
wasp_general/task/thread.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/thread.py#L176-L204
def start(self): """ :meth:`WStoppableTask.start` implementation that creates new thread """ start_event = self.start_event() stop_event = self.stop_event() ready_event = self.ready_event() def thread_target(): try: start_event.set() self.thread_started() if ready_event is not None: ready_event.set() except Exception as e: self.exception_event().set() self.thread_exception(e) if self.__thread is None: if stop_event is not None: stop_event.clear() if ready_event is not None: ready_event.clear() self.exception_event().clear() self.__thread = Thread(target=thread_target, name=self.thread_name()) self.__thread.start()
[ "def", "start", "(", "self", ")", ":", "start_event", "=", "self", ".", "start_event", "(", ")", "stop_event", "=", "self", ".", "stop_event", "(", ")", "ready_event", "=", "self", ".", "ready_event", "(", ")", "def", "thread_target", "(", ")", ":", "t...
:meth:`WStoppableTask.start` implementation that creates new thread
[ ":", "meth", ":", "WStoppableTask", ".", "start", "implementation", "that", "creates", "new", "thread" ]
python
train
jonathf/chaospy
chaospy/quad/sparse_grid.py
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/quad/sparse_grid.py#L52-L123
def sparse_grid(func, order, dim=None, skew=None): """ Smolyak sparse grid constructor. Args: func (:py:data:typing.Callable): Function that takes a single argument ``order`` of type ``numpy.ndarray`` and with ``order.shape = (dim,)`` order (int, numpy.ndarray): The order of the grid. If ``numpy.ndarray``, it overrides both ``dim`` and ``skew``. dim (int): Number of dimension. skew (list): Order skewness. """ if not isinstance(order, int): orders = numpy.array(order).flatten() dim = orders.size m_order = int(numpy.min(orders)) skew = [order-m_order for order in orders] return sparse_grid(func, m_order, dim, skew) abscissas, weights = [], [] bindex = chaospy.bertran.bindex(order-dim+1, order, dim) if skew is None: skew = numpy.zeros(dim, dtype=int) else: skew = numpy.array(skew, dtype=int) assert len(skew) == dim for idx in range( chaospy.bertran.terms(order, dim) - chaospy.bertran.terms(order-dim, dim)): idb = bindex[idx] abscissa, weight = func(skew+idb) weight *= (-1)**(order-sum(idb))*comb(dim-1, order-sum(idb)) abscissas.append(abscissa) weights.append(weight) abscissas = numpy.concatenate(abscissas, 1) weights = numpy.concatenate(weights, 0) abscissas = numpy.around(abscissas, 15) order = numpy.lexsort(tuple(abscissas)) abscissas = abscissas.T[order].T weights = weights[order] # identify non-unique terms diff = numpy.diff(abscissas.T, axis=0) unique = numpy.ones(len(abscissas.T), bool) unique[1:] = (diff != 0).any(axis=1) # merge duplicate nodes length = len(weights) idx = 1 while idx < length: while idx < length and unique[idx]: idx += 1 idy = idx+1 while idy < length and not unique[idy]: idy += 1 if idy-idx > 1: weights[idx-1] = numpy.sum(weights[idx-1:idy]) idx = idy+1 abscissas = abscissas[:, unique] weights = weights[unique] return abscissas, weights
[ "def", "sparse_grid", "(", "func", ",", "order", ",", "dim", "=", "None", ",", "skew", "=", "None", ")", ":", "if", "not", "isinstance", "(", "order", ",", "int", ")", ":", "orders", "=", "numpy", ".", "array", "(", "order", ")", ".", "flatten", ...
Smolyak sparse grid constructor. Args: func (:py:data:typing.Callable): Function that takes a single argument ``order`` of type ``numpy.ndarray`` and with ``order.shape = (dim,)`` order (int, numpy.ndarray): The order of the grid. If ``numpy.ndarray``, it overrides both ``dim`` and ``skew``. dim (int): Number of dimension. skew (list): Order skewness.
[ "Smolyak", "sparse", "grid", "constructor", "." ]
python
train
glyphobet/fragments
fragments/commands.py
https://github.com/glyphobet/fragments/blob/b58473604e2db47b98703260b8ee8605264247e3/fragments/commands.py#L21-L31
def help(*args): """Prints help.""" from . import commands parser = argparse.ArgumentParser(prog="%s %s" % (__package__, help.__name__), description=help.__doc__) parser.add_argument('COMMAND', help="command to show help for", nargs="?", choices=__all__) args = parser.parse_args(args) if args.COMMAND: for l in getattr(commands, args.COMMAND)('-h'): yield l else: parser.parse_args(['-h'])
[ "def", "help", "(", "*", "args", ")", ":", "from", ".", "import", "commands", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"%s %s\"", "%", "(", "__package__", ",", "help", ".", "__name__", ")", ",", "description", "=", "help", ...
Prints help.
[ "Prints", "help", "." ]
python
train
mabuchilab/QNET
src/qnet/algebra/core/abstract_quantum_algebra.py
https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/abstract_quantum_algebra.py#L1071-L1092
def _series_expand_combine_prod(c1, c2, order): """Given the result of the ``c1._series_expand(...)`` and ``c2._series_expand(...)``, construct the result of ``(c1*c2)._series_expand(...)`` """ from qnet.algebra.core.scalar_algebra import Zero res = [] c1 = list(c1) c2 = list(c2) for n in range(order + 1): summands = [] for k in range(n + 1): if c1[k].is_zero or c2[n-k].is_zero: summands.append(Zero) else: summands.append(c1[k] * c2[n - k]) sum = summands[0] for summand in summands[1:]: if summand != 0: sum += summand res.append(sum) return tuple(res)
[ "def", "_series_expand_combine_prod", "(", "c1", ",", "c2", ",", "order", ")", ":", "from", "qnet", ".", "algebra", ".", "core", ".", "scalar_algebra", "import", "Zero", "res", "=", "[", "]", "c1", "=", "list", "(", "c1", ")", "c2", "=", "list", "(",...
Given the result of the ``c1._series_expand(...)`` and ``c2._series_expand(...)``, construct the result of ``(c1*c2)._series_expand(...)``
[ "Given", "the", "result", "of", "the", "c1", ".", "_series_expand", "(", "...", ")", "and", "c2", ".", "_series_expand", "(", "...", ")", "construct", "the", "result", "of", "(", "c1", "*", "c2", ")", ".", "_series_expand", "(", "...", ")" ]
python
train
nicolargo/glances
glances/plugins/glances_psutilversion.py
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/plugins/glances_psutilversion.py#L44-L59
def update(self): """Update the stats.""" # Reset stats self.reset() # Return psutil version as a tuple if self.input_method == 'local': # psutil version only available in local try: self.stats = psutil_version_info except NameError: pass else: pass return self.stats
[ "def", "update", "(", "self", ")", ":", "# Reset stats", "self", ".", "reset", "(", ")", "# Return psutil version as a tuple", "if", "self", ".", "input_method", "==", "'local'", ":", "# psutil version only available in local", "try", ":", "self", ".", "stats", "=...
Update the stats.
[ "Update", "the", "stats", "." ]
python
train
metagriffin/pysyncml
pysyncml/agents/base.py
https://github.com/metagriffin/pysyncml/blob/a583fe0dbffa8b24e5a3e151524f84868b2382bb/pysyncml/agents/base.py#L208-L239
def matchItem(self, item): ''' [OPTIONAL] Attempts to find the specified item and returns an item that describes the same object although it's specific properties may be different. For example, a contact whose name is an identical match, but whose telephone number has changed would return the matched item. ``None`` should be returned if no match is found, otherwise the item that `item` matched should be returned. This is used primarily when a slow-sync is invoked and objects that exist in both peers should not be replicated. Note that **NO** merging of the items' properties should be done; that will be initiated via a separate call to :meth:`mergeItems`. This method by default will iterate over all items (by calling :meth:`getAllItems`) and compare them using ``cmp()``. This means that if the items managed by this agent implement the ``__eq__`` or ``__cmp__`` methods, then matching items will be detected and returned. Otherwise, any items that exist in both peers will be duplicated on slow-sync. Sub-classes *should* implement a more efficient method of finding matching items. See :doc:`../merging` for details. ''' for match in self.getAllItems(): if cmp(match, item) == 0: return match return None
[ "def", "matchItem", "(", "self", ",", "item", ")", ":", "for", "match", "in", "self", ".", "getAllItems", "(", ")", ":", "if", "cmp", "(", "match", ",", "item", ")", "==", "0", ":", "return", "match", "return", "None" ]
[OPTIONAL] Attempts to find the specified item and returns an item that describes the same object although it's specific properties may be different. For example, a contact whose name is an identical match, but whose telephone number has changed would return the matched item. ``None`` should be returned if no match is found, otherwise the item that `item` matched should be returned. This is used primarily when a slow-sync is invoked and objects that exist in both peers should not be replicated. Note that **NO** merging of the items' properties should be done; that will be initiated via a separate call to :meth:`mergeItems`. This method by default will iterate over all items (by calling :meth:`getAllItems`) and compare them using ``cmp()``. This means that if the items managed by this agent implement the ``__eq__`` or ``__cmp__`` methods, then matching items will be detected and returned. Otherwise, any items that exist in both peers will be duplicated on slow-sync. Sub-classes *should* implement a more efficient method of finding matching items. See :doc:`../merging` for details.
[ "[", "OPTIONAL", "]", "Attempts", "to", "find", "the", "specified", "item", "and", "returns", "an", "item", "that", "describes", "the", "same", "object", "although", "it", "s", "specific", "properties", "may", "be", "different", ".", "For", "example", "a", ...
python
valid
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/utils/path.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L38-L40
def _writable_dir(path): """Whether `path` is a directory, to which the user has write access.""" return os.path.isdir(path) and os.access(path, os.W_OK)
[ "def", "_writable_dir", "(", "path", ")", ":", "return", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "os", ".", "access", "(", "path", ",", "os", ".", "W_OK", ")" ]
Whether `path` is a directory, to which the user has write access.
[ "Whether", "path", "is", "a", "directory", "to", "which", "the", "user", "has", "write", "access", "." ]
python
test
saltstack/salt
salt/modules/boto_efs.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_efs.py#L82-L121
def _get_conn(key=None, keyid=None, profile=None, region=None, **kwargs): ''' Create a boto3 client connection to EFS ''' client = None if profile: if isinstance(profile, six.string_types): if profile in __pillar__: profile = __pillar__[profile] elif profile in __opts__: profile = __opts__[profile] elif key or keyid or region: profile = {} if key: profile['key'] = key if keyid: profile['keyid'] = keyid if region: profile['region'] = region if isinstance(profile, dict): if 'region' in profile: profile['region_name'] = profile['region'] profile.pop('region', None) if 'key' in profile: profile['aws_secret_access_key'] = profile['key'] profile.pop('key', None) if 'keyid' in profile: profile['aws_access_key_id'] = profile['keyid'] profile.pop('keyid', None) client = boto3.client('efs', **profile) else: client = boto3.client('efs') return client
[ "def", "_get_conn", "(", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "region", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "None", "if", "profile", ":", "if", "isinstance", "(", "profile", ","...
Create a boto3 client connection to EFS
[ "Create", "a", "boto3", "client", "connection", "to", "EFS" ]
python
train
rigetti/pyquil
pyquil/quilatom.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quilatom.py#L107-L121
def unpack_qubit(qubit): """ Get a qubit from an object. :param qubit: An int or Qubit. :return: A Qubit instance """ if isinstance(qubit, integer_types): return Qubit(qubit) elif isinstance(qubit, Qubit): return qubit elif isinstance(qubit, QubitPlaceholder): return qubit else: raise TypeError("qubit should be an int or Qubit instance")
[ "def", "unpack_qubit", "(", "qubit", ")", ":", "if", "isinstance", "(", "qubit", ",", "integer_types", ")", ":", "return", "Qubit", "(", "qubit", ")", "elif", "isinstance", "(", "qubit", ",", "Qubit", ")", ":", "return", "qubit", "elif", "isinstance", "(...
Get a qubit from an object. :param qubit: An int or Qubit. :return: A Qubit instance
[ "Get", "a", "qubit", "from", "an", "object", "." ]
python
train
erget/StereoVision
stereovision/blockmatchers.py
https://github.com/erget/StereoVision/blob/1adff45e291362f52188e0fd0211265845a4461a/stereovision/blockmatchers.py#L285-L293
def speckleWindowSize(self, value): """Set private ``_speckle_window_size`` and reset ``_block_matcher``.""" if value >= 0 and value <= 200: self._speckle_window_size = value else: raise InvalidSpeckleWindowSizeError("Speckle window size must be 0 " "for disabled checks or " "between 50 and 200.") self._replace_bm()
[ "def", "speckleWindowSize", "(", "self", ",", "value", ")", ":", "if", "value", ">=", "0", "and", "value", "<=", "200", ":", "self", ".", "_speckle_window_size", "=", "value", "else", ":", "raise", "InvalidSpeckleWindowSizeError", "(", "\"Speckle window size mus...
Set private ``_speckle_window_size`` and reset ``_block_matcher``.
[ "Set", "private", "_speckle_window_size", "and", "reset", "_block_matcher", "." ]
python
train
materialsproject/pymatgen
pymatgen/apps/borg/queen.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/apps/borg/queen.py#L131-L143
def order_assimilation(args): """ Internal helper method for BorgQueen to process assimilation """ (path, drone, data, status) = args newdata = drone.assimilate(path) if newdata: data.append(json.dumps(newdata, cls=MontyEncoder)) status['count'] += 1 count = status['count'] total = status['total'] logger.info('{}/{} ({:.2f}%) done'.format(count, total, count / total * 100))
[ "def", "order_assimilation", "(", "args", ")", ":", "(", "path", ",", "drone", ",", "data", ",", "status", ")", "=", "args", "newdata", "=", "drone", ".", "assimilate", "(", "path", ")", "if", "newdata", ":", "data", ".", "append", "(", "json", ".", ...
Internal helper method for BorgQueen to process assimilation
[ "Internal", "helper", "method", "for", "BorgQueen", "to", "process", "assimilation" ]
python
train
shapiromatron/bmds
bmds/datasets.py
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L109-L127
def as_dfile(self): """ Return the dataset representation in BMDS .(d) file. Example ------- >>> print(dataset.as_dfile()) Dose Incidence NEGATIVE_RESPONSE 0.000000 5 70 1.960000 1 48 5.690000 3 47 29.750000 14 35 """ rows = ["Dose Incidence NEGATIVE_RESPONSE"] for i, v in enumerate(self.doses): if i >= self.num_dose_groups: continue rows.append("%f %d %d" % (self.doses[i], self.incidences[i], self.remainings[i])) return "\n".join(rows)
[ "def", "as_dfile", "(", "self", ")", ":", "rows", "=", "[", "\"Dose Incidence NEGATIVE_RESPONSE\"", "]", "for", "i", ",", "v", "in", "enumerate", "(", "self", ".", "doses", ")", ":", "if", "i", ">=", "self", ".", "num_dose_groups", ":", "continue", "rows...
Return the dataset representation in BMDS .(d) file. Example ------- >>> print(dataset.as_dfile()) Dose Incidence NEGATIVE_RESPONSE 0.000000 5 70 1.960000 1 48 5.690000 3 47 29.750000 14 35
[ "Return", "the", "dataset", "representation", "in", "BMDS", ".", "(", "d", ")", "file", "." ]
python
train
hasgeek/coaster
coaster/sqlalchemy/roles.py
https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/sqlalchemy/roles.py#L363-L377
def current_roles(self): """ :class:`~coaster.utils.classes.InspectableSet` containing currently available roles on this object, using :obj:`~coaster.auth.current_auth`. Use in the view layer to inspect for a role being present: if obj.current_roles.editor: pass {% if obj.current_roles.editor %}...{% endif %} This property is also available in :class:`RoleAccessProxy`. """ return InspectableSet(self.roles_for(actor=current_auth.actor, anchors=current_auth.anchors))
[ "def", "current_roles", "(", "self", ")", ":", "return", "InspectableSet", "(", "self", ".", "roles_for", "(", "actor", "=", "current_auth", ".", "actor", ",", "anchors", "=", "current_auth", ".", "anchors", ")", ")" ]
:class:`~coaster.utils.classes.InspectableSet` containing currently available roles on this object, using :obj:`~coaster.auth.current_auth`. Use in the view layer to inspect for a role being present: if obj.current_roles.editor: pass {% if obj.current_roles.editor %}...{% endif %} This property is also available in :class:`RoleAccessProxy`.
[ ":", "class", ":", "~coaster", ".", "utils", ".", "classes", ".", "InspectableSet", "containing", "currently", "available", "roles", "on", "this", "object", "using", ":", "obj", ":", "~coaster", ".", "auth", ".", "current_auth", ".", "Use", "in", "the", "v...
python
train
JoelBender/bacpypes
py25/bacpypes/iocb.py
https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/iocb.py#L698-L727
def request_io(self, iocb): """Called by a client to start processing a request.""" if _debug: IOQController._debug("request_io %r", iocb) # bind the iocb to this controller iocb.ioController = self # if we're busy, queue it if (self.state != CTRL_IDLE): if _debug: IOQController._debug(" - busy, request queued, active_iocb: %r", self.active_iocb) iocb.ioState = PENDING self.ioQueue.put(iocb) return try: # hopefully there won't be an error err = None # let derived class figure out how to process this self.process_io(iocb) except: # extract the error err = sys.exc_info()[1] if _debug: IOQController._debug(" - process_io() exception: %r", err) # if there was an error, abort the request if err: if _debug: IOQController._debug(" - aborting") self.abort_io(iocb, err)
[ "def", "request_io", "(", "self", ",", "iocb", ")", ":", "if", "_debug", ":", "IOQController", ".", "_debug", "(", "\"request_io %r\"", ",", "iocb", ")", "# bind the iocb to this controller", "iocb", ".", "ioController", "=", "self", "# if we're busy, queue it", "...
Called by a client to start processing a request.
[ "Called", "by", "a", "client", "to", "start", "processing", "a", "request", "." ]
python
train
Esri/ArcREST
src/arcrest/_abstract/abstract.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L235-L244
def _unzip_file(self, zip_file, out_folder): """ unzips a file to a given folder """ try: zf = zipfile.ZipFile(zip_file, 'r') zf.extractall(path=out_folder) zf.close() del zf return True except: return False
[ "def", "_unzip_file", "(", "self", ",", "zip_file", ",", "out_folder", ")", ":", "try", ":", "zf", "=", "zipfile", ".", "ZipFile", "(", "zip_file", ",", "'r'", ")", "zf", ".", "extractall", "(", "path", "=", "out_folder", ")", "zf", ".", "close", "("...
unzips a file to a given folder
[ "unzips", "a", "file", "to", "a", "given", "folder" ]
python
train
Nike-Inc/cerberus-python-client
cerberus/client.py
https://github.com/Nike-Inc/cerberus-python-client/blob/ef38356822e722fcb6a6ed4a1b38a5b493e753ae/cerberus/client.py#L271-L278
def get_sdb_secret_version_paths(self, sdb_id): """ Get SDB secret version paths. This function takes the sdb_id """ sdb_resp = get_with_retry(str.join('', [self.cerberus_url, '/v1/sdb-secret-version-paths/', sdb_id]), headers=self.HEADERS) throw_if_bad_response(sdb_resp) return sdb_resp.json()
[ "def", "get_sdb_secret_version_paths", "(", "self", ",", "sdb_id", ")", ":", "sdb_resp", "=", "get_with_retry", "(", "str", ".", "join", "(", "''", ",", "[", "self", ".", "cerberus_url", ",", "'/v1/sdb-secret-version-paths/'", ",", "sdb_id", "]", ")", ",", "...
Get SDB secret version paths. This function takes the sdb_id
[ "Get", "SDB", "secret", "version", "paths", ".", "This", "function", "takes", "the", "sdb_id" ]
python
train
gnosis/gnosis-py
gnosis/eth/ethereum_client.py
https://github.com/gnosis/gnosis-py/blob/2a9a5d75a375fc9813ac04df133e6910c82f9d49/gnosis/eth/ethereum_client.py#L174-L186
def send_tokens(self, to: str, amount: int, erc20_address: str, private_key: str) -> bytes: """ Send tokens to address :param to: :param amount: :param erc20_address: :param private_key: :return: tx_hash """ erc20 = get_erc20_contract(self.w3, erc20_address) account = Account.privateKeyToAccount(private_key) tx = erc20.functions.transfer(to, amount).buildTransaction({'from': account.address}) return self.ethereum_client.send_unsigned_transaction(tx, private_key=private_key)
[ "def", "send_tokens", "(", "self", ",", "to", ":", "str", ",", "amount", ":", "int", ",", "erc20_address", ":", "str", ",", "private_key", ":", "str", ")", "->", "bytes", ":", "erc20", "=", "get_erc20_contract", "(", "self", ".", "w3", ",", "erc20_addr...
Send tokens to address :param to: :param amount: :param erc20_address: :param private_key: :return: tx_hash
[ "Send", "tokens", "to", "address", ":", "param", "to", ":", ":", "param", "amount", ":", ":", "param", "erc20_address", ":", ":", "param", "private_key", ":", ":", "return", ":", "tx_hash" ]
python
test
rosenbrockc/fortpy
fortpy/interop/converter.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/interop/converter.py#L354-L357
def _comment(self, element): """Extracts the character to use for comments in the input file.""" for v in _get_xml_version(element): self.versions[v].comment = element.text
[ "def", "_comment", "(", "self", ",", "element", ")", ":", "for", "v", "in", "_get_xml_version", "(", "element", ")", ":", "self", ".", "versions", "[", "v", "]", ".", "comment", "=", "element", ".", "text" ]
Extracts the character to use for comments in the input file.
[ "Extracts", "the", "character", "to", "use", "for", "comments", "in", "the", "input", "file", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/cwl/cwlutils.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L20-L24
def to_rec(samples, default_keys=None): """Convert inputs into CWL records, useful for single item parallelization. """ recs = samples_to_records([normalize_missing(utils.to_single_data(x)) for x in samples], default_keys) return [[x] for x in recs]
[ "def", "to_rec", "(", "samples", ",", "default_keys", "=", "None", ")", ":", "recs", "=", "samples_to_records", "(", "[", "normalize_missing", "(", "utils", ".", "to_single_data", "(", "x", ")", ")", "for", "x", "in", "samples", "]", ",", "default_keys", ...
Convert inputs into CWL records, useful for single item parallelization.
[ "Convert", "inputs", "into", "CWL", "records", "useful", "for", "single", "item", "parallelization", "." ]
python
train
louisun/iSearch
iSearch/isearch.py
https://github.com/louisun/iSearch/blob/06013d610338397f8cdd69f330b43e1ee8d29f1b/iSearch/isearch.py#L210-L219
def search_online(word, printer=True): '''search the word or phrase on http://dict.youdao.com.''' url = 'http://dict.youdao.com/w/ %s' % word expl = get_text(url) if printer: colorful_print(expl) return expl
[ "def", "search_online", "(", "word", ",", "printer", "=", "True", ")", ":", "url", "=", "'http://dict.youdao.com/w/ %s'", "%", "word", "expl", "=", "get_text", "(", "url", ")", "if", "printer", ":", "colorful_print", "(", "expl", ")", "return", "expl" ]
search the word or phrase on http://dict.youdao.com.
[ "search", "the", "word", "or", "phrase", "on", "http", ":", "//", "dict", ".", "youdao", ".", "com", "." ]
python
train
manodeep/Corrfunc
setup.py
https://github.com/manodeep/Corrfunc/blob/753aa50b93eebfefc76a0b0cd61522536bd45d2a/setup.py#L74-L144
def get_dict_from_buffer(buf, keys=['DISTNAME', 'MAJOR', 'MINOR', 'PATCHLEVEL', 'PYTHON', 'MIN_PYTHON_MAJOR', 'MIN_PYTHON_MINOR', 'MIN_NUMPY_MAJOR', 'MIN_NUMPY_MINOR']): """ Parses a string buffer for key-val pairs for the supplied keys. Returns: Python dictionary with all the keys (all keys in buffer if None is passed for keys) with the values being a list corresponding to each key. Note: Return dict will contain all keys supplied (if not None). If any key was not found in the buffer, then the value for that key will be [] such that dict[key] does not produce a KeyError. Slightly modified from: "http://stackoverflow.com/questions/5323703/regex-how-to-"\ "match-sequence-of-key-value-pairs-at-end-of-string """ pairs = dict() if keys is None: keys = "\S+" regex = re.compile(r''' \n # all key-value pairs are on separate lines \s* # there might be some leading spaces ( # start group to return (?:{0}\s*) # placeholder for tags to detect '\S+' == all \s*:*=\s* # optional spaces, optional colon, = , optional spaces .* # the value ) # end group to return '''.format(keys), re.VERBOSE) validate = False else: keys = [k.strip() for k in keys] regex = re.compile(r''' \n # all key-value pairs are on separate lines \s* # there might be some leading spaces ( # start group to return (?:{0}\s*) # placeholder for tags to detect '\S+' == all \s*:*=\s* # optional spaces, optional colon, = , optional spaces .* # the value ) # end group to return '''.format('|'.join(keys)), re.VERBOSE) validate = True for k in keys: pairs[k] = [] matches = regex.findall(buf) for match in matches: key, val = match.split('=', 1) # remove colon and leading/trailing whitespace from key key = (strip_line(key, ':')).strip() # remove newline and leading/trailing whitespace from value val = (strip_line(val)).strip() if validate and key not in keys: msg = "regex produced incorrect match. regex pattern = {0} "\ "claims key = [{1}] while original set of search keys "\ "= {2}".format(regex.pattern, key, '|'.join(keys)) raise AssertionError(msg) pairs.setdefault(key, []).append(val) return pairs
[ "def", "get_dict_from_buffer", "(", "buf", ",", "keys", "=", "[", "'DISTNAME'", ",", "'MAJOR'", ",", "'MINOR'", ",", "'PATCHLEVEL'", ",", "'PYTHON'", ",", "'MIN_PYTHON_MAJOR'", ",", "'MIN_PYTHON_MINOR'", ",", "'MIN_NUMPY_MAJOR'", ",", "'MIN_NUMPY_MINOR'", "]", ")"...
Parses a string buffer for key-val pairs for the supplied keys. Returns: Python dictionary with all the keys (all keys in buffer if None is passed for keys) with the values being a list corresponding to each key. Note: Return dict will contain all keys supplied (if not None). If any key was not found in the buffer, then the value for that key will be [] such that dict[key] does not produce a KeyError. Slightly modified from: "http://stackoverflow.com/questions/5323703/regex-how-to-"\ "match-sequence-of-key-value-pairs-at-end-of-string
[ "Parses", "a", "string", "buffer", "for", "key", "-", "val", "pairs", "for", "the", "supplied", "keys", "." ]
python
train
kisom/pypcapfile
pcapfile/savefile.py
https://github.com/kisom/pypcapfile/blob/67520cfbb6c2e9ab3e7c181a8012ddc56ec5cad8/pcapfile/savefile.py#L175-L190
def _load_packets(file_h, header, layers=0): """ Read packets from the capture file. Expects the file handle to point to the location immediately after the header (24 bytes). """ pkts = [] hdrp = ctypes.pointer(header) while True: pkt = _read_a_packet(file_h, hdrp, layers) if pkt: pkts.append(pkt) else: break return pkts
[ "def", "_load_packets", "(", "file_h", ",", "header", ",", "layers", "=", "0", ")", ":", "pkts", "=", "[", "]", "hdrp", "=", "ctypes", ".", "pointer", "(", "header", ")", "while", "True", ":", "pkt", "=", "_read_a_packet", "(", "file_h", ",", "hdrp",...
Read packets from the capture file. Expects the file handle to point to the location immediately after the header (24 bytes).
[ "Read", "packets", "from", "the", "capture", "file", ".", "Expects", "the", "file", "handle", "to", "point", "to", "the", "location", "immediately", "after", "the", "header", "(", "24", "bytes", ")", "." ]
python
valid
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L592-L601
def OnErrCancel(self, obj, f: OrderField, info: InfoField): """ 撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField: """ print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info)
[ "def", "OnErrCancel", "(", "self", ",", "obj", ",", "f", ":", "OrderField", ",", "info", ":", "InfoField", ")", ":", "print", "(", "'=== [TRADE] OnErrCancel ===\\n{0}'", ".", "format", "(", "f", ".", "__dict__", ")", ")", "print", "(", "info", ")" ]
撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField:
[ "撤单失败", ":", "param", "self", ":", ":", "param", "obj", ":", ":", "param", "f", ":", "OrderField", ":", ":", "param", "info", ":", "InfoField", ":" ]
python
train
CivicSpleen/ambry
ambry/library/search_backends/postgres_backend.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/postgres_backend.py#L586-L593
def _index_document(self, identifier, force=False): """ Adds identifier document to the index. """ query = text(""" INSERT INTO identifier_index(identifier, type, name) VALUES(:identifier, :type, :name); """) self.execute(query, **identifier)
[ "def", "_index_document", "(", "self", ",", "identifier", ",", "force", "=", "False", ")", ":", "query", "=", "text", "(", "\"\"\"\n INSERT INTO identifier_index(identifier, type, name)\n VALUES(:identifier, :type, :name);\n \"\"\"", ")", "self", "....
Adds identifier document to the index.
[ "Adds", "identifier", "document", "to", "the", "index", "." ]
python
train
senseobservationsystems/commonsense-python-lib
senseapi.py
https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L60-L84
def setServer(self, server): """ Set server to interact with. @param server (string) - 'live' for live server, 'dev' for test server, 'rc' for release candidate @return (boolean) - Boolean indicating whether setServer succeeded """ if server == 'live': self.__server__ = server self.__server_url__ = 'api.sense-os.nl' self.setUseHTTPS() return True elif server == 'dev': self.__server__ = server self.__server_url__ = 'api.dev.sense-os.nl' # the dev server doesn't support https self.setUseHTTPS(False) return True elif server == 'rc': self.__server__ = server self.__server_url__ = 'api.rc.dev.sense-os.nl' self.setUseHTTPS(False) else: return False
[ "def", "setServer", "(", "self", ",", "server", ")", ":", "if", "server", "==", "'live'", ":", "self", ".", "__server__", "=", "server", "self", ".", "__server_url__", "=", "'api.sense-os.nl'", "self", ".", "setUseHTTPS", "(", ")", "return", "True", "elif"...
Set server to interact with. @param server (string) - 'live' for live server, 'dev' for test server, 'rc' for release candidate @return (boolean) - Boolean indicating whether setServer succeeded
[ "Set", "server", "to", "interact", "with", "." ]
python
train
bykof/billomapy
billomapy/billomapy.py
https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L1464-L1478
def get_items_of_recurring_per_page(self, recurring_id, per_page=1000, page=1): """ Get items of recurring per page :param recurring_id: the recurring id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list """ return self._get_resource_per_page( resource=RECURRING_ITEMS, per_page=per_page, page=page, params={'recurring_id': recurring_id}, )
[ "def", "get_items_of_recurring_per_page", "(", "self", ",", "recurring_id", ",", "per_page", "=", "1000", ",", "page", "=", "1", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "RECURRING_ITEMS", ",", "per_page", "=", "per_page",...
Get items of recurring per page :param recurring_id: the recurring id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
[ "Get", "items", "of", "recurring", "per", "page" ]
python
train
PetrochukM/PyTorch-NLP
torchnlp/datasets/ud_pos.py
https://github.com/PetrochukM/PyTorch-NLP/blob/5f7320da5c8d781df072fab3f7e421c6347e5bfa/torchnlp/datasets/ud_pos.py#L8-L88
def ud_pos_dataset(directory='data/', train=False, dev=False, test=False, train_filename='en-ud-tag.v2.train.txt', dev_filename='en-ud-tag.v2.dev.txt', test_filename='en-ud-tag.v2.test.txt', extracted_name='en-ud-v2', check_files=['en-ud-v2/en-ud-tag.v2.train.txt'], url='https://bitbucket.org/sivareddyg/public/downloads/en-ud-v2.zip'): """ Load the Universal Dependencies - English Dependency Treebank dataset. Corpus of sentences annotated using Universal Dependencies annotation. The corpus comprises 254,830 words and 16,622 sentences, taken from various web media including weblogs, newsgroups, emails, reviews, and Yahoo! answers. References: * http://universaldependencies.org/ * https://github.com/UniversalDependencies/UD_English **Citation:** Natalia Silveira and Timothy Dozat and Marie-Catherine de Marneffe and Samuel Bowman and Miriam Connor and John Bauer and Christopher D. Manning (2014). A Gold Standard Dependency Corpus for {E}nglish Args: directory (str, optional): Directory to cache the dataset. train (bool, optional): If to load the training split of the dataset. dev (bool, optional): If to load the development split of the dataset. test (bool, optional): If to load the test split of the dataset. train_filename (str, optional): The filename of the training split. dev_filename (str, optional): The filename of the development split. test_filename (str, optional): The filename of the test split. extracted_name (str, optional): Name of the extracted dataset directory. check_files (str, optional): Check if these files exist, then this download was successful. url (str, optional): URL of the dataset `tar.gz` file. Returns: :class:`tuple` of :class:`torchnlp.datasets.Dataset` or :class:`torchnlp.datasets.Dataset`: Returns between one and all dataset splits (train, dev and test) depending on if their respective boolean argument is ``True``. Example: >>> from torchnlp.datasets import ud_pos_dataset # doctest: +SKIP >>> train = ud_pos_dataset(train=True) # doctest: +SKIP >>> train[17] # doctest: +SKIP { 'tokens': ['Guerrillas', 'killed', 'an', 'engineer', ',', 'Asi', 'Ali', ',', 'from', 'Tikrit', '.'], 'ud_tags': ['NOUN', 'VERB', 'DET', 'NOUN', 'PUNCT', 'PROPN', 'PROPN', 'PUNCT', 'ADP', 'PROPN', 'PUNCT'], 'ptb_tags': ['NNS', 'VBD', 'DT', 'NN', ',', 'NNP', 'NNP', ',', 'IN', 'NNP', '.'] } """ download_file_maybe_extract(url=url, directory=directory, check_files=check_files) ret = [] splits = [(train, train_filename), (dev, dev_filename), (test, test_filename)] splits = [f for (requested, f) in splits if requested] for filename in splits: full_path = os.path.join(directory, extracted_name, filename) examples = [] with io.open(full_path, encoding='utf-8') as f: sentence = {'tokens': [], 'ud_tags': [], 'ptb_tags': []} for line in f: line = line.strip() if line == '' and len(sentence['tokens']) > 0: examples.append(sentence) sentence = {'tokens': [], 'ud_tags': [], 'ptb_tags': []} elif line != '': token, ud_tag, ptb_tag = tuple(line.split('\t')) sentence['tokens'].append(token) sentence['ud_tags'].append(ud_tag) sentence['ptb_tags'].append(ptb_tag) ret.append(Dataset(examples)) if len(ret) == 1: return ret[0] else: return tuple(ret)
[ "def", "ud_pos_dataset", "(", "directory", "=", "'data/'", ",", "train", "=", "False", ",", "dev", "=", "False", ",", "test", "=", "False", ",", "train_filename", "=", "'en-ud-tag.v2.train.txt'", ",", "dev_filename", "=", "'en-ud-tag.v2.dev.txt'", ",", "test_fil...
Load the Universal Dependencies - English Dependency Treebank dataset. Corpus of sentences annotated using Universal Dependencies annotation. The corpus comprises 254,830 words and 16,622 sentences, taken from various web media including weblogs, newsgroups, emails, reviews, and Yahoo! answers. References: * http://universaldependencies.org/ * https://github.com/UniversalDependencies/UD_English **Citation:** Natalia Silveira and Timothy Dozat and Marie-Catherine de Marneffe and Samuel Bowman and Miriam Connor and John Bauer and Christopher D. Manning (2014). A Gold Standard Dependency Corpus for {E}nglish Args: directory (str, optional): Directory to cache the dataset. train (bool, optional): If to load the training split of the dataset. dev (bool, optional): If to load the development split of the dataset. test (bool, optional): If to load the test split of the dataset. train_filename (str, optional): The filename of the training split. dev_filename (str, optional): The filename of the development split. test_filename (str, optional): The filename of the test split. extracted_name (str, optional): Name of the extracted dataset directory. check_files (str, optional): Check if these files exist, then this download was successful. url (str, optional): URL of the dataset `tar.gz` file. Returns: :class:`tuple` of :class:`torchnlp.datasets.Dataset` or :class:`torchnlp.datasets.Dataset`: Returns between one and all dataset splits (train, dev and test) depending on if their respective boolean argument is ``True``. Example: >>> from torchnlp.datasets import ud_pos_dataset # doctest: +SKIP >>> train = ud_pos_dataset(train=True) # doctest: +SKIP >>> train[17] # doctest: +SKIP { 'tokens': ['Guerrillas', 'killed', 'an', 'engineer', ',', 'Asi', 'Ali', ',', 'from', 'Tikrit', '.'], 'ud_tags': ['NOUN', 'VERB', 'DET', 'NOUN', 'PUNCT', 'PROPN', 'PROPN', 'PUNCT', 'ADP', 'PROPN', 'PUNCT'], 'ptb_tags': ['NNS', 'VBD', 'DT', 'NN', ',', 'NNP', 'NNP', ',', 'IN', 'NNP', '.'] }
[ "Load", "the", "Universal", "Dependencies", "-", "English", "Dependency", "Treebank", "dataset", "." ]
python
train
Esri/ArcREST
src/arcrest/ags/server.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/server.py#L167-L239
def services(self): """gets the services in the current folder""" services = [] if self._services is None: self.__init() for service in self._services: url = "%s/%s/%s" % (self.root, service['name'], service['type']) if service['type'] == "GPServer": services.append(GPService(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) elif service['type'] == "MapServer": services.append(MapService(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) elif service['type'] == "ImageServer": services.append(ImageService(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) elif service['type'] == "FeatureServer": if self.currentFolder == 'root': serviceName = service['name'] else: serviceName = service['name'].split('/')[1] url = "%s/%s/%s" % (self.location, serviceName, service['type']) services.append(FeatureService(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) elif service['type'] == "GeometryServer": url = "%s/%s/%s" % (self.root, service['name'], service['type']) services.append(GeometryService(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) elif service['type'] == "MobileServer": services.append(MobileService(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) elif service['type'] == "NAServer": services.append(NetworkService(url=url, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url)) elif service['type'] == "GeocodeServer": services.append(GeocodeService(url=url, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url)) elif service['type'] == "GeoDataServer": services.append(GeoDataService(url=url, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url)) elif service['type'] == "GlobeServer": services.append(GlobeService(url=url, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url)) elif service['type'] == "StreamServer": services.append(StreamService(url=url, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url)) elif service['type'] in ("IndexGenerator", "IndexingLauncher", "SearchServer"): pass else: print (service['type'], service['name']) return services
[ "def", "services", "(", "self", ")", ":", "services", "=", "[", "]", "if", "self", ".", "_services", "is", "None", ":", "self", ".", "__init", "(", ")", "for", "service", "in", "self", ".", "_services", ":", "url", "=", "\"%s/%s/%s\"", "%", "(", "s...
gets the services in the current folder
[ "gets", "the", "services", "in", "the", "current", "folder" ]
python
train
EpistasisLab/scikit-mdr
mdr/utils/utils.py
https://github.com/EpistasisLab/scikit-mdr/blob/768565deb10467d04a960d27e000ab38b7aa8a62/mdr/utils/utils.py#L270-L307
def n_way_models(mdr_instance, X, y, n=[2], feature_names=None): """Fits a MDR model to all n-way combinations of the features in X. Note that this function performs an exhaustive search through all feature combinations and can be computationally expensive. Parameters ---------- mdr_instance: object An instance of the MDR type to use. X: array-like (# rows, # features) NumPy matrix containing the features y: array-like (# rows, 1) NumPy matrix containing the target values n: list (default: [2]) The maximum size(s) of the MDR model to generate. e.g., if n == [3], all 3-way models will be generated. feature_names: list (default: None) The corresponding names of the features in X. If None, then the features will be named according to their order. Returns ---------- (fitted_model, fitted_model_score, fitted_model_features): tuple of (list, list, list) fitted_model contains the MDR model fitted to the data. fitted_model_score contains the training scores corresponding to the fitted MDR model. fitted_model_features contains a list of the names of the features that were used in the corresponding model. """ if feature_names is None: feature_names = list(range(X.shape[1])) for cur_n in n: for features in itertools.combinations(range(X.shape[1]), cur_n): mdr_model = copy.deepcopy(mdr_instance) mdr_model.fit(X[:, features], y) mdr_model_score = mdr_model.score(X[:, features], y) model_features = [feature_names[feature] for feature in features] yield mdr_model, mdr_model_score, model_features
[ "def", "n_way_models", "(", "mdr_instance", ",", "X", ",", "y", ",", "n", "=", "[", "2", "]", ",", "feature_names", "=", "None", ")", ":", "if", "feature_names", "is", "None", ":", "feature_names", "=", "list", "(", "range", "(", "X", ".", "shape", ...
Fits a MDR model to all n-way combinations of the features in X. Note that this function performs an exhaustive search through all feature combinations and can be computationally expensive. Parameters ---------- mdr_instance: object An instance of the MDR type to use. X: array-like (# rows, # features) NumPy matrix containing the features y: array-like (# rows, 1) NumPy matrix containing the target values n: list (default: [2]) The maximum size(s) of the MDR model to generate. e.g., if n == [3], all 3-way models will be generated. feature_names: list (default: None) The corresponding names of the features in X. If None, then the features will be named according to their order. Returns ---------- (fitted_model, fitted_model_score, fitted_model_features): tuple of (list, list, list) fitted_model contains the MDR model fitted to the data. fitted_model_score contains the training scores corresponding to the fitted MDR model. fitted_model_features contains a list of the names of the features that were used in the corresponding model.
[ "Fits", "a", "MDR", "model", "to", "all", "n", "-", "way", "combinations", "of", "the", "features", "in", "X", "." ]
python
test
gem/oq-engine
openquake/calculators/getters.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/getters.py#L433-L460
def gen_rupture_getters(dstore, slc=slice(None), concurrent_tasks=1, hdf5cache=None): """ :yields: RuptureGetters """ if dstore.parent: dstore = dstore.parent csm_info = dstore['csm_info'] trt_by_grp = csm_info.grp_by("trt") samples = csm_info.get_samples_by_grp() rlzs_by_gsim = csm_info.get_rlzs_by_gsim_grp() rup_array = dstore['ruptures'][slc] maxweight = numpy.ceil(len(rup_array) / (concurrent_tasks or 1)) nr, ne = 0, 0 for grp_id, arr in general.group_array(rup_array, 'grp_id').items(): if not rlzs_by_gsim[grp_id]: # this may happen if a source model has no sources, like # in event_based_risk/case_3 continue for block in general.block_splitter(arr, maxweight): rgetter = RuptureGetter( hdf5cache or dstore.filename, numpy.array(block), grp_id, trt_by_grp[grp_id], samples[grp_id], rlzs_by_gsim[grp_id]) rgetter.weight = getattr(block, 'weight', len(block)) yield rgetter nr += len(block) ne += rgetter.num_events logging.info('Read %d ruptures and %d events', nr, ne)
[ "def", "gen_rupture_getters", "(", "dstore", ",", "slc", "=", "slice", "(", "None", ")", ",", "concurrent_tasks", "=", "1", ",", "hdf5cache", "=", "None", ")", ":", "if", "dstore", ".", "parent", ":", "dstore", "=", "dstore", ".", "parent", "csm_info", ...
:yields: RuptureGetters
[ ":", "yields", ":", "RuptureGetters" ]
python
train
bachya/pyflunearyou
pyflunearyou/cdc.py
https://github.com/bachya/pyflunearyou/blob/16a2f839c8df851e925e010a6b5c5708386febac/pyflunearyou/cdc.py#L23-L34
def adjust_status(info: dict) -> dict: """Apply status mapping to a raw API result.""" modified_info = deepcopy(info) modified_info.update({ 'level': get_nearest_by_numeric_key(STATUS_MAP, int(info['level'])), 'level2': STATUS_MAP[99] if info['level2'] is None else get_nearest_by_numeric_key(STATUS_MAP, int(info['level2'])) }) return modified_info
[ "def", "adjust_status", "(", "info", ":", "dict", ")", "->", "dict", ":", "modified_info", "=", "deepcopy", "(", "info", ")", "modified_info", ".", "update", "(", "{", "'level'", ":", "get_nearest_by_numeric_key", "(", "STATUS_MAP", ",", "int", "(", "info", ...
Apply status mapping to a raw API result.
[ "Apply", "status", "mapping", "to", "a", "raw", "API", "result", "." ]
python
train
amzn/ion-python
amazon/ion/reader_text.py
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader_text.py#L1222-L1302
def _symbol_or_keyword_handler(c, ctx, is_field_name=False): """Handles the start of an unquoted text token. This may be an operator (if in an s-expression), an identifier symbol, or a keyword. """ in_sexp = ctx.container.ion_type is IonType.SEXP if c not in _IDENTIFIER_STARTS: if in_sexp and c in _OPERATORS: c_next, _ = yield ctx.queue.unread(c_next) yield ctx.immediate_transition(_operator_symbol_handler(c, ctx)) _illegal_character(c, ctx) assert not ctx.value ctx.set_unicode().set_ion_type(IonType.SYMBOL) val = ctx.value val.append(c) maybe_null = c == _N_LOWER maybe_nan = maybe_null maybe_true = c == _T_LOWER maybe_false = c == _F_LOWER c, self = yield trans = ctx.immediate_transition(self) keyword_trans = None match_index = 0 while True: def check_keyword(name, keyword_sequence, ion_type, value, match_transition=lambda: None): maybe_keyword = True transition = None if match_index < len(keyword_sequence): maybe_keyword = c == keyword_sequence[match_index] else: transition = match_transition() if transition is not None: pass elif _ends_value(c): if is_field_name: _illegal_character(c, ctx, '%s keyword as field name not allowed.' % (name,)) transition = ctx.event_transition(IonEvent, IonEventType.SCALAR, ion_type, value) elif c == _COLON: message = '' if is_field_name: message = '%s keyword as field name not allowed.' % (name,) _illegal_character(c, ctx, message) elif in_sexp and c in _OPERATORS: transition = ctx.event_transition(IonEvent, IonEventType.SCALAR, ion_type, value) else: maybe_keyword = False return maybe_keyword, transition if maybe_null: def check_null_dot(): transition = None found = c == _DOT if found: if is_field_name: _illegal_character(c, ctx, "Illegal character in field name.") transition = ctx.immediate_transition(_typed_null_handler(c, ctx)) return transition maybe_null, keyword_trans = check_keyword('null', _NULL_SUFFIX.sequence, IonType.NULL, None, check_null_dot) if maybe_nan: maybe_nan, keyword_trans = check_keyword('nan', _NAN_SUFFIX, IonType.FLOAT, _NAN) elif maybe_true: maybe_true, keyword_trans = check_keyword('true', _TRUE_SUFFIX, IonType.BOOL, True) elif maybe_false: maybe_false, keyword_trans = check_keyword('false', _FALSE_SUFFIX, IonType.BOOL, False) if maybe_null or maybe_nan or maybe_true or maybe_false: if keyword_trans is not None: trans = keyword_trans else: val.append(c) match_index += 1 else: if c in _SYMBOL_TOKEN_TERMINATORS: # This might be an annotation or a field name ctx.set_pending_symbol(val) trans = ctx.immediate_transition(ctx.whence) elif _ends_value(c) or (in_sexp and c in _OPERATORS): trans = ctx.event_transition(IonEvent, IonEventType.SCALAR, IonType.SYMBOL, val.as_symbol()) else: trans = ctx.immediate_transition(_unquoted_symbol_handler(c, ctx, is_field_name=is_field_name)) c, _ = yield trans
[ "def", "_symbol_or_keyword_handler", "(", "c", ",", "ctx", ",", "is_field_name", "=", "False", ")", ":", "in_sexp", "=", "ctx", ".", "container", ".", "ion_type", "is", "IonType", ".", "SEXP", "if", "c", "not", "in", "_IDENTIFIER_STARTS", ":", "if", "in_se...
Handles the start of an unquoted text token. This may be an operator (if in an s-expression), an identifier symbol, or a keyword.
[ "Handles", "the", "start", "of", "an", "unquoted", "text", "token", "." ]
python
train
chimpler/pyhocon
pyhocon/config_tree.py
https://github.com/chimpler/pyhocon/blob/e5b22a8e74e8f88e43cf9e9140cca5f2cd0ab4a3/pyhocon/config_tree.py#L319-L344
def get_list(self, key, default=UndefinedKey): """Return list representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: list :return: list value :type return: list """ value = self.get(key, default) if isinstance(value, list): return value elif isinstance(value, ConfigTree): lst = [] for k, v in sorted(value.items(), key=lambda kv: kv[0]): if re.match('^[1-9][0-9]*$|0', k): lst.append(v) else: raise ConfigException(u"{key} does not translate to a list".format(key=key)) return lst elif value is None: return None else: raise ConfigException( u"{key} has type '{type}' rather than 'list'".format(key=key, type=type(value).__name__))
[ "def", "get_list", "(", "self", ",", "key", ",", "default", "=", "UndefinedKey", ")", ":", "value", "=", "self", ".", "get", "(", "key", ",", "default", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "value", "elif", "isinsta...
Return list representation of value found at key :param key: key to use (dot separated). E.g., a.b.c :type key: basestring :param default: default value if key not found :type default: list :return: list value :type return: list
[ "Return", "list", "representation", "of", "value", "found", "at", "key" ]
python
train
raamana/hiwenet
hiwenet/utils.py
https://github.com/raamana/hiwenet/blob/b12699b3722fd0a6a835e7d7ca4baf58fb181809/hiwenet/utils.py#L25-L37
def preprocess_histogram(hist, values, edges): """Handles edge-cases and extremely-skewed histograms""" # working with extremely skewed histograms if np.count_nonzero(hist) == 0: # all of them above upper bound if np.all(values >= edges[-1]): hist[-1] = 1 # all of them below lower bound elif np.all(values <= edges[0]): hist[0] = 1 return hist
[ "def", "preprocess_histogram", "(", "hist", ",", "values", ",", "edges", ")", ":", "# working with extremely skewed histograms", "if", "np", ".", "count_nonzero", "(", "hist", ")", "==", "0", ":", "# all of them above upper bound", "if", "np", ".", "all", "(", "...
Handles edge-cases and extremely-skewed histograms
[ "Handles", "edge", "-", "cases", "and", "extremely", "-", "skewed", "histograms" ]
python
train
Dynatrace/OneAgent-SDK-for-Python
src/oneagent/__init__.py
https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/__init__.py#L172-L205
def initialize(sdkopts=(), sdklibname=None): '''Attempts to initialize the SDK with the specified options. Even if initialization fails, a dummy SDK will be available so that SDK functions can be called but will do nothing. If you call this function multiple times, you must call :func:`shutdown` just as many times. The options from all but the first :code:`initialize` call will be ignored (the return value will have the :data:`InitResult.STATUS_ALREADY_INITIALIZED` status code in that case). :param sdkopts: A sequence of strings of the form :samp:`{NAME}={VALUE}` that set the given SDK options. Igored in all but the first :code:`initialize` call. :type sdkopts: ~typing.Iterable[str] :param str sdklibname: The file or directory name of the native C SDK DLL. If None, the shared library packaged directly with the agent is used. Using a value other than None is only acceptable for debugging. You are responsible for providing a native SDK version that matches the Python SDK version. :rtype: .InitResult ''' global _sdk_ref_count #pylint:disable=global-statement global _sdk_instance #pylint:disable=global-statement with _sdk_ref_lk: logger.debug("initialize: ref count = %d", _sdk_ref_count) result = _try_init_noref(sdkopts, sdklibname) if _sdk_instance is None: _sdk_instance = SDK(try_get_sdk()) _sdk_ref_count += 1 return result
[ "def", "initialize", "(", "sdkopts", "=", "(", ")", ",", "sdklibname", "=", "None", ")", ":", "global", "_sdk_ref_count", "#pylint:disable=global-statement", "global", "_sdk_instance", "#pylint:disable=global-statement", "with", "_sdk_ref_lk", ":", "logger", ".", "deb...
Attempts to initialize the SDK with the specified options. Even if initialization fails, a dummy SDK will be available so that SDK functions can be called but will do nothing. If you call this function multiple times, you must call :func:`shutdown` just as many times. The options from all but the first :code:`initialize` call will be ignored (the return value will have the :data:`InitResult.STATUS_ALREADY_INITIALIZED` status code in that case). :param sdkopts: A sequence of strings of the form :samp:`{NAME}={VALUE}` that set the given SDK options. Igored in all but the first :code:`initialize` call. :type sdkopts: ~typing.Iterable[str] :param str sdklibname: The file or directory name of the native C SDK DLL. If None, the shared library packaged directly with the agent is used. Using a value other than None is only acceptable for debugging. You are responsible for providing a native SDK version that matches the Python SDK version. :rtype: .InitResult
[ "Attempts", "to", "initialize", "the", "SDK", "with", "the", "specified", "options", "." ]
python
train
svinota/mdns
mdns/zeroconf.py
https://github.com/svinota/mdns/blob/295f6407132616a0ff7401124b9057d89555f91d/mdns/zeroconf.py#L723-L734
def read_questions(self): """Reads questions section of packet""" format = '!HH' length = struct.calcsize(format) for i in range(0, self.num_questions): name = self.read_name() info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length question = DNSQuestion(name, info[0], info[1]) self.questions.append(question)
[ "def", "read_questions", "(", "self", ")", ":", "format", "=", "'!HH'", "length", "=", "struct", ".", "calcsize", "(", "format", ")", "for", "i", "in", "range", "(", "0", ",", "self", ".", "num_questions", ")", ":", "name", "=", "self", ".", "read_na...
Reads questions section of packet
[ "Reads", "questions", "section", "of", "packet" ]
python
train
glormph/msstitch
src/app/actions/pycolator/splitmerge.py
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/pycolator/splitmerge.py#L24-L37
def merge_peptides(fns, ns): """Loops peptides from multiple files, fetches PSMs from sequence:PSM map, outputs correctly PSM mapped peptides""" peptides_to_map = reader.generate_peptides_multiple_fractions(fns, ns) psmmap = create_merge_psm_map(peptides_to_map, ns) peptides = reader.generate_peptides_multiple_fractions(fns, ns) for peptide in peptides: seq = reader.get_peptide_seq(peptide, ns) psm_ids = reader.get_psm_ids_from_peptide(peptide, ns) # remove current psm ids, repopulate with stored ones psm_ids.clear() for new_psm_id in psmmap[seq]: etree.SubElement(psm_ids, 'psm_id').text = new_psm_id yield formatting.string_and_clear(peptide, ns)
[ "def", "merge_peptides", "(", "fns", ",", "ns", ")", ":", "peptides_to_map", "=", "reader", ".", "generate_peptides_multiple_fractions", "(", "fns", ",", "ns", ")", "psmmap", "=", "create_merge_psm_map", "(", "peptides_to_map", ",", "ns", ")", "peptides", "=", ...
Loops peptides from multiple files, fetches PSMs from sequence:PSM map, outputs correctly PSM mapped peptides
[ "Loops", "peptides", "from", "multiple", "files", "fetches", "PSMs", "from", "sequence", ":", "PSM", "map", "outputs", "correctly", "PSM", "mapped", "peptides" ]
python
train
bhmm/bhmm
bhmm/output_models/gaussian.py
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L170-L212
def p_obs(self, obs, out=None): """ Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- oobs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at time point t from any of the N hidden states Examples -------- Generate an observation model and synthetic observation trajectory. >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) >>> o_t = output_model.generate_observation_trajectory(s_t) Compute output probabilities for entire trajectory and all hidden states. >>> p_o = output_model.p_obs(o_t) """ if self.__impl__ == self.__IMPL_C__: res = gc.p_obs(obs, self.means, self.sigmas, out=out, dtype=config.dtype) return self._handle_outliers(res) elif self.__impl__ == self.__IMPL_PYTHON__: T = len(obs) if out is None: res = np.zeros((T, self.nstates), dtype=config.dtype) else: res = out for t in range(T): res[t, :] = self._p_o(obs[t]) return self._handle_outliers(res) else: raise RuntimeError('Implementation '+str(self.__impl__)+' not available')
[ "def", "p_obs", "(", "self", ",", "obs", ",", "out", "=", "None", ")", ":", "if", "self", ".", "__impl__", "==", "self", ".", "__IMPL_C__", ":", "res", "=", "gc", ".", "p_obs", "(", "obs", ",", "self", ".", "means", ",", "self", ".", "sigmas", ...
Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- oobs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at time point t from any of the N hidden states Examples -------- Generate an observation model and synthetic observation trajectory. >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) >>> o_t = output_model.generate_observation_trajectory(s_t) Compute output probabilities for entire trajectory and all hidden states. >>> p_o = output_model.p_obs(o_t)
[ "Returns", "the", "output", "probabilities", "for", "an", "entire", "trajectory", "and", "all", "hidden", "states" ]
python
train
ChrisCummins/labm8
lockfile.py
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/lockfile.py#L186-L205
def read(path): """ Read the contents of a LockFile. Arguments: path (str): Path to lockfile. Returns: Tuple(int, datetime): The integer PID of the lock owner, and the date the lock was required. If the lock is not claimed, both values are None. """ if fs.exists(path): with open(path) as infile: components = infile.read().split() pid = int(components[0]) date = datetime.date.fromtimestamp(float(components[1])) return pid, date else: return None, None
[ "def", "read", "(", "path", ")", ":", "if", "fs", ".", "exists", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "infile", ":", "components", "=", "infile", ".", "read", "(", ")", ".", "split", "(", ")", "pid", "=", "int", "(", ...
Read the contents of a LockFile. Arguments: path (str): Path to lockfile. Returns: Tuple(int, datetime): The integer PID of the lock owner, and the date the lock was required. If the lock is not claimed, both values are None.
[ "Read", "the", "contents", "of", "a", "LockFile", "." ]
python
train
fedora-infra/fedmsg
fedmsg/config.py
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/config.py#L1149-L1152
def _load_defaults(self): """Iterate over self._defaults and set all default values on self.""" for k, v in self._defaults.items(): self[k] = v['default']
[ "def", "_load_defaults", "(", "self", ")", ":", "for", "k", ",", "v", "in", "self", ".", "_defaults", ".", "items", "(", ")", ":", "self", "[", "k", "]", "=", "v", "[", "'default'", "]" ]
Iterate over self._defaults and set all default values on self.
[ "Iterate", "over", "self", ".", "_defaults", "and", "set", "all", "default", "values", "on", "self", "." ]
python
train
hsolbrig/PyShEx
pyshex/shape_expressions_language/p5_3_shape_expressions.py
https://github.com/hsolbrig/PyShEx/blob/9d659cc36e808afd66d4a6d60e8ea21cb12eb744/pyshex/shape_expressions_language/p5_3_shape_expressions.py#L79-L89
def satisfiesExternal(cntxt: Context, n: Node, se: ShExJ.ShapeExternal, c: DebugContext) -> bool: """ Se is a ShapeExternal and implementation-specific mechansims not defined in this specification indicate success. """ if c.debug: print(f"id: {se.id}") extern_shape = cntxt.external_shape_for(se.id) if extern_shape: return satisfies(cntxt, n, extern_shape) cntxt.fail_reason = f"{se.id}: Shape is not in Schema" return False
[ "def", "satisfiesExternal", "(", "cntxt", ":", "Context", ",", "n", ":", "Node", ",", "se", ":", "ShExJ", ".", "ShapeExternal", ",", "c", ":", "DebugContext", ")", "->", "bool", ":", "if", "c", ".", "debug", ":", "print", "(", "f\"id: {se.id}\"", ")", ...
Se is a ShapeExternal and implementation-specific mechansims not defined in this specification indicate success.
[ "Se", "is", "a", "ShapeExternal", "and", "implementation", "-", "specific", "mechansims", "not", "defined", "in", "this", "specification", "indicate", "success", "." ]
python
train
jjkester/django-auditlog
src/auditlog/registry.py
https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/registry.py#L97-L102
def _disconnect_signals(self, model): """ Disconnect signals for the model. """ for signal, receiver in self._signals.items(): signal.disconnect(sender=model, dispatch_uid=self._dispatch_uid(signal, model))
[ "def", "_disconnect_signals", "(", "self", ",", "model", ")", ":", "for", "signal", ",", "receiver", "in", "self", ".", "_signals", ".", "items", "(", ")", ":", "signal", ".", "disconnect", "(", "sender", "=", "model", ",", "dispatch_uid", "=", "self", ...
Disconnect signals for the model.
[ "Disconnect", "signals", "for", "the", "model", "." ]
python
train
m32/endesive
endesive/pdf/fpdf/fpdf.py
https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L339-L345
def set_text_color(self, r,g=-1,b=-1): "Set color for text" if((r==0 and g==0 and b==0) or g==-1): self.text_color=sprintf('%.3f g',r/255.0) else: self.text_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0) self.color_flag=(self.fill_color!=self.text_color)
[ "def", "set_text_color", "(", "self", ",", "r", ",", "g", "=", "-", "1", ",", "b", "=", "-", "1", ")", ":", "if", "(", "(", "r", "==", "0", "and", "g", "==", "0", "and", "b", "==", "0", ")", "or", "g", "==", "-", "1", ")", ":", "self", ...
Set color for text
[ "Set", "color", "for", "text" ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/triangulation.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/triangulation.py#L601-L607
def _intersected_edge(self, edges, cut_edge): """ Given a list of *edges*, return the first that is intersected by *cut_edge*. """ for edge in edges: if self._edges_intersect(edge, cut_edge): return edge
[ "def", "_intersected_edge", "(", "self", ",", "edges", ",", "cut_edge", ")", ":", "for", "edge", "in", "edges", ":", "if", "self", ".", "_edges_intersect", "(", "edge", ",", "cut_edge", ")", ":", "return", "edge" ]
Given a list of *edges*, return the first that is intersected by *cut_edge*.
[ "Given", "a", "list", "of", "*", "edges", "*", "return", "the", "first", "that", "is", "intersected", "by", "*", "cut_edge", "*", "." ]
python
train
datadotworld/data.world-py
datadotworld/client/_swagger/apis/user_api.py
https://github.com/datadotworld/data.world-py/blob/ffaeb115f358731ab0b805b0c43b7ff2e3cf0a77/datadotworld/client/_swagger/apis/user_api.py#L43-L68
def fetch_contributing_datasets(self, **kwargs): """ List datasets as contributor Fetch datasets that the currently authenticated user has access to because he or she is a contributor. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.fetch_contributing_datasets(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str limit: Maximum number of items to include in a page of results. :param str next: Token from previous result page to be used when requesting a subsequent page. :return: PaginatedDatasetResults If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.fetch_contributing_datasets_with_http_info(**kwargs) else: (data) = self.fetch_contributing_datasets_with_http_info(**kwargs) return data
[ "def", "fetch_contributing_datasets", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "fetch_contributing_datasets_with_h...
List datasets as contributor Fetch datasets that the currently authenticated user has access to because he or she is a contributor. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.fetch_contributing_datasets(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str limit: Maximum number of items to include in a page of results. :param str next: Token from previous result page to be used when requesting a subsequent page. :return: PaginatedDatasetResults If the method is called asynchronously, returns the request thread.
[ "List", "datasets", "as", "contributor", "Fetch", "datasets", "that", "the", "currently", "authenticated", "user", "has", "access", "to", "because", "he", "or", "she", "is", "a", "contributor", ".", "This", "method", "makes", "a", "synchronous", "HTTP", "reque...
python
train
saltstack/salt
salt/utils/jid.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jid.py#L102-L108
def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret
[ "def", "format_jid_instance", "(", "jid", ",", "job", ")", ":", "ret", "=", "format_job_instance", "(", "job", ")", "ret", ".", "update", "(", "{", "'StartTime'", ":", "jid_to_time", "(", "jid", ")", "}", ")", "return", "ret" ]
Format the jid correctly
[ "Format", "the", "jid", "correctly" ]
python
train
bitesofcode/projexui
projexui/widgets/xnodewidget/xnode.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnode.py#L469-L485
def connectTo( self, node, cls = None ): """ Creates a connection between this node and the inputed node. :param node | <XNode> cls | <subclass of XNodeConnection> || None :return <XNodeConnection> """ if ( not node ): return con = self.scene().addConnection(cls) con.setOutputNode(self) con.setInputNode(node) return con
[ "def", "connectTo", "(", "self", ",", "node", ",", "cls", "=", "None", ")", ":", "if", "(", "not", "node", ")", ":", "return", "con", "=", "self", ".", "scene", "(", ")", ".", "addConnection", "(", "cls", ")", "con", ".", "setOutputNode", "(", "s...
Creates a connection between this node and the inputed node. :param node | <XNode> cls | <subclass of XNodeConnection> || None :return <XNodeConnection>
[ "Creates", "a", "connection", "between", "this", "node", "and", "the", "inputed", "node", ".", ":", "param", "node", "|", "<XNode", ">", "cls", "|", "<subclass", "of", "XNodeConnection", ">", "||", "None", ":", "return", "<XNodeConnection", ">" ]
python
train
sebdah/dynamic-dynamodb
dynamic_dynamodb/__init__.py
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/__init__.py#L107-L224
def execute(): """ Ensure provisioning """ boto_server_error_retries = 3 # Ensure provisioning for table_name, table_key in sorted(dynamodb.get_tables_and_gsis()): try: table_num_consec_read_checks = \ CHECK_STATUS['tables'][table_name]['reads'] except KeyError: table_num_consec_read_checks = 0 try: table_num_consec_write_checks = \ CHECK_STATUS['tables'][table_name]['writes'] except KeyError: table_num_consec_write_checks = 0 try: # The return var shows how many times the scale-down criteria # has been met. This is coupled with a var in config, # "num_intervals_scale_down", to delay the scale-down table_num_consec_read_checks, table_num_consec_write_checks = \ table.ensure_provisioning( table_name, table_key, table_num_consec_read_checks, table_num_consec_write_checks) CHECK_STATUS['tables'][table_name] = { 'reads': table_num_consec_read_checks, 'writes': table_num_consec_write_checks } gsi_names = set() # Add regexp table names for gst_instance in dynamodb.table_gsis(table_name): gsi_name = gst_instance[u'IndexName'] try: gsi_keys = get_table_option(table_key, 'gsis').keys() except AttributeError: # Continue if there are not GSIs configured continue for gsi_key in gsi_keys: try: if re.match(gsi_key, gsi_name): logger.debug( 'Table {0} GSI {1} matches ' 'GSI config key {2}'.format( table_name, gsi_name, gsi_key)) gsi_names.add((gsi_name, gsi_key)) except re.error: logger.error('Invalid regular expression: "{0}"'.format( gsi_key)) sys.exit(1) for gsi_name, gsi_key in sorted(gsi_names): unique_gsi_name = ':'.join([table_name, gsi_name]) try: gsi_num_consec_read_checks = \ CHECK_STATUS['gsis'][unique_gsi_name]['reads'] except KeyError: gsi_num_consec_read_checks = 0 try: gsi_num_consec_write_checks = \ CHECK_STATUS['gsis'][unique_gsi_name]['writes'] except KeyError: gsi_num_consec_write_checks = 0 gsi_num_consec_read_checks, gsi_num_consec_write_checks = \ gsi.ensure_provisioning( table_name, table_key, gsi_name, gsi_key, gsi_num_consec_read_checks, gsi_num_consec_write_checks) CHECK_STATUS['gsis'][unique_gsi_name] = { 'reads': gsi_num_consec_read_checks, 'writes': gsi_num_consec_write_checks } except JSONResponseError as error: exception = error.body['__type'].split('#')[1] if exception == 'ResourceNotFoundException': logger.error('{0} - Table {1} does not exist anymore'.format( table_name, table_name)) continue except BotoServerError as error: if boto_server_error_retries > 0: logger.error( 'Unknown boto error. Status: "{0}". ' 'Reason: "{1}". Message: {2}'.format( error.status, error.reason, error.message)) logger.error( 'Please bug report if this error persists') boto_server_error_retries -= 1 continue else: raise # Sleep between the checks if not get_global_option('run_once'): logger.debug('Sleeping {0} seconds until next check'.format( get_global_option('check_interval'))) time.sleep(get_global_option('check_interval'))
[ "def", "execute", "(", ")", ":", "boto_server_error_retries", "=", "3", "# Ensure provisioning", "for", "table_name", ",", "table_key", "in", "sorted", "(", "dynamodb", ".", "get_tables_and_gsis", "(", ")", ")", ":", "try", ":", "table_num_consec_read_checks", "="...
Ensure provisioning
[ "Ensure", "provisioning" ]
python
train
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L501-L627
async def handle_job_closing(self, container_id, retval): """ Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the backend """ try: self._logger.debug("Closing %s", container_id) try: message, container_path, future_results = self._containers_running[container_id] del self._containers_running[container_id] except asyncio.CancelledError: raise except: self._logger.warning("Container %s that has finished(p1) was not launched by this agent", str(container_id), exc_info=True) return # Close sub containers for student_container_id_loop in self._student_containers_for_job[message.job_id]: # little hack to ensure the value of student_container_id_loop is copied into the closure async def close_and_delete(student_container_id=student_container_id_loop): try: await self._docker.kill_container(student_container_id) await self._docker.remove_container(student_container_id) except asyncio.CancelledError: raise except: pass # ignore self._create_safe_task(close_and_delete(student_container_id_loop)) del self._student_containers_for_job[message.job_id] # Allow other container to reuse the external ports this container has finished to use if container_id in self._assigned_external_ports: for p in self._assigned_external_ports[container_id]: self._external_ports.add(p) del self._assigned_external_ports[container_id] # Verify if the container was killed, either by the client, by an OOM or by a timeout killed = await self._timeout_watcher.was_killed(container_id) if container_id in self._containers_killed: killed = self._containers_killed[container_id] del self._containers_killed[container_id] stdout = "" stderr = "" result = "crash" if retval == -1 else None error_msg = None grade = None problems = {} custom = {} tests = {} archive = None state = "" if killed is not None: result = killed # If everything did well, continue to retrieve the status from the container if result is None: # Get logs back try: return_value = await future_results # Accepted types for return dict accepted_types = {"stdout": str, "stderr": str, "result": str, "text": str, "grade": float, "problems": dict, "custom": dict, "tests": dict, "state": str, "archive": str} keys_fct = {"problems": id_checker, "custom": id_checker, "tests": id_checker_tests} # Check dict content for key, item in return_value.items(): if not isinstance(item, accepted_types[key]): raise Exception("Feedback file is badly formatted.") elif accepted_types[key] == dict and key != "custom": #custom can contain anything: for sub_key, sub_item in item.items(): if not keys_fct[key](sub_key) or isinstance(sub_item, dict): raise Exception("Feedback file is badly formatted.") # Set output fields stdout = return_value.get("stdout", "") stderr = return_value.get("stderr", "") result = return_value.get("result", "error") error_msg = return_value.get("text", "") grade = return_value.get("grade", None) problems = return_value.get("problems", {}) custom = return_value.get("custom", {}) tests = return_value.get("tests", {}) state = return_value.get("state", "") archive = return_value.get("archive", None) if archive is not None: archive = base64.b64decode(archive) except Exception as e: self._logger.exception("Cannot get back output of container %s! (%s)", container_id, str(e)) result = "crash" error_msg = 'The grader did not return a readable output : {}'.format(str(e)) # Default values if error_msg is None: error_msg = "" if grade is None: if result == "success": grade = 100.0 else: grade = 0.0 # Remove container try: await self._docker.remove_container(container_id) except asyncio.CancelledError: raise except: pass # Delete folders try: await self._ashutil.rmtree(container_path) except PermissionError: self._logger.debug("Cannot remove old container path!") pass # todo: run a docker container to force removal # Return! await self.send_job_result(message.job_id, result, error_msg, grade, problems, tests, custom, state, archive, stdout, stderr) # Do not forget to remove data from internal state del self._container_for_job[message.job_id] except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_job_closing")
[ "async", "def", "handle_job_closing", "(", "self", ",", "container_id", ",", "retval", ")", ":", "try", ":", "self", ".", "_logger", ".", "debug", "(", "\"Closing %s\"", ",", "container_id", ")", "try", ":", "message", ",", "container_path", ",", "future_res...
Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the backend
[ "Handle", "a", "closing", "student", "container", ".", "Do", "some", "cleaning", "verify", "memory", "limits", "timeouts", "...", "and", "returns", "data", "to", "the", "backend" ]
python
train
saltstack/salt
salt/states/bigip.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/bigip.py#L1269-L1355
def add_pool_member(hostname, username, password, name, member): ''' A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The member to add to the pool ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: return _test_output(ret, 'add', params={ 'hostname': hostname, 'username': username, 'password': password, 'name': name, 'members': member } ) #is this pool member currently configured? existing_pool = __salt__['bigip.list_pool'](hostname, username, password, name) if existing_pool['code'] == 200: # for some reason iControl REST doesn't support listing a single pool member. # the response from GET for listing a member will return 200 even if it doesn't exists. # because of this we have to do some rather "unnecessary" searching within a pool. #what are the current members? current_members = existing_pool['content']['membersReference']['items'] #loop through them exists = False for current_member in current_members: if current_member['name'] == member['name']: exists = True break if exists: ret['result'] = True ret['comment'] = 'Member: {name} already exists within this pool. No changes made.'.format(name=member['name']) ret['changes']['old'] = {} ret['changes']['new'] = {} else: new_member = __salt__['bigip.add_pool_member'](hostname, username, password, name, member) if new_member['code'] == 200: ret['result'] = True ret['comment'] = 'Member: {name} has been successfully added to the pool.'.format(name=member['name']) ret['changes']['old'] = {} #look up the member again... pool_listing = __salt__['bigip.list_pool'](hostname, username, password, name) if pool_listing['code'] != 200: ret = _load_result(new_member, ret) return ret members = pool_listing['content']['membersReference']['items'] #loop through them for current_member in members: if current_member['name'] == member['name']: added_member = current_member break ret['changes']['new'] = added_member # member wasn't added else: ret = _load_result(new_member, ret) #pool does not exists elif existing_pool['code'] == 404: ret['comment'] = 'A pool with this name was not found.' else: ret = _load_result(existing_pool, ret) return ret
[ "def", "add_pool_member", "(", "hostname", ",", "username", ",", "password", ",", "name", ",", "member", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}...
A function to connect to a bigip device and add a new member to an existing pool. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify member The member to add to the pool
[ "A", "function", "to", "connect", "to", "a", "bigip", "device", "and", "add", "a", "new", "member", "to", "an", "existing", "pool", "." ]
python
train
sepandhaghighi/pycm
pycm/pycm_util.py
https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L329-L343
def statistic_recommend(classes, P): """ Return recommend parameters which are more suitable due to the input dataset characteristics. :param classes: all classes name :type classes : list :param P: condition positive :type P : dict :return: recommendation_list as list """ if imbalance_check(P): return IMBALANCED_RECOMMEND if binary_check(classes): return BINARY_RECOMMEND return MULTICLASS_RECOMMEND
[ "def", "statistic_recommend", "(", "classes", ",", "P", ")", ":", "if", "imbalance_check", "(", "P", ")", ":", "return", "IMBALANCED_RECOMMEND", "if", "binary_check", "(", "classes", ")", ":", "return", "BINARY_RECOMMEND", "return", "MULTICLASS_RECOMMEND" ]
Return recommend parameters which are more suitable due to the input dataset characteristics. :param classes: all classes name :type classes : list :param P: condition positive :type P : dict :return: recommendation_list as list
[ "Return", "recommend", "parameters", "which", "are", "more", "suitable", "due", "to", "the", "input", "dataset", "characteristics", "." ]
python
train
dhocker/udmx-pyusb
uDMX.py
https://github.com/dhocker/udmx-pyusb/blob/ee7d10604ecd83857154ed6739793de3b7bd5fc1/uDMX.py#L176-L234
def load_rc_file(): """ Load the contents of the resource file ~/.uDMXrc """ # If an rc file is named in the config, use it. # Otherwise, fall back to looking in the HOME directory. # The fall back won't work under RPi because HOME will be root. if "uDMXrc" in config: rcfile = config["uDMXrc"] else: if os.name == "nt": # Windows rcfile = os.path.join(os.environ["USERPROFILE"], ".uDMXrc") else: # Mostly *nix type systems rcfile = os.path.join(os.environ["HOME"], ".uDMXrc") try: cf = open(rcfile, 'r') for line in cf: tokens = line.split() # Blank line if len(tokens) == 0: continue # A comment if tokens[0] == '#': continue # A channel alias elif tokens[0] == 'channel': # channel alias value if len(tokens) >= 3: if is_valid_channel(tokens[2]): add_channel(tokens[1], tokens[2]) else: print(line) print("Invalid channel value") else: print(line) print("Invalid channel statement") # A DMX value or values elif tokens[0] in ['value', 'values']: # value alias value if len(tokens) >= 3: if are_valid_values(tokens[2:]): add_values(tokens[1], tokens[2:]) else: print(line) print("Invalid value(s)") else: print(line) print("Invalid value statement") # Something we don't recognize else: print(line) print(tokens[0], "is not a recognized resource file statement") cf.close() except: print("Unable to open resource file", rcfile)
[ "def", "load_rc_file", "(", ")", ":", "# If an rc file is named in the config, use it.", "# Otherwise, fall back to looking in the HOME directory.", "# The fall back won't work under RPi because HOME will be root.", "if", "\"uDMXrc\"", "in", "config", ":", "rcfile", "=", "config", "[...
Load the contents of the resource file ~/.uDMXrc
[ "Load", "the", "contents", "of", "the", "resource", "file", "~", "/", ".", "uDMXrc" ]
python
train
jobovy/galpy
galpy/util/multi.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/multi.py#L53-L79
def worker(f, ii, chunk, out_q, err_q, lock): """ A worker function that maps an input function over a slice of the input iterable. :param f : callable function that accepts argument from iterable :param ii : process ID :param chunk: slice of input iterable :param out_q: thread-safe output queue :param err_q: thread-safe queue to populate on exception :param lock : thread-safe lock to protect a resource ( useful in extending parallel_map() ) """ vals = [] # iterate over slice for val in chunk: try: result = f(val) except Exception as e: err_q.put(e) return vals.append(result) # output the result and task ID to output queue out_q.put( (ii, vals) )
[ "def", "worker", "(", "f", ",", "ii", ",", "chunk", ",", "out_q", ",", "err_q", ",", "lock", ")", ":", "vals", "=", "[", "]", "# iterate over slice ", "for", "val", "in", "chunk", ":", "try", ":", "result", "=", "f", "(", "val", ")", "except", "E...
A worker function that maps an input function over a slice of the input iterable. :param f : callable function that accepts argument from iterable :param ii : process ID :param chunk: slice of input iterable :param out_q: thread-safe output queue :param err_q: thread-safe queue to populate on exception :param lock : thread-safe lock to protect a resource ( useful in extending parallel_map() )
[ "A", "worker", "function", "that", "maps", "an", "input", "function", "over", "a", "slice", "of", "the", "input", "iterable", "." ]
python
train
agoragames/haigha
haigha/classes/exchange_class.py
https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/classes/exchange_class.py#L34-L40
def _cleanup(self): ''' Cleanup local data. ''' self._declare_cb = None self._delete_cb = None super(ExchangeClass, self)._cleanup()
[ "def", "_cleanup", "(", "self", ")", ":", "self", ".", "_declare_cb", "=", "None", "self", ".", "_delete_cb", "=", "None", "super", "(", "ExchangeClass", ",", "self", ")", ".", "_cleanup", "(", ")" ]
Cleanup local data.
[ "Cleanup", "local", "data", "." ]
python
train
Qiskit/qiskit-terra
qiskit/pulse/timeslots.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/timeslots.py#L59-L70
def has_overlap(self, interval: 'Interval') -> bool: """Check if self has overlap with `interval`. Args: interval: interval to be examined Returns: bool: True if self has overlap with `interval` otherwise False """ if self.begin < interval.end and interval.begin < self.end: return True return False
[ "def", "has_overlap", "(", "self", ",", "interval", ":", "'Interval'", ")", "->", "bool", ":", "if", "self", ".", "begin", "<", "interval", ".", "end", "and", "interval", ".", "begin", "<", "self", ".", "end", ":", "return", "True", "return", "False" ]
Check if self has overlap with `interval`. Args: interval: interval to be examined Returns: bool: True if self has overlap with `interval` otherwise False
[ "Check", "if", "self", "has", "overlap", "with", "interval", "." ]
python
test
bearyinnovative/bearychat.py
bearychat/rtm_client.py
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L72-L108
def do(self, resource, method, params=None, data=None, json=None, headers=None): """Does the request job Args: resource(str): resource uri(relative path) method(str): HTTP method params(dict): uri queries data(dict): HTTP body(form) json(dict): HTTP body(json) headers(dict): HTTP headers Returns: RTMResponse """ uri = "{0}/{1}".format(self._api_base, resource) if not params: params = {} params.update({'token': self._token}) req = Request( method=method, url=uri, params=params, headers=headers, data=data, json=json) s = Session() prepped = s.prepare_request(req) resp = s.send(prepped) return RTMResponse(resp)
[ "def", "do", "(", "self", ",", "resource", ",", "method", ",", "params", "=", "None", ",", "data", "=", "None", ",", "json", "=", "None", ",", "headers", "=", "None", ")", ":", "uri", "=", "\"{0}/{1}\"", ".", "format", "(", "self", ".", "_api_base"...
Does the request job Args: resource(str): resource uri(relative path) method(str): HTTP method params(dict): uri queries data(dict): HTTP body(form) json(dict): HTTP body(json) headers(dict): HTTP headers Returns: RTMResponse
[ "Does", "the", "request", "job" ]
python
train
nicolargo/glances
glances/outputs/glances_bottle.py
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/outputs/glances_bottle.py#L435-L456
def _api_views(self, plugin): """Glances API RESTful implementation. Return the JSON views of a given plugin HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error """ response.content_type = 'application/json; charset=utf-8' if plugin not in self.plugins_list: abort(400, "Unknown plugin %s (available plugins: %s)" % (plugin, self.plugins_list)) # Update the stat # self.__update__() try: # Get the JSON value of the stat views ret = self.stats.get_plugin(plugin).get_views() except Exception as e: abort(404, "Cannot get views for plugin %s (%s)" % (plugin, str(e))) return ret
[ "def", "_api_views", "(", "self", ",", "plugin", ")", ":", "response", ".", "content_type", "=", "'application/json; charset=utf-8'", "if", "plugin", "not", "in", "self", ".", "plugins_list", ":", "abort", "(", "400", ",", "\"Unknown plugin %s (available plugins: %s...
Glances API RESTful implementation. Return the JSON views of a given plugin HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error
[ "Glances", "API", "RESTful", "implementation", "." ]
python
train
pazz/alot
alot/db/manager.py
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/manager.py#L271-L278
def _get_notmuch_thread(self, tid): """returns :class:`notmuch.database.Thread` with given id""" query = self.query('thread:' + tid) try: return next(query.search_threads()) except StopIteration: errmsg = 'no thread with id %s exists!' % tid raise NonexistantObjectError(errmsg)
[ "def", "_get_notmuch_thread", "(", "self", ",", "tid", ")", ":", "query", "=", "self", ".", "query", "(", "'thread:'", "+", "tid", ")", "try", ":", "return", "next", "(", "query", ".", "search_threads", "(", ")", ")", "except", "StopIteration", ":", "e...
returns :class:`notmuch.database.Thread` with given id
[ "returns", ":", "class", ":", "notmuch", ".", "database", ".", "Thread", "with", "given", "id" ]
python
train
psss/did
did/utils.py
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/utils.py#L160-L164
def ascii(text): """ Transliterate special unicode characters into pure ascii """ if not isinstance(text, unicode): text = unicode(text) return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
[ "def", "ascii", "(", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "text", "=", "unicode", "(", "text", ")", "return", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "text", ")", ".", "encode", "(", "'ascii...
Transliterate special unicode characters into pure ascii
[ "Transliterate", "special", "unicode", "characters", "into", "pure", "ascii" ]
python
train
flyte/upnpclient
upnpclient/soap.py
https://github.com/flyte/upnpclient/blob/5529b950df33c0eaf0c24a9a307cf00fe627d0ad/upnpclient/soap.py#L74-L146
def call(self, action_name, arg_in=None, http_auth=None, http_headers=None): """ Construct the XML and make the call to the device. Parse the response values into a dict. """ if arg_in is None: arg_in = {} soap_env = '{%s}' % NS_SOAP_ENV m = '{%s}' % self.service_type root = etree.Element(soap_env+'Envelope', nsmap={'SOAP-ENV': NS_SOAP_ENV}) root.attrib[soap_env+'encodingStyle'] = ENCODING_STYLE body = etree.SubElement(root, soap_env+'Body') action = etree.SubElement(body, m+action_name, nsmap={'m': self.service_type}) for key, value in arg_in.items(): etree.SubElement(action, key).text = str(value) body = etree.tostring(root, encoding=ENCODING, xml_declaration=True) headers = { 'SOAPAction': '"%s#%s"' % (self.service_type, action_name), 'Host': self._host, 'Content-Type': 'text/xml', 'Content-Length': str(len(body)), } headers.update(http_headers or {}) try: resp = requests.post( self.url, body, headers=headers, timeout=SOAP_TIMEOUT, auth=http_auth ) resp.raise_for_status() except requests.exceptions.HTTPError as exc: # If the body of the error response contains XML then it should be a UPnP error, # otherwise reraise the HTTPError. try: err_xml = etree.fromstring(exc.response.content) except etree.XMLSyntaxError: raise exc raise SOAPError(*self._extract_upnperror(err_xml)) xml_str = resp.content.strip() try: xml = etree.fromstring(xml_str) except etree.XMLSyntaxError: # Try removing any extra XML declarations in case there are more than one. # This sometimes happens when a device sends its own XML config files. xml = etree.fromstring(self._remove_extraneous_xml_declarations(xml_str)) except ValueError: # This can occur when requests returns a `str` (unicode) but there's also an XML # declaration, which lxml doesn't like. xml = etree.fromstring(xml_str.encode('utf8')) response = xml.find(".//{%s}%sResponse" % (self.service_type, action_name)) if response is None: msg = ('Returned XML did not include an element which matches namespace %r and tag name' ' \'%sResponse\'.' % (self.service_type, action_name)) self._log.debug(msg + '\n' + etree.tostring(xml, pretty_print=True).decode('utf8')) raise SOAPProtocolError(msg) # Sometimes devices return XML strings as their argument values without escaping them with # CDATA. This checks to see if the argument has been parsed as XML and un-parses it if so. ret = {} for arg in response.getchildren(): children = arg.getchildren() if children: ret[arg.tag] = b"\n".join(etree.tostring(x) for x in children) else: ret[arg.tag] = arg.text return ret
[ "def", "call", "(", "self", ",", "action_name", ",", "arg_in", "=", "None", ",", "http_auth", "=", "None", ",", "http_headers", "=", "None", ")", ":", "if", "arg_in", "is", "None", ":", "arg_in", "=", "{", "}", "soap_env", "=", "'{%s}'", "%", "NS_SOA...
Construct the XML and make the call to the device. Parse the response values into a dict.
[ "Construct", "the", "XML", "and", "make", "the", "call", "to", "the", "device", ".", "Parse", "the", "response", "values", "into", "a", "dict", "." ]
python
train
toumorokoshi/sprinter
sprinter/formula/perforce.py
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/perforce.py#L144-L164
def __install_perforce(self, config): """ install perforce binary """ if not system.is_64_bit(): self.logger.warn("Perforce formula is only designed for 64 bit systems! Not install executables...") return False version = config.get('version', 'r13.2') key = 'osx' if system.is_osx() else 'linux' perforce_packages = package_dict[version][key] d = self.directory.install_directory(self.feature_name) if not os.path.exists(d): os.makedirs(d) self.logger.info("Downloading p4 executable...") with open(os.path.join(d, "p4"), 'wb+') as fh: fh.write(lib.cleaned_request('get', url_prefix + perforce_packages['p4']).content) self.directory.symlink_to_bin("p4", os.path.join(d, "p4")) self.p4_command = os.path.join(d, "p4") self.logger.info("Installing p4v...") if system.is_osx(): return self._install_p4v_osx(url_prefix + perforce_packages['p4v']) else: return self._install_p4v_linux(url_prefix + perforce_packages['p4v'])
[ "def", "__install_perforce", "(", "self", ",", "config", ")", ":", "if", "not", "system", ".", "is_64_bit", "(", ")", ":", "self", ".", "logger", ".", "warn", "(", "\"Perforce formula is only designed for 64 bit systems! Not install executables...\"", ")", "return", ...
install perforce binary
[ "install", "perforce", "binary" ]
python
train