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
buriburisuri/sugartensor
sugartensor/sg_transform.py
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L199-L214
def sg_argmin(tensor, opt): r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tenso...
[ "def", "sg_argmin", "(", "tensor", ",", "opt", ")", ":", "opt", "+=", "tf", ".", "sg_opt", "(", "axis", "=", "tensor", ".", "get_shape", "(", ")", ".", "ndims", "-", "1", ")", "return", "tf", ".", "argmin", "(", "tensor", ",", "opt", ".", "axis",...
r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tensor's name. Returns: A ...
[ "r", "Returns", "the", "indices", "of", "the", "minimum", "values", "along", "the", "specified", "axis", "." ]
python
train
IdentityPython/pysaml2
src/saml2/httpbase.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L120-L149
def cookies(self, url): """ Return cookies that are matching the path and are still valid :param url: :return: """ part = urlparse(url) #if part.port: # _domain = "%s:%s" % (part.hostname, part.port) #else: _domain = part.hostname ...
[ "def", "cookies", "(", "self", ",", "url", ")", ":", "part", "=", "urlparse", "(", "url", ")", "#if part.port:", "# _domain = \"%s:%s\" % (part.hostname, part.port)", "#else:", "_domain", "=", "part", ".", "hostname", "cookie_dict", "=", "{", "}", "now", "=",...
Return cookies that are matching the path and are still valid :param url: :return:
[ "Return", "cookies", "that", "are", "matching", "the", "path", "and", "are", "still", "valid" ]
python
train
LordDarkula/chess_py
chess_py/pieces/king.py
https://github.com/LordDarkula/chess_py/blob/14bebc2f8c49ae25c59375cc83d0b38d8ff7281d/chess_py/pieces/king.py#L51-L63
def in_check_as_result(self, pos, move): """ Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool """ test = cp(pos) test.update(move) test_king = test.get_king(move.color) return self.loc_...
[ "def", "in_check_as_result", "(", "self", ",", "pos", ",", "move", ")", ":", "test", "=", "cp", "(", "pos", ")", "test", ".", "update", "(", "move", ")", "test_king", "=", "test", ".", "get_king", "(", "move", ".", "color", ")", "return", "self", "...
Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool
[ "Finds", "if", "playing", "my", "move", "would", "make", "both", "kings", "meet", "." ]
python
train
hvac/hvac
hvac/api/system_backend/key.py
https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/system_backend/key.py#L304-L325
def read_backup_keys(self, recovery_key=False): """Retrieve the backup copy of PGP-encrypted unseal keys. The returned value is the nonce of the rekey operation and a map of PGP key fingerprint to hex-encoded PGP-encrypted key. Supported methods: PUT: /sys/rekey/backup. Pro...
[ "def", "read_backup_keys", "(", "self", ",", "recovery_key", "=", "False", ")", ":", "api_path", "=", "'/v1/sys/rekey/backup'", "if", "recovery_key", ":", "api_path", "=", "'/v1/sys/rekey-recovery-key/backup'", "response", "=", "self", ".", "_adapter", ".", "get", ...
Retrieve the backup copy of PGP-encrypted unseal keys. The returned value is the nonce of the rekey operation and a map of PGP key fingerprint to hex-encoded PGP-encrypted key. Supported methods: PUT: /sys/rekey/backup. Produces: 200 application/json PUT: /sys/rekey-rec...
[ "Retrieve", "the", "backup", "copy", "of", "PGP", "-", "encrypted", "unseal", "keys", "." ]
python
train
RJT1990/pyflux
pyflux/ssm/dynlin.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/dynlin.py#L74-L92
def _forecast_model(self,beta,Z,h): """ Creates forecasted states and variances Parameters ---------- beta : np.ndarray Contains untransformed starting values for latent variables Returns ---------- a : np.ndarray Forecasted states ...
[ "def", "_forecast_model", "(", "self", ",", "beta", ",", "Z", ",", "h", ")", ":", "T", ",", "_", ",", "R", ",", "Q", ",", "H", "=", "self", ".", "_ss_matrices", "(", "beta", ")", "return", "dl_univariate_kalman_fcst", "(", "self", ".", "data", ",",...
Creates forecasted states and variances Parameters ---------- beta : np.ndarray Contains untransformed starting values for latent variables Returns ---------- a : np.ndarray Forecasted states P : np.ndarray Variance of foreca...
[ "Creates", "forecasted", "states", "and", "variances" ]
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/routing_system/route_map/content/set_/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/routing_system/route_map/content/set_/__init__.py#L527-L550
def _set_automatic_tag(self, v, load=False): """ Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method...
[ "def", "_set_automatic_tag", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should d...
[ "Setter", "method", "for", "automatic_tag", "mapped", "from", "YANG", "variable", "/", "routing_system", "/", "route_map", "/", "content", "/", "set", "/", "automatic_tag", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "con...
python
train
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1909-L1913
def console_load_xp(con: tcod.console.Console, filename: str) -> bool: """Update a console from a REXPaint `.xp` file.""" return bool( lib.TCOD_console_load_xp(_console(con), filename.encode("utf-8")) )
[ "def", "console_load_xp", "(", "con", ":", "tcod", ".", "console", ".", "Console", ",", "filename", ":", "str", ")", "->", "bool", ":", "return", "bool", "(", "lib", ".", "TCOD_console_load_xp", "(", "_console", "(", "con", ")", ",", "filename", ".", "...
Update a console from a REXPaint `.xp` file.
[ "Update", "a", "console", "from", "a", "REXPaint", ".", "xp", "file", "." ]
python
train
globocom/GloboNetworkAPI-client-python
networkapiclient/Interface.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Interface.py#L41-L72
def listar_por_equipamento(self, id_equipamento): """List all interfaces of an equipment. :param id_equipamento: Equipment identifier. :return: Dictionary with the following: :: {'interface': [{'protegida': < protegida >, 'nome': < nome >, ...
[ "def", "listar_por_equipamento", "(", "self", ",", "id_equipamento", ")", ":", "if", "not", "is_valid_int_param", "(", "id_equipamento", ")", ":", "raise", "InvalidParameterError", "(", "u'Equipment id is invalid or was not informed.'", ")", "url", "=", "'interface/equipa...
List all interfaces of an equipment. :param id_equipamento: Equipment identifier. :return: Dictionary with the following: :: {'interface': [{'protegida': < protegida >, 'nome': < nome >, 'id_ligacao_front': < id_ligacao_front >, 'id...
[ "List", "all", "interfaces", "of", "an", "equipment", "." ]
python
train
miguelgrinberg/python-socketio
socketio/base_manager.py
https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/base_manager.py#L116-L125
def get_rooms(self, sid, namespace): """Return the rooms a client is in.""" r = [] try: for room_name, room in six.iteritems(self.rooms[namespace]): if room_name is not None and sid in room and room[sid]: r.append(room_name) except KeyError...
[ "def", "get_rooms", "(", "self", ",", "sid", ",", "namespace", ")", ":", "r", "=", "[", "]", "try", ":", "for", "room_name", ",", "room", "in", "six", ".", "iteritems", "(", "self", ".", "rooms", "[", "namespace", "]", ")", ":", "if", "room_name", ...
Return the rooms a client is in.
[ "Return", "the", "rooms", "a", "client", "is", "in", "." ]
python
train
genepattern/genepattern-python
gp/core.py
https://github.com/genepattern/genepattern-python/blob/9478ea65362b91c72a94f7300c3de8d710bebb71/gp/core.py#L403-L415
def get_tags(self): """ Returns the tags for the job, querying the server if necessary. """ # Lazily load info if self.info is None: self.get_info() if 'tags' in self.info: return [structure['tag']['tag'] for structure in self.info['tags']...
[ "def", "get_tags", "(", "self", ")", ":", "# Lazily load info", "if", "self", ".", "info", "is", "None", ":", "self", ".", "get_info", "(", ")", "if", "'tags'", "in", "self", ".", "info", ":", "return", "[", "structure", "[", "'tag'", "]", "[", "'tag...
Returns the tags for the job, querying the server if necessary.
[ "Returns", "the", "tags", "for", "the", "job", "querying", "the", "server", "if", "necessary", "." ]
python
train
monarch-initiative/dipper
dipper/models/assoc/Association.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/models/assoc/Association.py#L250-L279
def make_association_id(definedby, sub, pred, obj, attributes=None): """ A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the str...
[ "def", "make_association_id", "(", "definedby", ",", "sub", ",", "pred", ",", "obj", ",", "attributes", "=", "None", ")", ":", "items_to_hash", "=", "[", "definedby", ",", "sub", ",", "pred", ",", "obj", "]", "if", "attributes", "is", "not", "None", "a...
A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated values. Subclasses of Assoc can submit an additional array of...
[ "A", "method", "to", "create", "unique", "identifiers", "for", "OBAN", "-", "style", "associations", "based", "on", "all", "the", "parts", "of", "the", "association", "If", "any", "of", "the", "items", "is", "empty", "or", "None", "it", "will", "convert", ...
python
train
Kozea/cairocffi
cairocffi/surfaces.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L397-L411
def get_font_options(self): """Retrieves the default font rendering options for the surface. This allows display surfaces to report the correct subpixel order for rendering on them, print surfaces to disable hinting of metrics and so forth. The result can then be used with :clas...
[ "def", "get_font_options", "(", "self", ")", ":", "font_options", "=", "FontOptions", "(", ")", "cairo", ".", "cairo_surface_get_font_options", "(", "self", ".", "_pointer", ",", "font_options", ".", "_pointer", ")", "return", "font_options" ]
Retrieves the default font rendering options for the surface. This allows display surfaces to report the correct subpixel order for rendering on them, print surfaces to disable hinting of metrics and so forth. The result can then be used with :class:`ScaledFont`. :returns: A ne...
[ "Retrieves", "the", "default", "font", "rendering", "options", "for", "the", "surface", "." ]
python
train
cltk/cltk
cltk/inflection/old_norse/nouns.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/inflection/old_norse/nouns.py#L693-L814
def decline_weak_feminine_noun(ns: str, gs: str, np: str): """ Gives the full declension of weak feminine nouns. >>> decline_weak_feminine_noun("saga", "sögu", "sögur") saga sögu sögu sögu sögur sögur sögum sagna >>> decline_weak_feminine_noun("kona", "konu", "konur") ...
[ "def", "decline_weak_feminine_noun", "(", "ns", ":", "str", ",", "gs", ":", "str", ",", "np", ":", "str", ")", ":", "if", "ns", "[", "-", "1", "]", "==", "\"i\"", "and", "gs", "[", "-", "1", "]", "==", "\"i\"", "and", "not", "np", ":", "print",...
Gives the full declension of weak feminine nouns. >>> decline_weak_feminine_noun("saga", "sögu", "sögur") saga sögu sögu sögu sögur sögur sögum sagna >>> decline_weak_feminine_noun("kona", "konu", "konur") kona konu konu konu konur konur konum kv...
[ "Gives", "the", "full", "declension", "of", "weak", "feminine", "nouns", "." ]
python
train
graphql-python/graphene-django
graphene_django/filter/utils.py
https://github.com/graphql-python/graphene-django/blob/20160113948b4167b61dbdaa477bb301227aac2e/graphene_django/filter/utils.py#L6-L19
def get_filtering_args_from_filterset(filterset_class, type): """ Inspect a FilterSet and produce the arguments to pass to a Graphene Field. These arguments will be available to filter against in the GraphQL """ from ..forms.converter import convert_form_field args = {} for name, fi...
[ "def", "get_filtering_args_from_filterset", "(", "filterset_class", ",", "type", ")", ":", "from", ".", ".", "forms", ".", "converter", "import", "convert_form_field", "args", "=", "{", "}", "for", "name", ",", "filter_field", "in", "six", ".", "iteritems", "(...
Inspect a FilterSet and produce the arguments to pass to a Graphene Field. These arguments will be available to filter against in the GraphQL
[ "Inspect", "a", "FilterSet", "and", "produce", "the", "arguments", "to", "pass", "to", "a", "Graphene", "Field", ".", "These", "arguments", "will", "be", "available", "to", "filter", "against", "in", "the", "GraphQL" ]
python
train
twisted/vertex
vertex/sigma.py
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/sigma.py#L518-L551
def selectOptimalChunk(self, peer): """ select an optimal chunk to send to a peer. @return: int(chunkNumber), str(chunkData) if there is data to be sent, otherwise None, None """ # stuff I have have = sets.Set(self.mask.positions(1)) # stuff that this pe...
[ "def", "selectOptimalChunk", "(", "self", ",", "peer", ")", ":", "# stuff I have", "have", "=", "sets", ".", "Set", "(", "self", ".", "mask", ".", "positions", "(", "1", ")", ")", "# stuff that this peer wants", "want", "=", "sets", ".", "Set", "(", "sel...
select an optimal chunk to send to a peer. @return: int(chunkNumber), str(chunkData) if there is data to be sent, otherwise None, None
[ "select", "an", "optimal", "chunk", "to", "send", "to", "a", "peer", "." ]
python
train
BreakingBytes/simkit
simkit/core/data_readers.py
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/data_readers.py#L243-L310
def load_data(self, filename, *args, **kwargs): """ Load parameters from Excel spreadsheet. :param filename: Name of Excel workbook with data. :type filename: str :returns: Data read from Excel workbook. :rtype: dict """ # workbook read from file ...
[ "def", "load_data", "(", "self", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# workbook read from file", "workbook", "=", "open_workbook", "(", "filename", ",", "verbosity", "=", "True", ")", "data", "=", "{", "}", "# an empty di...
Load parameters from Excel spreadsheet. :param filename: Name of Excel workbook with data. :type filename: str :returns: Data read from Excel workbook. :rtype: dict
[ "Load", "parameters", "from", "Excel", "spreadsheet", "." ]
python
train
ihgazni2/elist
elist/elist.py
https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L2506-L2536
def all_continuous_indexes_slices(ol,value): ''' from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] all_continuous_indexes_slices(ol,"a") ''' rslt = [] length = ol.__len__() cursor = 0 begin = None slice = [] while(cursor < length): cond1 =...
[ "def", "all_continuous_indexes_slices", "(", "ol", ",", "value", ")", ":", "rslt", "=", "[", "]", "length", "=", "ol", ".", "__len__", "(", ")", "cursor", "=", "0", "begin", "=", "None", "slice", "=", "[", "]", "while", "(", "cursor", "<", "length", ...
from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] all_continuous_indexes_slices(ol,"a")
[ "from", "elist", ".", "elist", "import", "*", "ol", "=", "[", "1", "a", "a", "2", "3", "a", "4", "a", "a", "a", "5", "]", "all_continuous_indexes_slices", "(", "ol", "a", ")" ]
python
valid
scikit-learn-contrib/hdbscan
hdbscan/validity.py
https://github.com/scikit-learn-contrib/hdbscan/blob/e40ccef139e56e38adf7bd6912cd63efd97598f9/hdbscan/validity.py#L116-L178
def internal_minimum_spanning_tree(mr_distances): """ Compute the 'internal' minimum spanning tree given a matrix of mutual reachability distances. Given a minimum spanning tree the 'internal' graph is the subgraph induced by vertices of degree greater than one. Parameters ---------- mr_dis...
[ "def", "internal_minimum_spanning_tree", "(", "mr_distances", ")", ":", "single_linkage_data", "=", "mst_linkage_core", "(", "mr_distances", ")", "min_span_tree", "=", "single_linkage_data", ".", "copy", "(", ")", "for", "index", ",", "row", "in", "enumerate", "(", ...
Compute the 'internal' minimum spanning tree given a matrix of mutual reachability distances. Given a minimum spanning tree the 'internal' graph is the subgraph induced by vertices of degree greater than one. Parameters ---------- mr_distances : array (cluster_size, cluster_size) The pairwi...
[ "Compute", "the", "internal", "minimum", "spanning", "tree", "given", "a", "matrix", "of", "mutual", "reachability", "distances", ".", "Given", "a", "minimum", "spanning", "tree", "the", "internal", "graph", "is", "the", "subgraph", "induced", "by", "vertices", ...
python
train
agoragames/leaderboard-python
leaderboard/leaderboard.py
https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L462-L481
def rank_for_in(self, leaderboard_name, member): ''' Retrieve the rank for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the rank for a member in the leaderboard. ''' if se...
[ "def", "rank_for_in", "(", "self", ",", "leaderboard_name", ",", "member", ")", ":", "if", "self", ".", "order", "==", "self", ".", "ASC", ":", "try", ":", "return", "self", ".", "redis_connection", ".", "zrank", "(", "leaderboard_name", ",", "member", "...
Retrieve the rank for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the rank for a member in the leaderboard.
[ "Retrieve", "the", "rank", "for", "a", "member", "in", "the", "named", "leaderboard", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/beacon/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/beacon/__init__.py#L94-L115
def _set_enable(self, v, load=False): """ Setter method for enable, mapped from YANG variable /beacon/enable (container) If this variable is read-only (config: false) in the source YANG file, then _set_enable is considered as a private method. Backends looking to populate this variable should do...
[ "def", "_set_enable", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for enable, mapped from YANG variable /beacon/enable (container) If this variable is read-only (config: false) in the source YANG file, then _set_enable is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_enable() directly.
[ "Setter", "method", "for", "enable", "mapped", "from", "YANG", "variable", "/", "beacon", "/", "enable", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file", ...
python
train
zqfang/GSEApy
gseapy/enrichr.py
https://github.com/zqfang/GSEApy/blob/673e9ec1391e3b14d3e8a4353117151fd2cb9345/gseapy/enrichr.py#L302-L352
def run(self): """run enrichr for one sample gene list but multi-libraries""" # set organism self.get_organism() # read input file genes_list = self.parse_genelists() gss = self.parse_genesets() # if gmt self._logger.info("Connecting to Enrichr Server to ...
[ "def", "run", "(", "self", ")", ":", "# set organism", "self", ".", "get_organism", "(", ")", "# read input file", "genes_list", "=", "self", ".", "parse_genelists", "(", ")", "gss", "=", "self", ".", "parse_genesets", "(", ")", "# if gmt", "self", ".", "_...
run enrichr for one sample gene list but multi-libraries
[ "run", "enrichr", "for", "one", "sample", "gene", "list", "but", "multi", "-", "libraries" ]
python
test
raphaelm/django-i18nfield
i18nfield/strings.py
https://github.com/raphaelm/django-i18nfield/blob/fb707931e4498ab1b609eaa0323bb5c3d5f7c7e7/i18nfield/strings.py#L48-L81
def localize(self, lng: str) -> str: """ Evaluate the given string with respect to the locale defined by ``lng``. If no string is available in the currently active language, this will give you the string in the system's default language. If this is unavailable as well, it will g...
[ "def", "localize", "(", "self", ",", "lng", ":", "str", ")", "->", "str", ":", "if", "self", ".", "data", "is", "None", ":", "return", "\"\"", "if", "isinstance", "(", "self", ".", "data", ",", "dict", ")", ":", "firstpart", "=", "lng", ".", "spl...
Evaluate the given string with respect to the locale defined by ``lng``. If no string is available in the currently active language, this will give you the string in the system's default language. If this is unavailable as well, it will give you the string in the first language available. ...
[ "Evaluate", "the", "given", "string", "with", "respect", "to", "the", "locale", "defined", "by", "lng", "." ]
python
train
Qiskit/qiskit-terra
qiskit/qasm/node/measure.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/measure.py#L24-L27
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" return "measure " + self.children[0].qasm(prec) + " -> " + \ self.children[1].qasm(prec) + ";"
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "return", "\"measure \"", "+", "self", ".", "children", "[", "0", "]", ".", "qasm", "(", "prec", ")", "+", "\" -> \"", "+", "self", ".", "children", "[", "1", "]", ".", "qasm", "(", ...
Return the corresponding OPENQASM string.
[ "Return", "the", "corresponding", "OPENQASM", "string", "." ]
python
test
redcanari/canari3
src/canari/entrypoints.py
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L220-L225
def remote_transform(host, transform, input, entity_field, transform_parameter, raw_output, ssl, base_path, soft_limit, hard_limit, verbose): """Runs Canari local transforms in a terminal-friendly fashion.""" from canari.commands.remote_transform import remote_transform remote_transform...
[ "def", "remote_transform", "(", "host", ",", "transform", ",", "input", ",", "entity_field", ",", "transform_parameter", ",", "raw_output", ",", "ssl", ",", "base_path", ",", "soft_limit", ",", "hard_limit", ",", "verbose", ")", ":", "from", "canari", ".", "...
Runs Canari local transforms in a terminal-friendly fashion.
[ "Runs", "Canari", "local", "transforms", "in", "a", "terminal", "-", "friendly", "fashion", "." ]
python
train
iotile/baBLE
tools/release.py
https://github.com/iotile/baBLE/blob/faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db/tools/release.py#L23-L34
def build_wheel(platform): """Create a wheel""" if platform in ['x86_64', 'i686']: system = 'manylinux1' else: system = 'linux' setuptools.sandbox.run_setup( 'setup.py', ['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platform)] )
[ "def", "build_wheel", "(", "platform", ")", ":", "if", "platform", "in", "[", "'x86_64'", ",", "'i686'", "]", ":", "system", "=", "'manylinux1'", "else", ":", "system", "=", "'linux'", "setuptools", ".", "sandbox", ".", "run_setup", "(", "'setup.py'", ",",...
Create a wheel
[ "Create", "a", "wheel" ]
python
train
yyuu/botornado
boto/ec2/elb/__init__.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/ec2/elb/__init__.py#L328-L349
def describe_instance_health(self, load_balancer_name, instances=None): """ Get current state of all Instances registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :par...
[ "def", "describe_instance_health", "(", "self", ",", "load_balancer_name", ",", "instances", "=", "None", ")", ":", "params", "=", "{", "'LoadBalancerName'", ":", "load_balancer_name", "}", "if", "instances", ":", "self", ".", "build_list_params", "(", "params", ...
Get current state of all Instances registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to return sta...
[ "Get", "current", "state", "of", "all", "Instances", "registered", "to", "an", "Load", "Balancer", "." ]
python
train
gpoulter/fablib
fablib.py
https://github.com/gpoulter/fablib/blob/5d14c4d998f79dd1aa3207063c3d06e30e3e2bf9/fablib.py#L280-L288
def write_version(path, ref=None): """Update version file using git desribe""" with lcd(dirname(path)): version = make_version(ref) if (env.get('full') or not os.path.exists(path) or version != open(path).read().strip()): with open(path, 'w') as out: out.write(version...
[ "def", "write_version", "(", "path", ",", "ref", "=", "None", ")", ":", "with", "lcd", "(", "dirname", "(", "path", ")", ")", ":", "version", "=", "make_version", "(", "ref", ")", "if", "(", "env", ".", "get", "(", "'full'", ")", "or", "not", "os...
Update version file using git desribe
[ "Update", "version", "file", "using", "git", "desribe" ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/utils/io.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L283-L303
def temp_pyfile(src, ext='.py'): """Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. ...
[ "def", "temp_pyfile", "(", "src", ",", "ext", "=", "'.py'", ")", ":", "fname", "=", "tempfile", ".", "mkstemp", "(", "ext", ")", "[", "1", "]", "f", "=", "open", "(", "fname", ",", "'w'", ")", "f", ".", "write", "(", "src", ")", "f", ".", "fl...
Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. Returns ------- (filename, ...
[ "Make", "a", "temporary", "python", "file", "return", "filename", "and", "filehandle", "." ]
python
test
dw/mitogen
ansible_mitogen/connection.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/connection.py#L349-L363
def _connect_mitogen_doas(spec): """ Return ContextService arguments for doas as a first class connection. """ return { 'method': 'doas', 'kwargs': { 'username': spec.remote_user(), 'password': spec.password(), 'python_path': spec.python_path(), ...
[ "def", "_connect_mitogen_doas", "(", "spec", ")", ":", "return", "{", "'method'", ":", "'doas'", ",", "'kwargs'", ":", "{", "'username'", ":", "spec", ".", "remote_user", "(", ")", ",", "'password'", ":", "spec", ".", "password", "(", ")", ",", "'python_...
Return ContextService arguments for doas as a first class connection.
[ "Return", "ContextService", "arguments", "for", "doas", "as", "a", "first", "class", "connection", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1140-L1153
def autoencoder_residual_discrete(): """Residual discrete autoencoder model.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.05 hparams.add_hparam("discretize_warmup_steps", 16000) hparams.add_hparam("bottleneck_kind", "tanh_discrete") hparams.add_hparam("is...
[ "def", "autoencoder_residual_discrete", "(", ")", ":", "hparams", "=", "autoencoder_residual", "(", ")", "hparams", ".", "bottleneck_bits", "=", "1024", "hparams", ".", "bottleneck_noise", "=", "0.05", "hparams", ".", "add_hparam", "(", "\"discretize_warmup_steps\"", ...
Residual discrete autoencoder model.
[ "Residual", "discrete", "autoencoder", "model", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/graph/graph.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/graph/graph.py#L298-L306
def log_time_frame(bcbio_log): """The bcbio running time frame. :return: an instance of :class collections.namedtuple: with the following fields: start and end """ output = collections.namedtuple("Time", ["start", "end", "steps"]) bcbio_timings = get_bcbio_timings(bcbio_log) ...
[ "def", "log_time_frame", "(", "bcbio_log", ")", ":", "output", "=", "collections", ".", "namedtuple", "(", "\"Time\"", ",", "[", "\"start\"", ",", "\"end\"", ",", "\"steps\"", "]", ")", "bcbio_timings", "=", "get_bcbio_timings", "(", "bcbio_log", ")", "return"...
The bcbio running time frame. :return: an instance of :class collections.namedtuple: with the following fields: start and end
[ "The", "bcbio", "running", "time", "frame", "." ]
python
train
Opentrons/opentrons
api/src/opentrons/hardware_control/simulator.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/simulator.py#L199-L202
def axis_bounds(self) -> Dict[str, Tuple[float, float]]: """ The (minimum, maximum) bounds for each axis. """ return {ax: (0, pos+0.5) for ax, pos in _HOME_POSITION.items() if ax not in 'BC'}
[ "def", "axis_bounds", "(", "self", ")", "->", "Dict", "[", "str", ",", "Tuple", "[", "float", ",", "float", "]", "]", ":", "return", "{", "ax", ":", "(", "0", ",", "pos", "+", "0.5", ")", "for", "ax", ",", "pos", "in", "_HOME_POSITION", ".", "i...
The (minimum, maximum) bounds for each axis.
[ "The", "(", "minimum", "maximum", ")", "bounds", "for", "each", "axis", "." ]
python
train
tcalmant/ipopo
pelix/ipopo/instance.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L628-L665
def safe_callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None...
[ "def", "safe_callback", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (str, *Any, **Any) -> Any", "if", "self", ".", "state", "==", "StoredInstance", ".", "KILLED", ":", "# Invalid state", "return", "None", "try", "...
Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None
[ "Calls", "the", "registered", "method", "in", "the", "component", "for", "the", "given", "event", "ignoring", "raised", "exceptions" ]
python
train
gmr/httpbl
httpbl.py
https://github.com/gmr/httpbl/blob/1728720e104748def509b142231c7e48f1f80e8c/httpbl.py#L103-L133
def _decode_response(self, ip_address): """Decodes a HttpBL response IP and return data structure of response data. :param ip_address: IP address to query :type ip_address: str :rtype: dict :raises: ValueError """ # Reverse the IP, reassign the octets to...
[ "def", "_decode_response", "(", "self", ",", "ip_address", ")", ":", "# Reverse the IP, reassign the octets to integers", "vt", ",", "ts", ",", "days", ",", "rc", "=", "[", "int", "(", "o", ")", "for", "o", "in", "ip_address", ".", "split", "(", "'.'", ")"...
Decodes a HttpBL response IP and return data structure of response data. :param ip_address: IP address to query :type ip_address: str :rtype: dict :raises: ValueError
[ "Decodes", "a", "HttpBL", "response", "IP", "and", "return", "data", "structure", "of", "response", "data", "." ]
python
train
ArangoDB-Community/pyArango
pyArango/document.py
https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L289-L316
def patch(self, keepNull = True, **docArgs) : """Saves the document by only updating the modified fields. The default behaviour concening the keepNull parameter is the opposite of ArangoDB's default, Null values won't be ignored Use docArgs for things such as waitForSync = True""" if se...
[ "def", "patch", "(", "self", ",", "keepNull", "=", "True", ",", "*", "*", "docArgs", ")", ":", "if", "self", ".", "URL", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot patch a document that was not previously saved\"", ")", "payload", "=", "self", ...
Saves the document by only updating the modified fields. The default behaviour concening the keepNull parameter is the opposite of ArangoDB's default, Null values won't be ignored Use docArgs for things such as waitForSync = True
[ "Saves", "the", "document", "by", "only", "updating", "the", "modified", "fields", ".", "The", "default", "behaviour", "concening", "the", "keepNull", "parameter", "is", "the", "opposite", "of", "ArangoDB", "s", "default", "Null", "values", "won", "t", "be", ...
python
train
piface/pifacedigitalio
pifacedigitalio/core.py
https://github.com/piface/pifacedigitalio/blob/d231a82bdb55d5f57f44ba7aec00bfd6c0b9a9d4/pifacedigitalio/core.py#L176-L192
def deinit(bus=DEFAULT_SPI_BUS, chip_select=DEFAULT_SPI_CHIP_SELECT): """Stops interrupts on all boards. Only required when using :func:`digital_read` and :func:`digital_write`. :param bus: SPI bus /dev/spidev<bus>.<chipselect> (default: {bus}) :type bus: int :param chip_select: SPI chip...
[ "def", "deinit", "(", "bus", "=", "DEFAULT_SPI_BUS", ",", "chip_select", "=", "DEFAULT_SPI_CHIP_SELECT", ")", ":", "global", "_pifacedigitals", "for", "pfd", "in", "_pifacedigitals", ":", "try", ":", "pfd", ".", "deinit_board", "(", ")", "except", "AttributeErro...
Stops interrupts on all boards. Only required when using :func:`digital_read` and :func:`digital_write`. :param bus: SPI bus /dev/spidev<bus>.<chipselect> (default: {bus}) :type bus: int :param chip_select: SPI chip select /dev/spidev<bus>.<chipselect> (default: {chip}) :type chip_select: i...
[ "Stops", "interrupts", "on", "all", "boards", ".", "Only", "required", "when", "using", ":", "func", ":", "digital_read", "and", ":", "func", ":", "digital_write", "." ]
python
train
edeposit/edeposit.amqp.pdfgen
src/edeposit/amqp/pdfgen/__init__.py
https://github.com/edeposit/edeposit.amqp.pdfgen/blob/1022d6d01196f4928d664a71e49273c2d8c67e63/src/edeposit/amqp/pdfgen/__init__.py#L24-L58
def reactToAMQPMessage(message, sender): """ React to given (AMQP) message. `message` is usually expected to be :py:func:`collections.namedtuple` structure filled with all necessary data. Args: message (\*Request class): One of the structures defined in :mod:`.requests`. ...
[ "def", "reactToAMQPMessage", "(", "message", ",", "sender", ")", ":", "if", "_instanceof", "(", "message", ",", "GenerateContract", ")", ":", "return", "pdf_from_file", "(", "# TODO: rewrite to decorator", "get_contract", "(", "*", "*", "message", ".", "_asdict", ...
React to given (AMQP) message. `message` is usually expected to be :py:func:`collections.namedtuple` structure filled with all necessary data. Args: message (\*Request class): One of the structures defined in :mod:`.requests`. sender (fn reference): Reference to function for res...
[ "React", "to", "given", "(", "AMQP", ")", "message", ".", "message", "is", "usually", "expected", "to", "be", ":", "py", ":", "func", ":", "collections", ".", "namedtuple", "structure", "filled", "with", "all", "necessary", "data", "." ]
python
train
rigetti/pyquil
pyquil/quil.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quil.py#L1024-L1035
def validate_protoquil(program: Program) -> None: """ Ensure that a program is valid ProtoQuil, otherwise raise a ValueError. Protoquil is a subset of Quil which excludes control flow and classical instructions. :param program: The Quil program to validate. """ valid_instruction_types = tuple([...
[ "def", "validate_protoquil", "(", "program", ":", "Program", ")", "->", "None", ":", "valid_instruction_types", "=", "tuple", "(", "[", "Pragma", ",", "Declare", ",", "Halt", ",", "Gate", ",", "Reset", ",", "ResetQubit", ",", "Measurement", "]", ")", "for"...
Ensure that a program is valid ProtoQuil, otherwise raise a ValueError. Protoquil is a subset of Quil which excludes control flow and classical instructions. :param program: The Quil program to validate.
[ "Ensure", "that", "a", "program", "is", "valid", "ProtoQuil", "otherwise", "raise", "a", "ValueError", ".", "Protoquil", "is", "a", "subset", "of", "Quil", "which", "excludes", "control", "flow", "and", "classical", "instructions", "." ]
python
train
spyder-ide/spyder
spyder/widgets/arraybuilder.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L47-L56
def keyPressEvent(self, event): """ Qt override. """ if event.key() in [Qt.Key_Enter, Qt.Key_Return]: self._parent.process_text() if self._parent.is_valid(): self._parent.keyPressEvent(event) else: QLineEdit.keyPressEve...
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "in", "[", "Qt", ".", "Key_Enter", ",", "Qt", ".", "Key_Return", "]", ":", "self", ".", "_parent", ".", "process_text", "(", ")", "if", "self", ".", ...
Qt override.
[ "Qt", "override", "." ]
python
train
ladybug-tools/ladybug
ladybug/dt.py
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L73-L79
def from_hoy(cls, hoy, leap_year=False): """Create Ladybug Datetime from an hour of the year. Args: hoy: A float value 0 <= and < 8760 """ return cls.from_moy(round(hoy * 60), leap_year)
[ "def", "from_hoy", "(", "cls", ",", "hoy", ",", "leap_year", "=", "False", ")", ":", "return", "cls", ".", "from_moy", "(", "round", "(", "hoy", "*", "60", ")", ",", "leap_year", ")" ]
Create Ladybug Datetime from an hour of the year. Args: hoy: A float value 0 <= and < 8760
[ "Create", "Ladybug", "Datetime", "from", "an", "hour", "of", "the", "year", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xorbbrowserwidget/xcardwidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xcardwidget.py#L33-L40
def browserWidget( self ): """ Returns the browser widget this card is linked to. :return <XOrbBrowserWidget> || None """ from projexui.widgets.xorbbrowserwidget import XOrbBrowserWidget return projexui.ancestor(self, XOrbBrowserWidget)
[ "def", "browserWidget", "(", "self", ")", ":", "from", "projexui", ".", "widgets", ".", "xorbbrowserwidget", "import", "XOrbBrowserWidget", "return", "projexui", ".", "ancestor", "(", "self", ",", "XOrbBrowserWidget", ")" ]
Returns the browser widget this card is linked to. :return <XOrbBrowserWidget> || None
[ "Returns", "the", "browser", "widget", "this", "card", "is", "linked", "to", ".", ":", "return", "<XOrbBrowserWidget", ">", "||", "None" ]
python
train
jobovy/galpy
galpy/df/quasiisothermaldf.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/quasiisothermaldf.py#L2530-L2532
def _vmomentsurfaceMCIntegrand(vz,vR,vT,R,z,df,sigmaR1,gamma,sigmaz1,mvT,n,m,o): """Internal function that is the integrand for the vmomentsurface mass integration""" return vR**n*vT**m*vz**o*df(R,vR*sigmaR1,vT*sigmaR1*gamma,z,vz*sigmaz1,use_physical=False)*numpy.exp(vR**2./2.+(vT-mvT)**2./2.+vz**2./2.)
[ "def", "_vmomentsurfaceMCIntegrand", "(", "vz", ",", "vR", ",", "vT", ",", "R", ",", "z", ",", "df", ",", "sigmaR1", ",", "gamma", ",", "sigmaz1", ",", "mvT", ",", "n", ",", "m", ",", "o", ")", ":", "return", "vR", "**", "n", "*", "vT", "**", ...
Internal function that is the integrand for the vmomentsurface mass integration
[ "Internal", "function", "that", "is", "the", "integrand", "for", "the", "vmomentsurface", "mass", "integration" ]
python
train
python-rope/rope
rope/refactor/sourceutils.py
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/sourceutils.py#L67-L87
def get_body_region(defined): """Return the start and end offsets of function body""" scope = defined.get_scope() pymodule = defined.get_module() lines = pymodule.lines node = defined.get_ast() start_line = node.lineno if defined.get_doc() is None: start_line = node.body[0].lineno ...
[ "def", "get_body_region", "(", "defined", ")", ":", "scope", "=", "defined", ".", "get_scope", "(", ")", "pymodule", "=", "defined", ".", "get_module", "(", ")", "lines", "=", "pymodule", ".", "lines", "node", "=", "defined", ".", "get_ast", "(", ")", ...
Return the start and end offsets of function body
[ "Return", "the", "start", "and", "end", "offsets", "of", "function", "body" ]
python
train
ungarj/mapchete
mapchete/config.py
https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L714-L740
def bounds_from_opts( wkt_geometry=None, point=None, bounds=None, zoom=None, raw_conf=None ): """ Loads the process pyramid of a raw configuration. Parameters ---------- raw_conf : dict Raw mapchete configuration as dictionary. Returns ------- BufferedTilePyramid """ ...
[ "def", "bounds_from_opts", "(", "wkt_geometry", "=", "None", ",", "point", "=", "None", ",", "bounds", "=", "None", ",", "zoom", "=", "None", ",", "raw_conf", "=", "None", ")", ":", "if", "wkt_geometry", ":", "return", "wkt", ".", "loads", "(", "wkt_ge...
Loads the process pyramid of a raw configuration. Parameters ---------- raw_conf : dict Raw mapchete configuration as dictionary. Returns ------- BufferedTilePyramid
[ "Loads", "the", "process", "pyramid", "of", "a", "raw", "configuration", "." ]
python
valid
vinitkumar/pycrawler
crawler.py
https://github.com/vinitkumar/pycrawler/blob/d3fe6d2da1469fc701c4fe04df88cee9cc8cd9c3/crawler.py#L17-L39
def option_parser(): """Option Parser to give various options.""" usage = ''' $ ./crawler -d5 <url> Here in this case it goes till depth of 5 and url is target URL to start crawling. ''' version = "2.0.0" parser = optparse.OptionParser(usage=usag...
[ "def", "option_parser", "(", ")", ":", "usage", "=", "'''\n $ ./crawler -d5 <url>\n Here in this case it goes till depth of 5 and url is target URL to\n start crawling.\n '''", "version", "=", "\"2.0.0\"", "parser", "=", "optparse", "....
Option Parser to give various options.
[ "Option", "Parser", "to", "give", "various", "options", "." ]
python
train
pantsbuild/pants
src/python/pants/option/option_tracker.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/option_tracker.py#L72-L87
def record_option(self, scope, option, value, rank, deprecation_version=None, details=None): """Records that the given option was set to the given value. :param string scope: scope of the option. :param string option: name of the option. :param string value: value the option was set to. :param int ...
[ "def", "record_option", "(", "self", ",", "scope", ",", "option", ",", "value", ",", "rank", ",", "deprecation_version", "=", "None", ",", "details", "=", "None", ")", ":", "scoped_options", "=", "self", ".", "option_history_by_scope", "[", "scope", "]", "...
Records that the given option was set to the given value. :param string scope: scope of the option. :param string option: name of the option. :param string value: value the option was set to. :param int rank: the rank of the option (Eg, RankedValue.HARDCODED), to keep track of where the option ca...
[ "Records", "that", "the", "given", "option", "was", "set", "to", "the", "given", "value", "." ]
python
train
mgedmin/findimports
findimports.py
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L634-L699
def collapseCycles(self): """Create a graph with cycles collapsed. Collapse modules participating in a cycle to a single node. """ # This algorithm determines Strongly Connected Components. Look it up. # It is adapted to suit our data structures. # Phase 0: prepare the ...
[ "def", "collapseCycles", "(", "self", ")", ":", "# This algorithm determines Strongly Connected Components. Look it up.", "# It is adapted to suit our data structures.", "# Phase 0: prepare the graph", "imports", "=", "{", "}", "for", "u", "in", "self", ".", "modules", ":", ...
Create a graph with cycles collapsed. Collapse modules participating in a cycle to a single node.
[ "Create", "a", "graph", "with", "cycles", "collapsed", "." ]
python
train
devopshq/crosspm
crosspm/helpers/downloader.py
https://github.com/devopshq/crosspm/blob/c831442ecfaa1d43c66cb148857096cea292c950/crosspm/helpers/downloader.py#L189-L217
def set_duplicated_flag(self): """ For all package set flag duplicated, if it's not unique package :return: """ package_by_name = defaultdict(list) for package1 in self._root_package.all_packages: if package1 is None: continue pkg_...
[ "def", "set_duplicated_flag", "(", "self", ")", ":", "package_by_name", "=", "defaultdict", "(", "list", ")", "for", "package1", "in", "self", ".", "_root_package", ".", "all_packages", ":", "if", "package1", "is", "None", ":", "continue", "pkg_name", "=", "...
For all package set flag duplicated, if it's not unique package :return:
[ "For", "all", "package", "set", "flag", "duplicated", "if", "it", "s", "not", "unique", "package", ":", "return", ":" ]
python
train
saltstack/salt
salt/cloud/clouds/qingcloud.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/qingcloud.py#L476-L521
def list_nodes_full(call=None): ''' Return a list of the instances that are on the provider. CLI Examples: .. code-block:: bash salt-cloud -F my-qingcloud ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --...
[ "def", "list_nodes_full", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes_full function must be called with -f or --function.'", ")", "zone", "=", "_get_specified_zone", "(", ")", "params", ...
Return a list of the instances that are on the provider. CLI Examples: .. code-block:: bash salt-cloud -F my-qingcloud
[ "Return", "a", "list", "of", "the", "instances", "that", "are", "on", "the", "provider", "." ]
python
train
tmr232/Sark
sark/structure.py
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/structure.py#L33-L56
def struct_member_error(err, sid, name, offset, size): """Create and format a struct member exception. Args: err: The error value returned from struct member creation sid: The struct id name: The member name offset: Memeber offset size: Member size Returns: ...
[ "def", "struct_member_error", "(", "err", ",", "sid", ",", "name", ",", "offset", ",", "size", ")", ":", "exception", ",", "msg", "=", "STRUCT_ERROR_MAP", "[", "err", "]", "struct_name", "=", "idc", ".", "GetStrucName", "(", "sid", ")", "return", "except...
Create and format a struct member exception. Args: err: The error value returned from struct member creation sid: The struct id name: The member name offset: Memeber offset size: Member size Returns: A ``SarkErrorAddStructMemeberFailed`` derivative exception, wi...
[ "Create", "and", "format", "a", "struct", "member", "exception", "." ]
python
train
halcy/Mastodon.py
mastodon/Mastodon.py
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L673-L706
def timeline_hashtag(self, hashtag, local=False, max_id=None, min_id=None, since_id=None, limit=None, only_media=False): """ Fetch a timeline of toots with a given hashtag. The hashtag parameter should not contain the leading #. Set `local` to True to retrieve only instance-local tagged...
[ "def", "timeline_hashtag", "(", "self", ",", "hashtag", ",", "local", "=", "False", ",", "max_id", "=", "None", ",", "min_id", "=", "None", ",", "since_id", "=", "None", ",", "limit", "=", "None", ",", "only_media", "=", "False", ")", ":", "if", "has...
Fetch a timeline of toots with a given hashtag. The hashtag parameter should not contain the leading #. Set `local` to True to retrieve only instance-local tagged posts. Set `only_media` to True to retrieve only statuses with media attachments. Returns a list of `toot dicts`_.
[ "Fetch", "a", "timeline", "of", "toots", "with", "a", "given", "hashtag", ".", "The", "hashtag", "parameter", "should", "not", "contain", "the", "leading", "#", "." ]
python
train
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2015_04_05/file/fileservice.py
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2015_04_05/file/fileservice.py#L1817-L1925
def get_file_to_stream( self, share_name, directory_name, file_name, stream, start_range=None, end_range=None, range_get_content_md5=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Downloads a file to a stream, with autom...
[ "def", "get_file_to_stream", "(", "self", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "stream", ",", "start_range", "=", "None", ",", "end_range", "=", "None", ",", "range_get_content_md5", "=", "None", ",", "progress_callback", "=", "None",...
Downloads a file to a stream, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties and metadata. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :para...
[ "Downloads", "a", "file", "to", "a", "stream", "with", "automatic", "chunking", "and", "progress", "notifications", ".", "Returns", "an", "instance", "of", ":", "class", ":", "File", "with", "properties", "and", "metadata", "." ]
python
train
SatelliteQE/nailgun
nailgun/entities.py
https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L2319-L2326
def create_payload(self): """Reset ``errata_id`` from DB ID to ``errata_id``.""" payload = super(ContentViewFilterRule, self).create_payload() if 'errata_id' in payload: if not hasattr(self.errata, 'errata_id'): self.errata = self.errata.read() payload['er...
[ "def", "create_payload", "(", "self", ")", ":", "payload", "=", "super", "(", "ContentViewFilterRule", ",", "self", ")", ".", "create_payload", "(", ")", "if", "'errata_id'", "in", "payload", ":", "if", "not", "hasattr", "(", "self", ".", "errata", ",", ...
Reset ``errata_id`` from DB ID to ``errata_id``.
[ "Reset", "errata_id", "from", "DB", "ID", "to", "errata_id", "." ]
python
train
joke2k/faker
faker/providers/address/ko_KR/__init__.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/address/ko_KR/__init__.py#L346-L351
def town(self): """ :example 가나동 """ pattern = self.random_element(self.town_formats) return self.generator.parse(pattern)
[ "def", "town", "(", "self", ")", ":", "pattern", "=", "self", ".", "random_element", "(", "self", ".", "town_formats", ")", "return", "self", ".", "generator", ".", "parse", "(", "pattern", ")" ]
:example 가나동
[ ":", "example", "가나동" ]
python
train
proycon/pynlpl
pynlpl/datatypes.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L196-L198
def randomprune(self,n): """prune down to n items at random, disregarding their score""" self.data = random.sample(self.data, n)
[ "def", "randomprune", "(", "self", ",", "n", ")", ":", "self", ".", "data", "=", "random", ".", "sample", "(", "self", ".", "data", ",", "n", ")" ]
prune down to n items at random, disregarding their score
[ "prune", "down", "to", "n", "items", "at", "random", "disregarding", "their", "score" ]
python
train
lucastheis/django-publications
publications/models/publication.py
https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/publication.py#L108-L207
def _produce_author_lists(self): """ Parse authors string to create lists of authors. """ # post-process author names self.authors = self.authors.replace(', and ', ', ') self.authors = self.authors.replace(',and ', ', ') self.authors = self.authors.replace(' and ', ', ') self.authors = self.authors.rep...
[ "def", "_produce_author_lists", "(", "self", ")", ":", "# post-process author names", "self", ".", "authors", "=", "self", ".", "authors", ".", "replace", "(", "', and '", ",", "', '", ")", "self", ".", "authors", "=", "self", ".", "authors", ".", "replace",...
Parse authors string to create lists of authors.
[ "Parse", "authors", "string", "to", "create", "lists", "of", "authors", "." ]
python
valid
AndresMWeber/Nomenclate
nomenclate/core/formatter.py
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/formatter.py#L88-L111
def validate_matched_parenthesis(cls, format_target): """ Adapted from https://stackoverflow.com/questions/6701853/parentheses-pairing-issue :param format_order: :return: """ iparens = iter('(){}[]<>') parens = dict(zip(iparens, iparens)) closing = parens.values(...
[ "def", "validate_matched_parenthesis", "(", "cls", ",", "format_target", ")", ":", "iparens", "=", "iter", "(", "'(){}[]<>'", ")", "parens", "=", "dict", "(", "zip", "(", "iparens", ",", "iparens", ")", ")", "closing", "=", "parens", ".", "values", "(", ...
Adapted from https://stackoverflow.com/questions/6701853/parentheses-pairing-issue :param format_order: :return:
[ "Adapted", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "6701853", "/", "parentheses", "-", "pairing", "-", "issue" ]
python
train
CalebBell/thermo
thermo/utils.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3446-L3483
def property_derivative_P(self, T, P, zs, ws, order=1): r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition, of a given order. Methods found valid by `select_valid_methods` are attempted until a method succeeds. If ...
[ "def", "property_derivative_P", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "order", "=", "1", ")", ":", "sorted_valid_methods", "=", "self", ".", "select_valid_methods", "(", "T", ",", "P", ",", "zs", ",", "ws", ")", "for", "method",...
r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition, of a given order. Methods found valid by `select_valid_methods` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. ...
[ "r", "Method", "to", "calculate", "a", "derivative", "of", "a", "mixture", "property", "with", "respect", "to", "pressure", "at", "constant", "temperature", "and", "composition", "of", "a", "given", "order", ".", "Methods", "found", "valid", "by", "select_vali...
python
valid
BlueBrain/hpcbench
hpcbench/benchmark/ior.py
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/ior.py#L313-L327
def file_mode(self): """onefile, fpp, or both""" fms = self.attributes['file_mode'] eax = set() if isinstance(fms, six.string_types): fms = shlex.split(fms) for fm in fms: if fm == 'both': eax.add('fpp') eax.add('onefile') ...
[ "def", "file_mode", "(", "self", ")", ":", "fms", "=", "self", ".", "attributes", "[", "'file_mode'", "]", "eax", "=", "set", "(", ")", "if", "isinstance", "(", "fms", ",", "six", ".", "string_types", ")", ":", "fms", "=", "shlex", ".", "split", "(...
onefile, fpp, or both
[ "onefile", "fpp", "or", "both" ]
python
train
timkpaine/pyEX
pyEX/stocks.py
https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L1029-L1046
def largestTradesDF(symbol, token='', version=''): '''This returns 15 minute delayed, last sale eligible trades. https://iexcloud.io/docs/api/#largest-trades 9:30-4pm ET M-F during regular market hours Args: symbol (string); Ticker to request token (string); Access token versio...
[ "def", "largestTradesDF", "(", "symbol", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "largestTrades", "(", "symbol", ",", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "_re...
This returns 15 minute delayed, last sale eligible trades. https://iexcloud.io/docs/api/#largest-trades 9:30-4pm ET M-F during regular market hours Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: DataFrame: r...
[ "This", "returns", "15", "minute", "delayed", "last", "sale", "eligible", "trades", "." ]
python
valid
ktbyers/netmiko
netmiko/cisco/cisco_ios.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/cisco/cisco_ios.py#L167-L172
def file_md5(self, file_name): """Compute MD5 hash of file.""" file_contents = self._read_file(file_name) file_contents = file_contents + "\n" # Cisco IOS automatically adds this file_contents = file_contents.encode("UTF-8") return hashlib.md5(file_contents).hexdigest()
[ "def", "file_md5", "(", "self", ",", "file_name", ")", ":", "file_contents", "=", "self", ".", "_read_file", "(", "file_name", ")", "file_contents", "=", "file_contents", "+", "\"\\n\"", "# Cisco IOS automatically adds this", "file_contents", "=", "file_contents", "...
Compute MD5 hash of file.
[ "Compute", "MD5", "hash", "of", "file", "." ]
python
train
tanghaibao/jcvi
jcvi/assembly/bambus.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/bambus.py#L22-L99
def scaffold(args): """ %prog scaffold ctgfasta reads1.fasta mapping1.bed reads2.fasta mapping2.bed ... Run BAMBUS on set of contigs, reads and read mappings. """ from jcvi.formats.base import FileMerger from jcvi.formats.bed import mates from jcvi.formats.conti...
[ "def", "scaffold", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "base", "import", "FileMerger", "from", "jcvi", ".", "formats", ".", "bed", "import", "mates", "from", "jcvi", ".", "formats", ".", "contig", "import", "frombed", "from", "jcv...
%prog scaffold ctgfasta reads1.fasta mapping1.bed reads2.fasta mapping2.bed ... Run BAMBUS on set of contigs, reads and read mappings.
[ "%prog", "scaffold", "ctgfasta", "reads1", ".", "fasta", "mapping1", ".", "bed", "reads2", ".", "fasta", "mapping2", ".", "bed", "..." ]
python
train
devision-io/metasdk
metasdk/services/MediaService.py
https://github.com/devision-io/metasdk/blob/1a1af5ceeb8ade843fd656c9c27c8b9ff789fc68/metasdk/services/MediaService.py#L13-L18
def persist_one(self, file_base64_content, filename, extension, mime, is_private=True): """ Загружает файл в облако :type origin: string Принимает значения ROBOT, USER """ return self.__app.api_call("MediaService", "persist_one", locals(), {})
[ "def", "persist_one", "(", "self", ",", "file_base64_content", ",", "filename", ",", "extension", ",", "mime", ",", "is_private", "=", "True", ")", ":", "return", "self", ".", "__app", ".", "api_call", "(", "\"MediaService\"", ",", "\"persist_one\"", ",", "l...
Загружает файл в облако :type origin: string Принимает значения ROBOT, USER
[ "Загружает", "файл", "в", "облако", ":", "type", "origin", ":", "string", "Принимает", "значения", "ROBOT", "USER" ]
python
train
artefactual-labs/agentarchives
agentarchives/atom/client.py
https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/atom/client.py#L114-L141
def _format_notes(self, record): """ Extracts notes from a record and reformats them in a simplified format. """ notes = [] if "notes" in record: for note in record["notes"]: self._append_note_dict_to_list(notes, "general", note) if "language...
[ "def", "_format_notes", "(", "self", ",", "record", ")", ":", "notes", "=", "[", "]", "if", "\"notes\"", "in", "record", ":", "for", "note", "in", "record", "[", "\"notes\"", "]", ":", "self", ".", "_append_note_dict_to_list", "(", "notes", ",", "\"gener...
Extracts notes from a record and reformats them in a simplified format.
[ "Extracts", "notes", "from", "a", "record", "and", "reformats", "them", "in", "a", "simplified", "format", "." ]
python
train
google/prettytensor
prettytensor/pretty_tensor_loss_methods.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_loss_methods.py#L222-L257
def sparse_cross_entropy(input_, labels, name=PROVIDED, loss_weight=None, per_example_weights=None): """Calculates the Cross Entropy of input_ vs labels. Args: input_: A rank 2 `Tensor` or a Pretty Tensor holdin...
[ "def", "sparse_cross_entropy", "(", "input_", ",", "labels", ",", "name", "=", "PROVIDED", ",", "loss_weight", "=", "None", ",", "per_example_weights", "=", "None", ")", ":", "if", "labels", "is", "None", ":", "raise", "ValueError", "(", "'Labels must be set'"...
Calculates the Cross Entropy of input_ vs labels. Args: input_: A rank 2 `Tensor` or a Pretty Tensor holding the logits. labels: A rank 1 integer `Tensor` with class ordinals name: The optional name. loss_weight: A weight to scale the loss. Used when there are multiple losses. per_example_w...
[ "Calculates", "the", "Cross", "Entropy", "of", "input_", "vs", "labels", "." ]
python
train
couchbase/couchbase-python-client
couchbase/bucket.py
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2406-L2429
def queue_pop(self, key, **kwargs): """ Remove and return the first item queue. :param key: The document ID :param kwargs: Arguments passed to :meth:`mutate_in` :return: A :class:`ValueResult` :raise: :cb_exc:`QueueEmpty` if there are no items in the queue. :rais...
[ "def", "queue_pop", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "while", "True", ":", "try", ":", "itm", "=", "self", ".", "list_get", "(", "key", ",", "-", "1", ")", "except", "IndexError", ":", "raise", "E", ".", "QueueEmpty", "...
Remove and return the first item queue. :param key: The document ID :param kwargs: Arguments passed to :meth:`mutate_in` :return: A :class:`ValueResult` :raise: :cb_exc:`QueueEmpty` if there are no items in the queue. :raise: :cb_exc:`NotFoundError` if the queue does not exist.
[ "Remove", "and", "return", "the", "first", "item", "queue", "." ]
python
train
OnroerendErfgoed/pyramid_urireferencer
pyramid_urireferencer/__init__.py
https://github.com/OnroerendErfgoed/pyramid_urireferencer/blob/c6ee4ba863e32ced304b9cf00f3f5b450757a29a/pyramid_urireferencer/__init__.py#L26-L37
def _add_referencer(registry): """ Gets the Referencer from config and adds it to the registry. """ referencer = registry.queryUtility(IReferencer) if referencer is not None: return referencer ref = registry.settings['urireferencer.referencer'] url = registry.settings['urireferencer....
[ "def", "_add_referencer", "(", "registry", ")", ":", "referencer", "=", "registry", ".", "queryUtility", "(", "IReferencer", ")", "if", "referencer", "is", "not", "None", ":", "return", "referencer", "ref", "=", "registry", ".", "settings", "[", "'urireference...
Gets the Referencer from config and adds it to the registry.
[ "Gets", "the", "Referencer", "from", "config", "and", "adds", "it", "to", "the", "registry", "." ]
python
train
pybel/pybel
src/pybel/struct/filters/node_predicates.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicates.py#L45-L63
def node_predicate(f: Callable[[BaseEntity], bool]) -> NodePredicate: # noqa: D202 """Tag a node predicate that takes a dictionary to also accept a pair of (BELGraph, node). Apply this as a decorator to a function that takes a single argument, a PyBEL node, to make sure that it can also accept a pair of a...
[ "def", "node_predicate", "(", "f", ":", "Callable", "[", "[", "BaseEntity", "]", ",", "bool", "]", ")", "->", "NodePredicate", ":", "# noqa: D202", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "*", "args", ")", ":", "x", "=", "args", "[", "0...
Tag a node predicate that takes a dictionary to also accept a pair of (BELGraph, node). Apply this as a decorator to a function that takes a single argument, a PyBEL node, to make sure that it can also accept a pair of arguments, a BELGraph and a PyBEL node as well.
[ "Tag", "a", "node", "predicate", "that", "takes", "a", "dictionary", "to", "also", "accept", "a", "pair", "of", "(", "BELGraph", "node", ")", "." ]
python
train
sosy-lab/benchexec
benchexec/util.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/util.py#L371-L376
def copy_all_lines_from_to(inputFile, outputFile): """Copy all lines from an input file object to an output file object.""" currentLine = inputFile.readline() while currentLine: outputFile.write(currentLine) currentLine = inputFile.readline()
[ "def", "copy_all_lines_from_to", "(", "inputFile", ",", "outputFile", ")", ":", "currentLine", "=", "inputFile", ".", "readline", "(", ")", "while", "currentLine", ":", "outputFile", ".", "write", "(", "currentLine", ")", "currentLine", "=", "inputFile", ".", ...
Copy all lines from an input file object to an output file object.
[ "Copy", "all", "lines", "from", "an", "input", "file", "object", "to", "an", "output", "file", "object", "." ]
python
train
sprockets/sprockets-influxdb
sprockets_influxdb.py
https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L235-L331
def install(url=None, auth_username=None, auth_password=None, submission_interval=None, max_batch_size=None, max_clients=10, base_tags=None, max_buffer_size=None, trigger_size=None, sample_probability=1.0): """Call this to install/setup the InfluxDB client collector. All argument...
[ "def", "install", "(", "url", "=", "None", ",", "auth_username", "=", "None", ",", "auth_password", "=", "None", ",", "submission_interval", "=", "None", ",", "max_batch_size", "=", "None", ",", "max_clients", "=", "10", ",", "base_tags", "=", "None", ",",...
Call this to install/setup the InfluxDB client collector. All arguments are optional. :param str url: The InfluxDB API URL. If URL is not specified, the ``INFLUXDB_SCHEME``, ``INFLUXDB_HOST`` and ``INFLUXDB_PORT`` environment variables will be used to construct the base URL. Default: ``...
[ "Call", "this", "to", "install", "/", "setup", "the", "InfluxDB", "client", "collector", ".", "All", "arguments", "are", "optional", "." ]
python
train
dpkp/kafka-python
kafka/admin/client.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/admin/client.py#L589-L644
def describe_consumer_groups(self, group_ids, group_coordinator_id=None): """Describe a set of consumer groups. Any errors are immediately raised. :param group_ids: A list of consumer group IDs. These are typically the group names as strings. :param group_coordinator_id: Th...
[ "def", "describe_consumer_groups", "(", "self", ",", "group_ids", ",", "group_coordinator_id", "=", "None", ")", ":", "group_descriptions", "=", "[", "]", "version", "=", "self", ".", "_matching_api_version", "(", "DescribeGroupsRequest", ")", "for", "group_id", "...
Describe a set of consumer groups. Any errors are immediately raised. :param group_ids: A list of consumer group IDs. These are typically the group names as strings. :param group_coordinator_id: The node_id of the groups' coordinator broker. If set to None, it will quer...
[ "Describe", "a", "set", "of", "consumer", "groups", "." ]
python
train
bitlabstudio/django-dashboard-app
dashboard_app/widget_pool.py
https://github.com/bitlabstudio/django-dashboard-app/blob/ed98f2bca91a4ced36d0dd1aa1baee78e989cf64/dashboard_app/widget_pool.py#L93-L96
def unregister_widget(self, widget_cls): """Unregisters the given widget.""" if widget_cls.__name__ in self.widgets: del self.widgets[widget_cls().get_name()]
[ "def", "unregister_widget", "(", "self", ",", "widget_cls", ")", ":", "if", "widget_cls", ".", "__name__", "in", "self", ".", "widgets", ":", "del", "self", ".", "widgets", "[", "widget_cls", "(", ")", ".", "get_name", "(", ")", "]" ]
Unregisters the given widget.
[ "Unregisters", "the", "given", "widget", "." ]
python
test
blockstack/virtualchain
virtualchain/lib/blockchain/bitcoin_blockchain/keys.py
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/bitcoin_blockchain/keys.py#L161-L215
def btc_script_deserialize(script): """ Given a script (hex or bin), decode it into its list of opcodes and data. Return a list of strings and ints. Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin """ if isinstance(script, str) and re.match('...
[ "def", "btc_script_deserialize", "(", "script", ")", ":", "if", "isinstance", "(", "script", ",", "str", ")", "and", "re", ".", "match", "(", "'^[0-9a-fA-F]*$'", ",", "script", ")", ":", "script", "=", "binascii", ".", "unhexlify", "(", "script", ")", "#...
Given a script (hex or bin), decode it into its list of opcodes and data. Return a list of strings and ints. Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
[ "Given", "a", "script", "(", "hex", "or", "bin", ")", "decode", "it", "into", "its", "list", "of", "opcodes", "and", "data", ".", "Return", "a", "list", "of", "strings", "and", "ints", "." ]
python
train
waqasbhatti/astrobase
astrobase/astrokep.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L2085-L2130
def _legendre_dtr(x, y, y_err, legendredeg=10): '''This calculates the residual and chi-sq values for a Legendre function fit. Parameters ---------- x : np.array Array of the independent variable. y : np.array Array of the dependent variable. y_err : np.array Arra...
[ "def", "_legendre_dtr", "(", "x", ",", "y", ",", "y_err", ",", "legendredeg", "=", "10", ")", ":", "try", ":", "p", "=", "Legendre", ".", "fit", "(", "x", ",", "y", ",", "legendredeg", ")", "fit_y", "=", "p", "(", "x", ")", "except", "Exception",...
This calculates the residual and chi-sq values for a Legendre function fit. Parameters ---------- x : np.array Array of the independent variable. y : np.array Array of the dependent variable. y_err : np.array Array of errors associated with each `y` value. Used to cal...
[ "This", "calculates", "the", "residual", "and", "chi", "-", "sq", "values", "for", "a", "Legendre", "function", "fit", "." ]
python
valid
frascoweb/frasco
frasco/views.py
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L28-L40
def exec_after_request_actions(actions, response, **kwargs): """Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context. """ current_context["response"] = response groups = ("after_" + flask.request.method.lower(), "after") try: ...
[ "def", "exec_after_request_actions", "(", "actions", ",", "response", ",", "*", "*", "kwargs", ")", ":", "current_context", "[", "\"response\"", "]", "=", "response", "groups", "=", "(", "\"after_\"", "+", "flask", ".", "request", ".", "method", ".", "lower"...
Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context.
[ "Executes", "actions", "of", "the", "after", "and", "after_METHOD", "groups", ".", "A", "response", "var", "will", "be", "injected", "in", "the", "current", "context", "." ]
python
train
awacha/sastool
sastool/misc/easylsq.py
https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/misc/easylsq.py#L217-L319
def nlsq_fit(x, y, dy, func, params_init, verbose=False, **kwargs): """Perform a non-linear least squares fit Inputs: x: one-dimensional numpy array of the independent variable y: one-dimensional numpy array of the dependent variable dy: absolute error (square root of the variance) of t...
[ "def", "nlsq_fit", "(", "x", ",", "y", ",", "dy", ",", "func", ",", "params_init", ",", "verbose", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "verbose", ":", "t0", "=", "time", ".", "monotonic", "(", ")", "print", "(", "\"nlsq_fit start...
Perform a non-linear least squares fit Inputs: x: one-dimensional numpy array of the independent variable y: one-dimensional numpy array of the dependent variable dy: absolute error (square root of the variance) of the dependent variable. Either a one-dimensional numpy array or ...
[ "Perform", "a", "non", "-", "linear", "least", "squares", "fit" ]
python
train
saltstack/salt
salt/utils/openstack/neutron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/neutron.py#L680-L686
def delete_vpnservice(self, vpnservice): ''' Deletes the specified VPN service ''' vpnservice_id = self._find_vpnservice_id(vpnservice) ret = self.network_conn.delete_vpnservice(vpnservice_id) return ret if ret else True
[ "def", "delete_vpnservice", "(", "self", ",", "vpnservice", ")", ":", "vpnservice_id", "=", "self", ".", "_find_vpnservice_id", "(", "vpnservice", ")", "ret", "=", "self", ".", "network_conn", ".", "delete_vpnservice", "(", "vpnservice_id", ")", "return", "ret",...
Deletes the specified VPN service
[ "Deletes", "the", "specified", "VPN", "service" ]
python
train
NarrativeScience/lsi
src/lsi/utils/hosts.py
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L481-L492
def _is_valid_cache(): """ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` """ if not os.path.exists(get_cache_location()): return False modified = os.path.getmtime(get_cache_location()) modified = tim...
[ "def", "_is_valid_cache", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "get_cache_location", "(", ")", ")", ":", "return", "False", "modified", "=", "os", ".", "path", ".", "getmtime", "(", "get_cache_location", "(", ")", ")", "mo...
Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool``
[ "Returns", "if", "the", "cache", "is", "valid", "(", "exists", "and", "modified", "within", "the", "interval", ")", ".", ":", "return", ":", "Whether", "the", "cache", "is", "valid", ".", ":", "rtype", ":", "bool" ]
python
test
amzn/ion-python
amazon/ion/writer_buffer.py
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L122-L129
def add_scalar_value(self, value_buf): """Add a node to the tree containing a scalar value. Args: value_buf (bytearray): bytearray containing the scalar value. """ self.__container_node.add_child(_Node(value_buf)) self.current_container_length += len(value_buf)
[ "def", "add_scalar_value", "(", "self", ",", "value_buf", ")", ":", "self", ".", "__container_node", ".", "add_child", "(", "_Node", "(", "value_buf", ")", ")", "self", ".", "current_container_length", "+=", "len", "(", "value_buf", ")" ]
Add a node to the tree containing a scalar value. Args: value_buf (bytearray): bytearray containing the scalar value.
[ "Add", "a", "node", "to", "the", "tree", "containing", "a", "scalar", "value", "." ]
python
train
nutechsoftware/alarmdecoder
alarmdecoder/devices/usb_device.py
https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/devices/usb_device.py#L324-L339
def write(self, data): """ Writes data to the device. :param data: data to write :type data: string :raises: :py:class:`~alarmdecoder.util.CommError` """ try: self._device.write_data(data) self.on_write(data=data) except FtdiErr...
[ "def", "write", "(", "self", ",", "data", ")", ":", "try", ":", "self", ".", "_device", ".", "write_data", "(", "data", ")", "self", ".", "on_write", "(", "data", "=", "data", ")", "except", "FtdiError", "as", "err", ":", "raise", "CommError", "(", ...
Writes data to the device. :param data: data to write :type data: string :raises: :py:class:`~alarmdecoder.util.CommError`
[ "Writes", "data", "to", "the", "device", "." ]
python
train
juicer/juicer
juicer/admin/JuicerAdmin.py
https://github.com/juicer/juicer/blob/0c9f0fd59e293d45df6b46e81f675d33221c600d/juicer/admin/JuicerAdmin.py#L439-L461
def sync_repo(self, repo_name=None, envs=[], query='/repositories/'): """ Sync repository in specified environments """ juicer.utils.Log.log_debug( "Sync Repo %s In: %s" % (repo_name, ",".join(envs))) data = { 'override_config': { 'verify_...
[ "def", "sync_repo", "(", "self", ",", "repo_name", "=", "None", ",", "envs", "=", "[", "]", ",", "query", "=", "'/repositories/'", ")", ":", "juicer", ".", "utils", ".", "Log", ".", "log_debug", "(", "\"Sync Repo %s In: %s\"", "%", "(", "repo_name", ",",...
Sync repository in specified environments
[ "Sync", "repository", "in", "specified", "environments" ]
python
train
niklasf/python-chess
chess/pgn.py
https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L432-L439
def board(self, *, _cache: bool = False) -> chess.Board: """ Gets the starting position of the game. Unless the ``FEN`` header tag is set, this is the default starting position (for the ``Variant``). """ return self.headers.board()
[ "def", "board", "(", "self", ",", "*", ",", "_cache", ":", "bool", "=", "False", ")", "->", "chess", ".", "Board", ":", "return", "self", ".", "headers", ".", "board", "(", ")" ]
Gets the starting position of the game. Unless the ``FEN`` header tag is set, this is the default starting position (for the ``Variant``).
[ "Gets", "the", "starting", "position", "of", "the", "game", "." ]
python
train
zarr-developers/zarr
zarr/core.py
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1635-L1659
def _chunk_setitem(self, chunk_coords, chunk_selection, value, fields=None): """Replace part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : tuple of slices Location of region within the chun...
[ "def", "_chunk_setitem", "(", "self", ",", "chunk_coords", ",", "chunk_selection", ",", "value", ",", "fields", "=", "None", ")", ":", "if", "self", ".", "_synchronizer", "is", "None", ":", "# no synchronization", "lock", "=", "nolock", "else", ":", "# synch...
Replace part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : tuple of slices Location of region within the chunk. value : scalar or ndarray Value to set.
[ "Replace", "part", "or", "whole", "of", "a", "chunk", "." ]
python
train
saltstack/salt
salt/cloud/clouds/digitalocean.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1051-L1090
def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='12...
[ "def", "create_floating_ip", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "log", ".", "error", "(", "'The create_floating_ip function must be called with -f or --function.'", ")", "return", "False", "if", "...
Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
[ "Create", "a", "new", "floating", "IP" ]
python
train
fishtown-analytics/dbt
core/dbt/task/runnable.py
https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/core/dbt/task/runnable.py#L268-L287
def run(self): """ Run dbt for the query, based on the graph. """ self._runtime_initialize() if len(self._flattened_nodes) == 0: logger.warning("WARNING: Nothing to do. Try checking your model " "configs and model specification args") ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_runtime_initialize", "(", ")", "if", "len", "(", "self", ".", "_flattened_nodes", ")", "==", "0", ":", "logger", ".", "warning", "(", "\"WARNING: Nothing to do. Try checking your model \"", "\"configs and model s...
Run dbt for the query, based on the graph.
[ "Run", "dbt", "for", "the", "query", "based", "on", "the", "graph", "." ]
python
train
escaped/django-video-encoding
video_encoding/tasks.py
https://github.com/escaped/django-video-encoding/blob/50d228dd91aca40acc7f9293808b1e87cb645e5d/video_encoding/tasks.py#L36-L90
def convert_video(fieldfile, force=False): """ Converts a given video file into all defined formats. """ instance = fieldfile.instance field = fieldfile.field filename = os.path.basename(fieldfile.path) source_path = fieldfile.path encoding_backend = get_backend() for options in s...
[ "def", "convert_video", "(", "fieldfile", ",", "force", "=", "False", ")", ":", "instance", "=", "fieldfile", ".", "instance", "field", "=", "fieldfile", ".", "field", "filename", "=", "os", ".", "path", ".", "basename", "(", "fieldfile", ".", "path", ")...
Converts a given video file into all defined formats.
[ "Converts", "a", "given", "video", "file", "into", "all", "defined", "formats", "." ]
python
train
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L14222-L14239
def get_hw_virt_ex_property(self, property_p): """Returns the value of the specified hardware virtualization boolean property. in property_p of type :class:`HWVirtExPropertyType` Property type to query. return value of type bool Property value. raises :class:`O...
[ "def", "get_hw_virt_ex_property", "(", "self", ",", "property_p", ")", ":", "if", "not", "isinstance", "(", "property_p", ",", "HWVirtExPropertyType", ")", ":", "raise", "TypeError", "(", "\"property_p can only be an instance of type HWVirtExPropertyType\"", ")", "value",...
Returns the value of the specified hardware virtualization boolean property. in property_p of type :class:`HWVirtExPropertyType` Property type to query. return value of type bool Property value. raises :class:`OleErrorInvalidarg` Invalid property.
[ "Returns", "the", "value", "of", "the", "specified", "hardware", "virtualization", "boolean", "property", "." ]
python
train
ray-project/ray
python/ray/experimental/features.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/features.py#L155-L169
def flush_finished_tasks_unsafe(): """This removes some critical state from the Redis shards. In a multitenant environment, this will flush metadata for all jobs, which may be undesirable. This removes all of the metadata for finished tasks. This can be used to try to address out-of-memory errors ...
[ "def", "flush_finished_tasks_unsafe", "(", ")", ":", "ray", ".", "worker", ".", "global_worker", ".", "check_connected", "(", ")", "for", "shard_index", "in", "range", "(", "len", "(", "ray", ".", "global_state", ".", "redis_clients", ")", ")", ":", "_flush_...
This removes some critical state from the Redis shards. In a multitenant environment, this will flush metadata for all jobs, which may be undesirable. This removes all of the metadata for finished tasks. This can be used to try to address out-of-memory errors caused by the accumulation of metadata ...
[ "This", "removes", "some", "critical", "state", "from", "the", "Redis", "shards", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L8421-L8429
def serial_udb_extra_f15_send(self, sue_ID_VEHICLE_MODEL_NAME, sue_ID_VEHICLE_REGISTRATION, force_mavlink1=False): ''' Backwards compatible version of SERIAL_UDB_EXTRA F15 and F16: format sue_ID_VEHICLE_MODEL_NAME : Serial UDB Extra Model Name Of Vehicle (uint8_t)...
[ "def", "serial_udb_extra_f15_send", "(", "self", ",", "sue_ID_VEHICLE_MODEL_NAME", ",", "sue_ID_VEHICLE_REGISTRATION", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "serial_udb_extra_f15_encode", "(", "sue_ID_VEHICLE_MOD...
Backwards compatible version of SERIAL_UDB_EXTRA F15 and F16: format sue_ID_VEHICLE_MODEL_NAME : Serial UDB Extra Model Name Of Vehicle (uint8_t) sue_ID_VEHICLE_REGISTRATION : Serial UDB Extra Registraton Number of Vehicle (uint8_t)
[ "Backwards", "compatible", "version", "of", "SERIAL_UDB_EXTRA", "F15", "and", "F16", ":", "format" ]
python
train
Opentrons/opentrons
api/src/opentrons/system/nmcli.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L570-L592
async def _call(cmd: List[str]) -> Tuple[str, str]: """ Runs the command in a subprocess and returns the captured stdout output. :param cmd: a list of arguments to nmcli. Should not include nmcli itself. :return: (stdout, stderr) """ to_exec = [quote(c) for c in ['nmcli'] + cmd] cmd_str = '...
[ "async", "def", "_call", "(", "cmd", ":", "List", "[", "str", "]", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "to_exec", "=", "[", "quote", "(", "c", ")", "for", "c", "in", "[", "'nmcli'", "]", "+", "cmd", "]", "cmd_str", "=", "' '...
Runs the command in a subprocess and returns the captured stdout output. :param cmd: a list of arguments to nmcli. Should not include nmcli itself. :return: (stdout, stderr)
[ "Runs", "the", "command", "in", "a", "subprocess", "and", "returns", "the", "captured", "stdout", "output", ".", ":", "param", "cmd", ":", "a", "list", "of", "arguments", "to", "nmcli", ".", "Should", "not", "include", "nmcli", "itself", "." ]
python
train
chrisrink10/basilisp
src/basilisp/lang/runtime.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L910-L917
def partial(f, *args): """Return a function which is the partial application of f with args.""" @functools.wraps(f) def partial_f(*inner_args): return f(*itertools.chain(args, inner_args)) return partial_f
[ "def", "partial", "(", "f", ",", "*", "args", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "partial_f", "(", "*", "inner_args", ")", ":", "return", "f", "(", "*", "itertools", ".", "chain", "(", "args", ",", "inner_args", ")", ...
Return a function which is the partial application of f with args.
[ "Return", "a", "function", "which", "is", "the", "partial", "application", "of", "f", "with", "args", "." ]
python
test
ewels/MultiQC
multiqc/modules/slamdunk/slamdunk.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/slamdunk/slamdunk.py#L364-L433
def slamdunkFilterStatsTable(self): """ Take the parsed filter stats from Slamdunk and add it to a separate table """ headers = OrderedDict() headers['mapped'] = { 'namespace': 'Slamdunk', 'title': '{} Mapped'.format(config.read_count_prefix), 'description': ...
[ "def", "slamdunkFilterStatsTable", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'mapped'", "]", "=", "{", "'namespace'", ":", "'Slamdunk'", ",", "'title'", ":", "'{} Mapped'", ".", "format", "(", "config", ".", "read_count...
Take the parsed filter stats from Slamdunk and add it to a separate table
[ "Take", "the", "parsed", "filter", "stats", "from", "Slamdunk", "and", "add", "it", "to", "a", "separate", "table" ]
python
train
wummel/linkchecker
linkcheck/HtmlParser/htmllib.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/HtmlParser/htmllib.py#L137-L146
def end_element (self, tag): """ Print HTML end element. @param tag: tag name @type tag: string @return: None """ tag = tag.encode(self.encoding, "ignore") self.fd.write("</%s>" % tag)
[ "def", "end_element", "(", "self", ",", "tag", ")", ":", "tag", "=", "tag", ".", "encode", "(", "self", ".", "encoding", ",", "\"ignore\"", ")", "self", ".", "fd", ".", "write", "(", "\"</%s>\"", "%", "tag", ")" ]
Print HTML end element. @param tag: tag name @type tag: string @return: None
[ "Print", "HTML", "end", "element", "." ]
python
train
AustralianSynchrotron/lightflow
lightflow/models/task.py
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task.py#L208-L295
def _run(self, data, store, signal, context, *, success_callback=None, stop_callback=None, abort_callback=None): """ The internal run method that decorates the public run method. This method makes sure data is being passed to and from the task. Args: data (MultiTaskDat...
[ "def", "_run", "(", "self", ",", "data", ",", "store", ",", "signal", ",", "context", ",", "*", ",", "success_callback", "=", "None", ",", "stop_callback", "=", "None", ",", "abort_callback", "=", "None", ")", ":", "if", "data", "is", "None", ":", "d...
The internal run method that decorates the public run method. This method makes sure data is being passed to and from the task. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. store (DataStoreDocument...
[ "The", "internal", "run", "method", "that", "decorates", "the", "public", "run", "method", "." ]
python
train
praekeltfoundation/seed-stage-based-messaging
subscriptions/management/commands/remove_duplicate_subscriptions.py
https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/management/commands/remove_duplicate_subscriptions.py#L79-L84
def is_within_limits(self, limit, date, dates): """ Returns True if the difference between date and any value in dates is less than or equal to limit. """ return any((self.second_diff(date, d) <= limit for d in dates))
[ "def", "is_within_limits", "(", "self", ",", "limit", ",", "date", ",", "dates", ")", ":", "return", "any", "(", "(", "self", ".", "second_diff", "(", "date", ",", "d", ")", "<=", "limit", "for", "d", "in", "dates", ")", ")" ]
Returns True if the difference between date and any value in dates is less than or equal to limit.
[ "Returns", "True", "if", "the", "difference", "between", "date", "and", "any", "value", "in", "dates", "is", "less", "than", "or", "equal", "to", "limit", "." ]
python
train
sosreport/sos
sos/policies/__init__.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L873-L877
def lsmod(self): """Return a list of kernel module names as strings. """ lines = shell_out("lsmod", timeout=0).splitlines() return [line.split()[0].strip() for line in lines]
[ "def", "lsmod", "(", "self", ")", ":", "lines", "=", "shell_out", "(", "\"lsmod\"", ",", "timeout", "=", "0", ")", ".", "splitlines", "(", ")", "return", "[", "line", ".", "split", "(", ")", "[", "0", "]", ".", "strip", "(", ")", "for", "line", ...
Return a list of kernel module names as strings.
[ "Return", "a", "list", "of", "kernel", "module", "names", "as", "strings", "." ]
python
train
gwpy/gwpy
gwpy/table/filter.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/table/filter.py#L99-L171
def parse_column_filter(definition): """Parse a `str` of the form 'column>50' Parameters ---------- definition : `str` a column filter definition of the form ``<name><operator><threshold>`` or ``<threshold><operator><name><operator><threshold>``, e.g. ``frequency >= 10``, or ``5...
[ "def", "parse_column_filter", "(", "definition", ")", ":", "# noqa", "# parse definition into parts (skipping null tokens)", "parts", "=", "list", "(", "generate_tokens", "(", "StringIO", "(", "definition", ".", "strip", "(", ")", ")", ".", "readline", ")", ")", "...
Parse a `str` of the form 'column>50' Parameters ---------- definition : `str` a column filter definition of the form ``<name><operator><threshold>`` or ``<threshold><operator><name><operator><threshold>``, e.g. ``frequency >= 10``, or ``50 < snr < 100`` Returns ------- ...
[ "Parse", "a", "str", "of", "the", "form", "column", ">", "50" ]
python
train
jborean93/ntlm-auth
ntlm_auth/compute_hash.py
https://github.com/jborean93/ntlm-auth/blob/2c7cd81516d9bfd42e8ff473a534d876b21ebb38/ntlm_auth/compute_hash.py#L48-L67
def _ntowfv1(password): """ [MS-NLMP] v28.0 2016-07-14 3.3.1 NTLM v1 Authentication Same function as NTOWFv1 in document to create a one way hash of the password. Only used in NTLMv1 auth without session security :param password: The password or hash of the user we are trying to authen...
[ "def", "_ntowfv1", "(", "password", ")", ":", "# if the password is a hash, return the NT hash", "if", "re", ".", "match", "(", "r'^[a-fA-F\\d]{32}:[a-fA-F\\d]{32}$'", ",", "password", ")", ":", "nt_hash", "=", "binascii", ".", "unhexlify", "(", "password", ".", "sp...
[MS-NLMP] v28.0 2016-07-14 3.3.1 NTLM v1 Authentication Same function as NTOWFv1 in document to create a one way hash of the password. Only used in NTLMv1 auth without session security :param password: The password or hash of the user we are trying to authenticate with :return digest: An N...
[ "[", "MS", "-", "NLMP", "]", "v28", ".", "0", "2016", "-", "07", "-", "14" ]
python
train
willkg/markus
markus/main.py
https://github.com/willkg/markus/blob/0cfbe67fb7ccfa7488b0120d21ddc0cdc1f8ed33/markus/main.py#L396-L464
def get_metrics(thing, extra=''): """Return MetricsInterface instance with specified name. The name is used as the prefix for all keys generated with this :py:class:`markus.main.MetricsInterface`. The :py:class:`markus.main.MetricsInterface` is not tied to metrics backends. The list of active back...
[ "def", "get_metrics", "(", "thing", ",", "extra", "=", "''", ")", ":", "thing", "=", "thing", "or", "''", "if", "not", "isinstance", "(", "thing", ",", "str", ")", ":", "# If it's not a str, it's either a class or an instance. Handle", "# accordingly.", "if", "t...
Return MetricsInterface instance with specified name. The name is used as the prefix for all keys generated with this :py:class:`markus.main.MetricsInterface`. The :py:class:`markus.main.MetricsInterface` is not tied to metrics backends. The list of active backends are globally configured. This allows...
[ "Return", "MetricsInterface", "instance", "with", "specified", "name", "." ]
python
test
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/api/core_v1_api.py
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L3243-L3265
def connect_patch_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501 """connect_patch_namespaced_service_proxy # noqa: E501 connect PATCH requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HT...
[ "def", "connect_patch_namespaced_service_proxy", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":...
connect_patch_namespaced_service_proxy # noqa: E501 connect PATCH requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_patch_namespaced_service_proxy...
[ "connect_patch_namespaced_service_proxy", "#", "noqa", ":", "E501" ]
python
train