repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
pulumi/pulumi
sdk/python/lib/pulumi/runtime/rpc.py
https://github.com/pulumi/pulumi/blob/95d51efe6ab9a533838b6d83aa240b5f912e72aa/sdk/python/lib/pulumi/runtime/rpc.py#L46-L70
async def serialize_properties(inputs: 'Inputs', property_deps: Dict[str, List['Resource']], input_transformer: Optional[Callable[[str], str]] = None) -> struct_pb2.Struct: """ Serializes an arbitrary Input bag into a Protobuf structure, keeping trac...
[ "async", "def", "serialize_properties", "(", "inputs", ":", "'Inputs'", ",", "property_deps", ":", "Dict", "[", "str", ",", "List", "[", "'Resource'", "]", "]", ",", "input_transformer", ":", "Optional", "[", "Callable", "[", "[", "str", "]", ",", "str", ...
Serializes an arbitrary Input bag into a Protobuf structure, keeping track of the list of dependent resources in the `deps` list. Serializing properties is inherently async because it awaits any futures that are contained transitively within the input bag.
[ "Serializes", "an", "arbitrary", "Input", "bag", "into", "a", "Protobuf", "structure", "keeping", "track", "of", "the", "list", "of", "dependent", "resources", "in", "the", "deps", "list", ".", "Serializing", "properties", "is", "inherently", "async", "because",...
python
train
54.2
Parisson/TimeSide
timeside/core/analyzer.py
https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/analyzer.py#L1047-L1056
def JSON_NumpyArrayEncoder(obj): '''Define Specialize JSON encoder for numpy array''' if isinstance(obj, np.ndarray): return {'numpyArray': obj.tolist(), 'dtype': obj.dtype.__str__()} elif isinstance(obj, np.generic): return np.asscalar(obj) else: print type(obj) ...
[ "def", "JSON_NumpyArrayEncoder", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "return", "{", "'numpyArray'", ":", "obj", ".", "tolist", "(", ")", ",", "'dtype'", ":", "obj", ".", "dtype", ".", "__str__", ...
Define Specialize JSON encoder for numpy array
[ "Define", "Specialize", "JSON", "encoder", "for", "numpy", "array" ]
python
train
37.5
Unidata/MetPy
metpy/calc/tools.py
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/tools.py#L101-L173
def find_intersections(x, a, b, direction='all'): """Calculate the best estimate of intersection. Calculates the best estimates of the intersection of two y-value data sets that share a common x-value set. Parameters ---------- x : array-like 1-dimensional array of numeric x-values ...
[ "def", "find_intersections", "(", "x", ",", "a", ",", "b", ",", "direction", "=", "'all'", ")", ":", "# Find the index of the points just before the intersection(s)", "nearest_idx", "=", "nearest_intersection_idx", "(", "a", ",", "b", ")", "next_idx", "=", "nearest_...
Calculate the best estimate of intersection. Calculates the best estimates of the intersection of two y-value data sets that share a common x-value set. Parameters ---------- x : array-like 1-dimensional array of numeric x-values a : array-like 1-dimensional array of y-values f...
[ "Calculate", "the", "best", "estimate", "of", "intersection", "." ]
python
train
38.39726
albertz/py_better_exchook
better_exchook.py
https://github.com/albertz/py_better_exchook/blob/3d524a027d7fc4e83e47e39a1978849561da69b3/better_exchook.py#L823-L833
def fold_text_string(self, prefix, hidden, **kwargs): """ :param str prefix: :param str hidden: :param kwargs: passed to :func:`fold_text` :rtype: str """ import io output_buf = io.StringIO() self.fold_text(prefix=prefix, hidden=hidden, file=output...
[ "def", "fold_text_string", "(", "self", ",", "prefix", ",", "hidden", ",", "*", "*", "kwargs", ")", ":", "import", "io", "output_buf", "=", "io", ".", "StringIO", "(", ")", "self", ".", "fold_text", "(", "prefix", "=", "prefix", ",", "hidden", "=", "...
:param str prefix: :param str hidden: :param kwargs: passed to :func:`fold_text` :rtype: str
[ ":", "param", "str", "prefix", ":", ":", "param", "str", "hidden", ":", ":", "param", "kwargs", ":", "passed", "to", ":", "func", ":", "fold_text", ":", "rtype", ":", "str" ]
python
train
32.909091
NuGrid/NuGridPy
nugridpy/mesa.py
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/mesa.py#L944-L971
def CO_ratio(self,ifig,ixaxis): """ plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis Parameters ---------- ifig : integer Figure number in which to plot ixaxis : string what quantity is to be on the x-axis, either 'time' or 'model...
[ "def", "CO_ratio", "(", "self", ",", "ifig", ",", "ixaxis", ")", ":", "def", "C_O", "(", "model", ")", ":", "surface_c12", "=", "model", ".", "get", "(", "'surface_c12'", ")", "surface_o16", "=", "model", ".", "get", "(", "'surface_o16'", ")", "CORatio...
plot surface C/O ratio in Figure ifig with x-axis quantity ixaxis Parameters ---------- ifig : integer Figure number in which to plot ixaxis : string what quantity is to be on the x-axis, either 'time' or 'model' The default is 'model'
[ "plot", "surface", "C", "/", "O", "ratio", "in", "Figure", "ifig", "with", "x", "-", "axis", "quantity", "ixaxis" ]
python
train
28.964286
cimatosa/progression
progression/progress.py
https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L806-L874
def _calc(count, last_count, start_time, max_count, speed_calc_cycles, q, last_speed, lock): """do the pre calculations in order to get TET, speed, TTG :param count: count ...
[ "def", "_calc", "(", "count", ",", "last_count", ",", "start_time", ",", "max_count", ",", "speed_calc_cycles", ",", "q", ",", "last_speed", ",", "lock", ")", ":", "count_value", "=", "count", ".", "value", "start_time_value", "=", "start_time", ".", "value"...
do the pre calculations in order to get TET, speed, TTG :param count: count :param last_count: count at the last call, allows to treat the case of no progress between sequential calls :param start_time: the time when start was triggered ...
[ "do", "the", "pre", "calculations", "in", "order", "to", "get", "TET", "speed", "TTG", ":", "param", "count", ":", "count", ":", "param", "last_count", ":", "count", "at", "the", "last", "call", "allows", "to", "treat", "the", "case", "of", "no", "prog...
python
train
35.086957
ergoithz/browsepy
browsepy/file.py
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/file.py#L828-L844
def check_forbidden_filename(filename, destiny_os=os.name, restricted_names=restricted_names): ''' Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_en...
[ "def", "check_forbidden_filename", "(", "filename", ",", "destiny_os", "=", "os", ".", "name", ",", "restricted_names", "=", "restricted_names", ")", ":", "return", "(", "filename", "in", "restricted_names", "or", "destiny_os", "==", "'nt'", "and", "filename", "...
Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_encoding: destination filesystem filename encoding :return: wether is forbidden on given OS (or filesystem) or not :rtype: bool
[ "Get", "if", "given", "filename", "is", "forbidden", "for", "current", "OS", "or", "filesystem", "." ]
python
train
34.823529
bcbio/bcbio-nextgen
bcbio/cwl/cwlutils.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/cwlutils.py#L39-L51
def handle_combined_input(args): """Check for cases where we have a combined input nested list. In these cases the CWL will be double nested: [[[rec_a], [rec_b]]] and we remove the outer nesting. """ cur_args = args[:] while len(cur_args) == 1 and isinstance(cur_args[0], (list, tuple)): ...
[ "def", "handle_combined_input", "(", "args", ")", ":", "cur_args", "=", "args", "[", ":", "]", "while", "len", "(", "cur_args", ")", "==", "1", "and", "isinstance", "(", "cur_args", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "cur...
Check for cases where we have a combined input nested list. In these cases the CWL will be double nested: [[[rec_a], [rec_b]]] and we remove the outer nesting.
[ "Check", "for", "cases", "where", "we", "have", "a", "combined", "input", "nested", "list", "." ]
python
train
27.461538
pyroscope/pyrocore
src/pyrocore/util/traits.py
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/traits.py#L127-L154
def get_filetypes(filelist, path=None, size=os.path.getsize): """ Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype) """ path = ...
[ "def", "get_filetypes", "(", "filelist", ",", "path", "=", "None", ",", "size", "=", "os", ".", "path", ".", "getsize", ")", ":", "path", "=", "path", "or", "(", "lambda", "_", ":", "_", ")", "# Get total size for each file extension", "histo", "=", "def...
Get a sorted list of file types and their weight in percent from an iterable of file names. @return: List of weighted file extensions (no '.'), sorted in descending order @rtype: list of (weight, filetype)
[ "Get", "a", "sorted", "list", "of", "file", "types", "and", "their", "weight", "in", "percent", "from", "an", "iterable", "of", "file", "names", "." ]
python
train
34.071429
thombashi/pytablewriter
pytablewriter/sanitizer/_excel.py
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/sanitizer/_excel.py#L53-L77
def sanitize_excel_sheet_name(sheet_name, replacement_text=""): """ Replace invalid characters for an Excel sheet name within the ``sheet_name`` with the ``replacement_text``. Invalid characters are as follows: |invalid_excel_sheet_chars|. The ``sheet_name`` truncate to 31 characters (max sh...
[ "def", "sanitize_excel_sheet_name", "(", "sheet_name", ",", "replacement_text", "=", "\"\"", ")", ":", "try", ":", "unicode_sheet_name", "=", "_preprocess", "(", "sheet_name", ")", "except", "AttributeError", "as", "e", ":", "raise", "ValueError", "(", "e", ")",...
Replace invalid characters for an Excel sheet name within the ``sheet_name`` with the ``replacement_text``. Invalid characters are as follows: |invalid_excel_sheet_chars|. The ``sheet_name`` truncate to 31 characters (max sheet name length of Excel) from the head, if the length of the name is ex...
[ "Replace", "invalid", "characters", "for", "an", "Excel", "sheet", "name", "within", "the", "sheet_name", "with", "the", "replacement_text", ".", "Invalid", "characters", "are", "as", "follows", ":", "|invalid_excel_sheet_chars|", ".", "The", "sheet_name", "truncate...
python
train
36.16
cloud-custodian/cloud-custodian
c7n/policy.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L426-L481
def run(self, event, lambda_context): """Run policy in push mode against given event. Lambda automatically generates cloud watch logs, and metrics for us, albeit with some deficienies, metrics no longer count against valid resources matches, but against execution. If metrics ex...
[ "def", "run", "(", "self", ",", "event", ",", "lambda_context", ")", ":", "from", "c7n", ".", "actions", "import", "EventAction", "mode", "=", "self", ".", "policy", ".", "data", ".", "get", "(", "'mode'", ",", "{", "}", ")", "if", "not", "bool", "...
Run policy in push mode against given event. Lambda automatically generates cloud watch logs, and metrics for us, albeit with some deficienies, metrics no longer count against valid resources matches, but against execution. If metrics execution option is enabled, custodian will generat...
[ "Run", "policy", "in", "push", "mode", "against", "given", "event", "." ]
python
train
38.696429
sanger-pathogens/ariba
ariba/summary.py
https://github.com/sanger-pathogens/ariba/blob/16a0b1916ce0e886bd22550ba2d648542977001b/ariba/summary.py#L223-L236
def _filter_matrix_rows(cls, matrix): '''matrix = output from _to_matrix''' indexes_to_keep = [] for i in range(len(matrix)): keep_row = False for element in matrix[i]: if element not in {'NA', 'no'}: keep_row = True ...
[ "def", "_filter_matrix_rows", "(", "cls", ",", "matrix", ")", ":", "indexes_to_keep", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "matrix", ")", ")", ":", "keep_row", "=", "False", "for", "element", "in", "matrix", "[", "i", "]", ":", ...
matrix = output from _to_matrix
[ "matrix", "=", "output", "from", "_to_matrix" ]
python
train
31
numenta/htmresearch
projects/feedback/feedback_experiment.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/feedback/feedback_experiment.py#L397-L406
def getL4PredictedActiveCells(self): """ Returns the predicted active cells in each column in L4. """ predictedActive = [] for i in xrange(self.numColumns): region = self.network.regions["L4Column_" + str(i)] predictedActive.append( region.getOutputData("predictedActiveCells").no...
[ "def", "getL4PredictedActiveCells", "(", "self", ")", ":", "predictedActive", "=", "[", "]", "for", "i", "in", "xrange", "(", "self", ".", "numColumns", ")", ":", "region", "=", "self", ".", "network", ".", "regions", "[", "\"L4Column_\"", "+", "str", "(...
Returns the predicted active cells in each column in L4.
[ "Returns", "the", "predicted", "active", "cells", "in", "each", "column", "in", "L4", "." ]
python
train
34.9
cds-astro/mocpy
mocpy/tmoc/tmoc.py
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/tmoc/tmoc.py#L84-L95
def add_neighbours(self): """ Add all the pixels at max order in the neighbourhood of the moc """ time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order)) intervals_arr = self._interval_set._intervals intervals_arr[:, 0] = np.maximum(intervals_arr[:, 0] - time...
[ "def", "add_neighbours", "(", "self", ")", ":", "time_delta", "=", "1", "<<", "(", "2", "*", "(", "IntervalSet", ".", "HPY_MAX_ORDER", "-", "self", ".", "max_order", ")", ")", "intervals_arr", "=", "self", ".", "_interval_set", ".", "_intervals", "interval...
Add all the pixels at max order in the neighbourhood of the moc
[ "Add", "all", "the", "pixels", "at", "max", "order", "in", "the", "neighbourhood", "of", "the", "moc" ]
python
train
38.833333
feliperyan/EinsteinVisionPython
EinsteinVision/EinsteinVision.py
https://github.com/feliperyan/EinsteinVisionPython/blob/c761c46c7dc5fe8bbe7b15a6e1166a3585ed3cfb/EinsteinVision/EinsteinVision.py#L48-L83
def get_token(self): """ Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file cont...
[ "def", "get_token", "(", "self", ")", ":", "payload", "=", "{", "'aud'", ":", "API_OAUTH", ",", "'exp'", ":", "time", ".", "time", "(", ")", "+", "600", ",", "# 10 minutes", "'sub'", ":", "self", ".", "email", "}", "header", "=", "{", "'Content-type'...
Acquires a token for futher API calls, unless you already have a token this will be the first thing you do before you use this. :param email: string, the username for your EinsteinVision service, usually in email form :para pem_file: string, file containing your Secret key. Copy cont...
[ "Acquires", "a", "token", "for", "futher", "API", "calls", "unless", "you", "already", "have", "a", "token", "this", "will", "be", "the", "first", "thing", "you", "do", "before", "you", "use", "this", ".", ":", "param", "email", ":", "string", "the", "...
python
train
38.527778
Locu/chronology
pykronos/pykronos/utils/cache.py
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/pykronos/pykronos/utils/cache.py#L237-L264
def compute_and_cache_missing_buckets(self, start_time, end_time, untrusted_time, force_recompute=False): """ Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to av...
[ "def", "compute_and_cache_missing_buckets", "(", "self", ",", "start_time", ",", "end_time", ",", "untrusted_time", ",", "force_recompute", "=", "False", ")", ":", "if", "untrusted_time", "and", "not", "untrusted_time", ".", "tzinfo", ":", "untrusted_time", "=", "...
Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to avoid recomputation. For any buckets where all events would have occurred before `untrusted_time`, cache the results. :param start_time: A datetim...
[ "Return", "the", "results", "for", "query_function", "on", "every", "bucket_width", "time", "period", "between", "start_time", "and", "end_time", ".", "Look", "for", "previously", "cached", "results", "to", "avoid", "recomputation", ".", "For", "any", "buckets", ...
python
train
46.678571
lsst-sqre/lander
lander/main.py
https://github.com/lsst-sqre/lander/blob/5e4f6123e48b451ba21963724ace0dc59798618e/lander/main.py#L171-L200
def main(): """Entrypoint for ``lander`` executable.""" args = parse_args() config_logger(args) logger = structlog.get_logger(__name__) if args.show_version: # only print the version print_version() sys.exit(0) version = pkg_resources.get_distribution('lander').version ...
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "config_logger", "(", "args", ")", "logger", "=", "structlog", ".", "get_logger", "(", "__name__", ")", "if", "args", ".", "show_version", ":", "# only print the version", "print_version", "(...
Entrypoint for ``lander`` executable.
[ "Entrypoint", "for", "lander", "executable", "." ]
python
train
25.533333
Alignak-monitoring/alignak
alignak/external_command.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/external_command.py#L563-L617
def resolve_command(self, excmd): """Parse command and dispatch it (to schedulers for example) if necessary If the command is not global it will be executed. :param excmd: external command to handle :type excmd: alignak.external_command.ExternalCommand :return: result of command...
[ "def", "resolve_command", "(", "self", ",", "excmd", ")", ":", "# Maybe the command is invalid. Bailout", "try", ":", "command", "=", "excmd", ".", "cmd_line", "except", "AttributeError", "as", "exp", ":", "# pragma: no cover, simple protection", "logger", ".", "warni...
Parse command and dispatch it (to schedulers for example) if necessary If the command is not global it will be executed. :param excmd: external command to handle :type excmd: alignak.external_command.ExternalCommand :return: result of command parsing. None for an invalid command.
[ "Parse", "command", "and", "dispatch", "it", "(", "to", "schedulers", "for", "example", ")", "if", "necessary", "If", "the", "command", "is", "not", "global", "it", "will", "be", "executed", "." ]
python
train
44.181818
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L12203-L12213
def scaled_pressure2_send(self, time_boot_ms, press_abs, press_diff, temperature, force_mavlink1=False): ''' Barometer readings for 2nd barometer time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) press_abs :...
[ "def", "scaled_pressure2_send", "(", "self", ",", "time_boot_ms", ",", "press_abs", ",", "press_diff", ",", "temperature", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "scaled_pressure2_encode", "(", "time_boot_...
Barometer readings for 2nd barometer time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) press_abs : Absolute pressure (hectopascal) (float) press_diff : Differential pressure 1 (hectopascal) (float) ...
[ "Barometer", "readings", "for", "2nd", "barometer" ]
python
train
64.181818
cirruscluster/cirruscluster
cirruscluster/ext/ansible/utils/__init__.py
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/utils/__init__.py#L482-L497
def filter_leading_non_json_lines(buf): ''' used to avoid random output from SSH at the top of JSON output, like messages from tcagetattr, or where dropbear spews MOTD on every single command (which is nuts). need to filter anything which starts not with '{', '[', ', '=' or is an empty line. filter...
[ "def", "filter_leading_non_json_lines", "(", "buf", ")", ":", "filtered_lines", "=", "StringIO", ".", "StringIO", "(", ")", "stop_filtering", "=", "False", "for", "line", "in", "buf", ".", "splitlines", "(", ")", ":", "if", "stop_filtering", "or", "\"=\"", "...
used to avoid random output from SSH at the top of JSON output, like messages from tcagetattr, or where dropbear spews MOTD on every single command (which is nuts). need to filter anything which starts not with '{', '[', ', '=' or is an empty line. filter only leading lines since multiline JSON is valid.
[ "used", "to", "avoid", "random", "output", "from", "SSH", "at", "the", "top", "of", "JSON", "output", "like", "messages", "from", "tcagetattr", "or", "where", "dropbear", "spews", "MOTD", "on", "every", "single", "command", "(", "which", "is", "nuts", ")",...
python
train
42.0625
bunq/sdk_python
bunq/sdk/json/converter.py
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/json/converter.py#L641-L651
def json_to_class(cls, json_str): """ :type cls: T|type :type json_str: str :rtype: T """ obj_raw = json.loads(json_str) return deserialize(cls, obj_raw)
[ "def", "json_to_class", "(", "cls", ",", "json_str", ")", ":", "obj_raw", "=", "json", ".", "loads", "(", "json_str", ")", "return", "deserialize", "(", "cls", ",", "obj_raw", ")" ]
:type cls: T|type :type json_str: str :rtype: T
[ ":", "type", "cls", ":", "T|type", ":", "type", "json_str", ":", "str" ]
python
train
15.818182
GGiecold/Concurrent_AP
Concurrent_AP.py
https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L142-L229
def parse_options(): """Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affi...
[ "def", "parse_options", "(", ")", ":", "parser", "=", "optparse", ".", "OptionParser", "(", "usage", "=", "\"Usage: %prog [options] file_name\\n\\n\"", "\"file_name denotes the path where the data to be \"", "\"processed by affinity propagation clustering is stored\"", ")", "parser...
Specify the command line options to parse. Returns ------- opts : optparse.Values instance Contains the option values in its 'dict' member variable. args[0] : string or file-handler The name of the file storing the data-set submitted for Affinity Propagation clustering.
[ "Specify", "the", "command", "line", "options", "to", "parse", ".", "Returns", "-------", "opts", ":", "optparse", ".", "Values", "instance", "Contains", "the", "option", "values", "in", "its", "dict", "member", "variable", ".", "args", "[", "0", "]", ":",...
python
train
50.272727
candango/firenado
firenado/config.py
https://github.com/candango/firenado/blob/4b1f628e485b521e161d64169c46a9818f26949f/firenado/config.py#L124-L143
def process_config(config, config_data): """ Populates config with data from the configuration data dict. It handles components, data, log, management and session sections from the configuration data. :param config: The config reference of the object that will hold the configuration data from the c...
[ "def", "process_config", "(", "config", ",", "config_data", ")", ":", "if", "'components'", "in", "config_data", ":", "process_components_config_section", "(", "config", ",", "config_data", "[", "'components'", "]", ")", "if", "'data'", "in", "config_data", ":", ...
Populates config with data from the configuration data dict. It handles components, data, log, management and session sections from the configuration data. :param config: The config reference of the object that will hold the configuration data from the config_data. :param config_data: The configura...
[ "Populates", "config", "with", "data", "from", "the", "configuration", "data", "dict", ".", "It", "handles", "components", "data", "log", "management", "and", "session", "sections", "from", "the", "configuration", "data", "." ]
python
train
46.1
hsolbrig/PyShEx
pyshex/shex_evaluator.py
https://github.com/hsolbrig/PyShEx/blob/9d659cc36e808afd66d4a6d60e8ea21cb12eb744/pyshex/shex_evaluator.py#L134-L152
def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None: """ Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema. :param shex: Schema """ self.pfx = None if shex is not None: if isinstance(shex, ShExJ.Schema): ...
[ "def", "schema", "(", "self", ",", "shex", ":", "Optional", "[", "Union", "[", "str", ",", "ShExJ", ".", "Schema", "]", "]", ")", "->", "None", ":", "self", ".", "pfx", "=", "None", "if", "shex", "is", "not", "None", ":", "if", "isinstance", "(",...
Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed schema. :param shex: Schema
[ "Set", "the", "schema", "to", "be", "used", ".", "Schema", "can", "either", "be", "a", "ShExC", "or", "ShExJ", "string", "or", "a", "pre", "-", "parsed", "schema", "." ]
python
train
44.052632
envi-idl/envipyarclib
envipyarclib/gptool/parameter/builder.py
https://github.com/envi-idl/envipyarclib/blob/90135652510c3d53c5f51177252c1fea2639bf22/envipyarclib/gptool/parameter/builder.py#L70-L73
def load_default_templates(self): """Load the default templates""" for importer, modname, is_pkg in pkgutil.iter_modules(templates.__path__): self.register_template('.'.join((templates.__name__, modname)))
[ "def", "load_default_templates", "(", "self", ")", ":", "for", "importer", ",", "modname", ",", "is_pkg", "in", "pkgutil", ".", "iter_modules", "(", "templates", ".", "__path__", ")", ":", "self", ".", "register_template", "(", "'.'", ".", "join", "(", "("...
Load the default templates
[ "Load", "the", "default", "templates" ]
python
train
57.5
getsentry/raven-python
raven/utils/stacks.py
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L128-L140
def iter_stack_frames(frames=None): """ Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. """ if not frames: frames = inspect.stack()[1:] for frame, lineno in ((f[0], f[2]) for f in r...
[ "def", "iter_stack_frames", "(", "frames", "=", "None", ")", ":", "if", "not", "frames", ":", "frames", "=", "inspect", ".", "stack", "(", ")", "[", "1", ":", "]", "for", "frame", ",", "lineno", "in", "(", "(", "f", "[", "0", "]", ",", "f", "["...
Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable.
[ "Given", "an", "optional", "list", "of", "frames", "(", "defaults", "to", "current", "stack", ")", "iterates", "over", "all", "frames", "that", "do", "not", "contain", "the", "__traceback_hide__", "local", "variable", "." ]
python
train
36.538462
RobotStudio/bors
bors/app/config.py
https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/config.py#L59-L67
def get_ws_subscriptions(self, apiname): """Returns the websocket subscriptions""" try: return self.services_by_name\ .get(apiname)\ .get("subscriptions")\ .copy() except AttributeError: raise Exception(f"Couldn'...
[ "def", "get_ws_subscriptions", "(", "self", ",", "apiname", ")", ":", "try", ":", "return", "self", ".", "services_by_name", ".", "get", "(", "apiname", ")", ".", "get", "(", "\"subscriptions\"", ")", ".", "copy", "(", ")", "except", "AttributeError", ":",...
Returns the websocket subscriptions
[ "Returns", "the", "websocket", "subscriptions" ]
python
train
38.666667
vtkiorg/vtki
vtki/common.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L111-L115
def points(self): """ returns a pointer to the points as a numpy object """ vtk_data = self.GetPoints().GetData() arr = vtk_to_numpy(vtk_data) return vtki_ndarray(arr, vtk_data)
[ "def", "points", "(", "self", ")", ":", "vtk_data", "=", "self", ".", "GetPoints", "(", ")", ".", "GetData", "(", ")", "arr", "=", "vtk_to_numpy", "(", "vtk_data", ")", "return", "vtki_ndarray", "(", "arr", ",", "vtk_data", ")" ]
returns a pointer to the points as a numpy object
[ "returns", "a", "pointer", "to", "the", "points", "as", "a", "numpy", "object" ]
python
train
41
michael-lazar/rtv
rtv/terminal.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/terminal.py#L144-L154
def addch(window, y, x, ch, attr): """ Curses addch() method that fixes a major bug in python 3.4. See http://bugs.python.org/issue21088 """ if sys.version_info[:3] == (3, 4, 0): y, x = x, y window.addch(y, x, ch, attr)
[ "def", "addch", "(", "window", ",", "y", ",", "x", ",", "ch", ",", "attr", ")", ":", "if", "sys", ".", "version_info", "[", ":", "3", "]", "==", "(", "3", ",", "4", ",", "0", ")", ":", "y", ",", "x", "=", "x", ",", "y", "window", ".", "...
Curses addch() method that fixes a major bug in python 3.4. See http://bugs.python.org/issue21088
[ "Curses", "addch", "()", "method", "that", "fixes", "a", "major", "bug", "in", "python", "3", ".", "4", "." ]
python
train
24.727273
nuagenetworks/bambou
bambou/nurest_login_controller.py
https://github.com/nuagenetworks/bambou/blob/d334fea23e384d3df8e552fe1849ad707941c666/bambou/nurest_login_controller.py#L273-L285
def impersonate(self, user, enterprise): """ Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enterprise where to use impersonation """ if not user or not enterprise: raise Val...
[ "def", "impersonate", "(", "self", ",", "user", ",", "enterprise", ")", ":", "if", "not", "user", "or", "not", "enterprise", ":", "raise", "ValueError", "(", "'You must set a user name and an enterprise name to begin impersonification'", ")", "self", ".", "_is_imperso...
Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enterprise where to use impersonation
[ "Impersonate", "a", "user", "in", "a", "enterprise" ]
python
train
37.769231
lingthio/Flask-User
flask_user/token_manager.py
https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/token_manager.py#L59-L77
def generate_token(self, *args): """ Convert a list of integers or strings, specified by ``*args``, into an encrypted, timestamped, and signed token. Note: strings may not contain any ``'|'`` characters, nor start with a ``'~'`` character as these are used as separators and integer indicators f...
[ "def", "generate_token", "(", "self", ",", "*", "args", ")", ":", "concatenated_str", "=", "self", ".", "encode_data_items", "(", "*", "args", ")", "token", "=", "self", ".", "encrypt_string", "(", "concatenated_str", ")", "return", "token" ]
Convert a list of integers or strings, specified by ``*args``, into an encrypted, timestamped, and signed token. Note: strings may not contain any ``'|'`` characters, nor start with a ``'~'`` character as these are used as separators and integer indicators for encoding. Example: :: ...
[ "Convert", "a", "list", "of", "integers", "or", "strings", "specified", "by", "*", "args", "into", "an", "encrypted", "timestamped", "and", "signed", "token", "." ]
python
train
40.736842
DheerendraRathor/django-auth-ldap-ng
django_auth_ldap/config.py
https://github.com/DheerendraRathor/django-auth-ldap-ng/blob/4d2458bd90c4539353c5bfd5ea793c1e59780ee8/django_auth_ldap/config.py#L170-L191
def _begin(self, connection, filterargs=(), escape=True): """ Begins an asynchronous search and returns the message id to retrieve the results. filterargs is an object that will be used for expansion of the filter string. If escape is True, values in filterargs will be escaped. ...
[ "def", "_begin", "(", "self", ",", "connection", ",", "filterargs", "=", "(", ")", ",", "escape", "=", "True", ")", ":", "if", "escape", ":", "filterargs", "=", "self", ".", "_escape_filterargs", "(", "filterargs", ")", "try", ":", "filterstr", "=", "s...
Begins an asynchronous search and returns the message id to retrieve the results. filterargs is an object that will be used for expansion of the filter string. If escape is True, values in filterargs will be escaped.
[ "Begins", "an", "asynchronous", "search", "and", "returns", "the", "message", "id", "to", "retrieve", "the", "results", "." ]
python
train
37.318182
marl/jams
jams/sonify.py
https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/sonify.py#L83-L103
def multi_segment(annotation, sr=22050, length=None, **kwargs): '''Sonify multi-level segmentations''' # Pentatonic scale, because why not PENT = [1, 32./27, 4./3, 3./2, 16./9] DURATION = 0.1 h_int, _ = hierarchy_flatten(annotation) if length is None: length = int(sr * (max(np.max(_) ...
[ "def", "multi_segment", "(", "annotation", ",", "sr", "=", "22050", ",", "length", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Pentatonic scale, because why not", "PENT", "=", "[", "1", ",", "32.", "/", "27", ",", "4.", "/", "3", ",", "3.", "/...
Sonify multi-level segmentations
[ "Sonify", "multi", "-", "level", "segmentations" ]
python
valid
36.142857
peterbe/gg
gg/builtins/merge/gg_merge.py
https://github.com/peterbe/gg/blob/2aace5bdb4a9b1cb65bea717784edf54c63b7bad/gg/builtins/merge/gg_merge.py#L8-L48
def merge(config): """Merge the current branch into master.""" repo = config.repo active_branch = repo.active_branch if active_branch.name == "master": error_out("You're already on the master branch.") if repo.is_dirty(): error_out( 'Repo is "dirty". ({})'.format( ...
[ "def", "merge", "(", "config", ")", ":", "repo", "=", "config", ".", "repo", "active_branch", "=", "repo", ".", "active_branch", "if", "active_branch", ".", "name", "==", "\"master\"", ":", "error_out", "(", "\"You're already on the master branch.\"", ")", "if",...
Merge the current branch into master.
[ "Merge", "the", "current", "branch", "into", "master", "." ]
python
train
30.853659
apple/turicreate
src/unity/python/turicreate/toolkits/recommender/util.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/recommender/util.py#L634-L782
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of lis...
[ "def", "_get_summary_struct", "(", "self", ")", ":", "stats", "=", "self", ".", "_list_fields", "(", ")", "options", "=", "self", ".", "_get_current_options", "(", ")", "section_titles", "=", "[", "]", "sections", "=", "[", "]", "observation_columns", "=", ...
Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of list of tuples) A list of summary sections...
[ "Returns", "a", "structured", "description", "of", "the", "model", "including", "(", "where", "relevant", ")", "the", "schema", "of", "the", "training", "data", "description", "of", "the", "training", "data", "training", "statistics", "and", "model", "hyperparam...
python
train
34.469799
openvax/pyensembl
pyensembl/locus.py
https://github.com/openvax/pyensembl/blob/4b995fb72e848206d6fbf11950cf30964cd9b3aa/pyensembl/locus.py#L120-L134
def offset(self, position): """Offset of given position from stranded start of this locus. For example, if a Locus goes from 10..20 and is on the negative strand, then the offset of position 13 is 7, whereas if the Locus is on the positive strand, then the offset is 3. """ ...
[ "def", "offset", "(", "self", ",", "position", ")", ":", "if", "position", ">", "self", ".", "end", "or", "position", "<", "self", ".", "start", ":", "raise", "ValueError", "(", "\"Position %d outside valid range %d..%d of %s\"", "%", "(", "position", ",", "...
Offset of given position from stranded start of this locus. For example, if a Locus goes from 10..20 and is on the negative strand, then the offset of position 13 is 7, whereas if the Locus is on the positive strand, then the offset is 3.
[ "Offset", "of", "given", "position", "from", "stranded", "start", "of", "this", "locus", "." ]
python
train
42.933333
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L695-L708
def _ConsumeAnyTypeUrl(self, tokenizer): """Consumes a google.protobuf.Any type URL and returns the type name.""" # Consume "type.googleapis.com/". tokenizer.ConsumeIdentifier() tokenizer.Consume('.') tokenizer.ConsumeIdentifier() tokenizer.Consume('.') tokenizer.ConsumeIdentifier() toke...
[ "def", "_ConsumeAnyTypeUrl", "(", "self", ",", "tokenizer", ")", ":", "# Consume \"type.googleapis.com/\".", "tokenizer", ".", "ConsumeIdentifier", "(", ")", "tokenizer", ".", "Consume", "(", "'.'", ")", "tokenizer", ".", "ConsumeIdentifier", "(", ")", "tokenizer", ...
Consumes a google.protobuf.Any type URL and returns the type name.
[ "Consumes", "a", "google", ".", "protobuf", ".", "Any", "type", "URL", "and", "returns", "the", "type", "name", "." ]
python
train
37.5
scanny/python-pptx
pptx/chart/category.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/category.py#L60-L80
def flattened_labels(self): """ Return a sequence of tuples, each containing the flattened hierarchy of category labels for a leaf category. Each tuple is in parent -> child order, e.g. ``('US', 'CA', 'San Francisco')``, with the leaf category appearing last. If this categories c...
[ "def", "flattened_labels", "(", "self", ")", ":", "cat", "=", "self", ".", "_xChart", ".", "cat", "if", "cat", "is", "None", ":", "return", "(", ")", "if", "cat", ".", "multiLvlStrRef", "is", "None", ":", "return", "tuple", "(", "[", "(", "category",...
Return a sequence of tuples, each containing the flattened hierarchy of category labels for a leaf category. Each tuple is in parent -> child order, e.g. ``('US', 'CA', 'San Francisco')``, with the leaf category appearing last. If this categories collection is non-hierarchical, each tupl...
[ "Return", "a", "sequence", "of", "tuples", "each", "containing", "the", "flattened", "hierarchy", "of", "category", "labels", "for", "a", "leaf", "category", ".", "Each", "tuple", "is", "in", "parent", "-", ">", "child", "order", "e", ".", "g", ".", "(",...
python
train
40.761905
cqparts/cqparts
src/cqparts_bearings/ball.py
https://github.com/cqparts/cqparts/blob/018e87e14c2c4d1d40b4bfe6a7e22bcf9baf0a53/src/cqparts_bearings/ball.py#L87-L99
def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.): """ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float`...
[ "def", "get_max_ballcount", "(", "cls", ",", "ball_diam", ",", "rolling_radius", ",", "min_gap", "=", "0.", ")", ":", "min_arc", "=", "asin", "(", "(", "(", "ball_diam", "+", "min_gap", ")", "/", "2", ")", "/", "rolling_radius", ")", "*", "2", "return"...
The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float` :return: maximum ball count :rtype: :class:`int`
[ "The", "maximum", "number", "of", "balls", "given", "rolling_radius", "and", "ball_diam" ]
python
train
38.307692
nicolargo/glances
glances/events.py
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/events.py#L78-L90
def get_event_sort_key(self, event_type): """Return the process sort key""" # Process sort depending on alert type if event_type.startswith("MEM"): # Sort TOP process by memory_percent ret = 'memory_percent' elif event_type.startswith("CPU_IOWAIT"): # ...
[ "def", "get_event_sort_key", "(", "self", ",", "event_type", ")", ":", "# Process sort depending on alert type", "if", "event_type", ".", "startswith", "(", "\"MEM\"", ")", ":", "# Sort TOP process by memory_percent", "ret", "=", "'memory_percent'", "elif", "event_type", ...
Return the process sort key
[ "Return", "the", "process", "sort", "key" ]
python
train
37.615385
Unidata/MetPy
metpy/calc/basic.py
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/basic.py#L179-L235
def windchill(temperature, speed, face_level_winds=False, mask_undefined=True): r"""Calculate the Wind Chill Temperature Index (WCTI). Calculates WCTI from the current temperature and wind speed using the formula outlined by the FCM [FCMR192003]_. Specifically, these formulas assume that wind speed is...
[ "def", "windchill", "(", "temperature", ",", "speed", ",", "face_level_winds", "=", "False", ",", "mask_undefined", "=", "True", ")", ":", "# Correct for lower height measurement of winds if necessary", "if", "face_level_winds", ":", "# No in-place so that we copy", "# noin...
r"""Calculate the Wind Chill Temperature Index (WCTI). Calculates WCTI from the current temperature and wind speed using the formula outlined by the FCM [FCMR192003]_. Specifically, these formulas assume that wind speed is measured at 10m. If, instead, the speeds are measured at face level, the winds...
[ "r", "Calculate", "the", "Wind", "Chill", "Temperature", "Index", "(", "WCTI", ")", "." ]
python
train
37.964912
mdeous/fatbotslim
fatbotslim/irc/bot.py
https://github.com/mdeous/fatbotslim/blob/341595d24454a79caee23750eac271f9d0626c88/fatbotslim/irc/bot.py#L243-L276
def _handle(self, msg): """ Pass a received message to the registered handlers. :param msg: received message :type msg: :class:`fatbotslim.irc.Message` """ def handler_yielder(): for handler in self.handlers: yield handler def handle...
[ "def", "_handle", "(", "self", ",", "msg", ")", ":", "def", "handler_yielder", "(", ")", ":", "for", "handler", "in", "self", ".", "handlers", ":", "yield", "handler", "def", "handler_callback", "(", "_", ")", ":", "if", "msg", ".", "propagate", ":", ...
Pass a received message to the registered handlers. :param msg: received message :type msg: :class:`fatbotslim.irc.Message`
[ "Pass", "a", "received", "message", "to", "the", "registered", "handlers", "." ]
python
train
29.647059
3DLIRIOUS/MeshLabXML
meshlabxml/select.py
https://github.com/3DLIRIOUS/MeshLabXML/blob/177cce21e92baca500f56a932d66bd9a33257af8/meshlabxml/select.py#L145-L163
def shrink(script, iterations=1): """ Shrink (erode, reduce) the current set of selected faces Args: script: the FilterScript object or script filename to write the filter to. iterations (int): the number of times to shrink the selection. Layer stack: No impacts Me...
[ "def", "shrink", "(", "script", ",", "iterations", "=", "1", ")", ":", "filter_xml", "=", "' <filter name=\"Erode Selection\"/>\\n'", "for", "_", "in", "range", "(", "iterations", ")", ":", "util", ".", "write_filter", "(", "script", ",", "filter_xml", ")", ...
Shrink (erode, reduce) the current set of selected faces Args: script: the FilterScript object or script filename to write the filter to. iterations (int): the number of times to shrink the selection. Layer stack: No impacts MeshLab versions: 2016.12 1....
[ "Shrink", "(", "erode", "reduce", ")", "the", "current", "set", "of", "selected", "faces" ]
python
test
26.789474
BDNYC/astrodbkit
astrodbkit/astrodb.py
https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L2608-L2620
def scrub(data, units=False): """ For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed. """ units = [i.unit if hasattr(i, 'unit') else 1 for i in data] data = [np.asarray(i.value if hasattr(i, 'unit') else i, dtype=...
[ "def", "scrub", "(", "data", ",", "units", "=", "False", ")", ":", "units", "=", "[", "i", ".", "unit", "if", "hasattr", "(", "i", ",", "'unit'", ")", "else", "1", "for", "i", "in", "data", "]", "data", "=", "[", "np", ".", "asarray", "(", "i...
For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed.
[ "For", "input", "data", "[", "w", "f", "e", "]", "or", "[", "w", "f", "]", "returns", "the", "list", "with", "NaN", "negative", "and", "zero", "flux", "(", "and", "corresponding", "wavelengths", "and", "errors", ")", "removed", "." ]
python
train
61.923077
alimanfoo/csvvalidator
csvvalidator.py
https://github.com/alimanfoo/csvvalidator/blob/50a86eefdc549c48f65a91a5c0a66099010ee65d/csvvalidator.py#L908-L914
def _as_dict(self, r): """Convert the record to a dictionary using field names as keys.""" d = dict() for i, f in enumerate(self._field_names): d[f] = r[i] if i < len(r) else None return d
[ "def", "_as_dict", "(", "self", ",", "r", ")", ":", "d", "=", "dict", "(", ")", "for", "i", ",", "f", "in", "enumerate", "(", "self", ".", "_field_names", ")", ":", "d", "[", "f", "]", "=", "r", "[", "i", "]", "if", "i", "<", "len", "(", ...
Convert the record to a dictionary using field names as keys.
[ "Convert", "the", "record", "to", "a", "dictionary", "using", "field", "names", "as", "keys", "." ]
python
valid
32.428571
saltstack/salt
salt/spm/pkgdb/sqlite3.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L20-L69
def init(): ''' Get an sqlite3 connection, and initialize the package database if necessary ''' if not os.path.exists(__opts__['spm_cache_dir']): log.debug('Creating SPM cache directory at %s', __opts__['spm_db']) os.makedirs(__opts__['spm_cache_dir']) if not os.path.exists(__opts__...
[ "def", "init", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "__opts__", "[", "'spm_cache_dir'", "]", ")", ":", "log", ".", "debug", "(", "'Creating SPM cache directory at %s'", ",", "__opts__", "[", "'spm_db'", "]", ")", "os", ".", ...
Get an sqlite3 connection, and initialize the package database if necessary
[ "Get", "an", "sqlite3", "connection", "and", "initialize", "the", "package", "database", "if", "necessary" ]
python
train
28.04
talentpair/featurevectormatrix
featurevectormatrix/__init__.py
https://github.com/talentpair/featurevectormatrix/blob/1327026f7e46138947ba55433c11a85bca1adc5d/featurevectormatrix/__init__.py#L206-L225
def get_row_dict(self, row_idx): """ Return a dictionary representation for a matrix row :param row_idx: which row :return: a dict of feature keys/values, not including ones which are the default value """ try: row = self._rows[row_idx] except TypeError: ...
[ "def", "get_row_dict", "(", "self", ",", "row_idx", ")", ":", "try", ":", "row", "=", "self", ".", "_rows", "[", "row_idx", "]", "except", "TypeError", ":", "row", "=", "self", ".", "_rows", "[", "self", ".", "_row_name_idx", "[", "row_idx", "]", "]"...
Return a dictionary representation for a matrix row :param row_idx: which row :return: a dict of feature keys/values, not including ones which are the default value
[ "Return", "a", "dictionary", "representation", "for", "a", "matrix", "row" ]
python
train
32.8
nschloe/accupy
accupy/dot.py
https://github.com/nschloe/accupy/blob/63a031cab7f4d3b9ba1073f9328c10c1862d1c4d/accupy/dot.py#L37-L48
def fdot(x, y): """Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3. """ xx = x.reshape(-1, x.shape[-1]) yy = y.reshape(y.shape[0], -1) xx = numpy.ascontiguousarray(xx) yy = numpy.ascontiguousarray(yy) r = _accupy.kdot_helper(xx, yy).reshape((-1,) + x.shape[:-1...
[ "def", "fdot", "(", "x", ",", "y", ")", ":", "xx", "=", "x", ".", "reshape", "(", "-", "1", ",", "x", ".", "shape", "[", "-", "1", "]", ")", "yy", "=", "y", ".", "reshape", "(", "y", ".", "shape", "[", "0", "]", ",", "-", "1", ")", "x...
Algorithm 5.10. Dot product algorithm in K-fold working precision, K >= 3.
[ "Algorithm", "5", ".", "10", ".", "Dot", "product", "algorithm", "in", "K", "-", "fold", "working", "precision", "K", ">", "=", "3", "." ]
python
train
28.666667
svenevs/exhale
exhale/parse.py
https://github.com/svenevs/exhale/blob/fe7644829057af622e467bb529db6c03a830da99/exhale/parse.py#L201-L245
def getBriefAndDetailedRST(textRoot, node): ''' Given an input ``node``, return a tuple of strings where the first element of the return is the ``brief`` description and the second is the ``detailed`` description. .. todo:: actually document this ''' node_xml_contents = utils.nodeCompoundXM...
[ "def", "getBriefAndDetailedRST", "(", "textRoot", ",", "node", ")", ":", "node_xml_contents", "=", "utils", ".", "nodeCompoundXMLContents", "(", "node", ")", "if", "not", "node_xml_contents", ":", "return", "\"\"", ",", "\"\"", "try", ":", "node_soup", "=", "B...
Given an input ``node``, return a tuple of strings where the first element of the return is the ``brief`` description and the second is the ``detailed`` description. .. todo:: actually document this
[ "Given", "an", "input", "node", "return", "a", "tuple", "of", "strings", "where", "the", "first", "element", "of", "the", "return", "is", "the", "brief", "description", "and", "the", "second", "is", "the", "detailed", "description", "." ]
python
train
42.866667
google/tangent
tangent/reverse_ad.py
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/reverse_ad.py#L853-L920
def store_state(node, reaching, defined, stack): """Push the final state of the primal onto the stack for the adjoint. Python's scoping rules make it possible for variables to not be defined in certain blocks based on the control flow path taken at runtime. In order to make sure we don't try to push non-existi...
[ "def", "store_state", "(", "node", ",", "reaching", ",", "defined", ",", "stack", ")", ":", "defs", "=", "[", "def_", "for", "def_", "in", "reaching", "if", "not", "isinstance", "(", "def_", "[", "1", "]", ",", "gast", ".", "arguments", ")", "]", "...
Push the final state of the primal onto the stack for the adjoint. Python's scoping rules make it possible for variables to not be defined in certain blocks based on the control flow path taken at runtime. In order to make sure we don't try to push non-existing variables onto the stack, we defined these variab...
[ "Push", "the", "final", "state", "of", "the", "primal", "onto", "the", "stack", "for", "the", "adjoint", "." ]
python
train
38.926471
wandb/client
wandb/vendor/prompt_toolkit/interface.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L763-L785
def suspend_to_background(self, suspend_group=True): """ (Not thread safe -- to be called from inside the key bindings.) Suspend process. :param suspend_group: When true, suspend the whole process group. (This is the default, and probably what you want.) """ ...
[ "def", "suspend_to_background", "(", "self", ",", "suspend_group", "=", "True", ")", ":", "# Only suspend when the opperating system supports it.", "# (Not on Windows.)", "if", "hasattr", "(", "signal", ",", "'SIGTSTP'", ")", ":", "def", "run", "(", ")", ":", "# Sen...
(Not thread safe -- to be called from inside the key bindings.) Suspend process. :param suspend_group: When true, suspend the whole process group. (This is the default, and probably what you want.)
[ "(", "Not", "thread", "safe", "--", "to", "be", "called", "from", "inside", "the", "key", "bindings", ".", ")", "Suspend", "process", "." ]
python
train
38.956522
timothydmorton/isochrones
isochrones/starmodel.py
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L1104-L1159
def load_hdf(cls, filename, path='', name=None): """ A class method to load a saved StarModel from an HDF5 file. File must have been created by a call to :func:`StarModel.save_hdf`. :param filename: H5 file to load. :param path: (optional) Path within H...
[ "def", "load_hdf", "(", "cls", ",", "filename", ",", "path", "=", "''", ",", "name", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "IOError", "(", "'{} does not exist.'", ".", "format", "(",...
A class method to load a saved StarModel from an HDF5 file. File must have been created by a call to :func:`StarModel.save_hdf`. :param filename: H5 file to load. :param path: (optional) Path within HDF file. :return: :class:`StarModel` object.
[ "A", "class", "method", "to", "load", "a", "saved", "StarModel", "from", "an", "HDF5", "file", "." ]
python
train
26.464286
Rapptz/discord.py
discord/user.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L810-L844
async def profile(self): """|coro| Gets the user's profile. .. note:: This only applies to non-bot accounts. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the profile failed. Returns...
[ "async", "def", "profile", "(", "self", ")", ":", "state", "=", "self", ".", "_state", "data", "=", "await", "state", ".", "http", ".", "get_user_profile", "(", "self", ".", "id", ")", "def", "transform", "(", "d", ")", ":", "return", "state", ".", ...
|coro| Gets the user's profile. .. note:: This only applies to non-bot accounts. Raises ------- Forbidden Not allowed to fetch profiles. HTTPException Fetching the profile failed. Returns -------- :class:`Pr...
[ "|coro|" ]
python
train
27
CalebBell/thermo
thermo/safety.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L890-L902
def fire_mixing(ys=None, FLs=None): # pragma: no cover ''' Crowl, Daniel A., and Joseph F. Louvar. Chemical Process Safety: Fundamentals with Applications. 2E. Upper Saddle River, N.J: Prentice Hall, 2001. >>> fire_mixing(ys=normalize([0.0024, 0.0061, 0.0015]), FLs=[.012, .053, .031]) 0.02751...
[ "def", "fire_mixing", "(", "ys", "=", "None", ",", "FLs", "=", "None", ")", ":", "# pragma: no cover", "return", "1.", "/", "sum", "(", "[", "yi", "/", "FLi", "for", "yi", ",", "FLi", "in", "zip", "(", "ys", ",", "FLs", ")", "]", ")" ]
Crowl, Daniel A., and Joseph F. Louvar. Chemical Process Safety: Fundamentals with Applications. 2E. Upper Saddle River, N.J: Prentice Hall, 2001. >>> fire_mixing(ys=normalize([0.0024, 0.0061, 0.0015]), FLs=[.012, .053, .031]) 0.02751172136637643 >>> fire_mixing(ys=normalize([0.0024, 0.0061, 0.001...
[ "Crowl", "Daniel", "A", ".", "and", "Joseph", "F", ".", "Louvar", ".", "Chemical", "Process", "Safety", ":", "Fundamentals", "with", "Applications", ".", "2E", ".", "Upper", "Saddle", "River", "N", ".", "J", ":", "Prentice", "Hall", "2001", "." ]
python
valid
37.692308
IRC-SPHERE/HyperStream
hyperstream/workflow/workflow.py
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/workflow/workflow.py#L186-L285
def create_factor(self, tool, sources, sink, alignment_node=None): """ Creates a factor. Instantiates a single tool for all of the plates, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that var...
[ "def", "create_factor", "(", "self", ",", "tool", ",", "sources", ",", "sink", ",", "alignment_node", "=", "None", ")", ":", "# if isinstance(tool, dict):", "# tool = self.channels.get_tool(**tool)", "if", "not", "isinstance", "(", "tool", ",", "BaseTool", ")", ...
Creates a factor. Instantiates a single tool for all of the plates, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that vary over a plate, an extra input stream should be used :param alignment_...
[ "Creates", "a", "factor", ".", "Instantiates", "a", "single", "tool", "for", "all", "of", "the", "plates", "and", "connects", "the", "source", "and", "sink", "nodes", "with", "that", "tool", "." ]
python
train
53.85
soldag/python-pwmled
pwmled/driver/pca9685.py
https://github.com/soldag/python-pwmled/blob/09cde36ecc0153fa81dc2a1b9bb07d1c0e418c8c/pwmled/driver/pca9685.py#L25-L32
def _set_pwm(self, raw_values): """ Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-4095). """ for i in range(len(self._pins)): self._device.set_pwm(self._pins[i], 0, raw_values[i])
[ "def", "_set_pwm", "(", "self", ",", "raw_values", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_pins", ")", ")", ":", "self", ".", "_device", ".", "set_pwm", "(", "self", ".", "_pins", "[", "i", "]", ",", "0", ",", "raw_...
Set pwm values on the controlled pins. :param raw_values: Raw values to set (0-4095).
[ "Set", "pwm", "values", "on", "the", "controlled", "pins", "." ]
python
train
32.25
treycucco/bidon
bidon/util/terminal.py
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/terminal.py#L101-L107
def ratio_and_percentage_with_time_remaining(current, total, time_remaining): """Returns the progress ratio, percentage and time remaining.""" return "{} / {} ({}% completed) (~{} remaining)".format( current, total, int(current / total * 100), time_remaining)
[ "def", "ratio_and_percentage_with_time_remaining", "(", "current", ",", "total", ",", "time_remaining", ")", ":", "return", "\"{} / {} ({}% completed) (~{} remaining)\"", ".", "format", "(", "current", ",", "total", ",", "int", "(", "current", "/", "total", "*", "10...
Returns the progress ratio, percentage and time remaining.
[ "Returns", "the", "progress", "ratio", "percentage", "and", "time", "remaining", "." ]
python
train
40.714286
StackStorm/pybind
pybind/nos/v7_2_0/rbridge_id/event_handler/activate/name/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/rbridge_id/event_handler/activate/name/__init__.py#L273-L294
def _set_trigger_mode(self, v, load=False): """ Setter method for trigger_mode, mapped from YANG variable /rbridge_id/event_handler/activate/name/trigger_mode (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_trigger_mode is considered as a private method...
[ "def", "_set_trigger_mode", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "b...
Setter method for trigger_mode, mapped from YANG variable /rbridge_id/event_handler/activate/name/trigger_mode (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_trigger_mode is considered as a private method. Backends looking to populate this variable should ...
[ "Setter", "method", "for", "trigger_mode", "mapped", "from", "YANG", "variable", "/", "rbridge_id", "/", "event_handler", "/", "activate", "/", "name", "/", "trigger_mode", "(", "enumeration", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "c...
python
train
106.863636
nitely/kua
kua/routes.py
https://github.com/nitely/kua/blob/6ffc9d0426e87a34cf8c3f8e7aedac6d35e59cb6/kua/routes.py#L213-L231
def _deconstruct_url(self, url: str) -> List[str]: """ Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern...
[ "def", "_deconstruct_url", "(", "self", ",", "url", ":", "str", ")", "->", "List", "[", "str", "]", ":", "parts", "=", "url", ".", "split", "(", "'/'", ",", "self", ".", "_max_depth", "+", "1", ")", "if", "depth_of", "(", "parts", ")", ">", "self...
Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern :private:
[ "Split", "a", "regular", "URL", "into", "parts" ]
python
train
26.052632
kyan001/PyKyanToolKit
KyanToolKit.py
https://github.com/kyan001/PyKyanToolKit/blob/a3974fcd45ce41f743b4a3d42af961fedea8fda8/KyanToolKit.py#L98-L107
def clearScreen(cls): """Clear the screen""" if "win32" in sys.platform: os.system('cls') elif "linux" in sys.platform: os.system('clear') elif 'darwin' in sys.platform: os.system('clear') else: cit.err("No clearScreen for " + sys.p...
[ "def", "clearScreen", "(", "cls", ")", ":", "if", "\"win32\"", "in", "sys", ".", "platform", ":", "os", ".", "system", "(", "'cls'", ")", "elif", "\"linux\"", "in", "sys", ".", "platform", ":", "os", ".", "system", "(", "'clear'", ")", "elif", "'darw...
Clear the screen
[ "Clear", "the", "screen" ]
python
train
31.9
noahbenson/neuropythy
neuropythy/freesurfer/core.py
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/freesurfer/core.py#L650-L661
def save_freesurfer_geometry(filename, obj, volume_info=None, create_stamp=None): ''' save_mgh(filename, obj) saves the given object to the given filename in the mgh format and returns the filename. All options that can be given to the to_mgh function can also be passed to this function; they are...
[ "def", "save_freesurfer_geometry", "(", "filename", ",", "obj", ",", "volume_info", "=", "None", ",", "create_stamp", "=", "None", ")", ":", "obj", "=", "geo", ".", "to_mesh", "(", "obj", ")", "fsio", ".", "write_geometry", "(", "filename", ",", "obj", "...
save_mgh(filename, obj) saves the given object to the given filename in the mgh format and returns the filename. All options that can be given to the to_mgh function can also be passed to this function; they are used to modify the object prior to exporting it.
[ "save_mgh", "(", "filename", "obj", ")", "saves", "the", "given", "object", "to", "the", "given", "filename", "in", "the", "mgh", "format", "and", "returns", "the", "filename", "." ]
python
train
46.666667
kensho-technologies/graphql-compiler
graphql_compiler/compiler/common.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/common.py#L56-L86
def compile_graphql_to_gremlin(schema, graphql_string, type_equivalence_hints=None): """Compile the GraphQL input using the schema into a Gremlin query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query...
[ "def", "compile_graphql_to_gremlin", "(", "schema", ",", "graphql_string", ",", "type_equivalence_hints", "=", "None", ")", ":", "lowering_func", "=", "ir_lowering_gremlin", ".", "lower_ir", "query_emitter_func", "=", "emit_gremlin", ".", "emit_code_from_ir", "return", ...
Compile the GraphQL input using the schema into a Gremlin query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to compile to Gremlin, as a string type_equivalence_hints: optional dict of GraphQL...
[ "Compile", "the", "GraphQL", "input", "using", "the", "schema", "into", "a", "Gremlin", "query", "and", "associated", "metadata", "." ]
python
train
61.774194
apache/incubator-mxnet
example/rcnn/symdata/bbox.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/bbox.py#L146-L180
def nms(dets, thresh): """ greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep """ x1 = dets[:, 0] y1 = dets[:, 1] x2...
[ "def", "nms", "(", "dets", ",", "thresh", ")", ":", "x1", "=", "dets", "[", ":", ",", "0", "]", "y1", "=", "dets", "[", ":", ",", "1", "]", "x2", "=", "dets", "[", ":", ",", "2", "]", "y2", "=", "dets", "[", ":", ",", "3", "]", "scores"...
greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep
[ "greedily", "select", "boxes", "with", "high", "confidence", "and", "overlap", "with", "current", "maximum", "<", "=", "thresh", "rule", "out", "overlap", ">", "=", "thresh", ":", "param", "dets", ":", "[[", "x1", "y1", "x2", "y2", "score", "]]", ":", ...
python
train
27.285714
delfick/harpoon
harpoon/option_spec/command_objs.py
https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/option_spec/command_objs.py#L83-L94
def external_dependencies(self): """ Return all the external images this Dockerfile will depend on These are images from self.dependent_images that aren't defined in this configuration. """ found = [] for dep in self.dependent_images: if isinstance(dep, six.s...
[ "def", "external_dependencies", "(", "self", ")", ":", "found", "=", "[", "]", "for", "dep", "in", "self", ".", "dependent_images", ":", "if", "isinstance", "(", "dep", ",", "six", ".", "string_types", ")", ":", "if", "dep", "not", "in", "found", ":", ...
Return all the external images this Dockerfile will depend on These are images from self.dependent_images that aren't defined in this configuration.
[ "Return", "all", "the", "external", "images", "this", "Dockerfile", "will", "depend", "on" ]
python
train
35.583333
chrislit/abydos
abydos/stats/_mean.py
https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L709-L744
def var(nums, mean_func=amean, ddof=0): r"""Calculate the variance. The variance (:math:`\sigma^2`) of a series of numbers (:math:`x_i`) with mean :math:`\mu` and population :math:`N` is: :math:`\sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2`. Cf. https://en.wikipedia.org/wiki/Variance Para...
[ "def", "var", "(", "nums", ",", "mean_func", "=", "amean", ",", "ddof", "=", "0", ")", ":", "x_bar", "=", "mean_func", "(", "nums", ")", "return", "sum", "(", "(", "x", "-", "x_bar", ")", "**", "2", "for", "x", "in", "nums", ")", "/", "(", "l...
r"""Calculate the variance. The variance (:math:`\sigma^2`) of a series of numbers (:math:`x_i`) with mean :math:`\mu` and population :math:`N` is: :math:`\sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2`. Cf. https://en.wikipedia.org/wiki/Variance Parameters ---------- nums : list ...
[ "r", "Calculate", "the", "variance", "." ]
python
valid
23
MisterY/price-database
pricedb/app.py
https://github.com/MisterY/price-database/blob/b4fd366b7763891c690fe3000b8840e656da023e/pricedb/app.py#L218-L224
def get_security_repository(self): """ Security repository """ from .repositories import SecurityRepository if not self.security_repo: self.security_repo = SecurityRepository(self.session) return self.security_repo
[ "def", "get_security_repository", "(", "self", ")", ":", "from", ".", "repositories", "import", "SecurityRepository", "if", "not", "self", ".", "security_repo", ":", "self", ".", "security_repo", "=", "SecurityRepository", "(", "self", ".", "session", ")", "retu...
Security repository
[ "Security", "repository" ]
python
test
36.142857
fermiPy/fermipy
fermipy/jobs/link.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/link.py#L631-L646
def update_args(self, override_args): """Update the argument used to invoke the application Note that this will also update the dictionary of input and output files. Parameters ----------- override_args : dict Dictionary of arguments to override the current values ...
[ "def", "update_args", "(", "self", ",", "override_args", ")", ":", "self", ".", "args", "=", "extract_arguments", "(", "override_args", ",", "self", ".", "args", ")", "self", ".", "_latch_file_info", "(", ")", "scratch_dir", "=", "self", ".", "args", ".", ...
Update the argument used to invoke the application Note that this will also update the dictionary of input and output files. Parameters ----------- override_args : dict Dictionary of arguments to override the current values
[ "Update", "the", "argument", "used", "to", "invoke", "the", "application" ]
python
train
35.5
scottgigante/tasklogger
tasklogger/api.py
https://github.com/scottgigante/tasklogger/blob/06a263715d2db0653615c17b2df14b8272967b8d/tasklogger/api.py#L152-L170
def log_critical(msg, logger="TaskLogger"): """Log a CRITICAL message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged name : `str`, optional (default: "TaskLogger") Name used to retrieve the unique TaskLogger ...
[ "def", "log_critical", "(", "msg", ",", "logger", "=", "\"TaskLogger\"", ")", ":", "tasklogger", "=", "get_tasklogger", "(", "logger", ")", "tasklogger", ".", "critical", "(", "msg", ")", "return", "tasklogger" ]
Log a CRITICAL message Convenience function to log a message to the default Logger Parameters ---------- msg : str Message to be logged name : `str`, optional (default: "TaskLogger") Name used to retrieve the unique TaskLogger Returns ------- logger : TaskLogger
[ "Log", "a", "CRITICAL", "message" ]
python
train
23.421053
SectorLabs/django-postgres-extra
psqlextra/backend/base.py
https://github.com/SectorLabs/django-postgres-extra/blob/eef2ed5504d225858d4e4f5d77a838082ca6053e/psqlextra/backend/base.py#L89-L95
def delete_model(self, model): """Ran when a model is being deleted.""" for mixin in self.post_processing_mixins: mixin.delete_model(model) super().delete_model(model)
[ "def", "delete_model", "(", "self", ",", "model", ")", ":", "for", "mixin", "in", "self", ".", "post_processing_mixins", ":", "mixin", ".", "delete_model", "(", "model", ")", "super", "(", ")", ".", "delete_model", "(", "model", ")" ]
Ran when a model is being deleted.
[ "Ran", "when", "a", "model", "is", "being", "deleted", "." ]
python
test
28.428571
JNRowe/upoints
upoints/edist.py
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/edist.py#L520-L541
def read_csv(filename): """Pull locations from a user's CSV file. Read gpsbabel_'s CSV output format .. _gpsbabel: http://www.gpsbabel.org/ Args: filename (str): CSV file to parse Returns: tuple of dict and list: List of locations as ``str`` objects """ field_names = ('la...
[ "def", "read_csv", "(", "filename", ")", ":", "field_names", "=", "(", "'latitude'", ",", "'longitude'", ",", "'name'", ")", "data", "=", "utils", ".", "prepare_csv_read", "(", "filename", ",", "field_names", ",", "skipinitialspace", "=", "True", ")", "locat...
Pull locations from a user's CSV file. Read gpsbabel_'s CSV output format .. _gpsbabel: http://www.gpsbabel.org/ Args: filename (str): CSV file to parse Returns: tuple of dict and list: List of locations as ``str`` objects
[ "Pull", "locations", "from", "a", "user", "s", "CSV", "file", "." ]
python
train
29.363636
nickmckay/LiPD-utilities
Python/lipd/jsons.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L337-L354
def idx_name_to_num(L): """ Switch from index-by-name to index-by-number. :param dict L: Metadata :return dict: Modified metadata """ logger_jsons.info("enter idx_name_to_num") # Process the paleoData section if "paleoData" in L: L["paleoData"] = _export_section(L["paleoData"], ...
[ "def", "idx_name_to_num", "(", "L", ")", ":", "logger_jsons", ".", "info", "(", "\"enter idx_name_to_num\"", ")", "# Process the paleoData section", "if", "\"paleoData\"", "in", "L", ":", "L", "[", "\"paleoData\"", "]", "=", "_export_section", "(", "L", "[", "\"...
Switch from index-by-name to index-by-number. :param dict L: Metadata :return dict: Modified metadata
[ "Switch", "from", "index", "-", "by", "-", "name", "to", "index", "-", "by", "-", "number", ".", ":", "param", "dict", "L", ":", "Metadata", ":", "return", "dict", ":", "Modified", "metadata" ]
python
train
27.722222
akatrevorjay/uninhibited
uninhibited/dispatch.py
https://github.com/akatrevorjay/uninhibited/blob/f23079fe61cf831fa274d3c60bda8076c571d3f1/uninhibited/dispatch.py#L204-L216
def _attach_handler_events(self, handler, events=None): """ Search handler for methods named after events, attaching to event handlers as applicable. :param object handler: Handler instance :param list events: List of event names to look for. If not specified, will do all known event na...
[ "def", "_attach_handler_events", "(", "self", ",", "handler", ",", "events", "=", "None", ")", ":", "if", "not", "events", ":", "events", "=", "self", "for", "name", "in", "events", ":", "meth", "=", "getattr", "(", "handler", ",", "name", ",", "None",...
Search handler for methods named after events, attaching to event handlers as applicable. :param object handler: Handler instance :param list events: List of event names to look for. If not specified, will do all known event names.
[ "Search", "handler", "for", "methods", "named", "after", "events", "attaching", "to", "event", "handlers", "as", "applicable", "." ]
python
train
39.384615
rueckstiess/mtools
mtools/util/logfile.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/util/logfile.py#L84-L94
def filesize(self): """ Lazy evaluation of start and end of logfile. Returns None for stdin input currently. """ if self.from_stdin: return None if not self._filesize: self._calculate_bounds() return self._filesize
[ "def", "filesize", "(", "self", ")", ":", "if", "self", ".", "from_stdin", ":", "return", "None", "if", "not", "self", ".", "_filesize", ":", "self", ".", "_calculate_bounds", "(", ")", "return", "self", ".", "_filesize" ]
Lazy evaluation of start and end of logfile. Returns None for stdin input currently.
[ "Lazy", "evaluation", "of", "start", "and", "end", "of", "logfile", "." ]
python
train
25.909091
robehickman/simple-http-file-sync
shttpfs/common.py
https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L56-L62
def make_dirs_if_dont_exist(path): """ Create directories in path if they do not exist """ if path[-1] not in ['/']: path += '/' path = os.path.dirname(path) if path != '': try: os.makedirs(path) except OSError: pass
[ "def", "make_dirs_if_dont_exist", "(", "path", ")", ":", "if", "path", "[", "-", "1", "]", "not", "in", "[", "'/'", "]", ":", "path", "+=", "'/'", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "path", "!=", "''", ":", ...
Create directories in path if they do not exist
[ "Create", "directories", "in", "path", "if", "they", "do", "not", "exist" ]
python
train
34.571429
cdgriffith/Reusables
reusables/string_manipulation.py
https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/string_manipulation.py#L97-L135
def roman_to_int(roman_string): """ Converts a string of roman numbers into an integer. .. code: python reusables.roman_to_int("XXXVI") # 36 :param roman_string: XVI or similar :return: parsed integer """ roman_string = roman_string.upper().strip() if "IIII" in roman_...
[ "def", "roman_to_int", "(", "roman_string", ")", ":", "roman_string", "=", "roman_string", ".", "upper", "(", ")", ".", "strip", "(", ")", "if", "\"IIII\"", "in", "roman_string", ":", "raise", "ValueError", "(", "\"Malformed roman string\"", ")", "value", "=",...
Converts a string of roman numbers into an integer. .. code: python reusables.roman_to_int("XXXVI") # 36 :param roman_string: XVI or similar :return: parsed integer
[ "Converts", "a", "string", "of", "roman", "numbers", "into", "an", "integer", "." ]
python
train
32.410256
nvdv/vprof
vprof/code_heatmap.py
https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/code_heatmap.py#L85-L89
def fill_heatmap(self): """Fills code heatmap and execution count dictionaries.""" for module_path, lineno, runtime in self.lines_without_stdlib: self._execution_count[module_path][lineno] += 1 self._heatmap[module_path][lineno] += runtime
[ "def", "fill_heatmap", "(", "self", ")", ":", "for", "module_path", ",", "lineno", ",", "runtime", "in", "self", ".", "lines_without_stdlib", ":", "self", ".", "_execution_count", "[", "module_path", "]", "[", "lineno", "]", "+=", "1", "self", ".", "_heatm...
Fills code heatmap and execution count dictionaries.
[ "Fills", "code", "heatmap", "and", "execution", "count", "dictionaries", "." ]
python
test
55
ome/omego
omego/main.py
https://github.com/ome/omego/blob/2dadbf3c6342b6c995f9e0dceaf3c0b7fab030fb/omego/main.py#L40-L58
def entry_point(): """ External entry point which calls main() and if Stop is raised, calls sys.exit() """ try: main("omego", items=[ (InstallCommand.NAME, InstallCommand), (UpgradeCommand.NAME, UpgradeCommand), (ConvertCommand.NAME, ConvertCommand), ...
[ "def", "entry_point", "(", ")", ":", "try", ":", "main", "(", "\"omego\"", ",", "items", "=", "[", "(", "InstallCommand", ".", "NAME", ",", "InstallCommand", ")", ",", "(", "UpgradeCommand", ".", "NAME", ",", "UpgradeCommand", ")", ",", "(", "ConvertComm...
External entry point which calls main() and if Stop is raised, calls sys.exit()
[ "External", "entry", "point", "which", "calls", "main", "()", "and", "if", "Stop", "is", "raised", "calls", "sys", ".", "exit", "()" ]
python
train
30.105263
mohamedattahri/PyXMLi
pyxmli/__init__.py
https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/__init__.py#L644-L653
def __set_status(self, value): ''' Sets the status of the invoice. @param value:str ''' if value not in [INVOICE_DUE, INVOICE_PAID, INVOICE_CANCELED, INVOICE_IRRECOVERABLE]: raise ValueError("Invalid invoice status") self.__status = v...
[ "def", "__set_status", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "[", "INVOICE_DUE", ",", "INVOICE_PAID", ",", "INVOICE_CANCELED", ",", "INVOICE_IRRECOVERABLE", "]", ":", "raise", "ValueError", "(", "\"Invalid invoice status\"", ")", "self...
Sets the status of the invoice. @param value:str
[ "Sets", "the", "status", "of", "the", "invoice", "." ]
python
train
31.5
google/dotty
efilter/protocol.py
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/protocol.py#L222-L245
def _build_late_dispatcher(func_name): """Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that ...
[ "def", "_build_late_dispatcher", "(", "func_name", ")", ":", "def", "_late_dynamic_dispatcher", "(", "obj", ",", "*", "args", ")", ":", "method", "=", "getattr", "(", "obj", ",", "func_name", ",", "None", ")", "if", "not", "callable", "(", "method", ")", ...
Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that takes an 'obj' parameter, followed by *args and ...
[ "Return", "a", "function", "that", "calls", "method", "func_name", "on", "objects", "." ]
python
train
37.958333
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_1/git/git_client_base.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/git/git_client_base.py#L1999-L2041
def get_pull_requests_by_project(self, project, search_criteria, max_comment_length=None, skip=None, top=None): """GetPullRequestsByProject. [Preview API] Retrieve all pull requests matching a specified criteria. :param str project: Project ID or project name :param :class:`<GitPullReque...
[ "def", "get_pull_requests_by_project", "(", "self", ",", "project", ",", "search_criteria", ",", "max_comment_length", "=", "None", ",", "skip", "=", "None", ",", "top", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "N...
GetPullRequestsByProject. [Preview API] Retrieve all pull requests matching a specified criteria. :param str project: Project ID or project name :param :class:`<GitPullRequestSearchCriteria> <azure.devops.v5_1.git.models.GitPullRequestSearchCriteria>` search_criteria: Pull requests will be retur...
[ "GetPullRequestsByProject", ".", "[", "Preview", "API", "]", "Retrieve", "all", "pull", "requests", "matching", "a", "specified", "criteria", ".", ":", "param", "str", "project", ":", "Project", "ID", "or", "project", "name", ":", "param", ":", "class", ":",...
python
train
68.697674
SMTG-UCL/sumo
sumo/electronic_structure/dos.py
https://github.com/SMTG-UCL/sumo/blob/47aec6bbfa033a624435a65bd4edabd18bfb437f/sumo/electronic_structure/dos.py#L270-L327
def write_files(dos, pdos, prefix=None, directory=None, zero_to_efermi=True): """Write the density of states data to disk. Args: dos (:obj:`~pymatgen.electronic_structure.dos.Dos` or \ :obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The total density of states. ...
[ "def", "write_files", "(", "dos", ",", "pdos", ",", "prefix", "=", "None", ",", "directory", "=", "None", ",", "zero_to_efermi", "=", "True", ")", ":", "# defining these cryptic lists makes formatting the data much easier later", "if", "len", "(", "dos", ".", "den...
Write the density of states data to disk. Args: dos (:obj:`~pymatgen.electronic_structure.dos.Dos` or \ :obj:`~pymatgen.electronic_structure.dos.CompleteDos`): The total density of states. pdos (dict): The projected density of states. Formatted as a :obj:`dict` ...
[ "Write", "the", "density", "of", "states", "data", "to", "disk", "." ]
python
train
39.672414
hyperledger/sawtooth-core
validator/sawtooth_validator/journal/consensus/dev_mode/dev_mode_consensus.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/journal/consensus/dev_mode/dev_mode_consensus.py#L103-L133
def check_publish_block(self, block_header): """Check if a candidate block is ready to be claimed. block_header (BlockHeader): the block_header to be checked if it should be claimed Returns: Boolean: True if the candidate block_header should be claimed. """ ...
[ "def", "check_publish_block", "(", "self", ",", "block_header", ")", ":", "if", "any", "(", "publisher_key", "!=", "block_header", ".", "signer_public_key", "for", "publisher_key", "in", "self", ".", "_valid_block_publishers", ")", ":", "return", "False", "if", ...
Check if a candidate block is ready to be claimed. block_header (BlockHeader): the block_header to be checked if it should be claimed Returns: Boolean: True if the candidate block_header should be claimed.
[ "Check", "if", "a", "candidate", "block", "is", "ready", "to", "be", "claimed", "." ]
python
train
31.064516
twisted/mantissa
xmantissa/liveform.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L383-L392
def _idForObject(self, defaultObject): """ Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int} """ identifier = self._allocateID() self._idsToObjects[identifier] = defaultObject return identifier
[ "def", "_idForObject", "(", "self", ",", "defaultObject", ")", ":", "identifier", "=", "self", ".", "_allocateID", "(", ")", "self", ".", "_idsToObjects", "[", "identifier", "]", "=", "defaultObject", "return", "identifier" ]
Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int}
[ "Generate", "an", "opaque", "identifier", "which", "can", "be", "used", "to", "talk", "about", "C", "{", "defaultObject", "}", "." ]
python
train
29.4
flatangle/flatlib
flatlib/ephem/ephem.py
https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/ephem/ephem.py#L90-L93
def nextSunrise(date, pos): """ Returns the date of the next sunrise. """ jd = eph.nextSunrise(date.jd, pos.lat, pos.lon) return Datetime.fromJD(jd, date.utcoffset)
[ "def", "nextSunrise", "(", "date", ",", "pos", ")", ":", "jd", "=", "eph", ".", "nextSunrise", "(", "date", ".", "jd", ",", "pos", ".", "lat", ",", "pos", ".", "lon", ")", "return", "Datetime", ".", "fromJD", "(", "jd", ",", "date", ".", "utcoffs...
Returns the date of the next sunrise.
[ "Returns", "the", "date", "of", "the", "next", "sunrise", "." ]
python
train
43.25
bcbio/bcbio-nextgen
bcbio/utils.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L232-L238
def file_exists(fname): """Check if a file exists and is non-empty. """ try: return fname and os.path.exists(fname) and os.path.getsize(fname) > 0 except OSError: return False
[ "def", "file_exists", "(", "fname", ")", ":", "try", ":", "return", "fname", "and", "os", ".", "path", ".", "exists", "(", "fname", ")", "and", "os", ".", "path", ".", "getsize", "(", "fname", ")", ">", "0", "except", "OSError", ":", "return", "Fal...
Check if a file exists and is non-empty.
[ "Check", "if", "a", "file", "exists", "and", "is", "non", "-", "empty", "." ]
python
train
28.714286
apache/incubator-mxnet
python/mxnet/gluon/parameter.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/parameter.py#L216-L228
def _get_row_sparse(self, arr_list, ctx, row_id): """ Get row_sparse data from row_sparse parameters based on row_id. """ # get row sparse params based on row ids if not isinstance(row_id, ndarray.NDArray): raise TypeError("row_id must have NDArray type, but %s is given"%(type(row_id...
[ "def", "_get_row_sparse", "(", "self", ",", "arr_list", ",", "ctx", ",", "row_id", ")", ":", "# get row sparse params based on row ids", "if", "not", "isinstance", "(", "row_id", ",", "ndarray", ".", "NDArray", ")", ":", "raise", "TypeError", "(", "\"row_id must...
Get row_sparse data from row_sparse parameters based on row_id.
[ "Get", "row_sparse", "data", "from", "row_sparse", "parameters", "based", "on", "row_id", "." ]
python
train
53.307692
gabstopper/smc-python
smc/core/interfaces.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/interfaces.py#L171-L227
def set_primary_mgt(self, interface_id, auth_request=None, address=None): """ Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. F...
[ "def", "set_primary_mgt", "(", "self", ",", "interface_id", ",", "auth_request", "=", "None", ",", "address", "=", "None", ")", ":", "intfattr", "=", "[", "'primary_mgt'", ",", "'outgoing'", "]", "if", "self", ".", "interface", ".", "engine", ".", "type", ...
Specifies the Primary Control IP address for Management Server contact. For single FW and cluster FW's, this will enable 'Outgoing', 'Auth Request' and the 'Primary Control' interface. For clusters, the primary heartbeat will NOT follow this change and should be set separately using :met...
[ "Specifies", "the", "Primary", "Control", "IP", "address", "for", "Management", "Server", "contact", ".", "For", "single", "FW", "and", "cluster", "FW", "s", "this", "will", "enable", "Outgoing", "Auth", "Request", "and", "the", "Primary", "Control", "interfac...
python
train
44.298246
Zsailer/kubeconf
kubeconf/kubeconf.py
https://github.com/Zsailer/kubeconf/blob/b4e81001b5d2fb8d461056f25eb8b03307d57a6b/kubeconf/kubeconf.py#L208-L214
def user_exists(self, name): """Check if a given user exists.""" users = self.data['users'] for user in users: if user['name'] == name: return True return False
[ "def", "user_exists", "(", "self", ",", "name", ")", ":", "users", "=", "self", ".", "data", "[", "'users'", "]", "for", "user", "in", "users", ":", "if", "user", "[", "'name'", "]", "==", "name", ":", "return", "True", "return", "False" ]
Check if a given user exists.
[ "Check", "if", "a", "given", "user", "exists", "." ]
python
train
30.571429
dmlc/xgboost
python-package/xgboost/core.py
https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1056-L1070
def set_attr(self, **kwargs): """Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute. """ for key, value in kwargs.items(): if value is not None: if n...
[ "def", "set_attr", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", ":", "if", "not", "isinstance", "(", "value", ",", "STRING_TYPES", ")", ...
Set the attribute of the Booster. Parameters ---------- **kwargs The attributes to set. Setting a value to None deletes an attribute.
[ "Set", "the", "attribute", "of", "the", "Booster", "." ]
python
train
37
Cologler/fsoopify-python
fsoopify/nodes.py
https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L165-L168
def write_bytes(self, data: bytes, *, append=True): ''' write bytes into the file. ''' mode = 'ab' if append else 'wb' return self.write(data, mode=mode)
[ "def", "write_bytes", "(", "self", ",", "data", ":", "bytes", ",", "*", ",", "append", "=", "True", ")", ":", "mode", "=", "'ab'", "if", "append", "else", "'wb'", "return", "self", ".", "write", "(", "data", ",", "mode", "=", "mode", ")" ]
write bytes into the file.
[ "write", "bytes", "into", "the", "file", "." ]
python
train
43.5
saltstack/salt
salt/queues/sqlite_queue.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L109-L115
def list_items(queue): ''' List contents of a queue ''' itemstuple = _list_items(queue) items = [item[0] for item in itemstuple] return items
[ "def", "list_items", "(", "queue", ")", ":", "itemstuple", "=", "_list_items", "(", "queue", ")", "items", "=", "[", "item", "[", "0", "]", "for", "item", "in", "itemstuple", "]", "return", "items" ]
List contents of a queue
[ "List", "contents", "of", "a", "queue" ]
python
train
22.714286
euske/pdfminer
pdfminer/encodingdb.py
https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/encodingdb.py#L13-L20
def name2unicode(name): """Converts Adobe glyph names to Unicode numbers.""" if name in glyphname2unicode: return glyphname2unicode[name] m = STRIP_NAME.search(name) if not m: raise KeyError(name) return unichr(int(m.group(0)))
[ "def", "name2unicode", "(", "name", ")", ":", "if", "name", "in", "glyphname2unicode", ":", "return", "glyphname2unicode", "[", "name", "]", "m", "=", "STRIP_NAME", ".", "search", "(", "name", ")", "if", "not", "m", ":", "raise", "KeyError", "(", "name",...
Converts Adobe glyph names to Unicode numbers.
[ "Converts", "Adobe", "glyph", "names", "to", "Unicode", "numbers", "." ]
python
train
32
KelSolaar/Umbra
umbra/ui/completers.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/completers.py#L114-L125
def __set_cache(self, tokens): """ Sets the tokens cache. :param tokens: Completer tokens list. :type tokens: tuple or list """ if DefaultCompleter._DefaultCompleter__tokens.get(self.__language): return DefaultCompleter._DefaultCompleter__tokens[sel...
[ "def", "__set_cache", "(", "self", ",", "tokens", ")", ":", "if", "DefaultCompleter", ".", "_DefaultCompleter__tokens", ".", "get", "(", "self", ".", "__language", ")", ":", "return", "DefaultCompleter", ".", "_DefaultCompleter__tokens", "[", "self", ".", "__lan...
Sets the tokens cache. :param tokens: Completer tokens list. :type tokens: tuple or list
[ "Sets", "the", "tokens", "cache", "." ]
python
train
27.583333
mlouielu/twstock
twstock/legacy.py
https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/legacy.py#L119-L122
def best_buy_3(self): """三日均價由下往上 """ return self.data.continuous(self.data.moving_average(self.data.price, 3)) == 1
[ "def", "best_buy_3", "(", "self", ")", ":", "return", "self", ".", "data", ".", "continuous", "(", "self", ".", "data", ".", "moving_average", "(", "self", ".", "data", ".", "price", ",", "3", ")", ")", "==", "1" ]
三日均價由下往上
[ "三日均價由下往上" ]
python
train
34.25
frasertweedale/ledgertools
ltlib/score.py
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/score.py#L56-L65
def highest(self): """Return the items with the higest score. If this ScoreSet is empty, returns None. """ scores = self.scores() if not scores: return None maxscore = max(map(score, scores)) return filter(lambda x: score(x) == maxscore, scores)
[ "def", "highest", "(", "self", ")", ":", "scores", "=", "self", ".", "scores", "(", ")", "if", "not", "scores", ":", "return", "None", "maxscore", "=", "max", "(", "map", "(", "score", ",", "scores", ")", ")", "return", "filter", "(", "lambda", "x"...
Return the items with the higest score. If this ScoreSet is empty, returns None.
[ "Return", "the", "items", "with", "the", "higest", "score", "." ]
python
train
30.5
RedHatInsights/insights-core
insights/client/mount.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/mount.py#L74-L84
def _activate_thin_device(name, dm_id, size, pool): """ Provisions an LVM device-mapper thin device reflecting, DM device id 'dm_id' in the docker pool. """ table = '0 %d thin /dev/mapper/%s %s' % (int(size) // 512, pool, dm_id) cmd = ['dmsetup', 'create', name, '--table'...
[ "def", "_activate_thin_device", "(", "name", ",", "dm_id", ",", "size", ",", "pool", ")", ":", "table", "=", "'0 %d thin /dev/mapper/%s %s'", "%", "(", "int", "(", "size", ")", "//", "512", ",", "pool", ",", "dm_id", ")", "cmd", "=", "[", "'dmsetup'", ...
Provisions an LVM device-mapper thin device reflecting, DM device id 'dm_id' in the docker pool.
[ "Provisions", "an", "LVM", "device", "-", "mapper", "thin", "device", "reflecting", "DM", "device", "id", "dm_id", "in", "the", "docker", "pool", "." ]
python
train
46.727273
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L1083-L1105
def _mock_imethodcall(self, methodname, namespace, response_params_rqd=None, **params): # pylint: disable=unused-argument """ Mocks the WBEMConnection._imethodcall() method. This mock calls methods within this class that fake the processing in a WBEM server (a...
[ "def", "_mock_imethodcall", "(", "self", ",", "methodname", ",", "namespace", ",", "response_params_rqd", "=", "None", ",", "*", "*", "params", ")", ":", "# pylint: disable=unused-argument", "method_name", "=", "'_fake_'", "+", "methodname", ".", "lower", "(", "...
Mocks the WBEMConnection._imethodcall() method. This mock calls methods within this class that fake the processing in a WBEM server (at the CIM Object level) for the varisous CIM/XML methods and return. Each function is named with the lower case method namd prepended with '_fak...
[ "Mocks", "the", "WBEMConnection", ".", "_imethodcall", "()", "method", "." ]
python
train
34.086957
novopl/peltak
src/peltak/core/git.py
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/git.py#L424-L436
def branches(): # type: () -> List[str] """ Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo. """ out = shell.run( 'git branch', capture=True, never_pretend=True ).stdout.strip() return [x.strip('* \t\n...
[ "def", "branches", "(", ")", ":", "# type: () -> List[str]", "out", "=", "shell", ".", "run", "(", "'git branch'", ",", "capture", "=", "True", ",", "never_pretend", "=", "True", ")", ".", "stdout", ".", "strip", "(", ")", "return", "[", "x", ".", "str...
Return a list of branches in the current repo. Returns: list[str]: A list of branches in the current repo.
[ "Return", "a", "list", "of", "branches", "in", "the", "current", "repo", "." ]
python
train
25.923077
monarch-initiative/dipper
dipper/sources/OMIM.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/OMIM.py#L927-L977
def _cleanup_label(label): """ Reformat the ALL CAPS OMIM labels to something more pleasant to read. This will: 1. remove the abbreviation suffixes 2. convert the roman numerals to integer numbers 3. make the text title case, except for suplied conjunctions...
[ "def", "_cleanup_label", "(", "label", ")", ":", "conjunctions", "=", "[", "'and'", ",", "'but'", ",", "'yet'", ",", "'for'", ",", "'nor'", ",", "'so'", "]", "little_preps", "=", "[", "'at'", ",", "'by'", ",", "'in'", ",", "'of'", ",", "'on'", ",", ...
Reformat the ALL CAPS OMIM labels to something more pleasant to read. This will: 1. remove the abbreviation suffixes 2. convert the roman numerals to integer numbers 3. make the text title case, except for suplied conjunctions/prepositions/articles :param label: ...
[ "Reformat", "the", "ALL", "CAPS", "OMIM", "labels", "to", "something", "more", "pleasant", "to", "read", ".", "This", "will", ":", "1", ".", "remove", "the", "abbreviation", "suffixes", "2", ".", "convert", "the", "roman", "numerals", "to", "integer", "num...
python
train
36.470588
daler/trackhub
trackhub/track.py
https://github.com/daler/trackhub/blob/e4655f79177822529f80b923df117e38e28df702/trackhub/track.py#L245-L256
def tracktype(self, tracktype): """ When setting the track type, the valid parameters for this track type need to be set as well. """ self._tracktype = tracktype if tracktype is not None: if 'bed' in tracktype.lower(): tracktype = 'bigBed' ...
[ "def", "tracktype", "(", "self", ",", "tracktype", ")", ":", "self", ".", "_tracktype", "=", "tracktype", "if", "tracktype", "is", "not", "None", ":", "if", "'bed'", "in", "tracktype", ".", "lower", "(", ")", ":", "tracktype", "=", "'bigBed'", "elif", ...
When setting the track type, the valid parameters for this track type need to be set as well.
[ "When", "setting", "the", "track", "type", "the", "valid", "parameters", "for", "this", "track", "type", "need", "to", "be", "set", "as", "well", "." ]
python
train
38.416667