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
coursera-dl/coursera-dl
coursera/cookies.py
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L258-L276
def find_cookies_for_class(cookies_file, class_name): """ Return a RequestsCookieJar containing the cookies for .coursera.org and class.coursera.org found in the given cookies_file. """ path = "/" + class_name def cookies_filter(c): return c.domain == ".coursera.org" \ or (...
[ "def", "find_cookies_for_class", "(", "cookies_file", ",", "class_name", ")", ":", "path", "=", "\"/\"", "+", "class_name", "def", "cookies_filter", "(", "c", ")", ":", "return", "c", ".", "domain", "==", "\".coursera.org\"", "or", "(", "c", ".", "domain", ...
Return a RequestsCookieJar containing the cookies for .coursera.org and class.coursera.org found in the given cookies_file.
[ "Return", "a", "RequestsCookieJar", "containing", "the", "cookies", "for", ".", "coursera", ".", "org", "and", "class", ".", "coursera", ".", "org", "found", "in", "the", "given", "cookies_file", "." ]
python
train
astropy/photutils
photutils/aperture/mask.py
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/mask.py#L49-L93
def _overlap_slices(self, shape): """ Calculate the slices for the overlapping part of the bounding box and an array of the given shape. Parameters ---------- shape : tuple of int The ``(ny, nx)`` shape of array where the slices are to be applied....
[ "def", "_overlap_slices", "(", "self", ",", "shape", ")", ":", "if", "len", "(", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'input shape must have 2 elements.'", ")", "xmin", "=", "self", ".", "bbox", ".", "ixmin", "xmax", "=", "self", "....
Calculate the slices for the overlapping part of the bounding box and an array of the given shape. Parameters ---------- shape : tuple of int The ``(ny, nx)`` shape of array where the slices are to be applied. Returns ------- slices_large...
[ "Calculate", "the", "slices", "for", "the", "overlapping", "part", "of", "the", "bounding", "box", "and", "an", "array", "of", "the", "given", "shape", "." ]
python
train
manahl/arctic
arctic/chunkstore/chunkstore.py
https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/chunkstore/chunkstore.py#L119-L168
def delete(self, symbol, chunk_range=None, audit=None): """ Delete all chunks for a symbol, or optionally, chunks within a range Parameters ---------- symbol : str symbol name for the item chunk_range: range object a date range to delete a...
[ "def", "delete", "(", "self", ",", "symbol", ",", "chunk_range", "=", "None", ",", "audit", "=", "None", ")", ":", "if", "chunk_range", "is", "not", "None", ":", "sym", "=", "self", ".", "_get_symbol_info", "(", "symbol", ")", "# read out chunks that fall ...
Delete all chunks for a symbol, or optionally, chunks within a range Parameters ---------- symbol : str symbol name for the item chunk_range: range object a date range to delete audit: dict dict to store in the audit log
[ "Delete", "all", "chunks", "for", "a", "symbol", "or", "optionally", "chunks", "within", "a", "range" ]
python
train
facebook/watchman
build/fbcode_builder/utils.py
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/utils.py#L42-L52
def _inner_read_config(path): ''' Helper to read a named config file. The grossness with the global is a workaround for this python bug: https://bugs.python.org/issue21591 The bug prevents us from defining either a local function or a lambda in the scope of read_fbcode_builder_config below. ...
[ "def", "_inner_read_config", "(", "path", ")", ":", "global", "_project_dir", "full_path", "=", "os", ".", "path", ".", "join", "(", "_project_dir", ",", "path", ")", "return", "read_fbcode_builder_config", "(", "full_path", ")" ]
Helper to read a named config file. The grossness with the global is a workaround for this python bug: https://bugs.python.org/issue21591 The bug prevents us from defining either a local function or a lambda in the scope of read_fbcode_builder_config below.
[ "Helper", "to", "read", "a", "named", "config", "file", ".", "The", "grossness", "with", "the", "global", "is", "a", "workaround", "for", "this", "python", "bug", ":", "https", ":", "//", "bugs", ".", "python", ".", "org", "/", "issue21591", "The", "bu...
python
train
streamlink/streamlink
src/streamlink/plugin/api/http_session.py
https://github.com/streamlink/streamlink/blob/c8ed1daff14ac03195870238b9b900c1109dd5c1/src/streamlink/plugin/api/http_session.py#L110-L116
def parse_cookies(self, cookies, **kwargs): """Parses a semi-colon delimited list of cookies. Example: foo=bar;baz=qux """ for name, value in _parse_keyvalue_list(cookies): self.cookies.set(name, value, **kwargs)
[ "def", "parse_cookies", "(", "self", ",", "cookies", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "value", "in", "_parse_keyvalue_list", "(", "cookies", ")", ":", "self", ".", "cookies", ".", "set", "(", "name", ",", "value", ",", "*", "*",...
Parses a semi-colon delimited list of cookies. Example: foo=bar;baz=qux
[ "Parses", "a", "semi", "-", "colon", "delimited", "list", "of", "cookies", "." ]
python
test
hydraplatform/hydra-base
hydra_base/util/permissions.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/permissions.py#L70-L87
def required_role(req_role): """ Decorator applied to functions requiring caller to possess the specified role """ def dec_wrapper(wfunc): @wraps(wfunc) def wrapped(*args, **kwargs): user_id = kwargs.get("user_id") try: res = db.DBSession.query...
[ "def", "required_role", "(", "req_role", ")", ":", "def", "dec_wrapper", "(", "wfunc", ")", ":", "@", "wraps", "(", "wfunc", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "kwargs", ".", "get", "(", "\"u...
Decorator applied to functions requiring caller to possess the specified role
[ "Decorator", "applied", "to", "functions", "requiring", "caller", "to", "possess", "the", "specified", "role" ]
python
train
tensorflow/cleverhans
cleverhans/attacks/momentum_iterative_method.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/momentum_iterative_method.py#L43-L123
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments. See `parse_params` for documentation. """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs)...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "asserts", "=", "[", "]", "# If a data range was specified, check that ...
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments. See `parse_params` for documentation.
[ "Generate", "symbolic", "graph", "for", "adversarial", "examples", "and", "return", "." ]
python
train
renweizhukov/pytwis
pytwis/pytwis.py
https://github.com/renweizhukov/pytwis/blob/1bc45b038d7e5343824c520f89f644bbd6faab0a/pytwis/pytwis.py#L152-L186
def _check_password(password): """Check the strength of a password. A password is considered strong if 8 characters length or more 1 digit or more 1 uppercase letter or more 1 lowercase letter or more 1 symbol (excluding whitespace characters) ...
[ "def", "_check_password", "(", "password", ")", ":", "# Check the length.", "length_error", "=", "len", "(", "password", ")", "<", "8", "# Search for digits.", "digit_error", "=", "re", ".", "search", "(", "r'\\d'", ",", "password", ")", "is", "None", "# Searc...
Check the strength of a password. A password is considered strong if 8 characters length or more 1 digit or more 1 uppercase letter or more 1 lowercase letter or more 1 symbol (excluding whitespace characters) or more Parameters ------...
[ "Check", "the", "strength", "of", "a", "password", ".", "A", "password", "is", "considered", "strong", "if", "8", "characters", "length", "or", "more", "1", "digit", "or", "more", "1", "uppercase", "letter", "or", "more", "1", "lowercase", "letter", "or", ...
python
train
google/grr
grr/server/grr_response_server/check_lib/checks.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/check_lib/checks.py#L785-L800
def LoadChecksFromFiles(file_paths, overwrite_if_exists=True): """Load the checks defined in the specified files.""" loaded = [] for file_path in file_paths: configs = LoadConfigsFromFile(file_path) for conf in itervalues(configs): check = Check(**conf) # Validate will raise if the check doesn...
[ "def", "LoadChecksFromFiles", "(", "file_paths", ",", "overwrite_if_exists", "=", "True", ")", ":", "loaded", "=", "[", "]", "for", "file_path", "in", "file_paths", ":", "configs", "=", "LoadConfigsFromFile", "(", "file_path", ")", "for", "conf", "in", "iterva...
Load the checks defined in the specified files.
[ "Load", "the", "checks", "defined", "in", "the", "specified", "files", "." ]
python
train
nutechsoftware/alarmdecoder
alarmdecoder/decoder.py
https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/decoder.py#L356-L377
def fault_zone(self, zone, simulate_wire_problem=False): """ Faults a zone if we are emulating a zone expander. :param zone: zone to fault :type zone: int :param simulate_wire_problem: Whether or not to simulate a wire fault :type simulate_wire_problem: bool """ ...
[ "def", "fault_zone", "(", "self", ",", "zone", ",", "simulate_wire_problem", "=", "False", ")", ":", "# Allow ourselves to also be passed an address/channel combination", "# for zone expanders.", "#", "# Format (expander index, channel)", "if", "isinstance", "(", "zone", ",",...
Faults a zone if we are emulating a zone expander. :param zone: zone to fault :type zone: int :param simulate_wire_problem: Whether or not to simulate a wire fault :type simulate_wire_problem: bool
[ "Faults", "a", "zone", "if", "we", "are", "emulating", "a", "zone", "expander", "." ]
python
train
pymupdf/PyMuPDF
fitz/fitz.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2605-L2616
def addStampAnnot(self, rect, stamp=0): """Add a 'rubber stamp' in a rectangle.""" CheckParent(self) val = _fitz.Page_addStampAnnot(self, rect, stamp) if not val: return val.thisown = True val.parent = weakref.proxy(self) self._annot_refs[id(val)] = val ...
[ "def", "addStampAnnot", "(", "self", ",", "rect", ",", "stamp", "=", "0", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addStampAnnot", "(", "self", ",", "rect", ",", "stamp", ")", "if", "not", "val", ":", "return", "val"...
Add a 'rubber stamp' in a rectangle.
[ "Add", "a", "rubber", "stamp", "in", "a", "rectangle", "." ]
python
train
sffjunkie/astral
src/astral.py
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L950-L989
def dusk(self, date=None, local=True, use_elevation=True): """Calculates the dusk time (the time in the evening when the sun is a certain number of degrees below the horizon. By default this is 6 degrees but can be changed by setting the :attr:`solar_depression` property.) :para...
[ "def", "dusk", "(", "self", ",", "date", "=", "None", ",", "local", "=", "True", ",", "use_elevation", "=", "True", ")", ":", "if", "local", "and", "self", ".", "timezone", "is", "None", ":", "raise", "ValueError", "(", "\"Local time requested but Location...
Calculates the dusk time (the time in the evening when the sun is a certain number of degrees below the horizon. By default this is 6 degrees but can be changed by setting the :attr:`solar_depression` property.) :param date: The date for which to calculate the dusk time. ...
[ "Calculates", "the", "dusk", "time", "(", "the", "time", "in", "the", "evening", "when", "the", "sun", "is", "a", "certain", "number", "of", "degrees", "below", "the", "horizon", ".", "By", "default", "this", "is", "6", "degrees", "but", "can", "be", "...
python
train
quantopian/trading_calendars
trading_calendars/calendar_utils.py
https://github.com/quantopian/trading_calendars/blob/951711c82c8a2875c09e96e2979faaf8734fb4df/trading_calendars/calendar_utils.py#L257-L285
def resolve_alias(self, name): """ Resolve a calendar alias for retrieval. Parameters ---------- name : str The name of the requested calendar. Returns ------- canonical_name : str The real name of the calendar to create/return. ...
[ "def", "resolve_alias", "(", "self", ",", "name", ")", ":", "seen", "=", "[", "]", "while", "name", "in", "self", ".", "_aliases", ":", "seen", ".", "append", "(", "name", ")", "name", "=", "self", ".", "_aliases", "[", "name", "]", "# This is O(N **...
Resolve a calendar alias for retrieval. Parameters ---------- name : str The name of the requested calendar. Returns ------- canonical_name : str The real name of the calendar to create/return.
[ "Resolve", "a", "calendar", "alias", "for", "retrieval", "." ]
python
train
peeringdb/peeringdb-py
peeringdb/config.py
https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L59-L68
def read_config(conf_dir=DEFAULT_CONFIG_DIR): "Find and read config file for a directory, return None if not found." conf_path = os.path.expanduser(conf_dir) if not os.path.exists(conf_path): # only throw if not default if conf_dir != DEFAULT_CONFIG_DIR: raise IOError("Config di...
[ "def", "read_config", "(", "conf_dir", "=", "DEFAULT_CONFIG_DIR", ")", ":", "conf_path", "=", "os", ".", "path", ".", "expanduser", "(", "conf_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "conf_path", ")", ":", "# only throw if not default"...
Find and read config file for a directory, return None if not found.
[ "Find", "and", "read", "config", "file", "for", "a", "directory", "return", "None", "if", "not", "found", "." ]
python
train
google/apitools
apitools/base/py/credentials_lib.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/credentials_lib.py#L643-L668
def LockedWrite(self, cache_data): """Acquire an interprocess lock and write a string. This method safely acquires the locks then writes a string to the cache file. If the string is written successfully the function will return True, if the write fails for any reason it will ret...
[ "def", "LockedWrite", "(", "self", ",", "cache_data", ")", ":", "if", "isinstance", "(", "cache_data", ",", "six", ".", "text_type", ")", ":", "cache_data", "=", "cache_data", ".", "encode", "(", "encoding", "=", "self", ".", "_encoding", ")", "with", "s...
Acquire an interprocess lock and write a string. This method safely acquires the locks then writes a string to the cache file. If the string is written successfully the function will return True, if the write fails for any reason it will return False. Args: cache_data...
[ "Acquire", "an", "interprocess", "lock", "and", "write", "a", "string", "." ]
python
train
tensorflow/tensorboard
tensorboard/compat/tensorflow_stub/io/gfile.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L184-L229
def read(self, filename, binary_mode=False, size=None, offset=None): """Reads contents of a file to a string. Args: filename: string, a path binary_mode: bool, read as binary if True, otherwise text size: int, number of bytes or characters to read, otherwise ...
[ "def", "read", "(", "self", ",", "filename", ",", "binary_mode", "=", "False", ",", "size", "=", "None", ",", "offset", "=", "None", ")", ":", "s3", "=", "boto3", ".", "resource", "(", "\"s3\"", ")", "bucket", ",", "path", "=", "self", ".", "bucket...
Reads contents of a file to a string. Args: filename: string, a path binary_mode: bool, read as binary if True, otherwise text size: int, number of bytes or characters to read, otherwise read all the contents of the file from the offset offset: in...
[ "Reads", "contents", "of", "a", "file", "to", "a", "string", "." ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/reedsolomon/reedsolo.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/reedsolomon/reedsolo.py#L507-L566
def rs_find_error_locator(synd, nsym, erase_loc=None, erase_count=0): '''Find error/errata locator and evaluator polynomials with Berlekamp-Massey algorithm''' # The idea is that BM will iteratively estimate the error locator polynomial. # To do this, it will compute a Discrepancy term called Delta, which w...
[ "def", "rs_find_error_locator", "(", "synd", ",", "nsym", ",", "erase_loc", "=", "None", ",", "erase_count", "=", "0", ")", ":", "# The idea is that BM will iteratively estimate the error locator polynomial.", "# To do this, it will compute a Discrepancy term called Delta, which wi...
Find error/errata locator and evaluator polynomials with Berlekamp-Massey algorithm
[ "Find", "error", "/", "errata", "locator", "and", "evaluator", "polynomials", "with", "Berlekamp", "-", "Massey", "algorithm" ]
python
train
deepmind/sonnet
sonnet/python/modules/util.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L509-L531
def _format_device(var): """Returns the device with an annotation specifying `ResourceVariable`. "legacy" means a normal tf.Variable while "resource" means a ResourceVariable. For example: `(legacy)` `(resource)` `/job:learner/task:0/device:CPU:* (legacy)` `/job:learner/task:0/device:CPU:* (resource)` ...
[ "def", "_format_device", "(", "var", ")", ":", "if", "var", ".", "dtype", ".", "name", ".", "endswith", "(", "\"_ref\"", ")", ":", "resource_var_annotation", "=", "\"(legacy)\"", "else", ":", "resource_var_annotation", "=", "\"(resource)\"", "if", "var", ".", ...
Returns the device with an annotation specifying `ResourceVariable`. "legacy" means a normal tf.Variable while "resource" means a ResourceVariable. For example: `(legacy)` `(resource)` `/job:learner/task:0/device:CPU:* (legacy)` `/job:learner/task:0/device:CPU:* (resource)` Args: var: The Tensorflo...
[ "Returns", "the", "device", "with", "an", "annotation", "specifying", "ResourceVariable", "." ]
python
train
adaptive-learning/proso-apps
proso_concepts/models.py
https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_concepts/models.py#L250-L300
def recalculate_concepts(self, concepts, lang=None): """ Recalculated given concepts for given users Args: concepts (dict): user id (int -> set of concepts to recalculate) lang(Optional[str]): language used to get items in all concepts (cached). Defaults ...
[ "def", "recalculate_concepts", "(", "self", ",", "concepts", ",", "lang", "=", "None", ")", ":", "if", "len", "(", "concepts", ")", "==", "0", ":", "return", "if", "lang", "is", "None", ":", "items", "=", "Concept", ".", "objects", ".", "get_concept_it...
Recalculated given concepts for given users Args: concepts (dict): user id (int -> set of concepts to recalculate) lang(Optional[str]): language used to get items in all concepts (cached). Defaults to None, in that case are get items only in used concepts
[ "Recalculated", "given", "concepts", "for", "given", "users" ]
python
train
rlabbe/filterpy
filterpy/stats/stats.py
https://github.com/rlabbe/filterpy/blob/8123214de798ffb63db968bb0b9492ee74e77950/filterpy/stats/stats.py#L63-L108
def mahalanobis(x, mean, cov): """ Computes the Mahalanobis distance between the state vector x from the Gaussian `mean` with covariance `cov`. This can be thought as the number of standard deviations x is from the mean, i.e. a return value of 3 means x is 3 std from mean. Parameters ------...
[ "def", "mahalanobis", "(", "x", ",", "mean", ",", "cov", ")", ":", "x", "=", "_validate_vector", "(", "x", ")", "mean", "=", "_validate_vector", "(", "mean", ")", "if", "x", ".", "shape", "!=", "mean", ".", "shape", ":", "raise", "ValueError", "(", ...
Computes the Mahalanobis distance between the state vector x from the Gaussian `mean` with covariance `cov`. This can be thought as the number of standard deviations x is from the mean, i.e. a return value of 3 means x is 3 std from mean. Parameters ---------- x : (N,) array_like, or float ...
[ "Computes", "the", "Mahalanobis", "distance", "between", "the", "state", "vector", "x", "from", "the", "Gaussian", "mean", "with", "covariance", "cov", ".", "This", "can", "be", "thought", "as", "the", "number", "of", "standard", "deviations", "x", "is", "fr...
python
train
mitsei/dlkit
dlkit/json_/resource/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/sessions.py#L2992-L3009
def has_child_bins(self, bin_id): """Tests if a bin has any children. arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if the ``bin_id`` has children, ``false`` otherwise raise: NotFound - ``bin_id`` not found raise: NullArgument - ...
[ "def", "has_child_bins", "(", "self", ",", "bin_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.has_child_bins", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session", ".", "has_...
Tests if a bin has any children. arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if the ``bin_id`` has children, ``false`` otherwise raise: NotFound - ``bin_id`` not found raise: NullArgument - ``bin_id`` is ``null`` raise: Operat...
[ "Tests", "if", "a", "bin", "has", "any", "children", "." ]
python
train
materialsproject/pymatgen
pymatgen/analysis/molecule_structure_comparator.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/molecule_structure_comparator.py#L103-L113
def are_equal(self, mol1, mol2): """ Compare the bond table of the two molecules. Args: mol1: first molecule. pymatgen Molecule object. mol2: second moleculs. pymatgen Molecule objec. """ b1 = set(self._get_bonds(mol1)) b2 = set(self._get_bonds(mo...
[ "def", "are_equal", "(", "self", ",", "mol1", ",", "mol2", ")", ":", "b1", "=", "set", "(", "self", ".", "_get_bonds", "(", "mol1", ")", ")", "b2", "=", "set", "(", "self", ".", "_get_bonds", "(", "mol2", ")", ")", "return", "b1", "==", "b2" ]
Compare the bond table of the two molecules. Args: mol1: first molecule. pymatgen Molecule object. mol2: second moleculs. pymatgen Molecule objec.
[ "Compare", "the", "bond", "table", "of", "the", "two", "molecules", "." ]
python
train
mitsei/dlkit
dlkit/aws_adapter/repository/aws_utils.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/aws_adapter/repository/aws_utils.py#L12-L31
def get_aws_s3_handle(config_map): """Convenience function for getting AWS S3 objects Added by cjshaw@mit.edu, Jan 9, 2015 Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and added support for Configuration May 25, 2017: Switch to boto3 """ url = 'https://' + config_map['s3_b...
[ "def", "get_aws_s3_handle", "(", "config_map", ")", ":", "url", "=", "'https://'", "+", "config_map", "[", "'s3_bucket'", "]", "+", "'.s3.amazonaws.com'", "if", "not", "AWS_CLIENT", ".", "is_aws_s3_client_set", "(", ")", ":", "client", "=", "boto3", ".", "clie...
Convenience function for getting AWS S3 objects Added by cjshaw@mit.edu, Jan 9, 2015 Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and added support for Configuration May 25, 2017: Switch to boto3
[ "Convenience", "function", "for", "getting", "AWS", "S3", "objects" ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py#L4538-L4553
def get_stp_mst_detail_output_msti_port_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
[ "def", "get_stp_mst_detail_output_msti_port_interface_type", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_stp_mst_detail", "=", "ET", ".", "Element", "(", "\"get_stp_mst_detail\"", ")", "config",...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
xtrementl/focus
focus/environment/cli.py
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/cli.py#L194-L209
def _get_plugin_parser(self, plugin_obj): """ Creates a plugin argument parser. `plugin_obj` ``Plugin`` object. Returns ``FocusArgParser`` object. """ prog_name = 'focus ' + plugin_obj.command desc = (plugin_obj.__doc__ or '').strip() ...
[ "def", "_get_plugin_parser", "(", "self", ",", "plugin_obj", ")", ":", "prog_name", "=", "'focus '", "+", "plugin_obj", ".", "command", "desc", "=", "(", "plugin_obj", ".", "__doc__", "or", "''", ")", ".", "strip", "(", ")", "parser", "=", "FocusArgParser"...
Creates a plugin argument parser. `plugin_obj` ``Plugin`` object. Returns ``FocusArgParser`` object.
[ "Creates", "a", "plugin", "argument", "parser", "." ]
python
train
pantsbuild/pants
src/python/pants/build_graph/build_graph.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/build_graph/build_graph.py#L115-L122
def apply_injectables(self, targets): """Given an iterable of `Target` instances, apply their transitive injectables.""" target_types = {type(t) for t in targets} target_subsystem_deps = {s for s in itertools.chain(*(t.subsystems() for t in target_types))} for subsystem in target_subsystem_deps: #...
[ "def", "apply_injectables", "(", "self", ",", "targets", ")", ":", "target_types", "=", "{", "type", "(", "t", ")", "for", "t", "in", "targets", "}", "target_subsystem_deps", "=", "{", "s", "for", "s", "in", "itertools", ".", "chain", "(", "*", "(", ...
Given an iterable of `Target` instances, apply their transitive injectables.
[ "Given", "an", "iterable", "of", "Target", "instances", "apply", "their", "transitive", "injectables", "." ]
python
train
saltstack/salt
salt/states/ipset.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipset.py#L312-L351
def flush(name, family='ipv4', **kwargs): ''' .. versionadded:: 2014.7.0 Flush current ipset set family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} set_check = __salt__['ipset.check...
[ "def", "flush", "(", "name", ",", "family", "=", "'ipv4'", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "set_check", "=...
.. versionadded:: 2014.7.0 Flush current ipset set family Networking family, either ipv4 or ipv6
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
python
train
lcharleux/argiope
argiope/mesh.py
https://github.com/lcharleux/argiope/blob/8170e431362dc760589f7d141090fd133dece259/argiope/mesh.py#L1153-L1179
def _make_conn(shape): """ Connectivity builder using Numba for speed boost. """ shape = np.array(shape) Ne = shape.prod() if len(shape) == 2: nx, ny = np.array(shape) +1 conn = np.zeros((Ne, 4), dtype = np.int32) counter = 0 pattern = np.array([0,1,1+nx,nx]) ...
[ "def", "_make_conn", "(", "shape", ")", ":", "shape", "=", "np", ".", "array", "(", "shape", ")", "Ne", "=", "shape", ".", "prod", "(", ")", "if", "len", "(", "shape", ")", "==", "2", ":", "nx", ",", "ny", "=", "np", ".", "array", "(", "shape...
Connectivity builder using Numba for speed boost.
[ "Connectivity", "builder", "using", "Numba", "for", "speed", "boost", "." ]
python
test
MartinThoma/hwrt
bin/convert.py
https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/bin/convert.py#L28-L33
def _str2array(d): """ Reconstructs a numpy array from a plain-text string """ if type(d) == list: return np.asarray([_str2array(s) for s in d]) ins = StringIO(d) return np.loadtxt(ins)
[ "def", "_str2array", "(", "d", ")", ":", "if", "type", "(", "d", ")", "==", "list", ":", "return", "np", ".", "asarray", "(", "[", "_str2array", "(", "s", ")", "for", "s", "in", "d", "]", ")", "ins", "=", "StringIO", "(", "d", ")", "return", ...
Reconstructs a numpy array from a plain-text string
[ "Reconstructs", "a", "numpy", "array", "from", "a", "plain", "-", "text", "string" ]
python
train
dereneaton/ipyrad
ipyrad/assemble/cluster_across.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_across.py#L1214-L1237
def inserted_indels(indels, ocatg): """ inserts indels into the catg array """ ## return copy with indels inserted newcatg = np.zeros(ocatg.shape, dtype=np.uint32) ## iterate over loci and make extensions for indels for iloc in xrange(ocatg.shape[0]): ## get indels indices i...
[ "def", "inserted_indels", "(", "indels", ",", "ocatg", ")", ":", "## return copy with indels inserted", "newcatg", "=", "np", ".", "zeros", "(", "ocatg", ".", "shape", ",", "dtype", "=", "np", ".", "uint32", ")", "## iterate over loci and make extensions for indels"...
inserts indels into the catg array
[ "inserts", "indels", "into", "the", "catg", "array" ]
python
valid
pywbem/pywbem
try/run_central_instances.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L1216-L1236
def get_profiles_in_svr(nickname, server, all_profiles_dict, org_vm, add_error_list=False): """ Test all profiles in server.profiles to determine if profile is in the all_profiles_dict. Returns list of profiles in the profile_dict and in the defined server. If add_error_list...
[ "def", "get_profiles_in_svr", "(", "nickname", ",", "server", ",", "all_profiles_dict", ",", "org_vm", ",", "add_error_list", "=", "False", ")", ":", "profiles_in_dict", "=", "[", "]", "for", "profile_inst", "in", "server", ".", "profiles", ":", "pn", "=", "...
Test all profiles in server.profiles to determine if profile is in the all_profiles_dict. Returns list of profiles in the profile_dict and in the defined server. If add_error_list is True, it also adds profiles not found to PROFILES_WITH_NO_DEFINITIONS.
[ "Test", "all", "profiles", "in", "server", ".", "profiles", "to", "determine", "if", "profile", "is", "in", "the", "all_profiles_dict", "." ]
python
train
farzadghanei/statsd-metrics
statsdmetrics/client/__init__.py
https://github.com/farzadghanei/statsd-metrics/blob/153ff37b79777f208e49bb9d3fb737ba52b99f98/statsdmetrics/client/__init__.py#L186-L199
def gauge(self, name, value, rate=1): # type: (str, float, float) -> None """Send a Gauge metric with the specified value""" if self._should_send_metric(name, rate): if not is_numeric(value): value = float(value) self._request( Gauge( ...
[ "def", "gauge", "(", "self", ",", "name", ",", "value", ",", "rate", "=", "1", ")", ":", "# type: (str, float, float) -> None", "if", "self", ".", "_should_send_metric", "(", "name", ",", "rate", ")", ":", "if", "not", "is_numeric", "(", "value", ")", ":...
Send a Gauge metric with the specified value
[ "Send", "a", "Gauge", "metric", "with", "the", "specified", "value" ]
python
test
djgagne/hagelslag
hagelslag/evaluation/NeighborEvaluator.py
https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/evaluation/NeighborEvaluator.py#L129-L170
def evaluate_hourly_forecasts(self): """ Calculates ROC curves and Reliability scores for each forecast hour. Returns: A pandas DataFrame containing forecast metadata as well as DistributedROC and Reliability objects. """ score_columns = ["Run_Date", "Forecast_Hour",...
[ "def", "evaluate_hourly_forecasts", "(", "self", ")", ":", "score_columns", "=", "[", "\"Run_Date\"", ",", "\"Forecast_Hour\"", ",", "\"Ensemble Name\"", ",", "\"Model_Name\"", ",", "\"Forecast_Variable\"", ",", "\"Neighbor_Radius\"", ",", "\"Smoothing_Radius\"", ",", "...
Calculates ROC curves and Reliability scores for each forecast hour. Returns: A pandas DataFrame containing forecast metadata as well as DistributedROC and Reliability objects.
[ "Calculates", "ROC", "curves", "and", "Reliability", "scores", "for", "each", "forecast", "hour", "." ]
python
train
brocade/pynos
pynos/versions/base/yang/ietf_netconf.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/ietf_netconf.py#L522-L533
def commit_input_persist_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") commit = ET.Element("commit") config = commit input = ET.SubElement(commit, "input") persist_id = ET.SubElement(input, "persist-id") persist_id.text = kwa...
[ "def", "commit_input_persist_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "commit", "=", "ET", ".", "Element", "(", "\"commit\"", ")", "config", "=", "commit", "input", "=", "ET", "."...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
F5Networks/f5-common-python
f5/bigip/tm/sys/application.py
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/application.py#L182-L222
def exists(self, **kwargs): '''Check for the existence of the named object on the BIG-IP Override of resource.Resource exists() to build proper URI unique to service resources. Sends an HTTP GET to the URI of the named object and if it fails with a :exc:~requests.HTTPError` exc...
[ "def", "exists", "(", "self", ",", "*", "*", "kwargs", ")", ":", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "self", ".", "_check_load_parameters", "(", "*", "*", "kwargs", ")", "kwargs", "[", "'uri_as_parts'", "]", ...
Check for the existence of the named object on the BIG-IP Override of resource.Resource exists() to build proper URI unique to service resources. Sends an HTTP GET to the URI of the named object and if it fails with a :exc:~requests.HTTPError` exception it checks the exception for ...
[ "Check", "for", "the", "existence", "of", "the", "named", "object", "on", "the", "BIG", "-", "IP" ]
python
train
camsci/meteor-pi
src/pythonModules/meteorpi_db/meteorpi_db/__init__.py
https://github.com/camsci/meteor-pi/blob/7b01527650bd1b2b76d6f364e8122e25b8812c8d/src/pythonModules/meteorpi_db/meteorpi_db/__init__.py#L749-L759
def has_obsgroup_id(self, group_id): """ Check for the presence of the given group_id :param string group_id: The group ID :return: True if we have a :class:`meteorpi_model.ObservationGroup` with this Id, False otherwise """ self.con.execute('SELE...
[ "def", "has_obsgroup_id", "(", "self", ",", "group_id", ")", ":", "self", ".", "con", ".", "execute", "(", "'SELECT 1 FROM archive_obs_groups WHERE publicId = %s'", ",", "(", "group_id", ",", ")", ")", "return", "len", "(", "self", ".", "con", ".", "fetchall",...
Check for the presence of the given group_id :param string group_id: The group ID :return: True if we have a :class:`meteorpi_model.ObservationGroup` with this Id, False otherwise
[ "Check", "for", "the", "presence", "of", "the", "given", "group_id" ]
python
train
OpenTreeOfLife/peyotl
peyotl/nexson_syntax/helper.py
https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_syntax/helper.py#L236-L246
def _python_instance_to_nexml_meta_datatype(v): """Returns 'xsd:string' or a more specific type for a <meta datatype="XYZ"... syntax using introspection. """ if isinstance(v, bool): return 'xsd:boolean' if is_int_type(v): return 'xsd:int' if isinstance(v, float): return '...
[ "def", "_python_instance_to_nexml_meta_datatype", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "bool", ")", ":", "return", "'xsd:boolean'", "if", "is_int_type", "(", "v", ")", ":", "return", "'xsd:int'", "if", "isinstance", "(", "v", ",", "float", ...
Returns 'xsd:string' or a more specific type for a <meta datatype="XYZ"... syntax using introspection.
[ "Returns", "xsd", ":", "string", "or", "a", "more", "specific", "type", "for", "a", "<meta", "datatype", "=", "XYZ", "...", "syntax", "using", "introspection", "." ]
python
train
ubyssey/dispatch
dispatch/admin/urls.py
https://github.com/ubyssey/dispatch/blob/8da6084fe61726f20e9cf675190480cfc45ee764/dispatch/admin/urls.py#L8-L16
def admin(request): """Render HTML entry point for manager app.""" context = { 'api_url': settings.API_URL, 'app_js_bundle': 'manager-%s.js' % dispatch.__version__, 'app_css_bundle': 'manager-%s.css' % dispatch.__version__ } return render_to_response('manager/index.html', co...
[ "def", "admin", "(", "request", ")", ":", "context", "=", "{", "'api_url'", ":", "settings", ".", "API_URL", ",", "'app_js_bundle'", ":", "'manager-%s.js'", "%", "dispatch", ".", "__version__", ",", "'app_css_bundle'", ":", "'manager-%s.css'", "%", "dispatch", ...
Render HTML entry point for manager app.
[ "Render", "HTML", "entry", "point", "for", "manager", "app", "." ]
python
test
HarveyHunt/i3situation
i3situation/core/plugin_manager.py
https://github.com/HarveyHunt/i3situation/blob/3160a21006fcc6961f240988874e228a5ec6f18e/i3situation/core/plugin_manager.py#L125-L142
def _compile_files(self): """ Compiles python plugin files in order to be processed by the loader. It compiles the plugins if they have been updated or haven't yet been compiled. """ for f in glob.glob(os.path.join(self.dir_path, '*.py')): # Check for compiled...
[ "def", "_compile_files", "(", "self", ")", ":", "for", "f", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "dir_path", ",", "'*.py'", ")", ")", ":", "# Check for compiled Python files that aren't in the __pycache__.", "if", ...
Compiles python plugin files in order to be processed by the loader. It compiles the plugins if they have been updated or haven't yet been compiled.
[ "Compiles", "python", "plugin", "files", "in", "order", "to", "be", "processed", "by", "the", "loader", ".", "It", "compiles", "the", "plugins", "if", "they", "have", "been", "updated", "or", "haven", "t", "yet", "been", "compiled", "." ]
python
train
obriencj/python-javatools
javatools/__init__.py
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1497-L1517
def get_identifier(self): """ For methods this is the return type, the name and the (non-pretty) argument descriptor. For fields it is simply the name. The return-type of methods is attached to the identifier when it is a bridge method, which can technically allow two methods ...
[ "def", "get_identifier", "(", "self", ")", ":", "ident", "=", "self", ".", "get_name", "(", ")", "if", "self", ".", "is_method", ":", "args", "=", "\",\"", ".", "join", "(", "self", ".", "get_arg_type_descriptors", "(", ")", ")", "if", "self", ".", "...
For methods this is the return type, the name and the (non-pretty) argument descriptor. For fields it is simply the name. The return-type of methods is attached to the identifier when it is a bridge method, which can technically allow two methods with the same name and argument type lis...
[ "For", "methods", "this", "is", "the", "return", "type", "the", "name", "and", "the", "(", "non", "-", "pretty", ")", "argument", "descriptor", ".", "For", "fields", "it", "is", "simply", "the", "name", "." ]
python
train
hannorein/rebound
rebound/simulation.py
https://github.com/hannorein/rebound/blob/bb0f814c98e629401acaab657cae2304b0e003f7/rebound/simulation.py#L1190-L1204
def particles_ascii(self, prec=8): """ Returns an ASCII string with all particles' masses, radii, positions and velocities. Parameters ---------- prec : int, optional Number of digits after decimal point. Default 8. """ s = "" for p in self.pa...
[ "def", "particles_ascii", "(", "self", ",", "prec", "=", "8", ")", ":", "s", "=", "\"\"", "for", "p", "in", "self", ".", "particles", ":", "s", "+=", "(", "(", "\"%%.%de \"", "%", "prec", ")", "*", "8", ")", "%", "(", "p", ".", "m", ",", "p",...
Returns an ASCII string with all particles' masses, radii, positions and velocities. Parameters ---------- prec : int, optional Number of digits after decimal point. Default 8.
[ "Returns", "an", "ASCII", "string", "with", "all", "particles", "masses", "radii", "positions", "and", "velocities", "." ]
python
train
CalebBell/fluids
fluids/fittings.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/fittings.py#L1230-L1364
def bend_rounded(Di, angle, fd=None, rc=None, bend_diameters=5.0, Re=None, roughness=0.0, L_unimpeded=None, method='Rennels'): r'''Returns loss coefficient for rounded bend in a pipe of diameter `Di`, `angle`, with a specified either radius of curvature `rc` or curvature defined by `bend_d...
[ "def", "bend_rounded", "(", "Di", ",", "angle", ",", "fd", "=", "None", ",", "rc", "=", "None", ",", "bend_diameters", "=", "5.0", ",", "Re", "=", "None", ",", "roughness", "=", "0.0", ",", "L_unimpeded", "=", "None", ",", "method", "=", "'Rennels'",...
r'''Returns loss coefficient for rounded bend in a pipe of diameter `Di`, `angle`, with a specified either radius of curvature `rc` or curvature defined by `bend_diameters`, Reynolds number `Re` and optionally pipe roughness, unimpeded length downstrean, and with the specified method. This calculation ...
[ "r", "Returns", "loss", "coefficient", "for", "rounded", "bend", "in", "a", "pipe", "of", "diameter", "Di", "angle", "with", "a", "specified", "either", "radius", "of", "curvature", "rc", "or", "curvature", "defined", "by", "bend_diameters", "Reynolds", "numbe...
python
train
log2timeline/dfvfs
dfvfs/vfs/vshadow_file_system.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/vshadow_file_system.py#L45-L74
def _Open(self, path_spec, mode='rb'): """Opens the file system object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the acces...
[ "def", "_Open", "(", "self", ",", "path_spec", ",", "mode", "=", "'rb'", ")", ":", "if", "not", "path_spec", ".", "HasParent", "(", ")", ":", "raise", "errors", ".", "PathSpecError", "(", "'Unsupported path specification without parent.'", ")", "file_object", ...
Opens the file system object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was denied. IOError: ...
[ "Opens", "the", "file", "system", "object", "defined", "by", "path", "specification", "." ]
python
train
happyleavesaoc/python-limitlessled
limitlessled/group/commands/legacy.py
https://github.com/happyleavesaoc/python-limitlessled/blob/70307c2bf8c91430a99579d2ad18b228ec7a8488/limitlessled/group/commands/legacy.py#L29-L42
def get_bytes(self, bridge): """ Gets the full command as bytes. :param bridge: The bridge, to which the command should be sent. """ if self.cmd_2 is not None: cmd = [self.cmd_1, self.cmd_2] else: cmd = [self.cmd_1, self.SUFFIX_BYTE] if br...
[ "def", "get_bytes", "(", "self", ",", "bridge", ")", ":", "if", "self", ".", "cmd_2", "is", "not", "None", ":", "cmd", "=", "[", "self", ".", "cmd_1", ",", "self", ".", "cmd_2", "]", "else", ":", "cmd", "=", "[", "self", ".", "cmd_1", ",", "sel...
Gets the full command as bytes. :param bridge: The bridge, to which the command should be sent.
[ "Gets", "the", "full", "command", "as", "bytes", ".", ":", "param", "bridge", ":", "The", "bridge", "to", "which", "the", "command", "should", "be", "sent", "." ]
python
train
BlueBrain/nat
nat/zotero_wrap.py
https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L233-L240
def reference_journal(self, index): """Return the reference journal name.""" # TODO Change the column name 'Journal' to an other? ref_type = self.reference_type(index) if ref_type == "journalArticle": return self.reference_data(index)["publicationTitle"] else: ...
[ "def", "reference_journal", "(", "self", ",", "index", ")", ":", "# TODO Change the column name 'Journal' to an other?", "ref_type", "=", "self", ".", "reference_type", "(", "index", ")", "if", "ref_type", "==", "\"journalArticle\"", ":", "return", "self", ".", "ref...
Return the reference journal name.
[ "Return", "the", "reference", "journal", "name", "." ]
python
train
danilobellini/audiolazy
audiolazy/lazy_synth.py
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L621-L654
def karplus_strong(freq, tau=2e4, memory=white_noise): """ Karplus-Strong "digitar" synthesis algorithm. Parameters ---------- freq : Frequency, in rad/sample. tau : Time decay (up to ``1/e``, or -8.686 dB), in number of samples. Defaults to 2e4. Be careful: using the default value will make du...
[ "def", "karplus_strong", "(", "freq", ",", "tau", "=", "2e4", ",", "memory", "=", "white_noise", ")", ":", "return", "comb", ".", "tau", "(", "2", "*", "pi", "/", "freq", ",", "tau", ")", ".", "linearize", "(", ")", "(", "zeros", "(", ")", ",", ...
Karplus-Strong "digitar" synthesis algorithm. Parameters ---------- freq : Frequency, in rad/sample. tau : Time decay (up to ``1/e``, or -8.686 dB), in number of samples. Defaults to 2e4. Be careful: using the default value will make duration different on each sample rate value. Use ``sHz`` if ...
[ "Karplus", "-", "Strong", "digitar", "synthesis", "algorithm", "." ]
python
train
openid/python-openid
openid/association.py
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L261-L297
def fromExpiresIn(cls, expires_in, handle, secret, assoc_type): """ This is an alternate constructor used by the OpenID consumer library to create associations. C{L{OpenIDStore <openid.store.interface.OpenIDStore>}} implementations shouldn't use this constructor. @para...
[ "def", "fromExpiresIn", "(", "cls", ",", "expires_in", ",", "handle", ",", "secret", ",", "assoc_type", ")", ":", "issued", "=", "int", "(", "time", ".", "time", "(", ")", ")", "lifetime", "=", "expires_in", "return", "cls", "(", "handle", ",", "secret...
This is an alternate constructor used by the OpenID consumer library to create associations. C{L{OpenIDStore <openid.store.interface.OpenIDStore>}} implementations shouldn't use this constructor. @param expires_in: This is the amount of time this association is good for, m...
[ "This", "is", "an", "alternate", "constructor", "used", "by", "the", "OpenID", "consumer", "library", "to", "create", "associations", ".", "C", "{", "L", "{", "OpenIDStore", "<openid", ".", "store", ".", "interface", ".", "OpenIDStore", ">", "}}", "implement...
python
train
liip/taxi
taxi/timesheet/parser.py
https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/parser.py#L292-L305
def extract_flags_from_text(self, text): """ Extract the flags from the given text and return a :class:`set` of flag values. See :class:`~taxi.timesheet.lines.Entry` for a list of existing flags. """ flags = set() reversed_flags_repr = {v: k for k, v in self.flags_repr.it...
[ "def", "extract_flags_from_text", "(", "self", ",", "text", ")", ":", "flags", "=", "set", "(", ")", "reversed_flags_repr", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "self", ".", "flags_repr", ".", "items", "(", ")", "}", "for", "flag_repr...
Extract the flags from the given text and return a :class:`set` of flag values. See :class:`~taxi.timesheet.lines.Entry` for a list of existing flags.
[ "Extract", "the", "flags", "from", "the", "given", "text", "and", "return", "a", ":", "class", ":", "set", "of", "flag", "values", ".", "See", ":", "class", ":", "~taxi", ".", "timesheet", ".", "lines", ".", "Entry", "for", "a", "list", "of", "existi...
python
train
NoviceLive/intellicoder
intellicoder/executables/elf.py
https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/executables/elf.py#L44-L52
def get_section_data(self, name): """Get the data of the section.""" logging.debug(_('Obtaining ELF section: %s'), name) section = self.binary.get_section_by_name(name) if section: return section.data() else: logging.error(_('Section no found: %s'), name) ...
[ "def", "get_section_data", "(", "self", ",", "name", ")", ":", "logging", ".", "debug", "(", "_", "(", "'Obtaining ELF section: %s'", ")", ",", "name", ")", "section", "=", "self", ".", "binary", ".", "get_section_by_name", "(", "name", ")", "if", "section...
Get the data of the section.
[ "Get", "the", "data", "of", "the", "section", "." ]
python
train
jlmadurga/permabots
permabots/views/api/hook.py
https://github.com/jlmadurga/permabots/blob/781a91702529a23fe7bc2aa84c5d88e961412466/permabots/views/api/hook.py#L106-L115
def get(self, request, bot_id, id, format=None): """ Get list of telegram recipients of a hook --- serializer: TelegramRecipientSerializer responseMessages: - code: 401 message: Not authenticated """ return super(TelegramRecipientList, se...
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "TelegramRecipientList", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "id", ",", "format", ")" ]
Get list of telegram recipients of a hook --- serializer: TelegramRecipientSerializer responseMessages: - code: 401 message: Not authenticated
[ "Get", "list", "of", "telegram", "recipients", "of", "a", "hook", "---", "serializer", ":", "TelegramRecipientSerializer", "responseMessages", ":", "-", "code", ":", "401", "message", ":", "Not", "authenticated" ]
python
train
pantsbuild/pants
src/python/pants/java/nailgun_executor.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/java/nailgun_executor.py#L228-L242
def ensure_connectable(self, nailgun): """Ensures that a nailgun client is connectable or raises NailgunError.""" attempt_count = 1 while 1: try: with closing(nailgun.try_connect()) as sock: logger.debug('Verified new ng server is connectable at {}'.format(sock.getpeername())) ...
[ "def", "ensure_connectable", "(", "self", ",", "nailgun", ")", ":", "attempt_count", "=", "1", "while", "1", ":", "try", ":", "with", "closing", "(", "nailgun", ".", "try_connect", "(", ")", ")", "as", "sock", ":", "logger", ".", "debug", "(", "'Verifi...
Ensures that a nailgun client is connectable or raises NailgunError.
[ "Ensures", "that", "a", "nailgun", "client", "is", "connectable", "or", "raises", "NailgunError", "." ]
python
train
Zaeb0s/loop-function
loopfunction/loopfunction.py
https://github.com/Zaeb0s/loop-function/blob/5999132aca5cf79b34e4ad5c05f9185712f1b583/loopfunction/loopfunction.py#L48-L61
def _loop(self, *args, **kwargs): """Loops the target function :param args: The args specified on initiation :param kwargs: The kwargs specified on initiation """ self.on_start(*self.on_start_args, **self.on_start_kwargs) try: while not self._stop_signal: ...
[ "def", "_loop", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "on_start", "(", "*", "self", ".", "on_start_args", ",", "*", "*", "self", ".", "on_start_kwargs", ")", "try", ":", "while", "not", "self", ".", "_stop_s...
Loops the target function :param args: The args specified on initiation :param kwargs: The kwargs specified on initiation
[ "Loops", "the", "target", "function" ]
python
train
siznax/wptools
wptools/wikidata.py
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L87-L93
def _pop_entities(self, limit=50): """ returns up to limit entities and pops them off the list """ pop = self.data['entities'][:limit] del self.data['entities'][:limit] return pop
[ "def", "_pop_entities", "(", "self", ",", "limit", "=", "50", ")", ":", "pop", "=", "self", ".", "data", "[", "'entities'", "]", "[", ":", "limit", "]", "del", "self", ".", "data", "[", "'entities'", "]", "[", ":", "limit", "]", "return", "pop" ]
returns up to limit entities and pops them off the list
[ "returns", "up", "to", "limit", "entities", "and", "pops", "them", "off", "the", "list" ]
python
train
bunq/sdk_python
bunq/sdk/security.py
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/security.py#L166-L179
def _add_header_client_encryption_key(api_context, key, custom_headers): """ :type api_context: bunq.sdk.context.ApiContext :type key: bytes :type custom_headers: dict[str, str] :rtype: None """ public_key_server = api_context.installation_context.public_key_server key_cipher = PKCS1_v...
[ "def", "_add_header_client_encryption_key", "(", "api_context", ",", "key", ",", "custom_headers", ")", ":", "public_key_server", "=", "api_context", ".", "installation_context", ".", "public_key_server", "key_cipher", "=", "PKCS1_v1_5_Cipher", ".", "new", "(", "public_...
:type api_context: bunq.sdk.context.ApiContext :type key: bytes :type custom_headers: dict[str, str] :rtype: None
[ ":", "type", "api_context", ":", "bunq", ".", "sdk", ".", "context", ".", "ApiContext", ":", "type", "key", ":", "bytes", ":", "type", "custom_headers", ":", "dict", "[", "str", "str", "]" ]
python
train
nivbend/mock-open
mock_open/mocks.py
https://github.com/nivbend/mock-open/blob/eb7c9484b8c0ed58ba81ad04f44974e3dfa1b023/mock_open/mocks.py#L77-L91
def set_properties(self, path, mode): """Set file's properties (name and mode). This function is also in charge of swapping between textual and binary streams. """ self.name = path self.mode = mode if 'b' in self.mode: if not isinstance(self.read_dat...
[ "def", "set_properties", "(", "self", ",", "path", ",", "mode", ")", ":", "self", ".", "name", "=", "path", "self", ".", "mode", "=", "mode", "if", "'b'", "in", "self", ".", "mode", ":", "if", "not", "isinstance", "(", "self", ".", "read_data", ","...
Set file's properties (name and mode). This function is also in charge of swapping between textual and binary streams.
[ "Set", "file", "s", "properties", "(", "name", "and", "mode", ")", "." ]
python
train
eng-tools/sfsimodels
sfsimodels/models/soils.py
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/models/soils.py#L1197-L1214
def shear_vel_at_depth(self, y_c): """ Get the shear wave velocity at a depth. :param y_c: float, depth from surface :return: """ sl = self.get_soil_at_depth(y_c) if y_c <= self.gwl: saturation = False else: saturation = True ...
[ "def", "shear_vel_at_depth", "(", "self", ",", "y_c", ")", ":", "sl", "=", "self", ".", "get_soil_at_depth", "(", "y_c", ")", "if", "y_c", "<=", "self", ".", "gwl", ":", "saturation", "=", "False", "else", ":", "saturation", "=", "True", "if", "hasattr...
Get the shear wave velocity at a depth. :param y_c: float, depth from surface :return:
[ "Get", "the", "shear", "wave", "velocity", "at", "a", "depth", "." ]
python
train
mlaprise/genSpline
genSpline/genSpline.py
https://github.com/mlaprise/genSpline/blob/cedfb45bd6afde47042dd71292549493f27cd136/genSpline/genSpline.py#L52-L70
def gaussianPulse(t, FWHM, t0, P0 = 1.0, m = 1, C = 0): """ Geneate a gaussian/supergaussiance envelope pulse * field_amp: output gaussian pulse envellope (amplitude). * t: vector of times at which to compute u * t0: center of pulse (default = 0) * FWHM: full-width at half-intensity of pulse ...
[ "def", "gaussianPulse", "(", "t", ",", "FWHM", ",", "t0", ",", "P0", "=", "1.0", ",", "m", "=", "1", ",", "C", "=", "0", ")", ":", "t_zero", "=", "FWHM", "/", "sqrt", "(", "4.0", "*", "log", "(", "2.0", ")", ")", "amp", "=", "sqrt", "(", ...
Geneate a gaussian/supergaussiance envelope pulse * field_amp: output gaussian pulse envellope (amplitude). * t: vector of times at which to compute u * t0: center of pulse (default = 0) * FWHM: full-width at half-intensity of pulse (default = 1) * P0: peak intensity of the pulse @ t=t0 ...
[ "Geneate", "a", "gaussian", "/", "supergaussiance", "envelope", "pulse" ]
python
train
opengridcc/opengrid
opengrid/library/plotting.py
https://github.com/opengridcc/opengrid/blob/69b8da3c8fcea9300226c45ef0628cd6d4307651/opengrid/library/plotting.py#L128-L177
def boxplot(df, plot_mean=False, plot_ids=None, title=None, xlabel=None, ylabel=None): """ Plot boxplots Plot the boxplots of a dataframe in time Parameters ---------- df: Pandas Dataframe Every collumn is a timeseries plot_mean: bool Wether or not to plot the means plo...
[ "def", "boxplot", "(", "df", ",", "plot_mean", "=", "False", ",", "plot_ids", "=", "None", ",", "title", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ")", ":", "df", "=", "df", ".", "applymap", "(", "float", ")", "descriptio...
Plot boxplots Plot the boxplots of a dataframe in time Parameters ---------- df: Pandas Dataframe Every collumn is a timeseries plot_mean: bool Wether or not to plot the means plot_ids: [str] List of id's to plot Returns ------- matplotlib figure
[ "Plot", "boxplots" ]
python
train
onnx/onnxmltools
onnxmltools/convert/coreml/shape_calculators/Classifier.py
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/shape_calculators/Classifier.py#L13-L66
def calculate_traditional_classifier_output_shapes(operator): ''' For classifiers, allowed input/output patterns are 1. [N, C_1], ..., [N, C_n] ---> [N], Sequence of Map 2. [N, C_1], ..., [N, C_n] ---> [N] For regressors, allowed input/output patterns are 1. [N, C_1], ..., [N, C_n] ...
[ "def", "calculate_traditional_classifier_output_shapes", "(", "operator", ")", ":", "check_input_and_output_numbers", "(", "operator", ",", "input_count_range", "=", "[", "1", ",", "None", "]", ",", "output_count_range", "=", "[", "1", ",", "2", "]", ")", "check_i...
For classifiers, allowed input/output patterns are 1. [N, C_1], ..., [N, C_n] ---> [N], Sequence of Map 2. [N, C_1], ..., [N, C_n] ---> [N] For regressors, allowed input/output patterns are 1. [N, C_1], ..., [N, C_n] ---> [N, 1] Core ML classifiers and regressors support multiple input...
[ "For", "classifiers", "allowed", "input", "/", "output", "patterns", "are", "1", ".", "[", "N", "C_1", "]", "...", "[", "N", "C_n", "]", "---", ">", "[", "N", "]", "Sequence", "of", "Map", "2", ".", "[", "N", "C_1", "]", "...", "[", "N", "C_n",...
python
train
ska-sa/katcp-python
katcp/kattypes.py
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L586-L605
def unpack(self, value): """Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value. """ # Wrap errors in Fa...
[ "def", "unpack", "(", "self", ",", "value", ")", ":", "# Wrap errors in FailReplies with information identifying the parameter", "try", ":", "return", "self", ".", "_kattype", ".", "unpack", "(", "value", ",", "self", ".", "major", ")", "except", "ValueError", ","...
Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value.
[ "Unpack", "the", "parameter", "using", "its", "kattype", "." ]
python
train
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L303-L314
def sync_to_peers(peer_interface, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync all hosts to an specific path The type of group is integer, it allows user has permissions to operate a directory have a different group id with the user id. Propagates except...
[ "def", "sync_to_peers", "(", "peer_interface", ",", "user", ",", "paths", "=", "None", ",", "verbose", "=", "False", ",", "cmd", "=", "None", ",", "gid", "=", "None", ",", "fatal", "=", "False", ")", ":", "if", "paths", ":", "for", "host", "in", "c...
Sync all hosts to an specific path The type of group is integer, it allows user has permissions to operate a directory have a different group id with the user id. Propagates exception if any operation fails and fatal=True.
[ "Sync", "all", "hosts", "to", "an", "specific", "path" ]
python
train
caseyjlaw/rtpipe
rtpipe/interactive.py
https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/interactive.py#L548-L572
def calcinds(data, threshold, ignoret=None): """ Find indexes for data above (or below) given threshold. """ inds = [] for i in range(len(data['time'])): snr = data['snrs'][i] time = data['time'][i] if (threshold >= 0 and snr > threshold): if ignoret: inc...
[ "def", "calcinds", "(", "data", ",", "threshold", ",", "ignoret", "=", "None", ")", ":", "inds", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "data", "[", "'time'", "]", ")", ")", ":", "snr", "=", "data", "[", "'snrs'", "]", "[", ...
Find indexes for data above (or below) given threshold.
[ "Find", "indexes", "for", "data", "above", "(", "or", "below", ")", "given", "threshold", "." ]
python
train
bjmorgan/lattice_mc
lattice_mc/cluster.py
https://github.com/bjmorgan/lattice_mc/blob/7fa7be85f2f23a2d8dfd0830ecdb89d0dbf2bfd5/lattice_mc/cluster.py#L101-L113
def remove_sites_from_neighbours( self, remove_labels ): """ Removes sites from the set of neighbouring sites if these have labels in remove_labels. Args: Remove_labels (List) or (Str): List of Site labels to be removed from the cluster neighbour set. Returns: N...
[ "def", "remove_sites_from_neighbours", "(", "self", ",", "remove_labels", ")", ":", "if", "type", "(", "remove_labels", ")", "is", "str", ":", "remove_labels", "=", "[", "remove_labels", "]", "self", ".", "neighbours", "=", "set", "(", "n", "for", "n", "in...
Removes sites from the set of neighbouring sites if these have labels in remove_labels. Args: Remove_labels (List) or (Str): List of Site labels to be removed from the cluster neighbour set. Returns: None
[ "Removes", "sites", "from", "the", "set", "of", "neighbouring", "sites", "if", "these", "have", "labels", "in", "remove_labels", "." ]
python
train
gem/oq-engine
openquake/hmtk/seismicity/catalogue.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/catalogue.py#L395-L429
def get_depth_distribution(self, depth_bins, normalisation=False, bootstrap=None): ''' Gets the depth distribution of the earthquake catalogue to return a single histogram. Depths may be normalised. If uncertainties are found in the catalogue the distrbutio...
[ "def", "get_depth_distribution", "(", "self", ",", "depth_bins", ",", "normalisation", "=", "False", ",", "bootstrap", "=", "None", ")", ":", "if", "len", "(", "self", ".", "data", "[", "'depth'", "]", ")", "==", "0", ":", "# If depth information is missing"...
Gets the depth distribution of the earthquake catalogue to return a single histogram. Depths may be normalised. If uncertainties are found in the catalogue the distrbution may be bootstrap sampled :param numpy.ndarray depth_bins: getBin edges for the depths :param bool nor...
[ "Gets", "the", "depth", "distribution", "of", "the", "earthquake", "catalogue", "to", "return", "a", "single", "histogram", ".", "Depths", "may", "be", "normalised", ".", "If", "uncertainties", "are", "found", "in", "the", "catalogue", "the", "distrbution", "m...
python
train
spyder-ide/spyder
spyder/utils/qthelpers.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/qthelpers.py#L511-L548
def calc_tools_spacing(tools_layout): """ Return a spacing (int) or None if we don't have the appropriate metrics to calculate the spacing. We're trying to adapt the spacing below the tools_layout spacing so that the main_widget has the same vertical position as the editor widgets (which...
[ "def", "calc_tools_spacing", "(", "tools_layout", ")", ":", "metrics", "=", "{", "# (tabbar_height, offset)\r", "'nt.fusion'", ":", "(", "32", ",", "0", ")", ",", "'nt.windowsvista'", ":", "(", "21", ",", "3", ")", ",", "'nt.windowsxp'", ":", "(", "24", ",...
Return a spacing (int) or None if we don't have the appropriate metrics to calculate the spacing. We're trying to adapt the spacing below the tools_layout spacing so that the main_widget has the same vertical position as the editor widgets (which have tabs above). The required spacing is ...
[ "Return", "a", "spacing", "(", "int", ")", "or", "None", "if", "we", "don", "t", "have", "the", "appropriate", "metrics", "to", "calculate", "the", "spacing", ".", "We", "re", "trying", "to", "adapt", "the", "spacing", "below", "the", "tools_layout", "sp...
python
train
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L569-L587
def file_update_all(backend, message, dryrun): """ Update all of the changed files for this Recipe """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You must be in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if re...
[ "def", "file_update_all", "(", "backend", ",", "message", ",", "dryrun", ")", ":", "kitchen", "=", "DKCloudCommandRunner", ".", "which_kitchen_name", "(", ")", "if", "kitchen", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "'You must be in a K...
Update all of the changed files for this Recipe
[ "Update", "all", "of", "the", "changed", "files", "for", "this", "Recipe" ]
python
train
mitsei/dlkit
dlkit/handcar/learning/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/managers.py#L1011-L1033
def get_objective_hierarchy_design_session(self): """Gets the session for designing objective hierarchies. return: (osid.learning.ObjectiveHierarchyDesignSession) - an ObjectiveHierarchyDesignSession raise: OperationFailed - unable to complete request raise: Unimplemen...
[ "def", "get_objective_hierarchy_design_session", "(", "self", ")", ":", "if", "not", "self", ".", "supports_objective_hierarchy_design", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", "ImportError", ":",...
Gets the session for designing objective hierarchies. return: (osid.learning.ObjectiveHierarchyDesignSession) - an ObjectiveHierarchyDesignSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_objective_hierarchy_design() is ...
[ "Gets", "the", "session", "for", "designing", "objective", "hierarchies", "." ]
python
train
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/labeled_network.py
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/labeled_network.py#L36-L46
def get_index_labels(self, targets): """Get the labels(known target/not) mapped to indices. :param targets: List of known targets :return: Dictionary of index-label mappings """ target_ind = self.graph.vs.select(name_in=targets).indices rest_ind = self.graph.vs.select(na...
[ "def", "get_index_labels", "(", "self", ",", "targets", ")", ":", "target_ind", "=", "self", ".", "graph", ".", "vs", ".", "select", "(", "name_in", "=", "targets", ")", ".", "indices", "rest_ind", "=", "self", ".", "graph", ".", "vs", ".", "select", ...
Get the labels(known target/not) mapped to indices. :param targets: List of known targets :return: Dictionary of index-label mappings
[ "Get", "the", "labels", "(", "known", "target", "/", "not", ")", "mapped", "to", "indices", "." ]
python
train
ciena/afkak
afkak/client.py
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/client.py#L509-L557
def send_produce_request(self, payloads=None, acks=1, timeout=DEFAULT_REPLICAS_ACK_MSECS, fail_on_error=True, callback=None): """ Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then ...
[ "def", "send_produce_request", "(", "self", ",", "payloads", "=", "None", ",", "acks", "=", "1", ",", "timeout", "=", "DEFAULT_REPLICAS_ACK_MSECS", ",", "fail_on_error", "=", "True", ",", "callback", "=", "None", ")", ":", "encoder", "=", "partial", "(", "...
Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of responses in the same order as the list of payloads specified Parameters ---------- payloads: list of ProduceRe...
[ "Encode", "and", "send", "some", "ProduceRequests" ]
python
train
tensorpack/tensorpack
examples/FasterRCNN/dataset.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/FasterRCNN/dataset.py#L77-L102
def load(self, add_gt=True, add_mask=False): """ Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'fil...
[ "def", "load", "(", "self", ",", "add_gt", "=", "True", ",", "add_mask", "=", "False", ")", ":", "if", "add_mask", ":", "assert", "add_gt", "with", "timed_operation", "(", "'Load Groundtruth Boxes for {}'", ".", "format", "(", "self", ".", "name", ")", ")"...
Args: add_gt: whether to add ground truth bounding box annotations to the dicts add_mask: whether to also add ground truth mask Returns: a list of dict, each has keys including: 'image_id', 'file_name', and (if add_gt is True) 'boxes', 'class'...
[ "Args", ":", "add_gt", ":", "whether", "to", "add", "ground", "truth", "bounding", "box", "annotations", "to", "the", "dicts", "add_mask", ":", "whether", "to", "also", "add", "ground", "truth", "mask" ]
python
train
PyCQA/pylint
pylint/checkers/exceptions.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/exceptions.py#L342-L357
def _check_bad_exception_context(self, node): """Verify that the exception context is properly set. An exception context can be only `None` or an exception. """ cause = utils.safe_infer(node.cause) if cause in (astroid.Uninferable, None): return if isinstanc...
[ "def", "_check_bad_exception_context", "(", "self", ",", "node", ")", ":", "cause", "=", "utils", ".", "safe_infer", "(", "node", ".", "cause", ")", "if", "cause", "in", "(", "astroid", ".", "Uninferable", ",", "None", ")", ":", "return", "if", "isinstan...
Verify that the exception context is properly set. An exception context can be only `None` or an exception.
[ "Verify", "that", "the", "exception", "context", "is", "properly", "set", "." ]
python
test
apache/airflow
airflow/hooks/S3_hook.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/S3_hook.py#L204-L218
def get_key(self, key, bucket_name=None): """ Returns a boto3.s3.Object :param key: the path to the key :type key: str :param bucket_name: the name of the bucket :type bucket_name: str """ if not bucket_name: (bucket_name, key) = self.parse_s3...
[ "def", "get_key", "(", "self", ",", "key", ",", "bucket_name", "=", "None", ")", ":", "if", "not", "bucket_name", ":", "(", "bucket_name", ",", "key", ")", "=", "self", ".", "parse_s3_url", "(", "key", ")", "obj", "=", "self", ".", "get_resource_type",...
Returns a boto3.s3.Object :param key: the path to the key :type key: str :param bucket_name: the name of the bucket :type bucket_name: str
[ "Returns", "a", "boto3", ".", "s3", ".", "Object" ]
python
test
facetoe/zenpy
zenpy/lib/api.py
https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api.py#L1095-L1103
def events(self, start_time, include=None): """ Retrieve TicketEvents :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param start_time: time to retrieve events from. """ ...
[ "def", "events", "(", "self", ",", "start_time", ",", "include", "=", "None", ")", ":", "return", "self", ".", "_query_zendesk", "(", "self", ".", "endpoint", ".", "events", ",", "'ticket_event'", ",", "start_time", "=", "start_time", ",", "include", "=", ...
Retrieve TicketEvents :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param start_time: time to retrieve events from.
[ "Retrieve", "TicketEvents" ]
python
train
denisenkom/pytds
src/pytds/tds.py
https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L77-L86
def tds7_crypt_pass(password): """ Mangle password according to tds rules :param password: Password str :returns: Byte-string with encoded password """ encoded = bytearray(ucs2_codec.encode(password)[0]) for i, ch in enumerate(encoded): encoded[i] = ((ch << 4) & 0xff | (ch >> 4)) ^ 0xA5...
[ "def", "tds7_crypt_pass", "(", "password", ")", ":", "encoded", "=", "bytearray", "(", "ucs2_codec", ".", "encode", "(", "password", ")", "[", "0", "]", ")", "for", "i", ",", "ch", "in", "enumerate", "(", "encoded", ")", ":", "encoded", "[", "i", "]"...
Mangle password according to tds rules :param password: Password str :returns: Byte-string with encoded password
[ "Mangle", "password", "according", "to", "tds", "rules" ]
python
train
softlayer/softlayer-python
SoftLayer/managers/ordering.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/ordering.py#L212-L230
def order_quote(self, quote_id, extra): """Places an order using a quote :: extras = { 'hardware': {'hostname': 'test', 'domain': 'testing.com'}, 'quantity': 2 } manager = ordering.OrderingManager(env.client) result = mana...
[ "def", "order_quote", "(", "self", ",", "quote_id", ",", "extra", ")", ":", "container", "=", "self", ".", "generate_order_template", "(", "quote_id", ",", "extra", ")", "return", "self", ".", "client", ".", "call", "(", "'SoftLayer_Billing_Order_Quote'", ",",...
Places an order using a quote :: extras = { 'hardware': {'hostname': 'test', 'domain': 'testing.com'}, 'quantity': 2 } manager = ordering.OrderingManager(env.client) result = manager.order_quote(12345, extras) :param int ...
[ "Places", "an", "order", "using", "a", "quote" ]
python
train
dropbox/stone
stone/frontend/ir_generator.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/ir_generator.py#L749-L803
def _populate_union_type_attributes(self, env, data_type): """ Converts a forward reference of a union into a complete definition. """ parent_type = None extends = data_type._ast_node.extends if extends: # A parent type must be fully defined and not just a for...
[ "def", "_populate_union_type_attributes", "(", "self", ",", "env", ",", "data_type", ")", ":", "parent_type", "=", "None", "extends", "=", "data_type", ".", "_ast_node", ".", "extends", "if", "extends", ":", "# A parent type must be fully defined and not just a forward"...
Converts a forward reference of a union into a complete definition.
[ "Converts", "a", "forward", "reference", "of", "a", "union", "into", "a", "complete", "definition", "." ]
python
train
Netflix-Skunkworks/swag-client
swag_client/backend.py
https://github.com/Netflix-Skunkworks/swag-client/blob/e43816a85c4f48011cf497a4eae14f9df71fee0f/swag_client/backend.py#L99-L132
def get_service_enabled(self, name, accounts_list=None, search_filter=None, region=None): """Get a list of accounts where a service has been enabled.""" if not accounts_list: accounts = self.get_all(search_filter=search_filter) else: accounts = accounts_list if s...
[ "def", "get_service_enabled", "(", "self", ",", "name", ",", "accounts_list", "=", "None", ",", "search_filter", "=", "None", ",", "region", "=", "None", ")", ":", "if", "not", "accounts_list", ":", "accounts", "=", "self", ".", "get_all", "(", "search_fil...
Get a list of accounts where a service has been enabled.
[ "Get", "a", "list", "of", "accounts", "where", "a", "service", "has", "been", "enabled", "." ]
python
train
MartinThoma/hwrt
hwrt/datasets/__init__.py
https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/datasets/__init__.py#L20-L79
def formula_to_dbid(formula_str, backslash_fix=False): """ Convert a LaTeX formula to the database index. Parameters ---------- formula_str : string The formula as LaTeX code. backslash_fix : boolean If this is set to true, then it will be checked if the same formula exi...
[ "def", "formula_to_dbid", "(", "formula_str", ",", "backslash_fix", "=", "False", ")", ":", "global", "__formula_to_dbid_cache", "if", "__formula_to_dbid_cache", "is", "None", ":", "mysql", "=", "utils", ".", "get_mysql_cfg", "(", ")", "connection", "=", "pymysql"...
Convert a LaTeX formula to the database index. Parameters ---------- formula_str : string The formula as LaTeX code. backslash_fix : boolean If this is set to true, then it will be checked if the same formula exists with a preceeding backslash. Returns ------- int :...
[ "Convert", "a", "LaTeX", "formula", "to", "the", "database", "index", "." ]
python
train
openid/python-openid
openid/association.py
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L151-L169
def addAllowedType(self, assoc_type, session_type=None): """Add an association type and session type to the allowed types list. The assocation/session pairs are tried in the order that they are added.""" if self.allowed_types is None: self.allowed_types = [] if sessi...
[ "def", "addAllowedType", "(", "self", ",", "assoc_type", ",", "session_type", "=", "None", ")", ":", "if", "self", ".", "allowed_types", "is", "None", ":", "self", ".", "allowed_types", "=", "[", "]", "if", "session_type", "is", "None", ":", "available", ...
Add an association type and session type to the allowed types list. The assocation/session pairs are tried in the order that they are added.
[ "Add", "an", "association", "type", "and", "session", "type", "to", "the", "allowed", "types", "list", ".", "The", "assocation", "/", "session", "pairs", "are", "tried", "in", "the", "order", "that", "they", "are", "added", "." ]
python
train
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L2811-L2831
def to_array(self): """ Serializes this InlineQueryResultCachedGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedGif, self).to_array() # 'type' and 'id' given by superclass array[...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "InlineQueryResultCachedGif", ",", "self", ")", ".", "to_array", "(", ")", "# 'type' and 'id' given by superclass", "array", "[", "'gif_file_id'", "]", "=", "u", "(", "self", ".", "gif_file_...
Serializes this InlineQueryResultCachedGif to a dictionary. :return: dictionary representation of this object. :rtype: dict
[ "Serializes", "this", "InlineQueryResultCachedGif", "to", "a", "dictionary", "." ]
python
train
PythonCharmers/python-future
src/future/backports/http/cookies.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookies.py#L235-L245
def _quote(str, LegalChars=_LegalChars): r"""Quote a string for use in a cookie header. If the string does not need to be double-quoted, then just return the string. Otherwise, surround the string in doublequotes and quote (with a \) special characters. """ if all(c in LegalChars for c in str)...
[ "def", "_quote", "(", "str", ",", "LegalChars", "=", "_LegalChars", ")", ":", "if", "all", "(", "c", "in", "LegalChars", "for", "c", "in", "str", ")", ":", "return", "str", "else", ":", "return", "'\"'", "+", "_nulljoin", "(", "_Translator", ".", "ge...
r"""Quote a string for use in a cookie header. If the string does not need to be double-quoted, then just return the string. Otherwise, surround the string in doublequotes and quote (with a \) special characters.
[ "r", "Quote", "a", "string", "for", "use", "in", "a", "cookie", "header", "." ]
python
train
Microsoft/nni
src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L142-L169
def _add_index(in_x, parameter): """ change parameters in NNI format to parameters in hyperopt format(This function also support nested dict.). For example, receive parameters like: {'dropout_rate': 0.8, 'conv_size': 3, 'hidden_size': 512} Will change to format in hyperopt, like: {'dropo...
[ "def", "_add_index", "(", "in_x", ",", "parameter", ")", ":", "if", "TYPE", "not", "in", "in_x", ":", "# if at the top level", "out_y", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "parameter", ".", "items", "(", ")", ":", "out_y", "[", "...
change parameters in NNI format to parameters in hyperopt format(This function also support nested dict.). For example, receive parameters like: {'dropout_rate': 0.8, 'conv_size': 3, 'hidden_size': 512} Will change to format in hyperopt, like: {'dropout_rate': 0.8, 'conv_size': {'_index': 1, '_v...
[ "change", "parameters", "in", "NNI", "format", "to", "parameters", "in", "hyperopt", "format", "(", "This", "function", "also", "support", "nested", "dict", ".", ")", ".", "For", "example", "receive", "parameters", "like", ":", "{", "dropout_rate", ":", "0",...
python
train
vinci1it2000/schedula
schedula/utils/alg.py
https://github.com/vinci1it2000/schedula/blob/addb9fd685be81544b796c51383ac00a31543ce9/schedula/utils/alg.py#L22-L45
def add_edge_fun(graph): """ Returns a function that adds an edge to the `graph` checking only the out node. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :return: A function that adds an edge to the `graph`. :rtype: callable """ # N...
[ "def", "add_edge_fun", "(", "graph", ")", ":", "# Namespace shortcut for speed.", "succ", ",", "pred", ",", "node", "=", "graph", ".", "_succ", ",", "graph", ".", "_pred", ",", "graph", ".", "_node", "def", "add_edge", "(", "u", ",", "v", ",", "*", "*"...
Returns a function that adds an edge to the `graph` checking only the out node. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :return: A function that adds an edge to the `graph`. :rtype: callable
[ "Returns", "a", "function", "that", "adds", "an", "edge", "to", "the", "graph", "checking", "only", "the", "out", "node", "." ]
python
train
ronaldguillen/wave
wave/parsers.py
https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/parsers.py#L79-L87
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a URL encoded form, and returns the resulting QueryDict. """ parser_context = parser_context or {} encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) ...
[ "def", "parse", "(", "self", ",", "stream", ",", "media_type", "=", "None", ",", "parser_context", "=", "None", ")", ":", "parser_context", "=", "parser_context", "or", "{", "}", "encoding", "=", "parser_context", ".", "get", "(", "'encoding'", ",", "setti...
Parses the incoming bytestream as a URL encoded form, and returns the resulting QueryDict.
[ "Parses", "the", "incoming", "bytestream", "as", "a", "URL", "encoded", "form", "and", "returns", "the", "resulting", "QueryDict", "." ]
python
train
dtmilano/AndroidViewClient
src/com/dtmilano/android/viewclient.py
https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L3415-L3472
def list(self, sleep=1): ''' List the windows. Sleep is useful to wait some time before obtaining the new content when something in the window has changed. This also sets L{self.windows} as the list of windows. @type sleep: int @param sleep: sleep in seconds bef...
[ "def", "list", "(", "self", ",", "sleep", "=", "1", ")", ":", "if", "sleep", ">", "0", ":", "time", ".", "sleep", "(", "sleep", ")", "if", "self", ".", "useUiAutomator", ":", "raise", "Exception", "(", "\"Not implemented yet: listing windows with UiAutomator...
List the windows. Sleep is useful to wait some time before obtaining the new content when something in the window has changed. This also sets L{self.windows} as the list of windows. @type sleep: int @param sleep: sleep in seconds before proceeding to dump the content @...
[ "List", "the", "windows", "." ]
python
train
atztogo/phonopy
phonopy/structure/spglib.py
https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L123-L235
def get_symmetry_dataset(cell, symprec=1e-5, angle_tolerance=-1.0, hall_number=0): """Search symmetry dataset from an input cell. Args: cell, symprec, angle_tolerance: See the docstring of get_symmetry. hall_...
[ "def", "get_symmetry_dataset", "(", "cell", ",", "symprec", "=", "1e-5", ",", "angle_tolerance", "=", "-", "1.0", ",", "hall_number", "=", "0", ")", ":", "_set_no_error", "(", ")", "lattice", ",", "positions", ",", "numbers", ",", "_", "=", "_expand_cell",...
Search symmetry dataset from an input cell. Args: cell, symprec, angle_tolerance: See the docstring of get_symmetry. hall_number: If a serial number of Hall symbol (>0) is given, the database corresponding to the Hall symbol is made. Return: A dictionar...
[ "Search", "symmetry", "dataset", "from", "an", "input", "cell", "." ]
python
train
mottosso/be
be/vendor/requests/adapters.py
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/adapters.py#L301-L321
def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be c...
[ "def", "proxy_headers", "(", "self", ",", "proxy", ")", ":", "headers", "=", "{", "}", "username", ",", "password", "=", "get_auth_from_url", "(", "proxy", ")", "if", "username", "and", "password", ":", "headers", "[", "'Proxy-Authorization'", "]", "=", "_...
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed f...
[ "Returns", "a", "dictionary", "of", "the", "headers", "to", "add", "to", "any", "request", "sent", "through", "a", "proxy", ".", "This", "works", "with", "urllib3", "magic", "to", "ensure", "that", "they", "are", "correctly", "sent", "to", "the", "proxy", ...
python
train
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L592-L597
def write_memory(self, addr, value, transfer_size=32): """ write a memory location. By default the transfer size is a word """ self.ap.write_memory(addr, value, transfer_size)
[ "def", "write_memory", "(", "self", ",", "addr", ",", "value", ",", "transfer_size", "=", "32", ")", ":", "self", ".", "ap", ".", "write_memory", "(", "addr", ",", "value", ",", "transfer_size", ")" ]
write a memory location. By default the transfer size is a word
[ "write", "a", "memory", "location", ".", "By", "default", "the", "transfer", "size", "is", "a", "word" ]
python
train
globus/globus-cli
globus_cli/commands/endpoint/permission/delete.py
https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/commands/endpoint/permission/delete.py#L14-L21
def delete_command(endpoint_id, rule_id): """ Executor for `globus endpoint permission delete` """ client = get_client() res = client.delete_endpoint_acl_rule(endpoint_id, rule_id) formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message")
[ "def", "delete_command", "(", "endpoint_id", ",", "rule_id", ")", ":", "client", "=", "get_client", "(", ")", "res", "=", "client", ".", "delete_endpoint_acl_rule", "(", "endpoint_id", ",", "rule_id", ")", "formatted_print", "(", "res", ",", "text_format", "="...
Executor for `globus endpoint permission delete`
[ "Executor", "for", "globus", "endpoint", "permission", "delete" ]
python
train
biolink/ontobio
ontobio/assocmodel.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/assocmodel.py#L295-L317
def as_dataframe(self, fillna=True, subjects=None): """ Return association set as pandas DataFrame Each row is a subject (e.g. gene) Each column is the inferred class used to describe the subject """ entries = [] selected_subjects = self.subjects if subje...
[ "def", "as_dataframe", "(", "self", ",", "fillna", "=", "True", ",", "subjects", "=", "None", ")", ":", "entries", "=", "[", "]", "selected_subjects", "=", "self", ".", "subjects", "if", "subjects", "is", "not", "None", ":", "selected_subjects", "=", "su...
Return association set as pandas DataFrame Each row is a subject (e.g. gene) Each column is the inferred class used to describe the subject
[ "Return", "association", "set", "as", "pandas", "DataFrame" ]
python
train
Kozea/pygal
pygal/graph/stackedline.py
https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/stackedline.py#L40-L50
def _value_format(self, value, serie, index): """ Display value and cumulation """ sum_ = serie.points[index][1] if serie in self.series and ( self.stack_from_top and self.series.index(serie) == self._order - 1 or not self.stack_fro...
[ "def", "_value_format", "(", "self", ",", "value", ",", "serie", ",", "index", ")", ":", "sum_", "=", "serie", ".", "points", "[", "index", "]", "[", "1", "]", "if", "serie", "in", "self", ".", "series", "and", "(", "self", ".", "stack_from_top", "...
Display value and cumulation
[ "Display", "value", "and", "cumulation" ]
python
train
chimera0/accel-brain-code
Reinforcement-Learning/pyqlearning/deep_q_learning.py
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Reinforcement-Learning/pyqlearning/deep_q_learning.py#L246-L253
def set_alpha_value(self, value): ''' setter Learning rate. ''' if isinstance(value, float) is False: raise TypeError("The type of __alpha_value must be float.") self.__alpha_value = value
[ "def", "set_alpha_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __alpha_value must be float.\"", ")", "self", ".", "__alpha_value", "=", "value" ]
setter Learning rate.
[ "setter", "Learning", "rate", "." ]
python
train
materialsproject/pymatgen
pymatgen/io/abinit/tasks.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L3939-L3947
def sigres_path(self): """Absolute path of the SIGRES file. Empty string if file is not present.""" # Lazy property to avoid multiple calls to has_abiext. try: return self._sigres_path except AttributeError: path = self.outdir.has_abiext("SIGRES") if p...
[ "def", "sigres_path", "(", "self", ")", ":", "# Lazy property to avoid multiple calls to has_abiext.", "try", ":", "return", "self", ".", "_sigres_path", "except", "AttributeError", ":", "path", "=", "self", ".", "outdir", ".", "has_abiext", "(", "\"SIGRES\"", ")", ...
Absolute path of the SIGRES file. Empty string if file is not present.
[ "Absolute", "path", "of", "the", "SIGRES", "file", ".", "Empty", "string", "if", "file", "is", "not", "present", "." ]
python
train
openstack/horizon
openstack_auth/backend.py
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_auth/backend.py#L102-L231
def authenticate(self, auth_url=None, **kwargs): """Authenticates a user via the Keystone Identity API.""" LOG.debug('Beginning user authentication') if not auth_url: auth_url = settings.OPENSTACK_KEYSTONE_URL auth_url, url_fixed = utils.fix_auth_url_version_prefix(auth_url...
[ "def", "authenticate", "(", "self", ",", "auth_url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "LOG", ".", "debug", "(", "'Beginning user authentication'", ")", "if", "not", "auth_url", ":", "auth_url", "=", "settings", ".", "OPENSTACK_KEYSTONE_URL", "...
Authenticates a user via the Keystone Identity API.
[ "Authenticates", "a", "user", "via", "the", "Keystone", "Identity", "API", "." ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py#L47-L60
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The event. """ if self._aspect is None: return w, h = self._canvas.size aspect = self._aspect / (w / h) self.scale = (self.scale[...
[ "def", "on_resize", "(", "self", ",", "event", ")", ":", "if", "self", ".", "_aspect", "is", "None", ":", "return", "w", ",", "h", "=", "self", ".", "_canvas", ".", "size", "aspect", "=", "self", ".", "_aspect", "/", "(", "w", "/", "h", ")", "s...
Resize handler Parameters ---------- event : instance of Event The event.
[ "Resize", "handler" ]
python
train
robhowley/nhlscrapi
nhlscrapi/games/toi.py
https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/games/toi.py#L100-L108
def away_shift_summ(self): """ :returns: :py:class:`.ShiftSummary` by player for the away team :rtype: dict ``{ player_num: shift_summary_obj }`` """ if not self.__wrapped_away: self.__wrapped_away = self.__wrap(self._away.by_player) return self.__wra...
[ "def", "away_shift_summ", "(", "self", ")", ":", "if", "not", "self", ".", "__wrapped_away", ":", "self", ".", "__wrapped_away", "=", "self", ".", "__wrap", "(", "self", ".", "_away", ".", "by_player", ")", "return", "self", ".", "__wrapped_away" ]
:returns: :py:class:`.ShiftSummary` by player for the away team :rtype: dict ``{ player_num: shift_summary_obj }``
[ ":", "returns", ":", ":", "py", ":", "class", ":", ".", "ShiftSummary", "by", "player", "for", "the", "away", "team", ":", "rtype", ":", "dict", "{", "player_num", ":", "shift_summary_obj", "}" ]
python
train
tilde-lab/tilde
utils/syshwinfo.py
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L127-L138
def diskdata(): """Get total disk size in GB.""" p = os.popen("/bin/df -l -P") ddata = {} tsize = 0 for line in p.readlines(): d = line.split() if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]): tsize = tsize + int(d[1]) ddata["Disk_GB"] = int(tsize...
[ "def", "diskdata", "(", ")", ":", "p", "=", "os", ".", "popen", "(", "\"/bin/df -l -P\"", ")", "ddata", "=", "{", "}", "tsize", "=", "0", "for", "line", "in", "p", ".", "readlines", "(", ")", ":", "d", "=", "line", ".", "split", "(", ")", "if",...
Get total disk size in GB.
[ "Get", "total", "disk", "size", "in", "GB", "." ]
python
train
swharden/webinspect
webinspect/webinspect.py
https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L24-L33
def launch(thing,title=False): """analyze a thing, create a nice HTML document, and launch it.""" html=htmlFromThing(thing,title=title) if not html: print("no HTML was generated.") return fname="%s/%s.html"%(tempfile.gettempdir(),str(time.time())) with open(fname,'w') as f: ...
[ "def", "launch", "(", "thing", ",", "title", "=", "False", ")", ":", "html", "=", "htmlFromThing", "(", "thing", ",", "title", "=", "title", ")", "if", "not", "html", ":", "print", "(", "\"no HTML was generated.\"", ")", "return", "fname", "=", "\"%s/%s....
analyze a thing, create a nice HTML document, and launch it.
[ "analyze", "a", "thing", "create", "a", "nice", "HTML", "document", "and", "launch", "it", "." ]
python
train
taizilongxu/douban.fm
doubanfm/colorset/colors.py
https://github.com/taizilongxu/douban.fm/blob/d65126d3bd3e12d8a7109137caff8da0efc22b2f/doubanfm/colorset/colors.py#L5-L18
def basic_color(code): """ 16 colors supported """ def inner(text, rl=False): """ Every raw_input with color sequences should be called with rl=True to avoid readline messed up the length calculation """ c = code if rl: return "\001\033[%sm\002%s\001\0...
[ "def", "basic_color", "(", "code", ")", ":", "def", "inner", "(", "text", ",", "rl", "=", "False", ")", ":", "\"\"\" Every raw_input with color sequences should be called with\n rl=True to avoid readline messed up the length calculation\n \"\"\"", "c", "=", "code"...
16 colors supported
[ "16", "colors", "supported" ]
python
train
dbcli/athenacli
athenacli/packages/filepaths.py
https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/filepaths.py#L5-L14
def list_path(root_dir): """List directory if exists. :param dir: str :return: list """ res = [] if os.path.isdir(root_dir): for name in os.listdir(root_dir): res.append(name) return res
[ "def", "list_path", "(", "root_dir", ")", ":", "res", "=", "[", "]", "if", "os", ".", "path", ".", "isdir", "(", "root_dir", ")", ":", "for", "name", "in", "os", ".", "listdir", "(", "root_dir", ")", ":", "res", ".", "append", "(", "name", ")", ...
List directory if exists. :param dir: str :return: list
[ "List", "directory", "if", "exists", ".", ":", "param", "dir", ":", "str", ":", "return", ":", "list" ]
python
train