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
nathan-hoad/outbox
outbox.py
https://github.com/nathan-hoad/outbox/blob/afd28cd14023fdbcd40ad8925ea09c2a9b4d98cb/outbox.py#L174-L193
def send(self, email, attachments=()): '''Send an email. Connect/Disconnect if not already connected Arguments: email: Email instance to send. attachments: iterable containing Attachment instances ''' msg = email.as_mime(attachments) if 'From' not in msg: msg['From'] = self.sender_address() if self._conn: self._conn.sendmail(self.username, email.recipients, msg.as_string()) else: with self: self._conn.sendmail(self.username, email.recipients, msg.as_string())
[ "def", "send", "(", "self", ",", "email", ",", "attachments", "=", "(", ")", ")", ":", "msg", "=", "email", ".", "as_mime", "(", "attachments", ")", "if", "'From'", "not", "in", "msg", ":", "msg", "[", "'From'", "]", "=", "self", ".", "sender_addre...
Send an email. Connect/Disconnect if not already connected Arguments: email: Email instance to send. attachments: iterable containing Attachment instances
[ "Send", "an", "email", ".", "Connect", "/", "Disconnect", "if", "not", "already", "connected" ]
python
train
ethereum/pyethereum
ethereum/utils.py
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/utils.py#L449-L498
def print_func_call(ignore_first_arg=False, max_call_number=100): """ utility function to facilitate debug, it will print input args before function call, and print return value after function call usage: @print_func_call def some_func_to_be_debu(): pass :param ignore_first_arg: whether print the first arg or not. useful when ignore the `self` parameter of an object method call """ from functools import wraps def display(x): x = to_string(x) try: x.decode('ascii') except BaseException: return 'NON_PRINTABLE' return x local = {'call_number': 0} def inner(f): @wraps(f) def wrapper(*args, **kwargs): local['call_number'] += 1 tmp_args = args[1:] if ignore_first_arg and len(args) else args this_call_number = local['call_number'] print(('{0}#{1} args: {2}, {3}'.format( f.__name__, this_call_number, ', '.join([display(x) for x in tmp_args]), ', '.join(display(key) + '=' + to_string(value) for key, value in kwargs.items()) ))) res = f(*args, **kwargs) print(('{0}#{1} return: {2}'.format( f.__name__, this_call_number, display(res)))) if local['call_number'] > 100: raise Exception("Touch max call number!") return res return wrapper return inner
[ "def", "print_func_call", "(", "ignore_first_arg", "=", "False", ",", "max_call_number", "=", "100", ")", ":", "from", "functools", "import", "wraps", "def", "display", "(", "x", ")", ":", "x", "=", "to_string", "(", "x", ")", "try", ":", "x", ".", "de...
utility function to facilitate debug, it will print input args before function call, and print return value after function call usage: @print_func_call def some_func_to_be_debu(): pass :param ignore_first_arg: whether print the first arg or not. useful when ignore the `self` parameter of an object method call
[ "utility", "function", "to", "facilitate", "debug", "it", "will", "print", "input", "args", "before", "function", "call", "and", "print", "return", "value", "after", "function", "call" ]
python
train
KnuVerse/knuverse-sdk-python
knuverse/knufactor.py
https://github.com/KnuVerse/knuverse-sdk-python/blob/00f1275a452a4dcf9bc92ef345f6985504226d8e/knuverse/knufactor.py#L615-L624
def events_system(self): """ Get all system events. Uses GET to /events/system interface. :Returns: (list) Events """ # TODO Add paging to this response = self._get(url.events_system) self._check_response(response, 200) return self._create_response(response).get("events")
[ "def", "events_system", "(", "self", ")", ":", "# TODO Add paging to this", "response", "=", "self", ".", "_get", "(", "url", ".", "events_system", ")", "self", ".", "_check_response", "(", "response", ",", "200", ")", "return", "self", ".", "_create_response"...
Get all system events. Uses GET to /events/system interface. :Returns: (list) Events
[ "Get", "all", "system", "events", ".", "Uses", "GET", "to", "/", "events", "/", "system", "interface", "." ]
python
train
AtteqCom/zsl
src/zsl/application/service_application.py
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/service_application.py#L130-L143
def _get_app_module(self): # type: () -> Callable """Returns a module which binds the current app and configuration. :return: configuration callback :rtype: Callable """ def configure(binder): # type: (Binder) -> Callable binder.bind(ServiceApplication, to=self, scope=singleton) binder.bind(Config, to=self.config, scope=singleton) return configure
[ "def", "_get_app_module", "(", "self", ")", ":", "# type: () -> Callable", "def", "configure", "(", "binder", ")", ":", "# type: (Binder) -> Callable", "binder", ".", "bind", "(", "ServiceApplication", ",", "to", "=", "self", ",", "scope", "=", "singleton", ")",...
Returns a module which binds the current app and configuration. :return: configuration callback :rtype: Callable
[ "Returns", "a", "module", "which", "binds", "the", "current", "app", "and", "configuration", "." ]
python
train
pysathq/pysat
examples/rc2.py
https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L1463-L1520
def parse_options(): """ Parses command-line option """ try: opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx', ['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo', 'minimize', 'solver=', 'trim=', 'verbose']) except getopt.GetoptError as err: sys.stderr.write(str(err).capitalize()) usage() sys.exit(1) adapt = False exhaust = False cmode = None to_enum = 1 incr = False blo = False minz = False solver = 'g3' trim = 0 verbose = 1 for opt, arg in opts: if opt in ('-a', '--adapt'): adapt = True elif opt in ('-c', '--comp'): cmode = str(arg) elif opt in ('-e', '--enum'): to_enum = str(arg) if to_enum != 'all': to_enum = int(to_enum) else: to_enum = 0 elif opt in ('-h', '--help'): usage() sys.exit(0) elif opt in ('-i', '--incr'): incr = True elif opt in ('-l', '--blo'): blo = True elif opt in ('-m', '--minimize'): minz = True elif opt in ('-s', '--solver'): solver = str(arg) elif opt in ('-t', '--trim'): trim = int(arg) elif opt in ('-v', '--verbose'): verbose += 1 elif opt in ('-x', '--exhaust'): exhaust = True else: assert False, 'Unhandled option: {0} {1}'.format(opt, arg) return adapt, blo, cmode, to_enum, exhaust, incr, minz, solver, trim, \ verbose, args
[ "def", "parse_options", "(", ")", ":", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'ac:e:hilms:t:vx'", ",", "[", "'adapt'", ",", "'comp='", ",", "'enum='", ",", "'exhaust'", ",", ...
Parses command-line option
[ "Parses", "command", "-", "line", "option" ]
python
train
Kozea/pygal
pygal/util.py
https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/util.py#L75-L79
def round_to_scale(number, precision): """Round a number or a float to a precision""" if precision < 1: return round_to_float(number, precision) return round_to_int(number, precision)
[ "def", "round_to_scale", "(", "number", ",", "precision", ")", ":", "if", "precision", "<", "1", ":", "return", "round_to_float", "(", "number", ",", "precision", ")", "return", "round_to_int", "(", "number", ",", "precision", ")" ]
Round a number or a float to a precision
[ "Round", "a", "number", "or", "a", "float", "to", "a", "precision" ]
python
train
fermiPy/fermipy
fermipy/diffuse/residual_cr.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L192-L202
def _fill_masked_intensity_resid(intensity_resid, bright_pixel_mask): """ Fill the pixels used to compute the effective area correction with the mean intensity """ filled_intensity = np.zeros((intensity_resid.data.shape)) nebins = len(intensity_resid.data) for i in range(nebins): masked = bright_pixel_mask.data[i] unmasked = np.invert(masked) mean_intensity = intensity_resid.data[i][unmasked].mean() filled_intensity[i] = np.where(masked, mean_intensity, intensity_resid.data[i]) return HpxMap(filled_intensity, intensity_resid.hpx)
[ "def", "_fill_masked_intensity_resid", "(", "intensity_resid", ",", "bright_pixel_mask", ")", ":", "filled_intensity", "=", "np", ".", "zeros", "(", "(", "intensity_resid", ".", "data", ".", "shape", ")", ")", "nebins", "=", "len", "(", "intensity_resid", ".", ...
Fill the pixels used to compute the effective area correction with the mean intensity
[ "Fill", "the", "pixels", "used", "to", "compute", "the", "effective", "area", "correction", "with", "the", "mean", "intensity" ]
python
train
openstack/proliantutils
proliantutils/ilo/ris.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ris.py#L1086-L1108
def reset_ilo_credential(self, password): """Resets the iLO password. :param password: The password to be set. :raises: IloError, if account not found or on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ acc_uri = '/rest/v1/AccountService/Accounts' for status, hds, account, memberuri in self._get_collection(acc_uri): if account['UserName'] == self.login: mod_user = {} mod_user['Password'] = password status, headers, response = self._rest_patch(memberuri, None, mod_user) if status != 200: msg = self._get_extended_error(response) raise exception.IloError(msg) return msg = "iLO Account with specified username is not found." raise exception.IloError(msg)
[ "def", "reset_ilo_credential", "(", "self", ",", "password", ")", ":", "acc_uri", "=", "'/rest/v1/AccountService/Accounts'", "for", "status", ",", "hds", ",", "account", ",", "memberuri", "in", "self", ".", "_get_collection", "(", "acc_uri", ")", ":", "if", "a...
Resets the iLO password. :param password: The password to be set. :raises: IloError, if account not found or on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
[ "Resets", "the", "iLO", "password", "." ]
python
train
acorg/dark-matter
dark/diamond/alignments.py
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/diamond/alignments.py#L84-L95
def _getReader(self, filename, scoreClass): """ Obtain a JSON record reader for DIAMOND records. @param filename: The C{str} file name holding the JSON. @param scoreClass: A class to hold and compare scores (see scores.py). """ if filename.endswith('.json') or filename.endswith('.json.bz2'): return JSONRecordsReader(filename, scoreClass) else: raise ValueError( 'Unknown DIAMOND record file suffix for file %r.' % filename)
[ "def", "_getReader", "(", "self", ",", "filename", ",", "scoreClass", ")", ":", "if", "filename", ".", "endswith", "(", "'.json'", ")", "or", "filename", ".", "endswith", "(", "'.json.bz2'", ")", ":", "return", "JSONRecordsReader", "(", "filename", ",", "s...
Obtain a JSON record reader for DIAMOND records. @param filename: The C{str} file name holding the JSON. @param scoreClass: A class to hold and compare scores (see scores.py).
[ "Obtain", "a", "JSON", "record", "reader", "for", "DIAMOND", "records", "." ]
python
train
voxpupuli/pypuppetdb
pypuppetdb/api.py
https://github.com/voxpupuli/pypuppetdb/blob/cedeecf48014b4ad5b8e2513ca8230c814f45603/pypuppetdb/api.py#L488-L498
def node(self, name): """Gets a single node from PuppetDB. :param name: The name of the node search. :type name: :obj:`string` :return: An instance of Node :rtype: :class:`pypuppetdb.types.Node` """ nodes = self.nodes(path=name) return next(node for node in nodes)
[ "def", "node", "(", "self", ",", "name", ")", ":", "nodes", "=", "self", ".", "nodes", "(", "path", "=", "name", ")", "return", "next", "(", "node", "for", "node", "in", "nodes", ")" ]
Gets a single node from PuppetDB. :param name: The name of the node search. :type name: :obj:`string` :return: An instance of Node :rtype: :class:`pypuppetdb.types.Node`
[ "Gets", "a", "single", "node", "from", "PuppetDB", "." ]
python
valid
scott-griffiths/bitstring
bitstring.py
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2567-L2622
def split(self, delimiter, start=None, end=None, count=None, bytealigned=None): """Return bitstring generator by splittling using a delimiter. The first item returned is the initial bitstring before the delimiter, which may be an empty bitstring. delimiter -- The bitstring used as the divider. start -- The bit position to start the split. Defaults to 0. end -- The bit position one past the last bit to use in the split. Defaults to self.len. count -- If specified then at most count items are generated. Default is to split as many times as possible. bytealigned -- If True splits will only occur on byte boundaries. Raises ValueError if the delimiter is empty. """ delimiter = Bits(delimiter) if not delimiter.len: raise ValueError("split delimiter cannot be empty.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if count is not None and count < 0: raise ValueError("Cannot split - count must be >= 0.") if count == 0: return if bytealigned and not delimiter.len % 8 and not self._datastore.offset: # Use the quick find method f = self._findbytes x = delimiter._getbytes() else: f = self._findregex x = re.compile(delimiter._getbin()) found = f(x, start, end, bytealigned) if not found: # Initial bits are the whole bitstring being searched yield self._slice(start, end) return # yield the bytes before the first occurrence of the delimiter, even if empty yield self._slice(start, found[0]) startpos = pos = found[0] c = 1 while count is None or c < count: pos += delimiter.len found = f(x, pos, end, bytealigned) if not found: # No more occurrences, so return the rest of the bitstring yield self._slice(startpos, end) return c += 1 yield self._slice(startpos, found[0]) startpos = pos = found[0] # Have generated count bitstrings, so time to quit. return
[ "def", "split", "(", "self", ",", "delimiter", ",", "start", "=", "None", ",", "end", "=", "None", ",", "count", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "delimiter", "=", "Bits", "(", "delimiter", ")", "if", "not", "delimiter", ".", ...
Return bitstring generator by splittling using a delimiter. The first item returned is the initial bitstring before the delimiter, which may be an empty bitstring. delimiter -- The bitstring used as the divider. start -- The bit position to start the split. Defaults to 0. end -- The bit position one past the last bit to use in the split. Defaults to self.len. count -- If specified then at most count items are generated. Default is to split as many times as possible. bytealigned -- If True splits will only occur on byte boundaries. Raises ValueError if the delimiter is empty.
[ "Return", "bitstring", "generator", "by", "splittling", "using", "a", "delimiter", "." ]
python
train
noahbenson/neuropythy
neuropythy/commands/atlas.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/atlas.py#L245-L311
def calc_filemap(atlas_properties, subject, atlas_version_tags, worklog, output_path=None, overwrite=False, output_format='mgz', create_directory=False): ''' calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth map whose keys are filenames and whose values are the interpolated property data. Afferent parameters @ output_path The directory into which the atlas files should be written. If not provided or None then uses the subject's surf directory. If this directory doesn't exist, then it uses the subject's directory itself. @ overwrite Whether to overwrite existing atlas files. If True, then atlas files that already exist will be overwritten. If False, then no files are overwritten. @ create_directory Whether to create the output path if it doesn't exist. This is False by default. @ output_format The desired output format of the files to be written. May be one of the following: 'mgz', 'mgh', or either 'curv' or 'morph'. Efferent values: @ filemap A pimms lazy map whose keys are filenames and whose values are interpolated atlas properties. @ export_all_fn A function of no arguments that, when called, exports all of the files in the filemap to the output_path. ''' if output_path is None: output_path = os.path.join(subject.path, 'surf') if not os.path.isdir(output_path): output_path = subject.path output_format = 'mgz' if output_format is None else output_format.lower() if output_format.startswith('.'): output_format = output_format[1:] (fmt,ending) = (('mgh','.mgz') if output_format == 'mgz' else ('mgh','.mgh') if output_format == 'mgh' else ('freesurfer_morph','')) # make the filemap... worklog('Preparing Filemap...') fm = AutoDict() for (atl,atldat) in six.iteritems(atlas_properties): for (ver,verdat) in six.iteritems(atldat): vstr = atlas_version_tags[atl][ver] for (h,hdat) in six.iteritems(verdat): for m in six.iterkeys(hdat): flnm = '%s.%s_%s%s%s' % (h, atl, m, vstr, ending) flnm = os.path.join(output_path, flnm) fm[flnm] = curry(lambda hdat,m: hdat[m], hdat, m) # okay, make that a lazy map: filemap = pimms.lazy_map(fm) # the function for exporting all properties: def export_all(): ''' This function will export all files from its associated filemap and return a list of the filenames. ''' if not os.path.isdir(output_path): if not create_directory: raise ValueError('No such path and create_direcotry is False: %s' % output_path) os.makedirs(os.path.abspath(output_path), 0o755) filenames = [] worklog('Extracting Files...') wl = worklog.indent() for flnm in six.iterkeys(filemap): wl(flnm) filenames.append(nyio.save(flnm, filemap[flnm], fmt)) return filenames return {'filemap': filemap, 'export_all_fn': export_all}
[ "def", "calc_filemap", "(", "atlas_properties", ",", "subject", ",", "atlas_version_tags", ",", "worklog", ",", "output_path", "=", "None", ",", "overwrite", "=", "False", ",", "output_format", "=", "'mgz'", ",", "create_directory", "=", "False", ")", ":", "if...
calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth map whose keys are filenames and whose values are the interpolated property data. Afferent parameters @ output_path The directory into which the atlas files should be written. If not provided or None then uses the subject's surf directory. If this directory doesn't exist, then it uses the subject's directory itself. @ overwrite Whether to overwrite existing atlas files. If True, then atlas files that already exist will be overwritten. If False, then no files are overwritten. @ create_directory Whether to create the output path if it doesn't exist. This is False by default. @ output_format The desired output format of the files to be written. May be one of the following: 'mgz', 'mgh', or either 'curv' or 'morph'. Efferent values: @ filemap A pimms lazy map whose keys are filenames and whose values are interpolated atlas properties. @ export_all_fn A function of no arguments that, when called, exports all of the files in the filemap to the output_path.
[ "calc_filemap", "is", "a", "calculator", "that", "converts", "the", "atlas", "properties", "nested", "-", "map", "into", "a", "single", "-", "depth", "map", "whose", "keys", "are", "filenames", "and", "whose", "values", "are", "the", "interpolated", "property"...
python
train
mitsei/dlkit
dlkit/aws_adapter/repository/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/aws_adapter/repository/sessions.py#L1798-L1824
def alias_repository(self, repository_id=None, alias_id=None): """Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility. The primary ``Id`` of the ``Repository`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer to another repository, it is reassigned to the given repository ``Id``. arg: repository_id (osid.id.Id): the ``Id`` of a ``Repository`` arg: alias_id (osid.id.Id): the alias ``Id`` raise: AlreadyExists - ``alias_id`` is in use as a primary ``Id`` raise: NotFound - ``repository_id`` not found raise: NullArgument - ``repository_id`` or ``alias_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ # Implemented from awsosid template for - # osid.resource.BinAdminSession.alias_bin_template if not self._can('alias'): raise PermissionDenied() else: return self._provider_session.alias_repository(repository_id)
[ "def", "alias_repository", "(", "self", ",", "repository_id", "=", "None", ",", "alias_id", "=", "None", ")", ":", "# Implemented from awsosid template for -", "# osid.resource.BinAdminSession.alias_bin_template", "if", "not", "self", ".", "_can", "(", "'alias'", ")", ...
Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility. The primary ``Id`` of the ``Repository`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer to another repository, it is reassigned to the given repository ``Id``. arg: repository_id (osid.id.Id): the ``Id`` of a ``Repository`` arg: alias_id (osid.id.Id): the alias ``Id`` raise: AlreadyExists - ``alias_id`` is in use as a primary ``Id`` raise: NotFound - ``repository_id`` not found raise: NullArgument - ``repository_id`` or ``alias_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.*
[ "Adds", "an", "Id", "to", "a", "Repository", "for", "the", "purpose", "of", "creating", "compatibility", "." ]
python
train
codeinn/vcs
vcs/backends/git/changeset.py
https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/changeset.py#L545-L552
def removed(self): """ Returns list of removed ``FileNode`` objects. """ if not self.parents: return [] return RemovedFileNodesGenerator([n for n in self._get_paths_for_status('deleted')], self)
[ "def", "removed", "(", "self", ")", ":", "if", "not", "self", ".", "parents", ":", "return", "[", "]", "return", "RemovedFileNodesGenerator", "(", "[", "n", "for", "n", "in", "self", ".", "_get_paths_for_status", "(", "'deleted'", ")", "]", ",", "self", ...
Returns list of removed ``FileNode`` objects.
[ "Returns", "list", "of", "removed", "FileNode", "objects", "." ]
python
train
uzumaxy/pyvalid
pyvalid/__accepts.py
https://github.com/uzumaxy/pyvalid/blob/74a1a64df1cc77cac55f12f0fe0f52292c6ae479/pyvalid/__accepts.py#L94-L145
def __validate_args(self, func_name, args, kwargs): """Compare value of each required argument with list of accepted values. Args: func_name (str): Function name. args (list): Collection of the position arguments. kwargs (dict): Collection of the keyword arguments. Raises: InvalidArgumentNumberError: When position or count of the arguments is incorrect. ArgumentValidationError: When encountered unexpected argument value. """ from pyvalid.validators import Validator for i, (arg_name, accepted_values) in enumerate(self.accepted_args): if i < len(args): value = args[i] else: if arg_name in kwargs: value = kwargs[arg_name] elif i in self.optional_args: continue else: raise InvalidArgumentNumberError(func_name) is_valid = False for accepted_val in accepted_values: is_validator = ( isinstance(accepted_val, Validator) or ( isinstance(accepted_val, MethodType) and hasattr(accepted_val, '__func__') and isinstance(accepted_val.__func__, Validator) ) ) if is_validator: is_valid = accepted_val(value) elif isinstance(accepted_val, type): is_valid = isinstance(value, accepted_val) else: is_valid = value == accepted_val if is_valid: break if not is_valid: ord_num = self.__ordinal(i + 1) raise ArgumentValidationError( ord_num, func_name, value, accepted_values )
[ "def", "__validate_args", "(", "self", ",", "func_name", ",", "args", ",", "kwargs", ")", ":", "from", "pyvalid", ".", "validators", "import", "Validator", "for", "i", ",", "(", "arg_name", ",", "accepted_values", ")", "in", "enumerate", "(", "self", ".", ...
Compare value of each required argument with list of accepted values. Args: func_name (str): Function name. args (list): Collection of the position arguments. kwargs (dict): Collection of the keyword arguments. Raises: InvalidArgumentNumberError: When position or count of the arguments is incorrect. ArgumentValidationError: When encountered unexpected argument value.
[ "Compare", "value", "of", "each", "required", "argument", "with", "list", "of", "accepted", "values", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_hparams.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_hparams.py#L473-L497
def basic_range1(ranged_hparams): """A basic range of hyperparameters.""" rhp = ranged_hparams rhp.set_discrete("batch_size", [1024, 2048, 4096]) rhp.set_discrete("num_hidden_layers", [1, 2, 3, 4, 5, 6]) rhp.set_discrete("hidden_size", [32, 64, 128, 256, 512], scale=rhp.LOG_SCALE) rhp.set_discrete("kernel_height", [1, 3, 5, 7]) rhp.set_discrete("kernel_width", [1, 3, 5, 7]) rhp.set_discrete("compress_steps", [0, 1, 2]) rhp.set_float("dropout", 0.0, 0.5) rhp.set_float("weight_decay", 1e-4, 10.0, scale=rhp.LOG_SCALE) rhp.set_float("label_smoothing", 0.0, 0.2) rhp.set_float("clip_grad_norm", 0.01, 50.0, scale=rhp.LOG_SCALE) rhp.set_float("learning_rate", 0.005, 2.0, scale=rhp.LOG_SCALE) rhp.set_categorical("initializer", ["uniform", "orthogonal", "uniform_unit_scaling"]) rhp.set_float("initializer_gain", 0.5, 3.5) rhp.set_categorical("learning_rate_decay_scheme", ["none", "sqrt", "noam", "exp"]) rhp.set_float("optimizer_adam_epsilon", 1e-7, 1e-2, scale=rhp.LOG_SCALE) rhp.set_float("optimizer_adam_beta1", 0.8, 0.9) rhp.set_float("optimizer_adam_beta2", 0.995, 0.999) rhp.set_categorical( "optimizer", ["adam", "adagrad", "momentum", "rms_prop", "sgd", "yellow_fin"])
[ "def", "basic_range1", "(", "ranged_hparams", ")", ":", "rhp", "=", "ranged_hparams", "rhp", ".", "set_discrete", "(", "\"batch_size\"", ",", "[", "1024", ",", "2048", ",", "4096", "]", ")", "rhp", ".", "set_discrete", "(", "\"num_hidden_layers\"", ",", "[",...
A basic range of hyperparameters.
[ "A", "basic", "range", "of", "hyperparameters", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/slugs.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/slugs.py#L7855-L7867
def diagnostic_encode(self, diagFl1, diagFl2, diagFl3, diagSh1, diagSh2, diagSh3): ''' Configurable diagnostic messages. diagFl1 : Diagnostic float 1 (float) diagFl2 : Diagnostic float 2 (float) diagFl3 : Diagnostic float 3 (float) diagSh1 : Diagnostic short 1 (int16_t) diagSh2 : Diagnostic short 2 (int16_t) diagSh3 : Diagnostic short 3 (int16_t) ''' return MAVLink_diagnostic_message(diagFl1, diagFl2, diagFl3, diagSh1, diagSh2, diagSh3)
[ "def", "diagnostic_encode", "(", "self", ",", "diagFl1", ",", "diagFl2", ",", "diagFl3", ",", "diagSh1", ",", "diagSh2", ",", "diagSh3", ")", ":", "return", "MAVLink_diagnostic_message", "(", "diagFl1", ",", "diagFl2", ",", "diagFl3", ",", "diagSh1", ",", "d...
Configurable diagnostic messages. diagFl1 : Diagnostic float 1 (float) diagFl2 : Diagnostic float 2 (float) diagFl3 : Diagnostic float 3 (float) diagSh1 : Diagnostic short 1 (int16_t) diagSh2 : Diagnostic short 2 (int16_t) diagSh3 : Diagnostic short 3 (int16_t)
[ "Configurable", "diagnostic", "messages", "." ]
python
train
PyPSA/PyPSA
pypsa/io.py
https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/io.py#L427-L441
def import_from_hdf5(network, path, skip_time=False): """ Import network data from HDF5 store at `path`. Parameters ---------- path : string Name of HDF5 store skip_time : bool, default False Skip reading in time dependent attributes """ basename = os.path.basename(path) with ImporterHDF5(path) as importer: _import_from_importer(network, importer, basename=basename, skip_time=skip_time)
[ "def", "import_from_hdf5", "(", "network", ",", "path", ",", "skip_time", "=", "False", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "with", "ImporterHDF5", "(", "path", ")", "as", "importer", ":", "_import_from_importer...
Import network data from HDF5 store at `path`. Parameters ---------- path : string Name of HDF5 store skip_time : bool, default False Skip reading in time dependent attributes
[ "Import", "network", "data", "from", "HDF5", "store", "at", "path", "." ]
python
train
SoCo/SoCo
soco/music_services/data_structures.py
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/music_services/data_structures.py#L288-L308
def to_element(self, include_namespaces=False): """Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree.Element: The (XML) Element representation of this object """ # We piggy back on the implementation in DidlItem didl_item = DidlItem( title="DUMMY", # This is ignored. Sonos gets the title from the item_id parent_id="DUMMY", # Ditto item_id=self.item_id, desc=self.desc, resources=self.resources ) return didl_item.to_element(include_namespaces=include_namespaces)
[ "def", "to_element", "(", "self", ",", "include_namespaces", "=", "False", ")", ":", "# We piggy back on the implementation in DidlItem", "didl_item", "=", "DidlItem", "(", "title", "=", "\"DUMMY\"", ",", "# This is ignored. Sonos gets the title from the item_id", "parent_id"...
Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree.Element: The (XML) Element representation of this object
[ "Return", "an", "ElementTree", "Element", "representing", "this", "instance", "." ]
python
train
bodylabs/lace
lace/geometry.py
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L100-L113
def flip(self, axis=0, preserve_centroid=False): ''' Flip the mesh across the given axis: 0 for x, 1 for y, 2 for z. When `preserve_centroid` is True, translate after flipping to preserve the location of the centroid. ''' self.v[:, axis] *= -1 if preserve_centroid: self.v[:, axis] -= 2 * self.centroid[0] self.flip_faces()
[ "def", "flip", "(", "self", ",", "axis", "=", "0", ",", "preserve_centroid", "=", "False", ")", ":", "self", ".", "v", "[", ":", ",", "axis", "]", "*=", "-", "1", "if", "preserve_centroid", ":", "self", ".", "v", "[", ":", ",", "axis", "]", "-=...
Flip the mesh across the given axis: 0 for x, 1 for y, 2 for z. When `preserve_centroid` is True, translate after flipping to preserve the location of the centroid.
[ "Flip", "the", "mesh", "across", "the", "given", "axis", ":", "0", "for", "x", "1", "for", "y", "2", "for", "z", "." ]
python
train
UCBerkeleySETI/blimpy
blimpy/calib_utils/fluxcal.py
https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/calib_utils/fluxcal.py#L181-L199
def f_ratios(calON_obs,calOFF_obs,chan_per_coarse,**kwargs): ''' Calculate f_ON, and f_OFF as defined in van Straten et al. 2012 equations 2 and 3 Parameters ---------- calON_obs : str Path to filterbank file (any format) for observation ON the calibrator source calOFF_obs : str Path to filterbank file (any format) for observation OFF the calibrator source ''' #Calculate noise diode ON and noise diode OFF spectra (H and L) for both observations L_ON,H_ON = integrate_calib(calON_obs,chan_per_coarse,**kwargs) L_OFF,H_OFF = integrate_calib(calOFF_obs,chan_per_coarse,**kwargs) f_ON = H_ON/L_ON-1 f_OFF = H_OFF/L_OFF-1 return f_ON, f_OFF
[ "def", "f_ratios", "(", "calON_obs", ",", "calOFF_obs", ",", "chan_per_coarse", ",", "*", "*", "kwargs", ")", ":", "#Calculate noise diode ON and noise diode OFF spectra (H and L) for both observations", "L_ON", ",", "H_ON", "=", "integrate_calib", "(", "calON_obs", ",", ...
Calculate f_ON, and f_OFF as defined in van Straten et al. 2012 equations 2 and 3 Parameters ---------- calON_obs : str Path to filterbank file (any format) for observation ON the calibrator source calOFF_obs : str Path to filterbank file (any format) for observation OFF the calibrator source
[ "Calculate", "f_ON", "and", "f_OFF", "as", "defined", "in", "van", "Straten", "et", "al", ".", "2012", "equations", "2", "and", "3" ]
python
test
bcbio/bcbio-nextgen
bcbio/variation/multi.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/multi.py#L236-L269
def split_variants_by_sample(data): """Split a multi-sample call file into inputs for individual samples. For tumor/normal paired analyses, do not split the final file and attach it to the tumor input. """ # not split, do nothing if "group_orig" not in data: return [[data]] # cancer tumor/normal elif (vcfutils.get_paired_phenotype(data) and "tumor" in [vcfutils.get_paired_phenotype(d) for d in get_orig_items(data)]): out = [] for i, sub_data in enumerate(get_orig_items(data)): if vcfutils.get_paired_phenotype(sub_data) == "tumor": cur_batch = tz.get_in(["metadata", "batch"], data) if cur_batch: sub_data["metadata"]["batch"] = cur_batch sub_data["vrn_file"] = data["vrn_file"] else: sub_data.pop("vrn_file", None) out.append([sub_data]) return out # joint calling or population runs, do not split back up and keep in batches else: out = [] for sub_data in get_orig_items(data): cur_batch = tz.get_in(["metadata", "batch"], data) if cur_batch: sub_data["metadata"]["batch"] = cur_batch sub_data["vrn_file_batch"] = data["vrn_file"] sub_data["vrn_file"] = data["vrn_file"] out.append([sub_data]) return out
[ "def", "split_variants_by_sample", "(", "data", ")", ":", "# not split, do nothing", "if", "\"group_orig\"", "not", "in", "data", ":", "return", "[", "[", "data", "]", "]", "# cancer tumor/normal", "elif", "(", "vcfutils", ".", "get_paired_phenotype", "(", "data",...
Split a multi-sample call file into inputs for individual samples. For tumor/normal paired analyses, do not split the final file and attach it to the tumor input.
[ "Split", "a", "multi", "-", "sample", "call", "file", "into", "inputs", "for", "individual", "samples", "." ]
python
train
onnx/onnx-mxnet
onnx_mxnet/backend.py
https://github.com/onnx/onnx-mxnet/blob/b602d75c5a01f5ed8f68b11150a06374f058a86b/onnx_mxnet/backend.py#L30-L68
def make_graph(node, inputs): """ Created ONNX GraphProto from node""" initializer = [] tensor_input_info = [] tensor_output_info = [] # Adding input tensor info. for index in range(len(node.input)): tensor_input_info.append( helper.make_tensor_value_info(str(node.input[index]), TensorProto.FLOAT, [1])) # Creating an initializer for Weight params. # Assumes that weight params is named as 'W'. # TODO: Handle multiple weight params. # TODO: Add for "bias" if needed if node.input[index] == 'W': dim = inputs[index].shape param_tensor = helper.make_tensor( name=node.input[index], data_type=TensorProto.FLOAT, dims=dim, vals=inputs[index].flatten()) initializer.append(param_tensor) # Adding output tensor info. for index in range(len(node.output)): tensor_output_info.append( helper.make_tensor_value_info(str(node.output[index]), TensorProto.FLOAT, [1])) # creating graph proto object. graph_proto = helper.make_graph( [node], "test", tensor_input_info, tensor_output_info, initializer=initializer) return graph_proto
[ "def", "make_graph", "(", "node", ",", "inputs", ")", ":", "initializer", "=", "[", "]", "tensor_input_info", "=", "[", "]", "tensor_output_info", "=", "[", "]", "# Adding input tensor info.", "for", "index", "in", "range", "(", "len", "(", "node", ".", "i...
Created ONNX GraphProto from node
[ "Created", "ONNX", "GraphProto", "from", "node" ]
python
train
signalfx/signalfx-python
signalfx/rest.py
https://github.com/signalfx/signalfx-python/blob/650eb9a2b301bcc795e4e3a8c031574ade69849d/signalfx/rest.py#L491-L500
def clear_incident(self, id, **kwargs): """Clear an incident. """ resp = self._put( self._u(self._INCIDENT_ENDPOINT_SUFFIX, id, 'clear'), None, **kwargs ) resp.raise_for_status() return resp
[ "def", "clear_incident", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "resp", "=", "self", ".", "_put", "(", "self", ".", "_u", "(", "self", ".", "_INCIDENT_ENDPOINT_SUFFIX", ",", "id", ",", "'clear'", ")", ",", "None", ",", "*", "*",...
Clear an incident.
[ "Clear", "an", "incident", "." ]
python
train
proycon/clam
clam/clamservice.py
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L473-L501
def index(credentials=None): """Get list of projects""" user, oauth_access_token = parsecredentials(credentials) if not settings.ADMINS or user not in settings.ADMINS: return flask.make_response('You shall not pass!!! You are not an administrator!',403) usersprojects = {} totalsize = {} for f in glob.glob(settings.ROOT + "projects/*"): if os.path.isdir(f): u = os.path.basename(f) usersprojects[u], totalsize[u] = getprojects(u) usersprojects[u].sort() return withheaders(flask.make_response(flask.render_template('admin.html', version=VERSION, system_id=settings.SYSTEM_ID, system_name=settings.SYSTEM_NAME, system_description=settings.SYSTEM_DESCRIPTION, system_author=settings.SYSTEM_AUTHOR, system_version=settings.SYSTEM_VERSION, system_email=settings.SYSTEM_EMAIL, user=user, url=getrooturl(), usersprojects = sorted(usersprojects.items()), totalsize=totalsize, allow_origin=settings.ALLOW_ORIGIN, oauth_access_token=oauth_encrypt(oauth_access_token) )), "text/html; charset=UTF-8", {'allow_origin':settings.ALLOW_ORIGIN})
[ "def", "index", "(", "credentials", "=", "None", ")", ":", "user", ",", "oauth_access_token", "=", "parsecredentials", "(", "credentials", ")", "if", "not", "settings", ".", "ADMINS", "or", "user", "not", "in", "settings", ".", "ADMINS", ":", "return", "fl...
Get list of projects
[ "Get", "list", "of", "projects" ]
python
train
mitsei/dlkit
dlkit/services/learning.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/learning.py#L1683-L1691
def get_objective_form(self, *args, **kwargs): """Pass through to provider ObjectiveAdminSession.get_objective_form_for_update""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.get_resource_form_for_update # This method might be a bit sketchy. Time will tell. if isinstance(args[-1], list) or 'objective_record_types' in kwargs: return self.get_objective_form_for_create(*args, **kwargs) else: return self.get_objective_form_for_update(*args, **kwargs)
[ "def", "get_objective_form", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.ResourceAdminSession.get_resource_form_for_update", "# This method might be a bit sketchy. Time will tell.", "if", "isinstanc...
Pass through to provider ObjectiveAdminSession.get_objective_form_for_update
[ "Pass", "through", "to", "provider", "ObjectiveAdminSession", ".", "get_objective_form_for_update" ]
python
train
andrewgross/pyrelic
pyrelic/client.py
https://github.com/andrewgross/pyrelic/blob/641abe7bfa56bf850281f2d9c90cebe7ea2dfd1e/pyrelic/client.py#L312-L335
def get_threshold_values(self, application_id): """ Requires: account ID, list of application ID Method: Get Endpoint: api.newrelic.com Restrictions: ??? Errors: 403 Invalid API key, 422 Invalid Parameters Returns: A list of threshold_value objects, each will have information about its start/end time, metric name, metric value, and the current threshold """ endpoint = "https://rpm.newrelic.com" remote_file = "threshold_values.xml" uri = "{endpoint}/accounts/{account_id}/applications/{app_id}/{xml}".format(endpoint=endpoint, account_id=self.account_id, app_id=application_id, xml=remote_file) response = self._make_get_request(uri) thresholds = [] for threshold_value in response.findall('.//threshold_value'): properties = {} # a little ugly, but the output works fine. for tag, text in threshold_value.items(): properties[tag] = text thresholds.append(Threshold(properties)) return thresholds
[ "def", "get_threshold_values", "(", "self", ",", "application_id", ")", ":", "endpoint", "=", "\"https://rpm.newrelic.com\"", "remote_file", "=", "\"threshold_values.xml\"", "uri", "=", "\"{endpoint}/accounts/{account_id}/applications/{app_id}/{xml}\"", ".", "format", "(", "e...
Requires: account ID, list of application ID Method: Get Endpoint: api.newrelic.com Restrictions: ??? Errors: 403 Invalid API key, 422 Invalid Parameters Returns: A list of threshold_value objects, each will have information about its start/end time, metric name, metric value, and the current threshold
[ "Requires", ":", "account", "ID", "list", "of", "application", "ID", "Method", ":", "Get", "Endpoint", ":", "api", ".", "newrelic", ".", "com", "Restrictions", ":", "???", "Errors", ":", "403", "Invalid", "API", "key", "422", "Invalid", "Parameters", "Retu...
python
train
nfcpy/nfcpy
src/nfc/tag/tt3.py
https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/tag/tt3.py#L589-L642
def write_without_encryption(self, service_list, block_list, data): """Write data blocks to unencrypted services. This method sends a Write Without Encryption command to the tag. The data blocks to overwrite are indicated by a sequence of :class:`~nfc.tag.tt3.BlockCode` objects in the parameter *block_list*. Each block code must reference one of the :class:`~nfc.tag.tt3.ServiceCode` objects in the iterable *service_list*. If any of the blocks or services do not exist, the tag will stop processing at that point and return a two byte error status. The status bytes become the :attr:`~nfc.tag.TagCommandError.errno` value of the :exc:`~nfc.tag.TagCommandError` exception. The *data* to write must be a byte string or array of length ``16 * len(block_list)``. As an example, the following code writes ``16 * "\\xAA"`` to block 5 of service 16, ``16 * "\\xBB"`` to block 0 of service 80 and ``16 * "\\xCC"`` to block 1 of service 80 (all services are writeable without key):: sc1 = nfc.tag.tt3.ServiceCode(16, 0x09) sc2 = nfc.tag.tt3.ServiceCode(80, 0x09) bc1 = nfc.tag.tt3.BlockCode(5, service=0) bc2 = nfc.tag.tt3.BlockCode(0, service=1) bc3 = nfc.tag.tt3.BlockCode(1, service=1) sc_list = [sc1, sc2] bc_list = [bc1, bc2, bc3] data = 16 * "\\xAA" + 16 * "\\xBB" + 16 * "\\xCC" try: data = tag.write_without_encryption(sc_list, bc_list, data) except nfc.tag.TagCommandError as e: if e.errno > 0x00FF: print("the tag returned an error status") else: print("command failed with some other error") Command execution errors raise :exc:`~nfc.tag.TagCommandError`. """ a, b, e = self.pmm[6] & 7, self.pmm[6] >> 3 & 7, self.pmm[6] >> 6 timeout = 302.1E-6 * ((b + 1) * len(block_list) + a + 1) * 4**e data = (chr(len(service_list)) + ''.join([sc.pack() for sc in service_list]) + chr(len(block_list)) + ''.join([bc.pack() for bc in block_list]) + data) log.debug("write w/o encryption service/block list: {0} / {1}".format( ' '.join([hexlify(sc.pack()) for sc in service_list]), ' '.join([hexlify(bc.pack()) for bc in block_list]))) self.send_cmd_recv_rsp(0x08, data, timeout)
[ "def", "write_without_encryption", "(", "self", ",", "service_list", ",", "block_list", ",", "data", ")", ":", "a", ",", "b", ",", "e", "=", "self", ".", "pmm", "[", "6", "]", "&", "7", ",", "self", ".", "pmm", "[", "6", "]", ">>", "3", "&", "7...
Write data blocks to unencrypted services. This method sends a Write Without Encryption command to the tag. The data blocks to overwrite are indicated by a sequence of :class:`~nfc.tag.tt3.BlockCode` objects in the parameter *block_list*. Each block code must reference one of the :class:`~nfc.tag.tt3.ServiceCode` objects in the iterable *service_list*. If any of the blocks or services do not exist, the tag will stop processing at that point and return a two byte error status. The status bytes become the :attr:`~nfc.tag.TagCommandError.errno` value of the :exc:`~nfc.tag.TagCommandError` exception. The *data* to write must be a byte string or array of length ``16 * len(block_list)``. As an example, the following code writes ``16 * "\\xAA"`` to block 5 of service 16, ``16 * "\\xBB"`` to block 0 of service 80 and ``16 * "\\xCC"`` to block 1 of service 80 (all services are writeable without key):: sc1 = nfc.tag.tt3.ServiceCode(16, 0x09) sc2 = nfc.tag.tt3.ServiceCode(80, 0x09) bc1 = nfc.tag.tt3.BlockCode(5, service=0) bc2 = nfc.tag.tt3.BlockCode(0, service=1) bc3 = nfc.tag.tt3.BlockCode(1, service=1) sc_list = [sc1, sc2] bc_list = [bc1, bc2, bc3] data = 16 * "\\xAA" + 16 * "\\xBB" + 16 * "\\xCC" try: data = tag.write_without_encryption(sc_list, bc_list, data) except nfc.tag.TagCommandError as e: if e.errno > 0x00FF: print("the tag returned an error status") else: print("command failed with some other error") Command execution errors raise :exc:`~nfc.tag.TagCommandError`.
[ "Write", "data", "blocks", "to", "unencrypted", "services", "." ]
python
train
unfoldingWord-dev/tx-shared-tools
general_tools/print_utils.py
https://github.com/unfoldingWord-dev/tx-shared-tools/blob/6ff5cd024e1ab54c53dd1bc788bbc78e2358772e/general_tools/print_utils.py#L22-L28
def print_with_header(header, message, color, indent=0): """ Use one of the functions below for printing, not this one. """ print() padding = ' ' * indent print(padding + color + BOLD + header + ENDC + color + message + ENDC)
[ "def", "print_with_header", "(", "header", ",", "message", ",", "color", ",", "indent", "=", "0", ")", ":", "print", "(", ")", "padding", "=", "' '", "*", "indent", "print", "(", "padding", "+", "color", "+", "BOLD", "+", "header", "+", "ENDC", "+", ...
Use one of the functions below for printing, not this one.
[ "Use", "one", "of", "the", "functions", "below", "for", "printing", "not", "this", "one", "." ]
python
train
zimeon/iiif
iiif/auth_flask.py
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/auth_flask.py#L23-L35
def info_authn(self): """Check to see if user if authenticated for info.json. Must have Authorization header with value that has the form "Bearer TOKEN", where TOKEN is an appropriate and valid access token. """ authz_header = request.headers.get('Authorization', '[none]') if (not authz_header.startswith('Bearer ')): return False token = authz_header[7:] return self.access_token_valid( token, "info_authn: Authorization header")
[ "def", "info_authn", "(", "self", ")", ":", "authz_header", "=", "request", ".", "headers", ".", "get", "(", "'Authorization'", ",", "'[none]'", ")", "if", "(", "not", "authz_header", ".", "startswith", "(", "'Bearer '", ")", ")", ":", "return", "False", ...
Check to see if user if authenticated for info.json. Must have Authorization header with value that has the form "Bearer TOKEN", where TOKEN is an appropriate and valid access token.
[ "Check", "to", "see", "if", "user", "if", "authenticated", "for", "info", ".", "json", "." ]
python
train
apache/incubator-superset
superset/connectors/druid/models.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L940-L970
def get_aggregations(metrics_dict, saved_metrics, adhoc_metrics=[]): """ Returns a dictionary of aggregation metric names to aggregation json objects :param metrics_dict: dictionary of all the metrics :param saved_metrics: list of saved metric names :param adhoc_metrics: list of adhoc metric names :raise SupersetException: if one or more metric names are not aggregations """ aggregations = OrderedDict() invalid_metric_names = [] for metric_name in saved_metrics: if metric_name in metrics_dict: metric = metrics_dict[metric_name] if metric.metric_type == POST_AGG_TYPE: invalid_metric_names.append(metric_name) else: aggregations[metric_name] = metric.json_obj else: invalid_metric_names.append(metric_name) if len(invalid_metric_names) > 0: raise SupersetException( _('Metric(s) {} must be aggregations.').format(invalid_metric_names)) for adhoc_metric in adhoc_metrics: aggregations[adhoc_metric['label']] = { 'fieldName': adhoc_metric['column']['column_name'], 'fieldNames': [adhoc_metric['column']['column_name']], 'type': DruidDatasource.druid_type_from_adhoc_metric(adhoc_metric), 'name': adhoc_metric['label'], } return aggregations
[ "def", "get_aggregations", "(", "metrics_dict", ",", "saved_metrics", ",", "adhoc_metrics", "=", "[", "]", ")", ":", "aggregations", "=", "OrderedDict", "(", ")", "invalid_metric_names", "=", "[", "]", "for", "metric_name", "in", "saved_metrics", ":", "if", "m...
Returns a dictionary of aggregation metric names to aggregation json objects :param metrics_dict: dictionary of all the metrics :param saved_metrics: list of saved metric names :param adhoc_metrics: list of adhoc metric names :raise SupersetException: if one or more metric names are not aggregations
[ "Returns", "a", "dictionary", "of", "aggregation", "metric", "names", "to", "aggregation", "json", "objects" ]
python
train
pycontribs/pyrax
pyrax/cloudblockstorage.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudblockstorage.py#L167-L184
def detach(self): """ Detaches this volume from any device it may be attached to. If it is not attached, nothing happens. """ attachments = self.attachments if not attachments: # Not attached; no error needed, just return return # A volume can only be attached to one device at a time, but for some # reason this is a list instead of a singular value att = attachments[0] instance_id = att["server_id"] attachment_id = att["id"] try: self._nova_volumes.delete_server_volume(instance_id, attachment_id) except Exception as e: raise exc.VolumeDetachmentFailed("%s" % e)
[ "def", "detach", "(", "self", ")", ":", "attachments", "=", "self", ".", "attachments", "if", "not", "attachments", ":", "# Not attached; no error needed, just return", "return", "# A volume can only be attached to one device at a time, but for some", "# reason this is a list ins...
Detaches this volume from any device it may be attached to. If it is not attached, nothing happens.
[ "Detaches", "this", "volume", "from", "any", "device", "it", "may", "be", "attached", "to", ".", "If", "it", "is", "not", "attached", "nothing", "happens", "." ]
python
train
GPflow/GPflow
gpflow/models/gpr.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/models/gpr.py#L64-L76
def _build_likelihood(self): r""" Construct a tensorflow function to compute the likelihood. \log p(Y | theta). """ K = self.kern.K(self.X) + tf.eye(tf.shape(self.X)[0], dtype=settings.float_type) * self.likelihood.variance L = tf.cholesky(K) m = self.mean_function(self.X) logpdf = multivariate_normal(self.Y, m, L) # (R,) log-likelihoods for each independent dimension of Y return tf.reduce_sum(logpdf)
[ "def", "_build_likelihood", "(", "self", ")", ":", "K", "=", "self", ".", "kern", ".", "K", "(", "self", ".", "X", ")", "+", "tf", ".", "eye", "(", "tf", ".", "shape", "(", "self", ".", "X", ")", "[", "0", "]", ",", "dtype", "=", "settings", ...
r""" Construct a tensorflow function to compute the likelihood. \log p(Y | theta).
[ "r", "Construct", "a", "tensorflow", "function", "to", "compute", "the", "likelihood", "." ]
python
train
hynek/doc2dash
src/doc2dash/__main__.py
https://github.com/hynek/doc2dash/blob/659a66e237eb0faa08e81094fc4140623b418952/src/doc2dash/__main__.py#L270-L293
def setup_paths(source, destination, name, add_to_global, force): """ Determine source and destination using the options. """ if source[-1] == "/": source = source[:-1] if not name: name = os.path.split(source)[-1] elif name.endswith(".docset"): name = name.replace(".docset", "") if add_to_global: destination = DEFAULT_DOCSET_PATH dest = os.path.join(destination or "", name + ".docset") dst_exists = os.path.lexists(dest) if dst_exists and force: shutil.rmtree(dest) elif dst_exists: log.error( 'Destination path "{}" already exists.'.format( click.format_filename(dest) ) ) raise SystemExit(errno.EEXIST) return source, dest, name
[ "def", "setup_paths", "(", "source", ",", "destination", ",", "name", ",", "add_to_global", ",", "force", ")", ":", "if", "source", "[", "-", "1", "]", "==", "\"/\"", ":", "source", "=", "source", "[", ":", "-", "1", "]", "if", "not", "name", ":", ...
Determine source and destination using the options.
[ "Determine", "source", "and", "destination", "using", "the", "options", "." ]
python
valid
neurodata/ndio
ndio/convert/tiff.py
https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/convert/tiff.py#L8-L28
def load(tiff_filename): """ Import a TIFF file into a numpy array. Arguments: tiff_filename: A string filename of a TIFF datafile Returns: A numpy array with data from the TIFF file """ # Expand filename to be absolute tiff_filename = os.path.expanduser(tiff_filename) try: img = tiff.imread(tiff_filename) except Exception as e: raise ValueError("Could not load file {0} for conversion." .format(tiff_filename)) raise return numpy.array(img)
[ "def", "load", "(", "tiff_filename", ")", ":", "# Expand filename to be absolute", "tiff_filename", "=", "os", ".", "path", ".", "expanduser", "(", "tiff_filename", ")", "try", ":", "img", "=", "tiff", ".", "imread", "(", "tiff_filename", ")", "except", "Excep...
Import a TIFF file into a numpy array. Arguments: tiff_filename: A string filename of a TIFF datafile Returns: A numpy array with data from the TIFF file
[ "Import", "a", "TIFF", "file", "into", "a", "numpy", "array", "." ]
python
test
uta-smile/smile-python
smile/flags.py
https://github.com/uta-smile/smile-python/blob/8918d1bb9ef76922ef976f6e3a10578b3a0af1c8/smile/flags.py#L142-L149
def DEFINE_integer(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'int'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as an int. docstring: A helpful message explaining the use of the flag. """ _define_helper(flag_name, default_value, docstring, int, required)
[ "def", "DEFINE_integer", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "required", "=", "False", ")", ":", "# pylint: disable=invalid-name", "_define_helper", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "int", ",", "required", "...
Defines a flag of type 'int'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as an int. docstring: A helpful message explaining the use of the flag.
[ "Defines", "a", "flag", "of", "type", "int", ".", "Args", ":", "flag_name", ":", "The", "name", "of", "the", "flag", "as", "a", "string", ".", "default_value", ":", "The", "default", "value", "the", "flag", "should", "take", "as", "an", "int", ".", "...
python
train
pypa/setuptools
setuptools/depends.py
https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/depends.py#L101-L132
def get_module_constant(module, symbol, default=-1, paths=None): """Find 'module' by searching 'paths', and extract 'symbol' Return 'None' if 'module' does not exist on 'paths', or it does not define 'symbol'. If the module defines 'symbol' as a constant, return the constant. Otherwise, return 'default'.""" try: f, path, (suffix, mode, kind) = find_module(module, paths) except ImportError: # Module doesn't exist return None try: if kind == PY_COMPILED: f.read(8) # skip magic & date code = marshal.load(f) elif kind == PY_FROZEN: code = imp.get_frozen_object(module) elif kind == PY_SOURCE: code = compile(f.read(), path, 'exec') else: # Not something we can parse; we'll have to import it. :( if module not in sys.modules: imp.load_module(module, f, path, (suffix, mode, kind)) return getattr(sys.modules[module], symbol, None) finally: if f: f.close() return extract_constant(code, symbol, default)
[ "def", "get_module_constant", "(", "module", ",", "symbol", ",", "default", "=", "-", "1", ",", "paths", "=", "None", ")", ":", "try", ":", "f", ",", "path", ",", "(", "suffix", ",", "mode", ",", "kind", ")", "=", "find_module", "(", "module", ",",...
Find 'module' by searching 'paths', and extract 'symbol' Return 'None' if 'module' does not exist on 'paths', or it does not define 'symbol'. If the module defines 'symbol' as a constant, return the constant. Otherwise, return 'default'.
[ "Find", "module", "by", "searching", "paths", "and", "extract", "symbol" ]
python
train
RPi-Distro/python-gpiozero
gpiozero/internal_devices.py
https://github.com/RPi-Distro/python-gpiozero/blob/7b67374fd0c8c4fde5586d9bad9531f076db9c0c/gpiozero/internal_devices.py#L112-L129
def value(self): """ Returns :data:`True` if the host returned a single ping, and :data:`False` otherwise. """ # XXX This is doing a DNS lookup every time it's queried; should we # call gethostbyname in the constructor and ping that instead (good # for consistency, but what if the user *expects* the host to change # address?) with io.open(os.devnull, 'wb') as devnull: try: subprocess.check_call( ['ping', '-c1', self.host], stdout=devnull, stderr=devnull) except subprocess.CalledProcessError: return False else: return True
[ "def", "value", "(", "self", ")", ":", "# XXX This is doing a DNS lookup every time it's queried; should we", "# call gethostbyname in the constructor and ping that instead (good", "# for consistency, but what if the user *expects* the host to change", "# address?)", "with", "io", ".", "op...
Returns :data:`True` if the host returned a single ping, and :data:`False` otherwise.
[ "Returns", ":", "data", ":", "True", "if", "the", "host", "returned", "a", "single", "ping", "and", ":", "data", ":", "False", "otherwise", "." ]
python
train
Kane610/deconz
pydeconz/utils.py
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/utils.py#L82-L103
async def async_request(session, url, **kwargs): """Do a web request and manage response.""" _LOGGER.debug("Sending %s to %s", kwargs, url) try: res = await session(url, **kwargs) if res.content_type != 'application/json': raise ResponseError( "Invalid content type: {}".format(res.content_type)) response = await res.json() _LOGGER.debug("HTTP request response: %s", response) _raise_on_error(response) return response except aiohttp.client_exceptions.ClientError as err: raise RequestError( "Error requesting data from {}: {}".format(url, err) ) from None
[ "async", "def", "async_request", "(", "session", ",", "url", ",", "*", "*", "kwargs", ")", ":", "_LOGGER", ".", "debug", "(", "\"Sending %s to %s\"", ",", "kwargs", ",", "url", ")", "try", ":", "res", "=", "await", "session", "(", "url", ",", "*", "*...
Do a web request and manage response.
[ "Do", "a", "web", "request", "and", "manage", "response", "." ]
python
train
sorgerlab/indra
indra/tools/reading/util/script_tools.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/util/script_tools.py#L11-L76
def get_parser(description, input_desc): """Get a parser that is generic to reading scripts. Parameters ---------- description : str A description of the tool, usually about one line long. input_desc: str A string describing the nature of the input file used by the reading tool. Returns ------- parser : argparse.ArgumentParser instance An argument parser object, to which further arguments can be added. """ parser = ArgumentParser(description=description) parser.add_argument( dest='input_file', help=input_desc ) parser.add_argument( '-r', '--readers', choices=['reach', 'sparser', 'trips'], help='List of readers to be used.', nargs='+' ) parser.add_argument( '-n', '--num_procs', dest='n_proc', help='Select the number of processes to use.', type=int, default=1 ) parser.add_argument( '-s', '--sample', dest='n_samp', help='Read a random sample of size N_SAMP of the inputs.', type=int ) parser.add_argument( '-I', '--in_range', dest='range_str', help='Only read input lines in the range given as <start>:<end>.' ) parser.add_argument( '-v', '--verbose', help='Include output from the readers.', action='store_true' ) parser.add_argument( '-q', '--quiet', help='Suppress most output. Overrides -v and -d options.', action='store_true' ) parser.add_argument( '-d', '--debug', help='Set the logging to debug level.', action='store_true' ) # parser.add_argument( # '-m', '--messy', # help='Do not clean up directories created while reading.', # action='store_true' # ) return parser
[ "def", "get_parser", "(", "description", ",", "input_desc", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "description", ")", "parser", ".", "add_argument", "(", "dest", "=", "'input_file'", ",", "help", "=", "input_desc", ")", "parser", ...
Get a parser that is generic to reading scripts. Parameters ---------- description : str A description of the tool, usually about one line long. input_desc: str A string describing the nature of the input file used by the reading tool. Returns ------- parser : argparse.ArgumentParser instance An argument parser object, to which further arguments can be added.
[ "Get", "a", "parser", "that", "is", "generic", "to", "reading", "scripts", "." ]
python
train
bitcraft/pyscroll
tutorial/quest.py
https://github.com/bitcraft/pyscroll/blob/b41c1016dfefd0e2d83a14a2ce40d7ad298c5b0f/tutorial/quest.py#L209-L230
def run(self): """ Run the game loop """ clock = pygame.time.Clock() self.running = True from collections import deque times = deque(maxlen=30) try: while self.running: dt = clock.tick() / 1000. times.append(clock.get_fps()) # print(sum(times)/len(times)) self.handle_input() self.update(dt) self.draw(screen) pygame.display.flip() except KeyboardInterrupt: self.running = False
[ "def", "run", "(", "self", ")", ":", "clock", "=", "pygame", ".", "time", ".", "Clock", "(", ")", "self", ".", "running", "=", "True", "from", "collections", "import", "deque", "times", "=", "deque", "(", "maxlen", "=", "30", ")", "try", ":", "whil...
Run the game loop
[ "Run", "the", "game", "loop" ]
python
train
riggsd/davies
fabfile.py
https://github.com/riggsd/davies/blob/8566c626202a875947ad01c087300108c68d80b5/fabfile.py#L30-L37
def lint(fmt='colorized'): """Run verbose PyLint on source. Optionally specify fmt=html for HTML output.""" if fmt == 'html': outfile = 'pylint_report.html' local('pylint -f %s davies > %s || true' % (fmt, outfile)) local('open %s' % outfile) else: local('pylint -f %s davies || true' % fmt)
[ "def", "lint", "(", "fmt", "=", "'colorized'", ")", ":", "if", "fmt", "==", "'html'", ":", "outfile", "=", "'pylint_report.html'", "local", "(", "'pylint -f %s davies > %s || true'", "%", "(", "fmt", ",", "outfile", ")", ")", "local", "(", "'open %s'", "%", ...
Run verbose PyLint on source. Optionally specify fmt=html for HTML output.
[ "Run", "verbose", "PyLint", "on", "source", ".", "Optionally", "specify", "fmt", "=", "html", "for", "HTML", "output", "." ]
python
train
jwkvam/bowtie
bowtie/_magic.py
https://github.com/jwkvam/bowtie/blob/c494850671ac805bf186fbf2bdb07d2a34ae876d/bowtie/_magic.py#L27-L47
def get_notebook_name() -> str: """Return the full path of the jupyter notebook. References ---------- https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246 """ kernel_id = re.search( # type: ignore 'kernel-(.*).json', ipykernel.connect.get_connection_file() ).group(1) servers = list_running_servers() for server in servers: response = requests.get(urljoin(server['url'], 'api/sessions'), params={'token': server.get('token', '')}) for session in json.loads(response.text): if session['kernel']['id'] == kernel_id: relative_path = session['notebook']['path'] return pjoin(server['notebook_dir'], relative_path) raise Exception('Noteboook not found.')
[ "def", "get_notebook_name", "(", ")", "->", "str", ":", "kernel_id", "=", "re", ".", "search", "(", "# type: ignore", "'kernel-(.*).json'", ",", "ipykernel", ".", "connect", ".", "get_connection_file", "(", ")", ")", ".", "group", "(", "1", ")", "servers", ...
Return the full path of the jupyter notebook. References ---------- https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246
[ "Return", "the", "full", "path", "of", "the", "jupyter", "notebook", "." ]
python
train
gem/oq-engine
openquake/hmtk/strain/regionalisation/kreemer_regionalisation.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/regionalisation/kreemer_regionalisation.py#L153-L204
def define_kreemer_regionalisation(self, north=90., south=-90., east=180., west=-180.): ''' Applies the regionalisation defined according to the regionalisation typology of Corne Kreemer ''' '''Applies the regionalisation of Kreemer (2003) :param input_file: Filename (str) of input file contraining Kreemer regionalisation :param north: Northern limit (decimal degrees)for consideration (float) :param south: Southern limit (decimal degrees)for consideration (float) :param east: Eastern limit (decimal degrees)for consideration (float) :param west: Western limit (decimal degrees)for consideration (float) :returns: List of polygons corresonding to the Kreemer cells. ''' input_data = getlines(self.filename) kreemer_polygons = [] for line_loc, line in enumerate(input_data): if '>' in line[0]: polygon_dict = {} # Get region type (char) and area (m ^ 2) from header primary_data = line[2:].rstrip('\n') primary_data = primary_data.split(' ', 1) polygon_dict['region_type'] = primary_data[0].strip(' ') polygon_dict['area'] = float(primary_data[1].strip(' ')) polygon_dict['cell'] = _build_kreemer_cell(input_data, line_loc) polygon_dict['long_lims'] = np.array([ np.min(polygon_dict['cell'][:, 0]), np.max(polygon_dict['cell'][:, 0])]) polygon_dict['lat_lims'] = np.array([ np.min(polygon_dict['cell'][:, 1]), np.max(polygon_dict['cell'][:, 1])]) polygon_dict['cell'] = None if polygon_dict['long_lims'][0] >= 180.0: polygon_dict['long_lims'] = \ polygon_dict['long_lims'] - 360.0 valid_check = [ polygon_dict['long_lims'][0] >= west, polygon_dict['long_lims'][1] <= east, polygon_dict['lat_lims'][0] >= south, polygon_dict['lat_lims'][1] <= north] if all(valid_check): kreemer_polygons.append(polygon_dict) return kreemer_polygons
[ "def", "define_kreemer_regionalisation", "(", "self", ",", "north", "=", "90.", ",", "south", "=", "-", "90.", ",", "east", "=", "180.", ",", "west", "=", "-", "180.", ")", ":", "'''Applies the regionalisation of Kreemer (2003)\n :param input_file:\n ...
Applies the regionalisation defined according to the regionalisation typology of Corne Kreemer
[ "Applies", "the", "regionalisation", "defined", "according", "to", "the", "regionalisation", "typology", "of", "Corne", "Kreemer" ]
python
train
huge-success/sanic
sanic/helpers.py
https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/helpers.py#L117-L133
def remove_entity_headers(headers, allowed=("content-location", "expires")): """ Removes all the entity headers present in the headers given. According to RFC 2616 Section 10.3.5, Content-Location and Expires are allowed as for the "strong cache validator". https://tools.ietf.org/html/rfc2616#section-10.3.5 returns the headers without the entity headers """ allowed = set([h.lower() for h in allowed]) headers = { header: value for header, value in headers.items() if not is_entity_header(header) or header.lower() in allowed } return headers
[ "def", "remove_entity_headers", "(", "headers", ",", "allowed", "=", "(", "\"content-location\"", ",", "\"expires\"", ")", ")", ":", "allowed", "=", "set", "(", "[", "h", ".", "lower", "(", ")", "for", "h", "in", "allowed", "]", ")", "headers", "=", "{...
Removes all the entity headers present in the headers given. According to RFC 2616 Section 10.3.5, Content-Location and Expires are allowed as for the "strong cache validator". https://tools.ietf.org/html/rfc2616#section-10.3.5 returns the headers without the entity headers
[ "Removes", "all", "the", "entity", "headers", "present", "in", "the", "headers", "given", ".", "According", "to", "RFC", "2616", "Section", "10", ".", "3", ".", "5", "Content", "-", "Location", "and", "Expires", "are", "allowed", "as", "for", "the", "str...
python
train
datamachine/twx.botapi
twx/botapi/botapi.py
https://github.com/datamachine/twx.botapi/blob/c85184da738169e8f9d6d8e62970540f427c486e/twx/botapi/botapi.py#L4374-L4376
def get_file(self, *args, **kwargs): """See :func:`get_file`""" return get_file(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "get_file", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "get_file", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
See :func:`get_file`
[ "See", ":", "func", ":", "get_file" ]
python
train
mozilla/configman
configman/def_sources/for_argparse.py
https://github.com/mozilla/configman/blob/83159fed61cc4cbbe5a4a6a00d3acad8a0c39c96/configman/def_sources/for_argparse.py#L98-L110
def add_namespace(self, name, a_namespace): """as we build up argparse, the actions that define a subparser are translated into configman options. Each of those options must be tagged with the value of the subparse to which they correspond.""" # save a local copy of the namespace self.namespaces[name] = a_namespace # iterate through the namespace branding each of the options with the # name of the subparser to which they belong for k in a_namespace.keys_breadth_first(): an_option = a_namespace[k] if not an_option.foreign_data: an_option.foreign_data = DotDict() an_option.foreign_data['argparse.owning_subparser_name'] = name
[ "def", "add_namespace", "(", "self", ",", "name", ",", "a_namespace", ")", ":", "# save a local copy of the namespace", "self", ".", "namespaces", "[", "name", "]", "=", "a_namespace", "# iterate through the namespace branding each of the options with the", "# name of the sub...
as we build up argparse, the actions that define a subparser are translated into configman options. Each of those options must be tagged with the value of the subparse to which they correspond.
[ "as", "we", "build", "up", "argparse", "the", "actions", "that", "define", "a", "subparser", "are", "translated", "into", "configman", "options", ".", "Each", "of", "those", "options", "must", "be", "tagged", "with", "the", "value", "of", "the", "subparse", ...
python
train
materialsproject/pymatgen
pymatgen/io/abinit/tasks.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L949-L990
def launch(self, task, **kwargs): """ Build the input files and submit the task via the :class:`Qadapter` Args: task: :class:`TaskObject` Returns: Process object. """ if task.status == task.S_LOCKED: raise ValueError("You shall not submit a locked task!") # Build the task task.build() # Pass information on the time limit to Abinit (we always assume ndtset == 1) if isinstance(task, AbinitTask): args = kwargs.get("exec_args", []) if args is None: args = [] args = args[:] args.append("--timelimit %s" % qu.time2slurm(self.qadapter.timelimit)) kwargs["exec_args"] = args # Write the submission script script_file = self.write_jobfile(task, **kwargs) # Submit the task and save the queue id. try: qjob, process = self.qadapter.submit_to_queue(script_file) task.set_status(task.S_SUB, msg='Submitted to queue') task.set_qjob(qjob) return process except self.qadapter.MaxNumLaunchesError as exc: # TODO: Here we should try to switch to another qadapter # 1) Find a new parallel configuration in those stored in task.pconfs # 2) Change the input file. # 3) Regenerate the submission script # 4) Relaunch task.set_status(task.S_ERROR, msg="max_num_launches reached: %s" % str(exc)) raise
[ "def", "launch", "(", "self", ",", "task", ",", "*", "*", "kwargs", ")", ":", "if", "task", ".", "status", "==", "task", ".", "S_LOCKED", ":", "raise", "ValueError", "(", "\"You shall not submit a locked task!\"", ")", "# Build the task", "task", ".", "build...
Build the input files and submit the task via the :class:`Qadapter` Args: task: :class:`TaskObject` Returns: Process object.
[ "Build", "the", "input", "files", "and", "submit", "the", "task", "via", "the", ":", "class", ":", "Qadapter" ]
python
train
sorgerlab/indra
indra/assemblers/sbgn/assembler.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/sbgn/assembler.py#L337-L372
def _glyph_for_monomer_pattern(self, pattern): """Add glyph for a PySB MonomerPattern.""" pattern.matches_key = lambda: str(pattern) agent_id = self._make_agent_id(pattern) # Handle sources and sinks if pattern.monomer.name in ('__source', '__sink'): return None # Handle molecules glyph = emaker.glyph(emaker.label(text=pattern.monomer.name), emaker.bbox(**self.monomer_style), class_('macromolecule'), id=agent_id) # Temporarily remove this # Add a glyph for type #type_glyph = emaker.glyph(emaker.label(text='mt:prot'), # class_('unit of information'), # emaker.bbox(**self.entity_type_style), # id=self._make_id()) #glyph.append(type_glyph) for site, value in pattern.site_conditions.items(): if value is None or isinstance(value, int): continue # Make some common abbreviations if site == 'phospho': site = 'p' elif site == 'activity': site = 'act' if value == 'active': value = 'a' elif value == 'inactive': value = 'i' state = emaker.state(variable=site, value=value) state_glyph = \ emaker.glyph(state, emaker.bbox(**self.entity_state_style), class_('state variable'), id=self._make_id()) glyph.append(state_glyph) return glyph
[ "def", "_glyph_for_monomer_pattern", "(", "self", ",", "pattern", ")", ":", "pattern", ".", "matches_key", "=", "lambda", ":", "str", "(", "pattern", ")", "agent_id", "=", "self", ".", "_make_agent_id", "(", "pattern", ")", "# Handle sources and sinks", "if", ...
Add glyph for a PySB MonomerPattern.
[ "Add", "glyph", "for", "a", "PySB", "MonomerPattern", "." ]
python
train
ManiacalLabs/BiblioPixel
bibliopixel/animation/animation.py
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/animation.py#L21-L41
def construct(cls, project, *, run=None, name=None, data=None, **desc): """ Construct an animation, set the runner, and add in the two "reserved fields" `name` and `data`. """ from . failed import Failed exception = desc.pop('_exception', None) if exception: a = Failed(project.layout, desc, exception) else: try: a = cls(project.layout, **desc) a._set_runner(run or {}) except Exception as e: if cls.FAIL_ON_EXCEPTION: raise a = Failed(project.layout, desc, e) a.name = name a.data = data return a
[ "def", "construct", "(", "cls", ",", "project", ",", "*", ",", "run", "=", "None", ",", "name", "=", "None", ",", "data", "=", "None", ",", "*", "*", "desc", ")", ":", "from", ".", "failed", "import", "Failed", "exception", "=", "desc", ".", "pop...
Construct an animation, set the runner, and add in the two "reserved fields" `name` and `data`.
[ "Construct", "an", "animation", "set", "the", "runner", "and", "add", "in", "the", "two", "reserved", "fields", "name", "and", "data", "." ]
python
valid
zomux/deepy
deepy/tensor/functions.py
https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/tensor/functions.py#L38-L49
def concatenate(vars, axis=-1): """ A utility function of concatenate. """ from deepy.core.neural_var import NeuralVariable if isinstance(vars[0], NeuralVariable): concat_var = Concatenate(axis=axis).compute(*vars) if axis == -1 or axis == vars[0].tensor.ndim - 1: concat_var.output_dim = sum([x.output_dim for x in vars], 0) else: concat_var = TT.concatenate(vars, axis) return concat_var
[ "def", "concatenate", "(", "vars", ",", "axis", "=", "-", "1", ")", ":", "from", "deepy", ".", "core", ".", "neural_var", "import", "NeuralVariable", "if", "isinstance", "(", "vars", "[", "0", "]", ",", "NeuralVariable", ")", ":", "concat_var", "=", "C...
A utility function of concatenate.
[ "A", "utility", "function", "of", "concatenate", "." ]
python
test
Jajcus/pyxmpp2
pyxmpp2/ext/muc/muccore.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L361-L388
def __from_xmlnode(self, xmlnode): """Initialize a `MucItem` object from an XML node. :Parameters: - `xmlnode`: the XML node. :Types: - `xmlnode`: `libxml2.xmlNode` """ actor=None reason=None n=xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=MUC_USER_NS: continue if n.name=="actor": actor=n.getContent() if n.name=="reason": reason=n.getContent() n=n.next self.__init( from_utf8(xmlnode.prop("affiliation")), from_utf8(xmlnode.prop("role")), from_utf8(xmlnode.prop("jid")), from_utf8(xmlnode.prop("nick")), from_utf8(actor), from_utf8(reason), );
[ "def", "__from_xmlnode", "(", "self", ",", "xmlnode", ")", ":", "actor", "=", "None", "reason", "=", "None", "n", "=", "xmlnode", ".", "children", "while", "n", ":", "ns", "=", "n", ".", "ns", "(", ")", "if", "ns", "and", "ns", ".", "getContent", ...
Initialize a `MucItem` object from an XML node. :Parameters: - `xmlnode`: the XML node. :Types: - `xmlnode`: `libxml2.xmlNode`
[ "Initialize", "a", "MucItem", "object", "from", "an", "XML", "node", "." ]
python
valid
PmagPy/PmagPy
pmagpy/pmag.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L32-L58
def sort_diclist(undecorated, sort_on): """ Sort a list of dictionaries by the value in each dictionary for the sorting key Parameters ---------- undecorated : list of dicts sort_on : str, numeric key that is present in all dicts to sort on Returns --------- ordered list of dicts Examples --------- >>> lst = [{'key1': 10, 'key2': 2}, {'key1': 1, 'key2': 20}] >>> sort_diclist(lst, 'key1') [{'key2': 20, 'key1': 1}, {'key2': 2, 'key1': 10}] >>> sort_diclist(lst, 'key2') [{'key2': 2, 'key1': 10}, {'key2': 20, 'key1': 1}] """ decorated = [(len(dict_[sort_on]) if hasattr(dict_[sort_on], '__len__') else dict_[ sort_on], index) for (index, dict_) in enumerate(undecorated)] decorated.sort() return[undecorated[index] for (key, index) in decorated]
[ "def", "sort_diclist", "(", "undecorated", ",", "sort_on", ")", ":", "decorated", "=", "[", "(", "len", "(", "dict_", "[", "sort_on", "]", ")", "if", "hasattr", "(", "dict_", "[", "sort_on", "]", ",", "'__len__'", ")", "else", "dict_", "[", "sort_on", ...
Sort a list of dictionaries by the value in each dictionary for the sorting key Parameters ---------- undecorated : list of dicts sort_on : str, numeric key that is present in all dicts to sort on Returns --------- ordered list of dicts Examples --------- >>> lst = [{'key1': 10, 'key2': 2}, {'key1': 1, 'key2': 20}] >>> sort_diclist(lst, 'key1') [{'key2': 20, 'key1': 1}, {'key2': 2, 'key1': 10}] >>> sort_diclist(lst, 'key2') [{'key2': 2, 'key1': 10}, {'key2': 20, 'key1': 1}]
[ "Sort", "a", "list", "of", "dictionaries", "by", "the", "value", "in", "each", "dictionary", "for", "the", "sorting", "key" ]
python
train
gamechanger/mongothon
mongothon/queries.py
https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/queries.py#L24-L46
def unpack_scope(cls, scope): """Unpacks the response from a scope function. The function should return either a query, a query and a projection, or a query a projection and an query options hash.""" query = {} projection = {} options = {} if isinstance(scope, tuple): if len(scope) > 3: raise ValueError("Invalid scope") if len(scope) >= 1: query = scope[0] if len(scope) >= 2: projection = scope[1] if len(scope) == 3: options = scope[2] elif isinstance(scope, dict): query = scope else: raise ValueError("Invalid scope") return query, projection, options
[ "def", "unpack_scope", "(", "cls", ",", "scope", ")", ":", "query", "=", "{", "}", "projection", "=", "{", "}", "options", "=", "{", "}", "if", "isinstance", "(", "scope", ",", "tuple", ")", ":", "if", "len", "(", "scope", ")", ">", "3", ":", "...
Unpacks the response from a scope function. The function should return either a query, a query and a projection, or a query a projection and an query options hash.
[ "Unpacks", "the", "response", "from", "a", "scope", "function", ".", "The", "function", "should", "return", "either", "a", "query", "a", "query", "and", "a", "projection", "or", "a", "query", "a", "projection", "and", "an", "query", "options", "hash", "." ...
python
train
mitsei/dlkit
dlkit/json_/authorization/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/authorization/managers.py#L493-L508
def get_authorization_query_session(self): """Gets the ``OsidSession`` associated with the authorization query service. return: (osid.authorization.AuthorizationQuerySession) - an ``AuthorizationQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_query()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_authorization_query()`` is ``true``.* """ if not self.supports_authorization_query(): raise errors.Unimplemented() # pylint: disable=no-member return sessions.AuthorizationQuerySession(runtime=self._runtime)
[ "def", "get_authorization_query_session", "(", "self", ")", ":", "if", "not", "self", ".", "supports_authorization_query", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "AuthorizationQuerySe...
Gets the ``OsidSession`` associated with the authorization query service. return: (osid.authorization.AuthorizationQuerySession) - an ``AuthorizationQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_query()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_authorization_query()`` is ``true``.*
[ "Gets", "the", "OsidSession", "associated", "with", "the", "authorization", "query", "service", "." ]
python
train
saulpw/visidata
plugins/vgit/git.py
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/plugins/vgit/git.py#L68-L98
def git_iter(sep, *args, git=maybeloggit, **kwargs): 'Generator of chunks of stdout from given git command, delineated by sep character' bufsize = 512 err = io.StringIO() chunks = [] try: for data in git('--no-pager', *args, _decode_errors='replace', _out_bufsize=bufsize, _iter=True, _err=err, **kwargs): while True: i = data.find(sep) if i < 0: break chunks.append(data[:i]) data = data[i+1:] yield ''.join(chunks) chunks.clear() chunks.append(data) except sh.ErrorReturnCode as e: status('exit_code=%s' % e.exit_code) r = ''.join(chunks) if r: yield r errlines = err.getvalue().splitlines() if len(errlines) < 3: for line in errlines: status(line) else: vd().push(TextSheet('git ' + ' '.join(args), errlines))
[ "def", "git_iter", "(", "sep", ",", "*", "args", ",", "git", "=", "maybeloggit", ",", "*", "*", "kwargs", ")", ":", "bufsize", "=", "512", "err", "=", "io", ".", "StringIO", "(", ")", "chunks", "=", "[", "]", "try", ":", "for", "data", "in", "g...
Generator of chunks of stdout from given git command, delineated by sep character
[ "Generator", "of", "chunks", "of", "stdout", "from", "given", "git", "command", "delineated", "by", "sep", "character" ]
python
train
Alignak-monitoring/alignak
alignak/daterange.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daterange.py#L781-L792
def is_correct(self): """Check if the Daterange is correct : weekdays are valid :return: True if weekdays are valid, False otherwise :rtype: bool """ valid = self.day in Daterange.weekdays if not valid: logger.error("Error: %s is not a valid day", self.day) # Check also if Daterange is correct. valid &= super(StandardDaterange, self).is_correct() return valid
[ "def", "is_correct", "(", "self", ")", ":", "valid", "=", "self", ".", "day", "in", "Daterange", ".", "weekdays", "if", "not", "valid", ":", "logger", ".", "error", "(", "\"Error: %s is not a valid day\"", ",", "self", ".", "day", ")", "# Check also if Dater...
Check if the Daterange is correct : weekdays are valid :return: True if weekdays are valid, False otherwise :rtype: bool
[ "Check", "if", "the", "Daterange", "is", "correct", ":", "weekdays", "are", "valid" ]
python
train
Esri/ArcREST
src/arcresthelper/portalautomation.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/portalautomation.py#L68-L194
def stageContent(self, configFiles, dateTimeFormat=None): """Parses a JSON configuration file to stage content. Args: configFiles (list): A list of JSON files on disk containing configuration data for staging content. dateTimeFormat (str): A valid date formatting directive, as understood by :py:meth:`datetime.datetime.strftime`. Defaults to ``None``, i.e., ``'%Y-%m-%d %H:%M'``. """ results = None groups = None items = None group = None content = None contentInfo = None startTime = None orgTools = None if dateTimeFormat is None: dateTimeFormat = '%Y-%m-%d %H:%M' scriptStartTime = datetime.datetime.now() try: print ("********************Stage Content Started********************") print ("Script started at %s" % scriptStartTime.strftime(dateTimeFormat)) if self.securityhandler.valid == False: print ("Login required") else: orgTools = orgtools.orgtools(securityinfo=self) if orgTools is None: print ("Error creating org tools") else: for configFile in configFiles: config = common.init_config_json(config_file=configFile) if config is not None: if 'ContentItems' in config: startTime = datetime.datetime.now() print ("Processing config %s, starting at: %s" % (configFile,startTime.strftime(dateTimeFormat))) contentInfo = config['ContentItems'] for cont in contentInfo: content = cont['Content'] group = cont['ShareToGroup'] print ("Sharing content to: %s" % group) if os.path.isfile(content): with open(content, 'rb') as csvfile: items = [] groups = [] for row in csv.DictReader(csvfile,dialect='excel'): if cont['Type'] == "Group": groups.append(row['id']) elif cont['Type'] == "Items": items.append(row['id']) results = orgTools.shareItemsToGroup(shareToGroupName=group,items=items,groups=groups) print ("Config %s completed, time to complete: %s" % (configFile, str(datetime.datetime.now() - startTime))) else: print ("Config file missing ContentItems section") else: print ("Config %s not found" % configFile) except(TypeError,ValueError,AttributeError) as e: print (e) except (common.ArcRestHelperError) as e: print ("error in function: %s" % e[0]['function']) print ("error on line: %s" % e[0]['line']) print ("error in file name: %s" % e[0]['filename']) print ("with error message: %s" % e[0]['synerror']) if 'arcpyError' in e[0]: print ("with arcpy message: %s" % e[0]['arcpyError']) except Exception as e: if (reportToolsInstalled): if isinstance(e,(ReportTools.ReportToolsError,DataPrep.DataPrepError)): print ("error in function: %s" % e[0]['function']) print ("error on line: %s" % e[0]['line']) print ("error in file name: %s" % e[0]['filename']) print ("with error message: %s" % e[0]['synerror']) if 'arcpyError' in e[0]: print ("with arcpy message: %s" % e[0]['arcpyError']) else: line, filename, synerror = trace() print ("error on line: %s" % line) print ("error in file name: %s" % filename) print ("with error message: %s" % synerror) else: line, filename, synerror = trace() print ("error on line: %s" % line) print ("error in file name: %s" % filename) print ("with error message: %s" % synerror) finally: print ("Script complete, time to complete: %s" % str(datetime.datetime.now() - scriptStartTime)) print ("###############Stage Content Completed#################") print ("") #if orgTools is not None: #orgTools.dispose() results = None groups = None items = None group = None content = None contentInfo = None startTime = None orgTools = None del results del groups del items del group del content del contentInfo del startTime del orgTools gc.collect()
[ "def", "stageContent", "(", "self", ",", "configFiles", ",", "dateTimeFormat", "=", "None", ")", ":", "results", "=", "None", "groups", "=", "None", "items", "=", "None", "group", "=", "None", "content", "=", "None", "contentInfo", "=", "None", "startTime"...
Parses a JSON configuration file to stage content. Args: configFiles (list): A list of JSON files on disk containing configuration data for staging content. dateTimeFormat (str): A valid date formatting directive, as understood by :py:meth:`datetime.datetime.strftime`. Defaults to ``None``, i.e., ``'%Y-%m-%d %H:%M'``.
[ "Parses", "a", "JSON", "configuration", "file", "to", "stage", "content", "." ]
python
train
frascoweb/frasco-users
frasco_users/__init__.py
https://github.com/frascoweb/frasco-users/blob/16591ca466de5b7c80d7a2384327d9cf2d919c41/frasco_users/__init__.py#L664-L684
def gen_reset_password_token(self, user=None, send_email=None): """Generates a reset password token and optionnaly (default to yes) send the reset password email """ if not user and "form" in current_context.data and request.method == "POST": form = current_context.data.form user = self.find_by_email(form[self.options["email_column"]].data) if user is None: if self.options["reset_password_token_error_message"]: flash(self.options["reset_password_token_error_message"], "error") current_context.exit(trigger_action_group="reset_password_failed") if not user: raise InvalidOptionError("Invalid user in 'reset_password_token' action") token = self._gen_reset_password_token(user) self.reset_password_token_signal.send(self, user=user, token=token) if (send_email is None and self.options["send_reset_password_email"]) or send_email: to_email = getattr(user, self.options["email_column"]) current_app.features.emails.send(to_email, "users/reset_password.txt", user=user, token=token) return token
[ "def", "gen_reset_password_token", "(", "self", ",", "user", "=", "None", ",", "send_email", "=", "None", ")", ":", "if", "not", "user", "and", "\"form\"", "in", "current_context", ".", "data", "and", "request", ".", "method", "==", "\"POST\"", ":", "form"...
Generates a reset password token and optionnaly (default to yes) send the reset password email
[ "Generates", "a", "reset", "password", "token", "and", "optionnaly", "(", "default", "to", "yes", ")", "send", "the", "reset", "password", "email" ]
python
train
seleniumbase/SeleniumBase
seleniumbase/fixtures/base_case.py
https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/base_case.py#L1212-L1239
def __add_introjs_tour_step(self, message, selector=None, name=None, title=None, alignment=None): """ Allows the user to add tour steps for a website. @Params message - The message to display. selector - The CSS Selector of the Element to attach to. name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to. title - Additional header text that appears above the message. alignment - Choose from "top", "bottom", "left", and "right". ("top" is the default alignment). """ if selector != "html": element_row = "element: '%s'," % selector else: element_row = "" if title: message = "<center><b>" + title + "</b></center><hr>" + message message = '<font size=\"3\" color=\"#33475B\">' + message + '</font>' step = ("""{%s intro: '%s', position: '%s'}, """ % (element_row, message, alignment)) self._tour_steps[name].append(step)
[ "def", "__add_introjs_tour_step", "(", "self", ",", "message", ",", "selector", "=", "None", ",", "name", "=", "None", ",", "title", "=", "None", ",", "alignment", "=", "None", ")", ":", "if", "selector", "!=", "\"html\"", ":", "element_row", "=", "\"ele...
Allows the user to add tour steps for a website. @Params message - The message to display. selector - The CSS Selector of the Element to attach to. name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to. title - Additional header text that appears above the message. alignment - Choose from "top", "bottom", "left", and "right". ("top" is the default alignment).
[ "Allows", "the", "user", "to", "add", "tour", "steps", "for", "a", "website", "." ]
python
train
rcmalli/keras-squeezenet
keras_squeezenet/squeezenet.py
https://github.com/rcmalli/keras-squeezenet/blob/4fb9cb7510ea0315303090edbc1bd97c2916af81/keras_squeezenet/squeezenet.py#L44-L148
def SqueezeNet(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000): """Instantiates the SqueezeNet architecture. """ if weights not in {'imagenet', None}: raise ValueError('The `weights` argument should be either ' '`None` (random initialization) or `imagenet` ' '(pre-training on ImageNet).') if weights == 'imagenet' and classes != 1000: raise ValueError('If using `weights` as imagenet with `include_top`' ' as true, `classes` should be 1000') input_shape = _obtain_input_shape(input_shape, default_size=227, min_size=48, data_format=K.image_data_format(), require_flatten=include_top) if input_tensor is None: img_input = Input(shape=input_shape) else: if not K.is_keras_tensor(input_tensor): img_input = Input(tensor=input_tensor, shape=input_shape) else: img_input = input_tensor x = Convolution2D(64, (3, 3), strides=(2, 2), padding='valid', name='conv1')(img_input) x = Activation('relu', name='relu_conv1')(x) x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool1')(x) x = fire_module(x, fire_id=2, squeeze=16, expand=64) x = fire_module(x, fire_id=3, squeeze=16, expand=64) x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool3')(x) x = fire_module(x, fire_id=4, squeeze=32, expand=128) x = fire_module(x, fire_id=5, squeeze=32, expand=128) x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool5')(x) x = fire_module(x, fire_id=6, squeeze=48, expand=192) x = fire_module(x, fire_id=7, squeeze=48, expand=192) x = fire_module(x, fire_id=8, squeeze=64, expand=256) x = fire_module(x, fire_id=9, squeeze=64, expand=256) if include_top: # It's not obvious where to cut the network... # Could do the 8th or 9th layer... some work recommends cutting earlier layers. x = Dropout(0.5, name='drop9')(x) x = Convolution2D(classes, (1, 1), padding='valid', name='conv10')(x) x = Activation('relu', name='relu_conv10')(x) x = GlobalAveragePooling2D()(x) x = Activation('softmax', name='loss')(x) else: if pooling == 'avg': x = GlobalAveragePooling2D()(x) elif pooling=='max': x = GlobalMaxPooling2D()(x) elif pooling==None: pass else: raise ValueError("Unknown argument for 'pooling'=" + pooling) # Ensure that the model takes into account # any potential predecessors of `input_tensor`. if input_tensor is not None: inputs = get_source_inputs(input_tensor) else: inputs = img_input model = Model(inputs, x, name='squeezenet') # load weights if weights == 'imagenet': if include_top: weights_path = get_file('squeezenet_weights_tf_dim_ordering_tf_kernels.h5', WEIGHTS_PATH, cache_subdir='models') else: weights_path = get_file('squeezenet_weights_tf_dim_ordering_tf_kernels_notop.h5', WEIGHTS_PATH_NO_TOP, cache_subdir='models') model.load_weights(weights_path) if K.backend() == 'theano': layer_utils.convert_all_kernels_in_model(model) if K.image_data_format() == 'channels_first': if K.backend() == 'tensorflow': warnings.warn('You are using the TensorFlow backend, yet you ' 'are using the Theano ' 'image data format convention ' '(`image_data_format="channels_first"`). ' 'For best performance, set ' '`image_data_format="channels_last"` in ' 'your Keras config ' 'at ~/.keras/keras.json.') return model
[ "def", "SqueezeNet", "(", "include_top", "=", "True", ",", "weights", "=", "'imagenet'", ",", "input_tensor", "=", "None", ",", "input_shape", "=", "None", ",", "pooling", "=", "None", ",", "classes", "=", "1000", ")", ":", "if", "weights", "not", "in", ...
Instantiates the SqueezeNet architecture.
[ "Instantiates", "the", "SqueezeNet", "architecture", "." ]
python
train
mitsei/dlkit
dlkit/json_/assessment/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/objects.py#L2753-L2763
def get_taker_metadata(self): """Gets the metadata for a resource to manually set which resource will be taking the assessment. return: (osid.Metadata) - metadata for the resource *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['taker']) metadata.update({'existing_id_values': self._my_map['takerId']}) return Metadata(**metadata)
[ "def", "get_taker_metadata", "(", "self", ")", ":", "# Implemented from template for osid.resource.ResourceForm.get_group_metadata_template", "metadata", "=", "dict", "(", "self", ".", "_mdata", "[", "'taker'", "]", ")", "metadata", ".", "update", "(", "{", "'existing_i...
Gets the metadata for a resource to manually set which resource will be taking the assessment. return: (osid.Metadata) - metadata for the resource *compliance: mandatory -- This method must be implemented.*
[ "Gets", "the", "metadata", "for", "a", "resource", "to", "manually", "set", "which", "resource", "will", "be", "taking", "the", "assessment", "." ]
python
train
bmcfee/pumpp
pumpp/task/beat.py
https://github.com/bmcfee/pumpp/blob/06a17b888271dd1f6cd41bddb22b0eb04d494056/pumpp/task/beat.py#L265-L339
def transform_annotation(self, ann, duration): '''Transform an annotation to the beat-position encoding Parameters ---------- ann : jams.Annotation The annotation to convert duration : number > 0 The duration of the track Returns ------- data : dict data['position'] : np.ndarray, shape=(n, n_labels) or (n, 1) A time-varying label encoding of beat position ''' # 1. get all the events # 2. find all the downbeats # 3. map each downbeat to a subdivision counter # number of beats until the next downbeat # 4. pad out events to intervals # 5. encode each beat interval to its position boundaries, values = ann.to_interval_values() # Convert to intervals and span the duration # padding at the end of track does not propagate the right label # this is an artifact of inferring end-of-track from boundaries though boundaries = list(boundaries[:, 0]) if boundaries and boundaries[-1] < duration: boundaries.append(duration) intervals = boundaries_to_intervals(boundaries) intervals, values = adjust_intervals(intervals, values, t_min=0, t_max=duration, start_label=0, end_label=0) values = np.asarray(values, dtype=int) downbeats = np.flatnonzero(values == 1) position = [] for i, v in enumerate(values): # If the value is a 0, mark it as X and move on if v == 0: position.extend(self.encoder.transform(['X'])) continue # Otherwise, let's try to find the surrounding downbeats prev_idx = np.searchsorted(downbeats, i, side='right') - 1 next_idx = 1 + prev_idx if prev_idx >= 0 and next_idx < len(downbeats): # In this case, the subdivision is well-defined subdivision = downbeats[next_idx] - downbeats[prev_idx] elif prev_idx < 0 and next_idx < len(downbeats): subdivision = np.max(values[:downbeats[0]+1]) elif next_idx >= len(downbeats): subdivision = len(values) - downbeats[prev_idx] if subdivision > self.max_divisions or subdivision < 1: position.extend(self.encoder.transform(['X'])) else: position.extend(self.encoder.transform(['{:02d}/{:02d}'.format(subdivision, v)])) dtype = self.fields[self.scope('position')].dtype position = np.asarray(position) if self.sparse: position = position[:, np.newaxis] target = self.encode_intervals(duration, intervals, position, multi=False, dtype=dtype) return {'position': target}
[ "def", "transform_annotation", "(", "self", ",", "ann", ",", "duration", ")", ":", "# 1. get all the events", "# 2. find all the downbeats", "# 3. map each downbeat to a subdivision counter", "# number of beats until the next downbeat", "# 4. pad out events to intervals", "# 5. e...
Transform an annotation to the beat-position encoding Parameters ---------- ann : jams.Annotation The annotation to convert duration : number > 0 The duration of the track Returns ------- data : dict data['position'] : np.ndarray, shape=(n, n_labels) or (n, 1) A time-varying label encoding of beat position
[ "Transform", "an", "annotation", "to", "the", "beat", "-", "position", "encoding" ]
python
train
ulfalizer/Kconfiglib
examples/print_config_tree.py
https://github.com/ulfalizer/Kconfiglib/blob/9fe13c03de16c341cd7ed40167216207b821ea50/examples/print_config_tree.py#L173-L182
def print_menuconfig(kconf): """ Prints all menu entries for the configuration. """ # Print the expanded mainmenu text at the top. This is the same as # kconf.top_node.prompt[0], but with variable references expanded. print("\n======== {} ========\n".format(kconf.mainmenu_text)) print_menuconfig_nodes(kconf.top_node.list, 0) print("")
[ "def", "print_menuconfig", "(", "kconf", ")", ":", "# Print the expanded mainmenu text at the top. This is the same as", "# kconf.top_node.prompt[0], but with variable references expanded.", "print", "(", "\"\\n======== {} ========\\n\"", ".", "format", "(", "kconf", ".", "mainmenu_t...
Prints all menu entries for the configuration.
[ "Prints", "all", "menu", "entries", "for", "the", "configuration", "." ]
python
train
carpedm20/fbchat
fbchat/_client.py
https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L709-L722
def searchForGroups(self, name, limit=10): """ Find and get group thread by its name :param name: Name of the group thread :param limit: The max. amount of groups to fetch :return: :class:`models.Group` objects, ordered by relevance :rtype: list :raises: FBchatException if request failed """ params = {"search": name, "limit": limit} j = self.graphql_request(GraphQL(query=GraphQL.SEARCH_GROUP, params=params)) return [Group._from_graphql(node) for node in j["viewer"]["groups"]["nodes"]]
[ "def", "searchForGroups", "(", "self", ",", "name", ",", "limit", "=", "10", ")", ":", "params", "=", "{", "\"search\"", ":", "name", ",", "\"limit\"", ":", "limit", "}", "j", "=", "self", ".", "graphql_request", "(", "GraphQL", "(", "query", "=", "G...
Find and get group thread by its name :param name: Name of the group thread :param limit: The max. amount of groups to fetch :return: :class:`models.Group` objects, ordered by relevance :rtype: list :raises: FBchatException if request failed
[ "Find", "and", "get", "group", "thread", "by", "its", "name" ]
python
train
pypa/setuptools
setuptools/config.py
https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/config.py#L312-L354
def _parse_attr(cls, value, package_dir=None): """Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str """ attr_directive = 'attr:' if not value.startswith(attr_directive): return value attrs_path = value.replace(attr_directive, '').strip().split('.') attr_name = attrs_path.pop() module_name = '.'.join(attrs_path) module_name = module_name or '__init__' parent_path = os.getcwd() if package_dir: if attrs_path[0] in package_dir: # A custom path was specified for the module we want to import custom_path = package_dir[attrs_path[0]] parts = custom_path.rsplit('/', 1) if len(parts) > 1: parent_path = os.path.join(os.getcwd(), parts[0]) module_name = parts[1] else: module_name = custom_path elif '' in package_dir: # A custom parent directory was specified for all root modules parent_path = os.path.join(os.getcwd(), package_dir['']) sys.path.insert(0, parent_path) try: module = import_module(module_name) value = getattr(module, attr_name) finally: sys.path = sys.path[1:] return value
[ "def", "_parse_attr", "(", "cls", ",", "value", ",", "package_dir", "=", "None", ")", ":", "attr_directive", "=", "'attr:'", "if", "not", "value", ".", "startswith", "(", "attr_directive", ")", ":", "return", "value", "attrs_path", "=", "value", ".", "repl...
Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str
[ "Represents", "value", "as", "a", "module", "attribute", "." ]
python
train
GNS3/gns3-server
gns3server/controller/gns3vm/virtualbox_gns3_vm.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L129-L142
def _check_vbox_port_forwarding(self): """ Checks if the NAT port forwarding rule exists. :returns: boolean """ result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"]) for info in result.splitlines(): if '=' in info: name, value = info.split('=', 1) if name.startswith("Forwarding") and value.strip('"').startswith("GNS3VM"): return True return False
[ "def", "_check_vbox_port_forwarding", "(", "self", ")", ":", "result", "=", "yield", "from", "self", ".", "_execute", "(", "\"showvminfo\"", ",", "[", "self", ".", "_vmname", ",", "\"--machinereadable\"", "]", ")", "for", "info", "in", "result", ".", "splitl...
Checks if the NAT port forwarding rule exists. :returns: boolean
[ "Checks", "if", "the", "NAT", "port", "forwarding", "rule", "exists", "." ]
python
train
ojii/django-multilingual-ng
multilingual/admin.py
https://github.com/ojii/django-multilingual-ng/blob/0d320a0732ec59949380d4b5f21e153174d3ecf7/multilingual/admin.py#L314-L322
def placeholder_plugin_filter(self, request, queryset): """ This is only used on models which use placeholders from the django-cms """ if not request: return queryset if GLL.is_active: return queryset.filter(language=GLL.language_code) return queryset
[ "def", "placeholder_plugin_filter", "(", "self", ",", "request", ",", "queryset", ")", ":", "if", "not", "request", ":", "return", "queryset", "if", "GLL", ".", "is_active", ":", "return", "queryset", ".", "filter", "(", "language", "=", "GLL", ".", "langu...
This is only used on models which use placeholders from the django-cms
[ "This", "is", "only", "used", "on", "models", "which", "use", "placeholders", "from", "the", "django", "-", "cms" ]
python
train
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/containers.py#L368-L377
def add(self, **kwargs): """Adds a new element at the end of the list and returns it. Keyword arguments may be used to initialize the element. """ new_element = self._message_descriptor._concrete_class(**kwargs) new_element._SetListener(self._message_listener) self._values.append(new_element) if not self._message_listener.dirty: self._message_listener.Modified() return new_element
[ "def", "add", "(", "self", ",", "*", "*", "kwargs", ")", ":", "new_element", "=", "self", ".", "_message_descriptor", ".", "_concrete_class", "(", "*", "*", "kwargs", ")", "new_element", ".", "_SetListener", "(", "self", ".", "_message_listener", ")", "sel...
Adds a new element at the end of the list and returns it. Keyword arguments may be used to initialize the element.
[ "Adds", "a", "new", "element", "at", "the", "end", "of", "the", "list", "and", "returns", "it", ".", "Keyword", "arguments", "may", "be", "used", "to", "initialize", "the", "element", "." ]
python
train
ga4gh/ga4gh-server
ga4gh/server/datamodel/datasets.py
https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/datasets.py#L97-L105
def addFeatureSet(self, featureSet): """ Adds the specified featureSet to this dataset. """ id_ = featureSet.getId() self._featureSetIdMap[id_] = featureSet self._featureSetIds.append(id_) name = featureSet.getLocalId() self._featureSetNameMap[name] = featureSet
[ "def", "addFeatureSet", "(", "self", ",", "featureSet", ")", ":", "id_", "=", "featureSet", ".", "getId", "(", ")", "self", ".", "_featureSetIdMap", "[", "id_", "]", "=", "featureSet", "self", ".", "_featureSetIds", ".", "append", "(", "id_", ")", "name"...
Adds the specified featureSet to this dataset.
[ "Adds", "the", "specified", "featureSet", "to", "this", "dataset", "." ]
python
train
LonamiWebs/Telethon
telethon/tl/tlobject.py
https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/tlobject.py#L157-L172
def to_json(self, fp=None, default=_json_default, **kwargs): """ Represent the current `TLObject` as JSON. If ``fp`` is given, the JSON will be dumped to said file pointer, otherwise a JSON string will be returned. Note that bytes and datetimes cannot be represented in JSON, so if those are found, they will be base64 encoded and ISO-formatted, respectively, by default. """ d = self.to_dict() if fp: return json.dump(d, fp, default=default, **kwargs) else: return json.dumps(d, default=default, **kwargs)
[ "def", "to_json", "(", "self", ",", "fp", "=", "None", ",", "default", "=", "_json_default", ",", "*", "*", "kwargs", ")", ":", "d", "=", "self", ".", "to_dict", "(", ")", "if", "fp", ":", "return", "json", ".", "dump", "(", "d", ",", "fp", ","...
Represent the current `TLObject` as JSON. If ``fp`` is given, the JSON will be dumped to said file pointer, otherwise a JSON string will be returned. Note that bytes and datetimes cannot be represented in JSON, so if those are found, they will be base64 encoded and ISO-formatted, respectively, by default.
[ "Represent", "the", "current", "TLObject", "as", "JSON", "." ]
python
train
tdryer/hangups
hangups/message_parser.py
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/message_parser.py#L87-L89
def markdown(tag): """Return start and end regex pattern sequences for simple Markdown tag.""" return (MARKDOWN_START.format(tag=tag), MARKDOWN_END.format(tag=tag))
[ "def", "markdown", "(", "tag", ")", ":", "return", "(", "MARKDOWN_START", ".", "format", "(", "tag", "=", "tag", ")", ",", "MARKDOWN_END", ".", "format", "(", "tag", "=", "tag", ")", ")" ]
Return start and end regex pattern sequences for simple Markdown tag.
[ "Return", "start", "and", "end", "regex", "pattern", "sequences", "for", "simple", "Markdown", "tag", "." ]
python
valid
ciena/afkak
afkak/consumer.py
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/consumer.py#L765-L856
def _handle_fetch_response(self, responses): """The callback handling the successful response from the fetch request Delivers the message list to the processor, handles per-message errors (ConsumerFetchSizeTooSmall), triggers another fetch request If the processor is still processing the last batch of messages, we defer this processing until it's done. Otherwise, we start another fetch request and submit the messages to the processor """ # Successful fetch, reset our retry delay self.retry_delay = self.retry_init_delay self._fetch_attempt_count = 1 # Check to see if we are still processing the last block we fetched... if self._msg_block_d: # We are still working through the last block of messages... # We have to wait until it's done, then process this response self._msg_block_d.addCallback( lambda _: self._handle_fetch_response(responses)) return # No ongoing processing, great, let's get some started. # Request no longer outstanding, clear the deferred tracker so we # can refetch self._request_d = None messages = [] try: for resp in responses: # We should really only ever get one... if resp.partition != self.partition: log.warning( "%r: Got response with partition: %r not our own: %r", self, resp.partition, self.partition) continue # resp.messages is a KafkaCodec._decode_message_set_iter # Note that 'message' here is really an OffsetAndMessage for message in resp.messages: # Check for messages included which are from prior to our # desired offset: can happen due to compressed message sets if message.offset < self._fetch_offset: log.debug( 'Skipping message at offset: %d, because its ' 'offset is less that our fetch offset: %d.', message.offset, self._fetch_offset) continue # Create a 'SourcedMessage' and add it to the messages list messages.append( SourcedMessage( message=message.message, offset=message.offset, topic=self.topic, partition=self.partition)) # Update our notion of from where to fetch. self._fetch_offset = message.offset + 1 except ConsumerFetchSizeTooSmall: # A message was too large for us to receive, given our current # buffer size. Grow it until it works, or we hit our max # Grow by 16x up to 1MB (could result in 16MB buf), then by 2x factor = 2 if self.buffer_size <= 2**20: factor = 16 if self.max_buffer_size is None: # No limit, increase until we succeed or fail to alloc RAM self.buffer_size *= factor elif (self.max_buffer_size is not None and self.buffer_size < self.max_buffer_size): # Limited, but currently below it. self.buffer_size = min( self.buffer_size * factor, self.max_buffer_size) else: # We failed, and are already at our max. Nothing we can do but # create a Failure and errback() our start() deferred log.error("Max fetch size %d too small", self.max_buffer_size) failure = Failure( ConsumerFetchSizeTooSmall( "Max buffer size:%d too small for message", self.max_buffer_size)) self._start_d.errback(failure) return log.debug( "Next message larger than fetch size, increasing " "to %d (~2x) and retrying", self.buffer_size) finally: # If we were able to extract any messages, deliver them to the # processor now. if messages: self._msg_block_d = Deferred() self._process_messages(messages) # start another fetch, if needed, but use callLater to avoid recursion self._retry_fetch(0)
[ "def", "_handle_fetch_response", "(", "self", ",", "responses", ")", ":", "# Successful fetch, reset our retry delay", "self", ".", "retry_delay", "=", "self", ".", "retry_init_delay", "self", ".", "_fetch_attempt_count", "=", "1", "# Check to see if we are still processing...
The callback handling the successful response from the fetch request Delivers the message list to the processor, handles per-message errors (ConsumerFetchSizeTooSmall), triggers another fetch request If the processor is still processing the last batch of messages, we defer this processing until it's done. Otherwise, we start another fetch request and submit the messages to the processor
[ "The", "callback", "handling", "the", "successful", "response", "from", "the", "fetch", "request" ]
python
train
praekeltfoundation/molo.yourtips
molo/yourtips/templatetags/tip_tags.py
https://github.com/praekeltfoundation/molo.yourtips/blob/8b3e3b1ff52cd4a78ccca5d153b3909a1f21625f/molo/yourtips/templatetags/tip_tags.py#L13-L48
def your_tips_on_homepage(context): """ A template tag for the Tip of the Day on the homepage. Note that: * If there is an active featured_in_homepage tip it will take precedence. * If there is no featured tip a popular tip will be displayed. * If there is no featured tip and no popular tip, the most recent tip will be displayed. :param context: takes context """ context = copy(context) site_main = context['request'].site.root_page if get_your_tip(context): tip_on_homepage = (YourTipsArticlePage.objects .descendant_of(site_main) .filter(featured_in_homepage=True) .order_by('-featured_in_homepage_start_date') .first()) if not tip_on_homepage: tip_on_homepage = (YourTipsArticlePage.objects .descendant_of(site_main) .order_by('-total_upvotes') .first()) if not tip_on_homepage: tip_on_homepage = (YourTipsArticlePage.objects .descendant_of(site_main) .order_by('-latest_revision_created_at') .first()) context.update({ 'article_tip': tip_on_homepage, 'your_tip_page_slug': get_your_tip(context).slug }) return context
[ "def", "your_tips_on_homepage", "(", "context", ")", ":", "context", "=", "copy", "(", "context", ")", "site_main", "=", "context", "[", "'request'", "]", ".", "site", ".", "root_page", "if", "get_your_tip", "(", "context", ")", ":", "tip_on_homepage", "=", ...
A template tag for the Tip of the Day on the homepage. Note that: * If there is an active featured_in_homepage tip it will take precedence. * If there is no featured tip a popular tip will be displayed. * If there is no featured tip and no popular tip, the most recent tip will be displayed. :param context: takes context
[ "A", "template", "tag", "for", "the", "Tip", "of", "the", "Day", "on", "the", "homepage", ".", "Note", "that", ":", "*", "If", "there", "is", "an", "active", "featured_in_homepage", "tip", "it", "will", "take", "precedence", ".", "*", "If", "there", "i...
python
train
roclark/sportsreference
sportsreference/ncaab/boxscore.py
https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaab/boxscore.py#L824-L835
def losing_name(self): """ Returns a ``string`` of the losing team's name, such as 'Indiana' Hoosiers'. """ if self.winner == HOME: if 'cbb/schools' not in str(self._away_name): return str(self._away_name) return self._away_name.text() if 'cbb/schools' not in str(self._home_name): return str(self._home_name) return self._home_name.text()
[ "def", "losing_name", "(", "self", ")", ":", "if", "self", ".", "winner", "==", "HOME", ":", "if", "'cbb/schools'", "not", "in", "str", "(", "self", ".", "_away_name", ")", ":", "return", "str", "(", "self", ".", "_away_name", ")", "return", "self", ...
Returns a ``string`` of the losing team's name, such as 'Indiana' Hoosiers'.
[ "Returns", "a", "string", "of", "the", "losing", "team", "s", "name", "such", "as", "Indiana", "Hoosiers", "." ]
python
train
gwpy/gwpy
gwpy/table/io/sql.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/table/io/sql.py#L29-L47
def format_db_selection(selection, engine=None): """Format a column filter selection as a SQL database WHERE string """ # parse selection for SQL query if selection is None: return '' selections = [] for col, op_, value in parse_column_filters(selection): if engine and engine.name == 'postgresql': col = '"%s"' % col try: opstr = [key for key in OPERATORS if OPERATORS[key] is op_][0] except KeyError: raise ValueError("Cannot format database 'WHERE' command with " "selection operator %r" % op_) selections.append('{0} {1} {2!r}'.format(col, opstr, value)) if selections: return 'WHERE %s' % ' AND '.join(selections) return ''
[ "def", "format_db_selection", "(", "selection", ",", "engine", "=", "None", ")", ":", "# parse selection for SQL query", "if", "selection", "is", "None", ":", "return", "''", "selections", "=", "[", "]", "for", "col", ",", "op_", ",", "value", "in", "parse_c...
Format a column filter selection as a SQL database WHERE string
[ "Format", "a", "column", "filter", "selection", "as", "a", "SQL", "database", "WHERE", "string" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_layers.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L1037-L1040
def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 1d convolutions.""" return conv_block_internal(conv1d, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
[ "def", "conv1d_block", "(", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", "kwargs", ")", ":", "return", "conv_block_internal", "(", "conv1d", ",", "inputs", ",", "filters", ",", "dilation_rates_and_kernel_sizes", ",", "*", "*", ...
A block of standard 1d convolutions.
[ "A", "block", "of", "standard", "1d", "convolutions", "." ]
python
train
cohorte/cohorte-herald
python/snippets/herald_irc/bonus.py
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_irc/bonus.py#L29-L33
def cmd_echo(self, connection, sender, target, payload): """ Echoes the given payload """ connection.privmsg(target, payload or "Hello, {0}".format(sender))
[ "def", "cmd_echo", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "payload", ")", ":", "connection", ".", "privmsg", "(", "target", ",", "payload", "or", "\"Hello, {0}\"", ".", "format", "(", "sender", ")", ")" ]
Echoes the given payload
[ "Echoes", "the", "given", "payload" ]
python
train
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L912-L918
def get_name_at( self, name, block_number, include_expired=False ): """ Generate and return the sequence of of states a name record was in at a particular block number. """ cur = self.db.cursor() return namedb_get_name_at(cur, name, block_number, include_expired=include_expired)
[ "def", "get_name_at", "(", "self", ",", "name", ",", "block_number", ",", "include_expired", "=", "False", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_get_name_at", "(", "cur", ",", "name", ",", "block_number", ","...
Generate and return the sequence of of states a name record was in at a particular block number.
[ "Generate", "and", "return", "the", "sequence", "of", "of", "states", "a", "name", "record", "was", "in", "at", "a", "particular", "block", "number", "." ]
python
train
quodlibet/mutagen
mutagen/dsf.py
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/dsf.py#L338-L355
def delete(filething): """Remove tags from a file. Args: filething (filething) Raises: mutagen.MutagenError """ dsf_file = DSFFile(filething.fileobj) if dsf_file.dsd_chunk.offset_metdata_chunk != 0: id3_location = dsf_file.dsd_chunk.offset_metdata_chunk dsf_file.dsd_chunk.offset_metdata_chunk = 0 dsf_file.dsd_chunk.write() filething.fileobj.seek(id3_location) filething.fileobj.truncate()
[ "def", "delete", "(", "filething", ")", ":", "dsf_file", "=", "DSFFile", "(", "filething", ".", "fileobj", ")", "if", "dsf_file", ".", "dsd_chunk", ".", "offset_metdata_chunk", "!=", "0", ":", "id3_location", "=", "dsf_file", ".", "dsd_chunk", ".", "offset_m...
Remove tags from a file. Args: filething (filething) Raises: mutagen.MutagenError
[ "Remove", "tags", "from", "a", "file", "." ]
python
train
huyingxi/Synonyms
synonyms/utils.py
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L140-L155
def deaccent(text): """ Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring. Return input string with accents removed, as unicode. >>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek") u'Sef chomutovskych komunistu dostal postou bily prasek' """ if not isinstance(text, unicode): # assume utf8 for byte strings, use default (strict) error handling text = text.decode('utf8') norm = unicodedata.normalize("NFD", text) result = u('').join(ch for ch in norm if unicodedata.category(ch) != 'Mn') return unicodedata.normalize("NFC", result)
[ "def", "deaccent", "(", "text", ")", ":", "if", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "# assume utf8 for byte strings, use default (strict) error handling", "text", "=", "text", ".", "decode", "(", "'utf8'", ")", "norm", "=", "unicodedata", ...
Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring. Return input string with accents removed, as unicode. >>> deaccent("Šéf chomutovských komunistů dostal poštou bílý prášek") u'Sef chomutovskych komunistu dostal postou bily prasek'
[ "Remove", "accentuation", "from", "the", "given", "string", ".", "Input", "text", "is", "either", "a", "unicode", "string", "or", "utf8", "encoded", "bytestring", "." ]
python
train
wummel/linkchecker
third_party/dnspython/dns/zone.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/zone.py#L456-L504
def to_file(self, f, sorted=True, relativize=True, nl=None): """Write a zone to a file. @param f: file or string. If I{f} is a string, it is treated as the name of a file to open. @param sorted: if True, the file will be written with the names sorted in DNSSEC order from least to greatest. Otherwise the names will be written in whatever order they happen to have in the zone's dictionary. @param relativize: if True, domain names in the output will be relativized to the zone's origin (if possible). @type relativize: bool @param nl: The end of line string. If not specified, the output will use the platform's native end-of-line marker (i.e. LF on POSIX, CRLF on Windows, CR on Macintosh). @type nl: string or None """ if sys.hexversion >= 0x02030000: # allow Unicode filenames str_type = basestring else: str_type = str if nl is None: opts = 'w' else: opts = 'wb' if isinstance(f, str_type): f = file(f, opts) want_close = True else: want_close = False try: if sorted: names = self.keys() names.sort() else: names = self.iterkeys() for n in names: l = self[n].to_text(n, origin=self.origin, relativize=relativize) if nl is None: print >> f, l else: f.write(l) f.write(nl) finally: if want_close: f.close()
[ "def", "to_file", "(", "self", ",", "f", ",", "sorted", "=", "True", ",", "relativize", "=", "True", ",", "nl", "=", "None", ")", ":", "if", "sys", ".", "hexversion", ">=", "0x02030000", ":", "# allow Unicode filenames", "str_type", "=", "basestring", "e...
Write a zone to a file. @param f: file or string. If I{f} is a string, it is treated as the name of a file to open. @param sorted: if True, the file will be written with the names sorted in DNSSEC order from least to greatest. Otherwise the names will be written in whatever order they happen to have in the zone's dictionary. @param relativize: if True, domain names in the output will be relativized to the zone's origin (if possible). @type relativize: bool @param nl: The end of line string. If not specified, the output will use the platform's native end-of-line marker (i.e. LF on POSIX, CRLF on Windows, CR on Macintosh). @type nl: string or None
[ "Write", "a", "zone", "to", "a", "file", "." ]
python
train
pinax/pinax-comments
pinax/comments/templatetags/pinax_comments_tags.py
https://github.com/pinax/pinax-comments/blob/3c239b929075d3843f6ed2d07c94b022e6c5b5ff/pinax/comments/templatetags/pinax_comments_tags.py#L52-L62
def comment_form(context, object): """ Usage: {% comment_form obj as comment_form %} Will read the `user` var out of the contex to know if the form should be form an auth'd user or not. """ user = context.get("user") form_class = context.get("form", CommentForm) form = form_class(obj=object, user=user) return form
[ "def", "comment_form", "(", "context", ",", "object", ")", ":", "user", "=", "context", ".", "get", "(", "\"user\"", ")", "form_class", "=", "context", ".", "get", "(", "\"form\"", ",", "CommentForm", ")", "form", "=", "form_class", "(", "obj", "=", "o...
Usage: {% comment_form obj as comment_form %} Will read the `user` var out of the contex to know if the form should be form an auth'd user or not.
[ "Usage", ":", "{", "%", "comment_form", "obj", "as", "comment_form", "%", "}", "Will", "read", "the", "user", "var", "out", "of", "the", "contex", "to", "know", "if", "the", "form", "should", "be", "form", "an", "auth", "d", "user", "or", "not", "." ...
python
train
clinicedc/edc-notification
edc_notification/notification/model_notification.py
https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/notification/model_notification.py#L52-L64
def notify(self, force_notify=None, use_email=None, use_sms=None, **kwargs): """Overridden to only call `notify` if model matches. """ notified = False instance = kwargs.get("instance") if instance._meta.label_lower == self.model: notified = super().notify( force_notify=force_notify, use_email=use_email, use_sms=use_sms, **kwargs, ) return notified
[ "def", "notify", "(", "self", ",", "force_notify", "=", "None", ",", "use_email", "=", "None", ",", "use_sms", "=", "None", ",", "*", "*", "kwargs", ")", ":", "notified", "=", "False", "instance", "=", "kwargs", ".", "get", "(", "\"instance\"", ")", ...
Overridden to only call `notify` if model matches.
[ "Overridden", "to", "only", "call", "notify", "if", "model", "matches", "." ]
python
train
brainiak/brainiak
brainiak/reprsimil/brsa.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/reprsimil/brsa.py#L991-L1004
def _prepare_DF(self, n_T, scan_onsets=None): """ Prepare the essential template matrices D and F for pre-calculating some terms to be re-used. The inverse covariance matrix of AR(1) noise is sigma^-2 * (I - rho1*D + rho1**2 * F). And we denote A = I - rho1*D + rho1**2 * F""" run_TRs, n_run = self._run_TR_from_scan_onsets(n_T, scan_onsets) D_ele = map(self._D_gen, run_TRs) F_ele = map(self._F_gen, run_TRs) D = scipy.linalg.block_diag(*D_ele) F = scipy.linalg.block_diag(*F_ele) # D and F above are templates for constructing # the inverse of temporal covariance matrix of noise return D, F, run_TRs, n_run
[ "def", "_prepare_DF", "(", "self", ",", "n_T", ",", "scan_onsets", "=", "None", ")", ":", "run_TRs", ",", "n_run", "=", "self", ".", "_run_TR_from_scan_onsets", "(", "n_T", ",", "scan_onsets", ")", "D_ele", "=", "map", "(", "self", ".", "_D_gen", ",", ...
Prepare the essential template matrices D and F for pre-calculating some terms to be re-used. The inverse covariance matrix of AR(1) noise is sigma^-2 * (I - rho1*D + rho1**2 * F). And we denote A = I - rho1*D + rho1**2 * F
[ "Prepare", "the", "essential", "template", "matrices", "D", "and", "F", "for", "pre", "-", "calculating", "some", "terms", "to", "be", "re", "-", "used", ".", "The", "inverse", "covariance", "matrix", "of", "AR", "(", "1", ")", "noise", "is", "sigma^", ...
python
train
bitesofcode/projexui
projexui/xapplication.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xapplication.py#L436-L446
def storagePath(self, location): """ Returns the path associated with this application and user for the given location. :param location | <QtGui.QDesktopServices.StandardLocation> :return <str> """ default = nativestring(QtGui.QDesktopServices.storageLocation(location)) return self._storagePaths.get(location, default)
[ "def", "storagePath", "(", "self", ",", "location", ")", ":", "default", "=", "nativestring", "(", "QtGui", ".", "QDesktopServices", ".", "storageLocation", "(", "location", ")", ")", "return", "self", ".", "_storagePaths", ".", "get", "(", "location", ",", ...
Returns the path associated with this application and user for the given location. :param location | <QtGui.QDesktopServices.StandardLocation> :return <str>
[ "Returns", "the", "path", "associated", "with", "this", "application", "and", "user", "for", "the", "given", "location", ".", ":", "param", "location", "|", "<QtGui", ".", "QDesktopServices", ".", "StandardLocation", ">", ":", "return", "<str", ">" ]
python
train
brocade/pynos
pynos/versions/base/yang/ietf_netconf.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/ietf_netconf.py#L57-L68
def get_config_input_with_defaults(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_config = ET.Element("get_config") config = get_config input = ET.SubElement(get_config, "input") with_defaults = ET.SubElement(input, "with-defaults", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults") with_defaults.text = kwargs.pop('with_defaults') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "get_config_input_with_defaults", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_config", "=", "ET", ".", "Element", "(", "\"get_config\"", ")", "config", "=", "get_config", "input", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ifl.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/ifl.py#L40-L63
def generate(env): """Add Builders and construction variables for ifl to an Environment.""" fscan = FortranScan("FORTRANPATH") SCons.Tool.SourceFileScanner.add_scanner('.i', fscan) SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan) if 'FORTRANFILESUFFIXES' not in env: env['FORTRANFILESUFFIXES'] = ['.i'] else: env['FORTRANFILESUFFIXES'].append('.i') if 'F90FILESUFFIXES' not in env: env['F90FILESUFFIXES'] = ['.i90'] else: env['F90FILESUFFIXES'].append('.i90') add_all_to_env(env) env['FORTRAN'] = 'ifl' env['SHFORTRAN'] = '$FORTRAN' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET'
[ "def", "generate", "(", "env", ")", ":", "fscan", "=", "FortranScan", "(", "\"FORTRANPATH\"", ")", "SCons", ".", "Tool", ".", "SourceFileScanner", ".", "add_scanner", "(", "'.i'", ",", "fscan", ")", "SCons", ".", "Tool", ".", "SourceFileScanner", ".", "add...
Add Builders and construction variables for ifl to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "ifl", "to", "an", "Environment", "." ]
python
train
aws/aws-iot-device-sdk-python
AWSIoTPythonSDK/core/protocol/paho/client.py
https://github.com/aws/aws-iot-device-sdk-python/blob/f0aa2ce34b21dd2e44f4fb7e1d058656aaf2fc62/AWSIoTPythonSDK/core/protocol/paho/client.py#L1257-L1293
def will_set(self, topic, payload=None, qos=0, retain=False): """Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message to send as a will. If not given, or set to None a zero length message will be used as the will. Passing an int or float will result in the payload being converted to a string representing that number. If you wish to send a true int/float, use struct.pack() to create the payload you require. qos: The quality of service level to use for the will. retain: If set to true, the will message will be set as the "last known good"/retained message for the topic. Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has zero string length. """ if topic is None or len(topic) == 0: raise ValueError('Invalid topic.') if qos<0 or qos>2: raise ValueError('Invalid QoS level.') if isinstance(payload, str): self._will_payload = payload.encode('utf-8') elif isinstance(payload, bytearray): self._will_payload = payload elif isinstance(payload, int) or isinstance(payload, float): self._will_payload = str(payload) elif payload is None: self._will_payload = None else: raise TypeError('payload must be a string, bytearray, int, float or None.') self._will = True self._will_topic = topic.encode('utf-8') self._will_qos = qos self._will_retain = retain
[ "def", "will_set", "(", "self", ",", "topic", ",", "payload", "=", "None", ",", "qos", "=", "0", ",", "retain", "=", "False", ")", ":", "if", "topic", "is", "None", "or", "len", "(", "topic", ")", "==", "0", ":", "raise", "ValueError", "(", "'Inv...
Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message to send as a will. If not given, or set to None a zero length message will be used as the will. Passing an int or float will result in the payload being converted to a string representing that number. If you wish to send a true int/float, use struct.pack() to create the payload you require. qos: The quality of service level to use for the will. retain: If set to true, the will message will be set as the "last known good"/retained message for the topic. Raises a ValueError if qos is not 0, 1 or 2, or if topic is None or has zero string length.
[ "Set", "a", "Will", "to", "be", "sent", "by", "the", "broker", "in", "case", "the", "client", "disconnects", "unexpectedly", "." ]
python
train
bunchesofdonald/django-hermes
hermes/models.py
https://github.com/bunchesofdonald/django-hermes/blob/ff5395a7b5debfd0756aab43db61f7a6cfa06aea/hermes/models.py#L89-L91
def root_parent(self, category=None): """ Returns the topmost parent of the current category. """ return next(filter(lambda c: c.is_root, self.hierarchy()))
[ "def", "root_parent", "(", "self", ",", "category", "=", "None", ")", ":", "return", "next", "(", "filter", "(", "lambda", "c", ":", "c", ".", "is_root", ",", "self", ".", "hierarchy", "(", ")", ")", ")" ]
Returns the topmost parent of the current category.
[ "Returns", "the", "topmost", "parent", "of", "the", "current", "category", "." ]
python
train
nutechsoftware/alarmdecoder
alarmdecoder/messages/lrr/events.py
https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/messages/lrr/events.py#L7-L24
def get_event_description(event_type, event_code): """ Retrieves the human-readable description of an LRR event. :param event_type: Base LRR event type. Use LRR_EVENT_TYPE.* :type event_type: int :param event_code: LRR event code :type event_code: int :returns: string """ description = 'Unknown' lookup_map = LRR_TYPE_MAP.get(event_type, None) if lookup_map is not None: description = lookup_map.get(event_code, description) return description
[ "def", "get_event_description", "(", "event_type", ",", "event_code", ")", ":", "description", "=", "'Unknown'", "lookup_map", "=", "LRR_TYPE_MAP", ".", "get", "(", "event_type", ",", "None", ")", "if", "lookup_map", "is", "not", "None", ":", "description", "=...
Retrieves the human-readable description of an LRR event. :param event_type: Base LRR event type. Use LRR_EVENT_TYPE.* :type event_type: int :param event_code: LRR event code :type event_code: int :returns: string
[ "Retrieves", "the", "human", "-", "readable", "description", "of", "an", "LRR", "event", "." ]
python
train
quantopian/zipline
zipline/pipeline/loaders/earnings_estimates.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L282-L353
def collect_overwrites_for_sid(self, group, dates, requested_qtr_data, last_per_qtr, sid_idx, columns, all_adjustments_for_sid, sid): """ Given a sid, collect all overwrites that should be applied for this sid at each quarter boundary. Parameters ---------- group : pd.DataFrame The data for `sid`. dates : pd.DatetimeIndex The calendar dates for which estimates data is requested. requested_qtr_data : pd.DataFrame The DataFrame with the latest values for the requested quarter for all columns. last_per_qtr : pd.DataFrame A DataFrame with a column MultiIndex of [self.estimates.columns, normalized_quarters, sid] that allows easily getting the timeline of estimates for a particular sid for a particular quarter. sid_idx : int The sid's index in the asset index. columns : list of BoundColumn The columns for which the overwrites should be computed. all_adjustments_for_sid : dict[int -> AdjustedArray] A dictionary of the integer index of each timestamp into the date index, mapped to adjustments that should be applied at that index for the given sid (`sid`). This dictionary is modified as adjustments are collected. sid : int The sid for which overwrites should be computed. """ # If data was requested for only 1 date, there can never be any # overwrites, so skip the extra work. if len(dates) == 1: return next_qtr_start_indices = dates.searchsorted( group[EVENT_DATE_FIELD_NAME].values, side=self.searchsorted_side, ) qtrs_with_estimates = group.index.get_level_values( NORMALIZED_QUARTERS ).values for idx in next_qtr_start_indices: if 0 < idx < len(dates): # Find the quarter being requested in the quarter we're # crossing into. requested_quarter = requested_qtr_data[ SHIFTED_NORMALIZED_QTRS, sid, ].iloc[idx] # Only add adjustments if the next quarter starts somewhere # in our date index for this sid. Our 'next' quarter can # never start at index 0; a starting index of 0 means that # the next quarter's event date was NaT. self.create_overwrites_for_quarter( all_adjustments_for_sid, idx, last_per_qtr, qtrs_with_estimates, requested_quarter, sid, sid_idx, columns )
[ "def", "collect_overwrites_for_sid", "(", "self", ",", "group", ",", "dates", ",", "requested_qtr_data", ",", "last_per_qtr", ",", "sid_idx", ",", "columns", ",", "all_adjustments_for_sid", ",", "sid", ")", ":", "# If data was requested for only 1 date, there can never be...
Given a sid, collect all overwrites that should be applied for this sid at each quarter boundary. Parameters ---------- group : pd.DataFrame The data for `sid`. dates : pd.DatetimeIndex The calendar dates for which estimates data is requested. requested_qtr_data : pd.DataFrame The DataFrame with the latest values for the requested quarter for all columns. last_per_qtr : pd.DataFrame A DataFrame with a column MultiIndex of [self.estimates.columns, normalized_quarters, sid] that allows easily getting the timeline of estimates for a particular sid for a particular quarter. sid_idx : int The sid's index in the asset index. columns : list of BoundColumn The columns for which the overwrites should be computed. all_adjustments_for_sid : dict[int -> AdjustedArray] A dictionary of the integer index of each timestamp into the date index, mapped to adjustments that should be applied at that index for the given sid (`sid`). This dictionary is modified as adjustments are collected. sid : int The sid for which overwrites should be computed.
[ "Given", "a", "sid", "collect", "all", "overwrites", "that", "should", "be", "applied", "for", "this", "sid", "at", "each", "quarter", "boundary", "." ]
python
train
pymupdf/PyMuPDF
fitz/utils.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L291-L308
def searchFor(page, text, hit_max = 16, quads = False): """ Search for a string on a page. Args: text: string to be searched for hit_max: maximum hits quads: return quads instead of rectangles Returns: a list of rectangles or quads, each containing one occurrence. """ CheckParent(page) dl = page.getDisplayList() # create DisplayList tp = dl.getTextPage() # create TextPage # return list of hitting reactangles rlist = tp.search(text, hit_max = hit_max, quads = quads) dl = None tp = None return rlist
[ "def", "searchFor", "(", "page", ",", "text", ",", "hit_max", "=", "16", ",", "quads", "=", "False", ")", ":", "CheckParent", "(", "page", ")", "dl", "=", "page", ".", "getDisplayList", "(", ")", "# create DisplayList", "tp", "=", "dl", ".", "getTextPa...
Search for a string on a page. Args: text: string to be searched for hit_max: maximum hits quads: return quads instead of rectangles Returns: a list of rectangles or quads, each containing one occurrence.
[ "Search", "for", "a", "string", "on", "a", "page", "." ]
python
train
beetbox/audioread
audioread/gstdec.py
https://github.com/beetbox/audioread/blob/c8bedf7880f13a7b7488b108aaf245d648674818/audioread/gstdec.py#L287-L296
def _pad_added(self, element, pad): """The callback for GstElement's "pad-added" signal. """ # Decoded data is ready. Connect up the decoder, finally. name = pad.query_caps(None).to_string() if name.startswith('audio/x-raw'): nextpad = self.conv.get_static_pad('sink') if not nextpad.is_linked(): self._got_a_pad = True pad.link(nextpad)
[ "def", "_pad_added", "(", "self", ",", "element", ",", "pad", ")", ":", "# Decoded data is ready. Connect up the decoder, finally.", "name", "=", "pad", ".", "query_caps", "(", "None", ")", ".", "to_string", "(", ")", "if", "name", ".", "startswith", "(", "'au...
The callback for GstElement's "pad-added" signal.
[ "The", "callback", "for", "GstElement", "s", "pad", "-", "added", "signal", "." ]
python
train
monarch-initiative/dipper
dipper/sources/OMIM.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/OMIM.py#L1182-L1250
def _get_omimtype(entry, globaltt): """ (note: there is anlaternative using mimTitle in omia) Here, we look at the omim 'prefix' to help to type the entry. For now, we only classify omim entries as genes; the rest we leave alone. :param entry: :return: """ # An asterisk (*) before an entry number indicates a gene. # A number symbol (#) before an entry number indicates # that it is a descriptive entry, usually of a phenotype, # and does not represent a unique locus. # The reason for the use of the number symbol # is given in the first paragraph of the entry. # Discussion of any gene(s) related to the phenotype resides in # another entry(ies) as described in the first paragraph. # # A plus sign (+) before an entry number indicates that the # entry contains the description of a gene of # known sequence and a phenotype. # # A percent sign (%) before an entry number indicates that the # entry describes a confirmed mendelian phenotype or phenotypic locus # for which the underlying molecular basis is not known. # # No symbol before an entry number generally indicates a # description of a phenotype for which the mendelian basis, # although suspected, has not been clearly established # or that the separateness of this phenotype # from that in another entry is unclear. # # A caret (^) before an entry number means the # entry no longer exists because it was removed from the database # or moved to another entry as indicated. prefix = None type_id = None if 'prefix' in entry: prefix = entry['prefix'] if prefix == '*': # gene, may not have a known sequence or a phenotype # note that some genes are also phenotypes, # even in this class, like 102480 # examples: 102560,102480,100678,102750 type_id = globaltt['gene'] elif prefix == '#': # phenotype/disease -- indicate that here? # examples: 104200,105400,114480,115300,121900 # type_id = globaltt['Phenotype'] # 'UPHENO_0001001' # species agnostic # type_id = globaltt['human phenotypic abnormality'] pass elif prefix == '+': # gene of known sequence and has a phenotype # examples: 107670,110600,126453 type_id = globaltt['gene'] # doublecheck this elif prefix == '%': # this is a disease (with a known locus). # examples include: 102150,104000,107200,100070 type_id = globaltt['heritable_phenotypic_marker'] elif prefix == '': # this is probably just a phenotype pass return type_id
[ "def", "_get_omimtype", "(", "entry", ",", "globaltt", ")", ":", "# An asterisk (*) before an entry number indicates a gene.", "# A number symbol (#) before an entry number indicates", "# that it is a descriptive entry, usually of a phenotype,", "# and does not represent a unique locus.", "#...
(note: there is anlaternative using mimTitle in omia) Here, we look at the omim 'prefix' to help to type the entry. For now, we only classify omim entries as genes; the rest we leave alone. :param entry: :return:
[ "(", "note", ":", "there", "is", "anlaternative", "using", "mimTitle", "in", "omia", ")" ]
python
train
shazow/unstdlib.py
unstdlib/standard/datetime_.py
https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/datetime_.py#L16-L43
def iterate_date_values(d, start_date=None, stop_date=None, default=0): """ Convert (date, value) sorted lists into contiguous value-per-day data sets. Great for sparklines. Example:: [(datetime.date(2011, 1, 1), 1), (datetime.date(2011, 1, 4), 2)] -> [1, 0, 0, 2] """ dataiter = iter(d) cur_day, cur_val = next(dataiter) start_date = start_date or cur_day while cur_day < start_date: cur_day, cur_val = next(dataiter) for d in iterate_date(start_date, stop_date): if d != cur_day: yield default continue yield cur_val try: cur_day, cur_val = next(dataiter) except StopIteration: if not stop_date: raise
[ "def", "iterate_date_values", "(", "d", ",", "start_date", "=", "None", ",", "stop_date", "=", "None", ",", "default", "=", "0", ")", ":", "dataiter", "=", "iter", "(", "d", ")", "cur_day", ",", "cur_val", "=", "next", "(", "dataiter", ")", "start_date...
Convert (date, value) sorted lists into contiguous value-per-day data sets. Great for sparklines. Example:: [(datetime.date(2011, 1, 1), 1), (datetime.date(2011, 1, 4), 2)] -> [1, 0, 0, 2]
[ "Convert", "(", "date", "value", ")", "sorted", "lists", "into", "contiguous", "value", "-", "per", "-", "day", "data", "sets", ".", "Great", "for", "sparklines", "." ]
python
train
noahbenson/neuropythy
neuropythy/geometry/util.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/geometry/util.py#L216-L243
def line_intersection_2D(abarg, cdarg): ''' line_intersection((a, b), (c, d)) yields the intersection point between the lines that pass through the given pairs of points. If any lines are parallel, (numpy.nan, numpy.nan) is returned; note that a, b, c, and d can all be 2 x n matrices of x and y coordinate row-vectors. ''' ((x1,y1),(x2,y2)) = abarg ((x3,y3),(x4,y4)) = cdarg dx12 = (x1 - x2) dx34 = (x3 - x4) dy12 = (y1 - y2) dy34 = (y3 - y4) denom = dx12*dy34 - dy12*dx34 unit = np.isclose(denom, 0) if unit is True: return (np.nan, np.nan) denom = unit + denom q12 = (x1*y2 - y1*x2) / denom q34 = (x3*y4 - y3*x4) / denom xi = q12*dx34 - q34*dx12 yi = q12*dy34 - q34*dy12 if unit is False: return (xi, yi) elif unit is True: return (np.nan, np.nan) else: xi = np.asarray(xi) yi = np.asarray(yi) xi[unit] = np.nan yi[unit] = np.nan return (xi, yi)
[ "def", "line_intersection_2D", "(", "abarg", ",", "cdarg", ")", ":", "(", "(", "x1", ",", "y1", ")", ",", "(", "x2", ",", "y2", ")", ")", "=", "abarg", "(", "(", "x3", ",", "y3", ")", ",", "(", "x4", ",", "y4", ")", ")", "=", "cdarg", "dx12...
line_intersection((a, b), (c, d)) yields the intersection point between the lines that pass through the given pairs of points. If any lines are parallel, (numpy.nan, numpy.nan) is returned; note that a, b, c, and d can all be 2 x n matrices of x and y coordinate row-vectors.
[ "line_intersection", "((", "a", "b", ")", "(", "c", "d", "))", "yields", "the", "intersection", "point", "between", "the", "lines", "that", "pass", "through", "the", "given", "pairs", "of", "points", ".", "If", "any", "lines", "are", "parallel", "(", "nu...
python
train
invinst/ResponseBot
responsebot/responsebot_client.py
https://github.com/invinst/ResponseBot/blob/a6b1a431a343007f7ae55a193e432a61af22253f/responsebot/responsebot_client.py#L140-L153
def follow(self, user_id, notify=False): """ Follow a user. :param user_id: ID of the user in question :param notify: whether to notify the user about the following :return: user that are followed """ try: return User(self._client.create_friendship(user_id=user_id, follow=notify)._json) except TweepError as e: if e.api_code in [TWITTER_ACCOUNT_SUSPENDED_ERROR]: return self.get_user(user_id) raise
[ "def", "follow", "(", "self", ",", "user_id", ",", "notify", "=", "False", ")", ":", "try", ":", "return", "User", "(", "self", ".", "_client", ".", "create_friendship", "(", "user_id", "=", "user_id", ",", "follow", "=", "notify", ")", ".", "_json", ...
Follow a user. :param user_id: ID of the user in question :param notify: whether to notify the user about the following :return: user that are followed
[ "Follow", "a", "user", "." ]
python
train
sethmlarson/virtualbox-python
virtualbox/library_ext/console.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library_ext/console.py#L13-L22
def register_on_network_adapter_changed(self, callback): """Set the callback function to consume on network adapter changed events. Callback receives a INetworkAdapterChangedEvent object. Returns the callback_id """ event_type = library.VBoxEventType.on_network_adapter_changed return self.event_source.register_callback(callback, event_type)
[ "def", "register_on_network_adapter_changed", "(", "self", ",", "callback", ")", ":", "event_type", "=", "library", ".", "VBoxEventType", ".", "on_network_adapter_changed", "return", "self", ".", "event_source", ".", "register_callback", "(", "callback", ",", "event_t...
Set the callback function to consume on network adapter changed events. Callback receives a INetworkAdapterChangedEvent object. Returns the callback_id
[ "Set", "the", "callback", "function", "to", "consume", "on", "network", "adapter", "changed", "events", "." ]
python
train
pantsbuild/pants
src/python/pants/option/options.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/options.py#L300-L312
def registration_function_for_optionable(self, optionable_class): """Returns a function for registering options on the given scope.""" self._assert_not_frozen() # TODO(benjy): Make this an instance of a class that implements __call__, so we can # docstring it, and so it's less weird than attatching properties to a function. def register(*args, **kwargs): kwargs['registering_class'] = optionable_class self.register(optionable_class.options_scope, *args, **kwargs) # Clients can access the bootstrap option values as register.bootstrap. register.bootstrap = self.bootstrap_option_values() # Clients can access the scope as register.scope. register.scope = optionable_class.options_scope return register
[ "def", "registration_function_for_optionable", "(", "self", ",", "optionable_class", ")", ":", "self", ".", "_assert_not_frozen", "(", ")", "# TODO(benjy): Make this an instance of a class that implements __call__, so we can", "# docstring it, and so it's less weird than attatching prope...
Returns a function for registering options on the given scope.
[ "Returns", "a", "function", "for", "registering", "options", "on", "the", "given", "scope", "." ]
python
train