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
hardbyte/python-can
can/interfaces/systec/ucan.py
https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/systec/ucan.py#L548-L559
def get_msg_pending(self, channel, flags): """ Returns the number of pending CAN messages. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int flags: Flags specifies which buffers should be checked (see enum :class:`Pendin...
[ "def", "get_msg_pending", "(", "self", ",", "channel", ",", "flags", ")", ":", "count", "=", "DWORD", "(", "0", ")", "UcanGetMsgPending", "(", "self", ".", "_handle", ",", "channel", ",", "flags", ",", "byref", "(", "count", ")", ")", "return", "count"...
Returns the number of pending CAN messages. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0` or :data:`Channel.CHANNEL_CH1`). :param int flags: Flags specifies which buffers should be checked (see enum :class:`PendingFlags`). :return: The number of pending messages. ...
[ "Returns", "the", "number", "of", "pending", "CAN", "messages", "." ]
python
train
minhhoit/yacms
yacms/accounts/views.py
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/views.py#L103-L111
def profile(request, username, template="accounts/account_profile.html", extra_context=None): """ Display a profile. """ lookup = {"username__iexact": username, "is_active": True} context = {"profile_user": get_object_or_404(User, **lookup)} context.update(extra_context or {}) re...
[ "def", "profile", "(", "request", ",", "username", ",", "template", "=", "\"accounts/account_profile.html\"", ",", "extra_context", "=", "None", ")", ":", "lookup", "=", "{", "\"username__iexact\"", ":", "username", ",", "\"is_active\"", ":", "True", "}", "conte...
Display a profile.
[ "Display", "a", "profile", "." ]
python
train
tk0miya/tk.phpautodoc
src/phply/phpparse.py
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L477-L483
def p_class_declaration_statement(p): '''class_declaration_statement : class_entry_type STRING extends_from implements_list LBRACE class_statement_list RBRACE | INTERFACE STRING interface_extends_list LBRACE class_statement_list RBRACE''' if len(p) == 8: p[0] = ast.Cla...
[ "def", "p_class_declaration_statement", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "8", ":", "p", "[", "0", "]", "=", "ast", ".", "Class", "(", "p", "[", "2", "]", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "p", "["...
class_declaration_statement : class_entry_type STRING extends_from implements_list LBRACE class_statement_list RBRACE | INTERFACE STRING interface_extends_list LBRACE class_statement_list RBRACE
[ "class_declaration_statement", ":", "class_entry_type", "STRING", "extends_from", "implements_list", "LBRACE", "class_statement_list", "RBRACE", "|", "INTERFACE", "STRING", "interface_extends_list", "LBRACE", "class_statement_list", "RBRACE" ]
python
train
takuti/flurs
flurs/datasets/movielens.py
https://github.com/takuti/flurs/blob/a998fc180b45db7eaf38dbbbf8125a93100b8a8c/flurs/datasets/movielens.py#L151-L167
def delta(d1, d2, opt='d'): """Compute difference between given 2 dates in month/day. """ delta = 0 if opt == 'm': while True: mdays = monthrange(d1.year, d1.month)[1] d1 += timedelta(days=mdays) if d1 <= d2: delta += 1 else: ...
[ "def", "delta", "(", "d1", ",", "d2", ",", "opt", "=", "'d'", ")", ":", "delta", "=", "0", "if", "opt", "==", "'m'", ":", "while", "True", ":", "mdays", "=", "monthrange", "(", "d1", ".", "year", ",", "d1", ".", "month", ")", "[", "1", "]", ...
Compute difference between given 2 dates in month/day.
[ "Compute", "difference", "between", "given", "2", "dates", "in", "month", "/", "day", "." ]
python
train
cackharot/suds-py3
suds/bindings/rpc.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/bindings/rpc.py#L89-L98
def unmarshaller(self, typed=True): """ Get the appropriate XML decoder. @return: Either the (basic|typed) unmarshaller. @rtype: L{UmxTyped} """ if typed: return UmxEncoded(self.schema()) else: return RPC.unmarshaller(self, typed)
[ "def", "unmarshaller", "(", "self", ",", "typed", "=", "True", ")", ":", "if", "typed", ":", "return", "UmxEncoded", "(", "self", ".", "schema", "(", ")", ")", "else", ":", "return", "RPC", ".", "unmarshaller", "(", "self", ",", "typed", ")" ]
Get the appropriate XML decoder. @return: Either the (basic|typed) unmarshaller. @rtype: L{UmxTyped}
[ "Get", "the", "appropriate", "XML", "decoder", "." ]
python
train
saltstack/salt
salt/modules/kubernetesmod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1551-L1560
def __dict_to_pod_spec(spec): ''' Converts a dictionary into kubernetes V1PodSpec instance. ''' spec_obj = kubernetes.client.V1PodSpec() for key, value in iteritems(spec): if hasattr(spec_obj, key): setattr(spec_obj, key, value) return spec_obj
[ "def", "__dict_to_pod_spec", "(", "spec", ")", ":", "spec_obj", "=", "kubernetes", ".", "client", ".", "V1PodSpec", "(", ")", "for", "key", ",", "value", "in", "iteritems", "(", "spec", ")", ":", "if", "hasattr", "(", "spec_obj", ",", "key", ")", ":", ...
Converts a dictionary into kubernetes V1PodSpec instance.
[ "Converts", "a", "dictionary", "into", "kubernetes", "V1PodSpec", "instance", "." ]
python
train
woolfson-group/isambard
isambard/ampal/base_ampal.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/base_ampal.py#L22-L39
def find_atoms_within_distance(atoms, cutoff_distance, point): """Returns atoms within the distance from the point. Parameters ---------- atoms : [ampal.atom] A list of `ampal.atoms`. cutoff_distance : float Maximum distance from point. point : (float, float, float) Refe...
[ "def", "find_atoms_within_distance", "(", "atoms", ",", "cutoff_distance", ",", "point", ")", ":", "return", "[", "x", "for", "x", "in", "atoms", "if", "distance", "(", "x", ",", "point", ")", "<=", "cutoff_distance", "]" ]
Returns atoms within the distance from the point. Parameters ---------- atoms : [ampal.atom] A list of `ampal.atoms`. cutoff_distance : float Maximum distance from point. point : (float, float, float) Reference point, 3D coordinate. Returns ------- filtered_atom...
[ "Returns", "atoms", "within", "the", "distance", "from", "the", "point", "." ]
python
train
CityOfZion/neo-python
neo/Core/TX/Transaction.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L124-L133
def Serialize(self, writer): """ Serialize object. Args: writer (neo.IO.BinaryWriter): """ writer.WriteUInt256(self.AssetId) writer.WriteFixed8(self.Value) writer.WriteUInt160(self.ScriptHash)
[ "def", "Serialize", "(", "self", ",", "writer", ")", ":", "writer", ".", "WriteUInt256", "(", "self", ".", "AssetId", ")", "writer", ".", "WriteFixed8", "(", "self", ".", "Value", ")", "writer", ".", "WriteUInt160", "(", "self", ".", "ScriptHash", ")" ]
Serialize object. Args: writer (neo.IO.BinaryWriter):
[ "Serialize", "object", "." ]
python
train
floydhub/floyd-cli
floyd/cli/auth.py
https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/auth.py#L77-L98
def login(token, apikey, username, password): """ Login to FloydHub. """ if manual_login_success(token, username, password): return if not apikey: if has_browser(): apikey = wait_for_apikey() else: floyd_logger.error( "No browser found...
[ "def", "login", "(", "token", ",", "apikey", ",", "username", ",", "password", ")", ":", "if", "manual_login_success", "(", "token", ",", "username", ",", "password", ")", ":", "return", "if", "not", "apikey", ":", "if", "has_browser", "(", ")", ":", "...
Login to FloydHub.
[ "Login", "to", "FloydHub", "." ]
python
train
jxtech/wechatpy
wechatpy/client/api/tag.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/tag.py#L169-L185
def get_black_list(self, begin_openid=None): """ 获取公众号的黑名单列表 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1471422259_pJMWA :param begin_openid: 起始的 OpenID,传空则默认从头开始拉取 :return: 返回的 JSON 数据包 :rtype: dict """ data = {} if begin_openid: ...
[ "def", "get_black_list", "(", "self", ",", "begin_openid", "=", "None", ")", ":", "data", "=", "{", "}", "if", "begin_openid", ":", "data", "[", "'begin_openid'", "]", "=", "begin_openid", "return", "self", ".", "_post", "(", "'tags/members/getblacklist'", "...
获取公众号的黑名单列表 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1471422259_pJMWA :param begin_openid: 起始的 OpenID,传空则默认从头开始拉取 :return: 返回的 JSON 数据包 :rtype: dict
[ "获取公众号的黑名单列表", "详情请参考", "https", ":", "//", "mp", ".", "weixin", ".", "qq", ".", "com", "/", "wiki?id", "=", "mp1471422259_pJMWA" ]
python
train
aboSamoor/polyglot
polyglot/downloader.py
https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/downloader.py#L1280-L1344
def build_index(root, base_url): """ Create a new data.xml index file, by combining the xml description files for various packages and collections. ``root`` should be the path to a directory containing the package xml and zip files; and the collection xml files. The ``root`` directory is expected to have ...
[ "def", "build_index", "(", "root", ",", "base_url", ")", ":", "# Find all packages.", "packages", "=", "[", "]", "for", "pkg_xml", ",", "zf", ",", "subdir", "in", "_find_packages", "(", "os", ".", "path", ".", "join", "(", "root", ",", "'packages'", ")",...
Create a new data.xml index file, by combining the xml description files for various packages and collections. ``root`` should be the path to a directory containing the package xml and zip files; and the collection xml files. The ``root`` directory is expected to have the following subdirectories:: root/...
[ "Create", "a", "new", "data", ".", "xml", "index", "file", "by", "combining", "the", "xml", "description", "files", "for", "various", "packages", "and", "collections", ".", "root", "should", "be", "the", "path", "to", "a", "directory", "containing", "the", ...
python
train
HazyResearch/fonduer
src/fonduer/learning/disc_models/sparse_logistic_regression.py
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/learning/disc_models/sparse_logistic_regression.py#L134-L150
def _update_settings(self, X): """ Update the model argument. :param X: The input data of the model. :type X: list of (candidate, features) pair """ self.logger.info("Loading default parameters for Sparse Logistic Regression") config = get_config()["learning"]["...
[ "def", "_update_settings", "(", "self", ",", "X", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Loading default parameters for Sparse Logistic Regression\"", ")", "config", "=", "get_config", "(", ")", "[", "\"learning\"", "]", "[", "\"SparseLogisticRegressi...
Update the model argument. :param X: The input data of the model. :type X: list of (candidate, features) pair
[ "Update", "the", "model", "argument", "." ]
python
train
rapidpro/expressions
python/temba_expressions/evaluator.py
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/evaluator.py#L475-L481
def visitConcatenation(self, ctx): """ expression: expression AMPERSAND expression """ arg1 = conversions.to_string(self.visit(ctx.expression(0)), self._eval_context) arg2 = conversions.to_string(self.visit(ctx.expression(1)), self._eval_context) return arg1 + arg2
[ "def", "visitConcatenation", "(", "self", ",", "ctx", ")", ":", "arg1", "=", "conversions", ".", "to_string", "(", "self", ".", "visit", "(", "ctx", ".", "expression", "(", "0", ")", ")", ",", "self", ".", "_eval_context", ")", "arg2", "=", "conversion...
expression: expression AMPERSAND expression
[ "expression", ":", "expression", "AMPERSAND", "expression" ]
python
train
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_map/srtm.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_map/srtm.py#L121-L131
def createFileList(self): """SRTM data is split into different directories, get a list of all of them and create a dictionary for easy lookup.""" global childFileListDownload global filelistDownloadActive mypid = os.getpid() if mypid not in childFileListDownload or no...
[ "def", "createFileList", "(", "self", ")", ":", "global", "childFileListDownload", "global", "filelistDownloadActive", "mypid", "=", "os", ".", "getpid", "(", ")", "if", "mypid", "not", "in", "childFileListDownload", "or", "not", "childFileListDownload", "[", "myp...
SRTM data is split into different directories, get a list of all of them and create a dictionary for easy lookup.
[ "SRTM", "data", "is", "split", "into", "different", "directories", "get", "a", "list", "of", "all", "of", "them", "and", "create", "a", "dictionary", "for", "easy", "lookup", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/pipeline/variation.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/variation.py#L65-L75
def _normalize_vc_input(data): """Normalize different types of variant calling inputs. Handles standard and ensemble inputs. """ if data.get("ensemble"): for k in ["batch_samples", "validate", "vrn_file"]: data[k] = data["ensemble"][k] data["config"]["algorithm"]["variantcal...
[ "def", "_normalize_vc_input", "(", "data", ")", ":", "if", "data", ".", "get", "(", "\"ensemble\"", ")", ":", "for", "k", "in", "[", "\"batch_samples\"", ",", "\"validate\"", ",", "\"vrn_file\"", "]", ":", "data", "[", "k", "]", "=", "data", "[", "\"en...
Normalize different types of variant calling inputs. Handles standard and ensemble inputs.
[ "Normalize", "different", "types", "of", "variant", "calling", "inputs", "." ]
python
train
lsst-sqre/documenteer
documenteer/sphinxext/lssttasks/taskutils.py
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/taskutils.py#L82-L103
def get_subtask_fields(config_class): """Get all configurable subtask fields from a Config class. Parameters ---------- config_class : ``lsst.pipe.base.Config``-type The configuration class (not an instance) corresponding to a Task. Returns ------- subtask_fields : `dict` M...
[ "def", "get_subtask_fields", "(", "config_class", ")", ":", "from", "lsst", ".", "pex", ".", "config", "import", "ConfigurableField", ",", "RegistryField", "def", "is_subtask_field", "(", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "(", "Configur...
Get all configurable subtask fields from a Config class. Parameters ---------- config_class : ``lsst.pipe.base.Config``-type The configuration class (not an instance) corresponding to a Task. Returns ------- subtask_fields : `dict` Mapping where keys are the config attribute na...
[ "Get", "all", "configurable", "subtask", "fields", "from", "a", "Config", "class", "." ]
python
train
IdentityPython/fedoidcmsg
src/fedoidcmsg/utils.py
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/utils.py#L15-L33
def self_sign_jwks(keyjar, iss, kid='', lifetime=3600): """ Create a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. :param keyjar: A KeyJar instance with at least one private signing key :param iss: issuer of the JWT, should be the owner of the keys :param kid: ...
[ "def", "self_sign_jwks", "(", "keyjar", ",", "iss", ",", "kid", "=", "''", ",", "lifetime", "=", "3600", ")", ":", "# _json = json.dumps(jwks)", "_jwt", "=", "JWT", "(", "keyjar", ",", "iss", "=", "iss", ",", "lifetime", "=", "lifetime", ")", "jwks", "...
Create a signed JWT containing a JWKS. The JWT is signed by one of the keys in the JWKS. :param keyjar: A KeyJar instance with at least one private signing key :param iss: issuer of the JWT, should be the owner of the keys :param kid: A key ID if a special key should be used otherwise one is pi...
[ "Create", "a", "signed", "JWT", "containing", "a", "JWKS", ".", "The", "JWT", "is", "signed", "by", "one", "of", "the", "keys", "in", "the", "JWKS", "." ]
python
test
Crunch-io/crunch-cube
src/cr/cube/crunch_cube.py
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1401-L1416
def population_fraction(self): """The filtered/unfiltered ratio for cube response. This value is required for properly calculating population on a cube where a filter has been applied. Returns 1.0 for an unfiltered cube. Returns `np.nan` if the unfiltered count is zero, which would ...
[ "def", "population_fraction", "(", "self", ")", ":", "numerator", "=", "self", ".", "_cube_dict", "[", "\"result\"", "]", ".", "get", "(", "\"filtered\"", ",", "{", "}", ")", ".", "get", "(", "\"weighted_n\"", ")", "denominator", "=", "self", ".", "_cube...
The filtered/unfiltered ratio for cube response. This value is required for properly calculating population on a cube where a filter has been applied. Returns 1.0 for an unfiltered cube. Returns `np.nan` if the unfiltered count is zero, which would otherwise result in a divide-by-zero e...
[ "The", "filtered", "/", "unfiltered", "ratio", "for", "cube", "response", "." ]
python
train
draperjames/qtpandas
qtpandas/models/DataFrameModelManager.py
https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/models/DataFrameModelManager.py#L164-L173
def remove_file(self, filepath): """ Removes the DataFrameModel from being registered. :param filepath: (str) The filepath to delete from the DataFrameModelManager. :return: None """ self._models.pop(filepath) self._updates.pop(filepath, default=None) ...
[ "def", "remove_file", "(", "self", ",", "filepath", ")", ":", "self", ".", "_models", ".", "pop", "(", "filepath", ")", "self", ".", "_updates", ".", "pop", "(", "filepath", ",", "default", "=", "None", ")", "self", ".", "signalModelDestroyed", ".", "e...
Removes the DataFrameModel from being registered. :param filepath: (str) The filepath to delete from the DataFrameModelManager. :return: None
[ "Removes", "the", "DataFrameModel", "from", "being", "registered", ".", ":", "param", "filepath", ":", "(", "str", ")", "The", "filepath", "to", "delete", "from", "the", "DataFrameModelManager", ".", ":", "return", ":", "None" ]
python
train
pandas-dev/pandas
pandas/core/series.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/series.py#L540-L580
def nonzero(self): """ Return the *integer* indices of the elements that are non-zero. .. deprecated:: 0.24.0 Please use .to_numpy().nonzero() as a replacement. This method is equivalent to calling `numpy.nonzero` on the series data. For compatibility with NumPy, the...
[ "def", "nonzero", "(", "self", ")", ":", "msg", "=", "(", "\"Series.nonzero() is deprecated \"", "\"and will be removed in a future version.\"", "\"Use Series.to_numpy().nonzero() instead\"", ")", "warnings", ".", "warn", "(", "msg", ",", "FutureWarning", ",", "stacklevel",...
Return the *integer* indices of the elements that are non-zero. .. deprecated:: 0.24.0 Please use .to_numpy().nonzero() as a replacement. This method is equivalent to calling `numpy.nonzero` on the series data. For compatibility with NumPy, the return value is the same (a tu...
[ "Return", "the", "*", "integer", "*", "indices", "of", "the", "elements", "that", "are", "non", "-", "zero", "." ]
python
train
rbarrois/restricted_pkg
restricted_pkg/base.py
https://github.com/rbarrois/restricted_pkg/blob/abbd3cb33ed85af02fbb531fd85dda9c1b070c85/restricted_pkg/base.py#L137-L146
def prompt_auth(self): """Prompt the user for login/pass, if needed.""" if self.username and self.password: return sys.stdout.write("Please insert your credentials for %s\n" % self.url.base_url) while not self.username: self.username = raw_input("Username [%s]: " ...
[ "def", "prompt_auth", "(", "self", ")", ":", "if", "self", ".", "username", "and", "self", ".", "password", ":", "return", "sys", ".", "stdout", ".", "write", "(", "\"Please insert your credentials for %s\\n\"", "%", "self", ".", "url", ".", "base_url", ")",...
Prompt the user for login/pass, if needed.
[ "Prompt", "the", "user", "for", "login", "/", "pass", "if", "needed", "." ]
python
train
pydanny-archive/django-uni-form
uni_form/layout.py
https://github.com/pydanny-archive/django-uni-form/blob/159f539e2fb98752b7964d75e955fc62881c28fb/uni_form/layout.py#L95-L99
def render(self, form, form_style, context): """ Renders an `<input />` if container is used as a Layout object """ return render_to_string(self.template, Context({'input': self}))
[ "def", "render", "(", "self", ",", "form", ",", "form_style", ",", "context", ")", ":", "return", "render_to_string", "(", "self", ".", "template", ",", "Context", "(", "{", "'input'", ":", "self", "}", ")", ")" ]
Renders an `<input />` if container is used as a Layout object
[ "Renders", "an", "<input", "/", ">", "if", "container", "is", "used", "as", "a", "Layout", "object" ]
python
train
spotify/luigi
luigi/contrib/hdfs/snakebite_client.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/snakebite_client.py#L110-L126
def rename_dont_move(self, path, dest): """ Use snakebite.rename_dont_move, if available. :param path: source path (single input) :type path: string :param dest: destination path :type dest: string :return: True if succeeded :raises: snakebite.errors.File...
[ "def", "rename_dont_move", "(", "self", ",", "path", ",", "dest", ")", ":", "from", "snakebite", ".", "errors", "import", "FileAlreadyExistsException", "try", ":", "self", ".", "get_bite", "(", ")", ".", "rename2", "(", "path", ",", "dest", ",", "overwrite...
Use snakebite.rename_dont_move, if available. :param path: source path (single input) :type path: string :param dest: destination path :type dest: string :return: True if succeeded :raises: snakebite.errors.FileAlreadyExistsException
[ "Use", "snakebite", ".", "rename_dont_move", "if", "available", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/nose/config.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/config.py#L423-L568
def getParser(self, doc=None): """Get the command line option parser. """ if self.parser: return self.parser env = self.env parser = self.parserClass(doc) parser.add_option( "-V","--version", action="store_true", dest="version", default...
[ "def", "getParser", "(", "self", ",", "doc", "=", "None", ")", ":", "if", "self", ".", "parser", ":", "return", "self", ".", "parser", "env", "=", "self", ".", "env", "parser", "=", "self", ".", "parserClass", "(", "doc", ")", "parser", ".", "add_o...
Get the command line option parser.
[ "Get", "the", "command", "line", "option", "parser", "." ]
python
test
Contraz/demosys-py
demosys/timers/clock.py
https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/clock.py#L57-L69
def get_time(self) -> float: """ Get the current time in seconds Returns: The current time in seconds """ if self.pause_time is not None: curr_time = self.pause_time - self.offset - self.start_time return curr_time curr_time = time.ti...
[ "def", "get_time", "(", "self", ")", "->", "float", ":", "if", "self", ".", "pause_time", "is", "not", "None", ":", "curr_time", "=", "self", ".", "pause_time", "-", "self", ".", "offset", "-", "self", ".", "start_time", "return", "curr_time", "curr_time...
Get the current time in seconds Returns: The current time in seconds
[ "Get", "the", "current", "time", "in", "seconds" ]
python
valid
bitesofcode/projexui
projexui/widgets/xloggerwidget/xloggerwidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xloggerwidget/xloggerwidget.py#L479-L486
def setConfigurable(self, state): """ Sets whether or not this logger widget is configurable. :param state | <bool> """ self._configurable = state self._configButton.setVisible(state)
[ "def", "setConfigurable", "(", "self", ",", "state", ")", ":", "self", ".", "_configurable", "=", "state", "self", ".", "_configButton", ".", "setVisible", "(", "state", ")" ]
Sets whether or not this logger widget is configurable. :param state | <bool>
[ "Sets", "whether", "or", "not", "this", "logger", "widget", "is", "configurable", ".", ":", "param", "state", "|", "<bool", ">" ]
python
train
fishtown-analytics/dbt
plugins/bigquery/dbt/adapters/bigquery/impl.py
https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/plugins/bigquery/dbt/adapters/bigquery/impl.py#L196-L207
def _get_dbt_columns_from_bq_table(self, table): "Translates BQ SchemaField dicts into dbt BigQueryColumn objects" columns = [] for col in table.schema: # BigQuery returns type labels that are not valid type specifiers dtype = self.Column.translate_type(col.field_type) ...
[ "def", "_get_dbt_columns_from_bq_table", "(", "self", ",", "table", ")", ":", "columns", "=", "[", "]", "for", "col", "in", "table", ".", "schema", ":", "# BigQuery returns type labels that are not valid type specifiers", "dtype", "=", "self", ".", "Column", ".", ...
Translates BQ SchemaField dicts into dbt BigQueryColumn objects
[ "Translates", "BQ", "SchemaField", "dicts", "into", "dbt", "BigQueryColumn", "objects" ]
python
train
openstack/proliantutils
proliantutils/redfish/redfish.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/redfish/redfish.py#L269-L282
def press_pwr_btn(self): """Simulates a physical press of the server power button. :raises: IloError, on an error from iLO. """ sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID) try: sushy_system.push_power_button(sys_cons.PUSH_POWER_BUTTON_PRESS) exc...
[ "def", "press_pwr_btn", "(", "self", ")", ":", "sushy_system", "=", "self", ".", "_get_sushy_system", "(", "PROLIANT_SYSTEM_ID", ")", "try", ":", "sushy_system", ".", "push_power_button", "(", "sys_cons", ".", "PUSH_POWER_BUTTON_PRESS", ")", "except", "sushy", "."...
Simulates a physical press of the server power button. :raises: IloError, on an error from iLO.
[ "Simulates", "a", "physical", "press", "of", "the", "server", "power", "button", "." ]
python
train
cokelaer/spectrum
src/spectrum/yulewalker.py
https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/yulewalker.py#L23-L116
def aryule(X, order, norm='biased', allow_singularity=True): r"""Compute AR coefficients using Yule-Walker method :param X: Array of complex data values, X(1) to X(N) :param int order: Order of autoregressive process to be fitted (integer) :param str norm: Use a biased or unbiased correlation. :par...
[ "def", "aryule", "(", "X", ",", "order", ",", "norm", "=", "'biased'", ",", "allow_singularity", "=", "True", ")", ":", "assert", "norm", "in", "[", "'biased'", ",", "'unbiased'", "]", "r", "=", "CORRELATION", "(", "X", ",", "maxlags", "=", "order", ...
r"""Compute AR coefficients using Yule-Walker method :param X: Array of complex data values, X(1) to X(N) :param int order: Order of autoregressive process to be fitted (integer) :param str norm: Use a biased or unbiased correlation. :param bool allow_singularity: :return: * AR coefficient...
[ "r", "Compute", "AR", "coefficients", "using", "Yule", "-", "Walker", "method" ]
python
valid
gwastro/pycbc
pycbc/filter/matchedfilter.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/matchedfilter.py#L1318-L1364
def match(vec1, vec2, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None, v1_norm=None, v2_norm=None): """ Return the match between the two TimeSeries or FrequencySeries. Return the match between two waveforms. This is equivelant to the overlap maximized over time and phase. Par...
[ "def", "match", "(", "vec1", ",", "vec2", ",", "psd", "=", "None", ",", "low_frequency_cutoff", "=", "None", ",", "high_frequency_cutoff", "=", "None", ",", "v1_norm", "=", "None", ",", "v2_norm", "=", "None", ")", ":", "htilde", "=", "make_frequency_serie...
Return the match between the two TimeSeries or FrequencySeries. Return the match between two waveforms. This is equivelant to the overlap maximized over time and phase. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a waveform. vec2 : TimeSeries ...
[ "Return", "the", "match", "between", "the", "two", "TimeSeries", "or", "FrequencySeries", "." ]
python
train
skymill/automated-ebs-snapshots
automated_ebs_snapshots/volume_manager.py
https://github.com/skymill/automated-ebs-snapshots/blob/9595bc49d458f6ffb93430722757d2284e878fab/automated_ebs_snapshots/volume_manager.py#L210-L222
def unwatch_from_file(connection, file_name): """ Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None """ with open(file_name, 'r') as filehandl...
[ "def", "unwatch_from_file", "(", "connection", ",", "file_name", ")", ":", "with", "open", "(", "file_name", ",", "'r'", ")", "as", "filehandle", ":", "for", "line", "in", "filehandle", ".", "xreadlines", "(", ")", ":", "volume", ",", "interval", ",", "r...
Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None
[ "Start", "watching", "a", "new", "volume" ]
python
train
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/iam/apis/aggregator_account_admin_api.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/iam/apis/aggregator_account_admin_api.py#L1744-L1765
def get_account_certificate(self, account_id, cert_id, **kwargs): # noqa: E501 """Get trusted certificate by ID. # noqa: E501 An endpoint for retrieving a trusted certificate by ID. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates/{cert-id} -...
[ "def", "get_account_certificate", "(", "self", ",", "account_id", ",", "cert_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "re...
Get trusted certificate by ID. # noqa: E501 An endpoint for retrieving a trusted certificate by ID. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates/{cert-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes a synchronous HT...
[ "Get", "trusted", "certificate", "by", "ID", ".", "#", "noqa", ":", "E501" ]
python
train
saltstack/salt
salt/modules/vboxmanage.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L404-L494
def clonemedium(medium, uuid_in=None, file_in=None, uuid_out=None, file_out=None, mformat=None, variant=None, existing=False, **kwargs): ''' Clone a new VM from an existing VM CLI...
[ "def", "clonemedium", "(", "medium", ",", "uuid_in", "=", "None", ",", "file_in", "=", "None", ",", "uuid_out", "=", "None", ",", "file_out", "=", "None", ",", "mformat", "=", "None", ",", "variant", "=", "None", ",", "existing", "=", "False", ",", "...
Clone a new VM from an existing VM CLI Example: .. code-block:: bash salt 'hypervisor' vboxmanage.clonemedium <name> <new_name>
[ "Clone", "a", "new", "VM", "from", "an", "existing", "VM" ]
python
train
RedFantom/ttkwidgets
ttkwidgets/itemscanvas.py
https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/itemscanvas.py#L220-L243
def cget(self, key): """ Query widget option. :param key: option name :type key: str :return: value of the option To get the list of options for this widget, call the method :meth:`~ItemsCanvas.keys`. """ if key is "canvaswidth": return self....
[ "def", "cget", "(", "self", ",", "key", ")", ":", "if", "key", "is", "\"canvaswidth\"", ":", "return", "self", ".", "_canvaswidth", "elif", "key", "is", "\"canvasheight\"", ":", "return", "self", ".", "_canvasheight", "elif", "key", "is", "\"function_new\"",...
Query widget option. :param key: option name :type key: str :return: value of the option To get the list of options for this widget, call the method :meth:`~ItemsCanvas.keys`.
[ "Query", "widget", "option", "." ]
python
train
ga4gh/ga4gh-client
ga4gh/client/client.py
https://github.com/ga4gh/ga4gh-client/blob/d23b00b89112ef0930d45ee75aa3c6de3db615c5/ga4gh/client/client.py#L814-L826
def search_rna_quantifications(self, rna_quantification_set_id=""): """ Returns an iterator over the RnaQuantification objects from the server :param str rna_quantification_set_id: The ID of the :class:`ga4gh.protocol.RnaQuantificationSet` of interest. """ request = ...
[ "def", "search_rna_quantifications", "(", "self", ",", "rna_quantification_set_id", "=", "\"\"", ")", ":", "request", "=", "protocol", ".", "SearchRnaQuantificationsRequest", "(", ")", "request", ".", "rna_quantification_set_id", "=", "rna_quantification_set_id", "request...
Returns an iterator over the RnaQuantification objects from the server :param str rna_quantification_set_id: The ID of the :class:`ga4gh.protocol.RnaQuantificationSet` of interest.
[ "Returns", "an", "iterator", "over", "the", "RnaQuantification", "objects", "from", "the", "server" ]
python
train
Diviyan-Kalainathan/CausalDiscoveryToolbox
cdt/utils/graph.py
https://github.com/Diviyan-Kalainathan/CausalDiscoveryToolbox/blob/be228b078ba9eb76c01b3ccba9a1c0ad9e9e5ed1/cdt/utils/graph.py#L176-L213
def aracne(m, **kwargs): """Implementation of the ARACNE algorithm. Args: mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes it is a relevance matrix where mat(i,j) represents the similarity content between nodes i and j. Elements of matrix should be non-...
[ "def", "aracne", "(", "m", ",", "*", "*", "kwargs", ")", ":", "I0", "=", "kwargs", ".", "get", "(", "'I0'", ",", "0.0", ")", "# No default thresholding", "W0", "=", "kwargs", ".", "get", "(", "'W0'", ",", "0.05", ")", "# thresholding", "m", "=", "n...
Implementation of the ARACNE algorithm. Args: mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes it is a relevance matrix where mat(i,j) represents the similarity content between nodes i and j. Elements of matrix should be non-negative. Returns: mat_...
[ "Implementation", "of", "the", "ARACNE", "algorithm", "." ]
python
valid
boriel/zxbasic
zxb.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxb.py#L74-L351
def main(args=None): """ Entry point when executed from command line. You can use zxb.py as a module with import, and this function won't be executed. """ api.config.init() zxbpp.init() zxbparser.init() arch.zx48k.backend.init() arch.zx48k.Translator.reset() asmparse.init() ...
[ "def", "main", "(", "args", "=", "None", ")", ":", "api", ".", "config", ".", "init", "(", ")", "zxbpp", ".", "init", "(", ")", "zxbparser", ".", "init", "(", ")", "arch", ".", "zx48k", ".", "backend", ".", "init", "(", ")", "arch", ".", "zx48k...
Entry point when executed from command line. You can use zxb.py as a module with import, and this function won't be executed.
[ "Entry", "point", "when", "executed", "from", "command", "line", ".", "You", "can", "use", "zxb", ".", "py", "as", "a", "module", "with", "import", "and", "this", "function", "won", "t", "be", "executed", "." ]
python
train
deepmipt/DeepPavlov
deeppavlov/metrics/squad_metrics.py
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/metrics/squad_metrics.py#L68-L100
def squad_v2_f1(y_true: List[List[str]], y_predicted: List[str]) -> float: """ Calculates F-1 score between y_true and y_predicted F-1 score uses the best matching y_true answer The same as in SQuAD-v2.0 Args: y_true: list of correct answers (correct answers are represented by list of stri...
[ "def", "squad_v2_f1", "(", "y_true", ":", "List", "[", "List", "[", "str", "]", "]", ",", "y_predicted", ":", "List", "[", "str", "]", ")", "->", "float", ":", "f1_total", "=", "0.0", "for", "ground_truth", ",", "prediction", "in", "zip", "(", "y_tru...
Calculates F-1 score between y_true and y_predicted F-1 score uses the best matching y_true answer The same as in SQuAD-v2.0 Args: y_true: list of correct answers (correct answers are represented by list of strings) y_predicted: list of predicted answers Returns: F-1 score...
[ "Calculates", "F", "-", "1", "score", "between", "y_true", "and", "y_predicted", "F", "-", "1", "score", "uses", "the", "best", "matching", "y_true", "answer" ]
python
test
Yipit/eventlib
eventlib/listener.py
https://github.com/Yipit/eventlib/blob/0cf29e5251a59fcbfc727af5f5157a3bb03832e2/eventlib/listener.py#L21-L37
def listen_for_events(): """Pubsub event listener Listen for events in the pubsub bus and calls the process function when somebody comes to play. """ import_event_modules() conn = redis_connection.get_connection() pubsub = conn.pubsub() pubsub.subscribe("eventlib") for message in pu...
[ "def", "listen_for_events", "(", ")", ":", "import_event_modules", "(", ")", "conn", "=", "redis_connection", ".", "get_connection", "(", ")", "pubsub", "=", "conn", ".", "pubsub", "(", ")", "pubsub", ".", "subscribe", "(", "\"eventlib\"", ")", "for", "messa...
Pubsub event listener Listen for events in the pubsub bus and calls the process function when somebody comes to play.
[ "Pubsub", "event", "listener" ]
python
train
Spinmob/spinmob
_pylab_tweaks.py
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_tweaks.py#L472-L506
def image_neighbor_smooth(xlevel=0.2, ylevel=0.2, image="auto"): """ This will bleed nearest neighbor pixels into each other with the specified weight factors. """ if image == "auto": image = _pylab.gca().images[0] Z = _n.array(image.get_array()) # store this image in the undo list glo...
[ "def", "image_neighbor_smooth", "(", "xlevel", "=", "0.2", ",", "ylevel", "=", "0.2", ",", "image", "=", "\"auto\"", ")", ":", "if", "image", "==", "\"auto\"", ":", "image", "=", "_pylab", ".", "gca", "(", ")", ".", "images", "[", "0", "]", "Z", "=...
This will bleed nearest neighbor pixels into each other with the specified weight factors.
[ "This", "will", "bleed", "nearest", "neighbor", "pixels", "into", "each", "other", "with", "the", "specified", "weight", "factors", "." ]
python
train
kmmbvnr/django-any
django_any/models.py
https://github.com/kmmbvnr/django-any/blob/6f64ebd05476e2149e2e71deeefbb10f8edfc412/django_any/models.py#L213-L235
def any_file_field(field, **kwargs): """ Lookup for nearest existing file """ def get_some_file(path): subdirs, files = field.storage.listdir(path) if files: result_file = random.choice(files) instance = field.storage.open("%s/%s" % (path, result_file)...
[ "def", "any_file_field", "(", "field", ",", "*", "*", "kwargs", ")", ":", "def", "get_some_file", "(", "path", ")", ":", "subdirs", ",", "files", "=", "field", ".", "storage", ".", "listdir", "(", "path", ")", "if", "files", ":", "result_file", "=", ...
Lookup for nearest existing file
[ "Lookup", "for", "nearest", "existing", "file" ]
python
test
deontologician/restnavigator
restnavigator/utils.py
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/utils.py#L205-L216
def get_by(self, prop, val, raise_exc=False): '''Retrieve an item from the dictionary with the given metadata properties. If there is no such item, None will be returned, if there are multiple such items, the first will be returned.''' try: val = self.serialize(val) ...
[ "def", "get_by", "(", "self", ",", "prop", ",", "val", ",", "raise_exc", "=", "False", ")", ":", "try", ":", "val", "=", "self", ".", "serialize", "(", "val", ")", "return", "self", ".", "_meta", "[", "prop", "]", "[", "val", "]", "[", "0", "]"...
Retrieve an item from the dictionary with the given metadata properties. If there is no such item, None will be returned, if there are multiple such items, the first will be returned.
[ "Retrieve", "an", "item", "from", "the", "dictionary", "with", "the", "given", "metadata", "properties", ".", "If", "there", "is", "no", "such", "item", "None", "will", "be", "returned", "if", "there", "are", "multiple", "such", "items", "the", "first", "w...
python
train
mitsei/dlkit
dlkit/json_/assessment/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/objects.py#L3042-L3058
def get_assessment_taken(self): """Gets the ``AssessmentTakeb``. return: (osid.assessment.AssessmentTaken) - the assessment taken raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from temp...
[ "def", "get_assessment_taken", "(", "self", ")", ":", "# Implemented from template for osid.learning.Activity.get_objective", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'assessmentTakenId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'as...
Gets the ``AssessmentTakeb``. return: (osid.assessment.AssessmentTaken) - the assessment taken raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.*
[ "Gets", "the", "AssessmentTakeb", "." ]
python
train
pybel/pybel
src/pybel/manager/cache_manager.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L1175-L1189
def _make_property_from_dict(self, property_def: Dict) -> Property: """Build an edge property from a dictionary.""" property_hash = hash_dump(property_def) edge_property_model = self.object_cache_property.get(property_hash) if edge_property_model is None: edge_property_model...
[ "def", "_make_property_from_dict", "(", "self", ",", "property_def", ":", "Dict", ")", "->", "Property", ":", "property_hash", "=", "hash_dump", "(", "property_def", ")", "edge_property_model", "=", "self", ".", "object_cache_property", ".", "get", "(", "property_...
Build an edge property from a dictionary.
[ "Build", "an", "edge", "property", "from", "a", "dictionary", "." ]
python
train
minrk/findspark
findspark.py
https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L68-L98
def edit_ipython_profile(spark_home, spark_python, py4j): """Adds a startup file to the current IPython profile to import pyspark. The startup file sets the required environment variables and imports pyspark. Parameters ---------- spark_home : str Path to Spark installation. spark_pyth...
[ "def", "edit_ipython_profile", "(", "spark_home", ",", "spark_python", ",", "py4j", ")", ":", "from", "IPython", "import", "get_ipython", "ip", "=", "get_ipython", "(", ")", "if", "ip", ":", "profile_dir", "=", "ip", ".", "profile_dir", ".", "location", "els...
Adds a startup file to the current IPython profile to import pyspark. The startup file sets the required environment variables and imports pyspark. Parameters ---------- spark_home : str Path to Spark installation. spark_python : str Path to python subdirectory of Spark installatio...
[ "Adds", "a", "startup", "file", "to", "the", "current", "IPython", "profile", "to", "import", "pyspark", "." ]
python
train
cslarsen/crianza
crianza/tokenizer.py
https://github.com/cslarsen/crianza/blob/fa044f9d491f37cc06892bad14b2c80b8ac5a7cd/crianza/tokenizer.py#L141-L152
def tokentype(self, s): """Parses string and returns a (Tokenizer.TYPE, value) tuple.""" a = s[0] if len(s)>0 else "" b = s[1] if len(s)>1 else "" if a.isdigit() or (a in ["+","-"] and b.isdigit()): return self.parse_number(s) elif a == '"': return self.parse_string(...
[ "def", "tokentype", "(", "self", ",", "s", ")", ":", "a", "=", "s", "[", "0", "]", "if", "len", "(", "s", ")", ">", "0", "else", "\"\"", "b", "=", "s", "[", "1", "]", "if", "len", "(", "s", ")", ">", "1", "else", "\"\"", "if", "a", ".",...
Parses string and returns a (Tokenizer.TYPE, value) tuple.
[ "Parses", "string", "and", "returns", "a", "(", "Tokenizer", ".", "TYPE", "value", ")", "tuple", "." ]
python
train
fracpete/python-weka-wrapper3
python/weka/core/converters.py
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L299-L340
def ndarray_to_instances(array, relation, att_template="Att-#", att_list=None): """ Converts the numpy matrix into an Instances object and returns it. :param array: the numpy ndarray to convert :type array: numpy.darray :param relation: the name of the dataset :type relation: str :param att...
[ "def", "ndarray_to_instances", "(", "array", ",", "relation", ",", "att_template", "=", "\"Att-#\"", ",", "att_list", "=", "None", ")", ":", "if", "len", "(", "numpy", ".", "shape", "(", "array", ")", ")", "!=", "2", ":", "raise", "Exception", "(", "\"...
Converts the numpy matrix into an Instances object and returns it. :param array: the numpy ndarray to convert :type array: numpy.darray :param relation: the name of the dataset :type relation: str :param att_template: the prefix to use for the attribute names, "#" is the 1-based index, ...
[ "Converts", "the", "numpy", "matrix", "into", "an", "Instances", "object", "and", "returns", "it", "." ]
python
train
rfosterslo/wagtailplus
wagtailplus/wagtailrelations/templatetags/wagtailrelations_tags.py
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/templatetags/wagtailrelations_tags.py#L33-L50
def get_related_entry_admin_url(entry): """ Returns admin URL for specified entry instance. :param entry: the entry instance. :return: str. """ namespaces = { Document: 'wagtaildocs:edit', Link: 'wagtaillinks:edit', Page: 'wagtailadmin_pages:edit', } ...
[ "def", "get_related_entry_admin_url", "(", "entry", ")", ":", "namespaces", "=", "{", "Document", ":", "'wagtaildocs:edit'", ",", "Link", ":", "'wagtaillinks:edit'", ",", "Page", ":", "'wagtailadmin_pages:edit'", ",", "}", "for", "cls", ",", "url", "in", "namesp...
Returns admin URL for specified entry instance. :param entry: the entry instance. :return: str.
[ "Returns", "admin", "URL", "for", "specified", "entry", "instance", "." ]
python
train
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L455-L468
def pyxb_is_v1(pyxb_obj): """ Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v1 type. """ # TODO: Will not detect v1.2 as v1. return ( pyxb_obj._element().name().namespace() == d1_common.types.dataon...
[ "def", "pyxb_is_v1", "(", "pyxb_obj", ")", ":", "# TODO: Will not detect v1.2 as v1.", "return", "(", "pyxb_obj", ".", "_element", "(", ")", ".", "name", "(", ")", ".", "namespace", "(", ")", "==", "d1_common", ".", "types", ".", "dataoneTypes_v1", ".", "Nam...
Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v1 type.
[ "Args", ":", "pyxb_obj", ":", "PyXB", "object", "PyXB", "object", "holding", "an", "unknown", "type", "." ]
python
train
bkg/django-spillway
spillway/query.py
https://github.com/bkg/django-spillway/blob/c488a62642430b005f1e0d4a19e160d8d5964b67/spillway/query.py#L161-L175
def arrays(self, field_name=None): """Returns a list of ndarrays. Keyword args: field_name -- raster field name as str """ fieldname = field_name or self.raster_field.name arrays = [] for obj in self: arr = getattr(obj, fieldname) if isins...
[ "def", "arrays", "(", "self", ",", "field_name", "=", "None", ")", ":", "fieldname", "=", "field_name", "or", "self", ".", "raster_field", ".", "name", "arrays", "=", "[", "]", "for", "obj", "in", "self", ":", "arr", "=", "getattr", "(", "obj", ",", ...
Returns a list of ndarrays. Keyword args: field_name -- raster field name as str
[ "Returns", "a", "list", "of", "ndarrays", "." ]
python
train
kennethreitz/bucketstore
bucketstore.py
https://github.com/kennethreitz/bucketstore/blob/2d79584d44b9c422192d7fdf08a85a49addf83d5/bucketstore.py#L180-L186
def temp_url(self, duration=120): """Returns a temporary URL for the given key.""" return self.bucket._boto_s3.meta.client.generate_presigned_url( 'get_object', Params={'Bucket': self.bucket.name, 'Key': self.name}, ExpiresIn=duration )
[ "def", "temp_url", "(", "self", ",", "duration", "=", "120", ")", ":", "return", "self", ".", "bucket", ".", "_boto_s3", ".", "meta", ".", "client", ".", "generate_presigned_url", "(", "'get_object'", ",", "Params", "=", "{", "'Bucket'", ":", "self", "."...
Returns a temporary URL for the given key.
[ "Returns", "a", "temporary", "URL", "for", "the", "given", "key", "." ]
python
train
OSSOS/MOP
src/jjk/preproc/verifyDetection.py
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/verifyDetection.py#L34-L43
def get_file_ids(object): """Get the exposure for a particular line in the meausre table""" import MOPdbaccess mysql = MOPdbaccess.connect('cfeps','cfhls',dbSystem='MYSQL') cfeps=mysql.cursor() sql="SELECT file_id FROM measure WHERE provisional LIKE %s" cfeps.execute(sql,(object, )) file_ids...
[ "def", "get_file_ids", "(", "object", ")", ":", "import", "MOPdbaccess", "mysql", "=", "MOPdbaccess", ".", "connect", "(", "'cfeps'", ",", "'cfhls'", ",", "dbSystem", "=", "'MYSQL'", ")", "cfeps", "=", "mysql", ".", "cursor", "(", ")", "sql", "=", "\"SEL...
Get the exposure for a particular line in the meausre table
[ "Get", "the", "exposure", "for", "a", "particular", "line", "in", "the", "meausre", "table" ]
python
train
QuantEcon/QuantEcon.py
quantecon/optimize/root_finding.py
https://github.com/QuantEcon/QuantEcon.py/blob/26a66c552f2a73967d7efb6e1f4b4c4985a12643/quantecon/optimize/root_finding.py#L297-L374
def bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter, disp=True): """ Find root of a function within an interval adapted from Scipy's bisect. Basic bisection routine to find a zero of the function `f` between the arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same sig...
[ "def", "bisect", "(", "f", ",", "a", ",", "b", ",", "args", "=", "(", ")", ",", "xtol", "=", "_xtol", ",", "rtol", "=", "_rtol", ",", "maxiter", "=", "_iter", ",", "disp", "=", "True", ")", ":", "if", "xtol", "<=", "0", ":", "raise", "ValueEr...
Find root of a function within an interval adapted from Scipy's bisect. Basic bisection routine to find a zero of the function `f` between the arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same signs. `f` must be jitted via numba. Parameters ---------- f : jitted and callable ...
[ "Find", "root", "of", "a", "function", "within", "an", "interval", "adapted", "from", "Scipy", "s", "bisect", "." ]
python
train
OTL/jps
jps/security.py
https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/security.py#L37-L41
def set_client_key(self, zmq_socket, client_secret_key_path, server_public_key_path): '''must call before bind''' load_and_set_key(zmq_socket, client_secret_key_path) server_public, _ = zmq.auth.load_certificate(server_public_key_path) zmq_socket.curve_serverkey = server_public
[ "def", "set_client_key", "(", "self", ",", "zmq_socket", ",", "client_secret_key_path", ",", "server_public_key_path", ")", ":", "load_and_set_key", "(", "zmq_socket", ",", "client_secret_key_path", ")", "server_public", ",", "_", "=", "zmq", ".", "auth", ".", "lo...
must call before bind
[ "must", "call", "before", "bind" ]
python
train
jeffh/sniffer
sniffer/scanner/__init__.py
https://github.com/jeffh/sniffer/blob/8e4c3e77743aef08109ea0225b4a6536d4e60270/sniffer/scanner/__init__.py#L18-L31
def _import(module, cls): """ A messy way to import library-specific classes. TODO: I should really make a factory class or something, but I'm lazy. Plus, factories remind me a lot of java... """ global Scanner try: cls = str(cls) mod = __import__(str(module), globals(), loc...
[ "def", "_import", "(", "module", ",", "cls", ")", ":", "global", "Scanner", "try", ":", "cls", "=", "str", "(", "cls", ")", "mod", "=", "__import__", "(", "str", "(", "module", ")", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "[", "...
A messy way to import library-specific classes. TODO: I should really make a factory class or something, but I'm lazy. Plus, factories remind me a lot of java...
[ "A", "messy", "way", "to", "import", "library", "-", "specific", "classes", ".", "TODO", ":", "I", "should", "really", "make", "a", "factory", "class", "or", "something", "but", "I", "m", "lazy", ".", "Plus", "factories", "remind", "me", "a", "lot", "o...
python
train
wummel/linkchecker
linkcheck/director/aggregator.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/director/aggregator.py#L134-L144
def wait_for_host(self, host): """Throttle requests to one host.""" t = time.time() if host in self.times: due_time = self.times[host] if due_time > t: wait = due_time - t time.sleep(wait) t = time.time() wait_time =...
[ "def", "wait_for_host", "(", "self", ",", "host", ")", ":", "t", "=", "time", ".", "time", "(", ")", "if", "host", "in", "self", ".", "times", ":", "due_time", "=", "self", ".", "times", "[", "host", "]", "if", "due_time", ">", "t", ":", "wait", ...
Throttle requests to one host.
[ "Throttle", "requests", "to", "one", "host", "." ]
python
train
inasafe/inasafe
safe/gui/tools/shake_grid/shake_grid.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/shake_grid/shake_grid.py#L493-L519
def _run_command(self, command): """Run a command and raise any error as needed. This is a simple runner for executing gdal commands. :param command: A command string to be run. :type command: str :raises: Any exceptions will be propagated. """ try: ...
[ "def", "_run_command", "(", "self", ",", "command", ")", ":", "try", ":", "my_result", "=", "call", "(", "command", ",", "shell", "=", "True", ")", "del", "my_result", "except", "CalledProcessError", "as", "e", ":", "LOGGER", ".", "exception", "(", "'Run...
Run a command and raise any error as needed. This is a simple runner for executing gdal commands. :param command: A command string to be run. :type command: str :raises: Any exceptions will be propagated.
[ "Run", "a", "command", "and", "raise", "any", "error", "as", "needed", "." ]
python
train
pgmpy/pgmpy
pgmpy/factors/distributions/GaussianDistribution.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/factors/distributions/GaussianDistribution.py#L323-L362
def copy(self): """ Return a copy of the distribution. Returns ------- GaussianDistribution: copy of the distribution Examples -------- >>> import numpy as np >>> from pgmpy.factors.distributions import GaussianDistribution as GD >>> gaus...
[ "def", "copy", "(", "self", ")", ":", "copy_distribution", "=", "GaussianDistribution", "(", "variables", "=", "self", ".", "variables", ",", "mean", "=", "self", ".", "mean", ".", "copy", "(", ")", ",", "cov", "=", "self", ".", "covariance", ".", "cop...
Return a copy of the distribution. Returns ------- GaussianDistribution: copy of the distribution Examples -------- >>> import numpy as np >>> from pgmpy.factors.distributions import GaussianDistribution as GD >>> gauss_dis = GD(variables=['x1', 'x2', 'x...
[ "Return", "a", "copy", "of", "the", "distribution", "." ]
python
train
ksbg/sparklanes
sparklanes/_submit/submit.py
https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L19-L47
def _package_and_submit(args): """ Packages and submits a job, which is defined in a YAML file, to Spark. Parameters ---------- args (List): Command-line arguments """ args = _parse_and_validate_args(args) logging.debug(args) dist = __make_tmp_dir() try: __package_depen...
[ "def", "_package_and_submit", "(", "args", ")", ":", "args", "=", "_parse_and_validate_args", "(", "args", ")", "logging", ".", "debug", "(", "args", ")", "dist", "=", "__make_tmp_dir", "(", ")", "try", ":", "__package_dependencies", "(", "dist_dir", "=", "d...
Packages and submits a job, which is defined in a YAML file, to Spark. Parameters ---------- args (List): Command-line arguments
[ "Packages", "and", "submits", "a", "job", "which", "is", "defined", "in", "a", "YAML", "file", "to", "Spark", "." ]
python
train
Rapptz/discord.py
discord/abc.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/abc.py#L488-L510
async def delete(self, *, reason=None): """|coro| Deletes the channel. You must have :attr:`~.Permissions.manage_channels` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this channel. Shows ...
[ "async", "def", "delete", "(", "self", ",", "*", ",", "reason", "=", "None", ")", ":", "await", "self", ".", "_state", ".", "http", ".", "delete_channel", "(", "self", ".", "id", ",", "reason", "=", "reason", ")" ]
|coro| Deletes the channel. You must have :attr:`~.Permissions.manage_channels` permission to use this. Parameters ----------- reason: Optional[:class:`str`] The reason for deleting this channel. Shows up on the audit log. Raises ------...
[ "|coro|" ]
python
train
tonioo/sievelib
sievelib/parser.py
https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/parser.py#L251-L285
def __argument(self, ttype, tvalue): """Argument parsing method This method acts as an entry point for 'argument' parsing. Syntax: string-list / number / tag :param ttype: current token type :param tvalue: current token value :return: False if an error is e...
[ "def", "__argument", "(", "self", ",", "ttype", ",", "tvalue", ")", ":", "if", "ttype", "in", "[", "\"multiline\"", ",", "\"string\"", "]", ":", "return", "self", ".", "__curcommand", ".", "check_next_arg", "(", "\"string\"", ",", "tvalue", ".", "decode", ...
Argument parsing method This method acts as an entry point for 'argument' parsing. Syntax: string-list / number / tag :param ttype: current token type :param tvalue: current token value :return: False if an error is encountered, True otherwise
[ "Argument", "parsing", "method" ]
python
train
tanghaibao/goatools
goatools/grouper/grprobj_init.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj_init.py#L143-L155
def get_go2nt(self, usr_go2nt): """Combine user namedtuple fields, GO object fields, and format_txt.""" gos_all = self.get_gos_all() # Minimum set of namedtuple fields available for use with Sorter on grouped GO IDs prt_flds_all = get_hdridx_flds() + self.gosubdag.prt_attr['flds'] ...
[ "def", "get_go2nt", "(", "self", ",", "usr_go2nt", ")", ":", "gos_all", "=", "self", ".", "get_gos_all", "(", ")", "# Minimum set of namedtuple fields available for use with Sorter on grouped GO IDs", "prt_flds_all", "=", "get_hdridx_flds", "(", ")", "+", "self", ".", ...
Combine user namedtuple fields, GO object fields, and format_txt.
[ "Combine", "user", "namedtuple", "fields", "GO", "object", "fields", "and", "format_txt", "." ]
python
train
jingw/pyhdfs
pyhdfs.py
https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L433-L445
def append(self, path, data, **kwargs): """Append to the given file. :param data: ``bytes`` or a ``file``-like object :param buffersize: The size of the buffer used in transferring data. :type buffersize: int """ metadata_response = self._post( path, 'APPEND'...
[ "def", "append", "(", "self", ",", "path", ",", "data", ",", "*", "*", "kwargs", ")", ":", "metadata_response", "=", "self", ".", "_post", "(", "path", ",", "'APPEND'", ",", "expected_status", "=", "httplib", ".", "TEMPORARY_REDIRECT", ",", "*", "*", "...
Append to the given file. :param data: ``bytes`` or a ``file``-like object :param buffersize: The size of the buffer used in transferring data. :type buffersize: int
[ "Append", "to", "the", "given", "file", "." ]
python
train
savvastj/nbashots
nbashots/charts.py
https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L15-L103
def draw_court(ax=None, color='gray', lw=1, outer_lines=False): """Returns an axes with a basketball court drawn onto to it. This function draws a court based on the x and y-axis values that the NBA stats API provides for the shot chart data. For example the center of the hoop is located at the (0,0) ...
[ "def", "draw_court", "(", "ax", "=", "None", ",", "color", "=", "'gray'", ",", "lw", "=", "1", ",", "outer_lines", "=", "False", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "# Create the various parts of an NBA bask...
Returns an axes with a basketball court drawn onto to it. This function draws a court based on the x and y-axis values that the NBA stats API provides for the shot chart data. For example the center of the hoop is located at the (0,0) coordinate. Twenty-two feet from the left of the center of the hoo...
[ "Returns", "an", "axes", "with", "a", "basketball", "court", "drawn", "onto", "to", "it", "." ]
python
train
allenai/allennlp
allennlp/semparse/domain_languages/wikitables_language.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L737-L745
def average(self, rows: List[Row], column: NumberColumn) -> Number: """ Takes a list of rows and a column and returns the mean of the values under that column in those rows. """ cell_values = [row.values[column.name] for row in rows] if not cell_values: return...
[ "def", "average", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "NumberColumn", ")", "->", "Number", ":", "cell_values", "=", "[", "row", ".", "values", "[", "column", ".", "name", "]", "for", "row", "in", "rows", "]",...
Takes a list of rows and a column and returns the mean of the values under that column in those rows.
[ "Takes", "a", "list", "of", "rows", "and", "a", "column", "and", "returns", "the", "mean", "of", "the", "values", "under", "that", "column", "in", "those", "rows", "." ]
python
train
zhmcclient/python-zhmcclient
zhmcclient/_cpc.py
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_cpc.py#L769-L815
def get_wwpns(self, partitions): """ Return the WWPNs of the host ports (of the :term:`HBAs <HBA>`) of the specified :term:`Partitions <Partition>` of this CPC. This method performs the HMC operation "Export WWPN List". Authorization requirements: * Object-access permi...
[ "def", "get_wwpns", "(", "self", ",", "partitions", ")", ":", "body", "=", "{", "'partitions'", ":", "[", "p", ".", "uri", "for", "p", "in", "partitions", "]", "}", "result", "=", "self", ".", "manager", ".", "session", ".", "post", "(", "self", "....
Return the WWPNs of the host ports (of the :term:`HBAs <HBA>`) of the specified :term:`Partitions <Partition>` of this CPC. This method performs the HMC operation "Export WWPN List". Authorization requirements: * Object-access permission to this CPC. * Object-access permission...
[ "Return", "the", "WWPNs", "of", "the", "host", "ports", "(", "of", "the", ":", "term", ":", "HBAs", "<HBA", ">", ")", "of", "the", "specified", ":", "term", ":", "Partitions", "<Partition", ">", "of", "this", "CPC", "." ]
python
train
juju/python-libjuju
juju/model.py
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L164-L169
def entity_data(self, entity_type, entity_id, history_index): """Return the data dict for an entity at a specific index of its history. """ return self.entity_history(entity_type, entity_id)[history_index]
[ "def", "entity_data", "(", "self", ",", "entity_type", ",", "entity_id", ",", "history_index", ")", ":", "return", "self", ".", "entity_history", "(", "entity_type", ",", "entity_id", ")", "[", "history_index", "]" ]
Return the data dict for an entity at a specific index of its history.
[ "Return", "the", "data", "dict", "for", "an", "entity", "at", "a", "specific", "index", "of", "its", "history", "." ]
python
train
dr-leo/pandaSDMX
pandasdmx/reader/__init__.py
https://github.com/dr-leo/pandaSDMX/blob/71dd81ebb0d5169e5adcb8b52d516573d193f2d6/pandasdmx/reader/__init__.py#L33-L52
def read_identifiables(self, cls, sdmxobj, offset=None): ''' If sdmxobj inherits from dict: update it with modelized elements. These must be instances of model.IdentifiableArtefact, i.e. have an 'id' attribute. This will be used as dict keys. If sdmxobj does not inherit fr...
[ "def", "read_identifiables", "(", "self", ",", "cls", ",", "sdmxobj", ",", "offset", "=", "None", ")", ":", "path", "=", "self", ".", "_paths", "[", "cls", "]", "if", "offset", ":", "try", ":", "base", "=", "self", ".", "_paths", "[", "offset", "]"...
If sdmxobj inherits from dict: update it with modelized elements. These must be instances of model.IdentifiableArtefact, i.e. have an 'id' attribute. This will be used as dict keys. If sdmxobj does not inherit from dict: return a new DictLike.
[ "If", "sdmxobj", "inherits", "from", "dict", ":", "update", "it", "with", "modelized", "elements", ".", "These", "must", "be", "instances", "of", "model", ".", "IdentifiableArtefact", "i", ".", "e", ".", "have", "an", "id", "attribute", ".", "This", "will"...
python
train
saltstack/salt
salt/modules/kerberos.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kerberos.py#L119-L144
def list_policies(): ''' List policies CLI Example: .. code-block:: bash salt 'kdc.example.com' kerberos.list_policies ''' ret = {} cmd = __execute_kadmin('list_policies') if cmd['retcode'] != 0 or cmd['stderr']: ret['comment'] = cmd['stderr'].splitlines()[-1] ...
[ "def", "list_policies", "(", ")", ":", "ret", "=", "{", "}", "cmd", "=", "__execute_kadmin", "(", "'list_policies'", ")", "if", "cmd", "[", "'retcode'", "]", "!=", "0", "or", "cmd", "[", "'stderr'", "]", ":", "ret", "[", "'comment'", "]", "=", "cmd",...
List policies CLI Example: .. code-block:: bash salt 'kdc.example.com' kerberos.list_policies
[ "List", "policies" ]
python
train
ucfopen/canvasapi
canvasapi/canvas.py
https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L901-L926
def get_user_participants(self, appointment_group, **kwargs): """ List user participants in this appointment group. :calls: `GET /api/v1/appointment_groups/:id/users \ <https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.users>`_ :param appo...
[ "def", "get_user_participants", "(", "self", ",", "appointment_group", ",", "*", "*", "kwargs", ")", ":", "from", "canvasapi", ".", "appointment_group", "import", "AppointmentGroup", "from", "canvasapi", ".", "user", "import", "User", "appointment_group_id", "=", ...
List user participants in this appointment group. :calls: `GET /api/v1/appointment_groups/:id/users \ <https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.users>`_ :param appointment_group: The object or ID of the appointment group. :type appointmen...
[ "List", "user", "participants", "in", "this", "appointment", "group", "." ]
python
train
jasonrbriggs/proton
python/proton/xmlutils.py
https://github.com/jasonrbriggs/proton/blob/e734734750797ef0caaa1680379e07b86d7a53e3/python/proton/xmlutils.py#L29-L39
def replaceelement(oldelem, newelem): ''' Given a parent element, replace oldelem with newelem. ''' parent = oldelem.getparent() if parent is not None: size = len(parent.getchildren()) for x in range(0, size): if parent.getchildren()[x] == oldelem: parent....
[ "def", "replaceelement", "(", "oldelem", ",", "newelem", ")", ":", "parent", "=", "oldelem", ".", "getparent", "(", ")", "if", "parent", "is", "not", "None", ":", "size", "=", "len", "(", "parent", ".", "getchildren", "(", ")", ")", "for", "x", "in",...
Given a parent element, replace oldelem with newelem.
[ "Given", "a", "parent", "element", "replace", "oldelem", "with", "newelem", "." ]
python
train
yyuu/botornado
boto/connection.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/connection.py#L267-L285
def clean(self): """ Clean up the stale connections in all of the pools, and then get rid of empty pools. Pools clean themselves every time a connection is fetched; this cleaning takes care of pools that aren't being used any more, so nothing is being gotten from them. ...
[ "def", "clean", "(", "self", ")", ":", "with", "self", ".", "mutex", ":", "now", "=", "time", ".", "time", "(", ")", "if", "self", ".", "last_clean_time", "+", "self", ".", "CLEAN_INTERVAL", "<", "now", ":", "to_remove", "=", "[", "]", "for", "(", ...
Clean up the stale connections in all of the pools, and then get rid of empty pools. Pools clean themselves every time a connection is fetched; this cleaning takes care of pools that aren't being used any more, so nothing is being gotten from them.
[ "Clean", "up", "the", "stale", "connections", "in", "all", "of", "the", "pools", "and", "then", "get", "rid", "of", "empty", "pools", ".", "Pools", "clean", "themselves", "every", "time", "a", "connection", "is", "fetched", ";", "this", "cleaning", "takes"...
python
train
sergei-maertens/django-systemjs
systemjs/templatetags/system_tags.py
https://github.com/sergei-maertens/django-systemjs/blob/efd4a3862a39d9771609a25a5556f36023cf6e5c/systemjs/templatetags/system_tags.py#L27-L56
def render(self, context): """ Build the filepath by appending the extension. """ module_path = self.path.resolve(context) if not settings.SYSTEMJS_ENABLED: if settings.SYSTEMJS_DEFAULT_JS_EXTENSIONS: name, ext = posixpath.splitext(module_path) ...
[ "def", "render", "(", "self", ",", "context", ")", ":", "module_path", "=", "self", ".", "path", ".", "resolve", "(", "context", ")", "if", "not", "settings", ".", "SYSTEMJS_ENABLED", ":", "if", "settings", ".", "SYSTEMJS_DEFAULT_JS_EXTENSIONS", ":", "name",...
Build the filepath by appending the extension.
[ "Build", "the", "filepath", "by", "appending", "the", "extension", "." ]
python
test
getfleety/coralillo
coralillo/datamodel.py
https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/datamodel.py#L39-L60
def distance(self, loc): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ assert type(loc) == type(self) # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [ self.lon, ...
[ "def", "distance", "(", "self", ",", "loc", ")", ":", "assert", "type", "(", "loc", ")", "==", "type", "(", "self", ")", "# convert decimal degrees to radians", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", "=", "map", "(", "radians", ",", "[", "self"...
Calculate the great circle distance between two points on the earth (specified in decimal degrees)
[ "Calculate", "the", "great", "circle", "distance", "between", "two", "points", "on", "the", "earth", "(", "specified", "in", "decimal", "degrees", ")" ]
python
train
yahoo/TensorFlowOnSpark
examples/imagenet/inception/inception_export.py
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/examples/imagenet/inception/inception_export.py#L30-L115
def export(_): FLAGS = tf.app.flags.FLAGS """Evaluate model on Dataset for a number of steps.""" #with tf.Graph().as_default(): tf.reset_default_graph() def preprocess_image(image_buffer): """Preprocess JPEG encoded bytes to 3D float Tensor.""" # Decode the string as an RGB JPEG. # Note that th...
[ "def", "export", "(", "_", ")", ":", "FLAGS", "=", "tf", ".", "app", ".", "flags", ".", "FLAGS", "#with tf.Graph().as_default():", "tf", ".", "reset_default_graph", "(", ")", "def", "preprocess_image", "(", "image_buffer", ")", ":", "\"\"\"Preprocess JPEG encode...
Evaluate model on Dataset for a number of steps.
[ "Evaluate", "model", "on", "Dataset", "for", "a", "number", "of", "steps", "." ]
python
train
riggsd/davies
examples/wx_compass.py
https://github.com/riggsd/davies/blob/8566c626202a875947ad01c087300108c68d80b5/examples/wx_compass.py#L262-L268
def OnInit(self): """Initialize by creating the split window with the tree""" project = compass.CompassProjectParser(sys.argv[1]).parse() frame = MyFrame(None, -1, 'wxCompass', project) frame.Show(True) self.SetTopWindow(frame) return True
[ "def", "OnInit", "(", "self", ")", ":", "project", "=", "compass", ".", "CompassProjectParser", "(", "sys", ".", "argv", "[", "1", "]", ")", ".", "parse", "(", ")", "frame", "=", "MyFrame", "(", "None", ",", "-", "1", ",", "'wxCompass'", ",", "proj...
Initialize by creating the split window with the tree
[ "Initialize", "by", "creating", "the", "split", "window", "with", "the", "tree" ]
python
train
rosenbrockc/ci
pyci/msg.py
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/msg.py#L74-L78
def vms(message, level=1): """Writes the specified message *only* if verbose output is enabled.""" if verbose is not None and verbose != False: if isinstance(verbose, bool) or (isinstance(verbose, int) and level <= verbose): std(message)
[ "def", "vms", "(", "message", ",", "level", "=", "1", ")", ":", "if", "verbose", "is", "not", "None", "and", "verbose", "!=", "False", ":", "if", "isinstance", "(", "verbose", ",", "bool", ")", "or", "(", "isinstance", "(", "verbose", ",", "int", "...
Writes the specified message *only* if verbose output is enabled.
[ "Writes", "the", "specified", "message", "*", "only", "*", "if", "verbose", "output", "is", "enabled", "." ]
python
train
loli/medpy
medpy/graphcut/wrapper.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/graphcut/wrapper.py#L42-L72
def split_marker(marker, fg_id = 1, bg_id = 2): """ Splits an integer marker image into two binary image containing the foreground and background markers respectively. All encountered 1's are hereby treated as foreground, all 2's as background, all 0's as neutral marker and all others are ignored. ...
[ "def", "split_marker", "(", "marker", ",", "fg_id", "=", "1", ",", "bg_id", "=", "2", ")", ":", "img_marker", "=", "scipy", ".", "asarray", "(", "marker", ")", "img_fgmarker", "=", "scipy", ".", "zeros", "(", "img_marker", ".", "shape", ",", "scipy", ...
Splits an integer marker image into two binary image containing the foreground and background markers respectively. All encountered 1's are hereby treated as foreground, all 2's as background, all 0's as neutral marker and all others are ignored. This behaviour can be changed by supplying the fg_id and/...
[ "Splits", "an", "integer", "marker", "image", "into", "two", "binary", "image", "containing", "the", "foreground", "and", "background", "markers", "respectively", ".", "All", "encountered", "1", "s", "are", "hereby", "treated", "as", "foreground", "all", "2", ...
python
train
tdryer/hangups
hangups/conversation.py
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L476-L506
async def leave(self): """Leave this conversation. Raises: .NetworkError: If conversation cannot be left. """ is_group_conversation = (self._conversation.type == hangouts_pb2.CONVERSATION_TYPE_GROUP) try: if is_group_conve...
[ "async", "def", "leave", "(", "self", ")", ":", "is_group_conversation", "=", "(", "self", ".", "_conversation", ".", "type", "==", "hangouts_pb2", ".", "CONVERSATION_TYPE_GROUP", ")", "try", ":", "if", "is_group_conversation", ":", "await", "self", ".", "_cli...
Leave this conversation. Raises: .NetworkError: If conversation cannot be left.
[ "Leave", "this", "conversation", "." ]
python
valid
Locu/chronology
kronos/kronos/storage/router.py
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/router.py#L101-L109
def backends_to_mutate(self, namespace, stream): """ Return all the backends enabled for writing for `stream`. """ if namespace not in self.namespaces: raise NamespaceMissing('`{}` namespace is not configured' .format(namespace)) return self.prefix_confs[namespace]...
[ "def", "backends_to_mutate", "(", "self", ",", "namespace", ",", "stream", ")", ":", "if", "namespace", "not", "in", "self", ".", "namespaces", ":", "raise", "NamespaceMissing", "(", "'`{}` namespace is not configured'", ".", "format", "(", "namespace", ")", ")"...
Return all the backends enabled for writing for `stream`.
[ "Return", "all", "the", "backends", "enabled", "for", "writing", "for", "stream", "." ]
python
train
twilio/twilio-python
twilio/rest/video/v1/composition_hook.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/video/v1/composition_hook.py#L104-L139
def page(self, enabled=values.unset, date_created_after=values.unset, date_created_before=values.unset, friendly_name=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of CompositionHookInstance rec...
[ "def", "page", "(", "self", ",", "enabled", "=", "values", ".", "unset", ",", "date_created_after", "=", "values", ".", "unset", ",", "date_created_before", "=", "values", ".", "unset", ",", "friendly_name", "=", "values", ".", "unset", ",", "page_token", ...
Retrieve a single page of CompositionHookInstance records from the API. Request is executed immediately :param bool enabled: Only show Composition Hooks enabled or disabled. :param datetime date_created_after: Only show Composition Hooks created on or after this ISO8601 date-time with timezone....
[ "Retrieve", "a", "single", "page", "of", "CompositionHookInstance", "records", "from", "the", "API", ".", "Request", "is", "executed", "immediately" ]
python
train
wavefrontHQ/python-client
wavefront_api_client/api/derived_metric_api.py
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/derived_metric_api.py#L143-L163
def create_derived_metric(self, **kwargs): # noqa: E501 """Create a specific derived metric definition # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_...
[ "def", "create_derived_metric", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "create_derived_metric...
Create a specific derived metric definition # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_derived_metric(async_req=True) >>> result = thread.get() ...
[ "Create", "a", "specific", "derived", "metric", "definition", "#", "noqa", ":", "E501" ]
python
train
PmagPy/PmagPy
pmagpy/contribution_builder.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/contribution_builder.py#L177-L206
def propagate_measurement_info(self): """ Take a contribution with a measurement table. Create specimen, sample, site, and location tables using the unique names in the measurement table to fill in the index. """ meas_df = self.tables['measurements'].df na...
[ "def", "propagate_measurement_info", "(", "self", ")", ":", "meas_df", "=", "self", ".", "tables", "[", "'measurements'", "]", ".", "df", "names_list", "=", "[", "'specimen'", ",", "'sample'", ",", "'site'", ",", "'location'", "]", "# add in any tables that you ...
Take a contribution with a measurement table. Create specimen, sample, site, and location tables using the unique names in the measurement table to fill in the index.
[ "Take", "a", "contribution", "with", "a", "measurement", "table", ".", "Create", "specimen", "sample", "site", "and", "location", "tables", "using", "the", "unique", "names", "in", "the", "measurement", "table", "to", "fill", "in", "the", "index", "." ]
python
train
guaix-ucm/numina
numina/array/nirproc.py
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/nirproc.py#L135-L202
def ramp_array(rampdata, ti, gain=1.0, ron=1.0, badpixels=None, dtype='float64', saturation=65631, blank=0, nsig=None, normalize=False): """Loop over the first axis applying ramp processing. *rampdata* is assumed to be a 3D numpy.ndarray containing the result of a nIR observat...
[ "def", "ramp_array", "(", "rampdata", ",", "ti", ",", "gain", "=", "1.0", ",", "ron", "=", "1.0", ",", "badpixels", "=", "None", ",", "dtype", "=", "'float64'", ",", "saturation", "=", "65631", ",", "blank", "=", "0", ",", "nsig", "=", "None", ",",...
Loop over the first axis applying ramp processing. *rampdata* is assumed to be a 3D numpy.ndarray containing the result of a nIR observation in folow-up-the-ramp mode. The shape of the array must be of the form N_s x M x N, with N_s being the number of samples. :param fowlerdata: Convertible to a ...
[ "Loop", "over", "the", "first", "axis", "applying", "ramp", "processing", "." ]
python
train
wummel/patool
patoolib/__init__.py
https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/__init__.py#L317-L322
def check_archive_format (format, compression): """Make sure format and compression is known.""" if format not in ArchiveFormats: raise util.PatoolError("unknown archive format `%s'" % format) if compression is not None and compression not in ArchiveCompressions: raise util.PatoolError("unko...
[ "def", "check_archive_format", "(", "format", ",", "compression", ")", ":", "if", "format", "not", "in", "ArchiveFormats", ":", "raise", "util", ".", "PatoolError", "(", "\"unknown archive format `%s'\"", "%", "format", ")", "if", "compression", "is", "not", "No...
Make sure format and compression is known.
[ "Make", "sure", "format", "and", "compression", "is", "known", "." ]
python
train
bokeh/bokeh
bokeh/protocol/message.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L248-L281
def send(self, conn): ''' Send the message on the given connection. Args: conn (WebSocketHandler) : a WebSocketHandler to send messages Returns: int : number of bytes sent ''' if conn is None: raise ValueError("Cannot send to connection None...
[ "def", "send", "(", "self", ",", "conn", ")", ":", "if", "conn", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot send to connection None\"", ")", "with", "(", "yield", "conn", ".", "write_lock", ".", "acquire", "(", ")", ")", ":", "sent", "=", ...
Send the message on the given connection. Args: conn (WebSocketHandler) : a WebSocketHandler to send messages Returns: int : number of bytes sent
[ "Send", "the", "message", "on", "the", "given", "connection", "." ]
python
train
PolyJIT/benchbuild
benchbuild/reports/status.py
https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/reports/status.py#L82-L100
def generate(self): """ Fetch all rows associated with this experiment. This will generate a huge .csv. """ exp_name = self.exp_name() fname = os.path.basename(self.out_path) fname = "{exp}_{prefix}_{name}{ending}".format( exp=exp_name, p...
[ "def", "generate", "(", "self", ")", ":", "exp_name", "=", "self", ".", "exp_name", "(", ")", "fname", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "out_path", ")", "fname", "=", "\"{exp}_{prefix}_{name}{ending}\"", ".", "format", "(", "exp...
Fetch all rows associated with this experiment. This will generate a huge .csv.
[ "Fetch", "all", "rows", "associated", "with", "this", "experiment", "." ]
python
train
StackStorm/pybind
pybind/nos/v7_2_0/rbridge_id/resource_monitor/memory/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/rbridge_id/resource_monitor/memory/__init__.py#L163-L184
def _set_action_memory(self, v, load=False): """ Setter method for action_memory, mapped from YANG variable /rbridge_id/resource_monitor/memory/action_memory (resource-monitor-actiontype) If this variable is read-only (config: false) in the source YANG file, then _set_action_memory is considered as a pr...
[ "def", "_set_action_memory", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
Setter method for action_memory, mapped from YANG variable /rbridge_id/resource_monitor/memory/action_memory (resource-monitor-actiontype) If this variable is read-only (config: false) in the source YANG file, then _set_action_memory is considered as a private method. Backends looking to populate this varia...
[ "Setter", "method", "for", "action_memory", "mapped", "from", "YANG", "variable", "/", "rbridge_id", "/", "resource_monitor", "/", "memory", "/", "action_memory", "(", "resource", "-", "monitor", "-", "actiontype", ")", "If", "this", "variable", "is", "read", ...
python
train
gwastro/pycbc
pycbc/waveform/generator.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/generator.py#L545-L594
def generate(self, **kwargs): """Generates a waveform, applies a time shift and the detector response function from the given kwargs. """ self.current_params.update(kwargs) rfparams = {param: self.current_params[param] for param in kwargs if param not in self.location...
[ "def", "generate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "current_params", ".", "update", "(", "kwargs", ")", "rfparams", "=", "{", "param", ":", "self", ".", "current_params", "[", "param", "]", "for", "param", "in", "kwargs", ...
Generates a waveform, applies a time shift and the detector response function from the given kwargs.
[ "Generates", "a", "waveform", "applies", "a", "time", "shift", "and", "the", "detector", "response", "function", "from", "the", "given", "kwargs", "." ]
python
train
streamlink/streamlink
src/streamlink/plugins/abweb.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugins/abweb.py#L93-L135
def _login(self, username, password): '''login and update cached cookies''' self.logger.debug('login ...') res = self.session.http.get(self.login_url) input_list = self._input_re.findall(res.text) if not input_list: raise PluginError('Missing input data on login webs...
[ "def", "_login", "(", "self", ",", "username", ",", "password", ")", ":", "self", ".", "logger", ".", "debug", "(", "'login ...'", ")", "res", "=", "self", ".", "session", ".", "http", ".", "get", "(", "self", ".", "login_url", ")", "input_list", "="...
login and update cached cookies
[ "login", "and", "update", "cached", "cookies" ]
python
test
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L121-L128
def complete_contexts(self): ''' Return a list of interfaces that have satisfied contexts. ''' if self._complete_contexts: return self._complete_contexts self.context() return self._complete_contexts
[ "def", "complete_contexts", "(", "self", ")", ":", "if", "self", ".", "_complete_contexts", ":", "return", "self", ".", "_complete_contexts", "self", ".", "context", "(", ")", "return", "self", ".", "_complete_contexts" ]
Return a list of interfaces that have satisfied contexts.
[ "Return", "a", "list", "of", "interfaces", "that", "have", "satisfied", "contexts", "." ]
python
train
drdoctr/doctr
doctr/local.py
https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/local.py#L86-L109
def encrypt_to_file(contents, filename): """ Encrypts ``contents`` and writes it to ``filename``. ``contents`` should be a bytes string. ``filename`` should end with ``.enc``. Returns the secret key used for the encryption. Decrypt the file with :func:`doctr.travis.decrypt_file`. """ ...
[ "def", "encrypt_to_file", "(", "contents", ",", "filename", ")", ":", "if", "not", "filename", ".", "endswith", "(", "'.enc'", ")", ":", "raise", "ValueError", "(", "\"%s does not end with .enc\"", "%", "filename", ")", "key", "=", "Fernet", ".", "generate_key...
Encrypts ``contents`` and writes it to ``filename``. ``contents`` should be a bytes string. ``filename`` should end with ``.enc``. Returns the secret key used for the encryption. Decrypt the file with :func:`doctr.travis.decrypt_file`.
[ "Encrypts", "contents", "and", "writes", "it", "to", "filename", "." ]
python
train
ConsenSys/mythril-classic
mythril/mythril/mythril_config.py
https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/mythril/mythril_config.py#L215-L226
def _set_rpc(self, rpc_type: str) -> None: """ Sets rpc based on the type :param rpc_type: The type of connection: like infura, ganache, localhost :return: """ if rpc_type == "infura": self.set_api_rpc_infura() elif rpc_type == "localhost": ...
[ "def", "_set_rpc", "(", "self", ",", "rpc_type", ":", "str", ")", "->", "None", ":", "if", "rpc_type", "==", "\"infura\"", ":", "self", ".", "set_api_rpc_infura", "(", ")", "elif", "rpc_type", "==", "\"localhost\"", ":", "self", ".", "set_api_rpc_localhost",...
Sets rpc based on the type :param rpc_type: The type of connection: like infura, ganache, localhost :return:
[ "Sets", "rpc", "based", "on", "the", "type", ":", "param", "rpc_type", ":", "The", "type", "of", "connection", ":", "like", "infura", "ganache", "localhost", ":", "return", ":" ]
python
train
bcbio/bcbio-nextgen
bcbio/bam/callable.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/callable.py#L32-L57
def sample_callable_bed(bam_file, ref_file, data): """Retrieve callable regions for a sample subset by defined analysis regions. """ from bcbio.heterogeneity import chromhacks CovInfo = collections.namedtuple("CovInfo", "callable, raw_callable, depth_files") noalt_calling = "noalt_calling" in dd.get...
[ "def", "sample_callable_bed", "(", "bam_file", ",", "ref_file", ",", "data", ")", ":", "from", "bcbio", ".", "heterogeneity", "import", "chromhacks", "CovInfo", "=", "collections", ".", "namedtuple", "(", "\"CovInfo\"", ",", "\"callable, raw_callable, depth_files\"", ...
Retrieve callable regions for a sample subset by defined analysis regions.
[ "Retrieve", "callable", "regions", "for", "a", "sample", "subset", "by", "defined", "analysis", "regions", "." ]
python
train
markchil/gptools
gptools/utils.py
https://github.com/markchil/gptools/blob/225db52bfe6baef1516529ad22177aa2cf7b71e4/gptools/utils.py#L1070-L1079
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ ...
[ "def", "random_draw", "(", "self", ",", "size", "=", "None", ")", ":", "return", "scipy", ".", "asarray", "(", "[", "scipy", ".", "stats", ".", "gamma", ".", "rvs", "(", "a", ",", "loc", "=", "0", ",", "scale", "=", "1.0", "/", "b", ",", "size"...
Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None.
[ "Draw", "random", "samples", "of", "the", "hyperparameters", ".", "Parameters", "----------", "size", ":", "None", "int", "or", "array", "-", "like", "optional", "The", "number", "/", "shape", "of", "samples", "to", "draw", ".", "If", "None", "only", "one"...
python
train
Spinmob/spinmob
_pylab_colormap.py
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_colormap.py#L406-L420
def _signal_load(self): """ Load the selected cmap. """ # set our name self.set_name(str(self._combobox_cmaps.currentText())) # load the colormap self.load_colormap() # rebuild the interface self._build_gui() self._button_save.setEnable...
[ "def", "_signal_load", "(", "self", ")", ":", "# set our name", "self", ".", "set_name", "(", "str", "(", "self", ".", "_combobox_cmaps", ".", "currentText", "(", ")", ")", ")", "# load the colormap", "self", ".", "load_colormap", "(", ")", "# rebuild the inte...
Load the selected cmap.
[ "Load", "the", "selected", "cmap", "." ]
python
train
peterbe/gg
gg/builtins/bugzilla.py
https://github.com/peterbe/gg/blob/2aace5bdb4a9b1cb65bea717784edf54c63b7bad/gg/builtins/bugzilla.py#L69-L76
def logout(config): """Remove and forget your Bugzilla credentials""" state = read(config.configfile) if state.get("BUGZILLA"): remove(config.configfile, "BUGZILLA") success_out("Forgotten") else: error_out("No stored Bugzilla credentials")
[ "def", "logout", "(", "config", ")", ":", "state", "=", "read", "(", "config", ".", "configfile", ")", "if", "state", ".", "get", "(", "\"BUGZILLA\"", ")", ":", "remove", "(", "config", ".", "configfile", ",", "\"BUGZILLA\"", ")", "success_out", "(", "...
Remove and forget your Bugzilla credentials
[ "Remove", "and", "forget", "your", "Bugzilla", "credentials" ]
python
train
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L739-L760
def setupTable_vmtx(self): """ Make the vmtx table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "vmtx" not in self.tables: return ...
[ "def", "setupTable_vmtx", "(", "self", ")", ":", "if", "\"vmtx\"", "not", "in", "self", ".", "tables", ":", "return", "self", ".", "otf", "[", "\"vmtx\"", "]", "=", "vmtx", "=", "newTable", "(", "\"vmtx\"", ")", "vmtx", ".", "metrics", "=", "{", "}",...
Make the vmtx table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
[ "Make", "the", "vmtx", "table", "." ]
python
train
CEA-COSMIC/ModOpt
modopt/base/transform.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/transform.py#L63-L113
def map2cube(data_map, layout): r"""Map to cube This method transforms the input data from a 2D map with given layout to a 3D cube Parameters ---------- data_map : np.ndarray Input data map, 2D array layout : tuple 2D layout of 2D images Returns ------- np.ndar...
[ "def", "map2cube", "(", "data_map", ",", "layout", ")", ":", "if", "np", ".", "all", "(", "np", ".", "array", "(", "data_map", ".", "shape", ")", "%", "np", ".", "array", "(", "layout", ")", ")", ":", "raise", "ValueError", "(", "'The desired layout ...
r"""Map to cube This method transforms the input data from a 2D map with given layout to a 3D cube Parameters ---------- data_map : np.ndarray Input data map, 2D array layout : tuple 2D layout of 2D images Returns ------- np.ndarray 3D cube Raises ------ ...
[ "r", "Map", "to", "cube" ]
python
train
asphalt-framework/asphalt
asphalt/core/context.py
https://github.com/asphalt-framework/asphalt/blob/4114b3ac9743cbd9facb374a3f53e19d3afef22d/asphalt/core/context.py#L504-L521
def call_in_executor(self, func: Callable, *args, executor: Union[Executor, str] = None, **kwargs) -> Awaitable: """ Call the given callable in an executor. :param func: the callable to call :param args: positional arguments to call the callable with :pa...
[ "def", "call_in_executor", "(", "self", ",", "func", ":", "Callable", ",", "*", "args", ",", "executor", ":", "Union", "[", "Executor", ",", "str", "]", "=", "None", ",", "*", "*", "kwargs", ")", "->", "Awaitable", ":", "assert", "check_argument_types", ...
Call the given callable in an executor. :param func: the callable to call :param args: positional arguments to call the callable with :param executor: either an :class:`~concurrent.futures.Executor` instance, the resource name of one or ``None`` to use the event loop's default execu...
[ "Call", "the", "given", "callable", "in", "an", "executor", "." ]
python
train