text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def ekf1_pos(EKF1): '''calculate EKF position when EKF disabled''' global ekf_home from . import mavutil self = mavutil.mavfile_global if ekf_home is None: if not 'GPS' in self.messages or self.messages['GPS'].Status != 3: return None ekf_home = self.messages['GPS'] (ekf_home.Lat, ...
[ "def", "ekf1_pos", "(", "EKF1", ")", ":", "global", "ekf_home", "from", ".", "import", "mavutil", "self", "=", "mavutil", ".", "mavfile_global", "if", "ekf_home", "is", "None", ":", "if", "not", "'GPS'", "in", "self", ".", "messages", "or", "self", ".", ...
39.5
0.030928
def set_bumper_color(self, particle, group, bumper, collision_point, collision_normal): """Set bumper color to the color of the particle that collided with it""" self.color = tuple(particle.color)[:3]
[ "def", "set_bumper_color", "(", "self", ",", "particle", ",", "group", ",", "bumper", ",", "collision_point", ",", "collision_normal", ")", ":", "self", ".", "color", "=", "tuple", "(", "particle", ".", "color", ")", "[", ":", "3", "]" ]
67.333333
0.02451
def _generateFind(self, **kwargs): """Generator which yields matches on AXChildren.""" for needle in self._generateChildren(): if needle._match(**kwargs): yield needle
[ "def", "_generateFind", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "needle", "in", "self", ".", "_generateChildren", "(", ")", ":", "if", "needle", ".", "_match", "(", "*", "*", "kwargs", ")", ":", "yield", "needle" ]
41.4
0.009479
def dependency_information(include_salt_cloud=False): ''' Report versions of library dependencies. ''' libs = [ ('Python', None, sys.version.rsplit('\n')[0].strip()), ('Jinja2', 'jinja2', '__version__'), ('M2Crypto', 'M2Crypto', 'version'), ('msgpack-python', 'msgpack', '...
[ "def", "dependency_information", "(", "include_salt_cloud", "=", "False", ")", ":", "libs", "=", "[", "(", "'Python'", ",", "None", ",", "sys", ".", "version", ".", "rsplit", "(", "'\\n'", ")", "[", "0", "]", ".", "strip", "(", ")", ")", ",", "(", ...
35.980392
0.000531
def update(self, modelID, modelParams, modelParamsHash, metricResult, completed, completionReason, matured, numRecords): """ Insert a new entry or update an existing one. If this is an update of an existing entry, then modelParams will be None Parameters: ----------------------------------...
[ "def", "update", "(", "self", ",", "modelID", ",", "modelParams", ",", "modelParamsHash", ",", "metricResult", ",", "completed", ",", "completionReason", ",", "matured", ",", "numRecords", ")", ":", "# The modelParamsHash must always be provided - it can change after a", ...
40.725714
0.008492
def fitsInfo(fitsname = None): """ Get fits info """ hdu = pyfits.open(fitsname) hdr = hdu[0].header ra = hdr['CRVAL1'] dra = abs(hdr['CDELT1']) raPix = hdr['CRPIX1'] dec = hdr['CRVAL2'] ddec = abs(hdr['CDELT2']) decPix = hdr['CRPIX2'] freq0 = 0 for i in range(1,hdr['...
[ "def", "fitsInfo", "(", "fitsname", "=", "None", ")", ":", "hdu", "=", "pyfits", ".", "open", "(", "fitsname", ")", "hdr", "=", "hdu", "[", "0", "]", ".", "header", "ra", "=", "hdr", "[", "'CRVAL1'", "]", "dra", "=", "abs", "(", "hdr", "[", "'C...
28.6
0.033829
def preprocess_fallback_config(): """Preprocesses the fallback include and library paths depending on the platform.""" global LIBIGRAPH_FALLBACK_INCLUDE_DIRS global LIBIGRAPH_FALLBACK_LIBRARY_DIRS global LIBIGRAPH_FALLBACK_LIBRARIES if os.name == 'nt' and distutils.ccompiler.get_default_com...
[ "def", "preprocess_fallback_config", "(", ")", ":", "global", "LIBIGRAPH_FALLBACK_INCLUDE_DIRS", "global", "LIBIGRAPH_FALLBACK_LIBRARY_DIRS", "global", "LIBIGRAPH_FALLBACK_LIBRARIES", "if", "os", ".", "name", "==", "'nt'", "and", "distutils", ".", "ccompiler", ".", "get_d...
52.352941
0.011031
def ara_config(key, env_var, default, section='ara', value_type=None): """ Wrapper around Ansible's get_config backward/forward compatibility """ # Bootstrap Ansible configuration # Ansible >=2.4 takes care of loading the configuration file itself path = find_ini_config_file() config = confi...
[ "def", "ara_config", "(", "key", ",", "env_var", ",", "default", ",", "section", "=", "'ara'", ",", "value_type", "=", "None", ")", ":", "# Bootstrap Ansible configuration", "# Ansible >=2.4 takes care of loading the configuration file itself", "path", "=", "find_ini_conf...
34.285714
0.002028
def _handle_assets(self, relpath, params): """Statically serve assets: js, css etc.""" if self._settings.assets_dir: abspath = os.path.normpath(os.path.join(self._settings.assets_dir, relpath)) with open(abspath, 'rb') as infile: content = infile.read() else: content = pkgutil.get_...
[ "def", "_handle_assets", "(", "self", ",", "relpath", ",", "params", ")", ":", "if", "self", ".", "_settings", ".", "assets_dir", ":", "abspath", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_settin...
47.2
0.010395
def find(pattern): ''' Find all instances where the pattern is in the running command .. code-block:: bash salt '*' onyx.cmd find '^snmp-server.*$' .. note:: This uses the `re.MULTILINE` regex format for python, and runs the regex against the whole show_run output. ''' ...
[ "def", "find", "(", "pattern", ")", ":", "matcher", "=", "re", ".", "compile", "(", "pattern", ",", "re", ".", "MULTILINE", ")", "return", "matcher", ".", "findall", "(", "show_run", "(", ")", ")" ]
27.857143
0.002481
def harmonize(self, harmonics_dict): """ Returns a "harmonized" table lookup instance by using a "harmonics" dictionary with {partial: amplitude} terms, where all "partial" keys have to be integers. """ data = sum(cycle(self.table[::partial+1]) * amplitude for partial, amplitude i...
[ "def", "harmonize", "(", "self", ",", "harmonics_dict", ")", ":", "data", "=", "sum", "(", "cycle", "(", "self", ".", "table", "[", ":", ":", "partial", "+", "1", "]", ")", "*", "amplitude", "for", "partial", ",", "amplitude", "in", "iteritems", "(",...
45
0.002421
def _merge_tops_same(self, tops): ''' For each saltenv, only consider the top file from that saltenv. All sections matching a given saltenv, which appear in a different saltenv's top file, will be ignored. ''' top = DefaultOrderedDict(OrderedDict) for cenv, ctops ...
[ "def", "_merge_tops_same", "(", "self", ",", "tops", ")", ":", "top", "=", "DefaultOrderedDict", "(", "OrderedDict", ")", "for", "cenv", ",", "ctops", "in", "six", ".", "iteritems", "(", "tops", ")", ":", "if", "all", "(", "[", "x", "==", "{", "}", ...
45.274194
0.001046
def open_vos_or_local(path, mode="rb"): """ Opens a file which can either be in VOSpace or the local filesystem. @param path: @param mode: @return: """ filename = os.path.basename(path) if os.access(filename, os.F_OK): return open(filename, mode) if path.startswith("vos:"): ...
[ "def", "open_vos_or_local", "(", "path", ",", "mode", "=", "\"rb\"", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "os", ".", "access", "(", "filename", ",", "os", ".", "F_OK", ")", ":", "return", "open", "(...
28.24
0.00137
def plot_annual_returns(returns, ax=None, **kwargs): """ Plots a bar graph of returns by year. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. ax : matplotlib.Axes, optional ...
[ "def", "plot_annual_returns", "(", "returns", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "x_axis_formatter", "=", "FuncFormatter", "(", "utils", ".", "percentage", ...
25.770833
0.000779
def load_json(json_list, into=None): """ Determine all types touched by loading the type and deposit them into the particular namespace. """ def l2t(obj): if isinstance(obj, list): return tuple(l2t(L) for L in obj) elif isinstance(obj, dict): return frozendict(obj) ...
[ "def", "load_json", "(", "json_list", ",", "into", "=", "None", ")", ":", "def", "l2t", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "tuple", "(", "l2t", "(", "L", ")", "for", "L", "in", "obj", ")", "el...
30.076923
0.009926
def _infer_binary_broadcast_shape(shape1, shape2, given_output_shape=None): """Infer shape of the output of a binary op with broadcasting. If the output shape is not given with given_output_shape, then we check to see if one of the shapes is a subsequence of the other one, and we return the one that is the sup...
[ "def", "_infer_binary_broadcast_shape", "(", "shape1", ",", "shape2", ",", "given_output_shape", "=", "None", ")", ":", "shape1", "=", "convert_to_shape", "(", "shape1", ")", "shape2", "=", "convert_to_shape", "(", "shape2", ")", "given_output_shape", "=", "conver...
35.807692
0.009414
def display_table(headers, table): """Print a formatted table. :param headers: A list of header objects that are displayed in the first row of the table. :param table: A list of lists where each sublist is a row of the table. The number of elements in each row should be equal to the number ...
[ "def", "display_table", "(", "headers", ",", "table", ")", ":", "assert", "all", "(", "len", "(", "row", ")", "==", "len", "(", "headers", ")", "for", "row", "in", "table", ")", "str_headers", "=", "[", "str", "(", "header", ")", "for", "header", "...
32.46875
0.000935
def pre_process(self, req, params): """ Pre-process the extensions for the action. If any pre-processing extension yields a value which tests as True, extension pre-processing aborts and that value is returned; otherwise, None is returned. Return value is always a tuple, ...
[ "def", "pre_process", "(", "self", ",", "req", ",", "params", ")", ":", "post_list", "=", "[", "]", "# Walk through the list of extensions", "for", "ext", "in", "self", ".", "extensions", ":", "if", "ext", ".", "isgenerator", ":", "gen", "=", "ext", "(", ...
35.787879
0.001649
def get_person_by_prox_rfid(self, prox_rfid): """ Returns a restclients.Person object for the given rfid. If the rfid isn't found, or if there is an error communicating with the IdCard WS, a DataFailureException will be thrown. """ if not self.valid_prox_rfid(prox_rfid):...
[ "def", "get_person_by_prox_rfid", "(", "self", ",", "prox_rfid", ")", ":", "if", "not", "self", ".", "valid_prox_rfid", "(", "prox_rfid", ")", ":", "raise", "InvalidProxRFID", "(", "prox_rfid", ")", "url", "=", "\"{}.json?{}\"", ".", "format", "(", "CARD_PREFI...
38.818182
0.002286
def predict(self, n_periods=10, exogenous=None, return_conf_int=False, alpha=0.05, **kwargs): """Forecast future (transformed) values Generate predictions (forecasts) ``n_periods`` in the future. Note that if ``exogenous`` variables were used in the model fit, they will ...
[ "def", "predict", "(", "self", ",", "n_periods", "=", "10", ",", "exogenous", "=", "None", ",", "return_conf_int", "=", "False", ",", "alpha", "=", "0.05", ",", "*", "*", "kwargs", ")", ":", "check_is_fitted", "(", "self", ",", "\"steps_\"", ")", "# Pu...
45.789474
0.000844
def rs(data, n, unbiased=True): """ Calculates an individual R/S value in the rescaled range approach for a given n. Note: This is just a helper function for hurst_rs and should not be called directly. Args: data (array-like of float): time series n (float): size of the subseries in wh...
[ "def", "rs", "(", "data", ",", "n", ",", "unbiased", "=", "True", ")", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", "total_N", "=", "len", "(", "data", ")", "m", "=", "total_N", "//", "n", "# number of sequences", "# cut values at the end ...
32.188679
0.015927
def window_size(self, value): """Set private ``_window_size`` and reset ``_block_matcher``.""" if (value > 4 and value < self.parameter_maxima["window_size"] and value % 2): self._window_size = value else: raise InvalidWindowSizeError("Window size ...
[ "def", "window_size", "(", "self", ",", "value", ")", ":", "if", "(", "value", ">", "4", "and", "value", "<", "self", ".", "parameter_maxima", "[", "\"window_size\"", "]", "and", "value", "%", "2", ")", ":", "self", ".", "_window_size", "=", "value", ...
46.090909
0.011605
def get_total_degree_day_too_low_warning( model_type, balance_point, degree_day_type, avg_degree_days, period_days, minimum_total, ): """ Return an empty list or a single warning wrapped in a list regarding the total summed degree day values. Parameters ---------- model_type...
[ "def", "get_total_degree_day_too_low_warning", "(", "model_type", ",", "balance_point", ",", "degree_day_type", ",", "avg_degree_days", ",", "period_days", ",", "minimum_total", ",", ")", ":", "warnings", "=", "[", "]", "total_degree_days", "=", "(", "avg_degree_days"...
34.080645
0.00092
def run(ctx, algofile, algotext, define, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, blotter): """Run a ...
[ "def", "run", "(", "ctx", ",", "algofile", ",", "algotext", ",", "define", ",", "data_frequency", ",", "capital_base", ",", "bundle", ",", "bundle_timestamp", ",", "start", ",", "end", ",", "output", ",", "trading_calendar", ",", "print_algo", ",", "metrics_...
28.086957
0.000499
def item_completed(self, results, item, info): ''' 在正常图片本地化处理管道业务执行完毕后,使用缩略图路径替换原 ``result[path]`` 路径, 从而使最终打包时使用缩略图,并根据配置,对缩略图进行灰度处理 :param item: 爬取到的数据模型 :type item: :class:`.MoearPackageMobiItem` or dict ''' # 处理 results 中的 path 使用缩略图路径替代 for ok, resul...
[ "def", "item_completed", "(", "self", ",", "results", ",", "item", ",", "info", ")", ":", "# 处理 results 中的 path 使用缩略图路径替代", "for", "ok", ",", "result", "in", "results", ":", "if", "not", "ok", ":", "continue", "path", "=", "result", "[", "'path'", "]", "...
34.882353
0.001641
def format_ffmpeg_filter(name, params): """ Build a string to call a FFMpeg filter. """ return "%s=%s" % (name, ":".join("%s=%s" % (k, v) for k, v in params.items()))
[ "def", "format_ffmpeg_filter", "(", "name", ",", "params", ")", ":", "return", "\"%s=%s\"", "%", "(", "name", ",", "\":\"", ".", "join", "(", "\"%s=%s\"", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", ...
46.75
0.015789
def get_bindings(self): """ :returns: list of dicts """ path = Client.urls['all_bindings'] bindings = self._call(path, 'GET') return bindings
[ "def", "get_bindings", "(", "self", ")", ":", "path", "=", "Client", ".", "urls", "[", "'all_bindings'", "]", "bindings", "=", "self", ".", "_call", "(", "path", ",", "'GET'", ")", "return", "bindings" ]
22.875
0.010526
def do_set(self, args: argparse.Namespace) -> None: """Set a settable parameter or show current settings of parameters""" # Check if param was passed in if not args.param: return self.show(args) param = utils.norm_fold(args.param.strip()) # Check if value was passed...
[ "def", "do_set", "(", "self", ",", "args", ":", "argparse", ".", "Namespace", ")", "->", "None", ":", "# Check if param was passed in", "if", "not", "args", ".", "param", ":", "return", "self", ".", "show", "(", "args", ")", "param", "=", "utils", ".", ...
36.69697
0.002414
def decorator(self, func): """ Wrapper function to decorate a function """ if inspect.isfunction(func): func._methodview = self elif inspect.ismethod(func): func.__func__._methodview = self else: raise AssertionError('Can only decorate function and met...
[ "def", "decorator", "(", "self", ",", "func", ")", ":", "if", "inspect", ".", "isfunction", "(", "func", ")", ":", "func", ".", "_methodview", "=", "self", "elif", "inspect", ".", "ismethod", "(", "func", ")", ":", "func", ".", "__func__", ".", "_met...
40.111111
0.00813
def select(self, space, key=None, **kwargs) -> _MethodRet: """ Select request coroutine. Examples: .. code-block:: pycon >>> await conn.select('tester') <Response sync=3 rowcount=2 data=[ <TarantoolTuple id=1 name='one'>,...
[ "def", "select", "(", "self", ",", "space", ",", "key", "=", "None", ",", "*", "*", "kwargs", ")", "->", "_MethodRet", ":", "return", "self", ".", "_db", ".", "select", "(", "space", ",", "key", ",", "*", "*", "kwargs", ")" ]
35.136364
0.001259
def verbose(self, msg, *args, **kwargs): """Log msg at 'verbose' level, debug < verbose < info""" self.log(logging.VERBOSE, msg, *args, **kwargs)
[ "def", "verbose", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log", "(", "logging", ".", "VERBOSE", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
53
0.012422
def get_user_group(self, id, **kwargs): # noqa: E501 """Get a specific user group # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_user_group(id, async_req...
[ "def", "get_user_group", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "get_user_grou...
40.52381
0.002296
def register_class_for_json( cls: ClassType, method: str = METHOD_SIMPLE, obj_to_dict_fn: InstanceToDictFnType = None, dict_to_obj_fn: DictToInstanceFnType = initdict_to_instance, default_factory: DefaultFactoryFnType = None) -> None: """ Registers the class cls for JSON ...
[ "def", "register_class_for_json", "(", "cls", ":", "ClassType", ",", "method", ":", "str", "=", "METHOD_SIMPLE", ",", "obj_to_dict_fn", ":", "InstanceToDictFnType", "=", "None", ",", "dict_to_obj_fn", ":", "DictToInstanceFnType", "=", "initdict_to_instance", ",", "d...
37.568627
0.000509
def SVGdocument(): "Create default SVG document" import xml.dom.minidom implementation = xml.dom.minidom.getDOMImplementation() doctype = implementation.createDocumentType( "svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" ) document= implementation.createDocument(None, "sv...
[ "def", "SVGdocument", "(", ")", ":", "import", "xml", ".", "dom", ".", "minidom", "implementation", "=", "xml", ".", "dom", ".", "minidom", ".", "getDOMImplementation", "(", ")", "doctype", "=", "implementation", ".", "createDocumentType", "(", "\"svg\"", ",...
29.928571
0.032407
def from_config(config): """ Creates new Parameters from ConfigMap object. :param config: a ConfigParams that contain parameters. :return: a new Parameters object. """ result = Parameters() if config == None or len(config) == 0: return resul...
[ "def", "from_config", "(", "config", ")", ":", "result", "=", "Parameters", "(", ")", "if", "config", "==", "None", "or", "len", "(", "config", ")", "==", "0", ":", "return", "result", "for", "(", "key", ",", "value", ")", "in", "config", ".", "ite...
24.941176
0.013636
def _CronJobFromRow(self, row): """Creates a cronjob object from a database result row.""" (job, create_time, enabled, forced_run_requested, last_run_status, last_run_time, current_run_id, state, leased_until, leased_by) = row job = rdf_cronjobs.CronJob.FromSerializedString(job) job.current_run_id...
[ "def", "_CronJobFromRow", "(", "self", ",", "row", ")", ":", "(", "job", ",", "create_time", ",", "enabled", ",", "forced_run_requested", ",", "last_run_status", ",", "last_run_time", ",", "current_run_id", ",", "state", ",", "leased_until", ",", "leased_by", ...
48.117647
0.002398
def iglob(pathname, patterns): """ Allow multiple file formats. This is also recursive. For example: >>> iglob("apps", "*.py,*.pyc") """ matches = [] patterns = patterns.split(",") if "," in patterns else listify(patterns) for root, dirnames, filenames in os.walk(pathname): matching...
[ "def", "iglob", "(", "pathname", ",", "patterns", ")", ":", "matches", "=", "[", "]", "patterns", "=", "patterns", ".", "split", "(", "\",\"", ")", "if", "\",\"", "in", "patterns", "else", "listify", "(", "patterns", ")", "for", "root", ",", "dirnames"...
34.933333
0.001859
def _set_stream_parameters(self, **kwargs): """ Sets the stream parameters which are expected to be declared constant. """ with util.disable_constant(self): self.param.set_param(**kwargs)
[ "def", "_set_stream_parameters", "(", "self", ",", "*", "*", "kwargs", ")", ":", "with", "util", ".", "disable_constant", "(", "self", ")", ":", "self", ".", "param", ".", "set_param", "(", "*", "*", "kwargs", ")" ]
33.285714
0.008368
def compute_group_label_positions(self): """ Computes the x,y positions of the group labels. """ assert self.group_label_position in ["beginning", "middle", "end"] data = [self.graph.node[n][self.node_grouping] for n in self.nodes] node_length = len(data) groups =...
[ "def", "compute_group_label_positions", "(", "self", ")", ":", "assert", "self", ".", "group_label_position", "in", "[", "\"beginning\"", ",", "\"middle\"", ",", "\"end\"", "]", "data", "=", "[", "self", ".", "graph", ".", "node", "[", "n", "]", "[", "self...
37.875
0.000919
def cpp_spec(): """C++ specification, provided for example, and java compatible.""" return { INDENTATION : '\t', BEG_BLOCK : '{', END_BLOCK : '}', BEG_LINE : '', END_LINE : '\n', BEG_ACTION : '', END_ACTION : ';', B...
[ "def", "cpp_spec", "(", ")", ":", "return", "{", "INDENTATION", ":", "'\\t'", ",", "BEG_BLOCK", ":", "'{'", ",", "END_BLOCK", ":", "'}'", ",", "BEG_LINE", ":", "''", ",", "END_LINE", ":", "'\\n'", ",", "BEG_ACTION", ":", "''", ",", "END_ACTION", ":", ...
28.6
0.027088
def circuit_to_image(circ: Circuit, qubits: Qubits = None) -> PIL.Image: # pragma: no cover """Create an image of a quantum circuit. A convenience function that calls circuit_to_latex() and render_latex(). Args: circ: A quantum Circuit qubits: Optional qubi...
[ "def", "circuit_to_image", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", "=", "None", ")", "->", "PIL", ".", "Image", ":", "# pragma: no cover", "latex", "=", "circuit_to_latex", "(", "circ", ",", "qubits", ")", "img", "=", "render_latex", "("...
31.15
0.001558
def value(self): """returns object as dictionary""" return { "type" : "uniqueValue", "field1" : self._field1, "field2" : self._field2, "field3" : self._field3, "fieldDelimiter" : self._fieldDelimiter, "defaultSymbol" : self._defaul...
[ "def", "value", "(", "self", ")", ":", "return", "{", "\"type\"", ":", "\"uniqueValue\"", ",", "\"field1\"", ":", "self", ".", "_field1", ",", "\"field2\"", ":", "self", ".", "_field2", ",", "\"field3\"", ":", "self", ".", "_field3", ",", "\"fieldDelimiter...
38.857143
0.017953
def add_suffix(file_path, suffix='modified', sep='_', ext=None): """Adds suffix to a file name seperated by an underscore and returns file path.""" return _add_suffix(file_path, suffix, sep, ext)
[ "def", "add_suffix", "(", "file_path", ",", "suffix", "=", "'modified'", ",", "sep", "=", "'_'", ",", "ext", "=", "None", ")", ":", "return", "_add_suffix", "(", "file_path", ",", "suffix", ",", "sep", ",", "ext", ")" ]
67
0.009852
def reveal(input_image: Union[str, IO[bytes]]): """ Find a message in an image. Check the red portion of an pixel (r, g, b) tuple for hidden message characters (ASCII values). The red value of the first pixel is used for message_length of string. """ img = tools.open_image(input_image) ...
[ "def", "reveal", "(", "input_image", ":", "Union", "[", "str", ",", "IO", "[", "bytes", "]", "]", ")", ":", "img", "=", "tools", ".", "open_image", "(", "input_image", ")", "width", ",", "height", "=", "img", ".", "size", "message", "=", "\"\"", "i...
31.521739
0.001339
def _parse_udiff(self): """ Parse the diff an return data for the template. """ lineiter = self.lines files = [] try: line = lineiter.next() # skip first context skipfirst = True while 1: # continue until we ...
[ "def", "_parse_udiff", "(", "self", ")", ":", "lineiter", "=", "self", ".", "lines", "files", "=", "[", "]", "try", ":", "line", "=", "lineiter", ".", "next", "(", ")", "# skip first context", "skipfirst", "=", "True", "while", "1", ":", "# continue unti...
36.264151
0.00076
def put_bug(self, bugid, bug_update): '''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#update-bug''' assert type(bug_update) is DotDict if (not 'ids' in bug_update): bug_update.ids = [bugid] return self._put('bug/{bugid}'.format(bugid=bugid), ...
[ "def", "put_bug", "(", "self", ",", "bugid", ",", "bug_update", ")", ":", "assert", "type", "(", "bug_update", ")", "is", "DotDict", "if", "(", "not", "'ids'", "in", "bug_update", ")", ":", "bug_update", ".", "ids", "=", "[", "bugid", "]", "return", ...
42.125
0.014535
def find_usage(self): """ Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. """ logger.debug("Checking usage for service %s", self.service_name) for lim in self.limits.values():...
[ "def", "find_usage", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Checking usage for service %s\"", ",", "self", ".", "service_name", ")", "for", "lim", "in", "self", ".", "limits", ".", "values", "(", ")", ":", "lim", ".", "_reset_usage", "(", ...
36.88
0.002114
def from_stream(cls, stream, marker_code, offset): """ Extract the horizontal and vertical dots-per-inch value from the APP1 header at *offset* in *stream*. """ # field off len type notes # -------------------- --- --- ----- -----------------------...
[ "def", "from_stream", "(", "cls", ",", "stream", ",", "marker_code", ",", "offset", ")", ":", "# field off len type notes", "# -------------------- --- --- ----- ----------------------------", "# segment length 0 2 short", "# Exif identifier ...
53.85
0.001825
def delete(self): """ Deletes the directory if it exists. """ if self.exists: logger.info("Deleting %s" % self.path) shutil.rmtree(self.path)
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "exists", ":", "logger", ".", "info", "(", "\"Deleting %s\"", "%", "self", ".", "path", ")", "shutil", ".", "rmtree", "(", "self", ".", "path", ")" ]
27.285714
0.010152
def find_saas_replication_price(package, tier=None, iops=None): """Find the price in the given package for the desired replicant volume :param package: The product package of the endurance storage type :param tier: The tier of the primary storage volume :param iops: The IOPS of the primary storage volu...
[ "def", "find_saas_replication_price", "(", "package", ",", "tier", "=", "None", ",", "iops", "=", "None", ")", ":", "if", "tier", "is", "not", "None", ":", "target_value", "=", "ENDURANCE_TIERS", ".", "get", "(", "tier", ")", "target_item_keyname", "=", "'...
36.225806
0.000867
def dir_tails_top(self, rr_id) -> str: """ Return top of tails tree for input rev reg id. :param rr_id: revocation registry identifier :return: top of tails tree """ return join(self.dir_tails_hopper, rr_id) if self.external else self.dir_tails
[ "def", "dir_tails_top", "(", "self", ",", "rr_id", ")", "->", "str", ":", "return", "join", "(", "self", ".", "dir_tails_hopper", ",", "rr_id", ")", "if", "self", ".", "external", "else", "self", ".", "dir_tails" ]
31.777778
0.010204
def readiter(d): """ Read iteration of size iterint """ da = ms.getdata([d['datacol'],'axis_info','u','v','w','flag','data_desc_id'], ifraxis=True) good = n.where((da['data_desc_id']) == d['spwlist'][0])[0] # take first spw time0 = da['axis_info']['...
[ "def", "readiter", "(", "d", ")", ":", "da", "=", "ms", ".", "getdata", "(", "[", "d", "[", "'datacol'", "]", ",", "'axis_info'", ",", "'u'", ",", "'v'", ",", "'w'", ",", "'flag'", ",", "'data_desc_id'", "]", ",", "ifraxis", "=", "True", ")", "go...
55.44
0.02695
def MT2Plane(mt): """ Calculates a nodal plane of a given moment tensor. :param mt: :class:`~MomentTensor` :return: :class:`~NodalPlane` Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd. """ ...
[ "def", "MT2Plane", "(", "mt", ")", ":", "(", "d", ",", "v", ")", "=", "np", ".", "linalg", ".", "eig", "(", "mt", ".", "mt", ")", "D", "=", "np", ".", "array", "(", "[", "d", "[", "1", "]", ",", "d", "[", "0", "]", ",", "d", "[", "2",...
31.371429
0.000883
def gzip_dir(path, compresslevel=6): """ Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: ...
[ "def", "gzip_dir", "(", "path", ",", "compresslevel", "=", "6", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "full_f", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "not", "f", ".", "lower", ...
41.47619
0.002245
def _write(self, context, report_dir, report_name, assets_dir=None, template=None): """Writes the data in `context` in the report's template to `report_name` in `report_dir`. If `assets_dir` is supplied, copies all assets for this report to the specified directory. ...
[ "def", "_write", "(", "self", ",", "context", ",", "report_dir", ",", "report_name", ",", "assets_dir", "=", "None", ",", "template", "=", "None", ")", ":", "if", "template", "is", "None", ":", "template", "=", "self", ".", "_get_template", "(", ")", "...
41.03125
0.002232
def assertrepr_compare(config, op, left, right): """Return specialised explanations for some operators/operands""" width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op left_repr = py.io.saferepr(left, maxsize=int(width//2)) right_repr = py.io.saferepr(right, maxsize=width-len(left_re...
[ "def", "assertrepr_compare", "(", "config", ",", "op", ",", "left", ",", "right", ")", ":", "width", "=", "80", "-", "15", "-", "len", "(", "op", ")", "-", "2", "# 15 chars indentation, 1 space around op", "left_repr", "=", "py", ".", "io", ".", "saferep...
40.392157
0.00237
def parse_json(data): """Parse the input data dict into a `Channel`. Parameters ---------- data : `dict` input data from CIS json query Returns ------- c : `Channel` a `Channel` built from the data """ sample_rate = data['datarate'] unit = data['units'] dtyp...
[ "def", "parse_json", "(", "data", ")", ":", "sample_rate", "=", "data", "[", "'datarate'", "]", "unit", "=", "data", "[", "'units'", "]", "dtype", "=", "CIS_DATA_TYPE", "[", "data", "[", "'datatype'", "]", "]", "model", "=", "data", "[", "'source'", "]...
25.75
0.001873
def types_msg(instance, types): """ Create an error message for a failure to match the given types. If the ``instance`` is an object and contains a ``name`` property, it will be considered to be a description of that object and used as its type. Otherwise the message is simply the reprs of the giv...
[ "def", "types_msg", "(", "instance", ",", "types", ")", ":", "reprs", "=", "[", "]", "for", "type", "in", "types", ":", "try", ":", "reprs", ".", "append", "(", "repr", "(", "type", "[", "\"name\"", "]", ")", ")", "except", "Exception", ":", "reprs...
30.555556
0.001764
def cli(ctx, profile, region, lambda_fn, config, debug): """ cruddy is a CLI interface to the cruddy handler. It can be used in one of two ways. First, you can pass in a ``--config`` option which is a JSON file containing all of your cruddy parameters and the CLI will create a cruddy handler t...
[ "def", "cli", "(", "ctx", ",", "profile", ",", "region", ",", "lambda_fn", ",", "config", ",", "debug", ")", ":", "ctx", ".", "obj", "=", "CLIHandler", "(", "profile", ",", "region", ",", "lambda_fn", ",", "config", ",", "debug", ")" ]
45.266667
0.001443
def PathExists(v): """Verify the path exists, regardless of its type. >>> os.path.basename(PathExists()(__file__)).startswith('validators.py') True >>> with raises(Invalid, 'path does not exist'): ... PathExists()("random_filename_goes_here.py") >>> with raises(PathInvalid, 'Not a Path'): ...
[ "def", "PathExists", "(", "v", ")", ":", "try", ":", "if", "v", ":", "v", "=", "str", "(", "v", ")", "return", "os", ".", "path", ".", "exists", "(", "v", ")", "else", ":", "raise", "PathInvalid", "(", "\"Not a Path\"", ")", "except", "TypeError", ...
29.944444
0.001799
def load_task_definition_file(task_def_file): """Open and parse a task-definition file in YAML format.""" try: with open(task_def_file) as f: task_def = yaml.safe_load(f) except OSError as e: raise BenchExecException("Cannot open task-definition file: " + str(e)) except yaml....
[ "def", "load_task_definition_file", "(", "task_def_file", ")", ":", "try", ":", "with", "open", "(", "task_def_file", ")", "as", "f", ":", "task_def", "=", "yaml", ".", "safe_load", "(", "f", ")", "except", "OSError", "as", "e", ":", "raise", "BenchExecExc...
41.125
0.001486
def initialize_pycons3rt_dirs(): """Initializes the pycons3rt directories :return: None :raises: OSError """ for pycons3rt_dir in [get_pycons3rt_home_dir(), get_pycons3rt_user_dir(), get_pycons3rt_conf_dir(), get_pycons3r...
[ "def", "initialize_pycons3rt_dirs", "(", ")", ":", "for", "pycons3rt_dir", "in", "[", "get_pycons3rt_home_dir", "(", ")", ",", "get_pycons3rt_user_dir", "(", ")", ",", "get_pycons3rt_conf_dir", "(", ")", ",", "get_pycons3rt_log_dir", "(", ")", ",", "get_pycons3rt_sr...
34.952381
0.001326
def restore_used_registers(self): """Pops all used working registers after function call""" used = self.used_registers_stack.pop() self.used_registers = used[:] used.sort(reverse = True) for reg in used: self.newline_text("POP \t%s" % SharedData.REGISTERS[reg], ...
[ "def", "restore_used_registers", "(", "self", ")", ":", "used", "=", "self", ".", "used_registers_stack", ".", "pop", "(", ")", "self", ".", "used_registers", "=", "used", "[", ":", "]", "used", ".", "sort", "(", "reverse", "=", "True", ")", "for", "re...
45.375
0.010811
def _realGetAllThemes(self): """ Collect themes from all available offerings. """ l = [] for offering in getOfferings(): l.extend(offering.themes) l.sort(key=lambda o: o.priority) l.reverse() return l
[ "def", "_realGetAllThemes", "(", "self", ")", ":", "l", "=", "[", "]", "for", "offering", "in", "getOfferings", "(", ")", ":", "l", ".", "extend", "(", "offering", ".", "themes", ")", "l", ".", "sort", "(", "key", "=", "lambda", "o", ":", "o", "....
26.7
0.01087
def abs(f=Ellipsis): ''' abs() yields a potential function equivalent to the absolute value of the input. abs(f) yields the absolute value of the potential function f. Note that abs has a derivative of 0 at 0; this is not mathematically correct, but it is useful for the purposes of numerical method...
[ "def", "abs", "(", "f", "=", "Ellipsis", ")", ":", "f", "=", "to_potential", "(", "f", ")", "if", "is_const_potential", "(", "f", ")", ":", "return", "const_potential", "(", "np", ".", "abs", "(", "f", ".", "c", ")", ")", "elif", "is_identity_potenti...
46.076923
0.011457
def transDrift(length=0.0, gamma=None): """ Transport matrix of drift :param length: drift length in [m] :param gamma: electron energy, gamma value :return: 6x6 numpy array """ m = np.eye(6, 6, dtype=np.float64) if length == 0.0: print("warning: 'length' should be a positive float n...
[ "def", "transDrift", "(", "length", "=", "0.0", ",", "gamma", "=", "None", ")", ":", "m", "=", "np", ".", "eye", "(", "6", ",", "6", ",", "dtype", "=", "np", ".", "float64", ")", "if", "length", "==", "0.0", ":", "print", "(", "\"warning: 'length...
33.3125
0.001825
def ls(sess_id_or_alias, path): """ List files in a path of a running container. \b SESSID: Session ID or its alias given when creating the session. PATH: Path inside container. """ with Session() as session: try: print_wait('Retrieving list of files in "{}"...'.format(p...
[ "def", "ls", "(", "sess_id_or_alias", ",", "path", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "try", ":", "print_wait", "(", "'Retrieving list of files in \"{}\"...'", ".", "format", "(", "path", ")", ")", "kernel", "=", "session", ".", "...
36.09375
0.000843
def get_description(self, lang='en'): """ Retrieve the description in a certain language :param lang: The Wikidata language the description should be retrieved for :return: Returns the description string """ if self.fast_run: return list(self.fast_run_containe...
[ "def", "get_description", "(", "self", ",", "lang", "=", "'en'", ")", ":", "if", "self", ".", "fast_run", ":", "return", "list", "(", "self", ".", "fast_run_container", ".", "get_language_data", "(", "self", ".", "wd_item_id", ",", "lang", ",", "'descripti...
50.416667
0.008117
def pattern_logic_srt(): """Return patterns to be used for searching srt subtitles.""" if Config.options.pattern_files and Config.options.regex: return prep_regex(prep_patterns(Config.options.pattern_files)) elif Config.options.pattern_files: return prep_patterns(Config.options.pattern_file...
[ "def", "pattern_logic_srt", "(", ")", ":", "if", "Config", ".", "options", ".", "pattern_files", "and", "Config", ".", "options", ".", "regex", ":", "return", "prep_regex", "(", "prep_patterns", "(", "Config", ".", "options", ".", "pattern_files", ")", ")", ...
38.272727
0.00232
def pull_all_ltr(configuration): """ Pulls all translations - reviewed or not - for LTR languages """ print("Pulling all translated LTR languages from transifex...") for lang in configuration.ltr_langs: print('rm -rf conf/locale/' + lang) execute('rm -rf conf/locale/' + lang) ...
[ "def", "pull_all_ltr", "(", "configuration", ")", ":", "print", "(", "\"Pulling all translated LTR languages from transifex...\"", ")", "for", "lang", "in", "configuration", ".", "ltr_langs", ":", "print", "(", "'rm -rf conf/locale/'", "+", "lang", ")", "execute", "("...
41.6
0.002353
def change_meta(self, para, new_value, log=True): """ Changes the meta data This function does nothing if None is passed as new_value. To set a certain value to None pass the str 'None' Parameters ---------- para: str Meta data entry to change new_v...
[ "def", "change_meta", "(", "self", ",", "para", ",", "new_value", ",", "log", "=", "True", ")", ":", "if", "not", "new_value", ":", "return", "para", "=", "para", ".", "lower", "(", ")", "if", "para", "==", "'history'", ":", "raise", "ValueError", "(...
32.777778
0.001646
def getCheckpointParentDir(experimentDir): """Get checkpoint parent dir. Returns: absolute path to the base serialization directory within which model checkpoints for this experiment are created """ baseDir = os.path.join(experimentDir, "savedmodels") baseDir = os.path.abspath(baseDir) return baseDi...
[ "def", "getCheckpointParentDir", "(", "experimentDir", ")", ":", "baseDir", "=", "os", ".", "path", ".", "join", "(", "experimentDir", ",", "\"savedmodels\"", ")", "baseDir", "=", "os", ".", "path", ".", "abspath", "(", "baseDir", ")", "return", "baseDir" ]
31.2
0.015576
def file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None): """Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): ...
[ "def", "file_response", "(", "request", ",", "filepath", ",", "block", "=", "None", ",", "status_code", "=", "None", ",", "content_type", "=", "None", ",", "encoding", "=", "None", ",", "cache_control", "=", "None", ")", ":", "file_wrapper", "=", "request"...
37.822222
0.000573
def ssml_prosody(self, words, volume=None, rate=None, pitch=None, **kwargs): """ Create a <Prosody> element :param words: Words to speak :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB :param rate: Specify the ...
[ "def", "ssml_prosody", "(", "self", ",", "words", ",", "volume", "=", "None", ",", "rate", "=", "None", ",", "pitch", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "nest", "(", "SsmlProsody", "(", "words", ",", "volume", "=...
51.461538
0.008811
async def info(self, fields: Iterable[str] = None) -> dict: ''' Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12 ''' if fields is None: fields = ( 'a...
[ "async", "def", "info", "(", "self", ",", "fields", ":", "Iterable", "[", "str", "]", "=", "None", ")", "->", "dict", ":", "if", "fields", "is", "None", ":", "fields", "=", "(", "'access_key'", ",", "'secret_key'", ",", "'is_active'", ",", "'is_admin'"...
29.884615
0.002494
def _send_packet(self): """ Send a single packet to the interface This function guarentees that the number of packets that are stored in daplink's buffer (the number of packets written but not read) does not exceed the number supported by the given device. """ ...
[ "def", "_send_packet", "(", "self", ")", ":", "cmd", "=", "self", ".", "_crnt_cmd", "if", "cmd", ".", "get_empty", "(", ")", ":", "return", "max_packets", "=", "self", ".", "_interface", ".", "get_packet_count", "(", ")", "if", "len", "(", "self", ".",...
33.708333
0.002404
def document_path_path(cls, project, database, document_path): """Return a fully-qualified document_path string.""" return google.api_core.path_template.expand( "projects/{project}/databases/{database}/documents/{document_path=**}", project=project, database=database,...
[ "def", "document_path_path", "(", "cls", ",", "project", ",", "database", ",", "document_path", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/databases/{database}/documents/{document_path=**}\"", ",", "pro...
45.5
0.008086
def _get_capirca_platform(): # pylint: disable=too-many-return-statements ''' Given the following NAPALM grains, we can determine the Capirca platform name: - vendor - device model - operating system Not the most optimal. ''' vendor = __grains__['vendor'].lower() os_ = __grains__[...
[ "def", "_get_capirca_platform", "(", ")", ":", "# pylint: disable=too-many-return-statements", "vendor", "=", "__grains__", "[", "'vendor'", "]", ".", "lower", "(", ")", "os_", "=", "__grains__", "[", "'os'", "]", ".", "lower", "(", ")", "model", "=", "__grain...
32.310345
0.002073
def __push_symbol(self, symbol): '''Ask the websocket for a symbol push. Gets instrument, orderBook, quote, and trade''' self.__send_command("getSymbol", symbol) while not {'instrument', 'trade', 'orderBook25'} <= set(self.data): sleep(0.1)
[ "def", "__push_symbol", "(", "self", ",", "symbol", ")", ":", "self", ".", "__send_command", "(", "\"getSymbol\"", ",", "symbol", ")", "while", "not", "{", "'instrument'", ",", "'trade'", ",", "'orderBook25'", "}", "<=", "set", "(", "self", ".", "data", ...
54.4
0.01087
def load(self): """Load all available DRPs in 'entry_point'.""" for drpins in self.iload(self.entry): self.drps[drpins.name] = drpins return self
[ "def", "load", "(", "self", ")", ":", "for", "drpins", "in", "self", ".", "iload", "(", "self", ".", "entry", ")", ":", "self", ".", "drps", "[", "drpins", ".", "name", "]", "=", "drpins", "return", "self" ]
25.285714
0.010929
def context_from_module(module): """ Given a module, create a context from all of the top level annotated symbols in that module. """ con = find_all(module) if hasattr(module, "__doc__"): setattr(con, "__doc__", module.__doc__) name = module.__name__ if hasattr(module, "_name_...
[ "def", "context_from_module", "(", "module", ")", ":", "con", "=", "find_all", "(", "module", ")", "if", "hasattr", "(", "module", ",", "\"__doc__\"", ")", ":", "setattr", "(", "con", ",", "\"__doc__\"", ",", "module", ".", "__doc__", ")", "name", "=", ...
23.526316
0.002151
def _check(value, message): """ Checks the libsbml return value and logs error messages. If 'value' is None, logs an error message constructed using 'message' and then exits with status code 1. If 'value' is an integer, it assumes it is a libSBML return status code. If the code value is L...
[ "def", "_check", "(", "value", ",", "message", ")", ":", "if", "value", "is", "None", ":", "LOGGER", ".", "error", "(", "'Error: LibSBML returned a null value trying '", "'to <'", "+", "message", "+", "'>.'", ")", "elif", "type", "(", "value", ")", "is", "...
43.375
0.00094
def main(): 'Main function. Handles delegation to other functions.' logging.basicConfig() type_choices = {'any': constants.PACKAGE_ANY, 'extension': constants.PACKAGE_EXTENSION, 'theme': constants.PACKAGE_THEME, 'dictionary': constants.PACKAGE_DI...
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", ")", "type_choices", "=", "{", "'any'", ":", "constants", ".", "PACKAGE_ANY", ",", "'extension'", ":", "constants", ".", "PACKAGE_EXTENSION", ",", "'theme'", ":", "constants", ".", "PACKAGE_TH...
44.537313
0.000164
def find_wheels(projects, search_dirs): """Find wheels from which we can import PROJECTS. Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return a list of the first wheel found for each PROJECT """ wheels = [] # Look through SEARCH_DIRS for the first suitable wheel. Don't bothe...
[ "def", "find_wheels", "(", "projects", ",", "search_dirs", ")", ":", "wheels", "=", "[", "]", "# Look through SEARCH_DIRS for the first suitable wheel. Don't bother", "# about version checking here, as this is simply to get something we can", "# then use to install the correct version.",...
38.96
0.001002
def _GetChunk(self): """Fetches a chunk corresponding to the current offset.""" found_ref = None for ref in self._blob_refs: if self._offset >= ref.offset and self._offset < (ref.offset + ref.size): found_ref = ref break if not found_ref: return None, None # If self._c...
[ "def", "_GetChunk", "(", "self", ")", ":", "found_ref", "=", "None", "for", "ref", "in", "self", ".", "_blob_refs", ":", "if", "self", ".", "_offset", ">=", "ref", ".", "offset", "and", "self", ".", "_offset", "<", "(", "ref", ".", "offset", "+", "...
31.333333
0.00885
def parse(self, stream, full_statusline=None): """ parse stream for status line and headers return a StatusAndHeaders object support continuation headers starting with space or tab """ # status line w newlines intact if full_statusline is None: full_...
[ "def", "parse", "(", "self", ",", "stream", ",", "full_statusline", "=", "None", ")", ":", "# status line w newlines intact", "if", "full_statusline", "is", "None", ":", "full_statusline", "=", "stream", ".", "readline", "(", ")", "full_statusline", "=", "self",...
35.287671
0.001888
def read_tree_nexus(nexus): '''Read a tree from a Nexus string or file Args: ``nexus`` (``str``): Either a Nexus string or the path to a Nexus file (plain-text or gzipped) Returns: ``dict`` of ``Tree``: A dictionary of the trees represented by ``nexus``, where keys are tree names (``str``)...
[ "def", "read_tree_nexus", "(", "nexus", ")", ":", "if", "not", "isinstance", "(", "nexus", ",", "str", ")", ":", "raise", "TypeError", "(", "\"nexus must be a str\"", ")", "if", "nexus", ".", "lower", "(", ")", ".", "endswith", "(", "'.gz'", ")", ":", ...
35.566667
0.010036
def cutL_seq(seq, cutL, max_palindrome): """Cut genomic sequence from the left. Parameters ---------- seq : str Nucleotide sequence to be cut from the right cutL : int cutL - max_palindrome = how many nucleotides to cut from the left. Negative cutL implies complementary pali...
[ "def", "cutL_seq", "(", "seq", ",", "cutL", ",", "max_palindrome", ")", ":", "complement_dict", "=", "{", "'A'", ":", "'T'", ",", "'C'", ":", "'G'", ",", "'G'", ":", "'C'", ",", "'T'", ":", "'A'", "}", "#can include lower case if wanted", "if", "cutL", ...
30.088235
0.012311
def pipe_sort(context=None, _INPUT=None, conf=None, **kwargs): """An operator that sorts the input source according to the specified key. Not loopable. Not lazy. Parameters ---------- context : pipe2py.Context object _INPUT : pipe2py.modules pipe like object (iterable of items) kwargs -- ot...
[ "def", "pipe_sort", "(", "context", "=", "None", ",", "_INPUT", "=", "None", ",", "conf", "=", "None", ",", "*", "*", "kwargs", ")", ":", "test", "=", "kwargs", ".", "pop", "(", "'pass_if'", ",", "None", ")", "_pass", "=", "utils", ".", "get_pass",...
35.393939
0.000833
def conv2d(x_input, w_matrix): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')
[ "def", "conv2d", "(", "x_input", ",", "w_matrix", ")", ":", "return", "tf", ".", "nn", ".", "conv2d", "(", "x_input", ",", "w_matrix", ",", "strides", "=", "[", "1", ",", "1", ",", "1", ",", "1", "]", ",", "padding", "=", "'SAME'", ")" ]
58.333333
0.011299
def eliminate_local_candidates(x, AggOp, A, T, Ca=1.0, **kwargs): """Eliminate canidates locally. Helper function that determines where to eliminate candidates locally on a per aggregate basis. Parameters --------- x : array n x 1 vector of new candidate AggOp : CSR or CSC sparse m...
[ "def", "eliminate_local_candidates", "(", "x", ",", "AggOp", ",", "A", ",", "T", ",", "Ca", "=", "1.0", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "isspmatrix_csr", "(", "AggOp", ")", "or", "isspmatrix_csc", "(", "AggOp", ")", ")", ":", "...
34.960526
0.000366
def update(self, value, tys=None, override=True): """ Update this context. if value is another context, the names from that context are added into this one. Otherwise, a new name is assigned and returned. TODO tys for inputs. """ if isinstance(value, WeldObject):...
[ "def", "update", "(", "self", ",", "value", ",", "tys", "=", "None", ",", "override", "=", "True", ")", ":", "if", "isinstance", "(", "value", ",", "WeldObject", ")", ":", "self", ".", "context", ".", "update", "(", "value", ".", "context", ")", "e...
38.238095
0.00243
def toy_data(n_obs): """ Randomly samples from the Dentate Gyrus dataset. Arguments --------- n_obs: `int` Size of the sampled dataset Returns ------- Returns `adata` object """ """Random samples from Dentate Gyrus. """ adata = dentategyrus() indices = np.r...
[ "def", "toy_data", "(", "n_obs", ")", ":", "\"\"\"Random samples from Dentate Gyrus.\n \"\"\"", "adata", "=", "dentategyrus", "(", ")", "indices", "=", "np", ".", "random", ".", "choice", "(", "adata", ".", "n_obs", ",", "n_obs", ")", "adata", "=", "adata",...
21.5
0.002024
def notification_update(request): """ Handles live updating of notifications, follows ajax-polling approach. Read more: http://stackoverflow.com/a/12855533/4726598 Required URL parameters: ``flag``. Explanation: - The ``flag`` parameter carries the last notification ID \ received...
[ "def", "notification_update", "(", "request", ")", ":", "flag", "=", "request", ".", "GET", ".", "get", "(", "'flag'", ",", "None", ")", "target", "=", "request", ".", "GET", ".", "get", "(", "'target'", ",", "'box'", ")", "last_notification", "=", "in...
36.574468
0.000283
def prepare_mosaic(self, image, fov_deg, name=None): """Prepare a new (blank) mosaic image based on the pointing of the parameter image """ header = image.get_header() ra_deg, dec_deg = header['CRVAL1'], header['CRVAL2'] data_np = image.get_data() #dtype = data_n...
[ "def", "prepare_mosaic", "(", "self", ",", "image", ",", "fov_deg", ",", "name", "=", "None", ")", ":", "header", "=", "image", ".", "get_header", "(", ")", "ra_deg", ",", "dec_deg", "=", "header", "[", "'CRVAL1'", "]", ",", "header", "[", "'CRVAL2'", ...
41.246914
0.000877
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]: """ Takes a number of wei and converts it to any other ether unit. """ if unit.lower() not in units: raise ValueError( "Unknown unit. Must be one of {0}".format("/".join(units.keys())) ) if number == 0...
[ "def", "from_wei", "(", "number", ":", "int", ",", "unit", ":", "str", ")", "->", "Union", "[", "int", ",", "decimal", ".", "Decimal", "]", ":", "if", "unit", ".", "lower", "(", ")", "not", "in", "units", ":", "raise", "ValueError", "(", "\"Unknown...
28.478261
0.001477
def get_configuration(self, key, default=None): """Returns the configuration for KEY""" if key in self.config: return self.config.get(key) else: return default
[ "def", "get_configuration", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ".", "config", ":", "return", "self", ".", "config", ".", "get", "(", "key", ")", "else", ":", "return", "default" ]
33.666667
0.009662
def encode_sentence(obj): """Encode a single sentence.""" warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_sentence", DeprecationWarning) return bioc.biocxml.encoder.encode_sentence(obj)
[ "def", "encode_sentence", "(", "obj", ")", ":", "warnings", ".", "warn", "(", "\"deprecated. Please use bioc.biocxml.encoder.encode_sentence\"", ",", "DeprecationWarning", ")", "return", "bioc", ".", "biocxml", ".", "encoder", ".", "encode_sentence", "(", "obj", ")" ]
53.75
0.009174
def list_members(self, list_id): """ List users in a list :param list_id: list ID number :return: list of :class:`~responsebot.models.User` objects """ return [User(user._json) for user in self._client.list_members(list_id=list_id)]
[ "def", "list_members", "(", "self", ",", "list_id", ")", ":", "return", "[", "User", "(", "user", ".", "_json", ")", "for", "user", "in", "self", ".", "_client", ".", "list_members", "(", "list_id", "=", "list_id", ")", "]" ]
34.25
0.010676
def chk_associations(self, fout_err="gaf.err"): """Check that fields are legal in GAF""" obj = GafData("2.1") return obj.chk(self.associations, fout_err)
[ "def", "chk_associations", "(", "self", ",", "fout_err", "=", "\"gaf.err\"", ")", ":", "obj", "=", "GafData", "(", "\"2.1\"", ")", "return", "obj", ".", "chk", "(", "self", ".", "associations", ",", "fout_err", ")" ]
43.5
0.011299