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
xeroc/python-graphenelib
graphenebase/account.py
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L287-L292
def point(self): """ Return the point for the public key """ string = unhexlify(self.unCompressed()) return ecdsa.VerifyingKey.from_string( string[1:], curve=ecdsa.SECP256k1 ).pubkey.point
[ "def", "point", "(", "self", ")", ":", "string", "=", "unhexlify", "(", "self", ".", "unCompressed", "(", ")", ")", "return", "ecdsa", ".", "VerifyingKey", ".", "from_string", "(", "string", "[", "1", ":", "]", ",", "curve", "=", "ecdsa", ".", "SECP2...
Return the point for the public key
[ "Return", "the", "point", "for", "the", "public", "key" ]
python
valid
ray-project/ray
python/ray/utils.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L420-L442
def check_oversized_pickle(pickled, name, obj_type, worker): """Send a warning message if the pickled object is too large. Args: pickled: the pickled object. name: name of the pickled object. obj_type: type of the pickled object, can be 'function', 'remote function', 'actor'...
[ "def", "check_oversized_pickle", "(", "pickled", ",", "name", ",", "obj_type", ",", "worker", ")", ":", "length", "=", "len", "(", "pickled", ")", "if", "length", "<=", "ray_constants", ".", "PICKLE_OBJECT_WARNING_SIZE", ":", "return", "warning_message", "=", ...
Send a warning message if the pickled object is too large. Args: pickled: the pickled object. name: name of the pickled object. obj_type: type of the pickled object, can be 'function', 'remote function', 'actor', or 'object'. worker: the worker used to send warning messa...
[ "Send", "a", "warning", "message", "if", "the", "pickled", "object", "is", "too", "large", "." ]
python
train
cosven/feeluown-core
fuocore/utils.py
https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/utils.py#L43-L69
def find_previous(element, l): """ find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2 """ length = len(l) for index, cur...
[ "def", "find_previous", "(", "element", ",", "l", ")", ":", "length", "=", "len", "(", "l", ")", "for", "index", ",", "current", "in", "enumerate", "(", "l", ")", ":", "# current is the last element", "if", "length", "-", "1", "==", "index", ":", "retu...
find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2
[ "find", "previous", "element", "in", "a", "sorted", "list" ]
python
train
trailofbits/manticore
manticore/native/cpu/x86.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5256-L5279
def PSRLDQ(cpu, dest, src): """ Packed shift right logical double quadword. Shifts the destination operand (first operand) to the right by the number of bytes specified in the count operand (second operand). The empty high-order bytes are cleared (set to all 0s). If the value sp...
[ "def", "PSRLDQ", "(", "cpu", ",", "dest", ",", "src", ")", ":", "# TODO(yan): Verify the correctness of truncating SRC like this ( tests", "# use '-1' as the value", "temp", "=", "Operators", ".", "EXTRACT", "(", "src", ".", "read", "(", ")", ",", "0", ",", "8", ...
Packed shift right logical double quadword. Shifts the destination operand (first operand) to the right by the number of bytes specified in the count operand (second operand). The empty high-order bytes are cleared (set to all 0s). If the value specified by the count operand is greater ...
[ "Packed", "shift", "right", "logical", "double", "quadword", "." ]
python
valid
KelSolaar/Umbra
umbra/components/factory/components_manager_ui/nodes.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/components_manager_ui/nodes.py#L231-L253
def __initialize_node(self, attributes_flags=int(Qt.ItemIsSelectable | Qt.ItemIsEnabled)): """ Initializes the node. :param attributes_flags: Attributes flags. :type attributes_flags: int """ attributes = dir(self.__component) for attribute in attributes: ...
[ "def", "__initialize_node", "(", "self", ",", "attributes_flags", "=", "int", "(", "Qt", ".", "ItemIsSelectable", "|", "Qt", ".", "ItemIsEnabled", ")", ")", ":", "attributes", "=", "dir", "(", "self", ".", "__component", ")", "for", "attribute", "in", "att...
Initializes the node. :param attributes_flags: Attributes flags. :type attributes_flags: int
[ "Initializes", "the", "node", "." ]
python
train
NuGrid/NuGridPy
nugridpy/nugridse.py
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/nugridse.py#L423-L462
def get_elemental_abunds(self,cycle,index=None): """ returns the elemental abundances for one cycle, either for the whole star or a specific zone depending upon the value of 'index'. Parameters ---------- cycle : string or integer Model to get the abu...
[ "def", "get_elemental_abunds", "(", "self", ",", "cycle", ",", "index", "=", "None", ")", ":", "isoabunds", "=", "self", ".", "se", ".", "get", "(", "cycle", ",", "'iso_massf'", ")", "A", "=", "array", "(", "self", ".", "se", ".", "A", ")", "Z", ...
returns the elemental abundances for one cycle, either for the whole star or a specific zone depending upon the value of 'index'. Parameters ---------- cycle : string or integer Model to get the abundances for. index : integer or list, optional zo...
[ "returns", "the", "elemental", "abundances", "for", "one", "cycle", "either", "for", "the", "whole", "star", "or", "a", "specific", "zone", "depending", "upon", "the", "value", "of", "index", "." ]
python
train
ajenhl/tacl
tacl/data_store.py
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/data_store.py#L162-L183
def _add_text_size_ngrams(self, text_id, size, ngrams): """Adds `ngrams`, that are of size `size`, to the data store. The added `ngrams` are associated with `text_id`. :param text_id: database ID of text associated with `ngrams` :type text_id: `int` :param size: size of n-grams...
[ "def", "_add_text_size_ngrams", "(", "self", ",", "text_id", ",", "size", ",", "ngrams", ")", ":", "unique_ngrams", "=", "len", "(", "ngrams", ")", "self", ".", "_logger", ".", "info", "(", "'Adding {} unique {}-grams'", ".", "format", "(", "unique_ngrams", ...
Adds `ngrams`, that are of size `size`, to the data store. The added `ngrams` are associated with `text_id`. :param text_id: database ID of text associated with `ngrams` :type text_id: `int` :param size: size of n-grams :type size: `int` :param ngrams: n-grams to be add...
[ "Adds", "ngrams", "that", "are", "of", "size", "size", "to", "the", "data", "store", "." ]
python
train
bids-standard/pybids
bids/reports/report.py
https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/reports/report.py#L94-L147
def _report_subject(self, subject, **kwargs): """Write a report for a single subject. Parameters ---------- subject : :obj:`str` Subject ID. Attributes ---------- layout : :obj:`bids.layout.BIDSLayout` Layout object for a BIDS dataset. ...
[ "def", "_report_subject", "(", "self", ",", "subject", ",", "*", "*", "kwargs", ")", ":", "description_list", "=", "[", "]", "# Remove sess from kwargs if provided, else set sess as all available", "sessions", "=", "kwargs", ".", "pop", "(", "'session'", ",", "self"...
Write a report for a single subject. Parameters ---------- subject : :obj:`str` Subject ID. Attributes ---------- layout : :obj:`bids.layout.BIDSLayout` Layout object for a BIDS dataset. config : :obj:`dict` Configuration info...
[ "Write", "a", "report", "for", "a", "single", "subject", "." ]
python
train
Qiskit/qiskit-terra
qiskit/validation/base.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/validation/base.py#L227-L233
def _validate(instance): """Validate the internal representation of the instance.""" try: _ = instance.schema.validate(instance.to_dict()) except ValidationError as ex: raise ModelValidationError( ex.messages, ex.field_names, ex.fields, ex.data, **ex.kwarg...
[ "def", "_validate", "(", "instance", ")", ":", "try", ":", "_", "=", "instance", ".", "schema", ".", "validate", "(", "instance", ".", "to_dict", "(", ")", ")", "except", "ValidationError", "as", "ex", ":", "raise", "ModelValidationError", "(", "ex", "."...
Validate the internal representation of the instance.
[ "Validate", "the", "internal", "representation", "of", "the", "instance", "." ]
python
test
ljcooke/see
see/output.py
https://github.com/ljcooke/see/blob/4cbc67a31c92367977ecb4bbb1f0736fa688a6ba/see/output.py#L117-L131
def column_width(tokens): """ Return a suitable column width to display one or more strings. """ get_len = tools.display_len if PY3 else len lens = sorted(map(get_len, tokens or [])) or [0] width = lens[-1] # adjust for disproportionately long strings if width >= 18: most = lens...
[ "def", "column_width", "(", "tokens", ")", ":", "get_len", "=", "tools", ".", "display_len", "if", "PY3", "else", "len", "lens", "=", "sorted", "(", "map", "(", "get_len", ",", "tokens", "or", "[", "]", ")", ")", "or", "[", "0", "]", "width", "=", ...
Return a suitable column width to display one or more strings.
[ "Return", "a", "suitable", "column", "width", "to", "display", "one", "or", "more", "strings", "." ]
python
train
google/openhtf
openhtf/util/conf.py
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/util/conf.py#L356-L366
def reset(self): """Reset the loaded state of the configuration to what it was at import. Note that this does *not* reset values set by commandline flags or loaded from --config-file (in fact, any values loaded from --config-file that have been overridden are reset to their value from --config-file). ...
[ "def", "reset", "(", "self", ")", ":", "# Populate loaded_values with values from --config-file, if it was given.", "self", ".", "_loaded_values", "=", "{", "}", "if", "self", ".", "_flags", ".", "config_file", "is", "not", "None", ":", "self", ".", "load_from_file"...
Reset the loaded state of the configuration to what it was at import. Note that this does *not* reset values set by commandline flags or loaded from --config-file (in fact, any values loaded from --config-file that have been overridden are reset to their value from --config-file).
[ "Reset", "the", "loaded", "state", "of", "the", "configuration", "to", "what", "it", "was", "at", "import", "." ]
python
train
decryptus/sonicprobe
sonicprobe/libs/pworkerpool.py
https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/pworkerpool.py#L188-L200
def add(self, nb = 1, name = None): """ Create one or many workers. """ for x in xrange(nb): self.count_lock.acquire() self.shared['workers'] += 1 xid = self.shared['workers'] self.kill_event.clear() self.count_lock.release() ...
[ "def", "add", "(", "self", ",", "nb", "=", "1", ",", "name", "=", "None", ")", ":", "for", "x", "in", "xrange", "(", "nb", ")", ":", "self", ".", "count_lock", ".", "acquire", "(", ")", "self", ".", "shared", "[", "'workers'", "]", "+=", "1", ...
Create one or many workers.
[ "Create", "one", "or", "many", "workers", "." ]
python
train
noobermin/pys
pys/__init__.py
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L130-L138
def parse_ctuple(s,length=2): '''parse a string of acceptable colors into matplotlib, that is, either strings, or three tuples of rgb. Don't quote strings. ''' if parse_utuple(s, colrx_s, length=length) is None: raise ValueError("{} is not a valid color tuple.".format(s)); #quote strings ...
[ "def", "parse_ctuple", "(", "s", ",", "length", "=", "2", ")", ":", "if", "parse_utuple", "(", "s", ",", "colrx_s", ",", "length", "=", "length", ")", "is", "None", ":", "raise", "ValueError", "(", "\"{} is not a valid color tuple.\"", ".", "format", "(", ...
parse a string of acceptable colors into matplotlib, that is, either strings, or three tuples of rgb. Don't quote strings.
[ "parse", "a", "string", "of", "acceptable", "colors", "into", "matplotlib", "that", "is", "either", "strings", "or", "three", "tuples", "of", "rgb", ".", "Don", "t", "quote", "strings", "." ]
python
train
google/dotty
efilter/scope.py
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/scope.py#L104-L119
def getmembers_runtime(self): """Gets members (vars) from all scopes using ONLY runtime information. You most likely want to use ScopeStack.getmembers instead. Returns: Set of available vars. Raises: NotImplementedError if any scope fails to implement 'getmembe...
[ "def", "getmembers_runtime", "(", "self", ")", ":", "names", "=", "set", "(", ")", "for", "scope", "in", "self", ".", "scopes", ":", "names", ".", "update", "(", "structured", ".", "getmembers_runtime", "(", "scope", ")", ")", "return", "names" ]
Gets members (vars) from all scopes using ONLY runtime information. You most likely want to use ScopeStack.getmembers instead. Returns: Set of available vars. Raises: NotImplementedError if any scope fails to implement 'getmembers'.
[ "Gets", "members", "(", "vars", ")", "from", "all", "scopes", "using", "ONLY", "runtime", "information", "." ]
python
train
asweigart/pysimplevalidate
src/pysimplevalidate/__init__.py
https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1122-L1180
def validateYesNo(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, yesVal='yes', noVal='no', caseSensitive=False, excMsg=None): """Raises ValidationException if value is not a yes or no response. Returns the yesVal or noVal argument, not value. Note that value can be any case (...
[ "def", "validateYesNo", "(", "value", ",", "blank", "=", "False", ",", "strip", "=", "None", ",", "allowlistRegexes", "=", "None", ",", "blocklistRegexes", "=", "None", ",", "yesVal", "=", "'yes'", ",", "noVal", "=", "'no'", ",", "caseSensitive", "=", "F...
Raises ValidationException if value is not a yes or no response. Returns the yesVal or noVal argument, not value. Note that value can be any case (by default) and can also just match the * value (str): The value being validated as an email address. * blank (bool): If True, a blank string will be acce...
[ "Raises", "ValidationException", "if", "value", "is", "not", "a", "yes", "or", "no", "response", ".", "Returns", "the", "yesVal", "or", "noVal", "argument", "not", "value", "." ]
python
train
hydpy-dev/hydpy
hydpy/auxs/anntools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/anntools.py#L1471-L1473
def shape(self) -> Tuple[int, ...]: """The shape of array |anntools.SeasonalANN.ratios|.""" return tuple(int(sub) for sub in self.ratios.shape)
[ "def", "shape", "(", "self", ")", "->", "Tuple", "[", "int", ",", "...", "]", ":", "return", "tuple", "(", "int", "(", "sub", ")", "for", "sub", "in", "self", ".", "ratios", ".", "shape", ")" ]
The shape of array |anntools.SeasonalANN.ratios|.
[ "The", "shape", "of", "array", "|anntools", ".", "SeasonalANN", ".", "ratios|", "." ]
python
train
inveniosoftware/invenio-records-rest
invenio_records_rest/serializers/jsonld.py
https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/serializers/jsonld.py#L70-L76
def transform_search_hit(self, pid, record_hit, links_factory=None, **kwargs): """Transform search result hit into an intermediate representation.""" result = super(JSONLDTransformerMixin, self).transform_search_hit( pid, record_hit, links_factory, **kwargs ...
[ "def", "transform_search_hit", "(", "self", ",", "pid", ",", "record_hit", ",", "links_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "JSONLDTransformerMixin", ",", "self", ")", ".", "transform_search_hit", "(", "pid",...
Transform search result hit into an intermediate representation.
[ "Transform", "search", "result", "hit", "into", "an", "intermediate", "representation", "." ]
python
train
ArchiveTeam/wpull
wpull/protocol/http/robots.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/robots.py#L61-L96
def fetch_robots_txt(self, request: Request, file=None): '''Fetch the robots.txt file for the request. Coroutine. ''' url_info = request.url_info url = URLInfo.parse('{0}://{1}/robots.txt'.format( url_info.scheme, url_info.hostname_with_port)).url if not fil...
[ "def", "fetch_robots_txt", "(", "self", ",", "request", ":", "Request", ",", "file", "=", "None", ")", ":", "url_info", "=", "request", ".", "url_info", "url", "=", "URLInfo", ".", "parse", "(", "'{0}://{1}/robots.txt'", ".", "format", "(", "url_info", "."...
Fetch the robots.txt file for the request. Coroutine.
[ "Fetch", "the", "robots", ".", "txt", "file", "for", "the", "request", "." ]
python
train
RomelTorres/alpha_vantage
alpha_vantage/alphavantage.py
https://github.com/RomelTorres/alpha_vantage/blob/4e0b5057e520e3e3de69cf947301765817290121/alpha_vantage/alphavantage.py#L214-L241
def map_to_matype(self, matype): """ Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: ...
[ "def", "map_to_matype", "(", "self", ",", "matype", ")", ":", "# Check if it is an integer or a string", "try", ":", "value", "=", "int", "(", "matype", ")", "if", "abs", "(", "value", ")", ">", "len", "(", "AlphaVantage", ".", "_ALPHA_VANTAGE_MATH_MAP", ")", ...
Convert to the alpha vantage math type integer. It returns an integer correspondent to the type of math to apply to a function. It raises ValueError if an integer greater than the supported math types is given. Keyword Arguments: matype: The math type of the alpha vantage a...
[ "Convert", "to", "the", "alpha", "vantage", "math", "type", "integer", ".", "It", "returns", "an", "integer", "correspondent", "to", "the", "type", "of", "math", "to", "apply", "to", "a", "function", ".", "It", "raises", "ValueError", "if", "an", "integer"...
python
train
saltstack/salt
salt/utils/openstack/neutron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/neutron.py#L872-L878
def delete_firewall_rule(self, firewall_rule): ''' Deletes the specified firewall rule ''' firewall_rule_id = self._find_firewall_rule_id(firewall_rule) ret = self.network_conn.delete_firewall_rule(firewall_rule_id) return ret if ret else True
[ "def", "delete_firewall_rule", "(", "self", ",", "firewall_rule", ")", ":", "firewall_rule_id", "=", "self", ".", "_find_firewall_rule_id", "(", "firewall_rule", ")", "ret", "=", "self", ".", "network_conn", ".", "delete_firewall_rule", "(", "firewall_rule_id", ")",...
Deletes the specified firewall rule
[ "Deletes", "the", "specified", "firewall", "rule" ]
python
train
bwohlberg/sporco
sporco/fista/fista.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/fista/fista.py#L397-L407
def proximal_step(self, grad=None): """Compute proximal update (gradient descent + regularization).""" if grad is None: grad = self.eval_grad() V = self.Y - (1. / self.L) * grad self.X = self.eval_proxop(V) return grad
[ "def", "proximal_step", "(", "self", ",", "grad", "=", "None", ")", ":", "if", "grad", "is", "None", ":", "grad", "=", "self", ".", "eval_grad", "(", ")", "V", "=", "self", ".", "Y", "-", "(", "1.", "/", "self", ".", "L", ")", "*", "grad", "s...
Compute proximal update (gradient descent + regularization).
[ "Compute", "proximal", "update", "(", "gradient", "descent", "+", "regularization", ")", "." ]
python
train
globality-corp/microcosm-flask
microcosm_flask/audit.py
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/audit.py#L59-L65
def should_skip_logging(func): """ Should we skip logging for this handler? """ disabled = strtobool(request.headers.get("x-request-nolog", "false")) return disabled or getattr(func, SKIP_LOGGING, False)
[ "def", "should_skip_logging", "(", "func", ")", ":", "disabled", "=", "strtobool", "(", "request", ".", "headers", ".", "get", "(", "\"x-request-nolog\"", ",", "\"false\"", ")", ")", "return", "disabled", "or", "getattr", "(", "func", ",", "SKIP_LOGGING", ",...
Should we skip logging for this handler?
[ "Should", "we", "skip", "logging", "for", "this", "handler?" ]
python
train
apache/spark
python/pyspark/heapq3.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/heapq3.py#L477-L481
def _heapify_max(x): """Transform list into a maxheap, in-place, in O(len(x)) time.""" n = len(x) for i in reversed(range(n//2)): _siftup_max(x, i)
[ "def", "_heapify_max", "(", "x", ")", ":", "n", "=", "len", "(", "x", ")", "for", "i", "in", "reversed", "(", "range", "(", "n", "//", "2", ")", ")", ":", "_siftup_max", "(", "x", ",", "i", ")" ]
Transform list into a maxheap, in-place, in O(len(x)) time.
[ "Transform", "list", "into", "a", "maxheap", "in", "-", "place", "in", "O", "(", "len", "(", "x", "))", "time", "." ]
python
train
alpha-xone/xbbg
xbbg/io/storage.py
https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/io/storage.py#L39-L134
def ref_file( ticker: str, fld: str, has_date=False, cache=False, ext='parq', **kwargs ) -> str: """ Data file location for Bloomberg reference data Args: ticker: ticker name fld: field has_date: whether add current date to data file cache: if has_date is True, wheth...
[ "def", "ref_file", "(", "ticker", ":", "str", ",", "fld", ":", "str", ",", "has_date", "=", "False", ",", "cache", "=", "False", ",", "ext", "=", "'parq'", ",", "*", "*", "kwargs", ")", "->", "str", ":", "data_path", "=", "os", ".", "environ", "....
Data file location for Bloomberg reference data Args: ticker: ticker name fld: field has_date: whether add current date to data file cache: if has_date is True, whether to load file from latest cached ext: file extension **kwargs: other overrides passed to ref functi...
[ "Data", "file", "location", "for", "Bloomberg", "reference", "data" ]
python
valid
hongtaocai/googlefinance
googlefinance/__init__.py
https://github.com/hongtaocai/googlefinance/blob/9f703d8d4e00d645320d49186eee4520341ec273/googlefinance/__init__.py#L84-L105
def getQuotes(symbols): ''' get real-time quotes (index, last trade price, last trade time, etc) for stocks, using google api: http://finance.google.com/finance/info?client=ig&q=symbols Unlike python package 'yahoo-finance' (15 min delay), There is no delay for NYSE and NASDAQ stocks in 'googlefinance' pac...
[ "def", "getQuotes", "(", "symbols", ")", ":", "if", "type", "(", "symbols", ")", "==", "type", "(", "'str'", ")", ":", "symbols", "=", "[", "symbols", "]", "content", "=", "json", ".", "loads", "(", "request", "(", "symbols", ")", ")", "return", "r...
get real-time quotes (index, last trade price, last trade time, etc) for stocks, using google api: http://finance.google.com/finance/info?client=ig&q=symbols Unlike python package 'yahoo-finance' (15 min delay), There is no delay for NYSE and NASDAQ stocks in 'googlefinance' package. example: quotes = get...
[ "get", "real", "-", "time", "quotes", "(", "index", "last", "trade", "price", "last", "trade", "time", "etc", ")", "for", "stocks", "using", "google", "api", ":", "http", ":", "//", "finance", ".", "google", ".", "com", "/", "finance", "/", "info?clien...
python
train
ToucanToco/toucan-data-sdk
toucan_data_sdk/sdk.py
https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/sdk.py#L194-L213
def extract(data): """ Args: data (str | byte): Returns: dict: Dict[str, DataFrame] """ _, tmp_file_path = tempfile.mkstemp() try: with open(tmp_file_path, 'wb') as tmp_file: tmp_file.write(data) if zipfile.is_zipfile(tmp_file_path): ret...
[ "def", "extract", "(", "data", ")", ":", "_", ",", "tmp_file_path", "=", "tempfile", ".", "mkstemp", "(", ")", "try", ":", "with", "open", "(", "tmp_file_path", ",", "'wb'", ")", "as", "tmp_file", ":", "tmp_file", ".", "write", "(", "data", ")", "if"...
Args: data (str | byte): Returns: dict: Dict[str, DataFrame]
[ "Args", ":", "data", "(", "str", "|", "byte", ")", ":" ]
python
test
giancosta86/Iris
info/gianlucacosta/iris/versioning.py
https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/versioning.py#L117-L143
def getFriendlyString(self): """ Returns the version, printed in a friendly way. More precisely, it trims trailing zero components. """ if self._friendlyString is not None: return self._friendlyString resultComponents = [ self.getIntMajor(), ...
[ "def", "getFriendlyString", "(", "self", ")", ":", "if", "self", ".", "_friendlyString", "is", "not", "None", ":", "return", "self", ".", "_friendlyString", "resultComponents", "=", "[", "self", ".", "getIntMajor", "(", ")", ",", "self", ".", "getIntMinor", ...
Returns the version, printed in a friendly way. More precisely, it trims trailing zero components.
[ "Returns", "the", "version", "printed", "in", "a", "friendly", "way", "." ]
python
train
HazyResearch/metal
metal/logging/logger.py
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/logging/logger.py#L180-L203
def print_to_screen(self, metrics_dict): """Print all metrics in metrics_dict to screen""" score_strings = defaultdict(list) for split_metric, value in metrics_dict.items(): split, metric = split_metric.split("/", 1) if isinstance(value, float): score_str...
[ "def", "print_to_screen", "(", "self", ",", "metrics_dict", ")", ":", "score_strings", "=", "defaultdict", "(", "list", ")", "for", "split_metric", ",", "value", "in", "metrics_dict", ".", "items", "(", ")", ":", "split", ",", "metric", "=", "split_metric", ...
Print all metrics in metrics_dict to screen
[ "Print", "all", "metrics", "in", "metrics_dict", "to", "screen" ]
python
train
persephone-tools/persephone
persephone/model.py
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/model.py#L195-L236
def transcribe(self, restore_model_path: Optional[str]=None) -> None: """ Transcribes an untranscribed dataset. Similar to eval() except no reference translation is assumed, thus no LER is calculated. """ saver = tf.train.Saver() with tf.Session(config=allow_growth_config) as se...
[ "def", "transcribe", "(", "self", ",", "restore_model_path", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "saver", "=", "tf", ".", "train", ".", "Saver", "(", ")", "with", "tf", ".", "Session", "(", "config", "=", "allow_gro...
Transcribes an untranscribed dataset. Similar to eval() except no reference translation is assumed, thus no LER is calculated.
[ "Transcribes", "an", "untranscribed", "dataset", ".", "Similar", "to", "eval", "()", "except", "no", "reference", "translation", "is", "assumed", "thus", "no", "LER", "is", "calculated", "." ]
python
train
tanghaibao/goatools
goatools/godag_plot.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag_plot.py#L226-L242
def _get_node_text(self, goid, goobj): """Return a string to be printed in a GO term box.""" txt = [] # Header line: "GO:0036464 L04 D06" txt.append(self.pltvars.fmthdr.format( GO=goobj.id.replace("GO:", "GO"), level=goobj.level, depth=goobj.depth)) ...
[ "def", "_get_node_text", "(", "self", ",", "goid", ",", "goobj", ")", ":", "txt", "=", "[", "]", "# Header line: \"GO:0036464 L04 D06\"", "txt", ".", "append", "(", "self", ".", "pltvars", ".", "fmthdr", ".", "format", "(", "GO", "=", "goobj", ".", "id",...
Return a string to be printed in a GO term box.
[ "Return", "a", "string", "to", "be", "printed", "in", "a", "GO", "term", "box", "." ]
python
train
hydroshare/hs_restclient
hs_restclient/__init__.py
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L1135-L1148
def updateReferenceURL(self, pid, name, ref_url, path=""): """Update a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be updated :param name: Filename for the referenced file :param r...
[ "def", "updateReferenceURL", "(", "self", ",", "pid", ",", "name", ",", "ref_url", ",", "path", "=", "\"\"", ")", ":", "return", "self", ".", "updateReferencedFile", "(", "pid", ",", "path", ",", "name", ",", "ref_url", ")" ]
Update a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be updated :param name: Filename for the referenced file :param ref_url: url to be updated in the referenced file ...
[ "Update", "a", "Referenced", "Content", "File", "(", ".", "url", ")" ]
python
train
loli/medpy
medpy/metric/binary.py
https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/binary.py#L118-L163
def precision(result, reference): """ Precison. Parameters ---------- result : array_like Input data containing objects. Can be any type but will be converted into binary: background where 0, object everywhere else. reference : array_like Input data containing object...
[ "def", "precision", "(", "result", ",", "reference", ")", ":", "result", "=", "numpy", ".", "atleast_1d", "(", "result", ".", "astype", "(", "numpy", ".", "bool", ")", ")", "reference", "=", "numpy", ".", "atleast_1d", "(", "reference", ".", "astype", ...
Precison. Parameters ---------- result : array_like Input data containing objects. Can be any type but will be converted into binary: background where 0, object everywhere else. reference : array_like Input data containing objects. Can be any type but will be converted ...
[ "Precison", ".", "Parameters", "----------", "result", ":", "array_like", "Input", "data", "containing", "objects", ".", "Can", "be", "any", "type", "but", "will", "be", "converted", "into", "binary", ":", "background", "where", "0", "object", "everywhere", "e...
python
train
hadrianl/huobi
huobitrade/utils.py
https://github.com/hadrianl/huobi/blob/bbfa2036703ee84a76d5d8e9f89c25fc8a55f2c7/huobitrade/utils.py#L272-L297
def api_key_post(params, request_path, _async=False): """ from 火币demo, 构造post请求并调用post方法 :param params: :param request_path: :return: """ method = 'POST' timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') params_to_sign = { 'AccessKeyId': ACCESS_KEY, ...
[ "def", "api_key_post", "(", "params", ",", "request_path", ",", "_async", "=", "False", ")", ":", "method", "=", "'POST'", "timestamp", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S'", ")", "params_to_si...
from 火币demo, 构造post请求并调用post方法 :param params: :param request_path: :return:
[ "from", "火币demo", "构造post请求并调用post方法", ":", "param", "params", ":", ":", "param", "request_path", ":", ":", "return", ":" ]
python
train
ev3dev/ev3dev-lang-python
ev3dev2/motor.py
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L797-L804
def stop(self, **kwargs): """ Stop any of the run commands before they are complete using the action specified by `stop_action`. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_STOP
[ "def", "stop", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", "in", "kwargs", ":", "setattr", "(", "self", ",", "key", ",", "kwargs", "[", "key", "]", ")", "self", ".", "command", "=", "self", ".", "COMMAND_STOP" ]
Stop any of the run commands before they are complete using the action specified by `stop_action`.
[ "Stop", "any", "of", "the", "run", "commands", "before", "they", "are", "complete", "using", "the", "action", "specified", "by", "stop_action", "." ]
python
train
raphaelvallat/pingouin
pingouin/pairwise.py
https://github.com/raphaelvallat/pingouin/blob/58b19fa4fffbfe09d58b456e3926a148249e4d9b/pingouin/pairwise.py#L411-L562
def pairwise_tukey(dv=None, between=None, data=None, alpha=.05, tail='two-sided', effsize='hedges'): '''Pairwise Tukey-HSD post-hoc test. Parameters ---------- dv : string Name of column containing the dependant variable. between: string Name of column containing ...
[ "def", "pairwise_tukey", "(", "dv", "=", "None", ",", "between", "=", "None", ",", "data", "=", "None", ",", "alpha", "=", ".05", ",", "tail", "=", "'two-sided'", ",", "effsize", "=", "'hedges'", ")", ":", "from", "pingouin", ".", "external", ".", "q...
Pairwise Tukey-HSD post-hoc test. Parameters ---------- dv : string Name of column containing the dependant variable. between: string Name of column containing the between factor. data : pandas DataFrame DataFrame alpha : float Significance level tail : strin...
[ "Pairwise", "Tukey", "-", "HSD", "post", "-", "hoc", "test", "." ]
python
train
spyder-ide/spyder
spyder/plugins/ipythonconsole/plugin.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/plugin.py#L1096-L1104
def get_client_for_file(self, filename): """Get client associated with a given file.""" client = None for idx, cl in enumerate(self.get_clients()): if self.filenames[idx] == filename: self.tabwidget.setCurrentIndex(idx) client = cl ...
[ "def", "get_client_for_file", "(", "self", ",", "filename", ")", ":", "client", "=", "None", "for", "idx", ",", "cl", "in", "enumerate", "(", "self", ".", "get_clients", "(", ")", ")", ":", "if", "self", ".", "filenames", "[", "idx", "]", "==", "file...
Get client associated with a given file.
[ "Get", "client", "associated", "with", "a", "given", "file", "." ]
python
train
gitpython-developers/GitPython
git/objects/util.py
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/util.py#L44-L65
def get_object_type_by_name(object_type_name): """ :return: type suitable to handle the given object type name. Use the type to create new instances. :param object_type_name: Member of TYPES :raise ValueError: In case object_type_name is unknown""" if object_type_name == b"commit": ...
[ "def", "get_object_type_by_name", "(", "object_type_name", ")", ":", "if", "object_type_name", "==", "b\"commit\"", ":", "from", ".", "import", "commit", "return", "commit", ".", "Commit", "elif", "object_type_name", "==", "b\"tag\"", ":", "from", ".", "import", ...
:return: type suitable to handle the given object type name. Use the type to create new instances. :param object_type_name: Member of TYPES :raise ValueError: In case object_type_name is unknown
[ ":", "return", ":", "type", "suitable", "to", "handle", "the", "given", "object", "type", "name", ".", "Use", "the", "type", "to", "create", "new", "instances", "." ]
python
train
epfl-lts2/pygsp
pygsp/optimization.py
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/optimization.py#L25-L96
def prox_tv(x, gamma, G, A=None, At=None, nu=1, tol=10e-4, maxit=200, use_matrix=True): r""" Total Variation proximal operator for graphs. This function computes the TV proximal operator for graphs. The TV norm is the one norm of the gradient. The gradient is defined in the function :meth:`pygsp.gr...
[ "def", "prox_tv", "(", "x", ",", "gamma", ",", "G", ",", "A", "=", "None", ",", "At", "=", "None", ",", "nu", "=", "1", ",", "tol", "=", "10e-4", ",", "maxit", "=", "200", ",", "use_matrix", "=", "True", ")", ":", "if", "A", "is", "None", "...
r""" Total Variation proximal operator for graphs. This function computes the TV proximal operator for graphs. The TV norm is the one norm of the gradient. The gradient is defined in the function :meth:`pygsp.graphs.Graph.grad`. This function requires the PyUNLocBoX to be executed. This functi...
[ "r", "Total", "Variation", "proximal", "operator", "for", "graphs", "." ]
python
train
jupyter-widgets/jupyterlab-sidecar
setupbase.py
https://github.com/jupyter-widgets/jupyterlab-sidecar/blob/8889d09f1a0933e2cbee06d4874f720b075b29e8/setupbase.py#L616-L630
def _iexplode_path(path): """Iterate over all the parts of a path. Splits path recursively with os.path.split(). """ (head, tail) = os.path.split(path) if not head or (not tail and head == path): if head: yield head if tail or not head: yield tail ret...
[ "def", "_iexplode_path", "(", "path", ")", ":", "(", "head", ",", "tail", ")", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "not", "head", "or", "(", "not", "tail", "and", "head", "==", "path", ")", ":", "if", "head", ":", "yie...
Iterate over all the parts of a path. Splits path recursively with os.path.split().
[ "Iterate", "over", "all", "the", "parts", "of", "a", "path", "." ]
python
test
marshmallow-code/apispec
src/apispec/yaml_utils.py
https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/yaml_utils.py#L32-L47
def load_yaml_from_docstring(docstring): """Loads YAML from docstring.""" split_lines = trim_docstring(docstring).split("\n") # Cut YAML from rest of docstring for index, line in enumerate(split_lines): line = line.strip() if line.startswith("---"): cut_from = index ...
[ "def", "load_yaml_from_docstring", "(", "docstring", ")", ":", "split_lines", "=", "trim_docstring", "(", "docstring", ")", ".", "split", "(", "\"\\n\"", ")", "# Cut YAML from rest of docstring", "for", "index", ",", "line", "in", "enumerate", "(", "split_lines", ...
Loads YAML from docstring.
[ "Loads", "YAML", "from", "docstring", "." ]
python
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/attention.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/attention.py#L106-L160
def get_prob(self, src, tgt, mask, pre_compute, return_logits=False): ''' :param s: [src_sequence_length, batch_size, src_dim] :param h: [batch_size, tgt_dim] or [tgt_sequence_length, batch_size, tgt_dim] :param mask: [src_sequence_length, batch_size]\ or [tgt_sequence_lengt...
[ "def", "get_prob", "(", "self", ",", "src", ",", "tgt", ",", "mask", ",", "pre_compute", ",", "return_logits", "=", "False", ")", ":", "s_shape", "=", "src", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "h_shape", "=", "tgt", ".", "get_shape...
:param s: [src_sequence_length, batch_size, src_dim] :param h: [batch_size, tgt_dim] or [tgt_sequence_length, batch_size, tgt_dim] :param mask: [src_sequence_length, batch_size]\ or [tgt_sequence_length, src_sequence_length, batch_sizse] :param pre_compute: [src_sequence_length, bat...
[ ":", "param", "s", ":", "[", "src_sequence_length", "batch_size", "src_dim", "]", ":", "param", "h", ":", "[", "batch_size", "tgt_dim", "]", "or", "[", "tgt_sequence_length", "batch_size", "tgt_dim", "]", ":", "param", "mask", ":", "[", "src_sequence_length", ...
python
train
theolind/pymysensors
mqtt.py
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mqtt.py#L18-L20
def publish(self, topic, payload, qos, retain): """Publish an MQTT message.""" self._mqttc.publish(topic, payload, qos, retain)
[ "def", "publish", "(", "self", ",", "topic", ",", "payload", ",", "qos", ",", "retain", ")", ":", "self", ".", "_mqttc", ".", "publish", "(", "topic", ",", "payload", ",", "qos", ",", "retain", ")" ]
Publish an MQTT message.
[ "Publish", "an", "MQTT", "message", "." ]
python
train
HazyResearch/metal
metal/contrib/backends/wrapper.py
https://github.com/HazyResearch/metal/blob/c24e3772e25ac6d0917b8b7af4c1bcb92928f84a/metal/contrib/backends/wrapper.py#L190-L208
def _build_vocab(self, sentences, markers=[]): """ Initalize symbol table dictionary :param sentences: :param markers: :return: """ from snorkel.learning.pytorch.rnn.utils import SymbolTable vocab = Counter() for sent in sentences: f...
[ "def", "_build_vocab", "(", "self", ",", "sentences", ",", "markers", "=", "[", "]", ")", ":", "from", "snorkel", ".", "learning", ".", "pytorch", ".", "rnn", ".", "utils", "import", "SymbolTable", "vocab", "=", "Counter", "(", ")", "for", "sent", "in"...
Initalize symbol table dictionary :param sentences: :param markers: :return:
[ "Initalize", "symbol", "table", "dictionary" ]
python
train
BernardFW/bernard
src/bernard/layers/definitions.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/layers/definitions.py#L75-L80
async def become(self, layer_type: Type[L], request: 'Request') -> L: """ Transform this layer into another layer type """ raise ValueError('Cannot become "{}"'.format(layer_type.__name__))
[ "async", "def", "become", "(", "self", ",", "layer_type", ":", "Type", "[", "L", "]", ",", "request", ":", "'Request'", ")", "->", "L", ":", "raise", "ValueError", "(", "'Cannot become \"{}\"'", ".", "format", "(", "layer_type", ".", "__name__", ")", ")"...
Transform this layer into another layer type
[ "Transform", "this", "layer", "into", "another", "layer", "type" ]
python
train
pandas-dev/pandas
pandas/io/excel/_util.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/excel/_util.py#L176-L204
def _fill_mi_header(row, control_row): """Forward fill blank entries in row but only inside the same parent index. Used for creating headers in Multiindex. Parameters ---------- row : list List of items in a single row. control_row : list of bool Helps to determine if particular...
[ "def", "_fill_mi_header", "(", "row", ",", "control_row", ")", ":", "last", "=", "row", "[", "0", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "row", ")", ")", ":", "if", "not", "control_row", "[", "i", "]", ":", "last", "=", "row...
Forward fill blank entries in row but only inside the same parent index. Used for creating headers in Multiindex. Parameters ---------- row : list List of items in a single row. control_row : list of bool Helps to determine if particular column is in same parent index as the ...
[ "Forward", "fill", "blank", "entries", "in", "row", "but", "only", "inside", "the", "same", "parent", "index", "." ]
python
train
UDST/urbansim
urbansim/models/regression.py
https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/models/regression.py#L178-L204
def _model_fit_to_table(fit): """ Produce a pandas DataFrame of model fit results from a statsmodels fit result object. Parameters ---------- fit : statsmodels.regression.linear_model.RegressionResults Returns ------- fit_parameters : pandas.DataFrame Will have columns 'Coe...
[ "def", "_model_fit_to_table", "(", "fit", ")", ":", "fit_parameters", "=", "pd", ".", "DataFrame", "(", "{", "'Coefficient'", ":", "fit", ".", "params", ",", "'Std. Error'", ":", "fit", ".", "bse", ",", "'T-Score'", ":", "fit", ".", "tvalues", "}", ")", ...
Produce a pandas DataFrame of model fit results from a statsmodels fit result object. Parameters ---------- fit : statsmodels.regression.linear_model.RegressionResults Returns ------- fit_parameters : pandas.DataFrame Will have columns 'Coefficient', 'Std. Error', and 'T-Score'. ...
[ "Produce", "a", "pandas", "DataFrame", "of", "model", "fit", "results", "from", "a", "statsmodels", "fit", "result", "object", "." ]
python
train
robinandeer/puzzle
puzzle/utils/get_info.py
https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/utils/get_info.py#L121-L139
def get_cytoband_coord(chrom, pos): """Get the cytoband coordinate for a position Args: chrom(str): A chromosome pos(int): The position Returns: cytoband """ chrom = chrom.strip('chr') pos = int(pos) result = None logger.debug("Finding Cytoba...
[ "def", "get_cytoband_coord", "(", "chrom", ",", "pos", ")", ":", "chrom", "=", "chrom", ".", "strip", "(", "'chr'", ")", "pos", "=", "int", "(", "pos", ")", "result", "=", "None", "logger", ".", "debug", "(", "\"Finding Cytoband for chrom:{0} pos:{1}\"", "...
Get the cytoband coordinate for a position Args: chrom(str): A chromosome pos(int): The position Returns: cytoband
[ "Get", "the", "cytoband", "coordinate", "for", "a", "position" ]
python
train
okfn/ofs
ofs/command.py
https://github.com/okfn/ofs/blob/c110cbecd7d0ae7e877963914a1a5af030cd6d45/ofs/command.py#L87-L187
def proxy_upload(self, path, filename, content_type=None, content_encoding=None, cb=None, num_cb=None): """ This is the main function that uploads. We assume the bucket and key (== path) exists. What we do here is simple. Calculate the headers we will need, (e.g. md5...
[ "def", "proxy_upload", "(", "self", ",", "path", ",", "filename", ",", "content_type", "=", "None", ",", "content_encoding", "=", "None", ",", "cb", "=", "None", ",", "num_cb", "=", "None", ")", ":", "from", "boto", ".", "connection", "import", "AWSAuthC...
This is the main function that uploads. We assume the bucket and key (== path) exists. What we do here is simple. Calculate the headers we will need, (e.g. md5, content-type, etc). Then we ask the self.get_proxy_config method to fill in the authentication information and tell us which re...
[ "This", "is", "the", "main", "function", "that", "uploads", ".", "We", "assume", "the", "bucket", "and", "key", "(", "==", "path", ")", "exists", ".", "What", "we", "do", "here", "is", "simple", ".", "Calculate", "the", "headers", "we", "will", "need",...
python
train
warner/magic-wormhole
src/wormhole/cli/cli.py
https://github.com/warner/magic-wormhole/blob/995d3f546a33eec4f64df929848d86937d2003a7/src/wormhole/cli/cli.py#L332-L341
def ssh_invite(ctx, code_length, user, **kwargs): """ Add a public-key to a ~/.ssh/authorized_keys file """ for name, value in kwargs.items(): setattr(ctx.obj, name, value) from . import cmd_ssh ctx.obj.code_length = code_length ctx.obj.ssh_user = user return go(cmd_ssh.invite, c...
[ "def", "ssh_invite", "(", "ctx", ",", "code_length", ",", "user", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "setattr", "(", "ctx", ".", "obj", ",", "name", ",", "value", ")", "fro...
Add a public-key to a ~/.ssh/authorized_keys file
[ "Add", "a", "public", "-", "key", "to", "a", "~", "/", ".", "ssh", "/", "authorized_keys", "file" ]
python
train
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L2919-L2922
def resource_collection_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/resource_collections#create-a-resource-collection" api_path = "/api/v2/resource_collections.json" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "resource_collection_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/resource_collections.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data"...
https://developer.zendesk.com/rest_api/docs/core/resource_collections#create-a-resource-collection
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "core", "/", "resource_collections#create", "-", "a", "-", "resource", "-", "collection" ]
python
train
django-fluent/django-fluent-contents
fluent_contents/extensions/pluginpool.py
https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/extensions/pluginpool.py#L113-L126
def get_allowed_plugins(self, placeholder_slot): """ Return the plugins which are supported in the given placeholder name. """ # See if there is a limit imposed. slot_config = appsettings.FLUENT_CONTENTS_PLACEHOLDER_CONFIG.get(placeholder_slot) or {} plugins = slot_config...
[ "def", "get_allowed_plugins", "(", "self", ",", "placeholder_slot", ")", ":", "# See if there is a limit imposed.", "slot_config", "=", "appsettings", ".", "FLUENT_CONTENTS_PLACEHOLDER_CONFIG", ".", "get", "(", "placeholder_slot", ")", "or", "{", "}", "plugins", "=", ...
Return the plugins which are supported in the given placeholder name.
[ "Return", "the", "plugins", "which", "are", "supported", "in", "the", "given", "placeholder", "name", "." ]
python
train
mattimck/python-exist
exist/auth.py
https://github.com/mattimck/python-exist/blob/2c4be9d176d8e8007c4e020ee7cd6263a2096abb/exist/auth.py#L138-L157
def index(self, state, code=None, error=None): """ Receive a Exist response containing a verification code. Use the code to fetch the access_token. """ error = None if code: try: auth_token = self.fetch_token(code, state) except Mis...
[ "def", "index", "(", "self", ",", "state", ",", "code", "=", "None", ",", "error", "=", "None", ")", ":", "error", "=", "None", "if", "code", ":", "try", ":", "auth_token", "=", "self", ".", "fetch_token", "(", "code", ",", "state", ")", "except", ...
Receive a Exist response containing a verification code. Use the code to fetch the access_token.
[ "Receive", "a", "Exist", "response", "containing", "a", "verification", "code", ".", "Use", "the", "code", "to", "fetch", "the", "access_token", "." ]
python
train
cmheisel/basecampreporting
src/basecampreporting/basecamp.py
https://github.com/cmheisel/basecampreporting/blob/88ecfc6e835608650ff6be23cbf2421d224c122b/src/basecampreporting/basecamp.py#L289-L298
def create_comment(self, post_id, body): """ Create a new comment, associating it with a specific message. """ path = '/msg/create_comment' req = ET.Element('request') comment = ET.SubElement(req, 'comment') ET.SubElement(comment, 'post-id').text = str(int(post_id...
[ "def", "create_comment", "(", "self", ",", "post_id", ",", "body", ")", ":", "path", "=", "'/msg/create_comment'", "req", "=", "ET", ".", "Element", "(", "'request'", ")", "comment", "=", "ET", ".", "SubElement", "(", "req", ",", "'comment'", ")", "ET", ...
Create a new comment, associating it with a specific message.
[ "Create", "a", "new", "comment", "associating", "it", "with", "a", "specific", "message", "." ]
python
train
gwastro/pycbc
pycbc/workflow/core.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L281-L302
def add_ini_profile(self, cp, sec): """Add profile from configuration file. Parameters ----------- cp : ConfigParser object The ConfigParser object holding the workflow configuration settings sec : string The section containing options for this job. ...
[ "def", "add_ini_profile", "(", "self", ",", "cp", ",", "sec", ")", ":", "for", "opt", "in", "cp", ".", "options", "(", "sec", ")", ":", "namespace", "=", "opt", ".", "split", "(", "'|'", ")", "[", "0", "]", "if", "namespace", "==", "'pycbc'", "or...
Add profile from configuration file. Parameters ----------- cp : ConfigParser object The ConfigParser object holding the workflow configuration settings sec : string The section containing options for this job.
[ "Add", "profile", "from", "configuration", "file", "." ]
python
train
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/guerilla/guerillamgmt.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L966-L980
def setup_task_signals(self, ): """Setup the signals for the task page :returns: None :rtype: None :raises: None """ log.debug("Setting up task page signals.") self.task_user_view_pb.clicked.connect(self.task_view_user) self.task_user_add_pb.clicked.conne...
[ "def", "setup_task_signals", "(", "self", ",", ")", ":", "log", ".", "debug", "(", "\"Setting up task page signals.\"", ")", "self", ".", "task_user_view_pb", ".", "clicked", ".", "connect", "(", "self", ".", "task_view_user", ")", "self", ".", "task_user_add_pb...
Setup the signals for the task page :returns: None :rtype: None :raises: None
[ "Setup", "the", "signals", "for", "the", "task", "page" ]
python
train
jermnelson/flask-fedora-commons
flask_fedora_commons/__init__.py
https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L464-L503
def replace(self, entity_id, property_name, old_value, value): """Method replaces a triple for the given entity/subject. Property name is from the schema.org vocabulary. Args: entity_id(string): Unique ID of Fedora obje...
[ "def", "replace", "(", "self", ",", "entity_id", ",", "property_name", ",", "old_value", ",", "value", ")", ":", "if", "not", "entity_id", ".", "startswith", "(", "\"http\"", ")", ":", "entity_uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "base...
Method replaces a triple for the given entity/subject. Property name is from the schema.org vocabulary. Args: entity_id(string): Unique ID of Fedora object property_name(string): Prefix and property name i.e. schema:name old_value(string): Literal or URI of old value...
[ "Method", "replaces", "a", "triple", "for", "the", "given", "entity", "/", "subject", ".", "Property", "name", "is", "from", "the", "schema", ".", "org", "vocabulary", "." ]
python
train
ecederstrand/exchangelib
exchangelib/properties.py
https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/properties.py#L560-L603
def to_server_timezone(self, timezones, for_year): """Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there may be multiple matches. If so, we return a random timezone ID. :param timezones: A list of server timezones, as returned by ...
[ "def", "to_server_timezone", "(", "self", ",", "timezones", ",", "for_year", ")", ":", "candidates", "=", "set", "(", ")", "for", "tz_id", ",", "tz_name", ",", "tz_periods", ",", "tz_transitions", ",", "tz_transitions_groups", "in", "timezones", ":", "candidat...
Returns the Microsoft timezone ID corresponding to this timezone. There may not be a match at all, and there may be multiple matches. If so, we return a random timezone ID. :param timezones: A list of server timezones, as returned by list(account.protocol.get_timezones(return_full_timezone_...
[ "Returns", "the", "Microsoft", "timezone", "ID", "corresponding", "to", "this", "timezone", ".", "There", "may", "not", "be", "a", "match", "at", "all", "and", "there", "may", "be", "multiple", "matches", ".", "If", "so", "we", "return", "a", "random", "...
python
train
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2695-L2734
def _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line): """Reflow the lines so that it looks nice.""" if unicode(parsed_tokens[0]) == 'def': # A function definition gets indented a bit more. continued_indent = indentation + ' ' * 2 * DEFAULT_INDEN...
[ "def", "_reflow_lines", "(", "parsed_tokens", ",", "indentation", ",", "max_line_length", ",", "start_on_prefix_line", ")", ":", "if", "unicode", "(", "parsed_tokens", "[", "0", "]", ")", "==", "'def'", ":", "# A function definition gets indented a bit more.", "contin...
Reflow the lines so that it looks nice.
[ "Reflow", "the", "lines", "so", "that", "it", "looks", "nice", "." ]
python
train
rosenbrockc/fortpy
fortpy/code.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/code.py#L431-L478
def tree_find(self, symbol, origin, attribute): """Finds the code element corresponding to specified symbol by searching all modules in the parser. :arg symbol: the name of the code element to find. :arg origin: an instance of a Module element who owns the text that is generat...
[ "def", "tree_find", "(", "self", ",", "symbol", ",", "origin", ",", "attribute", ")", ":", "#The symbol must be accessible to the origin module, otherwise", "#it wouldn't compile. Start there, first looking at the origin", "#itself and then the other modules that it depends on.", "#Sin...
Finds the code element corresponding to specified symbol by searching all modules in the parser. :arg symbol: the name of the code element to find. :arg origin: an instance of a Module element who owns the text that is generate the find search. :arg attribute: one of ['depende...
[ "Finds", "the", "code", "element", "corresponding", "to", "specified", "symbol", "by", "searching", "all", "modules", "in", "the", "parser", "." ]
python
train
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L16853-L16869
def create_host_only_network_interface(self): """Creates a new adapter for Host Only Networking. out host_interface of type :class:`IHostNetworkInterface` Created host interface object. return progress of type :class:`IProgress` Progress object to track the operation co...
[ "def", "create_host_only_network_interface", "(", "self", ")", ":", "(", "progress", ",", "host_interface", ")", "=", "self", ".", "_call", "(", "\"createHostOnlyNetworkInterface\"", ")", "progress", "=", "IProgress", "(", "progress", ")", "host_interface", "=", "...
Creates a new adapter for Host Only Networking. out host_interface of type :class:`IHostNetworkInterface` Created host interface object. return progress of type :class:`IProgress` Progress object to track the operation completion. raises :class:`OleErrorInvalidarg` ...
[ "Creates", "a", "new", "adapter", "for", "Host", "Only", "Networking", "." ]
python
train
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L7153-L7160
def validateElement(self, doc, elem): """Try to validate the subtree under an element """ if doc is None: doc__o = None else: doc__o = doc._o if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlValidateElement(self._o, doc__o, elem__o) retu...
[ "def", "validateElement", "(", "self", ",", "doc", ",", "elem", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "elem", "is", "None", ":", "elem__o", "=", "None", "else", ":", "...
Try to validate the subtree under an element
[ "Try", "to", "validate", "the", "subtree", "under", "an", "element" ]
python
train
intuition-io/intuition
intuition/api/algorithm.py
https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/algorithm.py#L114-L128
def process_orders(self, orderbook): ''' Default and costant orders processor. Overwrite it for more sophisticated strategies ''' for stock, alloc in orderbook.iteritems(): self.logger.info('{}: Ordered {} {} stocks'.format( self.datetime, stock, alloc)) i...
[ "def", "process_orders", "(", "self", ",", "orderbook", ")", ":", "for", "stock", ",", "alloc", "in", "orderbook", ".", "iteritems", "(", ")", ":", "self", ".", "logger", ".", "info", "(", "'{}: Ordered {} {} stocks'", ".", "format", "(", "self", ".", "d...
Default and costant orders processor. Overwrite it for more sophisticated strategies
[ "Default", "and", "costant", "orders", "processor", ".", "Overwrite", "it", "for", "more", "sophisticated", "strategies" ]
python
train
datadotworld/data.world-py
datadotworld/client/_swagger/apis/datasets_api.py
https://github.com/datadotworld/data.world-py/blob/ffaeb115f358731ab0b805b0c43b7ff2e3cf0a77/datadotworld/client/_swagger/apis/datasets_api.py#L282-L307
def delete_dataset(self, owner, id, **kwargs): """ Delete a dataset Permanently deletes a dataset and all data associated with it. This operation cannot be undone, although a new dataset may be created with the same id. This method makes a synchronous HTTP request by default. To make an ...
[ "def", "delete_dataset", "(", "self", ",", "owner", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "delete_dataset...
Delete a dataset Permanently deletes a dataset and all data associated with it. This operation cannot be undone, although a new dataset may be created with the same id. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` funct...
[ "Delete", "a", "dataset", "Permanently", "deletes", "a", "dataset", "and", "all", "data", "associated", "with", "it", ".", "This", "operation", "cannot", "be", "undone", "although", "a", "new", "dataset", "may", "be", "created", "with", "the", "same", "id", ...
python
train
brocade/pynos
pynos/versions/base/yang/ietf_netconf.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/ietf_netconf.py#L484-L494
def commit_input_confirmed(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") commit = ET.Element("commit") config = commit input = ET.SubElement(commit, "input") confirmed = ET.SubElement(input, "confirmed") callback = kwargs.pop('...
[ "def", "commit_input_confirmed", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "commit", "=", "ET", ".", "Element", "(", "\"commit\"", ")", "config", "=", "commit", "input", "=", "ET", ".",...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
chaimleib/intervaltree
intervaltree/intervaltree.py
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L1084-L1091
def containsi(self, begin, end, data=None): """ Shortcut for (Interval(begin, end, data) in tree). Completes in O(1) time. :rtype: bool """ return Interval(begin, end, data) in self
[ "def", "containsi", "(", "self", ",", "begin", ",", "end", ",", "data", "=", "None", ")", ":", "return", "Interval", "(", "begin", ",", "end", ",", "data", ")", "in", "self" ]
Shortcut for (Interval(begin, end, data) in tree). Completes in O(1) time. :rtype: bool
[ "Shortcut", "for", "(", "Interval", "(", "begin", "end", "data", ")", "in", "tree", ")", "." ]
python
train
angr/angr
angr/storage/memory.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/storage/memory.py#L341-L365
def set_state(self, state): """ Call the set_state method in SimStatePlugin class, and then perform the delayed initialization. :param state: The SimState instance """ SimStatePlugin.set_state(self, state) # Delayed initialization stack_region_map, generic_regio...
[ "def", "set_state", "(", "self", ",", "state", ")", ":", "SimStatePlugin", ".", "set_state", "(", "self", ",", "state", ")", "# Delayed initialization", "stack_region_map", ",", "generic_region_map", "=", "self", ".", "_temp_stack_region_map", ",", "self", ".", ...
Call the set_state method in SimStatePlugin class, and then perform the delayed initialization. :param state: The SimState instance
[ "Call", "the", "set_state", "method", "in", "SimStatePlugin", "class", "and", "then", "perform", "the", "delayed", "initialization", "." ]
python
train
nvdv/vprof
vprof/stats_server.py
https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/stats_server.py#L57-L66
def do_GET(self): """Handles HTTP GET requests.""" handler = self.uri_map.get(self.path) or self._handle_other content, content_type = handler() compressed_content = gzip.compress(content) self._send_response( 200, headers=(('Content-type', '%s; charset=utf-8' % conte...
[ "def", "do_GET", "(", "self", ")", ":", "handler", "=", "self", ".", "uri_map", ".", "get", "(", "self", ".", "path", ")", "or", "self", ".", "_handle_other", "content", ",", "content_type", "=", "handler", "(", ")", "compressed_content", "=", "gzip", ...
Handles HTTP GET requests.
[ "Handles", "HTTP", "GET", "requests", "." ]
python
test
jtwhite79/pyemu
pyemu/en.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/en.py#L600-L611
def copy(self): """ overload of Ensemble.copy() Returns ------- ParameterEnsemble : ParameterEnsemble """ df = super(Ensemble,self).copy() pe = ParameterEnsemble.from_dataframe(df=df,pst=self.pst.get()) pe.__istransformed = self.istransformed ret...
[ "def", "copy", "(", "self", ")", ":", "df", "=", "super", "(", "Ensemble", ",", "self", ")", ".", "copy", "(", ")", "pe", "=", "ParameterEnsemble", ".", "from_dataframe", "(", "df", "=", "df", ",", "pst", "=", "self", ".", "pst", ".", "get", "(",...
overload of Ensemble.copy() Returns ------- ParameterEnsemble : ParameterEnsemble
[ "overload", "of", "Ensemble", ".", "copy", "()" ]
python
train
Clinical-Genomics/scout
scout/adapter/mongo/variant_loader.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/variant_loader.py#L491-L609
def load_variants(self, case_obj, variant_type='clinical', category='snv', rank_threshold=None, chrom=None, start=None, end=None, gene_obj=None, build='37'): """Load variants for a case into scout. Load the variants for a specific analysis type and category i...
[ "def", "load_variants", "(", "self", ",", "case_obj", ",", "variant_type", "=", "'clinical'", ",", "category", "=", "'snv'", ",", "rank_threshold", "=", "None", ",", "chrom", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "gene_obj...
Load variants for a case into scout. Load the variants for a specific analysis type and category into scout. If no region is specified, load all variants above rank score threshold If region or gene is specified, load all variants from that region disregarding variant rank(if not specif...
[ "Load", "variants", "for", "a", "case", "into", "scout", "." ]
python
test
viewflow/django-fsm
django_fsm/__init__.py
https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L181-L192
def conditions_met(self, instance, state): """ Check if all conditions have been met """ transition = self.get_transition(state) if transition is None: return False elif transition.conditions is None: return True else: return a...
[ "def", "conditions_met", "(", "self", ",", "instance", ",", "state", ")", ":", "transition", "=", "self", ".", "get_transition", "(", "state", ")", "if", "transition", "is", "None", ":", "return", "False", "elif", "transition", ".", "conditions", "is", "No...
Check if all conditions have been met
[ "Check", "if", "all", "conditions", "have", "been", "met" ]
python
train
ergoithz/browsepy
browsepy/manager.py
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/manager.py#L99-L127
def import_plugin(self, plugin): ''' Import plugin by given name, looking at :attr:`namespaces`. :param plugin: plugin module name :type plugin: str :raises PluginNotFoundError: if not found on any namespace ''' names = [ '%s%s%s' % (namespace, '' if ...
[ "def", "import_plugin", "(", "self", ",", "plugin", ")", ":", "names", "=", "[", "'%s%s%s'", "%", "(", "namespace", ",", "''", "if", "namespace", "[", "-", "1", "]", "==", "'_'", "else", "'.'", ",", "plugin", ")", "if", "namespace", "else", "plugin",...
Import plugin by given name, looking at :attr:`namespaces`. :param plugin: plugin module name :type plugin: str :raises PluginNotFoundError: if not found on any namespace
[ "Import", "plugin", "by", "given", "name", "looking", "at", ":", "attr", ":", "namespaces", "." ]
python
train
Robpol86/libnl
example_scan_access_points.py
https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/example_scan_access_points.py#L102-L118
def callback_trigger(msg, arg): """Called when the kernel is done scanning. Only signals if it was successful or if it failed. No other data. Positional arguments: msg -- nl_msg class instance containing the data sent by the kernel. arg -- mutable integer (ctypes.c_int()) to update with results. R...
[ "def", "callback_trigger", "(", "msg", ",", "arg", ")", ":", "gnlh", "=", "genlmsghdr", "(", "nlmsg_data", "(", "nlmsg_hdr", "(", "msg", ")", ")", ")", "if", "gnlh", ".", "cmd", "==", "nl80211", ".", "NL80211_CMD_SCAN_ABORTED", ":", "arg", ".", "value", ...
Called when the kernel is done scanning. Only signals if it was successful or if it failed. No other data. Positional arguments: msg -- nl_msg class instance containing the data sent by the kernel. arg -- mutable integer (ctypes.c_int()) to update with results. Returns: An integer, value of NL_SKI...
[ "Called", "when", "the", "kernel", "is", "done", "scanning", ".", "Only", "signals", "if", "it", "was", "successful", "or", "if", "it", "failed", ".", "No", "other", "data", "." ]
python
train
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L18-L25
def get_imageblock(filename, format=''): """ Generates rst raw block for given image filename and format""" _, extension = os.path.splitext(filename) with open(filename, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode('utf-8') return '\n\n.. raw:: html\n\n\t<im...
[ "def", "get_imageblock", "(", "filename", ",", "format", "=", "''", ")", ":", "_", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "image_file", ":", "encoded_s...
Generates rst raw block for given image filename and format
[ "Generates", "rst", "raw", "block", "for", "given", "image", "filename", "and", "format" ]
python
train
SheffieldML/GPy
GPy/kern/src/multidimensional_integral_limits.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/kern/src/multidimensional_integral_limits.py#L111-L120
def Kdiag(self, X): """I've used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we're returning K_ff!! $K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$""" K_ff = np.ones(X.shape[0]) for ...
[ "def", "Kdiag", "(", "self", ",", "X", ")", ":", "K_ff", "=", "np", ".", "ones", "(", "X", ".", "shape", "[", "0", "]", ")", "for", "i", ",", "x", "in", "enumerate", "(", "X", ")", ":", "for", "il", ",", "l", "in", "enumerate", "(", "self",...
I've used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we're returning K_ff!! $K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$
[ "I", "ve", "used", "the", "fact", "that", "we", "call", "this", "method", "for", "K_ff", "when", "finding", "the", "covariance", "as", "a", "hack", "so", "I", "know", "if", "I", "should", "return", "K_ff", "or", "K_xx", ".", "In", "this", "case", "we...
python
train
hydraplatform/hydra-base
hydra_base/util/dataset_util.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/dataset_util.py#L95-L165
def _get_val(val, full=False): """ Get the value(s) of a dataset as a single value or as 1-d list of values. In the special case of timeseries, when a check is for time-based criteria, you can return the entire timeseries. """ try: val = val.strip() except: pass ...
[ "def", "_get_val", "(", "val", ",", "full", "=", "False", ")", ":", "try", ":", "val", "=", "val", ".", "strip", "(", ")", "except", ":", "pass", "logging", ".", "debug", "(", "\"%s, type=%s\"", ",", "val", ",", "type", "(", "val", ")", ")", "if"...
Get the value(s) of a dataset as a single value or as 1-d list of values. In the special case of timeseries, when a check is for time-based criteria, you can return the entire timeseries.
[ "Get", "the", "value", "(", "s", ")", "of", "a", "dataset", "as", "a", "single", "value", "or", "as", "1", "-", "d", "list", "of", "values", ".", "In", "the", "special", "case", "of", "timeseries", "when", "a", "check", "is", "for", "time", "-", ...
python
train
iotile/coretools
iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/tile_manager.py#L86-L92
def clear_to_reset(self, config_vars): """Clear to the state immediately after a reset.""" super(TileManagerState, self).clear_to_reset(config_vars) self.registered_tiles = self.registered_tiles[:1] self.safe_mode = False self.debug_mode = False
[ "def", "clear_to_reset", "(", "self", ",", "config_vars", ")", ":", "super", "(", "TileManagerState", ",", "self", ")", ".", "clear_to_reset", "(", "config_vars", ")", "self", ".", "registered_tiles", "=", "self", ".", "registered_tiles", "[", ":", "1", "]",...
Clear to the state immediately after a reset.
[ "Clear", "to", "the", "state", "immediately", "after", "a", "reset", "." ]
python
train
thiagopbueno/rddl2tf
rddl2tf/compiler.py
https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/compiler.py#L736-L784
def _compile_arithmetic_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None...
[ "def", "_compile_arithmetic_expression", "(", "self", ",", "expr", ":", "Expression", ",", "scope", ":", "Dict", "[", "str", ",", "TensorFluent", "]", ",", "batch_size", ":", "Optional", "[", "int", "]", "=", "None", ",", "noise", ":", "Optional", "[", "...
Compile an arithmetic expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL arithmetic expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Op...
[ "Compile", "an", "arithmetic", "expression", "expr", "into", "a", "TensorFluent", "in", "the", "given", "scope", "with", "optional", "batch", "size", "." ]
python
train
saltstack/salt
salt/cloud/clouds/vmware.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1664-L1688
def list_datastore_full(kwargs=None, call=None, datastore=None): ''' Returns a dictionary with basic information for the given datastore CLI Example: .. code-block:: bash salt-cloud -f list_datastore_full my-vmware-config datastore=datastore-name ''' if call != 'function': rai...
[ "def", "list_datastore_full", "(", "kwargs", "=", "None", ",", "call", "=", "None", ",", "datastore", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_datastore_full function must be called with '", "'-f o...
Returns a dictionary with basic information for the given datastore CLI Example: .. code-block:: bash salt-cloud -f list_datastore_full my-vmware-config datastore=datastore-name
[ "Returns", "a", "dictionary", "with", "basic", "information", "for", "the", "given", "datastore" ]
python
train
mbedmicro/pyOCD
pyocd/probe/stlink/detect/windows.py
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/stlink/detect/windows.py#L189-L209
def _vid_pid_path_to_usb_info(vid_pid_path): """! Provide the vendor ID and product ID of a device based on its entry in the registry @return Returns {'vendor_id': '<vendor ID>', 'product': '<product ID>'} @details If the vendor ID or product ID can't be determined, they will be returned as None. ""...
[ "def", "_vid_pid_path_to_usb_info", "(", "vid_pid_path", ")", ":", "result", "=", "{", "\"vendor_id\"", ":", "None", ",", "\"product_id\"", ":", "None", "}", "for", "component", "in", "vid_pid_path", ".", "split", "(", "\"&\"", ")", ":", "component_part", "=",...
! Provide the vendor ID and product ID of a device based on its entry in the registry @return Returns {'vendor_id': '<vendor ID>', 'product': '<product ID>'} @details If the vendor ID or product ID can't be determined, they will be returned as None.
[ "!", "Provide", "the", "vendor", "ID", "and", "product", "ID", "of", "a", "device", "based", "on", "its", "entry", "in", "the", "registry" ]
python
train
christophertbrown/bioscripts
ctbBio/rRNA_copies.py
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/rRNA_copies.py#L18-L29
def rna_bases(rna_cov, scaffold, bases, line): """ determine if read overlaps with rna, if so count bases """ start = int(line[3]) stop = start + bases - 1 if scaffold not in rna_cov: return rna_cov for pos in rna_cov[scaffold][2]: ol = get_overlap([start, stop], pos) ...
[ "def", "rna_bases", "(", "rna_cov", ",", "scaffold", ",", "bases", ",", "line", ")", ":", "start", "=", "int", "(", "line", "[", "3", "]", ")", "stop", "=", "start", "+", "bases", "-", "1", "if", "scaffold", "not", "in", "rna_cov", ":", "return", ...
determine if read overlaps with rna, if so count bases
[ "determine", "if", "read", "overlaps", "with", "rna", "if", "so", "count", "bases" ]
python
train
StackStorm/pybind
pybind/nos/v6_0_2f/brocade_entity_rpc/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/brocade_entity_rpc/__init__.py#L100-L126
def _set_get_contained_in_ID(self, v, load=False): """ Setter method for get_contained_in_ID, mapped from YANG variable /brocade_entity_rpc/get_contained_in_ID (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_contained_in_ID is considered as a private method...
[ "def", "_set_get_contained_in_ID", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",...
Setter method for get_contained_in_ID, mapped from YANG variable /brocade_entity_rpc/get_contained_in_ID (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_contained_in_ID is considered as a private method. Backends looking to populate this variable should do so v...
[ "Setter", "method", "for", "get_contained_in_ID", "mapped", "from", "YANG", "variable", "/", "brocade_entity_rpc", "/", "get_contained_in_ID", "(", "rpc", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", ...
python
train
caesar0301/relogger
relogger/config_parser.py
https://github.com/caesar0301/relogger/blob/40b722ad2115ac6a179e2cc4eb0c88333f5114de/relogger/config_parser.py#L149-L154
def _detect_loop(self): """ detect loops in flow table, raise error if being present """ for source, dests in self.flowtable.items(): if source in dests: raise conferr('Loops detected: %s --> %s' % (source, source))
[ "def", "_detect_loop", "(", "self", ")", ":", "for", "source", ",", "dests", "in", "self", ".", "flowtable", ".", "items", "(", ")", ":", "if", "source", "in", "dests", ":", "raise", "conferr", "(", "'Loops detected: %s --> %s'", "%", "(", "source", ",",...
detect loops in flow table, raise error if being present
[ "detect", "loops", "in", "flow", "table", "raise", "error", "if", "being", "present" ]
python
train
fabaff/python-mystrom
pymystrom/cli.py
https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/cli.py#L157-L160
def color(ip, mac, hue, saturation, value): """Switch the bulb on with the given color.""" bulb = MyStromBulb(ip, mac) bulb.set_color_hsv(hue, saturation, value)
[ "def", "color", "(", "ip", ",", "mac", ",", "hue", ",", "saturation", ",", "value", ")", ":", "bulb", "=", "MyStromBulb", "(", "ip", ",", "mac", ")", "bulb", ".", "set_color_hsv", "(", "hue", ",", "saturation", ",", "value", ")" ]
Switch the bulb on with the given color.
[ "Switch", "the", "bulb", "on", "with", "the", "given", "color", "." ]
python
train
pyrogram/pyrogram
pyrogram/client/methods/bots/answer_callback_query.py
https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/methods/bots/answer_callback_query.py#L24-L70
def answer_callback_query( self, callback_query_id: str, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = 0 ): """Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed ...
[ "def", "answer_callback_query", "(", "self", ",", "callback_query_id", ":", "str", ",", "text", ":", "str", "=", "None", ",", "show_alert", ":", "bool", "=", "None", ",", "url", ":", "str", "=", "None", ",", "cache_time", ":", "int", "=", "0", ")", "...
Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. Args: callback_query_id (``str``): Unique identifier for the query to be answered. ...
[ "Use", "this", "method", "to", "send", "answers", "to", "callback", "queries", "sent", "from", "inline", "keyboards", ".", "The", "answer", "will", "be", "displayed", "to", "the", "user", "as", "a", "notification", "at", "the", "top", "of", "the", "chat", ...
python
train
chezou/tabula-py
tabula/file_util.py
https://github.com/chezou/tabula-py/blob/e61d46ee3c93bb40396e48dac5a9493e898f561a/tabula/file_util.py#L24-L63
def localize_file(path_or_buffer): '''Ensure localize target file. If the target file is remote, this function fetches into local storage. Args: path (str): File path or file like object or URL of target file. Returns: filename (str): file name in local storage tem...
[ "def", "localize_file", "(", "path_or_buffer", ")", ":", "path_or_buffer", "=", "_stringify_path", "(", "path_or_buffer", ")", "if", "_is_url", "(", "path_or_buffer", ")", ":", "req", "=", "urlopen", "(", "path_or_buffer", ")", "filename", "=", "os", ".", "pat...
Ensure localize target file. If the target file is remote, this function fetches into local storage. Args: path (str): File path or file like object or URL of target file. Returns: filename (str): file name in local storage temporary_file_flag (bool): temporary file fl...
[ "Ensure", "localize", "target", "file", "." ]
python
train
saltstack/salt
salt/cloud/clouds/vmware.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L3737-L3811
def create_folder(kwargs=None, call=None): ''' Create the specified folder path in this VMware environment .. note:: To create a Host and Cluster Folder under a Datacenter, specify ``path="/yourDatacenterName/host/yourFolderName"`` To create a Network Folder under a Datacenter, sp...
[ "def", "create_folder", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_folder function must be called with '", "'-f or --function.'", ")", "# Get the service instan...
Create the specified folder path in this VMware environment .. note:: To create a Host and Cluster Folder under a Datacenter, specify ``path="/yourDatacenterName/host/yourFolderName"`` To create a Network Folder under a Datacenter, specify ``path="/yourDatacenterName/network/yourF...
[ "Create", "the", "specified", "folder", "path", "in", "this", "VMware", "environment" ]
python
train
github/octodns
octodns/provider/dyn.py
https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/dyn.py#L156-L162
def flush_zone(cls, zone_name): '''Flushes the zone cache, if there is one''' cls.log.debug('flush_zone: zone_name=%s', zone_name) try: del cls._cache[zone_name] except KeyError: pass
[ "def", "flush_zone", "(", "cls", ",", "zone_name", ")", ":", "cls", ".", "log", ".", "debug", "(", "'flush_zone: zone_name=%s'", ",", "zone_name", ")", "try", ":", "del", "cls", ".", "_cache", "[", "zone_name", "]", "except", "KeyError", ":", "pass" ]
Flushes the zone cache, if there is one
[ "Flushes", "the", "zone", "cache", "if", "there", "is", "one" ]
python
train
DataMedSci/mcpartools
setup.py
https://github.com/DataMedSci/mcpartools/blob/84f869094d05bf70f09e8aaeca671ddaa1c56ec4/setup.py#L84-L97
def get_version(): """ Get project version (using versioneer) :return: string containing version """ setup_versioneer() clean_cache() import versioneer version = versioneer.get_version() parsed_version = parse_version(version) if '*@' in str(parsed_version): import time ...
[ "def", "get_version", "(", ")", ":", "setup_versioneer", "(", ")", "clean_cache", "(", ")", "import", "versioneer", "version", "=", "versioneer", ".", "get_version", "(", ")", "parsed_version", "=", "parse_version", "(", "version", ")", "if", "'*@'", "in", "...
Get project version (using versioneer) :return: string containing version
[ "Get", "project", "version", "(", "using", "versioneer", ")", ":", "return", ":", "string", "containing", "version" ]
python
train
brentp/cruzdb
cruzdb/models.py
https://github.com/brentp/cruzdb/blob/9068d46e25952f4a929dde0242beb31fa4c7e89a/cruzdb/models.py#L527-L542
def sequence(self, per_exon=False): """ Return the sequence for this feature. if per-exon is True, return an array of exon sequences This sequence is never reverse complemented """ db = self.db if not per_exon: start = self.txStart + 1 retu...
[ "def", "sequence", "(", "self", ",", "per_exon", "=", "False", ")", ":", "db", "=", "self", ".", "db", "if", "not", "per_exon", ":", "start", "=", "self", ".", "txStart", "+", "1", "return", "_sequence", "(", "db", ",", "self", ".", "chrom", ",", ...
Return the sequence for this feature. if per-exon is True, return an array of exon sequences This sequence is never reverse complemented
[ "Return", "the", "sequence", "for", "this", "feature", ".", "if", "per", "-", "exon", "is", "True", "return", "an", "array", "of", "exon", "sequences", "This", "sequence", "is", "never", "reverse", "complemented" ]
python
train
buildbot/buildbot
master/buildbot/steps/package/deb/lintian.py
https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/steps/package/deb/lintian.py#L84-L98
def createSummary(self, log): """ Create nice summary logs. @param log: log to create summary off of. """ warnings = self.obs.warnings errors = self.obs.errors if warnings: self.addCompleteLog('%d Warnings' % len(warnings), "\n".join(warnings)) ...
[ "def", "createSummary", "(", "self", ",", "log", ")", ":", "warnings", "=", "self", ".", "obs", ".", "warnings", "errors", "=", "self", ".", "obs", ".", "errors", "if", "warnings", ":", "self", ".", "addCompleteLog", "(", "'%d Warnings'", "%", "len", "...
Create nice summary logs. @param log: log to create summary off of.
[ "Create", "nice", "summary", "logs", "." ]
python
train
stevearc/dql
dql/output.py
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/output.py#L249-L253
def wait(self): """ Block for user input """ self._write_footer() super(ColumnFormat, self).wait() self._write_header()
[ "def", "wait", "(", "self", ")", ":", "self", ".", "_write_footer", "(", ")", "super", "(", "ColumnFormat", ",", "self", ")", ".", "wait", "(", ")", "self", ".", "_write_header", "(", ")" ]
Block for user input
[ "Block", "for", "user", "input" ]
python
train
mar10/wsgidav
wsgidav/util.py
https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/util.py#L246-L257
def get_module_logger(moduleName, defaultToVerbose=False): """Create a module logger, that can be en/disabled by configuration. @see: unit.init_logging """ # moduleName = moduleName.split(".")[-1] if not moduleName.startswith(BASE_LOGGER_NAME + "."): moduleName = BASE_LOGGER_NAME + "." + mo...
[ "def", "get_module_logger", "(", "moduleName", ",", "defaultToVerbose", "=", "False", ")", ":", "# moduleName = moduleName.split(\".\")[-1]", "if", "not", "moduleName", ".", "startswith", "(", "BASE_LOGGER_NAME", "+", "\".\"", ")", ":", "moduleName", "=", "BASE_LOGGER...
Create a module logger, that can be en/disabled by configuration. @see: unit.init_logging
[ "Create", "a", "module", "logger", "that", "can", "be", "en", "/", "disabled", "by", "configuration", "." ]
python
valid
PaulHancock/Aegean
AegeanTools/fitting.py
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/fitting.py#L760-L792
def bias_correct(params, data, acf=None): """ Calculate and apply a bias correction to the given fit parameters Parameters ---------- params : lmfit.Parameters The model parameters. These will be modified. data : 2d-array The data which was used in the fitting acf : 2d-ar...
[ "def", "bias_correct", "(", "params", ",", "data", ",", "acf", "=", "None", ")", ":", "bias", "=", "RB_bias", "(", "data", ",", "params", ",", "acf", "=", "acf", ")", "i", "=", "0", "for", "p", "in", "params", ":", "if", "'theta'", "in", "p", "...
Calculate and apply a bias correction to the given fit parameters Parameters ---------- params : lmfit.Parameters The model parameters. These will be modified. data : 2d-array The data which was used in the fitting acf : 2d-array ACF of the data. Default = None. Retu...
[ "Calculate", "and", "apply", "a", "bias", "correction", "to", "the", "given", "fit", "parameters" ]
python
train
PmagPy/PmagPy
dialogs/pmag_er_magic_dialogs.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/pmag_er_magic_dialogs.py#L1131-L1142
def onLeftClickLabel(self, event): """ When user clicks on a grid label, determine if it is a row label or a col label. Pass along the event to the appropriate function. (It will either highlight a column for editing all values, or highlight a row for deletion). """ if ev...
[ "def", "onLeftClickLabel", "(", "self", ",", "event", ")", ":", "if", "event", ".", "Col", "==", "-", "1", "and", "event", ".", "Row", "==", "-", "1", ":", "pass", "elif", "event", ".", "Col", "<", "0", ":", "self", ".", "onSelectRow", "(", "even...
When user clicks on a grid label, determine if it is a row label or a col label. Pass along the event to the appropriate function. (It will either highlight a column for editing all values, or highlight a row for deletion).
[ "When", "user", "clicks", "on", "a", "grid", "label", "determine", "if", "it", "is", "a", "row", "label", "or", "a", "col", "label", ".", "Pass", "along", "the", "event", "to", "the", "appropriate", "function", ".", "(", "It", "will", "either", "highli...
python
train
senaite/senaite.core
bika/lims/browser/header_table.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/header_table.py#L164-L203
def get_field_visibility_mode(self, field): """Returns "view" or "edit" modes, together with the place within where this field has to be rendered, based on the permissions the current user has for the context and the field passed in """ fallback_mode = ("hidden", "hidden") ...
[ "def", "get_field_visibility_mode", "(", "self", ",", "field", ")", ":", "fallback_mode", "=", "(", "\"hidden\"", ",", "\"hidden\"", ")", "widget", "=", "field", ".", "widget", "# TODO This needs to be done differently", "# Check where the field has to be located", "layou...
Returns "view" or "edit" modes, together with the place within where this field has to be rendered, based on the permissions the current user has for the context and the field passed in
[ "Returns", "view", "or", "edit", "modes", "together", "with", "the", "place", "within", "where", "this", "field", "has", "to", "be", "rendered", "based", "on", "the", "permissions", "the", "current", "user", "has", "for", "the", "context", "and", "the", "f...
python
train
twitterdev/tweet_parser
tweet_parser/tweet_checking.py
https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet_checking.py#L129-L148
def check_tweet(tweet, validation_checking=False): """ Ensures a tweet is valid and determines the type of format for the tweet. Args: tweet (dict/Tweet): the tweet payload validation_checking (bool): check for valid key structure in a tweet. """ if "id" not in tweet: raise...
[ "def", "check_tweet", "(", "tweet", ",", "validation_checking", "=", "False", ")", ":", "if", "\"id\"", "not", "in", "tweet", ":", "raise", "NotATweetError", "(", "\"This text has no 'id' key\"", ")", "original_format", "=", "is_original_format", "(", "tweet", ")"...
Ensures a tweet is valid and determines the type of format for the tweet. Args: tweet (dict/Tweet): the tweet payload validation_checking (bool): check for valid key structure in a tweet.
[ "Ensures", "a", "tweet", "is", "valid", "and", "determines", "the", "type", "of", "format", "for", "the", "tweet", "." ]
python
train
kstaniek/condoor
condoor/drivers/XE.py
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/XE.py#L34-L73
def reload(self, reload_timeout=300, save_config=True): """Reload the device. CSM_DUT#reload System configuration has been modified. Save? [yes/no]: yes Building configuration... [OK] Proceed with reload? [confirm] """ SAVE_CONFIG = re.compile(re.escape(...
[ "def", "reload", "(", "self", ",", "reload_timeout", "=", "300", ",", "save_config", "=", "True", ")", ":", "SAVE_CONFIG", "=", "re", ".", "compile", "(", "re", ".", "escape", "(", "\"System configuration has been modified. Save? [yes/no]: \"", ")", ")", "PROCEE...
Reload the device. CSM_DUT#reload System configuration has been modified. Save? [yes/no]: yes Building configuration... [OK] Proceed with reload? [confirm]
[ "Reload", "the", "device", "." ]
python
train
ymoch/apyori
apyori.py
https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L206-L222
def gen_ordered_statistics(transaction_manager, record): """ Returns a generator of ordered statistics as OrderedStatistic instances. Arguments: transaction_manager -- Transactions as a TransactionManager instance. record -- A support record as a SupportRecord instance. """ items = ...
[ "def", "gen_ordered_statistics", "(", "transaction_manager", ",", "record", ")", ":", "items", "=", "record", ".", "items", "for", "combination_set", "in", "combinations", "(", "sorted", "(", "items", ")", ",", "len", "(", "items", ")", "-", "1", ")", ":",...
Returns a generator of ordered statistics as OrderedStatistic instances. Arguments: transaction_manager -- Transactions as a TransactionManager instance. record -- A support record as a SupportRecord instance.
[ "Returns", "a", "generator", "of", "ordered", "statistics", "as", "OrderedStatistic", "instances", "." ]
python
train
ossobv/dutree
dutree/dutree.py
https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L120-L124
def app_size(self): "Return the total apparent size, including children." if self._nodes is None: return self._app_size return sum(i.app_size() for i in self._nodes)
[ "def", "app_size", "(", "self", ")", ":", "if", "self", ".", "_nodes", "is", "None", ":", "return", "self", ".", "_app_size", "return", "sum", "(", "i", ".", "app_size", "(", ")", "for", "i", "in", "self", ".", "_nodes", ")" ]
Return the total apparent size, including children.
[ "Return", "the", "total", "apparent", "size", "including", "children", "." ]
python
train
skorch-dev/skorch
skorch/net.py
https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/skorch/net.py#L1222-L1248
def _get_params_for_optimizer(self, prefix, named_parameters): """Parse kwargs configuration for the optimizer identified by the given prefix. Supports param group assignment using wildcards: optimizer__lr=0.05, optimizer__param_groups=[ ('rnn*.period', {'lr': 0....
[ "def", "_get_params_for_optimizer", "(", "self", ",", "prefix", ",", "named_parameters", ")", ":", "kwargs", "=", "self", ".", "_get_params_for", "(", "prefix", ")", "params", "=", "list", "(", "named_parameters", ")", "pgroups", "=", "[", "]", "for", "patte...
Parse kwargs configuration for the optimizer identified by the given prefix. Supports param group assignment using wildcards: optimizer__lr=0.05, optimizer__param_groups=[ ('rnn*.period', {'lr': 0.3, 'momentum': 0}), ('rnn0', {'lr': 0.1}), ] ...
[ "Parse", "kwargs", "configuration", "for", "the", "optimizer", "identified", "by", "the", "given", "prefix", ".", "Supports", "param", "group", "assignment", "using", "wildcards", ":" ]
python
train