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
robinandeer/puzzle
puzzle/models/mixins.py
https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/models/mixins.py#L17-L25
def is_affected(self): """Boolean for telling if the sample is affected.""" phenotype = self.phenotype if phenotype == '1': return False elif phenotype == '2': return True else: return False
[ "def", "is_affected", "(", "self", ")", ":", "phenotype", "=", "self", ".", "phenotype", "if", "phenotype", "==", "'1'", ":", "return", "False", "elif", "phenotype", "==", "'2'", ":", "return", "True", "else", ":", "return", "False" ]
Boolean for telling if the sample is affected.
[ "Boolean", "for", "telling", "if", "the", "sample", "is", "affected", "." ]
python
train
allenai/allennlp
allennlp/data/dataset_readers/dataset_utils/span_utils.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_utils/span_utils.py#L376-L435
def bmes_tags_to_spans(tag_sequence: List[str], classes_to_ignore: List[str] = None) -> List[TypedStringSpan]: """ Given a sequence corresponding to BMES tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also...
[ "def", "bmes_tags_to_spans", "(", "tag_sequence", ":", "List", "[", "str", "]", ",", "classes_to_ignore", ":", "List", "[", "str", "]", "=", "None", ")", "->", "List", "[", "TypedStringSpan", "]", ":", "def", "extract_bmes_tag_label", "(", "text", ")", ":"...
Given a sequence corresponding to BMES tags, extracts spans. Spans are inclusive and can be of zero length, representing a single word span. Ill-formed spans are also included (i.e those which do not start with a "B-LABEL"), as otherwise it is possible to get a perfect precision score whilst still predictin...
[ "Given", "a", "sequence", "corresponding", "to", "BMES", "tags", "extracts", "spans", ".", "Spans", "are", "inclusive", "and", "can", "be", "of", "zero", "length", "representing", "a", "single", "word", "span", ".", "Ill", "-", "formed", "spans", "are", "a...
python
train
pschmitt/zhue
zhue/model/basemodel.py
https://github.com/pschmitt/zhue/blob/4a3f4ddf12ceeedcb2157f92d93ff1c6438a7d59/zhue/model/basemodel.py#L65-L75
def address(self): ''' Return the address of this "object", minus the scheme, hostname and port of the bridge ''' return self.API.replace( 'http://{}:{}'.format( self._bridge.hostname, self._bridge.port ), '' )
[ "def", "address", "(", "self", ")", ":", "return", "self", ".", "API", ".", "replace", "(", "'http://{}:{}'", ".", "format", "(", "self", ".", "_bridge", ".", "hostname", ",", "self", ".", "_bridge", ".", "port", ")", ",", "''", ")" ]
Return the address of this "object", minus the scheme, hostname and port of the bridge
[ "Return", "the", "address", "of", "this", "object", "minus", "the", "scheme", "hostname", "and", "port", "of", "the", "bridge" ]
python
train
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L94-L104
def body(self): """Returns the HTTP response body, deserialized if possible. :rtype: mixed """ if not self._responses: return None if self._responses[-1].code >= 400: return self._error_message() return self._deserialize()
[ "def", "body", "(", "self", ")", ":", "if", "not", "self", ".", "_responses", ":", "return", "None", "if", "self", ".", "_responses", "[", "-", "1", "]", ".", "code", ">=", "400", ":", "return", "self", ".", "_error_message", "(", ")", "return", "s...
Returns the HTTP response body, deserialized if possible. :rtype: mixed
[ "Returns", "the", "HTTP", "response", "body", "deserialized", "if", "possible", "." ]
python
train
Unity-Technologies/ml-agents
ml-agents/mlagents/trainers/trainer_controller.py
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/trainer_controller.py#L122-L169
def initialize_trainers(self, trainer_config: Dict[str, Dict[str, str]]): """ Initialization of the trainers :param trainer_config: The configurations of the trainers """ trainer_parameters_dict = {} for brain_name in self.external_brains: trainer_parameters =...
[ "def", "initialize_trainers", "(", "self", ",", "trainer_config", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "str", "]", "]", ")", ":", "trainer_parameters_dict", "=", "{", "}", "for", "brain_name", "in", "self", ".", "external_brains", ":", ...
Initialization of the trainers :param trainer_config: The configurations of the trainers
[ "Initialization", "of", "the", "trainers", ":", "param", "trainer_config", ":", "The", "configurations", "of", "the", "trainers" ]
python
train
kwikteam/phy
phy/electrode/mea.py
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/electrode/mea.py#L53-L57
def _probe_positions(probe, group): """Return the positions of a probe channel group.""" positions = probe['channel_groups'][group]['geometry'] channels = _probe_channels(probe, group) return np.array([positions[channel] for channel in channels])
[ "def", "_probe_positions", "(", "probe", ",", "group", ")", ":", "positions", "=", "probe", "[", "'channel_groups'", "]", "[", "group", "]", "[", "'geometry'", "]", "channels", "=", "_probe_channels", "(", "probe", ",", "group", ")", "return", "np", ".", ...
Return the positions of a probe channel group.
[ "Return", "the", "positions", "of", "a", "probe", "channel", "group", "." ]
python
train
markovmodel/PyEMMA
pyemma/_base/estimator.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/estimator.py#L194-L369
def estimate_param_scan(estimator, X, param_sets, evaluate=None, evaluate_args=None, failfast=True, return_estimators=False, n_jobs=1, progress_reporter=None, show_progress=True, return_exceptions=False): """ Runs multiple estimations using a list of parameter setting...
[ "def", "estimate_param_scan", "(", "estimator", ",", "X", ",", "param_sets", ",", "evaluate", "=", "None", ",", "evaluate_args", "=", "None", ",", "failfast", "=", "True", ",", "return_estimators", "=", "False", ",", "n_jobs", "=", "1", ",", "progress_report...
Runs multiple estimations using a list of parameter settings Parameters ---------- estimator : Estimator object or class An estimator object that provides an estimate(X, **params) function. If only a class is provided here, the Estimator objects will be constructed with default para...
[ "Runs", "multiple", "estimations", "using", "a", "list", "of", "parameter", "settings" ]
python
train
mila-iqia/fuel
fuel/transformers/__init__.py
https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/transformers/__init__.py#L34-L67
def verify_axis_labels(self, expected, actual, source_name): """Verify that axis labels for a given source are as expected. Parameters ---------- expected : tuple A tuple of strings representing the expected axis labels. actual : tuple or None A tuple of ...
[ "def", "verify_axis_labels", "(", "self", ",", "expected", ",", "actual", ",", "source_name", ")", ":", "if", "not", "getattr", "(", "self", ",", "'_checked_axis_labels'", ",", "False", ")", ":", "self", ".", "_checked_axis_labels", "=", "defaultdict", "(", ...
Verify that axis labels for a given source are as expected. Parameters ---------- expected : tuple A tuple of strings representing the expected axis labels. actual : tuple or None A tuple of strings representing the actual axis labels, or `None` if th...
[ "Verify", "that", "axis", "labels", "for", "a", "given", "source", "are", "as", "expected", "." ]
python
train
pip-services3-python/pip-services3-commons-python
pip_services3_commons/reflect/TypeReflector.py
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/TypeReflector.py#L125-L140
def is_primitive(value): """ Checks if value has primitive type. Primitive types are: numbers, strings, booleans, date and time. Complex (non-primitive types are): objects, maps and arrays :param value: a value to check :return: true if the value has primitive type and...
[ "def", "is_primitive", "(", "value", ")", ":", "typeCode", "=", "TypeConverter", ".", "to_type_code", "(", "value", ")", "return", "typeCode", "==", "TypeCode", ".", "String", "or", "typeCode", "==", "TypeCode", ".", "Enum", "or", "typeCode", "==", "TypeCode...
Checks if value has primitive type. Primitive types are: numbers, strings, booleans, date and time. Complex (non-primitive types are): objects, maps and arrays :param value: a value to check :return: true if the value has primitive type and false if value type is complex.
[ "Checks", "if", "value", "has", "primitive", "type", "." ]
python
train
PeerAssets/pypeerassets
pypeerassets/provider/cryptoid.py
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/cryptoid.py#L44-L52
def get_url(url: str) -> Union[dict, int, float, str]: '''Perform a GET request for the url and return a dictionary parsed from the JSON response.''' request = Request(url, headers={"User-Agent": "pypeerassets"}) response = cast(HTTPResponse, urlopen(request)) if response.status...
[ "def", "get_url", "(", "url", ":", "str", ")", "->", "Union", "[", "dict", ",", "int", ",", "float", ",", "str", "]", ":", "request", "=", "Request", "(", "url", ",", "headers", "=", "{", "\"User-Agent\"", ":", "\"pypeerassets\"", "}", ")", "response...
Perform a GET request for the url and return a dictionary parsed from the JSON response.
[ "Perform", "a", "GET", "request", "for", "the", "url", "and", "return", "a", "dictionary", "parsed", "from", "the", "JSON", "response", "." ]
python
train
benley/butcher
butcher/buildfile.py
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/buildfile.py#L122-L126
def local_targets(self): """Iterator over the targets defined in this build file.""" for node in self.node: if (node.repo, node.path) == (self.target.repo, self.target.path): yield node
[ "def", "local_targets", "(", "self", ")", ":", "for", "node", "in", "self", ".", "node", ":", "if", "(", "node", ".", "repo", ",", "node", ".", "path", ")", "==", "(", "self", ".", "target", ".", "repo", ",", "self", ".", "target", ".", "path", ...
Iterator over the targets defined in this build file.
[ "Iterator", "over", "the", "targets", "defined", "in", "this", "build", "file", "." ]
python
train
getfleety/coralillo
coralillo/core.py
https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L460-L482
def delete(self): ''' Deletes this model from the database, calling delete in each field to properly delete special cases ''' redis = type(self).get_redis() for fieldname, field in self.proxy: field.delete(redis) redis.delete(self.key()) redis.srem(type(self...
[ "def", "delete", "(", "self", ")", ":", "redis", "=", "type", "(", "self", ")", ".", "get_redis", "(", ")", "for", "fieldname", ",", "field", "in", "self", ".", "proxy", ":", "field", ".", "delete", "(", "redis", ")", "redis", ".", "delete", "(", ...
Deletes this model from the database, calling delete in each field to properly delete special cases
[ "Deletes", "this", "model", "from", "the", "database", "calling", "delete", "in", "each", "field", "to", "properly", "delete", "special", "cases" ]
python
train
saltstack/salt
salt/states/zenoss.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zenoss.py#L37-L92
def monitored(name, device_class=None, collector='localhost', prod_state=None): ''' Ensure a device is monitored. The 'name' given will be used for Zenoss device name and should be resolvable. .. code-block:: yaml enable_monitoring: zenoss.monitored: - name: web01.example.com...
[ "def", "monitored", "(", "name", ",", "device_class", "=", "None", ",", "collector", "=", "'localhost'", ",", "prod_state", "=", "None", ")", ":", "ret", "=", "{", "}", "ret", "[", "'name'", "]", "=", "name", "# If device is already monitored, return early", ...
Ensure a device is monitored. The 'name' given will be used for Zenoss device name and should be resolvable. .. code-block:: yaml enable_monitoring: zenoss.monitored: - name: web01.example.com - device_class: /Servers/Linux - collector: localhost -...
[ "Ensure", "a", "device", "is", "monitored", ".", "The", "name", "given", "will", "be", "used", "for", "Zenoss", "device", "name", "and", "should", "be", "resolvable", "." ]
python
train
programa-stic/barf-project
barf/barf.py
https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L382-L430
def emulate(self, context=None, start=None, end=None, arch_mode=None, hooks=None, max_instrs=None, print_asm=False): """Emulate native code. Args: context (dict): Processor context (register and/or memory). start (int): Start address. end (int): End address. ...
[ "def", "emulate", "(", "self", ",", "context", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "arch_mode", "=", "None", ",", "hooks", "=", "None", ",", "max_instrs", "=", "None", ",", "print_asm", "=", "False", ")", ":", "if"...
Emulate native code. Args: context (dict): Processor context (register and/or memory). start (int): Start address. end (int): End address. arch_mode (int): Architecture mode. hooks (dict): Hooks by address. max_instrs (int): Maximum number...
[ "Emulate", "native", "code", "." ]
python
train
F-Secure/see
see/environment.py
https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/environment.py#L77-L81
def allocate(self): """Builds the context and the Hooks.""" self.logger.debug("Allocating environment.") self._allocate() self.logger.debug("Environment successfully allocated.")
[ "def", "allocate", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Allocating environment.\"", ")", "self", ".", "_allocate", "(", ")", "self", ".", "logger", ".", "debug", "(", "\"Environment successfully allocated.\"", ")" ]
Builds the context and the Hooks.
[ "Builds", "the", "context", "and", "the", "Hooks", "." ]
python
train
zfrenchee/Axial
axial/axial.py
https://github.com/zfrenchee/Axial/blob/69672b4ce46518e0348dedb74a907cc73f71c0fe/axial/axial.py#L364-L425
def heatmap(genes_by_samples_matrix, sample_attributes, title='Axial Heatmap', scripts_mode="CDN", data_mode="directory", organism="human", separate_zscore_by=["system"], output_dir=".", filename="heatmap.html", version=this_version): """ Arguments: genes_by_samples_matrix (panda...
[ "def", "heatmap", "(", "genes_by_samples_matrix", ",", "sample_attributes", ",", "title", "=", "'Axial Heatmap'", ",", "scripts_mode", "=", "\"CDN\"", ",", "data_mode", "=", "\"directory\"", ",", "organism", "=", "\"human\"", ",", "separate_zscore_by", "=", "[", "...
Arguments: genes_by_samples_matrix (pandas.DataFrame): dataframe indexed by genes, columns are samples sample_attributes (pandas.DataFrame): dataframe indexed by samples, columns are sample attributes (e.g. classes) title (str): The title of the plot (to be embedded in the html). scripts...
[ "Arguments", ":", "genes_by_samples_matrix", "(", "pandas", ".", "DataFrame", ")", ":", "dataframe", "indexed", "by", "genes", "columns", "are", "samples", "sample_attributes", "(", "pandas", ".", "DataFrame", ")", ":", "dataframe", "indexed", "by", "samples", "...
python
valid
lsbardel/python-stdnet
stdnet/odm/query.py
https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/query.py#L575-L583
def dont_load(self, *fields): '''Works like :meth:`load_only` to provides a :ref:`performance boost <increase-performance>` in cases when you need to load all fields except a subset specified by *fields*. ''' q = self._clone() fs = unique_tuple(q.exclude_fields, fields) q.exclude_...
[ "def", "dont_load", "(", "self", ",", "*", "fields", ")", ":", "q", "=", "self", ".", "_clone", "(", ")", "fs", "=", "unique_tuple", "(", "q", ".", "exclude_fields", ",", "fields", ")", "q", ".", "exclude_fields", "=", "fs", "if", "fs", "else", "No...
Works like :meth:`load_only` to provides a :ref:`performance boost <increase-performance>` in cases when you need to load all fields except a subset specified by *fields*.
[ "Works", "like", ":", "meth", ":", "load_only", "to", "provides", "a", ":", "ref", ":", "performance", "boost", "<increase", "-", "performance", ">", "in", "cases", "when", "you", "need", "to", "load", "all", "fields", "except", "a", "subset", "specified",...
python
train
Jaymon/captain
captain/parse.py
https://github.com/Jaymon/captain/blob/4297f32961d423a10d0f053bc252e29fbe939a47/captain/parse.py#L382-L401
def _fill_text(self, text, width, indent): """Overridden to not get rid of newlines https://github.com/python/cpython/blob/2.7/Lib/argparse.py#L620""" lines = [] for line in text.splitlines(False): if line: # https://docs.python.org/2/library/textwrap.html ...
[ "def", "_fill_text", "(", "self", ",", "text", ",", "width", ",", "indent", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "text", ".", "splitlines", "(", "False", ")", ":", "if", "line", ":", "# https://docs.python.org/2/library/textwrap.html", "l...
Overridden to not get rid of newlines https://github.com/python/cpython/blob/2.7/Lib/argparse.py#L620
[ "Overridden", "to", "not", "get", "rid", "of", "newlines" ]
python
valid
timkpaine/pyEX
pyEX/stocks.py
https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L1280-L1300
def ohlcDF(symbol, token='', version=''): '''Returns the official open and close for a give symbol. https://iexcloud.io/docs/api/#news 9:30am-5pm ET Mon-Fri Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: ...
[ "def", "ohlcDF", "(", "symbol", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "o", "=", "ohlc", "(", "symbol", ",", "token", ",", "version", ")", "if", "o", ":", "df", "=", "pd", ".", "io", ".", "json", ".", "json_normalize", "(...
Returns the official open and close for a give symbol. https://iexcloud.io/docs/api/#news 9:30am-5pm ET Mon-Fri Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: DataFrame: result
[ "Returns", "the", "official", "open", "and", "close", "for", "a", "give", "symbol", "." ]
python
valid
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/ce933ccc4ca8e0d3718f271c59bd530a4518bf63/grip/app.py#L375-L385
def render(self, route=None): """ Renders the application and returns the HTML unicode that would normally appear when visiting in the browser. """ if route is None: route = '/' with self.test_client() as c: response = c.get(route, follow_redirects...
[ "def", "render", "(", "self", ",", "route", "=", "None", ")", ":", "if", "route", "is", "None", ":", "route", "=", "'/'", "with", "self", ".", "test_client", "(", ")", "as", "c", ":", "response", "=", "c", ".", "get", "(", "route", ",", "follow_r...
Renders the application and returns the HTML unicode that would normally appear when visiting in the browser.
[ "Renders", "the", "application", "and", "returns", "the", "HTML", "unicode", "that", "would", "normally", "appear", "when", "visiting", "in", "the", "browser", "." ]
python
train
jamieleshaw/lurklib
lurklib/core.py
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/core.py#L83-L101
def find(self, haystack, needle): """ Finds needle in haystack. If needle is found return True, if not return False. Required arguments: * haystack - Text to search in. * needle - Text to search for. """ try: qstatus = haystack.find(needle) ...
[ "def", "find", "(", "self", ",", "haystack", ",", "needle", ")", ":", "try", ":", "qstatus", "=", "haystack", ".", "find", "(", "needle", ")", "except", "AttributeError", ":", "if", "needle", "in", "haystack", ":", "return", "True", "else", ":", "retur...
Finds needle in haystack. If needle is found return True, if not return False. Required arguments: * haystack - Text to search in. * needle - Text to search for.
[ "Finds", "needle", "in", "haystack", ".", "If", "needle", "is", "found", "return", "True", "if", "not", "return", "False", ".", "Required", "arguments", ":", "*", "haystack", "-", "Text", "to", "search", "in", ".", "*", "needle", "-", "Text", "to", "se...
python
train
djgagne/hagelslag
hagelslag/processing/EnsembleProducts.py
https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/processing/EnsembleProducts.py#L460-L485
def point_consensus(self, consensus_type): """ Calculate grid-point statistics across ensemble members. Args: consensus_type: mean, std, median, max, or percentile_nn Returns: EnsembleConsensus containing point statistic """ if "mean" in consensu...
[ "def", "point_consensus", "(", "self", ",", "consensus_type", ")", ":", "if", "\"mean\"", "in", "consensus_type", ":", "consensus_data", "=", "np", ".", "mean", "(", "self", ".", "data", ",", "axis", "=", "0", ")", "elif", "\"std\"", "in", "consensus_type"...
Calculate grid-point statistics across ensemble members. Args: consensus_type: mean, std, median, max, or percentile_nn Returns: EnsembleConsensus containing point statistic
[ "Calculate", "grid", "-", "point", "statistics", "across", "ensemble", "members", "." ]
python
train
manns/pyspread
pyspread/src/actions/_main_window_actions.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_main_window_actions.py#L243-L253
def get_print_rect(self, grid_rect): """Returns wx.Rect that is correctly positioned on the print canvas""" grid = self.grid rect_x = grid_rect.x - \ grid.GetScrollPos(wx.HORIZONTAL) * grid.GetScrollLineX() rect_y = grid_rect.y - \ grid.GetScrollPos(wx.VERTICAL)...
[ "def", "get_print_rect", "(", "self", ",", "grid_rect", ")", ":", "grid", "=", "self", ".", "grid", "rect_x", "=", "grid_rect", ".", "x", "-", "grid", ".", "GetScrollPos", "(", "wx", ".", "HORIZONTAL", ")", "*", "grid", ".", "GetScrollLineX", "(", ")",...
Returns wx.Rect that is correctly positioned on the print canvas
[ "Returns", "wx", ".", "Rect", "that", "is", "correctly", "positioned", "on", "the", "print", "canvas" ]
python
train
jssimporter/python-jss
jss/jssobject.py
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobject.py#L547-L561
def as_list_data(self): """Return an Element to be used in a list. Most lists want an element with tag of list_type, and subelements of id and name. Returns: Element: list representation of object. """ element = ElementTree.Element(self.list_type) id...
[ "def", "as_list_data", "(", "self", ")", ":", "element", "=", "ElementTree", ".", "Element", "(", "self", ".", "list_type", ")", "id_", "=", "ElementTree", ".", "SubElement", "(", "element", ",", "\"id\"", ")", "id_", ".", "text", "=", "self", ".", "id...
Return an Element to be used in a list. Most lists want an element with tag of list_type, and subelements of id and name. Returns: Element: list representation of object.
[ "Return", "an", "Element", "to", "be", "used", "in", "a", "list", "." ]
python
train
stefankoegl/kdtree
kdtree.py
https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L103-L123
def children(self): """ Returns an iterator for the non-empty children of the Node The children are returned as (Node, pos) tuples where pos is 0 for the left subnode and 1 for the right. >>> len(list(create(dimensions=2).children)) 0 >>> len(list(create([ (1, ...
[ "def", "children", "(", "self", ")", ":", "if", "self", ".", "left", "and", "self", ".", "left", ".", "data", "is", "not", "None", ":", "yield", "self", ".", "left", ",", "0", "if", "self", ".", "right", "and", "self", ".", "right", ".", "data", ...
Returns an iterator for the non-empty children of the Node The children are returned as (Node, pos) tuples where pos is 0 for the left subnode and 1 for the right. >>> len(list(create(dimensions=2).children)) 0 >>> len(list(create([ (1, 2) ]).children)) 0 >>> ...
[ "Returns", "an", "iterator", "for", "the", "non", "-", "empty", "children", "of", "the", "Node" ]
python
train
google/grumpy
third_party/pythonparser/parser.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L1004-L1007
def import_name(self, import_loc, names): """import_name: 'import' dotted_as_names""" return ast.Import(names=names, keyword_loc=import_loc, loc=import_loc.join(names[-1].loc))
[ "def", "import_name", "(", "self", ",", "import_loc", ",", "names", ")", ":", "return", "ast", ".", "Import", "(", "names", "=", "names", ",", "keyword_loc", "=", "import_loc", ",", "loc", "=", "import_loc", ".", "join", "(", "names", "[", "-", "1", ...
import_name: 'import' dotted_as_names
[ "import_name", ":", "import", "dotted_as_names" ]
python
valid
Othernet-Project/squery-pg
squery_pg/squery_pg.py
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/squery_pg.py#L68-L80
def serialize_query(func): """ Ensure any SQLExpression instances are serialized""" @functools.wraps(func) def wrapper(self, query, *args, **kwargs): if hasattr(query, 'serialize'): query = query.serialize() assert isinstance(query, basestring), 'Expected...
[ "def", "serialize_query", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "query", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "query", ",", "'serialize'", ...
Ensure any SQLExpression instances are serialized
[ "Ensure", "any", "SQLExpression", "instances", "are", "serialized" ]
python
train
tarzanjw/python-mysql-binlog-to-blinker
mysqlbinlog2blinker/__init__.py
https://github.com/tarzanjw/python-mysql-binlog-to-blinker/blob/d61ab5962345377e142a225b16f731ab4196fc26/mysqlbinlog2blinker/__init__.py#L56-L90
def start_replication(mysql_settings, binlog_pos_memory=(None, 2), **kwargs): """ Start replication on server specified by *mysql_settings* Args: mysql_settings (dict): mysql settings that is used to connect to mysql via pymys...
[ "def", "start_replication", "(", "mysql_settings", ",", "binlog_pos_memory", "=", "(", "None", ",", "2", ")", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "binlog_pos_memory", ",", "_bpm", ".", "BaseBinlogPosMemory", ")", ":", "if", "...
Start replication on server specified by *mysql_settings* Args: mysql_settings (dict): mysql settings that is used to connect to mysql via pymysql binlog_pos_memory (_bpm.BaseBinlogPosMemory): Binlog Position Memory, it should be an instance of subclass ...
[ "Start", "replication", "on", "server", "specified", "by", "*", "mysql_settings", "*" ]
python
train
apache/airflow
airflow/contrib/operators/gcp_container_operator.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/gcp_container_operator.py#L282-L308
def _set_env_from_extras(self, extras): """ Sets the environment variable `GOOGLE_APPLICATION_CREDENTIALS` with either: - The path to the keyfile from the specified connection id - A generated file's path if the user specified JSON in the connection id. The file is assumed t...
[ "def", "_set_env_from_extras", "(", "self", ",", "extras", ")", ":", "key_path", "=", "self", ".", "_get_field", "(", "extras", ",", "'key_path'", ",", "False", ")", "keyfile_json_str", "=", "self", ".", "_get_field", "(", "extras", ",", "'keyfile_dict'", ",...
Sets the environment variable `GOOGLE_APPLICATION_CREDENTIALS` with either: - The path to the keyfile from the specified connection id - A generated file's path if the user specified JSON in the connection id. The file is assumed to be deleted after the process dies due to how mkstemp() ...
[ "Sets", "the", "environment", "variable", "GOOGLE_APPLICATION_CREDENTIALS", "with", "either", ":" ]
python
test
tcalmant/ipopo
pelix/ipopo/waiting.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L199-L230
def add(self, factory, component, properties=None): # type: (str, str, dict) -> None """ Enqueues the instantiation of the given component :param factory: Factory name :param component: Component name :param properties: Component properties :raise ValueError: Com...
[ "def", "add", "(", "self", ",", "factory", ",", "component", ",", "properties", "=", "None", ")", ":", "# type: (str, str, dict) -> None", "with", "self", ".", "__lock", ":", "if", "component", "in", "self", ".", "__names", ":", "raise", "ValueError", "(", ...
Enqueues the instantiation of the given component :param factory: Factory name :param component: Component name :param properties: Component properties :raise ValueError: Component name already reserved in the queue :raise Exception: Error instantiating the component
[ "Enqueues", "the", "instantiation", "of", "the", "given", "component" ]
python
train
radjkarl/imgProcessor
imgProcessor/uncertainty/positionToIntensityUncertainty.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/uncertainty/positionToIntensityUncertainty.py#L94-L104
def _coarsenImage(image, f): ''' seems to be a more precise (but slower) way to down-scale an image ''' from skimage.morphology import square from skimage.filters import rank from skimage.transform._warps import rescale selem = square(f) arri = rank.mean(image, selem=selem) ...
[ "def", "_coarsenImage", "(", "image", ",", "f", ")", ":", "from", "skimage", ".", "morphology", "import", "square", "from", "skimage", ".", "filters", "import", "rank", "from", "skimage", ".", "transform", ".", "_warps", "import", "rescale", "selem", "=", ...
seems to be a more precise (but slower) way to down-scale an image
[ "seems", "to", "be", "a", "more", "precise", "(", "but", "slower", ")", "way", "to", "down", "-", "scale", "an", "image" ]
python
train
radjkarl/fancyTools
fancytools/math/line.py
https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/line.py#L311-L343
def intersection(line1, line2): """ Return the coordinates of a point of intersection given two lines. Return None if the lines are parallel, but non-colli_near. Return an arbitrary point of intersection if the lines are colli_near. Parameters: line1 and line2: lines given by 4 points (x0,y0,x1...
[ "def", "intersection", "(", "line1", ",", "line2", ")", ":", "x1", ",", "y1", ",", "x2", ",", "y2", "=", "line1", "u1", ",", "v1", ",", "u2", ",", "v2", "=", "line2", "(", "a", ",", "b", ")", ",", "(", "c", ",", "d", ")", "=", "(", "x2", ...
Return the coordinates of a point of intersection given two lines. Return None if the lines are parallel, but non-colli_near. Return an arbitrary point of intersection if the lines are colli_near. Parameters: line1 and line2: lines given by 4 points (x0,y0,x1,y1).
[ "Return", "the", "coordinates", "of", "a", "point", "of", "intersection", "given", "two", "lines", ".", "Return", "None", "if", "the", "lines", "are", "parallel", "but", "non", "-", "colli_near", ".", "Return", "an", "arbitrary", "point", "of", "intersection...
python
train
SmokinCaterpillar/pypet
pypet/naturalnaming.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L3188-L3202
def f_get_groups(self, copy=True): """Returns a dictionary of groups hanging immediately below this group. :param copy: Whether the group's original dictionary or a shallow copy is returned. If you want the real dictionary please do not modify it at all! :returns: Dict...
[ "def", "f_get_groups", "(", "self", ",", "copy", "=", "True", ")", ":", "if", "copy", ":", "return", "self", ".", "_groups", ".", "copy", "(", ")", "else", ":", "return", "self", ".", "_groups" ]
Returns a dictionary of groups hanging immediately below this group. :param copy: Whether the group's original dictionary or a shallow copy is returned. If you want the real dictionary please do not modify it at all! :returns: Dictionary of nodes
[ "Returns", "a", "dictionary", "of", "groups", "hanging", "immediately", "below", "this", "group", "." ]
python
test
undertherain/pycontextfree
setup_boilerplate.py
https://github.com/undertherain/pycontextfree/blob/91505e978f6034863747c98d919ac11b029b1ac3/setup_boilerplate.py#L129-L136
def parse_rst(text: str) -> docutils.nodes.document: """Parse text assuming it's an RST markup.""" parser = docutils.parsers.rst.Parser() components = (docutils.parsers.rst.Parser,) settings = docutils.frontend.OptionParser(components=components).get_default_values() document = docutils.utils.new_do...
[ "def", "parse_rst", "(", "text", ":", "str", ")", "->", "docutils", ".", "nodes", ".", "document", ":", "parser", "=", "docutils", ".", "parsers", ".", "rst", ".", "Parser", "(", ")", "components", "=", "(", "docutils", ".", "parsers", ".", "rst", "....
Parse text assuming it's an RST markup.
[ "Parse", "text", "assuming", "it", "s", "an", "RST", "markup", "." ]
python
train
OpenKMIP/PyKMIP
kmip/core/enums.py
https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/core/enums.py#L1762-L1787
def convert_attribute_name_to_tag(value): """ A utility function that converts an attribute name string into the corresponding attribute tag. For example: 'State' -> enums.Tags.STATE Args: value (string): The string name of the attribute. Returns: enum: The Tags enumeration va...
[ "def", "convert_attribute_name_to_tag", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "raise", "ValueError", "(", "\"The attribute name must be a string.\"", ")", "for", "entry", "in", "attribute_name_tag...
A utility function that converts an attribute name string into the corresponding attribute tag. For example: 'State' -> enums.Tags.STATE Args: value (string): The string name of the attribute. Returns: enum: The Tags enumeration value that corresponds to the attribute name...
[ "A", "utility", "function", "that", "converts", "an", "attribute", "name", "string", "into", "the", "corresponding", "attribute", "tag", "." ]
python
test
jerith/txTwitter
txtwitter/twitter.py
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L507-L529
def statuses_retweets(self, id, count=None, trim_user=None): """ Returns a list of the most recent retweets of the Tweet specified by the id parameter. https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid :param str id: (*required*) The numerical ID of t...
[ "def", "statuses_retweets", "(", "self", ",", "id", ",", "count", "=", "None", ",", "trim_user", "=", "None", ")", ":", "params", "=", "{", "'id'", ":", "id", "}", "set_int_param", "(", "params", ",", "'count'", ",", "count", ")", "set_bool_param", "("...
Returns a list of the most recent retweets of the Tweet specified by the id parameter. https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid :param str id: (*required*) The numerical ID of the desired tweet. :param int count: The maximum number of re...
[ "Returns", "a", "list", "of", "the", "most", "recent", "retweets", "of", "the", "Tweet", "specified", "by", "the", "id", "parameter", "." ]
python
train
SeabornGames/RequestClient
seaborn/request_client/connection_basic.py
https://github.com/SeabornGames/RequestClient/blob/21aeb951ddfdb6ee453ad0edc896ff224e06425d/seaborn/request_client/connection_basic.py#L513-L532
def create_connection(username=None, password=None, login_url=None, auth_url=None, api_key=None, realm=None, base_uri=None, proxies=None, timeout=None, headers=None, cookies=None, accepted_return=None): """ Creates and returns a connection ...
[ "def", "create_connection", "(", "username", "=", "None", ",", "password", "=", "None", ",", "login_url", "=", "None", ",", "auth_url", "=", "None", ",", "api_key", "=", "None", ",", "realm", "=", "None", ",", "base_uri", "=", "None", ",", "proxies", "...
Creates and returns a connection :param realm: :param username : str of user's email to use for the session. :param password : str of password for the user :param login_url : str of the login_url :param auth_url : str of the auth_url, if Oauth2 is used ...
[ "Creates", "and", "returns", "a", "connection", ":", "param", "realm", ":", ":", "param", "username", ":", "str", "of", "user", "s", "email", "to", "use", "for", "the", "session", ".", ":", "param", "password", ":", "str", "of", "password", "for", "the...
python
train
alephdata/memorious
memorious/logic/context.py
https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/context.py#L143-L158
def store_data(self, data, encoding='utf-8'): """Put the given content into a file, possibly encoding it as UTF-8 in the process.""" path = random_filename(self.work_path) try: with open(path, 'wb') as fh: if isinstance(data, str): data = d...
[ "def", "store_data", "(", "self", ",", "data", ",", "encoding", "=", "'utf-8'", ")", ":", "path", "=", "random_filename", "(", "self", ".", "work_path", ")", "try", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "fh", ":", "if", "isinstanc...
Put the given content into a file, possibly encoding it as UTF-8 in the process.
[ "Put", "the", "given", "content", "into", "a", "file", "possibly", "encoding", "it", "as", "UTF", "-", "8", "in", "the", "process", "." ]
python
train
numenta/nupic
src/nupic/database/client_jobs_dao.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/client_jobs_dao.py#L2274-L2411
def modelInsertAndStart(self, jobID, params, paramsHash, particleHash=None): """ Insert a new unique model (based on params) into the model table in the "running" state. This will return two things: whether or not the model was actually inserted (i.e. that set of params isn't already in the table) and t...
[ "def", "modelInsertAndStart", "(", "self", ",", "jobID", ",", "params", ",", "paramsHash", ",", "particleHash", "=", "None", ")", ":", "# Fill in default particleHash", "if", "particleHash", "is", "None", ":", "particleHash", "=", "paramsHash", "# Normalize hashes",...
Insert a new unique model (based on params) into the model table in the "running" state. This will return two things: whether or not the model was actually inserted (i.e. that set of params isn't already in the table) and the modelID chosen for that set of params. Even if the model was not inserted by t...
[ "Insert", "a", "new", "unique", "model", "(", "based", "on", "params", ")", "into", "the", "model", "table", "in", "the", "running", "state", ".", "This", "will", "return", "two", "things", ":", "whether", "or", "not", "the", "model", "was", "actually", ...
python
valid
YosaiProject/yosai
yosai/core/logging/formatters.py
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/logging/formatters.py#L37-L48
def extra_from_record(self, record): """Returns `extra` dict you passed to logger. The `extra` keyword argument is used to populate the `__dict__` of the `LogRecord`. """ return { attr_name: record.__dict__[attr_name] for attr_name in record.__dict__ ...
[ "def", "extra_from_record", "(", "self", ",", "record", ")", ":", "return", "{", "attr_name", ":", "record", ".", "__dict__", "[", "attr_name", "]", "for", "attr_name", "in", "record", ".", "__dict__", "if", "attr_name", "not", "in", "BUILTIN_ATTRS", "}" ]
Returns `extra` dict you passed to logger. The `extra` keyword argument is used to populate the `__dict__` of the `LogRecord`.
[ "Returns", "extra", "dict", "you", "passed", "to", "logger", "." ]
python
train
Peter-Slump/python-keycloak-client
src/keycloak/openid_connect.py
https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/openid_connect.py#L276-L293
def _token_request(self, grant_type, **kwargs): """ Do the actual call to the token end-point. :param grant_type: :param kwargs: See invoking methods. :return: """ payload = { 'grant_type': grant_type, 'client_id': self._client_id, ...
[ "def", "_token_request", "(", "self", ",", "grant_type", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "'grant_type'", ":", "grant_type", ",", "'client_id'", ":", "self", ".", "_client_id", ",", "'client_secret'", ":", "self", ".", "_client_secret"...
Do the actual call to the token end-point. :param grant_type: :param kwargs: See invoking methods. :return:
[ "Do", "the", "actual", "call", "to", "the", "token", "end", "-", "point", "." ]
python
train
lbryio/aioupnp
aioupnp/upnp.py
https://github.com/lbryio/aioupnp/blob/a404269d91cff5358bcffb8067b0fd1d9c6842d3/aioupnp/upnp.py#L144-L152
async def delete_port_mapping(self, external_port: int, protocol: str) -> None: """ :param external_port: (int) external port to listen on :param protocol: (str) 'UDP' | 'TCP' :return: None """ return await self.gateway.commands.DeletePortMapping( NewRemo...
[ "async", "def", "delete_port_mapping", "(", "self", ",", "external_port", ":", "int", ",", "protocol", ":", "str", ")", "->", "None", ":", "return", "await", "self", ".", "gateway", ".", "commands", ".", "DeletePortMapping", "(", "NewRemoteHost", "=", "\"\""...
:param external_port: (int) external port to listen on :param protocol: (str) 'UDP' | 'TCP' :return: None
[ ":", "param", "external_port", ":", "(", "int", ")", "external", "port", "to", "listen", "on", ":", "param", "protocol", ":", "(", "str", ")", "UDP", "|", "TCP", ":", "return", ":", "None" ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/interface/port_channel/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/interface/port_channel/__init__.py#L447-L471
def _set_minimum_links(self, v, load=False): """ Setter method for minimum_links, mapped from YANG variable /interface/port_channel/minimum_links (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_minimum_links is considered as a private method. Backends lookin...
[ "def", "_set_minimum_links", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
Setter method for minimum_links, mapped from YANG variable /interface/port_channel/minimum_links (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_minimum_links is considered as a private method. Backends looking to populate this variable should do so via calling ...
[ "Setter", "method", "for", "minimum_links", "mapped", "from", "YANG", "variable", "/", "interface", "/", "port_channel", "/", "minimum_links", "(", "uint32", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", ...
python
train
titusjan/argos
argos/config/floatcti.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/floatcti.py#L256-L260
def createEditor(self, delegate, parent, option): """ Creates a FloatCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return SnFloatCtiEditor(self, delegate, self.precision, parent=parent)
[ "def", "createEditor", "(", "self", ",", "delegate", ",", "parent", ",", "option", ")", ":", "return", "SnFloatCtiEditor", "(", "self", ",", "delegate", ",", "self", ".", "precision", ",", "parent", "=", "parent", ")" ]
Creates a FloatCtiEditor. For the parameters see the AbstractCti constructor documentation.
[ "Creates", "a", "FloatCtiEditor", ".", "For", "the", "parameters", "see", "the", "AbstractCti", "constructor", "documentation", "." ]
python
train
tklovett/PyShirtsIO
interactive_console.py
https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/interactive_console.py#L8-L25
def new_user(yaml_path): ''' Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory. ''' print 'Retrieve API Key from https://www.shirts.io/accounts/api_console/' api_key = raw_input('Shirts.io API Key: ') tokens = { ...
[ "def", "new_user", "(", "yaml_path", ")", ":", "print", "'Retrieve API Key from https://www.shirts.io/accounts/api_console/'", "api_key", "=", "raw_input", "(", "'Shirts.io API Key: '", ")", "tokens", "=", "{", "'api_key'", ":", "api_key", ",", "}", "yaml_file", "=", ...
Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory.
[ "Return", "the", "consumer", "and", "oauth", "tokens", "with", "three", "-", "legged", "OAuth", "process", "and", "save", "in", "a", "yaml", "file", "in", "the", "user", "s", "home", "directory", "." ]
python
valid
pvlib/pvlib-python
pvlib/forecast.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/forecast.py#L539-L569
def cloud_cover_to_irradiance(self, cloud_cover, how='clearsky_scaling', **kwargs): """ Convert cloud cover to irradiance. A wrapper method. Parameters ---------- cloud_cover : Series how : str, default 'clearsky_scaling' Sel...
[ "def", "cloud_cover_to_irradiance", "(", "self", ",", "cloud_cover", ",", "how", "=", "'clearsky_scaling'", ",", "*", "*", "kwargs", ")", ":", "how", "=", "how", ".", "lower", "(", ")", "if", "how", "==", "'clearsky_scaling'", ":", "irrads", "=", "self", ...
Convert cloud cover to irradiance. A wrapper method. Parameters ---------- cloud_cover : Series how : str, default 'clearsky_scaling' Selects the method for conversion. Can be one of clearsky_scaling or liujordan. **kwargs Passed to the select...
[ "Convert", "cloud", "cover", "to", "irradiance", ".", "A", "wrapper", "method", "." ]
python
train
googleapis/oauth2client
oauth2client/contrib/appengine.py
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L96-L116
def xsrf_secret_key(): """Return the secret key for use for XSRF protection. If the Site entity does not have a secret key, this method will also create one and persist it. Returns: The secret key. """ secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE) if not...
[ "def", "xsrf_secret_key", "(", ")", ":", "secret", "=", "memcache", ".", "get", "(", "XSRF_MEMCACHE_ID", ",", "namespace", "=", "OAUTH2CLIENT_NAMESPACE", ")", "if", "not", "secret", ":", "# Load the one and only instance of SiteXsrfSecretKey.", "model", "=", "SiteXsrf...
Return the secret key for use for XSRF protection. If the Site entity does not have a secret key, this method will also create one and persist it. Returns: The secret key.
[ "Return", "the", "secret", "key", "for", "use", "for", "XSRF", "protection", "." ]
python
valid
yuma-m/pychord
pychord/chord.py
https://github.com/yuma-m/pychord/blob/4aa39189082daae76e36a2701890f91776d86b47/pychord/chord.py#L130-L143
def as_chord(chord): """ convert from str to Chord instance if input is str :type chord: str|pychord.Chord :param chord: Chord name or Chord instance :rtype: pychord.Chord :return: Chord instance """ if isinstance(chord, Chord): return chord elif isinstance(chord, str): ...
[ "def", "as_chord", "(", "chord", ")", ":", "if", "isinstance", "(", "chord", ",", "Chord", ")", ":", "return", "chord", "elif", "isinstance", "(", "chord", ",", "str", ")", ":", "return", "Chord", "(", "chord", ")", "else", ":", "raise", "TypeError", ...
convert from str to Chord instance if input is str :type chord: str|pychord.Chord :param chord: Chord name or Chord instance :rtype: pychord.Chord :return: Chord instance
[ "convert", "from", "str", "to", "Chord", "instance", "if", "input", "is", "str" ]
python
train
eternnoir/pyTelegramBotAPI
telebot/__init__.py
https://github.com/eternnoir/pyTelegramBotAPI/blob/47b53b88123097f1b9562a6cd5d4e080b86185d1/telebot/__init__.py#L879-L903
def promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None): """ ...
[ "def", "promote_chat_member", "(", "self", ",", "chat_id", ",", "user_id", ",", "can_change_info", "=", "None", ",", "can_post_messages", "=", "None", ",", "can_edit_messages", "=", "None", ",", "can_delete_messages", "=", "None", ",", "can_invite_users", "=", "...
Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success. :param chat_id: Unique identifier f...
[ "Use", "this", "method", "to", "promote", "or", "demote", "a", "user", "in", "a", "supergroup", "or", "a", "channel", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "chat", "for", "this", "to", "work", "and", "must", "have", "the"...
python
train
emilydolson/avida-spatial-tools
avidaspatial/utils.py
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L382-L393
def initialize_grid(world_size, inner): """ Creates an empty grid (2d list) with the dimensions specified in world_size. Each element is initialized to the inner argument. """ data = [] for i in range(world_size[1]): data.append([]) for j in range(world_size[0]): dat...
[ "def", "initialize_grid", "(", "world_size", ",", "inner", ")", ":", "data", "=", "[", "]", "for", "i", "in", "range", "(", "world_size", "[", "1", "]", ")", ":", "data", ".", "append", "(", "[", "]", ")", "for", "j", "in", "range", "(", "world_s...
Creates an empty grid (2d list) with the dimensions specified in world_size. Each element is initialized to the inner argument.
[ "Creates", "an", "empty", "grid", "(", "2d", "list", ")", "with", "the", "dimensions", "specified", "in", "world_size", ".", "Each", "element", "is", "initialized", "to", "the", "inner", "argument", "." ]
python
train
rootpy/rootpy
rootpy/decorators.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/decorators.py#L187-L200
def sync(lock): """ A synchronization decorator """ def sync(f): @wraps(f) def new_function(*args, **kwargs): lock.acquire() try: return f(*args, **kwargs) finally: lock.release() return new_function return s...
[ "def", "sync", "(", "lock", ")", ":", "def", "sync", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "new_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lock", ".", "acquire", "(", ")", "try", ":", "return", "f", "("...
A synchronization decorator
[ "A", "synchronization", "decorator" ]
python
train
QualiSystems/cloudshell-networking-devices
cloudshell/devices/runners/state_runner.py
https://github.com/QualiSystems/cloudshell-networking-devices/blob/009aab33edb30035b52fe10dbb91db61c95ba4d9/cloudshell/devices/runners/state_runner.py#L26-L46
def health_check(self): """ Verify that device is accessible over CLI by sending ENTER for cli session """ api_response = 'Online' result = 'Health check on resource {}'.format(self._resource_name) try: health_check_flow = RunCommandFlow(self.cli_handler, self._logger) ...
[ "def", "health_check", "(", "self", ")", ":", "api_response", "=", "'Online'", "result", "=", "'Health check on resource {}'", ".", "format", "(", "self", ".", "_resource_name", ")", "try", ":", "health_check_flow", "=", "RunCommandFlow", "(", "self", ".", "cli_...
Verify that device is accessible over CLI by sending ENTER for cli session
[ "Verify", "that", "device", "is", "accessible", "over", "CLI", "by", "sending", "ENTER", "for", "cli", "session" ]
python
train
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_gimbal.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_gimbal.py#L58-L74
def cmd_gimbal_mode(self, args): '''control gimbal mode''' if len(args) != 1: print("usage: gimbal mode <GPS|MAVLink>") return if args[0].upper() == 'GPS': mode = mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT elif args[0].upper() == 'MAVLINK': m...
[ "def", "cmd_gimbal_mode", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "!=", "1", ":", "print", "(", "\"usage: gimbal mode <GPS|MAVLink>\"", ")", "return", "if", "args", "[", "0", "]", ".", "upper", "(", ")", "==", "'GPS'", ":", ...
control gimbal mode
[ "control", "gimbal", "mode" ]
python
train
jxtech/wechatpy
wechatpy/client/api/merchant/__init__.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/merchant/__init__.py#L185-L197
def update_express(self, template_id, delivery_template): """ 增加邮费模板 :param template_id: 邮费模板ID :param delivery_template: 邮费模板信息(字段说明详见增加邮费模板) :return: 返回的 JSON 数据包 """ delivery_template['template_id'] = template_id return self._post( 'merchan...
[ "def", "update_express", "(", "self", ",", "template_id", ",", "delivery_template", ")", ":", "delivery_template", "[", "'template_id'", "]", "=", "template_id", "return", "self", ".", "_post", "(", "'merchant/express/update'", ",", "data", "=", "delivery_template",...
增加邮费模板 :param template_id: 邮费模板ID :param delivery_template: 邮费模板信息(字段说明详见增加邮费模板) :return: 返回的 JSON 数据包
[ "增加邮费模板" ]
python
train
intel-analytics/BigDL
pyspark/bigdl/util/common.py
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/util/common.py#L306-L345
def from_ndarray(cls, features, labels, bigdl_type="float"): """ Convert a ndarray of features and labels to Sample, which would be used in Java side. :param features: an ndarray or a list of ndarrays :param labels: an ndarray or a list of ndarrays or a scalar :param bigdl_type: ...
[ "def", "from_ndarray", "(", "cls", ",", "features", ",", "labels", ",", "bigdl_type", "=", "\"float\"", ")", ":", "if", "isinstance", "(", "features", ",", "np", ".", "ndarray", ")", ":", "features", "=", "[", "features", "]", "else", ":", "assert", "a...
Convert a ndarray of features and labels to Sample, which would be used in Java side. :param features: an ndarray or a list of ndarrays :param labels: an ndarray or a list of ndarrays or a scalar :param bigdl_type: "double" or "float" >>> import numpy as np >>> from bigdl.util.c...
[ "Convert", "a", "ndarray", "of", "features", "and", "labels", "to", "Sample", "which", "would", "be", "used", "in", "Java", "side", ".", ":", "param", "features", ":", "an", "ndarray", "or", "a", "list", "of", "ndarrays", ":", "param", "labels", ":", "...
python
test
rogerhil/thegamesdb
thegamesdb/resources.py
https://github.com/rogerhil/thegamesdb/blob/795314215f9ee73697c7520dea4ddecfb23ca8e6/thegamesdb/resources.py#L38-L47
def list(self, name, platform='', genre=''): """ The name argument is required for this method as per the API server specification. This method also provides the platform and genre optional arguments as filters. """ data_list = self.db.get_data(self.list_path, name=name, ...
[ "def", "list", "(", "self", ",", "name", ",", "platform", "=", "''", ",", "genre", "=", "''", ")", ":", "data_list", "=", "self", ".", "db", ".", "get_data", "(", "self", ".", "list_path", ",", "name", "=", "name", ",", "platform", "=", "platform",...
The name argument is required for this method as per the API server specification. This method also provides the platform and genre optional arguments as filters.
[ "The", "name", "argument", "is", "required", "for", "this", "method", "as", "per", "the", "API", "server", "specification", ".", "This", "method", "also", "provides", "the", "platform", "and", "genre", "optional", "arguments", "as", "filters", "." ]
python
train
danifus/django-override-storage
override_storage/utils.py
https://github.com/danifus/django-override-storage/blob/a1e6c19ca102147762d09aa1f633734224f84926/override_storage/utils.py#L320-L331
def setup_storage(self): """Save existing FileField storages and patch them with test instance(s). If storage_per_field is False (default) this function will create a single instance here and assign it to self.storage to be used for all filefields. If storage_per_field is True, ...
[ "def", "setup_storage", "(", "self", ")", ":", "if", "self", ".", "storage_callable", "is", "not", "None", "and", "not", "self", ".", "storage_per_field", ":", "self", ".", "storage", "=", "self", ".", "get_storage_from_callable", "(", "field", "=", "None", ...
Save existing FileField storages and patch them with test instance(s). If storage_per_field is False (default) this function will create a single instance here and assign it to self.storage to be used for all filefields. If storage_per_field is True, an independent storage instance will...
[ "Save", "existing", "FileField", "storages", "and", "patch", "them", "with", "test", "instance", "(", "s", ")", "." ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/triangulation.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/triangulation.py#L575-L583
def _edges_in_tri_except(self, tri, edge): """Return the edges in *tri*, excluding *edge*. """ edges = [(tri[i], tri[(i+1) % 3]) for i in range(3)] try: edges.remove(tuple(edge)) except ValueError: edges.remove(tuple(edge[::-1])) return edges
[ "def", "_edges_in_tri_except", "(", "self", ",", "tri", ",", "edge", ")", ":", "edges", "=", "[", "(", "tri", "[", "i", "]", ",", "tri", "[", "(", "i", "+", "1", ")", "%", "3", "]", ")", "for", "i", "in", "range", "(", "3", ")", "]", "try",...
Return the edges in *tri*, excluding *edge*.
[ "Return", "the", "edges", "in", "*", "tri", "*", "excluding", "*", "edge", "*", "." ]
python
train
adaptive-learning/proso-apps
proso_models/views.py
https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/views.py#L245-L277
def answer(request): """ Save the answer. GET parameters: html: turn on the HTML version of the API BODY json in following format: { "answer": #answer, -- for one answer "answers": [#answer, #answer, #answer ...] -- for multiple ans...
[ "def", "answer", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'GET'", ":", "return", "render", "(", "request", ",", "'models_answer.html'", ",", "{", "}", ",", "help_text", "=", "answer", ".", "__doc__", ")", "elif", "request", ".", ...
Save the answer. GET parameters: html: turn on the HTML version of the API BODY json in following format: { "answer": #answer, -- for one answer "answers": [#answer, #answer, #answer ...] -- for multiple answers } answer = { ...
[ "Save", "the", "answer", "." ]
python
train
onicagroup/runway
runway/module/cloudformation.py
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/cloudformation.py#L45-L50
def get_stacker_env_file(path, environment, region): """Determine Stacker environment file name.""" for name in gen_stacker_env_files(environment, region): if os.path.isfile(os.path.join(path, name)): return name return "%s-%s.env" % (environment, region)
[ "def", "get_stacker_env_file", "(", "path", ",", "environment", ",", "region", ")", ":", "for", "name", "in", "gen_stacker_env_files", "(", "environment", ",", "region", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join...
Determine Stacker environment file name.
[ "Determine", "Stacker", "environment", "file", "name", "." ]
python
train
HumanCellAtlas/cloud-blobstore
cloud_blobstore/s3.py
https://github.com/HumanCellAtlas/cloud-blobstore/blob/b8a60e8e8c0da0e39dda084cb467a34cd2d1ef0a/cloud_blobstore/s3.py#L206-L223
def get(self, bucket: str, key: str) -> bytes: """ Retrieves the data for a given object in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which metadata is being retrieved. :return: the data """ try:...
[ "def", "get", "(", "self", ",", "bucket", ":", "str", ",", "key", ":", "str", ")", "->", "bytes", ":", "try", ":", "response", "=", "self", ".", "s3_client", ".", "get_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ")", "return", ...
Retrieves the data for a given object in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which metadata is being retrieved. :return: the data
[ "Retrieves", "the", "data", "for", "a", "given", "object", "in", "a", "given", "bucket", ".", ":", "param", "bucket", ":", "the", "bucket", "the", "object", "resides", "in", ".", ":", "param", "key", ":", "the", "key", "of", "the", "object", "for", "...
python
train
rix0rrr/gcl
gcl/ast.py
https://github.com/rix0rrr/gcl/blob/4e3bccc978a9c60aaaffd20f6f291c4d23775cdf/gcl/ast.py#L909-L921
def bracketedList(l, r, sep, expr, allow_missing_close=False): """Parse bracketed list. Empty list is possible, as is a trailing separator. """ # We may need to backtrack for lists, because of list comprehension, but not for # any of the other lists strict = l != '[' closer = sym(r) if not allow_missing_...
[ "def", "bracketedList", "(", "l", ",", "r", ",", "sep", ",", "expr", ",", "allow_missing_close", "=", "False", ")", ":", "# We may need to backtrack for lists, because of list comprehension, but not for", "# any of the other lists", "strict", "=", "l", "!=", "'['", "clo...
Parse bracketed list. Empty list is possible, as is a trailing separator.
[ "Parse", "bracketed", "list", "." ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/profilers/visual/runsnakerun/meliaeloader.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/runsnakerun/meliaeloader.py#L33-L55
def recurse( record, index, stop_types=STOP_TYPES,already_seen=None, type_group=False ): """Depth first traversal of a tree, all children are yielded before parent record -- dictionary record to be recursed upon index -- mapping 'address' ids to dictionary records stop_types -- types which will *...
[ "def", "recurse", "(", "record", ",", "index", ",", "stop_types", "=", "STOP_TYPES", ",", "already_seen", "=", "None", ",", "type_group", "=", "False", ")", ":", "if", "already_seen", "is", "None", ":", "already_seen", "=", "set", "(", ")", "if", "record...
Depth first traversal of a tree, all children are yielded before parent record -- dictionary record to be recursed upon index -- mapping 'address' ids to dictionary records stop_types -- types which will *not* recurse already_seen -- set storing already-visited nodes yields the travers...
[ "Depth", "first", "traversal", "of", "a", "tree", "all", "children", "are", "yielded", "before", "parent", "record", "--", "dictionary", "record", "to", "be", "recursed", "upon", "index", "--", "mapping", "address", "ids", "to", "dictionary", "records", "stop_...
python
train
dpkp/kafka-python
kafka/client_async.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/client_async.py#L478-L502
def is_ready(self, node_id, metadata_priority=True): """Check whether a node is ready to send more requests. In addition to connection-level checks, this method also is used to block additional requests from being sent during a metadata refresh. Arguments: node_id (int): id...
[ "def", "is_ready", "(", "self", ",", "node_id", ",", "metadata_priority", "=", "True", ")", ":", "if", "not", "self", ".", "_can_send_request", "(", "node_id", ")", ":", "return", "False", "# if we need to update our metadata now declare all requests unready to", "# m...
Check whether a node is ready to send more requests. In addition to connection-level checks, this method also is used to block additional requests from being sent during a metadata refresh. Arguments: node_id (int): id of the node to check metadata_priority (bool): Mark...
[ "Check", "whether", "a", "node", "is", "ready", "to", "send", "more", "requests", "." ]
python
train
Netflix-Skunkworks/historical
historical/historical-cookiecutter/historical_{{cookiecutter.technology_slug}}/{{cookiecutter.technology_slug}}/collector.py
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/historical-cookiecutter/historical_{{cookiecutter.technology_slug}}/{{cookiecutter.technology_slug}}/collector.py#L135-L149
def capture_delete_records(records): """Writes all of our delete events to DynamoDB.""" for r in records: model = create_delete_model(r) if model: try: model.delete(eventTime__le=r['detail']['eventTime']) except DeleteError as e: log.warnin...
[ "def", "capture_delete_records", "(", "records", ")", ":", "for", "r", "in", "records", ":", "model", "=", "create_delete_model", "(", "r", ")", "if", "model", ":", "try", ":", "model", ".", "delete", "(", "eventTime__le", "=", "r", "[", "'detail'", "]",...
Writes all of our delete events to DynamoDB.
[ "Writes", "all", "of", "our", "delete", "events", "to", "DynamoDB", "." ]
python
train
DataDog/integrations-core
tokumx/datadog_checks/tokumx/vendor/pymongo/message.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/message.py#L594-L601
def _start(self, request_id, docs): """Publish a CommandStartedEvent.""" cmd = self.command.copy() cmd[self.field] = docs self.listeners.publish_command_start( cmd, self.db_name, request_id, self.sock_info.address, self.op_id) return cmd
[ "def", "_start", "(", "self", ",", "request_id", ",", "docs", ")", ":", "cmd", "=", "self", ".", "command", ".", "copy", "(", ")", "cmd", "[", "self", ".", "field", "]", "=", "docs", "self", ".", "listeners", ".", "publish_command_start", "(", "cmd",...
Publish a CommandStartedEvent.
[ "Publish", "a", "CommandStartedEvent", "." ]
python
train
urschrei/pyzotero
pyzotero/zotero.py
https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L337-L365
def _extract_links(self): """ Extract self, first, next, last links from a request response """ extracted = dict() try: for key, value in self.request.links.items(): parsed = urlparse(value["url"]) fragment = "{path}?{query}".format(pat...
[ "def", "_extract_links", "(", "self", ")", ":", "extracted", "=", "dict", "(", ")", "try", ":", "for", "key", ",", "value", "in", "self", ".", "request", ".", "links", ".", "items", "(", ")", ":", "parsed", "=", "urlparse", "(", "value", "[", "\"ur...
Extract self, first, next, last links from a request response
[ "Extract", "self", "first", "next", "last", "links", "from", "a", "request", "response" ]
python
valid
blockstack/blockstack-core
blockstack/lib/subdomains.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L345-L357
def get_public_key(self): """ Parse the scriptSig and extract the public key. Raises ValueError if this is a multisig-controlled subdomain. """ res = self.get_public_key_info() if 'error' in res: raise ValueError(res['error']) if res['type'] != 'singl...
[ "def", "get_public_key", "(", "self", ")", ":", "res", "=", "self", ".", "get_public_key_info", "(", ")", "if", "'error'", "in", "res", ":", "raise", "ValueError", "(", "res", "[", "'error'", "]", ")", "if", "res", "[", "'type'", "]", "!=", "'singlesig...
Parse the scriptSig and extract the public key. Raises ValueError if this is a multisig-controlled subdomain.
[ "Parse", "the", "scriptSig", "and", "extract", "the", "public", "key", ".", "Raises", "ValueError", "if", "this", "is", "a", "multisig", "-", "controlled", "subdomain", "." ]
python
train
spyder-ide/spyder
spyder/config/base.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/base.py#L222-L224
def get_module_path(modname): """Return module *modname* base path""" return osp.abspath(osp.dirname(sys.modules[modname].__file__))
[ "def", "get_module_path", "(", "modname", ")", ":", "return", "osp", ".", "abspath", "(", "osp", ".", "dirname", "(", "sys", ".", "modules", "[", "modname", "]", ".", "__file__", ")", ")" ]
Return module *modname* base path
[ "Return", "module", "*", "modname", "*", "base", "path" ]
python
train
sleepyfran/itunespy
itunespy/music_album.py
https://github.com/sleepyfran/itunespy/blob/0e7e931b135b5e0daae49ba68e9167ff4ac73eb5/itunespy/music_album.py#L31-L40
def get_tracks(self): """ Retrieves all the tracks of the album if they haven't been retrieved yet :return: List. Tracks of the current album """ if not self._track_list: tracks = itunespy.lookup(id=self.collection_id, entity=itunespy.entities['song'])[1:] ...
[ "def", "get_tracks", "(", "self", ")", ":", "if", "not", "self", ".", "_track_list", ":", "tracks", "=", "itunespy", ".", "lookup", "(", "id", "=", "self", ".", "collection_id", ",", "entity", "=", "itunespy", ".", "entities", "[", "'song'", "]", ")", ...
Retrieves all the tracks of the album if they haven't been retrieved yet :return: List. Tracks of the current album
[ "Retrieves", "all", "the", "tracks", "of", "the", "album", "if", "they", "haven", "t", "been", "retrieved", "yet", ":", "return", ":", "List", ".", "Tracks", "of", "the", "current", "album" ]
python
train
PyCQA/astroid
astroid/builder.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/builder.py#L278-L314
def _extract_expressions(node): """Find expressions in a call to _TRANSIENT_FUNCTION and extract them. The function walks the AST recursively to search for expressions that are wrapped into a call to _TRANSIENT_FUNCTION. If it finds such an expression, it completely removes the function call node from ...
[ "def", "_extract_expressions", "(", "node", ")", ":", "if", "(", "isinstance", "(", "node", ",", "nodes", ".", "Call", ")", "and", "isinstance", "(", "node", ".", "func", ",", "nodes", ".", "Name", ")", "and", "node", ".", "func", ".", "name", "==", ...
Find expressions in a call to _TRANSIENT_FUNCTION and extract them. The function walks the AST recursively to search for expressions that are wrapped into a call to _TRANSIENT_FUNCTION. If it finds such an expression, it completely removes the function call node from the tree, replacing it by the wrapp...
[ "Find", "expressions", "in", "a", "call", "to", "_TRANSIENT_FUNCTION", "and", "extract", "them", "." ]
python
train
aliyun/aliyun-odps-python-sdk
odps/ml/algolib/objects.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/ml/algolib/objects.py#L252-L265
def build_data_output(cls, name='output', copy_input=None, schema=None): """ Build a data output port. :param name: port name :type name: str :return: port object :param copy_input: input name where the schema is copied from. :type copy_input: str :param ...
[ "def", "build_data_output", "(", "cls", ",", "name", "=", "'output'", ",", "copy_input", "=", "None", ",", "schema", "=", "None", ")", ":", "return", "cls", "(", "name", ",", "PortDirection", ".", "OUTPUT", ",", "type", "=", "PortType", ".", "DATA", ",...
Build a data output port. :param name: port name :type name: str :return: port object :param copy_input: input name where the schema is copied from. :type copy_input: str :param schema: k1:v1,k2:v2 string describing the schema to be appended :type schema: str ...
[ "Build", "a", "data", "output", "port", "." ]
python
train
tamasgal/km3pipe
km3modules/k40.py
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L529-L566
def load_k40_coincidences_from_rootfile(filename, dom_id): """Load k40 coincidences from JMonitorK40 ROOT file Parameters ---------- filename: root file produced by JMonitorK40 dom_id: DOM ID Returns ------- data: numpy array of coincidences dom_weight: weight to apply to coinciden...
[ "def", "load_k40_coincidences_from_rootfile", "(", "filename", ",", "dom_id", ")", ":", "from", "ROOT", "import", "TFile", "root_file_monitor", "=", "TFile", "(", "filename", ",", "\"READ\"", ")", "dom_name", "=", "str", "(", "dom_id", ")", "+", "\".2S\"", "hi...
Load k40 coincidences from JMonitorK40 ROOT file Parameters ---------- filename: root file produced by JMonitorK40 dom_id: DOM ID Returns ------- data: numpy array of coincidences dom_weight: weight to apply to coincidences to get rate in Hz
[ "Load", "k40", "coincidences", "from", "JMonitorK40", "ROOT", "file" ]
python
train
blockstack/virtualchain
virtualchain/lib/blockchain/session.py
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/session.py#L151-L178
def connect_bitcoind_impl( bitcoind_opts ): """ Create a connection to bitcoind, using a dict of config options. """ if 'bitcoind_port' not in bitcoind_opts.keys() or bitcoind_opts['bitcoind_port'] is None: log.error("No port given") raise ValueError("No RPC port given (bitcoind_port)")...
[ "def", "connect_bitcoind_impl", "(", "bitcoind_opts", ")", ":", "if", "'bitcoind_port'", "not", "in", "bitcoind_opts", ".", "keys", "(", ")", "or", "bitcoind_opts", "[", "'bitcoind_port'", "]", "is", "None", ":", "log", ".", "error", "(", "\"No port given\"", ...
Create a connection to bitcoind, using a dict of config options.
[ "Create", "a", "connection", "to", "bitcoind", "using", "a", "dict", "of", "config", "options", "." ]
python
train
tyarkoni/pliers
pliers/external/tensorflow/classify_image.py
https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/external/tensorflow/classify_image.py#L120-L127
def create_graph(): """Creates a graph from saved GraphDef file and returns a saver.""" # Creates graph from saved graph_def.pb. with tf.gfile.FastGFile(os.path.join( FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf...
[ "def", "create_graph", "(", ")", ":", "# Creates graph from saved graph_def.pb.", "with", "tf", ".", "gfile", ".", "FastGFile", "(", "os", ".", "path", ".", "join", "(", "FLAGS", ".", "model_dir", ",", "'classify_image_graph_def.pb'", ")", ",", "'rb'", ")", "a...
Creates a graph from saved GraphDef file and returns a saver.
[ "Creates", "a", "graph", "from", "saved", "GraphDef", "file", "and", "returns", "a", "saver", "." ]
python
train
kblin/ncbi-genome-download
ncbi_genome_download/core.py
https://github.com/kblin/ncbi-genome-download/blob/dc55382d351c29e1027be8fa3876701762c1d752/ncbi_genome_download/core.py#L300-L328
def get_summary(section, domain, uri, use_cache): """Get the assembly_summary.txt file from NCBI and return a StringIO object for it.""" logging.debug('Checking for a cached summary file') cachefile = "{section}_{domain}_assembly_summary.txt".format(section=section, domain=domain) full_cachefile = os.p...
[ "def", "get_summary", "(", "section", ",", "domain", ",", "uri", ",", "use_cache", ")", ":", "logging", ".", "debug", "(", "'Checking for a cached summary file'", ")", "cachefile", "=", "\"{section}_{domain}_assembly_summary.txt\"", ".", "format", "(", "section", "=...
Get the assembly_summary.txt file from NCBI and return a StringIO object for it.
[ "Get", "the", "assembly_summary", ".", "txt", "file", "from", "NCBI", "and", "return", "a", "StringIO", "object", "for", "it", "." ]
python
train
kalekundert/nonstdlib
nonstdlib/meta.py
https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/meta.py#L40-L75
def singleton(cls): """ Decorator function that turns a class into a singleton. """ import inspect # Create a structure to store instances of any singletons that get # created. instances = {} # Make sure that the constructor for this class doesn't take any # arguments. Since singletons ca...
[ "def", "singleton", "(", "cls", ")", ":", "import", "inspect", "# Create a structure to store instances of any singletons that get", "# created.", "instances", "=", "{", "}", "# Make sure that the constructor for this class doesn't take any", "# arguments. Since singletons can only be...
Decorator function that turns a class into a singleton.
[ "Decorator", "function", "that", "turns", "a", "class", "into", "a", "singleton", "." ]
python
train
dbcli/athenacli
athenacli/packages/special/iocommands.py
https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L158-L186
def execute_favorite_query(cur, arg, **_): """Returns (title, rows, headers, status)""" if arg == '': for result in list_favorite_queries(): yield result """Parse out favorite name and optional substitution parameters""" name, _, arg_str = arg.partition(' ') args = shlex.split(a...
[ "def", "execute_favorite_query", "(", "cur", ",", "arg", ",", "*", "*", "_", ")", ":", "if", "arg", "==", "''", ":", "for", "result", "in", "list_favorite_queries", "(", ")", ":", "yield", "result", "\"\"\"Parse out favorite name and optional substitution paramete...
Returns (title, rows, headers, status)
[ "Returns", "(", "title", "rows", "headers", "status", ")" ]
python
train
Shizmob/pydle
pydle/client.py
https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/client.py#L468-L472
def disconnect(self, client): """ Remove client from pool. """ self.clients.remove(client) del self.connect_args[client] client.disconnect()
[ "def", "disconnect", "(", "self", ",", "client", ")", ":", "self", ".", "clients", ".", "remove", "(", "client", ")", "del", "self", ".", "connect_args", "[", "client", "]", "client", ".", "disconnect", "(", ")" ]
Remove client from pool.
[ "Remove", "client", "from", "pool", "." ]
python
train
jldbc/pybaseball
pybaseball/league_pitching_stats.py
https://github.com/jldbc/pybaseball/blob/085ea26bfd1b5f5926d79d4fac985c88278115f2/pybaseball/league_pitching_stats.py#L67-L96
def pitching_stats_range(start_dt=None, end_dt=None): """ Get all pitching stats for a set time range. This can be the past week, the month of August, anything. Just supply the start and end date in YYYY-MM-DD format. """ # ensure valid date strings, perform necessary processing for query ...
[ "def", "pitching_stats_range", "(", "start_dt", "=", "None", ",", "end_dt", "=", "None", ")", ":", "# ensure valid date strings, perform necessary processing for query", "start_dt", ",", "end_dt", "=", "sanitize_input", "(", "start_dt", ",", "end_dt", ")", "if", "date...
Get all pitching stats for a set time range. This can be the past week, the month of August, anything. Just supply the start and end date in YYYY-MM-DD format.
[ "Get", "all", "pitching", "stats", "for", "a", "set", "time", "range", ".", "This", "can", "be", "the", "past", "week", "the", "month", "of", "August", "anything", ".", "Just", "supply", "the", "start", "and", "end", "date", "in", "YYYY", "-", "MM", ...
python
train
serkanyersen/underscore.py
src/underscore.py
https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L561-L579
def without(self, *values): """ Return a version of the array that does not contain the specified value(s). """ if self._clean.isDict(): newlist = {} for i, k in enumerate(self.obj): # if k not in values: # use indexof to check identity ...
[ "def", "without", "(", "self", ",", "*", "values", ")", ":", "if", "self", ".", "_clean", ".", "isDict", "(", ")", ":", "newlist", "=", "{", "}", "for", "i", ",", "k", "in", "enumerate", "(", "self", ".", "obj", ")", ":", "# if k not in values: # ...
Return a version of the array that does not contain the specified value(s).
[ "Return", "a", "version", "of", "the", "array", "that", "does", "not", "contain", "the", "specified", "value", "(", "s", ")", "." ]
python
train
gwastro/pycbc
pycbc/filter/matchedfilter.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/matchedfilter.py#L659-L788
def compute_max_snr_over_sky_loc_stat_no_phase(hplus, hcross, hphccorr, hpnorm=None, hcnorm=None, out=None, thresh=0, analyse_slice=None): """ Compute the match maximized ...
[ "def", "compute_max_snr_over_sky_loc_stat_no_phase", "(", "hplus", ",", "hcross", ",", "hphccorr", ",", "hpnorm", "=", "None", ",", "hcnorm", "=", "None", ",", "out", "=", "None", ",", "thresh", "=", "0", ",", "analyse_slice", "=", "None", ")", ":", "# NOT...
Compute the match maximized over polarization phase. In contrast to compute_max_snr_over_sky_loc_stat_no_phase this function performs no maximization over orbital phase, treating that as an intrinsic parameter. In the case of aligned-spin 2,2-mode only waveforms, this collapses to the normal statistic ...
[ "Compute", "the", "match", "maximized", "over", "polarization", "phase", "." ]
python
train
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L33-L52
def recursive_repr(func): """Decorator to prevent infinite repr recursion.""" repr_running = set() @wraps(func) def wrapper(self): "Return ellipsis on recursive re-entry to function." key = id(self), get_ident() if key in repr_running: return '...' repr_run...
[ "def", "recursive_repr", "(", "func", ")", ":", "repr_running", "=", "set", "(", ")", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ")", ":", "\"Return ellipsis on recursive re-entry to function.\"", "key", "=", "id", "(", "self", ")", ",", ...
Decorator to prevent infinite repr recursion.
[ "Decorator", "to", "prevent", "infinite", "repr", "recursion", "." ]
python
train
reflexsc/reflex
dev/build.py
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/build.py#L146-L194
def release(self, lane, status, target=None, meta=None, svcs=None): """Set release information on a build""" if target not in (None, 'current', 'future'): raise ValueError("\nError: Target must be None, 'current', or 'future'\n") svcs, meta, lane = self._prep_for_release(lane, svcs...
[ "def", "release", "(", "self", ",", "lane", ",", "status", ",", "target", "=", "None", ",", "meta", "=", "None", ",", "svcs", "=", "None", ")", ":", "if", "target", "not", "in", "(", "None", ",", "'current'", ",", "'future'", ")", ":", "raise", "...
Set release information on a build
[ "Set", "release", "information", "on", "a", "build" ]
python
train
jmurty/xml4h
xml4h/nodes.py
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L344-L359
def delete(self, destroy=True): """ Delete this node from the owning document. :param bool destroy: if True the child node will be destroyed in addition to being removed from the document. :returns: the removed child node, or *None* if the child was destroyed. """ ...
[ "def", "delete", "(", "self", ",", "destroy", "=", "True", ")", ":", "removed_child", "=", "self", ".", "adapter", ".", "remove_node_child", "(", "self", ".", "adapter", ".", "get_node_parent", "(", "self", ".", "impl_node", ")", ",", "self", ".", "impl_...
Delete this node from the owning document. :param bool destroy: if True the child node will be destroyed in addition to being removed from the document. :returns: the removed child node, or *None* if the child was destroyed.
[ "Delete", "this", "node", "from", "the", "owning", "document", "." ]
python
train
owncloud/pyocclient
owncloud/owncloud.py
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L868-L887
def get_share(self, share_id): """Returns share information about known share :param share_id: id of the share to be checked :returns: instance of ShareInfo class :raises: ResponseError in case an HTTP error status was returned """ if (share_id is None) or not (isinstanc...
[ "def", "get_share", "(", "self", ",", "share_id", ")", ":", "if", "(", "share_id", "is", "None", ")", "or", "not", "(", "isinstance", "(", "share_id", ",", "int", ")", ")", ":", "return", "None", "res", "=", "self", ".", "_make_ocs_request", "(", "'G...
Returns share information about known share :param share_id: id of the share to be checked :returns: instance of ShareInfo class :raises: ResponseError in case an HTTP error status was returned
[ "Returns", "share", "information", "about", "known", "share" ]
python
train
awentzonline/keras-vgg-buddy
keras_vgg_buddy/models.py
https://github.com/awentzonline/keras-vgg-buddy/blob/716cb66396b839a66ec8dc66998066b360a8f395/keras_vgg_buddy/models.py#L21-L28
def img_to_vgg(x): '''Condition an image for use with the VGG16 model.''' x = x[:,:,::-1] # to BGR x[:, :, 0] -= 103.939 x[:, :, 1] -= 116.779 x[:, :, 2] -= 123.68 x = x.transpose((2, 0, 1)) return x
[ "def", "img_to_vgg", "(", "x", ")", ":", "x", "=", "x", "[", ":", ",", ":", ",", ":", ":", "-", "1", "]", "# to BGR", "x", "[", ":", ",", ":", ",", "0", "]", "-=", "103.939", "x", "[", ":", ",", ":", ",", "1", "]", "-=", "116.779", "x",...
Condition an image for use with the VGG16 model.
[ "Condition", "an", "image", "for", "use", "with", "the", "VGG16", "model", "." ]
python
test
DistrictDataLabs/yellowbrick
yellowbrick/regressor/residuals.py
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/regressor/residuals.py#L202-L253
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title on the plot self.set_title...
[ "def", "finalize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Set the title on the plot", "self", ".", "set_title", "(", "'Prediction Error for {}'", ".", "format", "(", "self", ".", "name", ")", ")", "# Square the axes to ensure a 45 degree line", "if", "...
Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments.
[ "Finalize", "executes", "any", "subclass", "-", "specific", "axes", "finalization", "steps", ".", "The", "user", "calls", "poof", "and", "poof", "calls", "finalize", "." ]
python
train
ranaroussi/qtpylib
qtpylib/algo.py
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/algo.py#L792-L859
def _base_bar_handler(self, bar): """ non threaded bar handler (called by threaded _tick_handler) """ # bar symbol symbol = bar['symbol'].values if len(symbol) == 0: return symbol = symbol[0] self_bars = self.bars.copy() # work on copy is_tick_or_vol...
[ "def", "_base_bar_handler", "(", "self", ",", "bar", ")", ":", "# bar symbol", "symbol", "=", "bar", "[", "'symbol'", "]", ".", "values", "if", "len", "(", "symbol", ")", "==", "0", ":", "return", "symbol", "=", "symbol", "[", "0", "]", "self_bars", ...
non threaded bar handler (called by threaded _tick_handler)
[ "non", "threaded", "bar", "handler", "(", "called", "by", "threaded", "_tick_handler", ")" ]
python
train
wndhydrnt/python-oauth2
oauth2/store/memcache.py
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/memcache.py#L54-L69
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`. """ key = self._generate_cache_key(authorization_code.code) self.mc.set(key, {"client_id": authorization_code.cli...
[ "def", "save_code", "(", "self", ",", "authorization_code", ")", ":", "key", "=", "self", ".", "_generate_cache_key", "(", "authorization_code", ".", "code", ")", "self", ".", "mc", ".", "set", "(", "key", ",", "{", "\"client_id\"", ":", "authorization_code"...
Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`.
[ "Stores", "the", "data", "belonging", "to", "an", "authorization", "code", "token", "in", "memcache", "." ]
python
train
google/grr
grr/core/grr_response_core/lib/parsers/chrome_history.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/chrome_history.py#L95-L121
def Parse(self): """Iterator returning a list for each entry in history. We store all the download events in an array (choosing this over visits since there are likely to be less of them). We later interleave them with visit events to get an overall correct time order. Yields: a list of attr...
[ "def", "Parse", "(", "self", ")", ":", "# Query for old style and newstyle downloads storage.", "query_iter", "=", "itertools", ".", "chain", "(", "self", ".", "Query", "(", "self", ".", "DOWNLOADS_QUERY", ")", ",", "self", ".", "Query", "(", "self", ".", "DOW...
Iterator returning a list for each entry in history. We store all the download events in an array (choosing this over visits since there are likely to be less of them). We later interleave them with visit events to get an overall correct time order. Yields: a list of attributes for each entry
[ "Iterator", "returning", "a", "list", "for", "each", "entry", "in", "history", "." ]
python
train
MuhammedHasan/sklearn_utils
sklearn_utils/preprocessing/standard_scale_by_label.py
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/preprocessing/standard_scale_by_label.py#L15-L24
def partial_fit(self, X, y): """ :X: {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. :y: Healthy 'h' or 'sick_name' """ X, y = filter_by_lab...
[ "def", "partial_fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "y", "=", "filter_by_label", "(", "X", ",", "y", ",", "self", ".", "reference_label", ")", "super", "(", ")", ".", "partial_fit", "(", "X", ",", "y", ")", "return", "self"...
:X: {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. :y: Healthy 'h' or 'sick_name'
[ ":", "X", ":", "{", "array", "-", "like", "sparse", "matrix", "}", "shape", "[", "n_samples", "n_features", "]", "The", "data", "used", "to", "compute", "the", "mean", "and", "standard", "deviation", "used", "for", "later", "scaling", "along", "the", "fe...
python
test
google/google-visualization-python
gviz_api.py
https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L567-L591
def AppendData(self, data, custom_properties=None): """Appends new data to the table. Data is appended in rows. Data must comply with the table schema passed in to __init__(). See CoerceValue() for a list of acceptable data types. See the class documentation for more information and examples of sch...
[ "def", "AppendData", "(", "self", ",", "data", ",", "custom_properties", "=", "None", ")", ":", "# If the maximal depth is 0, we simply iterate over the data table", "# lines and insert them using _InnerAppendData. Otherwise, we simply", "# let the _InnerAppendData handle all the levels....
Appends new data to the table. Data is appended in rows. Data must comply with the table schema passed in to __init__(). See CoerceValue() for a list of acceptable data types. See the class documentation for more information and examples of schema and data values. Args: data: The row to add ...
[ "Appends", "new", "data", "to", "the", "table", "." ]
python
train
xflr6/gsheets
gsheets/backend.py
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/backend.py#L63-L69
def values(service, id, ranges): """Fetch and return spreadsheet cell values with Google sheets API.""" params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE', 'dateTimeRenderOption': 'FORMATTED_STRING'} params.update(spreadsheetId=id, ranges=ranges) response = servic...
[ "def", "values", "(", "service", ",", "id", ",", "ranges", ")", ":", "params", "=", "{", "'majorDimension'", ":", "'ROWS'", ",", "'valueRenderOption'", ":", "'UNFORMATTED_VALUE'", ",", "'dateTimeRenderOption'", ":", "'FORMATTED_STRING'", "}", "params", ".", "upd...
Fetch and return spreadsheet cell values with Google sheets API.
[ "Fetch", "and", "return", "spreadsheet", "cell", "values", "with", "Google", "sheets", "API", "." ]
python
train
DasIch/argvard
argvard/__init__.py
https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/__init__.py#L119-L149
def option(self, signature, overrideable=False): """ A decorator for registering an option with the given `signature`:: @app.option('--option') def option(context): # do something pass If the name in the signature has already been used to...
[ "def", "option", "(", "self", ",", "signature", ",", "overrideable", "=", "False", ")", ":", "def", "decorator", "(", "function", ")", ":", "try", ":", "function", "=", "annotations", "(", ")", "(", "function", ")", "except", "RuntimeError", ":", "pass",...
A decorator for registering an option with the given `signature`:: @app.option('--option') def option(context): # do something pass If the name in the signature has already been used to register an option, a :exc:`RuntimeError` is raised unless t...
[ "A", "decorator", "for", "registering", "an", "option", "with", "the", "given", "signature", "::" ]
python
train
angr/angr
angr/sim_state_options.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/sim_state_options.py#L372-L390
def register_option(cls, name, types, default=None, description=None): """ Register a state option. :param str name: Name of the state option. :param types: A collection of allowed types of this state option. :param default: The default value of this sta...
[ "def", "register_option", "(", "cls", ",", "name", ",", "types", ",", "default", "=", "None", ",", "description", "=", "None", ")", ":", "if", "name", "in", "cls", ".", "OPTIONS", ":", "raise", "SimStateOptionsError", "(", "\"A state option with the same name ...
Register a state option. :param str name: Name of the state option. :param types: A collection of allowed types of this state option. :param default: The default value of this state option. :param str description: The description of this state option. :r...
[ "Register", "a", "state", "option", "." ]
python
train
nabla-c0d3/sslyze
sslyze/plugins/utils/trust_store/trust_store.py
https://github.com/nabla-c0d3/sslyze/blob/0fb3ae668453d7ecf616d0755f237ca7be9f62fa/sslyze/plugins/utils/trust_store/trust_store.py#L121-L147
def build_verified_certificate_chain(self, received_certificate_chain: List[Certificate]) -> List[Certificate]: """Try to figure out the verified chain by finding the anchor/root CA the received chain chains up to in the trust store. This will not clean the certificate chain if additional/inval...
[ "def", "build_verified_certificate_chain", "(", "self", ",", "received_certificate_chain", ":", "List", "[", "Certificate", "]", ")", "->", "List", "[", "Certificate", "]", ":", "# The certificates must have been sent in the correct order or we give up", "if", "not", "self"...
Try to figure out the verified chain by finding the anchor/root CA the received chain chains up to in the trust store. This will not clean the certificate chain if additional/invalid certificates were sent and the signatures and fields (notBefore, etc.) are not verified.
[ "Try", "to", "figure", "out", "the", "verified", "chain", "by", "finding", "the", "anchor", "/", "root", "CA", "the", "received", "chain", "chains", "up", "to", "in", "the", "trust", "store", "." ]
python
train
fananimi/pyzk
zk/base.py
https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L388-L401
def disconnect(self): """ diconnect from the connected device :return: bool """ cmd_response = self.__send_command(const.CMD_EXIT) if cmd_response.get('status'): self.is_connect = False if self.__sock: self.__sock.close() ...
[ "def", "disconnect", "(", "self", ")", ":", "cmd_response", "=", "self", ".", "__send_command", "(", "const", ".", "CMD_EXIT", ")", "if", "cmd_response", ".", "get", "(", "'status'", ")", ":", "self", ".", "is_connect", "=", "False", "if", "self", ".", ...
diconnect from the connected device :return: bool
[ "diconnect", "from", "the", "connected", "device" ]
python
train
SITools2/pySitools2_1.0
sitools2/core/query.py
https://github.com/SITools2/pySitools2_1.0/blob/acd13198162456ba401a0b923af989bb29feb3b6/sitools2/core/query.py#L386-L394
def __buildLimit(self, query ,limitResMax): """Builds limit parameter.""" limit = query._getParameters()['limit'] if limitResMax>0 and limitResMax < limit: query = UpdateParameter(query, 'limit', limitResMax) query = UpdateParameter(query, 'nocount', 'true') ...
[ "def", "__buildLimit", "(", "self", ",", "query", ",", "limitResMax", ")", ":", "limit", "=", "query", ".", "_getParameters", "(", ")", "[", "'limit'", "]", "if", "limitResMax", ">", "0", "and", "limitResMax", "<", "limit", ":", "query", "=", "UpdatePara...
Builds limit parameter.
[ "Builds", "limit", "parameter", "." ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/wrappers.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/wrappers.py#L253-L271
def set_blend_func(self, srgb='one', drgb='zero', salpha=None, dalpha=None): """Specify pixel arithmetic for RGB and alpha Parameters ---------- srgb : str Source RGB factor. drgb : str Destination RGB factor. salpha : s...
[ "def", "set_blend_func", "(", "self", ",", "srgb", "=", "'one'", ",", "drgb", "=", "'zero'", ",", "salpha", "=", "None", ",", "dalpha", "=", "None", ")", ":", "salpha", "=", "srgb", "if", "salpha", "is", "None", "else", "salpha", "dalpha", "=", "drgb...
Specify pixel arithmetic for RGB and alpha Parameters ---------- srgb : str Source RGB factor. drgb : str Destination RGB factor. salpha : str | None Source alpha factor. If None, ``srgb`` is used. dalpha : str Destinat...
[ "Specify", "pixel", "arithmetic", "for", "RGB", "and", "alpha", "Parameters", "----------", "srgb", ":", "str", "Source", "RGB", "factor", ".", "drgb", ":", "str", "Destination", "RGB", "factor", ".", "salpha", ":", "str", "|", "None", "Source", "alpha", "...
python
train