repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
Chilipp/funcargparse
funcargparse/__init__.py
https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L467-L474
def _get_corresponding_parsers(self, func): """Get the parser that has been set up by the given `function`""" if func in self._used_functions: yield self if self._subparsers_action is not None: for parser in self._subparsers_action.choices.values(): for sp in parser._get_corresponding_parsers(func): yield sp
[ "def", "_get_corresponding_parsers", "(", "self", ",", "func", ")", ":", "if", "func", "in", "self", ".", "_used_functions", ":", "yield", "self", "if", "self", ".", "_subparsers_action", "is", "not", "None", ":", "for", "parser", "in", "self", ".", "_subp...
Get the parser that has been set up by the given `function`
[ "Get", "the", "parser", "that", "has", "been", "set", "up", "by", "the", "given", "function" ]
python
train
yymao/generic-catalog-reader
GCR/base.py
https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L102-L124
def has_quantities(self, quantities, include_native=True): """ Check if ALL *quantities* specified are available in this catalog Parameters ---------- quantities : iterable a list of quantity names to check include_native : bool, optional whether or not to include native quantity names when checking Returns ------- has_quantities : bool True if the quantities are all available; otherwise False """ quantities = set(quantities) if include_native: return all(q in self._native_quantities for q in self._translate_quantities(quantities)) return all(q in self._quantity_modifiers for q in quantities)
[ "def", "has_quantities", "(", "self", ",", "quantities", ",", "include_native", "=", "True", ")", ":", "quantities", "=", "set", "(", "quantities", ")", "if", "include_native", ":", "return", "all", "(", "q", "in", "self", ".", "_native_quantities", "for", ...
Check if ALL *quantities* specified are available in this catalog Parameters ---------- quantities : iterable a list of quantity names to check include_native : bool, optional whether or not to include native quantity names when checking Returns ------- has_quantities : bool True if the quantities are all available; otherwise False
[ "Check", "if", "ALL", "*", "quantities", "*", "specified", "are", "available", "in", "this", "catalog" ]
python
train
kejbaly2/metrique
metrique/utils.py
https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/utils.py#L374-L429
def debug_setup(logger=None, level=None, log2file=None, log_file=None, log_format=None, log_dir=None, log2stdout=None, truncate=False): ''' Local object instance logger setup. Verbosity levels are determined as such:: if level in [-1, False]: logger.setLevel(logging.WARN) elif level in [0, None]: logger.setLevel(logging.INFO) elif level in [True, 1, 2]: logger.setLevel(logging.DEBUG) If (level == 2) `logging.DEBUG` will be set even for the "root logger". Configuration options available for customized logger behaivor: * debug (bool) * log2stdout (bool) * log2file (bool) * log_file (path) ''' log2stdout = False if log2stdout is None else log2stdout _log_format = "%(levelname)s.%(name)s.%(process)s:%(asctime)s:%(message)s" log_format = log_format or _log_format if isinstance(log_format, basestring): log_format = logging.Formatter(log_format, "%Y%m%dT%H%M%S") log2file = True if log2file is None else log2file logger = logger or 'metrique' if isinstance(logger, basestring): logger = logging.getLogger(logger) else: logger = logger or logging.getLogger(logger) logger.propagate = 0 logger.handlers = [] if log2file: log_dir = log_dir or LOGS_DIR log_file = log_file or 'metrique' log_file = os.path.join(log_dir, log_file) if truncate: # clear the existing data before writing (truncate) open(log_file, 'w+').close() hdlr = logging.FileHandler(log_file) hdlr.setFormatter(log_format) logger.addHandler(hdlr) else: log2stdout = True if log2stdout: hdlr = logging.StreamHandler() hdlr.setFormatter(log_format) logger.addHandler(hdlr) logger = _debug_set_level(logger, level) return logger
[ "def", "debug_setup", "(", "logger", "=", "None", ",", "level", "=", "None", ",", "log2file", "=", "None", ",", "log_file", "=", "None", ",", "log_format", "=", "None", ",", "log_dir", "=", "None", ",", "log2stdout", "=", "None", ",", "truncate", "=", ...
Local object instance logger setup. Verbosity levels are determined as such:: if level in [-1, False]: logger.setLevel(logging.WARN) elif level in [0, None]: logger.setLevel(logging.INFO) elif level in [True, 1, 2]: logger.setLevel(logging.DEBUG) If (level == 2) `logging.DEBUG` will be set even for the "root logger". Configuration options available for customized logger behaivor: * debug (bool) * log2stdout (bool) * log2file (bool) * log_file (path)
[ "Local", "object", "instance", "logger", "setup", "." ]
python
train
noahbenson/pimms
pimms/immutable.py
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/immutable.py#L588-L618
def _imm_merge_class(cls, parent): ''' _imm_merge_class(imm_class, parent) updates the given immutable class imm_class to have the appropriate attributes of its given parent class. The parents should be passed through this function in method-resolution order. ''' # If this is not an immutable parent, ignore it if not hasattr(parent, '_pimms_immutable_data_'): return cls # otherwise, let's look at the data cdat = cls._pimms_immutable_data_ pdat = parent._pimms_immutable_data_ # for params, values, and checks, we add them to cls only if they do not already exist in cls cparams = cdat['params'] cvalues = cdat['values'] cconsts = cdat['consts'] for (param, (dflt, tx_fn, arg_lists, check_fns, deps)) in six.iteritems(pdat['params']): if param not in cparams and param not in cvalues: cparams[param] = (dflt, tx_fn, [], [], []) for (value, (arg_list, calc_fn, deps)) in six.iteritems(pdat['values']): if value in cparams: raise ValueError('cannot convert value into parameter: %s' % value) if value not in cvalues: cvalues[value] = (arg_list, calc_fn, []) if len(arg_list) == 0: cconsts[value] = ([], []) cchecks = cdat['checks'] for (check, (arg_list, check_fn)) in six.iteritems(pdat['checks']): if check not in cchecks: cchecks[check] = (arg_list, check_fn) # That's it for now return cls
[ "def", "_imm_merge_class", "(", "cls", ",", "parent", ")", ":", "# If this is not an immutable parent, ignore it", "if", "not", "hasattr", "(", "parent", ",", "'_pimms_immutable_data_'", ")", ":", "return", "cls", "# otherwise, let's look at the data", "cdat", "=", "cls...
_imm_merge_class(imm_class, parent) updates the given immutable class imm_class to have the appropriate attributes of its given parent class. The parents should be passed through this function in method-resolution order.
[ "_imm_merge_class", "(", "imm_class", "parent", ")", "updates", "the", "given", "immutable", "class", "imm_class", "to", "have", "the", "appropriate", "attributes", "of", "its", "given", "parent", "class", ".", "The", "parents", "should", "be", "passed", "throug...
python
train
SCIP-Interfaces/PySCIPOpt
examples/finished/read_tsplib.py
https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/finished/read_tsplib.py#L14-L24
def distL2(x1,y1,x2,y2): """Compute the L2-norm (Euclidean) distance between two points. The distance is rounded to the closest integer, for compatibility with the TSPLIB convention. The two points are located on coordinates (x1,y1) and (x2,y2), sent as parameters""" xdiff = x2 - x1 ydiff = y2 - y1 return int(math.sqrt(xdiff*xdiff + ydiff*ydiff) + .5)
[ "def", "distL2", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", ":", "xdiff", "=", "x2", "-", "x1", "ydiff", "=", "y2", "-", "y1", "return", "int", "(", "math", ".", "sqrt", "(", "xdiff", "*", "xdiff", "+", "ydiff", "*", "ydiff", ")", "+", ...
Compute the L2-norm (Euclidean) distance between two points. The distance is rounded to the closest integer, for compatibility with the TSPLIB convention. The two points are located on coordinates (x1,y1) and (x2,y2), sent as parameters
[ "Compute", "the", "L2", "-", "norm", "(", "Euclidean", ")", "distance", "between", "two", "points", "." ]
python
train
portfors-lab/sparkle
sparkle/tools/audiotools.py
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/tools/audiotools.py#L399-L427
def calibrate_signal(signal, resp, fs, frange): """Given original signal and recording, spits out a calibrated signal""" # remove dc offset from recorded response (synthesized orignal shouldn't have one) dc = np.mean(resp) resp = resp - dc npts = len(signal) f0 = np.ceil(frange[0] / (float(fs) / npts)) f1 = np.floor(frange[1] / (float(fs) / npts)) y = resp # y = y/np.amax(y) # normalize Y = np.fft.rfft(y) x = signal # x = x/np.amax(x) # normalize X = np.fft.rfft(x) H = Y / X # still issues warning because all of Y/X is executed to selected answers from # H = np.where(X.real!=0, Y/X, 1) # H[:f0].real = 1 # H[f1:].real = 1 # H = smooth(H) A = X / H return np.fft.irfft(A)
[ "def", "calibrate_signal", "(", "signal", ",", "resp", ",", "fs", ",", "frange", ")", ":", "# remove dc offset from recorded response (synthesized orignal shouldn't have one)", "dc", "=", "np", ".", "mean", "(", "resp", ")", "resp", "=", "resp", "-", "dc", "npts",...
Given original signal and recording, spits out a calibrated signal
[ "Given", "original", "signal", "and", "recording", "spits", "out", "a", "calibrated", "signal" ]
python
train
ralphje/imagemounter
imagemounter/unmounter.py
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/unmounter.py#L103-L114
def _index_loopbacks(self): """Finds all loopbacks and stores them in :attr:`loopbacks`""" self.loopbacks = {} try: result = _util.check_output_(['losetup', '-a']) for line in result.splitlines(): m = re.match(r'(.+): (.+) \((.+)\).*', line) if m: self.loopbacks[m.group(1)] = m.group(3) except Exception: pass
[ "def", "_index_loopbacks", "(", "self", ")", ":", "self", ".", "loopbacks", "=", "{", "}", "try", ":", "result", "=", "_util", ".", "check_output_", "(", "[", "'losetup'", ",", "'-a'", "]", ")", "for", "line", "in", "result", ".", "splitlines", "(", ...
Finds all loopbacks and stores them in :attr:`loopbacks`
[ "Finds", "all", "loopbacks", "and", "stores", "them", "in", ":", "attr", ":", "loopbacks" ]
python
train
Parsl/parsl
parsl/data_provider/data_manager.py
https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/data_provider/data_manager.py#L51-L57
def get_data_manager(cls): """Return the DataManager of the currently loaded DataFlowKernel. """ from parsl.dataflow.dflow import DataFlowKernelLoader dfk = DataFlowKernelLoader.dfk() return dfk.executors['data_manager']
[ "def", "get_data_manager", "(", "cls", ")", ":", "from", "parsl", ".", "dataflow", ".", "dflow", "import", "DataFlowKernelLoader", "dfk", "=", "DataFlowKernelLoader", ".", "dfk", "(", ")", "return", "dfk", ".", "executors", "[", "'data_manager'", "]" ]
Return the DataManager of the currently loaded DataFlowKernel.
[ "Return", "the", "DataManager", "of", "the", "currently", "loaded", "DataFlowKernel", "." ]
python
valid
zimeon/iiif
iiif/manipulator.py
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator.py#L49-L68
def compliance_uri(self): """Compliance URI based on api_version. Value is based on api_version and complicance_level, will be None if either are unset/unrecognized. The assumption here is that the api_version and level are orthogonal, override this method if that isn't true. """ if (self.api_version == '1.0'): uri_pattern = r'http://library.stanford.edu/iiif/image-api/compliance.html#level%d' elif (self.api_version == '1.1'): uri_pattern = r'http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level%d' elif (self.api_version == '2.0' or self.api_version == '2.1'): uri_pattern = r'http://iiif.io/api/image/2/level%d.json' else: return if (self.compliance_level is None): return return(uri_pattern % self.compliance_level)
[ "def", "compliance_uri", "(", "self", ")", ":", "if", "(", "self", ".", "api_version", "==", "'1.0'", ")", ":", "uri_pattern", "=", "r'http://library.stanford.edu/iiif/image-api/compliance.html#level%d'", "elif", "(", "self", ".", "api_version", "==", "'1.1'", ")", ...
Compliance URI based on api_version. Value is based on api_version and complicance_level, will be None if either are unset/unrecognized. The assumption here is that the api_version and level are orthogonal, override this method if that isn't true.
[ "Compliance", "URI", "based", "on", "api_version", "." ]
python
train
autokey/autokey
lib/autokey/qtapp.py
https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtapp.py#L182-L192
def _create_storage_directories(): """Create various storage directories, if those do not exist.""" # Create configuration directory if not os.path.exists(common.CONFIG_DIR): os.makedirs(common.CONFIG_DIR) # Create data directory (for log file) if not os.path.exists(common.DATA_DIR): os.makedirs(common.DATA_DIR) # Create run directory (for lock file) if not os.path.exists(common.RUN_DIR): os.makedirs(common.RUN_DIR)
[ "def", "_create_storage_directories", "(", ")", ":", "# Create configuration directory", "if", "not", "os", ".", "path", ".", "exists", "(", "common", ".", "CONFIG_DIR", ")", ":", "os", ".", "makedirs", "(", "common", ".", "CONFIG_DIR", ")", "# Create data direc...
Create various storage directories, if those do not exist.
[ "Create", "various", "storage", "directories", "if", "those", "do", "not", "exist", "." ]
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/sizeformatter.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sizeformatter.py#L29-L38
def sizeof_fmt(num: float, suffix: str = 'B') -> str: """ Formats a number of bytes in a human-readable binary format (e.g. ``2048`` becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841. """ for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'): if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
[ "def", "sizeof_fmt", "(", "num", ":", "float", ",", "suffix", ":", "str", "=", "'B'", ")", "->", "str", ":", "for", "unit", "in", "(", "''", ",", "'Ki'", ",", "'Mi'", ",", "'Gi'", ",", "'Ti'", ",", "'Pi'", ",", "'Ei'", ",", "'Zi'", ")", ":", ...
Formats a number of bytes in a human-readable binary format (e.g. ``2048`` becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
[ "Formats", "a", "number", "of", "bytes", "in", "a", "human", "-", "readable", "binary", "format", "(", "e", ".", "g", ".", "2048", "becomes", "2", "KiB", ")", ";", "from", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "109484...
python
train
tanghaibao/jcvi
jcvi/assembly/unitig.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/unitig.py#L346-L370
def pull(args): """ %prog pull version partID unitigID For example, `%prog pull 5 530` will pull the utg530 from partition 5 The layout is written to `unitig530` """ p = OptionParser(pull.__doc__) opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) prefix = get_prefix() version, partID, unitigID = args s = ".".join(args) cmd = "tigStore" cmd += " -g ../{0}.gkpStore -t ../{0}.tigStore".format(prefix) cmd += " {0} -up {1} -d layout -u {2}".format(version, partID, unitigID) unitigfile = "unitig" + s sh(cmd, outfile=unitigfile) return unitigfile
[ "def", "pull", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "pull", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "3", ":", "sys", ".", "exit", "(", "not",...
%prog pull version partID unitigID For example, `%prog pull 5 530` will pull the utg530 from partition 5 The layout is written to `unitig530`
[ "%prog", "pull", "version", "partID", "unitigID" ]
python
train
SystemRDL/systemrdl-compiler
systemrdl/compiler.py
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/compiler.py#L94-L152
def compile_file(self, path, incl_search_paths=None): """ Parse & compile a single file and append it to RDLCompiler's root namespace. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during compilation, then the RDLCompiler object should be discarded. Parameters ---------- path:str Path to an RDL source file incl_search_paths:list List of additional paths to search to resolve includes. If unset, defaults to an empty list. Relative include paths are resolved in the following order: 1. Search each path specified in ``incl_search_paths``. 2. Path relative to the source file performing the include. Raises ------ :class:`~systemrdl.RDLCompileError` If any fatal compile error is encountered. """ if incl_search_paths is None: incl_search_paths = [] fpp = preprocessor.FilePreprocessor(self.env, path, incl_search_paths) preprocessed_text, seg_map = fpp.preprocess() input_stream = preprocessor.PreprocessedInputStream(preprocessed_text, seg_map) lexer = SystemRDLLexer(input_stream) lexer.removeErrorListeners() lexer.addErrorListener(messages.RDLAntlrErrorListener(self.msg)) token_stream = CommonTokenStream(lexer) parser = SystemRDLParser(token_stream) parser.removeErrorListeners() parser.addErrorListener(messages.RDLAntlrErrorListener(self.msg)) # Run Antlr parser on input parsed_tree = parser.root() if self.msg.had_error: self.msg.fatal("Parse aborted due to previous errors") # Traverse parse tree with RootVisitor self.visitor.visit(parsed_tree) # Reset default property assignments from namespace. # They should not be shared between files since that would be confusing. self.namespace.default_property_ns_stack = [{}] if self.msg.had_error: self.msg.fatal("Compile aborted due to previous errors")
[ "def", "compile_file", "(", "self", ",", "path", ",", "incl_search_paths", "=", "None", ")", ":", "if", "incl_search_paths", "is", "None", ":", "incl_search_paths", "=", "[", "]", "fpp", "=", "preprocessor", ".", "FilePreprocessor", "(", "self", ".", "env", ...
Parse & compile a single file and append it to RDLCompiler's root namespace. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during compilation, then the RDLCompiler object should be discarded. Parameters ---------- path:str Path to an RDL source file incl_search_paths:list List of additional paths to search to resolve includes. If unset, defaults to an empty list. Relative include paths are resolved in the following order: 1. Search each path specified in ``incl_search_paths``. 2. Path relative to the source file performing the include. Raises ------ :class:`~systemrdl.RDLCompileError` If any fatal compile error is encountered.
[ "Parse", "&", "compile", "a", "single", "file", "and", "append", "it", "to", "RDLCompiler", "s", "root", "namespace", "." ]
python
train
SKA-ScienceDataProcessor/integration-prototype
sip/platform/logging/sip_logging/sip_logging.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/platform/logging/sip_logging/sip_logging.py#L111-L116
def disable_logger(logger_name: str, propagate: bool = False): """Disable output for the logger of the specified name.""" log = logging.getLogger(logger_name) log.propagate = propagate for handler in log.handlers: log.removeHandler(handler)
[ "def", "disable_logger", "(", "logger_name", ":", "str", ",", "propagate", ":", "bool", "=", "False", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "log", ".", "propagate", "=", "propagate", "for", "handler", "in", "log", "....
Disable output for the logger of the specified name.
[ "Disable", "output", "for", "the", "logger", "of", "the", "specified", "name", "." ]
python
train
junzis/pyModeS
pyModeS/extra/tcpclient.py
https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/extra/tcpclient.py#L67-L145
def read_beast_buffer(self): ''' <esc> "1" : 6 byte MLAT timestamp, 1 byte signal level, 2 byte Mode-AC <esc> "2" : 6 byte MLAT timestamp, 1 byte signal level, 7 byte Mode-S short frame <esc> "3" : 6 byte MLAT timestamp, 1 byte signal level, 14 byte Mode-S long frame <esc> "4" : 6 byte MLAT timestamp, status data, DIP switch configuration settings (not on Mode-S Beast classic) <esc><esc>: true 0x1a <esc> is 0x1a, and "1", "2" and "3" are 0x31, 0x32 and 0x33 timestamp: wiki.modesbeast.com/Radarcape:Firmware_Versions#The_GPS_timestamp ''' messages_mlat = [] msg = [] i = 0 # process the buffer until the last divider <esc> 0x1a # then, reset the self.buffer with the remainder while i < len(self.buffer): if (self.buffer[i:i+2] == [0x1a, 0x1a]): msg.append(0x1a) i += 1 elif (i == len(self.buffer) - 1) and (self.buffer[i] == 0x1a): # special case where the last bit is 0x1a msg.append(0x1a) elif self.buffer[i] == 0x1a: if i == len(self.buffer) - 1: # special case where the last bit is 0x1a msg.append(0x1a) elif len(msg) > 0: messages_mlat.append(msg) msg = [] else: msg.append(self.buffer[i]) i += 1 # save the reminder for next reading cycle, if not empty if len(msg) > 0: reminder = [] for i, m in enumerate(msg): if (m == 0x1a) and (i < len(msg)-1): # rewind 0x1a, except when it is at the last bit reminder.extend([m, m]) else: reminder.append(m) self.buffer = [0x1a] + msg else: self.buffer = [] # extract messages messages = [] for mm in messages_mlat: ts = time.time() msgtype = mm[0] # print(''.join('%02X' % i for i in mm)) if msgtype == 0x32: # Mode-S Short Message, 7 byte, 14-len hexstr msg = ''.join('%02X' % i for i in mm[8:15]) elif msgtype == 0x33: # Mode-S Long Message, 14 byte, 28-len hexstr msg = ''.join('%02X' % i for i in mm[8:22]) else: # Other message tupe continue if len(msg) not in [14, 28]: # incomplete message continue messages.append([msg, ts]) return messages
[ "def", "read_beast_buffer", "(", "self", ")", ":", "messages_mlat", "=", "[", "]", "msg", "=", "[", "]", "i", "=", "0", "# process the buffer until the last divider <esc> 0x1a", "# then, reset the self.buffer with the remainder", "while", "i", "<", "len", "(", "self",...
<esc> "1" : 6 byte MLAT timestamp, 1 byte signal level, 2 byte Mode-AC <esc> "2" : 6 byte MLAT timestamp, 1 byte signal level, 7 byte Mode-S short frame <esc> "3" : 6 byte MLAT timestamp, 1 byte signal level, 14 byte Mode-S long frame <esc> "4" : 6 byte MLAT timestamp, status data, DIP switch configuration settings (not on Mode-S Beast classic) <esc><esc>: true 0x1a <esc> is 0x1a, and "1", "2" and "3" are 0x31, 0x32 and 0x33 timestamp: wiki.modesbeast.com/Radarcape:Firmware_Versions#The_GPS_timestamp
[ "<esc", ">", "1", ":", "6", "byte", "MLAT", "timestamp", "1", "byte", "signal", "level", "2", "byte", "Mode", "-", "AC", "<esc", ">", "2", ":", "6", "byte", "MLAT", "timestamp", "1", "byte", "signal", "level", "7", "byte", "Mode", "-", "S", "short"...
python
train
biocore/burrito-fillings
bfillings/uclust.py
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L433-L482
def uclust_cluster_from_sorted_fasta_filepath( fasta_filepath, uc_save_filepath=None, percent_ID=0.97, max_accepts=1, max_rejects=8, stepwords=8, word_length=8, optimal=False, exact=False, suppress_sort=False, enable_rev_strand_matching=False, subject_fasta_filepath=None, suppress_new_clusters=False, stable_sort=False, tmp_dir=gettempdir(), HALT_EXEC=False): """ Returns clustered uclust file from sorted fasta""" output_filepath = uc_save_filepath if not output_filepath: _, output_filepath = mkstemp(dir=tmp_dir, prefix='uclust_clusters', suffix='.uc') params = {'--id': percent_ID, '--maxaccepts': max_accepts, '--maxrejects': max_rejects, '--stepwords': stepwords, '--w': word_length, '--tmpdir': tmp_dir} app = Uclust(params, TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC) # Set any additional parameters specified by the user if enable_rev_strand_matching: app.Parameters['--rev'].on() if optimal: app.Parameters['--optimal'].on() if exact: app.Parameters['--exact'].on() if suppress_sort: app.Parameters['--usersort'].on() if subject_fasta_filepath: app.Parameters['--lib'].on(subject_fasta_filepath) if suppress_new_clusters: app.Parameters['--libonly'].on() if stable_sort: app.Parameters['--stable_sort'].on() app_result = app({'--input': fasta_filepath, '--uc': output_filepath}) return app_result
[ "def", "uclust_cluster_from_sorted_fasta_filepath", "(", "fasta_filepath", ",", "uc_save_filepath", "=", "None", ",", "percent_ID", "=", "0.97", ",", "max_accepts", "=", "1", ",", "max_rejects", "=", "8", ",", "stepwords", "=", "8", ",", "word_length", "=", "8",...
Returns clustered uclust file from sorted fasta
[ "Returns", "clustered", "uclust", "file", "from", "sorted", "fasta" ]
python
train
pytries/DAWG-Python
dawg_python/wrapper.py
https://github.com/pytries/DAWG-Python/blob/e56241ec919b78735ff79014bf18d7fd1f8e08b9/dawg_python/wrapper.py#L51-L59
def follow_char(self, label, index): "Follows a transition" offset = units.offset(self._units[index]) next_index = (index ^ offset ^ label) & units.PRECISION_MASK if units.label(self._units[next_index]) != label: return None return next_index
[ "def", "follow_char", "(", "self", ",", "label", ",", "index", ")", ":", "offset", "=", "units", ".", "offset", "(", "self", ".", "_units", "[", "index", "]", ")", "next_index", "=", "(", "index", "^", "offset", "^", "label", ")", "&", "units", "."...
Follows a transition
[ "Follows", "a", "transition" ]
python
train
Azure/blobxfer
blobxfer/operations/download.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/download.py#L659-L671
def _cleanup_temporary_files(self): # type: (Downloader) -> None """Cleanup temporary files in case of an exception or interrupt. This function is not thread-safe. :param Downloader self: this """ # iterate through dd map and cleanup files for key in self._dd_map: dd = self._dd_map[key] try: dd.cleanup_all_temporary_files() except Exception as e: logger.exception(e)
[ "def", "_cleanup_temporary_files", "(", "self", ")", ":", "# type: (Downloader) -> None", "# iterate through dd map and cleanup files", "for", "key", "in", "self", ".", "_dd_map", ":", "dd", "=", "self", ".", "_dd_map", "[", "key", "]", "try", ":", "dd", ".", "c...
Cleanup temporary files in case of an exception or interrupt. This function is not thread-safe. :param Downloader self: this
[ "Cleanup", "temporary", "files", "in", "case", "of", "an", "exception", "or", "interrupt", ".", "This", "function", "is", "not", "thread", "-", "safe", ".", ":", "param", "Downloader", "self", ":", "this" ]
python
train
lanius/tinyik
tinyik/solver.py
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/solver.py#L26-L32
def solve(self, angles): """Calculate a position of the end-effector and return it.""" return reduce( lambda a, m: np.dot(m, a), reversed(self._matrices(angles)), np.array([0., 0., 0., 1.]) )[:3]
[ "def", "solve", "(", "self", ",", "angles", ")", ":", "return", "reduce", "(", "lambda", "a", ",", "m", ":", "np", ".", "dot", "(", "m", ",", "a", ")", ",", "reversed", "(", "self", ".", "_matrices", "(", "angles", ")", ")", ",", "np", ".", "...
Calculate a position of the end-effector and return it.
[ "Calculate", "a", "position", "of", "the", "end", "-", "effector", "and", "return", "it", "." ]
python
train
FujiMakoto/IPS-Vagrant
ips_vagrant/installer/V_4_1_3_2.py
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/installer/V_4_1_3_2.py#L76-L113
def install(self): """ Run the actual installation """ self._start_install() mr_link = self._get_mr_link() # Set up the progress bar pbar = ProgressBar(100, 'Running installation...') pbar.start() mr_j, mr_r = self._ajax(mr_link) # Loop until we get a redirect json response while True: mr_link = self._parse_response(mr_link, mr_j) stage = self._get_stage(mr_j) progress = self._get_progress(mr_j) mr_j, mr_r = self._ajax(mr_link) pbar.update(min([progress, 100]), stage) # NOTE: Response may return progress values above 100 # If we're done, finalize the installation and break redirect = self._check_if_complete(mr_link, mr_j) if redirect: pbar.finish() break p = Echo('Finalizing...') mr_r = self._request(redirect, raise_request=False) p.done() # Install developer tools if self.site.in_dev: DevToolsInstaller(self.ctx, self.site).install() # Get the link to our community homepage self._finalize(mr_r)
[ "def", "install", "(", "self", ")", ":", "self", ".", "_start_install", "(", ")", "mr_link", "=", "self", ".", "_get_mr_link", "(", ")", "# Set up the progress bar", "pbar", "=", "ProgressBar", "(", "100", ",", "'Running installation...'", ")", "pbar", ".", ...
Run the actual installation
[ "Run", "the", "actual", "installation" ]
python
train
janpipek/physt
physt/plotting/matplotlib.py
https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/plotting/matplotlib.py#L865-L958
def _apply_xy_lims(ax: Axes, h: Union[Histogram1D, Histogram2D], data: np.ndarray, kwargs: dict): """Apply axis limits and scales from kwargs. Note: if exponential binning is used, the scale defaults to "log" Parameters ---------- data : np.ndarray The frequencies or densities or otherwise manipulated data kwargs: dict xscale : Optional[str] If "log", the horizontal axis will use logarithmic scale yscale : Optional[str] If "log", the vertical axis will use logarithmic scale xlim : { "keep", "auto" } or tuple(float) "auto" (default) - the axis will fit first and last bin edges "keep" - let matlotlib figure this out tuple - standard parameter for set_xlim ylim : { "keep", "auto" } or tuple(float) "auto" (default) - the axis will fit first and last bin edges (2D) - the axis will exceed a bit the maximum value (1D) "keep" - let matlotlib figure this out tuple - standard parameter for set_ylim invert_y : Optional[bool] If True, higher values go down See Also -------- plt.Axes.set_xlim, plt.Axes.set_ylim, plt.Axes.set_xscale, plt.Axes.set_yscale """ ylim = kwargs.pop("ylim", "auto") xlim = kwargs.pop("xlim", "auto") invert_y = kwargs.pop("invert_y", False) xscale = yscale = None from ..binnings import ExponentialBinning if ylim is not "keep": if isinstance(ylim, tuple): pass elif ylim: ylim = ax.get_ylim() if h.ndim == 1: xscale = kwargs.pop("xscale", "log" if isinstance(h.binning, ExponentialBinning) else None) yscale = kwargs.pop("yscale", None) if data.size > 0 and data.max() > 0: ylim = (0, max(ylim[1], data.max() + (data.max() - ylim[0]) * 0.1)) if yscale == "log": ylim = (abs(data[data > 0].min()) * 0.9, ylim[1] * 1.1) elif h.ndim == 2: xscale = kwargs.pop("xscale", "log" if isinstance(h.binnings[0], ExponentialBinning) else None) yscale = kwargs.pop("yscale", "log" if isinstance(h.binnings[1], ExponentialBinning) else None) if h.shape[1] >= 2: ylim = (h.get_bin_left_edges(1)[0], h.get_bin_right_edges(1)[-1]) if yscale == "log": if ylim[0] <= 0: raise RuntimeError( "Cannot use logarithmic scale for non-positive bins.") else: raise RuntimeError("Invalid dimension: {0}".format(h.ndim)) if invert_y: ylim = ylim[::-1] # ax.xaxis.tick_top() # ax.xaxis.set_label_position('top') ax.set_ylim(ylim) if xlim is not "keep": if isinstance(xlim, tuple): pass elif xlim: xlim = ax.get_xlim() if h.shape[0] >= 1: if h.ndim == 1: xlim = (h.bin_left_edges[0], h.bin_right_edges[-1]) elif h.ndim == 2: xlim = (h.get_bin_left_edges(0)[ 0], h.get_bin_right_edges(0)[-1]) else: raise RuntimeError( "Invalid dimension: {0}".format(h.ndim)) if xscale == "log": if xlim[0] <= 0: raise RuntimeError( "Cannot use logarithmic scale for non-positive bins.") ax.set_xlim(*xlim) if xscale: ax.set_xscale(xscale) if yscale: ax.set_yscale(yscale)
[ "def", "_apply_xy_lims", "(", "ax", ":", "Axes", ",", "h", ":", "Union", "[", "Histogram1D", ",", "Histogram2D", "]", ",", "data", ":", "np", ".", "ndarray", ",", "kwargs", ":", "dict", ")", ":", "ylim", "=", "kwargs", ".", "pop", "(", "\"ylim\"", ...
Apply axis limits and scales from kwargs. Note: if exponential binning is used, the scale defaults to "log" Parameters ---------- data : np.ndarray The frequencies or densities or otherwise manipulated data kwargs: dict xscale : Optional[str] If "log", the horizontal axis will use logarithmic scale yscale : Optional[str] If "log", the vertical axis will use logarithmic scale xlim : { "keep", "auto" } or tuple(float) "auto" (default) - the axis will fit first and last bin edges "keep" - let matlotlib figure this out tuple - standard parameter for set_xlim ylim : { "keep", "auto" } or tuple(float) "auto" (default) - the axis will fit first and last bin edges (2D) - the axis will exceed a bit the maximum value (1D) "keep" - let matlotlib figure this out tuple - standard parameter for set_ylim invert_y : Optional[bool] If True, higher values go down See Also -------- plt.Axes.set_xlim, plt.Axes.set_ylim, plt.Axes.set_xscale, plt.Axes.set_yscale
[ "Apply", "axis", "limits", "and", "scales", "from", "kwargs", "." ]
python
train
jxtech/wechatpy
wechatpy/pay/api/coupon.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/pay/api/coupon.py#L43-L60
def query_stock(self, stock_id, op_user_id=None, device_info=None): """ 查询代金券批次 :param stock_id: 代金券批次 ID :param op_user_id: 可选,操作员账号,默认为商户号 :param device_info: 可选,微信支付分配的终端设备号 :return: 返回的结果信息 """ data = { 'appid': self.appid, 'coupon_stock_id': stock_id, 'op_user_id': op_user_id, 'device_info': device_info, 'version': '1.0', 'type': 'XML', } return self._post('mmpaymkttransfers/query_coupon_stock', data=data)
[ "def", "query_stock", "(", "self", ",", "stock_id", ",", "op_user_id", "=", "None", ",", "device_info", "=", "None", ")", ":", "data", "=", "{", "'appid'", ":", "self", ".", "appid", ",", "'coupon_stock_id'", ":", "stock_id", ",", "'op_user_id'", ":", "o...
查询代金券批次 :param stock_id: 代金券批次 ID :param op_user_id: 可选,操作员账号,默认为商户号 :param device_info: 可选,微信支付分配的终端设备号 :return: 返回的结果信息
[ "查询代金券批次" ]
python
train
frascoweb/frasco-users
frasco_users/__init__.py
https://github.com/frascoweb/frasco-users/blob/16591ca466de5b7c80d7a2384327d9cf2d919c41/frasco_users/__init__.py#L431-L439
def _login(self, user, provider=None, remember=False, force=False, **attrs): """Updates user attributes and login the user in flask-login """ user.last_login_at = datetime.datetime.now() user.last_login_provider = provider or self.options["default_auth_provider_name"] user.last_login_from = request.remote_addr populate_obj(user, attrs) save_model(user) flask_login.login_user(user, remember=remember, force=force)
[ "def", "_login", "(", "self", ",", "user", ",", "provider", "=", "None", ",", "remember", "=", "False", ",", "force", "=", "False", ",", "*", "*", "attrs", ")", ":", "user", ".", "last_login_at", "=", "datetime", ".", "datetime", ".", "now", "(", "...
Updates user attributes and login the user in flask-login
[ "Updates", "user", "attributes", "and", "login", "the", "user", "in", "flask", "-", "login" ]
python
train
tuomas2/automate
src/automate/callable.py
https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/callable.py#L192-L211
def setup_callable_system(self, system, init=False): """ This function basically sets up :attr:`.system`, if it is not yet set up. After that, other Callable initialization actions are performed. :param init: value ``True`` is given when running this at the initialization phase. Then system attribute is set already, but callable needs to be initialized otherwise. """ if not self.system or init: self.system = system self._fix_list(self._args) self._fix_list(self._kwargs) for i in self.children: if isinstance(i, AbstractCallable): i.setup_callable_system(system, init=init) elif isinstance(i, SystemObject): i.system = system self.on_setup_callable = 1 self.logger.debug('setup_callable_system for %s (%s) ready.', self, id(self))
[ "def", "setup_callable_system", "(", "self", ",", "system", ",", "init", "=", "False", ")", ":", "if", "not", "self", ".", "system", "or", "init", ":", "self", ".", "system", "=", "system", "self", ".", "_fix_list", "(", "self", ".", "_args", ")", "s...
This function basically sets up :attr:`.system`, if it is not yet set up. After that, other Callable initialization actions are performed. :param init: value ``True`` is given when running this at the initialization phase. Then system attribute is set already, but callable needs to be initialized otherwise.
[ "This", "function", "basically", "sets", "up", ":", "attr", ":", ".", "system", "if", "it", "is", "not", "yet", "set", "up", ".", "After", "that", "other", "Callable", "initialization", "actions", "are", "performed", "." ]
python
train
hazelcast/hazelcast-python-client
hazelcast/proxy/transactional_map.py
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/transactional_map.py#L35-L47
def get_for_update(self, key): """ Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at the end of the transaction (either commit or rollback). :param key: (object), the specified key. :return: (object), the value for the specified key. .. seealso:: :func:`Map.get(key) <hazelcast.proxy.map.Map.get>` """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_map_get_for_update_codec, key=self._to_data(key))
[ "def", "get_for_update", "(", "self", ",", "key", ")", ":", "check_not_none", "(", "key", ",", "\"key can't be none\"", ")", "return", "self", ".", "_encode_invoke", "(", "transactional_map_get_for_update_codec", ",", "key", "=", "self", ".", "_to_data", "(", "k...
Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at the end of the transaction (either commit or rollback). :param key: (object), the specified key. :return: (object), the value for the specified key. .. seealso:: :func:`Map.get(key) <hazelcast.proxy.map.Map.get>`
[ "Locks", "the", "key", "and", "then", "gets", "and", "returns", "the", "value", "to", "which", "the", "specified", "key", "is", "mapped", ".", "Lock", "will", "be", "released", "at", "the", "end", "of", "the", "transaction", "(", "either", "commit", "or"...
python
train
cloudendpoints/endpoints-python
endpoints/parameter_converter.py
https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/parameter_converter.py#L126-L147
def _get_parameter_conversion_entry(parameter_config): """Get information needed to convert the given parameter to its API type. Args: parameter_config: The dictionary containing information specific to the parameter in question. This is retrieved from request.parameters in the method config. Returns: The entry from _PARAM_CONVERSION_MAP with functions/information needed to validate and convert the given parameter from a string to the type expected by the API. """ entry = _PARAM_CONVERSION_MAP.get(parameter_config.get('type')) # Special handling for enum parameters. An enum's type is 'string', so we # need to detect them by the presence of an 'enum' property in their # configuration. if entry is None and 'enum' in parameter_config: entry = _PARAM_CONVERSION_MAP['enum'] return entry
[ "def", "_get_parameter_conversion_entry", "(", "parameter_config", ")", ":", "entry", "=", "_PARAM_CONVERSION_MAP", ".", "get", "(", "parameter_config", ".", "get", "(", "'type'", ")", ")", "# Special handling for enum parameters. An enum's type is 'string', so we", "# need ...
Get information needed to convert the given parameter to its API type. Args: parameter_config: The dictionary containing information specific to the parameter in question. This is retrieved from request.parameters in the method config. Returns: The entry from _PARAM_CONVERSION_MAP with functions/information needed to validate and convert the given parameter from a string to the type expected by the API.
[ "Get", "information", "needed", "to", "convert", "the", "given", "parameter", "to", "its", "API", "type", "." ]
python
train
biocore/burrito-fillings
bfillings/clearcut.py
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clearcut.py#L319-L364
def build_tree_from_distance_matrix(matrix, best_tree=False, params={},\ working_dir='/tmp'): """Returns a tree from a distance matrix. matrix: a square Dict2D object (cogent.util.dict2d) best_tree: if True (default:False), uses a slower but more accurate algorithm to build the tree. params: dict of parameters to pass in to the Clearcut app controller. The result will be an cogent.core.tree.PhyloNode object, or None if tree fails. """ params['--out'] = get_tmp_filename(working_dir) # Create instance of app controller, enable tree, disable alignment app = Clearcut(InputHandler='_input_as_multiline_string', params=params, \ WorkingDir=working_dir, SuppressStdout=True,\ SuppressStderr=True) #Turn off input as alignment app.Parameters['-a'].off() #Input is a distance matrix app.Parameters['-d'].on() if best_tree: app.Parameters['-N'].on() # Turn the dict2d object into the expected input format matrix_input, int_keys = _matrix_input_from_dict2d(matrix) # Collect result result = app(matrix_input) # Build tree tree = DndParser(result['Tree'].read(), constructor=PhyloNode) # reassign to original names for node in tree.tips(): node.Name = int_keys[node.Name] # Clean up result.cleanUp() del(app, result, params) return tree
[ "def", "build_tree_from_distance_matrix", "(", "matrix", ",", "best_tree", "=", "False", ",", "params", "=", "{", "}", ",", "working_dir", "=", "'/tmp'", ")", ":", "params", "[", "'--out'", "]", "=", "get_tmp_filename", "(", "working_dir", ")", "# Create insta...
Returns a tree from a distance matrix. matrix: a square Dict2D object (cogent.util.dict2d) best_tree: if True (default:False), uses a slower but more accurate algorithm to build the tree. params: dict of parameters to pass in to the Clearcut app controller. The result will be an cogent.core.tree.PhyloNode object, or None if tree fails.
[ "Returns", "a", "tree", "from", "a", "distance", "matrix", "." ]
python
train
bblfsh/client-python
bblfsh/client.py
https://github.com/bblfsh/client-python/blob/815835d191d5e385973f3c685849cc3b46aa20a5/bblfsh/client.py#L56-L85
def parse(self, filename: str, language: Optional[str]=None, contents: Optional[str]=None, mode: Optional[ModeType]=None, timeout: Optional[int]=None) -> ResultContext: """ Queries the Babelfish server and receives the UAST response for the specified file. :param filename: The path to the file. Can be arbitrary if contents \ is not None. :param language: The programming language of the file. Refer to \ https://doc.bblf.sh/languages.html for the list of \ currently supported languages. None means autodetect. :param contents: The contents of the file. IF None, it is read from \ filename. :param mode: UAST transformation mode. :param timeout: The request timeout in seconds. :type filename: str :type language: str :type contents: str :type timeout: float :return: UAST object. """ # TODO: handle syntax errors contents = self._get_contents(contents, filename) request = ParseRequest(filename=os.path.basename(filename), content=contents, mode=mode, language=self._scramble_language(language)) response = self._stub_v2.Parse(request, timeout=timeout) return ResultContext(response)
[ "def", "parse", "(", "self", ",", "filename", ":", "str", ",", "language", ":", "Optional", "[", "str", "]", "=", "None", ",", "contents", ":", "Optional", "[", "str", "]", "=", "None", ",", "mode", ":", "Optional", "[", "ModeType", "]", "=", "None...
Queries the Babelfish server and receives the UAST response for the specified file. :param filename: The path to the file. Can be arbitrary if contents \ is not None. :param language: The programming language of the file. Refer to \ https://doc.bblf.sh/languages.html for the list of \ currently supported languages. None means autodetect. :param contents: The contents of the file. IF None, it is read from \ filename. :param mode: UAST transformation mode. :param timeout: The request timeout in seconds. :type filename: str :type language: str :type contents: str :type timeout: float :return: UAST object.
[ "Queries", "the", "Babelfish", "server", "and", "receives", "the", "UAST", "response", "for", "the", "specified", "file", "." ]
python
train
wrobstory/vincent
vincent/data.py
https://github.com/wrobstory/vincent/blob/c5a06e50179015fbb788a7a42e4570ff4467a9e9/vincent/data.py#L367-L430
def keypairs(cls, data, columns=None, use_index=False, name=None): """This will format the data as Key: Value pairs, rather than the idx/col/val style. This is useful for some transforms, and to key choropleth map data Standard Data Types: List: [0, 10, 20, 30, 40] Paired Tuples: ((0, 1), (0, 2), (0, 3)) Dict: {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50} Plus Pandas DataFrame and Series, and Numpy ndarray Parameters ---------- data: List, Tuple, Dict, Pandas Series/DataFrame, Numpy ndarray columns: list, default None If passing Pandas DataFrame, you must pass at least one column name.If one column is passed, x-values will default to the index values.If two column names are passed, x-values are columns[0], y-values columns[1]. use_index: boolean, default False Use the DataFrame index for your x-values """ if not name: name = 'table' cls.raw_data = data # Tuples if isinstance(data, tuple): values = [{"x": x[0], "y": x[1]} for x in data] # Lists elif isinstance(data, list): values = [{"x": x, "y": y} for x, y in zip(range(len(data) + 1), data)] # Dicts elif isinstance(data, dict) or isinstance(data, pd.Series): values = [{"x": x, "y": y} for x, y in sorted(data.items())] # Dataframes elif isinstance(data, pd.DataFrame): if len(columns) > 1 and use_index: raise ValueError('If using index as x-axis, len(columns)' 'cannot be > 1') if use_index or len(columns) == 1: values = [{"x": cls.serialize(x[0]), "y": cls.serialize(x[1][columns[0]])} for x in data.iterrows()] else: values = [{"x": cls.serialize(x[1][columns[0]]), "y": cls.serialize(x[1][columns[1]])} for x in data.iterrows()] # NumPy arrays elif isinstance(data, np.ndarray): values = cls._numpy_to_values(data) else: raise TypeError('unknown data type %s' % type(data)) return cls(name, values=values)
[ "def", "keypairs", "(", "cls", ",", "data", ",", "columns", "=", "None", ",", "use_index", "=", "False", ",", "name", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "'table'", "cls", ".", "raw_data", "=", "data", "# Tuples", "if", "i...
This will format the data as Key: Value pairs, rather than the idx/col/val style. This is useful for some transforms, and to key choropleth map data Standard Data Types: List: [0, 10, 20, 30, 40] Paired Tuples: ((0, 1), (0, 2), (0, 3)) Dict: {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50} Plus Pandas DataFrame and Series, and Numpy ndarray Parameters ---------- data: List, Tuple, Dict, Pandas Series/DataFrame, Numpy ndarray columns: list, default None If passing Pandas DataFrame, you must pass at least one column name.If one column is passed, x-values will default to the index values.If two column names are passed, x-values are columns[0], y-values columns[1]. use_index: boolean, default False Use the DataFrame index for your x-values
[ "This", "will", "format", "the", "data", "as", "Key", ":", "Value", "pairs", "rather", "than", "the", "idx", "/", "col", "/", "val", "style", ".", "This", "is", "useful", "for", "some", "transforms", "and", "to", "key", "choropleth", "map", "data" ]
python
train
pypa/pipenv
pipenv/vendor/dotenv/cli.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/cli.py#L72-L80
def unset(ctx, key): '''Removes the given key.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key = unset_key(file, key, quote) if success: click.echo("Successfully removed %s" % key) else: exit(1)
[ "def", "unset", "(", "ctx", ",", "key", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "quote", "=", "ctx", ".", "obj", "[", "'QUOTE'", "]", "success", ",", "key", "=", "unset_key", "(", "file", ",", "key", ",", "quote", ")", "if...
Removes the given key.
[ "Removes", "the", "given", "key", "." ]
python
train
oceanprotocol/squid-py
squid_py/agreements/service_factory.py
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L100-L137
def build_service(service_descriptor, did): """ Build a service. :param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes and the second item is a dict of parameters and values required by the service :param did: DID, str :return: Service """ assert isinstance(service_descriptor, tuple) and len( service_descriptor) == 2, 'Unknown service descriptor format.' service_type, kwargs = service_descriptor if service_type == ServiceTypes.METADATA: return ServiceFactory.build_metadata_service( did, kwargs['metadata'], kwargs['serviceEndpoint'] ) elif service_type == ServiceTypes.AUTHORIZATION: return ServiceFactory.build_authorization_service( kwargs['serviceEndpoint'] ) elif service_type == ServiceTypes.ASSET_ACCESS: return ServiceFactory.build_access_service( did, kwargs['price'], kwargs['consumeEndpoint'], kwargs['serviceEndpoint'], kwargs['timeout'], kwargs['templateId'] ) elif service_type == ServiceTypes.CLOUD_COMPUTE: return ServiceFactory.build_compute_service( did, kwargs['price'], kwargs['consumeEndpoint'], kwargs['serviceEndpoint'], kwargs['timeout'] ) raise ValueError(f'Unknown service type {service_type}')
[ "def", "build_service", "(", "service_descriptor", ",", "did", ")", ":", "assert", "isinstance", "(", "service_descriptor", ",", "tuple", ")", "and", "len", "(", "service_descriptor", ")", "==", "2", ",", "'Unknown service descriptor format.'", "service_type", ",", ...
Build a service. :param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes and the second item is a dict of parameters and values required by the service :param did: DID, str :return: Service
[ "Build", "a", "service", "." ]
python
train
useblocks/sphinxcontrib-needs
sphinxcontrib/needs/directives/need.py
https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L444-L476
def create_back_links(env): """ Create back-links in all found needs. But do this only once, as all needs are already collected and this sorting is for all needs and not only for the ones of the current document. :param env: sphinx enviroment :return: None """ if env.needs_workflow['backlink_creation']: return needs = env.needs_all_needs for key, need in needs.items(): for link in need["links"]: link_main = link.split('.')[0] try: link_part = link.split('.')[1] except IndexError: link_part = None if link_main in needs: if key not in needs[link_main]["links_back"]: needs[link_main]["links_back"].append(key) # Handling of links to need_parts inside a need if link_part is not None: if link_part in needs[link_main]['parts']: if 'links_back' not in needs[link_main]['parts'][link_part].keys(): needs[link_main]['parts'][link_part]['links_back'] = [] needs[link_main]['parts'][link_part]['links_back'].append(key) env.needs_workflow['backlink_creation'] = True
[ "def", "create_back_links", "(", "env", ")", ":", "if", "env", ".", "needs_workflow", "[", "'backlink_creation'", "]", ":", "return", "needs", "=", "env", ".", "needs_all_needs", "for", "key", ",", "need", "in", "needs", ".", "items", "(", ")", ":", "for...
Create back-links in all found needs. But do this only once, as all needs are already collected and this sorting is for all needs and not only for the ones of the current document. :param env: sphinx enviroment :return: None
[ "Create", "back", "-", "links", "in", "all", "found", "needs", ".", "But", "do", "this", "only", "once", "as", "all", "needs", "are", "already", "collected", "and", "this", "sorting", "is", "for", "all", "needs", "and", "not", "only", "for", "the", "on...
python
train
n1analytics/python-paillier
phe/util.py
https://github.com/n1analytics/python-paillier/blob/955f8c0bfa9623be15b75462b121d28acf70f04b/phe/util.py#L367-L404
def miller_rabin(n, k): """Run the Miller-Rabin test on n with at most k iterations Arguments: n (int): number whose primality is to be tested k (int): maximum number of iterations to run Returns: bool: If n is prime, then True is returned. Otherwise, False is returned, except with probability less than 4**-k. See <https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test> """ assert n > 3 # find r and d such that n-1 = 2^r × d d = n-1 r = 0 while d % 2 == 0: d //= 2 r += 1 assert n-1 == d * 2**r assert d % 2 == 1 for _ in range(k): # each iteration divides risk of false prime by 4 a = random.randint(2, n-2) # choose a random witness x = pow(a, d, n) if x == 1 or x == n-1: continue # go to next witness for _ in range(1, r): x = x*x % n if x == n-1: break # go to next witness else: return False return True
[ "def", "miller_rabin", "(", "n", ",", "k", ")", ":", "assert", "n", ">", "3", "# find r and d such that n-1 = 2^r × d", "d", "=", "n", "-", "1", "r", "=", "0", "while", "d", "%", "2", "==", "0", ":", "d", "//=", "2", "r", "+=", "1", "assert", "n"...
Run the Miller-Rabin test on n with at most k iterations Arguments: n (int): number whose primality is to be tested k (int): maximum number of iterations to run Returns: bool: If n is prime, then True is returned. Otherwise, False is returned, except with probability less than 4**-k. See <https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test>
[ "Run", "the", "Miller", "-", "Rabin", "test", "on", "n", "with", "at", "most", "k", "iterations" ]
python
train
TheOneHyer/arandomness
build/lib.linux-x86_64-3.6/arandomness/str/max_substring.py
https://github.com/TheOneHyer/arandomness/blob/ae9f630e9a1d67b0eb6d61644a49756de8a5268c/build/lib.linux-x86_64-3.6/arandomness/str/max_substring.py#L31-L71
def max_substring(words, position=0, _last_letter=''): """Finds max substring shared by all strings starting at position Args: words (list): list of unicode of all words to compare position (int): starting position in each word to begin analyzing for substring _last_letter (unicode): last common letter, only for use internally unless you really know what you are doing Returns: unicode: max str common to all words Examples: .. code-block:: Python >>> max_substring(['aaaa', 'aaab', 'aaac']) 'aaa' >>> max_substring(['abbb', 'bbbb', 'cbbb'], position=1) 'bbb' >>> max_substring(['abc', 'bcd', 'cde']) '' """ # If end of word is reached, begin reconstructing the substring try: letter = [word[position] for word in words] except IndexError: return _last_letter # Recurse if position matches, else begin reconstructing the substring if all(l == letter[0] for l in letter) is True: _last_letter += max_substring(words, position=position + 1, _last_letter=letter[0]) return _last_letter else: return _last_letter
[ "def", "max_substring", "(", "words", ",", "position", "=", "0", ",", "_last_letter", "=", "''", ")", ":", "# If end of word is reached, begin reconstructing the substring", "try", ":", "letter", "=", "[", "word", "[", "position", "]", "for", "word", "in", "word...
Finds max substring shared by all strings starting at position Args: words (list): list of unicode of all words to compare position (int): starting position in each word to begin analyzing for substring _last_letter (unicode): last common letter, only for use internally unless you really know what you are doing Returns: unicode: max str common to all words Examples: .. code-block:: Python >>> max_substring(['aaaa', 'aaab', 'aaac']) 'aaa' >>> max_substring(['abbb', 'bbbb', 'cbbb'], position=1) 'bbb' >>> max_substring(['abc', 'bcd', 'cde']) ''
[ "Finds", "max", "substring", "shared", "by", "all", "strings", "starting", "at", "position" ]
python
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L201-L233
def update_coefs(self): """(Re)calculate the MA coefficients based on the instantaneous unit hydrograph.""" coefs = [] sum_coefs = 0. moment1 = self.iuh.moment1 for t in itertools.count(0., 1.): points = (moment1 % 1,) if t <= moment1 <= (t+2.) else () try: coef = integrate.quad( self._quad, 0., 1., args=(t,), points=points)[0] except integrate.IntegrationWarning: idx = int(moment1) coefs = numpy.zeros(idx+2, dtype=float) weight = (moment1-idx) coefs[idx] = (1.-weight) coefs[idx+1] = weight self.coefs = coefs warnings.warn( 'During the determination of the MA coefficients ' 'corresponding to the instantaneous unit hydrograph ' '`%s` a numerical integration problem occurred. ' 'Please check the calculated coefficients: %s.' % (repr(self.iuh), objecttools.repr_values(coefs))) break # pragma: no cover sum_coefs += coef if (sum_coefs > .9) and (coef < self.smallest_coeff): coefs = numpy.array(coefs) coefs /= numpy.sum(coefs) self.coefs = coefs break else: coefs.append(coef)
[ "def", "update_coefs", "(", "self", ")", ":", "coefs", "=", "[", "]", "sum_coefs", "=", "0.", "moment1", "=", "self", ".", "iuh", ".", "moment1", "for", "t", "in", "itertools", ".", "count", "(", "0.", ",", "1.", ")", ":", "points", "=", "(", "mo...
(Re)calculate the MA coefficients based on the instantaneous unit hydrograph.
[ "(", "Re", ")", "calculate", "the", "MA", "coefficients", "based", "on", "the", "instantaneous", "unit", "hydrograph", "." ]
python
train
cgrok/cr-async
examples/crcog.py
https://github.com/cgrok/cr-async/blob/f65a968e54704168706d137d1ba662f55f8ab852/examples/crcog.py#L22-L42
async def profile(self, ctx, tag): '''Example command for use inside a discord bot cog.''' if not self.check_valid_tag(tag): return await ctx.send('Invalid tag!') profile = await self.cr.get_profile(tag) em = discord.Embed(color=0x00FFFFF) em.set_author(name=str(profile), icon_url=profile.clan_badge_url) em.set_thumbnail(url=profile.arena.badge_url) # Example of adding data. (Bad) for attr in self.cdir(profile): value = getattr(profile, attr) if not callable(value): em.add_field( name=attr.replace('_').title(), value=str(value) ) await ctx.send(embed=em)
[ "async", "def", "profile", "(", "self", ",", "ctx", ",", "tag", ")", ":", "if", "not", "self", ".", "check_valid_tag", "(", "tag", ")", ":", "return", "await", "ctx", ".", "send", "(", "'Invalid tag!'", ")", "profile", "=", "await", "self", ".", "cr"...
Example command for use inside a discord bot cog.
[ "Example", "command", "for", "use", "inside", "a", "discord", "bot", "cog", "." ]
python
train
MAVENSDC/cdflib
cdflib/cdfread.py
https://github.com/MAVENSDC/cdflib/blob/d237c60e5db67db0f92d96054209c25c4042465c/cdflib/cdfread.py#L2196-L2211
def _find_block(starts, ends, cur_block, rec_num): # @NoSelf ''' Finds the block that rec_num is in if it is found. Otherwise it returns -1. It also returns the block that has the physical data either at or preceeding the rec_num. It could be -1 if the preceeding block does not exists. ''' total = len(starts) if (cur_block == -1): cur_block = 0 for x in range(cur_block, total): if (starts[x] <= rec_num and ends[x] >= rec_num): return x, x if (starts[x] > rec_num): break return -1, x-1
[ "def", "_find_block", "(", "starts", ",", "ends", ",", "cur_block", ",", "rec_num", ")", ":", "# @NoSelf", "total", "=", "len", "(", "starts", ")", "if", "(", "cur_block", "==", "-", "1", ")", ":", "cur_block", "=", "0", "for", "x", "in", "range", ...
Finds the block that rec_num is in if it is found. Otherwise it returns -1. It also returns the block that has the physical data either at or preceeding the rec_num. It could be -1 if the preceeding block does not exists.
[ "Finds", "the", "block", "that", "rec_num", "is", "in", "if", "it", "is", "found", ".", "Otherwise", "it", "returns", "-", "1", ".", "It", "also", "returns", "the", "block", "that", "has", "the", "physical", "data", "either", "at", "or", "preceeding", ...
python
train
pyecore/pyecore
pyecore/ordered_set_patch.py
https://github.com/pyecore/pyecore/blob/22b67ad8799594f8f44fd8bee497583d4f12ed63/pyecore/ordered_set_patch.py#L8-L27
def insert(self, index, key): """Adds an element at a dedicated position in an OrderedSet. This implementation is meant for the OrderedSet from the ordered_set package only. """ if key in self.map: return # compute the right index size = len(self.items) if index < 0: index = size + index if size + index > 0 else 0 else: index = index if index < size else size # insert the value self.items.insert(index, key) for k, v in self.map.items(): if v >= index: self.map[k] = v + 1 self.map[key] = index
[ "def", "insert", "(", "self", ",", "index", ",", "key", ")", ":", "if", "key", "in", "self", ".", "map", ":", "return", "# compute the right index", "size", "=", "len", "(", "self", ".", "items", ")", "if", "index", "<", "0", ":", "index", "=", "si...
Adds an element at a dedicated position in an OrderedSet. This implementation is meant for the OrderedSet from the ordered_set package only.
[ "Adds", "an", "element", "at", "a", "dedicated", "position", "in", "an", "OrderedSet", "." ]
python
train
HttpRunner/HttpRunner
httprunner/report.py
https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/report.py#L92-L106
def stringify_summary(summary): """ stringify summary, in order to dump json file and generate html report. """ for index, suite_summary in enumerate(summary["details"]): if not suite_summary.get("name"): suite_summary["name"] = "testcase {}".format(index) for record in suite_summary.get("records"): meta_datas = record['meta_datas'] __stringify_meta_datas(meta_datas) meta_datas_expanded = [] __expand_meta_datas(meta_datas, meta_datas_expanded) record["meta_datas_expanded"] = meta_datas_expanded record["response_time"] = __get_total_response_time(meta_datas_expanded)
[ "def", "stringify_summary", "(", "summary", ")", ":", "for", "index", ",", "suite_summary", "in", "enumerate", "(", "summary", "[", "\"details\"", "]", ")", ":", "if", "not", "suite_summary", ".", "get", "(", "\"name\"", ")", ":", "suite_summary", "[", "\"...
stringify summary, in order to dump json file and generate html report.
[ "stringify", "summary", "in", "order", "to", "dump", "json", "file", "and", "generate", "html", "report", "." ]
python
train
jut-io/jut-python-tools
jut/commands/jobs.py
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/jobs.py#L116-L145
def list(options): """ show all currently running jobs """ configuration = config.get_default() app_url = configuration['app_url'] if options.deployment != None: deployment_name = options.deployment else: deployment_name = configuration['deployment_name'] client_id = configuration['client_id'] client_secret = configuration['client_secret'] token_manager = auth.TokenManager(client_id=client_id, client_secret=client_secret, app_url=app_url) jobs = data_engine.get_jobs(deployment_name, token_manager=token_manager, app_url=app_url) if len(jobs) == 0: error('No running jobs') else: _print_jobs(jobs, token_manager, app_url, options)
[ "def", "list", "(", "options", ")", ":", "configuration", "=", "config", ".", "get_default", "(", ")", "app_url", "=", "configuration", "[", "'app_url'", "]", "if", "options", ".", "deployment", "!=", "None", ":", "deployment_name", "=", "options", ".", "d...
show all currently running jobs
[ "show", "all", "currently", "running", "jobs" ]
python
train
quantopian/zipline
zipline/data/hdf5_daily_bars.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L745-L757
def from_file(cls, h5_file): """ Construct from an h5py.File. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file. """ return cls({ country: HDF5DailyBarReader.from_file(h5_file, country) for country in h5_file.keys() })
[ "def", "from_file", "(", "cls", ",", "h5_file", ")", ":", "return", "cls", "(", "{", "country", ":", "HDF5DailyBarReader", ".", "from_file", "(", "h5_file", ",", "country", ")", "for", "country", "in", "h5_file", ".", "keys", "(", ")", "}", ")" ]
Construct from an h5py.File. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file.
[ "Construct", "from", "an", "h5py", ".", "File", "." ]
python
train
ib-lundgren/flask-oauthprovider
examples/demoprovider/login.py
https://github.com/ib-lundgren/flask-oauthprovider/blob/6c91e8c11fc3cee410cb755d52d9d2c5331ee324/examples/demoprovider/login.py#L33-L46
def login(): """Does the login via OpenID. Has to call into `oid.try_login` to start the OpenID machinery. """ # if we are already logged in, go back to were we came from if g.user is not None: return redirect(oid.get_next_url()) if request.method == 'POST': openid = request.form.get('openid') if openid: return oid.try_login(openid, ask_for=['email', 'fullname', 'nickname']) return render_template('login.html', next=oid.get_next_url(), error=oid.fetch_error())
[ "def", "login", "(", ")", ":", "# if we are already logged in, go back to were we came from", "if", "g", ".", "user", "is", "not", "None", ":", "return", "redirect", "(", "oid", ".", "get_next_url", "(", ")", ")", "if", "request", ".", "method", "==", "'POST'"...
Does the login via OpenID. Has to call into `oid.try_login` to start the OpenID machinery.
[ "Does", "the", "login", "via", "OpenID", ".", "Has", "to", "call", "into", "oid", ".", "try_login", "to", "start", "the", "OpenID", "machinery", "." ]
python
train
Microsoft/LightGBM
helpers/parameter_generator.py
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L12-L77
def get_parameter_infos(config_hpp): """Parse config header file. Parameters ---------- config_hpp : string Path to the config header file. Returns ------- infos : tuple Tuple with names and content of sections. """ is_inparameter = False parameter_group = None cur_key = None cur_info = {} keys = [] member_infos = [] with open(config_hpp) as config_hpp_file: for line in config_hpp_file: if "#pragma region Parameters" in line: is_inparameter = True elif "#pragma region" in line and "Parameters" in line: cur_key = line.split("region")[1].strip() keys.append(cur_key) member_infos.append([]) elif '#pragma endregion' in line: if cur_key is not None: cur_key = None elif is_inparameter: is_inparameter = False elif cur_key is not None: line = line.strip() if line.startswith("//"): key, _, val = line[2:].partition("=") key = key.strip() val = val.strip() if key not in cur_info: if key == "descl2" and "desc" not in cur_info: cur_info["desc"] = [] elif key != "descl2": cur_info[key] = [] if key == "desc": cur_info["desc"].append(("l1", val)) elif key == "descl2": cur_info["desc"].append(("l2", val)) else: cur_info[key].append(val) elif line: has_eqsgn = False tokens = line.split("=") if len(tokens) == 2: if "default" not in cur_info: cur_info["default"] = [tokens[1][:-1].strip()] has_eqsgn = True tokens = line.split() cur_info["inner_type"] = [tokens[0].strip()] if "name" not in cur_info: if has_eqsgn: cur_info["name"] = [tokens[1].strip()] else: cur_info["name"] = [tokens[1][:-1].strip()] member_infos[-1].append(cur_info) cur_info = {} return keys, member_infos
[ "def", "get_parameter_infos", "(", "config_hpp", ")", ":", "is_inparameter", "=", "False", "parameter_group", "=", "None", "cur_key", "=", "None", "cur_info", "=", "{", "}", "keys", "=", "[", "]", "member_infos", "=", "[", "]", "with", "open", "(", "config...
Parse config header file. Parameters ---------- config_hpp : string Path to the config header file. Returns ------- infos : tuple Tuple with names and content of sections.
[ "Parse", "config", "header", "file", "." ]
python
train
openstack/monasca-common
monasca_common/kafka_lib/conn.py
https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/kafka_lib/conn.py#L199-L217
def close(self): """ Shutdown and close the connection socket """ log.debug("Closing socket connection for %s:%d" % (self.host, self.port)) if self._sock: # Call shutdown to be a good TCP client # But expect an error if the socket has already been # closed by the server try: self._sock.shutdown(socket.SHUT_RDWR) except socket.error: pass # Closing the socket should always succeed self._sock.close() self._sock = None else: log.debug("No socket found to close!")
[ "def", "close", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Closing socket connection for %s:%d\"", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "if", "self", ".", "_sock", ":", "# Call shutdown to be a good TCP client", "# But ex...
Shutdown and close the connection socket
[ "Shutdown", "and", "close", "the", "connection", "socket" ]
python
train
DLR-RM/RAFCON
source/rafcon/core/states/container_state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1583-L1590
def add_default_values_of_scoped_variables_to_scoped_data(self): """Add the scoped variables default values to the scoped_data dictionary """ for key, scoped_var in self.scoped_variables.items(): self.scoped_data[str(scoped_var.data_port_id) + self.state_id] = \ ScopedData(scoped_var.name, scoped_var.default_value, scoped_var.data_type, self.state_id, ScopedVariable, parent=self)
[ "def", "add_default_values_of_scoped_variables_to_scoped_data", "(", "self", ")", ":", "for", "key", ",", "scoped_var", "in", "self", ".", "scoped_variables", ".", "items", "(", ")", ":", "self", ".", "scoped_data", "[", "str", "(", "scoped_var", ".", "data_port...
Add the scoped variables default values to the scoped_data dictionary
[ "Add", "the", "scoped", "variables", "default", "values", "to", "the", "scoped_data", "dictionary" ]
python
train
niolabs/python-xbee
examples/alarm.py
https://github.com/niolabs/python-xbee/blob/b91be3d0ee7ccaa1990120b5b5490999d8e6cbc7/examples/alarm.py#L122-L132
def _set_LED(self, status): """ _set_LED: boolean -> None Sets the status of the remote LED """ # DIO pin 1 (LED), active low self.hw.remote_at( dest_addr=self.remote_addr, command='D1', parameter='\x04' if status else '\x05')
[ "def", "_set_LED", "(", "self", ",", "status", ")", ":", "# DIO pin 1 (LED), active low", "self", ".", "hw", ".", "remote_at", "(", "dest_addr", "=", "self", ".", "remote_addr", ",", "command", "=", "'D1'", ",", "parameter", "=", "'\\x04'", "if", "status", ...
_set_LED: boolean -> None Sets the status of the remote LED
[ "_set_LED", ":", "boolean", "-", ">", "None" ]
python
train
rosenbrockc/ci
pyci/server.py
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/server.py#L540-L565
def fields_general(self, event): """Appends any additional fields to the common ones and returns the fields dictionary. """ result = self._fields_common() basic = { "__test_html__": self.repo.testing.html(False), "__test_text__": self.repo.testing.text(False)} full = { "__test_html__": self.repo.testing.html(), "__test_text__": self.repo.testing.text()} if event in ["finish", "success"]: full["__percent__"] = "{0:.2%}".format(self.percent) full["__status__"] = self.message extra = { "start": basic, "error": basic, "finish": full, "success": full, "timeout": basic } if event in extra: result.update(extra[event]) return result
[ "def", "fields_general", "(", "self", ",", "event", ")", ":", "result", "=", "self", ".", "_fields_common", "(", ")", "basic", "=", "{", "\"__test_html__\"", ":", "self", ".", "repo", ".", "testing", ".", "html", "(", "False", ")", ",", "\"__test_text__\...
Appends any additional fields to the common ones and returns the fields dictionary.
[ "Appends", "any", "additional", "fields", "to", "the", "common", "ones", "and", "returns", "the", "fields", "dictionary", "." ]
python
train
Geotab/mygeotab-python
mygeotab/api.py
https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/api.py#L126-L144
def get(self, type_name, **parameters): """Gets entities using the API. Shortcut for using call() with the 'Get' method. :param type_name: The type of entity. :type type_name: str :param parameters: Additional parameters to send. :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: The results from the server. :rtype: list """ if parameters: results_limit = parameters.get('resultsLimit', None) if results_limit is not None: del parameters['resultsLimit'] if 'search' in parameters: parameters.update(parameters['search']) parameters = dict(search=parameters, resultsLimit=results_limit) return self.call('Get', type_name=type_name, **parameters)
[ "def", "get", "(", "self", ",", "type_name", ",", "*", "*", "parameters", ")", ":", "if", "parameters", ":", "results_limit", "=", "parameters", ".", "get", "(", "'resultsLimit'", ",", "None", ")", "if", "results_limit", "is", "not", "None", ":", "del", ...
Gets entities using the API. Shortcut for using call() with the 'Get' method. :param type_name: The type of entity. :type type_name: str :param parameters: Additional parameters to send. :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. :raise TimeoutException: Raises when the request does not respond after some time. :return: The results from the server. :rtype: list
[ "Gets", "entities", "using", "the", "API", ".", "Shortcut", "for", "using", "call", "()", "with", "the", "Get", "method", "." ]
python
train
ronhanson/python-tbx
tbx/bytes.py
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/bytes.py#L180-L193
def decode_ber(ber): """ Decodes a ber length byte array into an integer return: (length, bytes_read) - a tuple of values """ ber = bytearray(ber) length = ber[0] bytes_read = 1 if length > 127: bytes_read += length & 127 # Strip off the high bit length = 0 for i in range(1, bytes_read): length += ber[i] << (8 * (bytes_read - i - 1)) return length, bytes_read
[ "def", "decode_ber", "(", "ber", ")", ":", "ber", "=", "bytearray", "(", "ber", ")", "length", "=", "ber", "[", "0", "]", "bytes_read", "=", "1", "if", "length", ">", "127", ":", "bytes_read", "+=", "length", "&", "127", "# Strip off the high bit", "le...
Decodes a ber length byte array into an integer return: (length, bytes_read) - a tuple of values
[ "Decodes", "a", "ber", "length", "byte", "array", "into", "an", "integer", "return", ":", "(", "length", "bytes_read", ")", "-", "a", "tuple", "of", "values" ]
python
train
troeger/opensubmit
web/opensubmit/models/submission.py
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/models/submission.py#L361-L420
def can_modify(self, user=None): """Determines whether the submission can be modified. Returns a boolean value. The 'user' parameter is optional and additionally checks whether the given user is authorized to perform these actions. This function checks the submission states and assignment deadlines.""" # The user must be authorized to commit these actions. if user and not self.user_can_modify(user): #self.log('DEBUG', "Submission cannot be modified, user is not an authorized user ({!r} not in {!r})", user, self.authorized_users) return False # Modification of submissions, that are withdrawn, graded or currently being graded, is prohibited. if self.state in [self.WITHDRAWN, self.GRADED, self.GRADING_IN_PROGRESS, ]: #self.log('DEBUG', "Submission cannot be modified, is in state '{}'", self.state) return False # Modification of closed submissions is prohibited. if self.is_closed(): if self.assignment.is_graded(): # There is a grading procedure, so taking it back would invalidate the tutors work #self.log('DEBUG', "Submission cannot be modified, it is closed and graded") return False else: #self.log('DEBUG', "Closed submission can be modified, since it has no grading scheme.") return True # Submissions, that are executed right now, cannot be modified if self.state in [self.TEST_VALIDITY_PENDING, self.TEST_FULL_PENDING]: if not self.file_upload: self.log( 'CRITICAL', "Submission is in invalid state! State is '{}', but there is no file uploaded!", self.state) raise AssertionError() return False if self.file_upload.is_executed(): # The above call informs that the uploaded file is being executed, or execution has been completed. # Since the current state is 'PENDING', the execution cannot yet be completed. # Thus, the submitted file is being executed right now. return False # Submissions must belong to an assignment. if not self.assignment: self.log('CRITICAL', "Submission does not belong to an assignment!") raise AssertionError() # Submissions, that belong to an assignment where the hard deadline has passed, # cannot be modified. if self.assignment.hard_deadline and timezone.now() > self.assignment.hard_deadline: #self.log('DEBUG', "Submission cannot be modified - assignment's hard deadline has passed (hard deadline is: {})", self.assignment.hard_deadline) return False # The soft deadline has no effect (yet). if self.assignment.soft_deadline: if timezone.now() > self.assignment.soft_deadline: # The soft deadline has passed pass # do nothing. #self.log('DEBUG', "Submission can be modified.") return True
[ "def", "can_modify", "(", "self", ",", "user", "=", "None", ")", ":", "# The user must be authorized to commit these actions.", "if", "user", "and", "not", "self", ".", "user_can_modify", "(", "user", ")", ":", "#self.log('DEBUG', \"Submission cannot be modified, user is ...
Determines whether the submission can be modified. Returns a boolean value. The 'user' parameter is optional and additionally checks whether the given user is authorized to perform these actions. This function checks the submission states and assignment deadlines.
[ "Determines", "whether", "the", "submission", "can", "be", "modified", ".", "Returns", "a", "boolean", "value", ".", "The", "user", "parameter", "is", "optional", "and", "additionally", "checks", "whether", "the", "given", "user", "is", "authorized", "to", "pe...
python
train
gaqzi/gocd-cli
gocd_cli/utils.py
https://github.com/gaqzi/gocd-cli/blob/ca8df8ec2274fdc69bce0619aa3794463c4f5a6f/gocd_cli/utils.py#L62-L96
def format_arguments(*args): """ Converts a list of arguments from the command line into a list of positional arguments and a dictionary of keyword arguments. Handled formats for keyword arguments are: * --argument=value * --argument value Args: *args (list): a list of arguments Returns: ([positional_args], {kwargs}) """ positional_args = [] kwargs = {} split_key = None for arg in args: if arg.startswith('--'): arg = arg[2:] if '=' in arg: key, value = arg.split('=', 1) kwargs[key.replace('-', '_')] = value else: split_key = arg.replace('-', '_') elif split_key: kwargs[split_key] = arg split_key = None else: positional_args.append(arg) return positional_args, kwargs
[ "def", "format_arguments", "(", "*", "args", ")", ":", "positional_args", "=", "[", "]", "kwargs", "=", "{", "}", "split_key", "=", "None", "for", "arg", "in", "args", ":", "if", "arg", ".", "startswith", "(", "'--'", ")", ":", "arg", "=", "arg", "...
Converts a list of arguments from the command line into a list of positional arguments and a dictionary of keyword arguments. Handled formats for keyword arguments are: * --argument=value * --argument value Args: *args (list): a list of arguments Returns: ([positional_args], {kwargs})
[ "Converts", "a", "list", "of", "arguments", "from", "the", "command", "line", "into", "a", "list", "of", "positional", "arguments", "and", "a", "dictionary", "of", "keyword", "arguments", "." ]
python
train
odlgroup/odl
odl/space/entry_points.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/entry_points.py#L56-L84
def tensor_space_impl(impl): """Tensor space class corresponding to the given impl name. Parameters ---------- impl : str Name of the implementation, see `tensor_space_impl_names` for the full list. Returns ------- tensor_space_impl : type Class inheriting from `TensorSpace`. Raises ------ ValueError If ``impl`` is not a valid name of a tensor space imlementation. """ if impl != 'numpy': # Shortcut to improve "import odl" times since most users do not use # non-numpy backends _initialize_if_needed() try: return TENSOR_SPACE_IMPLS[impl] except KeyError: raise ValueError("`impl` {!r} does not correspond to a valid tensor " "space implmentation".format(impl))
[ "def", "tensor_space_impl", "(", "impl", ")", ":", "if", "impl", "!=", "'numpy'", ":", "# Shortcut to improve \"import odl\" times since most users do not use", "# non-numpy backends", "_initialize_if_needed", "(", ")", "try", ":", "return", "TENSOR_SPACE_IMPLS", "[", "impl...
Tensor space class corresponding to the given impl name. Parameters ---------- impl : str Name of the implementation, see `tensor_space_impl_names` for the full list. Returns ------- tensor_space_impl : type Class inheriting from `TensorSpace`. Raises ------ ValueError If ``impl`` is not a valid name of a tensor space imlementation.
[ "Tensor", "space", "class", "corresponding", "to", "the", "given", "impl", "name", "." ]
python
train
Stanford-Online/xblock-image-modal
imagemodal/views.py
https://github.com/Stanford-Online/xblock-image-modal/blob/bd05f99a830a44f8d1a0e6e137e507b8ff8ff028/imagemodal/views.py#L27-L53
def student_view(self, context=None): """ Build the fragment for the default student view """ context = context or {} context.update({ 'display_name': self.display_name, 'image_url': self.image_url, 'thumbnail_url': self.thumbnail_url or self.image_url, 'description': self.description, 'xblock_id': text_type(self.scope_ids.usage_id), 'alt_text': self.alt_text or self.display_name, }) fragment = self.build_fragment( template='view.html', context=context, css=[ 'view.less.css', URL_FONT_AWESOME_CSS, ], js=[ 'draggabilly.pkgd.js', 'view.js', ], js_init='ImageModalView', ) return fragment
[ "def", "student_view", "(", "self", ",", "context", "=", "None", ")", ":", "context", "=", "context", "or", "{", "}", "context", ".", "update", "(", "{", "'display_name'", ":", "self", ".", "display_name", ",", "'image_url'", ":", "self", ".", "image_url...
Build the fragment for the default student view
[ "Build", "the", "fragment", "for", "the", "default", "student", "view" ]
python
train
instaloader/instaloader
instaloader/instaloadercontext.py
https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/instaloadercontext.py#L484-L493
def write_raw(self, resp: Union[bytes, requests.Response], filename: str) -> None: """Write raw response data into a file. .. versionadded:: 4.2.1""" self.log(filename, end=' ', flush=True) with open(filename, 'wb') as file: if isinstance(resp, requests.Response): shutil.copyfileobj(resp.raw, file) else: file.write(resp)
[ "def", "write_raw", "(", "self", ",", "resp", ":", "Union", "[", "bytes", ",", "requests", ".", "Response", "]", ",", "filename", ":", "str", ")", "->", "None", ":", "self", ".", "log", "(", "filename", ",", "end", "=", "' '", ",", "flush", "=", ...
Write raw response data into a file. .. versionadded:: 4.2.1
[ "Write", "raw", "response", "data", "into", "a", "file", "." ]
python
train
getfleety/coralillo
coralillo/hashing.py
https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/hashing.py#L49-L68
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if isinstance(s, bytes): if encoding == 'utf-8': return s else: return s.decode('utf-8', errors).encode(encoding, errors) if strings_only and is_protected_type(s): return s if isinstance(s, memoryview): return bytes(s) if not isinstance(s, str): return str(s).encode(encoding, errors) else: return s.encode(encoding, errors)
[ "def", "force_bytes", "(", "s", ",", "encoding", "=", "'utf-8'", ",", "strings_only", "=", "False", ",", "errors", "=", "'strict'", ")", ":", "# Handle the common case first for performance reasons.", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "if", ...
Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects.
[ "Similar", "to", "smart_bytes", "except", "that", "lazy", "instances", "are", "resolved", "to", "strings", "rather", "than", "kept", "as", "lazy", "objects", ".", "If", "strings_only", "is", "True", "don", "t", "convert", "(", "some", ")", "non", "-", "str...
python
train
mortada/fredapi
fredapi/fred.py
https://github.com/mortada/fredapi/blob/d3ca79efccb9525f2752a0d6da90e793e87c3fd8/fredapi/fred.py#L250-L272
def get_series_vintage_dates(self, series_id): """ Get a list of vintage dates for a series. Vintage dates are the dates in history when a series' data values were revised or new data values were released. Parameters ---------- series_id : str Fred series id such as 'CPIAUCSL' Returns ------- dates : list list of vintage dates """ url = "%s/series/vintagedates?series_id=%s" % (self.root_url, series_id) root = self.__fetch_data(url) if root is None: raise ValueError('No vintage date exists for series id: ' + series_id) dates = [] for child in root.getchildren(): dates.append(self._parse(child.text)) return dates
[ "def", "get_series_vintage_dates", "(", "self", ",", "series_id", ")", ":", "url", "=", "\"%s/series/vintagedates?series_id=%s\"", "%", "(", "self", ".", "root_url", ",", "series_id", ")", "root", "=", "self", ".", "__fetch_data", "(", "url", ")", "if", "root"...
Get a list of vintage dates for a series. Vintage dates are the dates in history when a series' data values were revised or new data values were released. Parameters ---------- series_id : str Fred series id such as 'CPIAUCSL' Returns ------- dates : list list of vintage dates
[ "Get", "a", "list", "of", "vintage", "dates", "for", "a", "series", ".", "Vintage", "dates", "are", "the", "dates", "in", "history", "when", "a", "series", "data", "values", "were", "revised", "or", "new", "data", "values", "were", "released", "." ]
python
train
zhanglab/psamm
psamm/lpsolver/glpk.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/lpsolver/glpk.py#L407-L414
def status(self): """Return string indicating the error encountered on failure.""" self._check_valid() if self._ret_val == swiglpk.GLP_ENOPFS: return 'No primal feasible solution' elif self._ret_val == swiglpk.GLP_ENODFS: return 'No dual feasible solution' return str(swiglpk.glp_get_status(self._problem._p))
[ "def", "status", "(", "self", ")", ":", "self", ".", "_check_valid", "(", ")", "if", "self", ".", "_ret_val", "==", "swiglpk", ".", "GLP_ENOPFS", ":", "return", "'No primal feasible solution'", "elif", "self", ".", "_ret_val", "==", "swiglpk", ".", "GLP_ENOD...
Return string indicating the error encountered on failure.
[ "Return", "string", "indicating", "the", "error", "encountered", "on", "failure", "." ]
python
train
apache/airflow
airflow/contrib/sensors/aws_glue_catalog_partition_sensor.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/sensors/aws_glue_catalog_partition_sensor.py#L83-L93
def get_hook(self): """ Gets the AwsGlueCatalogHook """ if not hasattr(self, 'hook'): from airflow.contrib.hooks.aws_glue_catalog_hook import AwsGlueCatalogHook self.hook = AwsGlueCatalogHook( aws_conn_id=self.aws_conn_id, region_name=self.region_name) return self.hook
[ "def", "get_hook", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'hook'", ")", ":", "from", "airflow", ".", "contrib", ".", "hooks", ".", "aws_glue_catalog_hook", "import", "AwsGlueCatalogHook", "self", ".", "hook", "=", "AwsGlueCatalogHo...
Gets the AwsGlueCatalogHook
[ "Gets", "the", "AwsGlueCatalogHook" ]
python
test
lincolnloop/django-dynamic-raw-id
dynamic_raw_id/filters.py
https://github.com/lincolnloop/django-dynamic-raw-id/blob/4bf234f4a9d99daf44141205c0948222442f4957/dynamic_raw_id/filters.py#L57-L65
def queryset(self, request, queryset): """Filter queryset using params from the form.""" if self.form.is_valid(): # get no null params filter_params = dict( filter(lambda x: bool(x[1]), self.form.cleaned_data.items()) ) return queryset.filter(**filter_params) return queryset
[ "def", "queryset", "(", "self", ",", "request", ",", "queryset", ")", ":", "if", "self", ".", "form", ".", "is_valid", "(", ")", ":", "# get no null params", "filter_params", "=", "dict", "(", "filter", "(", "lambda", "x", ":", "bool", "(", "x", "[", ...
Filter queryset using params from the form.
[ "Filter", "queryset", "using", "params", "from", "the", "form", "." ]
python
train
quantopian/zipline
zipline/pipeline/graph.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/graph.py#L110-L119
def execution_order(self, refcounts): """ Return a topologically-sorted iterator over the terms in ``self`` which need to be computed. """ return iter(nx.topological_sort( self.graph.subgraph( {term for term, refcount in refcounts.items() if refcount > 0}, ), ))
[ "def", "execution_order", "(", "self", ",", "refcounts", ")", ":", "return", "iter", "(", "nx", ".", "topological_sort", "(", "self", ".", "graph", ".", "subgraph", "(", "{", "term", "for", "term", ",", "refcount", "in", "refcounts", ".", "items", "(", ...
Return a topologically-sorted iterator over the terms in ``self`` which need to be computed.
[ "Return", "a", "topologically", "-", "sorted", "iterator", "over", "the", "terms", "in", "self", "which", "need", "to", "be", "computed", "." ]
python
train
pywbem/pywbem
attic/cimxml_parse.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/attic/cimxml_parse.py#L85-L88
def _is_end(event, node, tagName): # pylint: disable=invalid-name """Return true if (event, node) is an end event for tagname.""" return event == pulldom.END_ELEMENT and node.tagName == tagName
[ "def", "_is_end", "(", "event", ",", "node", ",", "tagName", ")", ":", "# pylint: disable=invalid-name", "return", "event", "==", "pulldom", ".", "END_ELEMENT", "and", "node", ".", "tagName", "==", "tagName" ]
Return true if (event, node) is an end event for tagname.
[ "Return", "true", "if", "(", "event", "node", ")", "is", "an", "end", "event", "for", "tagname", "." ]
python
train
aboSamoor/polyglot
polyglot/downloader.py
https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/downloader.py#L982-L992
def supported_tasks(self, lang=None): """Languages that are covered by a specific task. Args: lang (string): Language code name. """ if lang: collection = self.get_collection(lang=lang) return [x.id.split('.')[0] for x in collection.packages] else: return [x.name.split()[0] for x in self.collections() if Downloader.TASK_PREFIX in x.id]
[ "def", "supported_tasks", "(", "self", ",", "lang", "=", "None", ")", ":", "if", "lang", ":", "collection", "=", "self", ".", "get_collection", "(", "lang", "=", "lang", ")", "return", "[", "x", ".", "id", ".", "split", "(", "'.'", ")", "[", "0", ...
Languages that are covered by a specific task. Args: lang (string): Language code name.
[ "Languages", "that", "are", "covered", "by", "a", "specific", "task", "." ]
python
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/__init__.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L1300-L1366
def find_keywords(string, parser, top=10, frequency={}, **kwargs): """ Returns a sorted list of keywords in the given string. The given parser (e.g., pattern.en.parser) is used to identify noun phrases. The given frequency dictionary can be a reference corpus, with relative document frequency (df, 0.0-1.0) for each lemma, e.g., {"the": 0.8, "cat": 0.1, ...} """ lemmata = kwargs.pop("lemmata", kwargs.pop("stem", True)) # Parse the string and extract noun phrases (NP). chunks = [] wordcount = 0 for sentence in parser.parse(string, chunks=True, lemmata=lemmata).split(): for w in sentence: # ["cats", "NNS", "I-NP", "O", "cat"] if w[2] == "B-NP": chunks.append([w]) wordcount += 1 elif w[2] == "I-NP" and w[1][:3] == chunks[-1][-1][1][:3] == "NNP": chunks[-1][-1][+0] += " " + w[+0] # Collapse NNPs: "Ms Kitty". chunks[-1][-1][-1] += " " + w[-1] elif w[2] == "I-NP": chunks[-1].append(w) wordcount += 1 # Rate the nouns in noun phrases. m = {} for i, chunk in enumerate(chunks): head = True if parser.language not in ("ca", "es", "pt", "fr", "it", "pt", "ro"): # Head of "cat hair" => "hair". # Head of "poils de chat" => "poils". chunk = list(reversed(chunk)) for w in chunk: if w[1].startswith("NN"): if lemmata: k = w[-1] else: k = w[0].lower() if not k in m: m[k] = [0.0, set(), 1.0, 1.0, 1.0] # Higher score for chunks that appear more frequently. m[k][0] += 1 / float(wordcount) # Higher score for chunks that appear in more contexts (semantic centrality). m[k][1].add(" ".join(map(lambda x: x[0], chunk)).lower()) # Higher score for chunks at the start (25%) of the text. m[k][2] += 1 if float(i) / len(chunks) <= 0.25 else 0 # Higher score for chunks not in a prepositional phrase. m[k][3] += 1 if w[3] == "O" else 0 # Higher score for chunk head. m[k][4] += 1 if head else 0 head = False # Rate tf-idf if a frequency dict is given. for k in m: if frequency: df = frequency.get(k, 0.0) df = max(df, 1e-10) df = log(1.0 / df, 2.71828) else: df = 1.0 m[k][0] = max(1e-10, m[k][0] * df) m[k][1] = 1 + float(len(m[k][1])) # Sort candidates alphabetically by total score # The harmonic mean will emphasize tf-idf score. hmean = lambda a: len(a) / sum(1.0 / x for x in a) m = [(hmean(m[k]), k) for k in m] m = sorted(m, key=lambda x: x[1]) m = sorted(m, key=lambda x: x[0], reverse=True) m = [k for score, k in m] return m[:top]
[ "def", "find_keywords", "(", "string", ",", "parser", ",", "top", "=", "10", ",", "frequency", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "lemmata", "=", "kwargs", ".", "pop", "(", "\"lemmata\"", ",", "kwargs", ".", "pop", "(", "\"stem\"", "...
Returns a sorted list of keywords in the given string. The given parser (e.g., pattern.en.parser) is used to identify noun phrases. The given frequency dictionary can be a reference corpus, with relative document frequency (df, 0.0-1.0) for each lemma, e.g., {"the": 0.8, "cat": 0.1, ...}
[ "Returns", "a", "sorted", "list", "of", "keywords", "in", "the", "given", "string", ".", "The", "given", "parser", "(", "e", ".", "g", ".", "pattern", ".", "en", ".", "parser", ")", "is", "used", "to", "identify", "noun", "phrases", ".", "The", "give...
python
train
llazzaro/analyzerstrategies
analyzerstrategies/zscoreMomentumPortfolioStrategy.py
https://github.com/llazzaro/analyzerstrategies/blob/3c647802f582bf2f06c6793f282bee0d26514cd6/analyzerstrategies/zscoreMomentumPortfolioStrategy.py#L85-L99
def __placeBuyOrder(self, tick): ''' place buy order''' cash=self.__getCashToBuyStock() if cash == 0: return share=math.floor(cash / float(tick.close)) order=Order(accountId=self.__strategy.accountId, action=Action.BUY, is_market=True, symbol=self.__symbol, share=share) if self.__strategy.placeOrder(order): self.__position=share self.__buyPrice=tick.close
[ "def", "__placeBuyOrder", "(", "self", ",", "tick", ")", ":", "cash", "=", "self", ".", "__getCashToBuyStock", "(", ")", "if", "cash", "==", "0", ":", "return", "share", "=", "math", ".", "floor", "(", "cash", "/", "float", "(", "tick", ".", "close",...
place buy order
[ "place", "buy", "order" ]
python
train
HazyResearch/fonduer
src/fonduer/candidates/candidates.py
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/candidates.py#L131-L140
def clear_all(self, split): """Delete ALL Candidates from given split the database. :param split: Which split to clear. :type split: int """ logger.info("Clearing ALL Candidates.") self.session.query(Candidate).filter(Candidate.split == split).delete( synchronize_session="fetch" )
[ "def", "clear_all", "(", "self", ",", "split", ")", ":", "logger", ".", "info", "(", "\"Clearing ALL Candidates.\"", ")", "self", ".", "session", ".", "query", "(", "Candidate", ")", ".", "filter", "(", "Candidate", ".", "split", "==", "split", ")", ".",...
Delete ALL Candidates from given split the database. :param split: Which split to clear. :type split: int
[ "Delete", "ALL", "Candidates", "from", "given", "split", "the", "database", "." ]
python
train
softlayer/softlayer-python
SoftLayer/CLI/virt/power.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/power.py#L88-L99
def pause(env, identifier): """Pauses an active virtual server.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.confirm('This will pause the VS with id %s. Continue?' % vs_id)): raise exceptions.CLIAbort('Aborted.') env.client['Virtual_Guest'].pause(id=vs_id)
[ "def", "pause", "(", "env", ",", "identifier", ")", ":", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "if", ...
Pauses an active virtual server.
[ "Pauses", "an", "active", "virtual", "server", "." ]
python
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/cssParser.py
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L987-L1012
def _parseSelectorPseudo(self, src, selector): """pseudo : ':' [ IDENT | function ] ; """ ctxsrc = src if not src.startswith(':'): raise self.ParseError('Selector Pseudo \':\' not found', src, ctxsrc) src = re.search('^:{1,2}(.*)', src, re.M | re.S).group(1) name, src = self._getIdent(src) if not name: raise self.ParseError('Selector Pseudo identifier not found', src, ctxsrc) if src.startswith('('): # function src = src[1:].lstrip() src, term = self._parseExpression(src, True) if not src.startswith(')'): raise self.ParseError('Selector Pseudo Function closing \')\' not found', src, ctxsrc) src = src[1:] selector.addPseudoFunction(name, term) else: selector.addPseudo(name) return src, selector
[ "def", "_parseSelectorPseudo", "(", "self", ",", "src", ",", "selector", ")", ":", "ctxsrc", "=", "src", "if", "not", "src", ".", "startswith", "(", "':'", ")", ":", "raise", "self", ".", "ParseError", "(", "'Selector Pseudo \\':\\' not found'", ",", "src", ...
pseudo : ':' [ IDENT | function ] ;
[ "pseudo", ":", ":", "[", "IDENT", "|", "function", "]", ";" ]
python
train
tgbugs/pyontutils
nifstd/nifstd_tools/ilx_utils.py
https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/nifstd/nifstd_tools/ilx_utils.py#L154-L165
def decodeIlxResp(resp): """ We need this until we can get json back directly and this is SUPER nasty""" lines = [_ for _ in resp.text.split('\n') if _] # strip empties if 'successfull' in lines[0]: return [(_.split('"')[1], ilxIdFix(_.split(': ')[-1])) for _ in lines[1:]] elif 'errors' in lines[0]: return [(_.split('"')[1], ilxIdFix(_.split('(')[1].split(')')[0])) for _ in lines[1:]]
[ "def", "decodeIlxResp", "(", "resp", ")", ":", "lines", "=", "[", "_", "for", "_", "in", "resp", ".", "text", ".", "split", "(", "'\\n'", ")", "if", "_", "]", "# strip empties", "if", "'successfull'", "in", "lines", "[", "0", "]", ":", "return", "[...
We need this until we can get json back directly and this is SUPER nasty
[ "We", "need", "this", "until", "we", "can", "get", "json", "back", "directly", "and", "this", "is", "SUPER", "nasty" ]
python
train
KE-works/pykechain
pykechain/models/part.py
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/part.py#L505-L556
def update(self, name=None, update_dict=None, bulk=True, **kwargs): """ Edit part name and property values in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the frontend won't notice any changes unless the page is refreshed. :param name: new part name (defined as a string) :type name: basestring or None :param update_dict: dictionary with keys being property names (str) or property ids (uuid) and values being property values :type update_dict: dict :param bulk: True to use the bulk_update_properties API endpoint for KE-chain versions later then 2.1.0b :type bulk: boolean or None :param kwargs: (optional) additional keyword arguments that will be passed inside the update request :type kwargs: dict or None :return: the updated :class:`Part` :raises NotFoundError: when the property name is not a valid property of this part :raises IllegalArgumentError: when the type or value of an argument provided is incorrect :raises APIError: in case an Error occurs Example ------- >>> bike = client.scope('Bike Project').part('Bike') >>> bike.update(name='Good name', update_dict={'Gears': 11, 'Total Height': 56.3}, bulk=True) """ # dict(name=name, properties=json.dumps(update_dict))) with property ids:value action = 'bulk_update_properties' request_body = dict() for prop_name_or_id, property_value in update_dict.items(): if is_uuid(prop_name_or_id): request_body[prop_name_or_id] = property_value else: request_body[self.property(prop_name_or_id).id] = property_value if bulk and len(update_dict.keys()) > 1: if name: if not isinstance(name, str): raise IllegalArgumentError("Name of the part should be provided as a string") r = self._client._request('PUT', self._client._build_url('part', part_id=self.id), data=dict(name=name, properties=json.dumps(request_body), **kwargs), params=dict(select_action=action)) if r.status_code != requests.codes.ok: # pragma: no cover raise APIError('{}: {}'.format(str(r), r.content)) else: for property_name, property_value in update_dict.items(): self.property(property_name).value = property_value
[ "def", "update", "(", "self", ",", "name", "=", "None", ",", "update_dict", "=", "None", ",", "bulk", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# dict(name=name, properties=json.dumps(update_dict))) with property ids:value", "action", "=", "'bulk_update_prope...
Edit part name and property values in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the frontend won't notice any changes unless the page is refreshed. :param name: new part name (defined as a string) :type name: basestring or None :param update_dict: dictionary with keys being property names (str) or property ids (uuid) and values being property values :type update_dict: dict :param bulk: True to use the bulk_update_properties API endpoint for KE-chain versions later then 2.1.0b :type bulk: boolean or None :param kwargs: (optional) additional keyword arguments that will be passed inside the update request :type kwargs: dict or None :return: the updated :class:`Part` :raises NotFoundError: when the property name is not a valid property of this part :raises IllegalArgumentError: when the type or value of an argument provided is incorrect :raises APIError: in case an Error occurs Example ------- >>> bike = client.scope('Bike Project').part('Bike') >>> bike.update(name='Good name', update_dict={'Gears': 11, 'Total Height': 56.3}, bulk=True)
[ "Edit", "part", "name", "and", "property", "values", "in", "one", "go", "." ]
python
train
agoragames/leaderboard-python
leaderboard/leaderboard.py
https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L884-L918
def members_from_rank_range_in( self, leaderboard_name, starting_rank, ending_rank, **options): ''' Retrieve members from the named leaderboard within a given rank range. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given rank range. ''' starting_rank -= 1 if starting_rank < 0: starting_rank = 0 ending_rank -= 1 if ending_rank > self.total_members_in(leaderboard_name): ending_rank = self.total_members_in(leaderboard_name) - 1 raw_leader_data = [] if self.order == self.DESC: raw_leader_data = self.redis_connection.zrevrange( leaderboard_name, starting_rank, ending_rank, withscores=False) else: raw_leader_data = self.redis_connection.zrange( leaderboard_name, starting_rank, ending_rank, withscores=False) return self._parse_raw_members( leaderboard_name, raw_leader_data, **options)
[ "def", "members_from_rank_range_in", "(", "self", ",", "leaderboard_name", ",", "starting_rank", ",", "ending_rank", ",", "*", "*", "options", ")", ":", "starting_rank", "-=", "1", "if", "starting_rank", "<", "0", ":", "starting_rank", "=", "0", "ending_rank", ...
Retrieve members from the named leaderboard within a given rank range. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return members from the leaderboard that fall within the given rank range.
[ "Retrieve", "members", "from", "the", "named", "leaderboard", "within", "a", "given", "rank", "range", "." ]
python
train
lordmauve/lepton
examples/games/bonk/game.py
https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/game.py#L53-L56
def bind_objects(self, *objects): """Bind one or more objects""" self.control.bind_keys(objects) self.objects += objects
[ "def", "bind_objects", "(", "self", ",", "*", "objects", ")", ":", "self", ".", "control", ".", "bind_keys", "(", "objects", ")", "self", ".", "objects", "+=", "objects" ]
Bind one or more objects
[ "Bind", "one", "or", "more", "objects" ]
python
train
alixnovosi/botskeleton
botskeleton/outputs/output_birdsite.py
https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L95-L144
def send_with_media( self, *, text: str, files: List[str], captions: List[str]=[] ) -> List[OutputRecord]: """ Upload media to birdsite, and send status and media, and captions if present. :param text: tweet text. :param files: list of files to upload with post. :param captions: list of captions to include as alt-text with files. :returns: list of output records, each corresponding to either a single post, or an error. """ # upload media media_ids = None try: self.ldebug(f"Uploading files {files}.") media_ids = [self.api.media_upload(file).media_id_string for file in files] except tweepy.TweepError as e: return [self.handle_error( message=f"Bot {self.bot_name} encountered an error when uploading {files}:\n{e}\n", error=e)] # apply captions, if present self._handle_caption_upload(media_ids=media_ids, captions=captions) # send status try: status = self.api.update_status(status=text, media_ids=media_ids) self.ldebug(f"Status object from tweet: {status}.") return [TweetRecord(record_data={ "tweet_id": status._json["id"], "text": text, "media_ids": media_ids, "captions": captions, "files": files })] except tweepy.TweepError as e: return [self.handle_error( message=(f"Bot {self.bot_name} encountered an error when " f"sending post {text} with media ids {media_ids}:\n{e}\n"), error=e)]
[ "def", "send_with_media", "(", "self", ",", "*", ",", "text", ":", "str", ",", "files", ":", "List", "[", "str", "]", ",", "captions", ":", "List", "[", "str", "]", "=", "[", "]", ")", "->", "List", "[", "OutputRecord", "]", ":", "# upload media", ...
Upload media to birdsite, and send status and media, and captions if present. :param text: tweet text. :param files: list of files to upload with post. :param captions: list of captions to include as alt-text with files. :returns: list of output records, each corresponding to either a single post, or an error.
[ "Upload", "media", "to", "birdsite", "and", "send", "status", "and", "media", "and", "captions", "if", "present", "." ]
python
train
googleapis/google-auth-library-python
google/auth/jwt.py
https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/jwt.py#L730-L748
def before_request(self, request, method, url, headers): """Performs credential-specific before request logic. Args: request (Any): Unused. JWT credentials do not need to make an HTTP request to refresh. method (str): The request's HTTP method. url (str): The request's URI. This is used as the audience claim when generating the JWT. headers (Mapping): The request's headers. """ # pylint: disable=unused-argument # (pylint doesn't correctly recognize overridden methods.) parts = urllib.parse.urlsplit(url) # Strip query string and fragment audience = urllib.parse.urlunsplit( (parts.scheme, parts.netloc, parts.path, "", "")) token = self._get_jwt_for_audience(audience) self.apply(headers, token=token)
[ "def", "before_request", "(", "self", ",", "request", ",", "method", ",", "url", ",", "headers", ")", ":", "# pylint: disable=unused-argument", "# (pylint doesn't correctly recognize overridden methods.)", "parts", "=", "urllib", ".", "parse", ".", "urlsplit", "(", "u...
Performs credential-specific before request logic. Args: request (Any): Unused. JWT credentials do not need to make an HTTP request to refresh. method (str): The request's HTTP method. url (str): The request's URI. This is used as the audience claim when generating the JWT. headers (Mapping): The request's headers.
[ "Performs", "credential", "-", "specific", "before", "request", "logic", "." ]
python
train
HdrHistogram/HdrHistogram_py
hdrh/histogram.py
https://github.com/HdrHistogram/HdrHistogram_py/blob/cb99981b0564a62e1aa02bd764efa6445923f8f7/hdrh/histogram.py#L287-L326
def get_percentile_to_value_dict(self, percentile_list): '''A faster alternative to query values for a list of percentiles. Args: percentile_list: a list of percentiles in any order, dups will be ignored each element in the list must be a float value in [0.0 .. 100.0] Returns: a dict of percentile values indexed by the percentile ''' result = {} total = 0 percentile_list_index = 0 count_at_percentile = 0 # remove dups and sort percentile_list = list(set(percentile_list)) percentile_list.sort() for index in range(self.counts_len): total += self.get_count_at_index(index) while True: # recalculate target based on next requested percentile if not count_at_percentile: if percentile_list_index == len(percentile_list): return result percentile = percentile_list[percentile_list_index] percentile_list_index += 1 if percentile > 100: return result count_at_percentile = self.get_target_count_at_percentile(percentile) if total >= count_at_percentile: value_at_index = self.get_value_from_index(index) if percentile: result[percentile] = self.get_highest_equivalent_value(value_at_index) else: result[percentile] = self.get_lowest_equivalent_value(value_at_index) count_at_percentile = 0 else: break return result
[ "def", "get_percentile_to_value_dict", "(", "self", ",", "percentile_list", ")", ":", "result", "=", "{", "}", "total", "=", "0", "percentile_list_index", "=", "0", "count_at_percentile", "=", "0", "# remove dups and sort", "percentile_list", "=", "list", "(", "se...
A faster alternative to query values for a list of percentiles. Args: percentile_list: a list of percentiles in any order, dups will be ignored each element in the list must be a float value in [0.0 .. 100.0] Returns: a dict of percentile values indexed by the percentile
[ "A", "faster", "alternative", "to", "query", "values", "for", "a", "list", "of", "percentiles", "." ]
python
train
crypto101/arthur
arthur/auth.py
https://github.com/crypto101/arthur/blob/c32e693fb5af17eac010e3b20f7653ed6e11eb6a/arthur/auth.py#L52-L66
def _getContextFactory(path, workbench): """Get a context factory. If the client already has a credentials at path, use them. Otherwise, generate them at path. Notifications are reported to the given workbench. """ try: return succeed(getContextFactory(path)) except IOError: d = prompt(workbench, u"E-mail entry", u"Enter e-mail:") d.addCallback(_makeCredentials, path, workbench) d.addCallback(lambda _result: getContextFactory(path)) return d
[ "def", "_getContextFactory", "(", "path", ",", "workbench", ")", ":", "try", ":", "return", "succeed", "(", "getContextFactory", "(", "path", ")", ")", "except", "IOError", ":", "d", "=", "prompt", "(", "workbench", ",", "u\"E-mail entry\"", ",", "u\"Enter e...
Get a context factory. If the client already has a credentials at path, use them. Otherwise, generate them at path. Notifications are reported to the given workbench.
[ "Get", "a", "context", "factory", "." ]
python
train
jesford/cluster-lensing
clusterlensing/clusters.py
https://github.com/jesford/cluster-lensing/blob/2815c1bb07d904ca91a80dae3f52090016768072/clusterlensing/clusters.py#L502-L562
def calc_nfw(self, rbins, offsets=None, numTh=200, numRoff=200, numRinner=20, factorRouter=3): """Calculates Sigma and DeltaSigma profiles. Generates the surface mass density (sigma_nfw attribute of parent object) and differential surface mass density (deltasigma_nfw attribute of parent object) profiles of each cluster, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets. Parameters ---------- rbins : array_like Radial bins (in Mpc) for calculating cluster profiles. Should be 1D, optionally with astropy.units of Mpc. offsets : array_like, optional Parameter describing the width (in Mpc) of the Gaussian distribution of miscentering offsets. Should be 1D, optionally with astropy.units of Mpc. Other Parameters ------------------- numTh : int, optional Parameter to pass to SurfaceMassDensity(). Number of bins to use for integration over theta, for calculating offset profiles (no effect for offsets=None). Default 200. numRoff : int, optional Parameter to pass to SurfaceMassDensity(). Number of bins to use for integration over R_off, for calculating offset profiles (no effect for offsets=None). Default 200. numRinner : int, optional Parameter to pass to SurfaceMassDensity(). Number of bins at r < min(rbins) to use for integration over Sigma(<r), for calculating DeltaSigma (no effect for Sigma ever, and no effect for DeltaSigma if offsets=None). Default 20. factorRouter : int, optional Parameter to pass to SurfaceMassDensity(). Factor increase over number of rbins, at min(r) < r < max(r), of bins that will be used at for integration over Sigma(<r), for calculating DeltaSigma (no effect for Sigma, and no effect for DeltaSigma if offsets=None). Default 3. """ if offsets is None: self._sigoffset = np.zeros(self.number) * units.Mpc else: self._sigoffset = utils.check_units_and_type(offsets, units.Mpc, num=self.number) self.rbins = utils.check_units_and_type(rbins, units.Mpc) rhoc = self._rho_crit.to(units.Msun / units.pc**2 / units.Mpc) smd = SurfaceMassDensity(self.rs, self.delta_c, rhoc, offsets=self._sigoffset, rbins=self.rbins, numTh=numTh, numRoff=numRoff, numRinner=numRinner, factorRouter=factorRouter) self.sigma_nfw = smd.sigma_nfw() self.deltasigma_nfw = smd.deltasigma_nfw()
[ "def", "calc_nfw", "(", "self", ",", "rbins", ",", "offsets", "=", "None", ",", "numTh", "=", "200", ",", "numRoff", "=", "200", ",", "numRinner", "=", "20", ",", "factorRouter", "=", "3", ")", ":", "if", "offsets", "is", "None", ":", "self", ".", ...
Calculates Sigma and DeltaSigma profiles. Generates the surface mass density (sigma_nfw attribute of parent object) and differential surface mass density (deltasigma_nfw attribute of parent object) profiles of each cluster, assuming a spherical NFW model. Optionally includes the effect of cluster miscentering offsets. Parameters ---------- rbins : array_like Radial bins (in Mpc) for calculating cluster profiles. Should be 1D, optionally with astropy.units of Mpc. offsets : array_like, optional Parameter describing the width (in Mpc) of the Gaussian distribution of miscentering offsets. Should be 1D, optionally with astropy.units of Mpc. Other Parameters ------------------- numTh : int, optional Parameter to pass to SurfaceMassDensity(). Number of bins to use for integration over theta, for calculating offset profiles (no effect for offsets=None). Default 200. numRoff : int, optional Parameter to pass to SurfaceMassDensity(). Number of bins to use for integration over R_off, for calculating offset profiles (no effect for offsets=None). Default 200. numRinner : int, optional Parameter to pass to SurfaceMassDensity(). Number of bins at r < min(rbins) to use for integration over Sigma(<r), for calculating DeltaSigma (no effect for Sigma ever, and no effect for DeltaSigma if offsets=None). Default 20. factorRouter : int, optional Parameter to pass to SurfaceMassDensity(). Factor increase over number of rbins, at min(r) < r < max(r), of bins that will be used at for integration over Sigma(<r), for calculating DeltaSigma (no effect for Sigma, and no effect for DeltaSigma if offsets=None). Default 3.
[ "Calculates", "Sigma", "and", "DeltaSigma", "profiles", "." ]
python
train
Cymmetria/honeycomb
honeycomb/servicemanager/base_service.py
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/base_service.py#L212-L226
def on_server_start(self): """Service run loop function. Run the desired docker container with parameters and start parsing the monitored file for alerts. """ self._container = self._docker_client.containers.run(self.docker_image_name, detach=True, **self.docker_params) self.signal_ready() for log_line in self.get_lines(): try: alert_dict = self.parse_line(log_line) if alert_dict: self.add_alert_to_queue(alert_dict) except Exception: self.logger.exception(None)
[ "def", "on_server_start", "(", "self", ")", ":", "self", ".", "_container", "=", "self", ".", "_docker_client", ".", "containers", ".", "run", "(", "self", ".", "docker_image_name", ",", "detach", "=", "True", ",", "*", "*", "self", ".", "docker_params", ...
Service run loop function. Run the desired docker container with parameters and start parsing the monitored file for alerts.
[ "Service", "run", "loop", "function", "." ]
python
train
Hackerfleet/hfos
hfos/logger.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/logger.py#L113-L117
def set_logfile(path, instance): """Specify logfile path""" global logfile logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
[ "def", "set_logfile", "(", "path", ",", "instance", ")", ":", "global", "logfile", "logfile", "=", "os", ".", "path", ".", "normpath", "(", "path", ")", "+", "'/hfos.'", "+", "instance", "+", "'.log'" ]
Specify logfile path
[ "Specify", "logfile", "path" ]
python
train
soravux/scoop
scoop/discovery/minusconf.py
https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/discovery/minusconf.py#L623-L688
def _compat_inet_pton(family, addr): """ socket.inet_pton for platforms that don't have it """ if family == socket.AF_INET: # inet_aton accepts some strange forms, so we use our own res = _compat_bytes('') parts = addr.split('.') if len(parts) != 4: raise ValueError('Expected 4 dot-separated numbers') for part in parts: intval = int(part, 10) if intval < 0 or intval > 0xff: raise ValueError("Invalid integer value in IPv4 address: " + str(intval)) res = res + struct.pack('!B', intval) return res elif family == socket.AF_INET6: wordcount = 8 res = _compat_bytes('') # IPv4 embedded? dotpos = addr.find('.') if dotpos >= 0: v4start = addr.rfind(':', 0, dotpos) if v4start == -1: raise ValueException("Missing colons in an IPv6 address") wordcount = 6 res = socket.inet_aton(addr[v4start+1:]) addr = addr[:v4start] + '!' # We leave a marker that the address is not finished # Compact version? compact_pos = addr.find('::') if compact_pos >= 0: if compact_pos == 0: addr = '0' + addr compact_pos += 1 if compact_pos == len(addr)-len('::'): addr = addr + '0' addr = (addr[:compact_pos] + ':' + ('0:' * (wordcount - (addr.count(':') - '::'.count(':')) - 2)) + addr[compact_pos + len('::'):]) # Remove any dots we left if addr.endswith('!'): addr = addr[:-len('!')] words = addr.split(':') if len(words) != wordcount: raise ValueError('Invalid number of IPv6 hextets, expected ' + str(wordcount) + ', got ' + str(len(words))) for w in reversed(words): # 0x and negative is not valid here, but accepted by int(,16) if 'x' in w or '-' in w: raise ValueError("Invalid character in IPv6 address") intval = int(w, 16) if intval > 0xffff: raise ValueError("IPv6 address componenent too big") res = struct.pack('!H', intval) + res return res else: raise ValueError("Unknown protocol family " + family)
[ "def", "_compat_inet_pton", "(", "family", ",", "addr", ")", ":", "if", "family", "==", "socket", ".", "AF_INET", ":", "# inet_aton accepts some strange forms, so we use our own", "res", "=", "_compat_bytes", "(", "''", ")", "parts", "=", "addr", ".", "split", "...
socket.inet_pton for platforms that don't have it
[ "socket", ".", "inet_pton", "for", "platforms", "that", "don", "t", "have", "it" ]
python
train
Esri/ArcREST
src/arcresthelper/common.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L490-L525
def find_replace(obj, find, replace): """ Searches an object and performs a find and replace. Args: obj (object): The object to iterate and find/replace. find (str): The string to search for. replace (str): The string to replace with. Returns: object: The object with replaced strings. """ try: if isinstance(obj, dict): return {find_replace(key,find,replace): find_replace(value,find,replace) for key, value in obj.items()} elif isinstance(obj, list): return [find_replace(element,find,replace) for element in obj] elif obj == find: return unicode_convert(replace) else: try: return unicode_convert(find_replace_string(obj, find, replace)) #obj = unicode_convert(json.loads(obj)) #return find_replace(obj,find,replace) except: return unicode_convert(obj) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "find_replace", "line": line, "filename": filename, "synerror": synerror, } ) finally: pass
[ "def", "find_replace", "(", "obj", ",", "find", ",", "replace", ")", ":", "try", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "{", "find_replace", "(", "key", ",", "find", ",", "replace", ")", ":", "find_replace", "(", "value...
Searches an object and performs a find and replace. Args: obj (object): The object to iterate and find/replace. find (str): The string to search for. replace (str): The string to replace with. Returns: object: The object with replaced strings.
[ "Searches", "an", "object", "and", "performs", "a", "find", "and", "replace", "." ]
python
train
pyca/pyopenssl
src/OpenSSL/crypto.py
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1310-L1321
def gmtime_adj_notBefore(self, amount): """ Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None`` """ if not isinstance(amount, int): raise TypeError("amount must be an integer") notBefore = _lib.X509_get_notBefore(self._x509) _lib.X509_gmtime_adj(notBefore, amount)
[ "def", "gmtime_adj_notBefore", "(", "self", ",", "amount", ")", ":", "if", "not", "isinstance", "(", "amount", ",", "int", ")", ":", "raise", "TypeError", "(", "\"amount must be an integer\"", ")", "notBefore", "=", "_lib", ".", "X509_get_notBefore", "(", "sel...
Adjust the timestamp on which the certificate starts being valid. :param amount: The number of seconds by which to adjust the timestamp. :return: ``None``
[ "Adjust", "the", "timestamp", "on", "which", "the", "certificate", "starts", "being", "valid", "." ]
python
test
bububa/pyTOP
pyTOP/logistics.py
https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/logistics.py#L384-L396
def send(self, tid, out_sid, company_code, session, sender_id=None, cancel_id=None, feature=None): '''taobao.logistics.offline.send 自己联系物流(线下物流)发货 用户调用该接口可实现自己联系发货(线下物流),使用该接口发货,交易订单状态会直接变成卖家已发货。不支持货到付款、在线下单类型的订单。''' request = TOPRequest('taobao.logistics.offline.send') request['tid'] = tid request['out_sid'] = out_sid request['company_code'] = company_code if feature!=None: request['feature'] = feature if sender_id!=None: request['sender_id'] = sender_id if cancel_id!=None: request['cancel_id'] = cancel_id self.create(self.execute(request, session)) return self.shipping
[ "def", "send", "(", "self", ",", "tid", ",", "out_sid", ",", "company_code", ",", "session", ",", "sender_id", "=", "None", ",", "cancel_id", "=", "None", ",", "feature", "=", "None", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.logistics.offline....
taobao.logistics.offline.send 自己联系物流(线下物流)发货 用户调用该接口可实现自己联系发货(线下物流),使用该接口发货,交易订单状态会直接变成卖家已发货。不支持货到付款、在线下单类型的订单。
[ "taobao", ".", "logistics", ".", "offline", ".", "send", "自己联系物流(线下物流)发货", "用户调用该接口可实现自己联系发货(线下物流),使用该接口发货,交易订单状态会直接变成卖家已发货。不支持货到付款、在线下单类型的订单。" ]
python
train
cedricbonhomme/Stegano
stegano/tools.py
https://github.com/cedricbonhomme/Stegano/blob/502e6303791d348e479290c22108551ba3be254f/stegano/tools.py#L83-L93
def n_at_a_time( items: List[int], n: int, fillvalue: str ) -> Iterator[Tuple[Union[int, str]]]: """Returns an iterator which groups n items at a time. Any final partial tuple will be padded with the fillvalue >>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X')) [(1, 2), (3, 4), (5, 'X')] """ it = iter(items) return itertools.zip_longest(*[it] * n, fillvalue=fillvalue)
[ "def", "n_at_a_time", "(", "items", ":", "List", "[", "int", "]", ",", "n", ":", "int", ",", "fillvalue", ":", "str", ")", "->", "Iterator", "[", "Tuple", "[", "Union", "[", "int", ",", "str", "]", "]", "]", ":", "it", "=", "iter", "(", "items"...
Returns an iterator which groups n items at a time. Any final partial tuple will be padded with the fillvalue >>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X')) [(1, 2), (3, 4), (5, 'X')]
[ "Returns", "an", "iterator", "which", "groups", "n", "items", "at", "a", "time", ".", "Any", "final", "partial", "tuple", "will", "be", "padded", "with", "the", "fillvalue" ]
python
train
dhermes/bezier
src/bezier/_clipping.py
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L122-L179
def _update_parameters(s_min, s_max, start0, end0, start1, end1): """Update clipped parameter range. .. note:: This is a helper for :func:`clip_range`. Does so by intersecting one of the two fat lines with an edge of the convex hull of the distance polynomial of the curve being clipped. If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s` value that is valid for ``s_min`` would also be valid for ``s_max``. Rather than adding a special case to handle this scenario, **only** ``s_min`` will be updated. In cases where a given parameter :math:`s` would be a valid update for both ``s_min`` and ``s_max`` This function **only** updates ``s_min`` Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of one of the two fat lines. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of one of the two fat lines. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. Raises: NotImplementedError: If the two line segments are parallel. (This case will be supported at some point, just not now.) """ s, t, success = _geometric_intersection.segment_intersection( start0, end0, start1, end1 ) if not success: raise NotImplementedError(NO_PARALLEL) if _helpers.in_interval(t, 0.0, 1.0): if _helpers.in_interval(s, 0.0, s_min): return s, s_max elif _helpers.in_interval(s, s_max, 1.0): return s_min, s return s_min, s_max
[ "def", "_update_parameters", "(", "s_min", ",", "s_max", ",", "start0", ",", "end0", ",", "start1", ",", "end1", ")", ":", "s", ",", "t", ",", "success", "=", "_geometric_intersection", ".", "segment_intersection", "(", "start0", ",", "end0", ",", "start1"...
Update clipped parameter range. .. note:: This is a helper for :func:`clip_range`. Does so by intersecting one of the two fat lines with an edge of the convex hull of the distance polynomial of the curve being clipped. If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s` value that is valid for ``s_min`` would also be valid for ``s_max``. Rather than adding a special case to handle this scenario, **only** ``s_min`` will be updated. In cases where a given parameter :math:`s` would be a valid update for both ``s_min`` and ``s_max`` This function **only** updates ``s_min`` Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of one of the two fat lines. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of one of the two fat lines. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. Raises: NotImplementedError: If the two line segments are parallel. (This case will be supported at some point, just not now.)
[ "Update", "clipped", "parameter", "range", "." ]
python
train
tweepy/tweepy
tweepy/api.py
https://github.com/tweepy/tweepy/blob/cc3894073905811c4d9fd816202f93454ed932da/tweepy/api.py#L619-L635
def set_settings(self): """ :reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings :allowed_param:'sleep_time_enabled', 'start_sleep_time', 'end_sleep_time', 'time_zone', 'trend_location_woeid', 'allow_contributor_request', 'lang' """ return bind_api( api=self, path='/account/settings.json', method='POST', payload_type='json', allowed_param=['sleep_time_enabled', 'start_sleep_time', 'end_sleep_time', 'time_zone', 'trend_location_woeid', 'allow_contributor_request', 'lang'], use_cache=False )
[ "def", "set_settings", "(", "self", ")", ":", "return", "bind_api", "(", "api", "=", "self", ",", "path", "=", "'/account/settings.json'", ",", "method", "=", "'POST'", ",", "payload_type", "=", "'json'", ",", "allowed_param", "=", "[", "'sleep_time_enabled'",...
:reference: https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-settings :allowed_param:'sleep_time_enabled', 'start_sleep_time', 'end_sleep_time', 'time_zone', 'trend_location_woeid', 'allow_contributor_request', 'lang'
[ ":", "reference", ":", "https", ":", "//", "developer", ".", "twitter", ".", "com", "/", "en", "/", "docs", "/", "accounts", "-", "and", "-", "users", "/", "manage", "-", "account", "-", "settings", "/", "api", "-", "reference", "/", "post", "-", "...
python
train
evhub/coconut
coconut/compiler/matching.py
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/matching.py#L177-L181
def insert_def(self, index, def_item): """Inserts a def universally.""" self.defs.insert(index, def_item) for other in self.others: other.insert_def(index, def_item)
[ "def", "insert_def", "(", "self", ",", "index", ",", "def_item", ")", ":", "self", ".", "defs", ".", "insert", "(", "index", ",", "def_item", ")", "for", "other", "in", "self", ".", "others", ":", "other", ".", "insert_def", "(", "index", ",", "def_i...
Inserts a def universally.
[ "Inserts", "a", "def", "universally", "." ]
python
train
feifangit/dj-api-auth
djapiauth/forms.py
https://github.com/feifangit/dj-api-auth/blob/9d833134fc8a6e74bf8d9fe6c98598dd5061ea9b/djapiauth/forms.py#L7-L17
def get_api_key_form(userfilter={}): """ userfileter: when binding api key with user, filter some users if necessary """ class APIKeyForm(ModelForm): class Meta: model = APIKeys exclude = ("apitree",) user = forms.ModelChoiceField(queryset=get_user_model().objects.filter(**userfilter), required=True,) return APIKeyForm
[ "def", "get_api_key_form", "(", "userfilter", "=", "{", "}", ")", ":", "class", "APIKeyForm", "(", "ModelForm", ")", ":", "class", "Meta", ":", "model", "=", "APIKeys", "exclude", "=", "(", "\"apitree\"", ",", ")", "user", "=", "forms", ".", "ModelChoice...
userfileter: when binding api key with user, filter some users if necessary
[ "userfileter", ":", "when", "binding", "api", "key", "with", "user", "filter", "some", "users", "if", "necessary" ]
python
test
jab/bidict
bidict/_mut.py
https://github.com/jab/bidict/blob/1a1ba9758651aed9c4f58384eff006d2e2ad6835/bidict/_mut.py#L162-L171
def putall(self, items, on_dup_key=RAISE, on_dup_val=RAISE, on_dup_kv=None): """ Like a bulk :meth:`put`. If one of the given items causes an exception to be raised, none of the items is inserted. """ if items: on_dup = self._get_on_dup((on_dup_key, on_dup_val, on_dup_kv)) self._update(False, on_dup, items)
[ "def", "putall", "(", "self", ",", "items", ",", "on_dup_key", "=", "RAISE", ",", "on_dup_val", "=", "RAISE", ",", "on_dup_kv", "=", "None", ")", ":", "if", "items", ":", "on_dup", "=", "self", ".", "_get_on_dup", "(", "(", "on_dup_key", ",", "on_dup_v...
Like a bulk :meth:`put`. If one of the given items causes an exception to be raised, none of the items is inserted.
[ "Like", "a", "bulk", ":", "meth", ":", "put", "." ]
python
test
carlthome/python-audio-effects
pysndfx/dsp.py
https://github.com/carlthome/python-audio-effects/blob/b2d85c166720c549c6ef3c382b561edd09229722/pysndfx/dsp.py#L226-L235
def bend(self, bends, frame_rate=None, over_sample=None): """TODO Add docstring.""" self.command.append("bend") if frame_rate is not None and isinstance(frame_rate, int): self.command.append('-f %s' % frame_rate) if over_sample is not None and isinstance(over_sample, int): self.command.append('-o %s' % over_sample) for bend in bends: self.command.append(','.join(bend)) return self
[ "def", "bend", "(", "self", ",", "bends", ",", "frame_rate", "=", "None", ",", "over_sample", "=", "None", ")", ":", "self", ".", "command", ".", "append", "(", "\"bend\"", ")", "if", "frame_rate", "is", "not", "None", "and", "isinstance", "(", "frame_...
TODO Add docstring.
[ "TODO", "Add", "docstring", "." ]
python
train
JustinLovinger/optimal
optimal/algorithms/gsa.py
https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/gsa.py#L128-L193
def _new_population_gsa(population, fitnesses, velocities, lower_bounds, upper_bounds, grav_initial, grav_reduction_rate, iteration, max_iterations): """Generate a new population as given by GSA algorithm. In GSA paper, grav_initial is G_i """ # Update the gravitational constant, and the best and worst of the population # Calculate the mass and acceleration for each solution # Update the velocity and position of each solution population_size = len(population) solution_size = len(population[0]) # In GSA paper, grav is G grav = _next_grav_gsa(grav_initial, grav_reduction_rate, iteration, max_iterations) masses = _get_masses(fitnesses) # Create bundled solution with position and mass for the K best calculation # Also store index to later check if two solutions are the same # Sorted by solution fitness (mass) solutions = [{ 'pos': pos, 'mass': mass, 'index': i } for i, (pos, mass) in enumerate(zip(population, masses))] solutions.sort(key=lambda x: x['mass'], reverse=True) # Get the force on each solution # Only the best K solutions apply force # K linearly decreases to 1 num_best = int(population_size - (population_size - 1) * (iteration / float(max_iterations))) forces = [] for i in range(population_size): force_vectors = [] for j in range(num_best): # If it is not the same solution if i != solutions[j]['index']: force_vectors.append( _gsa_force(grav, masses[i], solutions[j]['mass'], population[i], solutions[j]['pos'])) forces.append(_gsa_total_force(force_vectors, solution_size)) # Get the acceleration of each solution accelerations = [] for i in range(population_size): accelerations.append(_gsa_acceleration(forces[i], masses[i])) # Update the velocity of each solution new_velocities = [] for i in range(population_size): new_velocities.append( _gsa_update_velocity(velocities[i], accelerations[i])) # Create the new population new_population = [] for i in range(population_size): new_position = _gsa_update_position(population[i], new_velocities[i]) # Constrain to bounds new_position = list( numpy.clip(new_position, lower_bounds, upper_bounds)) new_population.append(new_position) return new_population, new_velocities
[ "def", "_new_population_gsa", "(", "population", ",", "fitnesses", ",", "velocities", ",", "lower_bounds", ",", "upper_bounds", ",", "grav_initial", ",", "grav_reduction_rate", ",", "iteration", ",", "max_iterations", ")", ":", "# Update the gravitational constant, and th...
Generate a new population as given by GSA algorithm. In GSA paper, grav_initial is G_i
[ "Generate", "a", "new", "population", "as", "given", "by", "GSA", "algorithm", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/interface/ethernet/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/interface/ethernet/__init__.py#L223-L246
def _set_long_distance_isl(self, v, load=False): """ Setter method for long_distance_isl, mapped from YANG variable /interface/ethernet/long_distance_isl (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_long_distance_isl is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_long_distance_isl() directly. YANG Description: Configure the link as long-distance-link """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'2000': {'value': 2000}, u'5000': {'value': 5000}, u'10000': {'value': 10000}, u'30000': {'value': 30000}},), is_leaf=True, yang_name="long-distance-isl", rest_name="long-distance-isl", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure the link as long-distance-link', u'display-when': u'/vcsmode/vcs-mode = "true"'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='enumeration', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """long_distance_isl must be of a type compatible with enumeration""", 'defined-type': "brocade-interface:enumeration", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u'2000': {'value': 2000}, u'5000': {'value': 5000}, u'10000': {'value': 10000}, u'30000': {'value': 30000}},), is_leaf=True, yang_name="long-distance-isl", rest_name="long-distance-isl", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure the link as long-distance-link', u'display-when': u'/vcsmode/vcs-mode = "true"'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='enumeration', is_config=True)""", }) self.__long_distance_isl = t if hasattr(self, '_set'): self._set()
[ "def", "_set_long_distance_isl", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",",...
Setter method for long_distance_isl, mapped from YANG variable /interface/ethernet/long_distance_isl (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_long_distance_isl is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_long_distance_isl() directly. YANG Description: Configure the link as long-distance-link
[ "Setter", "method", "for", "long_distance_isl", "mapped", "from", "YANG", "variable", "/", "interface", "/", "ethernet", "/", "long_distance_isl", "(", "enumeration", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", ...
python
train
utiasSTARS/pykitti
pykitti/utils.py
https://github.com/utiasSTARS/pykitti/blob/d3e1bb81676e831886726cc5ed79ce1f049aef2c/pykitti/utils.py#L61-L65
def transform_from_rot_trans(R, t): """Transforation matrix from rotation matrix and translation vector.""" R = R.reshape(3, 3) t = t.reshape(3, 1) return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))
[ "def", "transform_from_rot_trans", "(", "R", ",", "t", ")", ":", "R", "=", "R", ".", "reshape", "(", "3", ",", "3", ")", "t", "=", "t", ".", "reshape", "(", "3", ",", "1", ")", "return", "np", ".", "vstack", "(", "(", "np", ".", "hstack", "("...
Transforation matrix from rotation matrix and translation vector.
[ "Transforation", "matrix", "from", "rotation", "matrix", "and", "translation", "vector", "." ]
python
train
WebarchivCZ/WA-KAT
src/wa_kat/analyzers/language_detector.py
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/analyzers/language_detector.py#L49-L87
def get_html_tag_lang_params(index_page): """ Parse lang and xml:lang parameters in the ``<html>`` tag. See https://www.w3.org/International/questions/qa-html-language-declarations for details. Args: index_page (str): HTML content of the page you wisht to analyze. Returns: list: List of :class:`.SourceString` objects. """ dom = dhtmlparser.parseString(index_page) html_tag = dom.find("html") if not html_tag: return [] html_tag = html_tag[0] # parse parameters lang = html_tag.params.get("lang") xml_lang = html_tag.params.get("xml:lang") if lang and lang == xml_lang: return [SourceString(lang, source="<html> tag")] out = [] if lang: out.append(SourceString(lang, source="<html lang=..>")) if xml_lang: out.append(SourceString(xml_lang, source="<html xml:lang=..>")) return out
[ "def", "get_html_tag_lang_params", "(", "index_page", ")", ":", "dom", "=", "dhtmlparser", ".", "parseString", "(", "index_page", ")", "html_tag", "=", "dom", ".", "find", "(", "\"html\"", ")", "if", "not", "html_tag", ":", "return", "[", "]", "html_tag", ...
Parse lang and xml:lang parameters in the ``<html>`` tag. See https://www.w3.org/International/questions/qa-html-language-declarations for details. Args: index_page (str): HTML content of the page you wisht to analyze. Returns: list: List of :class:`.SourceString` objects.
[ "Parse", "lang", "and", "xml", ":", "lang", "parameters", "in", "the", "<html", ">", "tag", "." ]
python
train
pip-services3-python/pip-services3-components-python
pip_services3_components/count/CompositeCounters.py
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CompositeCounters.py#L79-L89
def end_timing(self, name, elapsed): """ Ends measurement of execution elapsed time and updates specified counter. :param name: a counter name :param elapsed: execution elapsed time in milliseconds to update the counter. """ for counter in self._counters: if isinstance(counter, ITimingCallback): counter.end_timing(name, elapsed)
[ "def", "end_timing", "(", "self", ",", "name", ",", "elapsed", ")", ":", "for", "counter", "in", "self", ".", "_counters", ":", "if", "isinstance", "(", "counter", ",", "ITimingCallback", ")", ":", "counter", ".", "end_timing", "(", "name", ",", "elapsed...
Ends measurement of execution elapsed time and updates specified counter. :param name: a counter name :param elapsed: execution elapsed time in milliseconds to update the counter.
[ "Ends", "measurement", "of", "execution", "elapsed", "time", "and", "updates", "specified", "counter", "." ]
python
train
saltstack/salt
salt/modules/boto_cloudtrail.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudtrail.py#L298-L342
def update(Name, S3BucketName, S3KeyPrefix=None, SnsTopicName=None, IncludeGlobalServiceEvents=None, IsMultiRegionTrail=None, EnableLogFileValidation=None, CloudWatchLogsLogGroupArn=None, CloudWatchLogsRoleArn=None, KmsKeyId=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid config, update a trail. Returns {created: true} if the trail was created and returns {created: False} if the trail was not created. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.update my_trail my_bucket ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {} for arg in ('S3KeyPrefix', 'SnsTopicName', 'IncludeGlobalServiceEvents', 'IsMultiRegionTrail', 'EnableLogFileValidation', 'CloudWatchLogsLogGroupArn', 'CloudWatchLogsRoleArn', 'KmsKeyId'): if locals()[arg] is not None: kwargs[arg] = locals()[arg] trail = conn.update_trail(Name=Name, S3BucketName=S3BucketName, **kwargs) if trail: log.info('The updated trail name is %s', trail['Name']) return {'updated': True, 'name': trail['Name']} else: log.warning('Trail was not created') return {'updated': False} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "update", "(", "Name", ",", "S3BucketName", ",", "S3KeyPrefix", "=", "None", ",", "SnsTopicName", "=", "None", ",", "IncludeGlobalServiceEvents", "=", "None", ",", "IsMultiRegionTrail", "=", "None", ",", "EnableLogFileValidation", "=", "None", ",", "Cloud...
Given a valid config, update a trail. Returns {created: true} if the trail was created and returns {created: False} if the trail was not created. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.update my_trail my_bucket
[ "Given", "a", "valid", "config", "update", "a", "trail", "." ]
python
train
IdentityPython/pysaml2
example/idp2/idp.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/idp2/idp.py#L273-L313
def verify_request(self, query, binding): """ :param query: The SAML query, transport encoded :param binding: Which binding the query came in over """ resp_args = {} if not query: logger.info("Missing QUERY") resp = Unauthorized("Unknown user") return resp_args, resp(self.environ, self.start_response) if not self.req_info: self.req_info = IDP.parse_authn_request(query, binding) logger.info("parsed OK") _authn_req = self.req_info.message logger.debug("%s", _authn_req) try: self.binding_out, self.destination = IDP.pick_binding( "assertion_consumer_service", bindings=self.response_bindings, entity_id=_authn_req.issuer.text, request=_authn_req, ) except Exception as err: logger.error("Couldn't find receiver endpoint: %s", err) raise logger.debug("Binding: %s, destination: %s", self.binding_out, self.destination) resp_args = {} try: resp_args = IDP.response_args(_authn_req) _resp = None except UnknownPrincipal as excp: _resp = IDP.create_error_response(_authn_req.id, self.destination, excp) except UnsupportedBinding as excp: _resp = IDP.create_error_response(_authn_req.id, self.destination, excp) return resp_args, _resp
[ "def", "verify_request", "(", "self", ",", "query", ",", "binding", ")", ":", "resp_args", "=", "{", "}", "if", "not", "query", ":", "logger", ".", "info", "(", "\"Missing QUERY\"", ")", "resp", "=", "Unauthorized", "(", "\"Unknown user\"", ")", "return", ...
:param query: The SAML query, transport encoded :param binding: Which binding the query came in over
[ ":", "param", "query", ":", "The", "SAML", "query", "transport", "encoded", ":", "param", "binding", ":", "Which", "binding", "the", "query", "came", "in", "over" ]
python
train
Azure/msrest-for-python
msrest/serialization.py
https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/serialization.py#L240-L270
def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer): """Return a dict that can be JSONify using json.dump. Advanced usage might optionaly use a callback as parameter: .. code::python def my_key_transformer(key, attr_desc, value): return key Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains 'type' with the msrest type and 'key' with the RestAPI encoded key. Value is the current value in this object. The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict. See the three examples in this file: - attribute_transformer - full_restapi_key_transformer - last_restapi_key_transformer :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly)
[ "def", "as_dict", "(", "self", ",", "keep_readonly", "=", "True", ",", "key_transformer", "=", "attribute_transformer", ")", ":", "serializer", "=", "Serializer", "(", "self", ".", "_infer_class_models", "(", ")", ")", "return", "serializer", ".", "_serialize", ...
Return a dict that can be JSONify using json.dump. Advanced usage might optionaly use a callback as parameter: .. code::python def my_key_transformer(key, attr_desc, value): return key Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains 'type' with the msrest type and 'key' with the RestAPI encoded key. Value is the current value in this object. The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict. See the three examples in this file: - attribute_transformer - full_restapi_key_transformer - last_restapi_key_transformer :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict
[ "Return", "a", "dict", "that", "can", "be", "JSONify", "using", "json", ".", "dump", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L808-L828
def update_selection_self_prior(self): """Tree view prior update of state machine selection""" if self._do_selection_update: return self._do_selection_update = True tree_selection, selected_model_list, sm_selection, sm_selected_model_set = self.get_selections() if isinstance(sm_selection, Selection): # current sm_selected_model_set will be updated and hand it back self.iter_tree_with_handed_function(self.update_selection_self_prior_condition, sm_selected_model_set, selected_model_list) sm_selection.handle_prepared_selection_of_core_class_elements(self.CORE_ELEMENT_CLASS, sm_selected_model_set) # TODO check if we can solve the difference that occurs e.g. while complex actions?, or same state paths! # -> models in selection for core element not in the tree the function iter tree + condition tolerates this if not set(selected_model_list) == sm_selected_model_set: self._logger.verbose("Difference between tree view selection: \n{0} \nand state machine selection: " "\n{1}".format(set(selected_model_list), sm_selected_model_set)) # TODO check why sometimes not consistent with sm selection. e.g while modification history test if self.check_selection_consistency(sm_check=False): self.update_selection_sm_prior() self._do_selection_update = False
[ "def", "update_selection_self_prior", "(", "self", ")", ":", "if", "self", ".", "_do_selection_update", ":", "return", "self", ".", "_do_selection_update", "=", "True", "tree_selection", ",", "selected_model_list", ",", "sm_selection", ",", "sm_selected_model_set", "=...
Tree view prior update of state machine selection
[ "Tree", "view", "prior", "update", "of", "state", "machine", "selection" ]
python
train
genepattern/genepattern-python
gp/data.py
https://github.com/genepattern/genepattern-python/blob/9478ea65362b91c72a94f7300c3de8d710bebb71/gp/data.py#L263-L270
def _bytes_to_str(lines): """ Convert all lines from byte string to unicode string, if necessary """ if len(lines) >= 1 and hasattr(lines[0], 'decode'): return [line.decode('utf-8') for line in lines] else: return lines
[ "def", "_bytes_to_str", "(", "lines", ")", ":", "if", "len", "(", "lines", ")", ">=", "1", "and", "hasattr", "(", "lines", "[", "0", "]", ",", "'decode'", ")", ":", "return", "[", "line", ".", "decode", "(", "'utf-8'", ")", "for", "line", "in", "...
Convert all lines from byte string to unicode string, if necessary
[ "Convert", "all", "lines", "from", "byte", "string", "to", "unicode", "string", "if", "necessary" ]
python
train
duniter/duniter-python-api
duniterpy/api/endpoint.py
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/endpoint.py#L492-L504
def from_inline(cls: Type[ESSubscribtionEndpointType], inline: str) -> ESSubscribtionEndpointType: """ Return ESSubscribtionEndpoint instance from endpoint string :param inline: Endpoint string :return: """ m = ESSubscribtionEndpoint.re_inline.match(inline) if m is None: raise MalformedDocumentError(ESSubscribtionEndpoint.API) server = m.group(1) port = int(m.group(2)) return cls(server, port)
[ "def", "from_inline", "(", "cls", ":", "Type", "[", "ESSubscribtionEndpointType", "]", ",", "inline", ":", "str", ")", "->", "ESSubscribtionEndpointType", ":", "m", "=", "ESSubscribtionEndpoint", ".", "re_inline", ".", "match", "(", "inline", ")", "if", "m", ...
Return ESSubscribtionEndpoint instance from endpoint string :param inline: Endpoint string :return:
[ "Return", "ESSubscribtionEndpoint", "instance", "from", "endpoint", "string" ]
python
train