text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def len(self, dict_name, priority_min='-inf', priority_max='+inf'): '''Get the number of items in (part of) a dictionary. Returns number of items in `dict_name` within [`priority_min`, `priority_max`]. This is similar to ``len(filter(dict_name, priority_min, priority_max))`` but ...
[ "def", "len", "(", "self", ",", "dict_name", ",", "priority_min", "=", "'-inf'", ",", "priority_max", "=", "'+inf'", ")", ":", "dict_name", "=", "self", ".", "_namespace", "(", "dict_name", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", ...
44.166667
0.002463
def load_config(config, expand_env=False, force=False): """Return repos from a directory and fnmatch. Not recursive. :param config: paths to config file :type config: str :param expand_env: True to expand environment varialbes in the config. :type expand_env: bool :param bool force: True to agg...
[ "def", "load_config", "(", "config", ",", "expand_env", "=", "False", ",", "force", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config", ")", ":", "raise", "ConfigException", "(", "'Unable to find configuration file: %s'", "%...
37.333333
0.001088
def get_all_services(self, view = None): """ Get all services in this cluster. @return: A list of ApiService objects. """ return services.get_all_services(self._get_resource_root(), self.name, view)
[ "def", "get_all_services", "(", "self", ",", "view", "=", "None", ")", ":", "return", "services", ".", "get_all_services", "(", "self", ".", "_get_resource_root", "(", ")", ",", "self", ".", "name", ",", "view", ")" ]
30.428571
0.018265
def k_means( X, n_clusters, init="k-means||", precompute_distances="auto", n_init=1, max_iter=300, verbose=False, tol=1e-4, random_state=None, copy_x=True, n_jobs=-1, algorithm="full", return_n_iter=False, oversampling_factor=2, init_max_iter=None, ): """K...
[ "def", "k_means", "(", "X", ",", "n_clusters", ",", "init", "=", "\"k-means||\"", ",", "precompute_distances", "=", "\"auto\"", ",", "n_init", "=", "1", ",", "max_iter", "=", "300", ",", "verbose", "=", "False", ",", "tol", "=", "1e-4", ",", "random_stat...
21.425
0.001116
def __createHTMNetwork(self, sensorParams, spEnable, spParams, tmEnable, tmParams, clEnable, clParams, anomalyParams): """ Create a CLA network and return it. description: HTMPredictionModel description dictionary (TODO: define schema) Returns: NetworkInfo instance; """ ...
[ "def", "__createHTMNetwork", "(", "self", ",", "sensorParams", ",", "spEnable", ",", "spParams", ",", "tmEnable", ",", "tmParams", ",", "clEnable", ",", "clParams", ",", "anomalyParams", ")", ":", "#--------------------------------------------------", "# Create the netw...
38.604839
0.011405
def append(self, page, content, **options): """Appends *content* text to *page*. Valid *options* are: * *sum*: (str) change summary * *minor*: (bool) whether this is a minor change """ return self._dokuwiki.send('dokuwiki.appendPage', page, content, options)
[ "def", "append", "(", "self", ",", "page", ",", "content", ",", "*", "*", "options", ")", ":", "return", "self", ".", "_dokuwiki", ".", "send", "(", "'dokuwiki.appendPage'", ",", "page", ",", "content", ",", "options", ")" ]
34.222222
0.009494
def set_computer_policy(name, setting, cumulative_rights_assignments=True, adml_language='en-US'): ''' Set a single computer policy Args: name (str): The name of the policy to configure setting (str): ...
[ "def", "set_computer_policy", "(", "name", ",", "setting", ",", "cumulative_rights_assignments", "=", "True", ",", "adml_language", "=", "'en-US'", ")", ":", "pol", "=", "{", "}", "pol", "[", "name", "]", "=", "setting", "ret", "=", "set_", "(", "computer_...
32.775
0.000741
def on_epoch_end(self, pbar, epoch, last_metrics, **kwargs): "Put the various losses in the recorder and show a sample image." if not hasattr(self, 'last_gen') or not self.show_img: return data = self.learn.data img = self.last_gen[0] norm = getattr(data,'norm',False) if ...
[ "def", "on_epoch_end", "(", "self", ",", "pbar", ",", "epoch", ",", "last_metrics", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'last_gen'", ")", "or", "not", "self", ".", "show_img", ":", "return", "data", "=", "sel...
55.5
0.019202
def colored(text, color=None, on_color=None, attrs=None, ansi_code=None): """Colorize text, while stripping nested ANSI color sequences. Author: Konstantin Lepa <konstantin.lepa@gmail.com> / termcolor Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highli...
[ "def", "colored", "(", "text", ",", "color", "=", "None", ",", "on_color", "=", "None", ",", "attrs", "=", "None", ",", "ansi_code", "=", "None", ")", ":", "if", "os", ".", "getenv", "(", "'ANSI_COLORS_DISABLED'", ")", "is", "None", ":", "if", "ansi_...
41.90625
0.000729
async def _sort_using_by_arg(self, data, by, alpha): """ Used by sort() """ if getattr(by, "decode", None): by = by.decode("utf-8") async def _by_key(arg): if getattr(arg, "decode", None): arg = arg.decode("utf-8") key = by.re...
[ "async", "def", "_sort_using_by_arg", "(", "self", ",", "data", ",", "by", ",", "alpha", ")", ":", "if", "getattr", "(", "by", ",", "\"decode\"", ",", "None", ")", ":", "by", "=", "by", ".", "decode", "(", "\"utf-8\"", ")", "async", "def", "_by_key",...
31.36
0.002475
def left_brake(self): """allows left motor to coast to a stop""" self.board.digital_write(L_CTRL_1, 1) self.board.digital_write(L_CTRL_2, 1) self.board.analog_write(PWM_L, 0)
[ "def", "left_brake", "(", "self", ")", ":", "self", ".", "board", ".", "digital_write", "(", "L_CTRL_1", ",", "1", ")", "self", ".", "board", ".", "digital_write", "(", "L_CTRL_2", ",", "1", ")", "self", ".", "board", ".", "analog_write", "(", "PWM_L",...
40.4
0.009709
def packints_decode(data, dtype, numbits, runlen=0, out=None): """Decompress byte string to array of integers. This implementation only handles itemsizes 1, 8, 16, 32, and 64 bits. Install the imagecodecs package for decoding other integer sizes. Parameters ---------- data : byte str D...
[ "def", "packints_decode", "(", "data", ",", "dtype", ",", "numbits", ",", "runlen", "=", "0", ",", "out", "=", "None", ")", ":", "if", "numbits", "==", "1", ":", "# bitarray", "data", "=", "numpy", ".", "frombuffer", "(", "data", ",", "'|B'", ")", ...
33.823529
0.000845
def add_algorithm(self, parser): """Add the --algorithm option.""" help = 'The HashAlgorithm that will be used to generate the signature (default: %(default)s).' % { 'default': ca_settings.CA_DIGEST_ALGORITHM.name, } parser.add_argument( '--algorithm', metavar='{sha512,...
[ "def", "add_algorithm", "(", "self", ",", "parser", ")", ":", "help", "=", "'The HashAlgorithm that will be used to generate the signature (default: %(default)s).'", "%", "{", "'default'", ":", "ca_settings", ".", "CA_DIGEST_ALGORITHM", ".", "name", ",", "}", "parser", ...
45.888889
0.009501
def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ if isinstance(value, six.string_types): value = value.encode("utf_8") return value
[ "def", "value_to_db", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "value", ".", "encode", "(", "\"utf_8\"", ")", "return", "value" ]
43.6
0.013514
def dict_take(dict_, keys, default=util_const.NoParam): r""" Generates values from a dictionary Args: dict_ (Mapping): a dictionary to take from keys (Iterable): the keys to take default (object, optional): if specified uses default if keys are missing CommandLine: pyth...
[ "def", "dict_take", "(", "dict_", ",", "keys", ",", "default", "=", "util_const", ".", "NoParam", ")", ":", "if", "default", "is", "util_const", ".", "NoParam", ":", "for", "key", "in", "keys", ":", "yield", "dict_", "[", "key", "]", "else", ":", "fo...
30.742857
0.001802
def build_regression_matrix(H, model, build=None): """ Build a regression matrix using a DOE matrix and a list of monomials. Parameters ---------- H : 2d-array model : str build : bool-array Returns ------- R : 2d-array """ ListOfTokens = mod...
[ "def", "build_regression_matrix", "(", "H", ",", "model", ",", "build", "=", "None", ")", ":", "ListOfTokens", "=", "model", ".", "split", "(", "' '", ")", "if", "H", ".", "shape", "[", "1", "]", "==", "1", ":", "size_index", "=", "len", "(", "str"...
31.463768
0.008933
def getThirdPartyLibIncludeDirs(self, libs): """ Retrieves the list of include directories for building against the Unreal-bundled versions of the specified third-party libraries """ platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThi...
[ "def", "getThirdPartyLibIncludeDirs", "(", "self", ",", "libs", ")", ":", "platformDefaults", "=", "True", "if", "libs", "[", "0", "]", "==", "'--nodefaults'", ":", "platformDefaults", "=", "False", "libs", "=", "libs", "[", "1", ":", "]", "details", "=", ...
40.545455
0.032895
def p_const_map(self, p): '''const_map : '{' const_map_seq '}' ''' p[0] = ast.ConstMap(dict(p[2]), p.lineno(1))
[ "def", "p_const_map", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "ConstMap", "(", "dict", "(", "p", "[", "2", "]", ")", ",", "p", ".", "lineno", "(", "1", ")", ")" ]
41.666667
0.015748
def litemfreq(inlist): """ Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies) """ scores = pstat.unique(inlist) scores.sort() ...
[ "def", "litemfreq", "(", "inlist", ")", ":", "scores", "=", "pstat", ".", "unique", "(", "inlist", ")", "scores", ".", "sort", "(", ")", "freq", "=", "[", "]", "for", "item", "in", "scores", ":", "freq", ".", "append", "(", "inlist", ".", "count", ...
29.785714
0.002326
def parse_rich_header(self): """Parses the rich header see http://www.ntcore.com/files/richsign.htm for more information Structure: 00 DanS ^ checksum, checksum, checksum, checksum 10 Symbol RVA ^ checksum, Symbol size ^ checksum... ... XX Rich, checksum,...
[ "def", "parse_rich_header", "(", "self", ")", ":", "# Rich Header constants", "#", "DANS", "=", "0x536E6144", "# 'DanS' as dword", "RICH", "=", "0x68636952", "# 'Rich' as dword", "# Read a block of data", "#", "try", ":", "data", "=", "list", "(", "struct", ".", "...
30.888889
0.009297
def add_line(self, line): """Add a line of source to the code. Don't include indentations or newlines. """ self.code.append(" " * self.indent_amount) self.code.append(line) self.code.append("\n")
[ "def", "add_line", "(", "self", ",", "line", ")", ":", "self", ".", "code", ".", "append", "(", "\" \"", "*", "self", ".", "indent_amount", ")", "self", ".", "code", ".", "append", "(", "line", ")", "self", ".", "code", ".", "append", "(", "\"\\n\"...
26.333333
0.008163
def GetClientVersion(client_id, token=None): """Returns last known GRR version that the client used.""" if data_store.RelationalDBEnabled(): sinfo = data_store.REL_DB.ReadClientStartupInfo(client_id=client_id) if sinfo is not None: return sinfo.client_info.client_version else: return config....
[ "def", "GetClientVersion", "(", "client_id", ",", "token", "=", "None", ")", ":", "if", "data_store", ".", "RelationalDBEnabled", "(", ")", ":", "sinfo", "=", "data_store", ".", "REL_DB", ".", "ReadClientStartupInfo", "(", "client_id", "=", "client_id", ")", ...
39.4
0.014876
def SearchUbuntuAmiDatabase(release_name, region_name, root_store_type, virtualization_type): """ Returns the ubuntu created ami matching the given criteria. """ ami_list_url = 'http://cloud-images.ubuntu.com/query/%s/server/released.txt' \ % (release_name) url_file = urllib2.urlope...
[ "def", "SearchUbuntuAmiDatabase", "(", "release_name", ",", "region_name", ",", "root_store_type", ",", "virtualization_type", ")", ":", "ami_list_url", "=", "'http://cloud-images.ubuntu.com/query/%s/server/released.txt'", "%", "(", "release_name", ")", "url_file", "=", "ur...
41.589744
0.01747
def filter(self, **filters): """Update filters with provided arguments. Note that filters are only resolved when the view is iterated, and hence they do not compose. Each call to filter merely updates the relevant filters. For example, with this code:: view = sdat.steps[500...
[ "def", "filter", "(", "self", ",", "*", "*", "filters", ")", ":", "for", "flt", ",", "val", "in", "self", ".", "_flt", ".", "items", "(", ")", ":", "self", ".", "_flt", "[", "flt", "]", "=", "filters", ".", "pop", "(", "flt", ",", "val", ")",...
40.5
0.001608
def generate(self, name: str, **kwargs): """ generate full qualified url for named url pattern with kwargs """ path = self.urlmapper.generate(name, **kwargs) return self.make_full_qualified_url(path)
[ "def", "generate", "(", "self", ",", "name", ":", "str", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "urlmapper", ".", "generate", "(", "name", ",", "*", "*", "kwargs", ")", "return", "self", ".", "make_full_qualified_url", "(", "pat...
45.4
0.008658
def total_receipts(pronac, dt): """ This metric calculates the project total of receipts and compare it to projects in the same segment output: is_outlier: True if projects receipts is not compatible to others projects in the same segment total_receipts: a...
[ "def", "total_receipts", "(", "pronac", ",", "dt", ")", ":", "dataframe", "=", "data", ".", "planilha_comprovacao", "project", "=", "dataframe", ".", "loc", "[", "dataframe", "[", "'PRONAC'", "]", "==", "pronac", "]", "segment_id", "=", "project", ".", "il...
40.071429
0.00087
def calc_correction(temp, mag, add=False, T_std=10, m=0.021): """Function to add or substract the temperature effect to given data. The function can be called in python scripts. For application via command line in a file system use the script td_correct_temperature.py. The data is taken and given in Ohm...
[ "def", "calc_correction", "(", "temp", ",", "mag", ",", "add", "=", "False", ",", "T_std", "=", "10", ",", "m", "=", "0.021", ")", ":", "if", "mag", ".", "shape", "[", "1", "]", "==", "3", ":", "if", "add", ":", "data_x", "=", "(", "m", "*", ...
46.027027
0.000575
def filter_by_rows(self, rows, ID=None): """ Keep only Measurements in corresponding rows. """ rows = to_list(rows) fil = lambda x: x in rows applyto = {k: self._positions[k][0] for k in self.keys()} if ID is None: ID = self.ID return self.filt...
[ "def", "filter_by_rows", "(", "self", ",", "rows", ",", "ID", "=", "None", ")", ":", "rows", "=", "to_list", "(", "rows", ")", "fil", "=", "lambda", "x", ":", "x", "in", "rows", "applyto", "=", "{", "k", ":", "self", ".", "_positions", "[", "k", ...
34.2
0.008547
def execute_command(working_dir, cmd, env_dict): """ execute_command: run the command provided in the working dir specified adding the env_dict settings to the execution environment :param working_dir: path to directory to execute command also gets added to the PATH :param cmd: Shell com...
[ "def", "execute_command", "(", "working_dir", ",", "cmd", ",", "env_dict", ")", ":", "proc_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "proc_env", "[", "\"PATH\"", "]", "=", "\"{}:{}:.\"", ".", "format", "(", "proc_env", "[", "\"PATH\"", "]",...
30.114286
0.000919
def node_is_result_assignment(node: ast.AST) -> bool: """ Args: node: An ``ast`` node. Returns: bool: ``node`` corresponds to the code ``result =``, assignment to the ``result `` variable. Note: Performs a very weak test that the line starts with 'result =' rather ...
[ "def", "node_is_result_assignment", "(", "node", ":", "ast", ".", "AST", ")", "->", "bool", ":", "# `.first_token` is added by asttokens", "token", "=", "node", ".", "first_token", "# type: ignore", "return", "token", ".", "line", ".", "strip", "(", ")", ".", ...
30.0625
0.002016
def ISO8601Format(dt): """ Python datetime isoformat() has the following problems: - leave trailing 0 at the end of microseconds (violates XMLSchema rule) - tz print +00:00 instead of Z - Missing timezone offset for datetime without tzinfo """ isoStr = dt.strftime('%Y-%m-%dT%H:%M:%S') if dt.micr...
[ "def", "ISO8601Format", "(", "dt", ")", ":", "isoStr", "=", "dt", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S'", ")", "if", "dt", ".", "microsecond", ":", "isoStr", "+=", "(", "'.%06d'", "%", "dt", ".", "microsecond", ")", ".", "rstrip", "(", "'0'", ")",...
33.32
0.024504
def get_encodings(): ''' return a list of string encodings to try ''' encodings = [__salt_system_encoding__] try: sys_enc = sys.getdefaultencoding() except ValueError: # system encoding is nonstandard or malformed sys_enc = None if sys_enc and sys_enc not in encodings: ...
[ "def", "get_encodings", "(", ")", ":", "encodings", "=", "[", "__salt_system_encoding__", "]", "try", ":", "sys_enc", "=", "sys", ".", "getdefaultencoding", "(", ")", "except", "ValueError", ":", "# system encoding is nonstandard or malformed", "sys_enc", "=", "None...
25.5
0.002101
def get_resource(url): """ Issue a GET request to R25 with the given url and return a response as an etree element. """ response = R25_DAO().getURL(url, {"Accept": "text/xml"}) if response.status != 200: raise DataFailureException(url, response.status, response.data) tree = etree.fr...
[ "def", "get_resource", "(", "url", ")", ":", "response", "=", "R25_DAO", "(", ")", ".", "getURL", "(", "url", ",", "{", "\"Accept\"", ":", "\"text/xml\"", "}", ")", "if", "response", ".", "status", "!=", "200", ":", "raise", "DataFailureException", "(", ...
31.235294
0.001828
def get_sys(): ''' Get current system keyboard setting CLI Example: .. code-block:: bash salt '*' keyboard.get_sys ''' cmd = '' if salt.utils.path.which('localectl'): cmd = 'localectl | grep Keymap | sed -e"s/: /=/" -e"s/^[ \t]*//"' elif 'RedHat' in __grains__['os_fami...
[ "def", "get_sys", "(", ")", ":", "cmd", "=", "''", "if", "salt", ".", "utils", ".", "path", ".", "which", "(", "'localectl'", ")", ":", "cmd", "=", "'localectl | grep Keymap | sed -e\"s/: /=/\" -e\"s/^[ \\t]*//\"'", "elif", "'RedHat'", "in", "__grains__", "[", ...
32.454545
0.001361
def silence(cls, *modules, **kwargs): """ Args: *modules: Modules, or names of modules to silence (by setting their log level to WARNING or above) **kwargs: Pass as kwargs due to python 2.7, would be level=logging.WARNING otherwise """ level = kwargs.pop("level", ...
[ "def", "silence", "(", "cls", ",", "*", "modules", ",", "*", "*", "kwargs", ")", ":", "level", "=", "kwargs", ".", "pop", "(", "\"level\"", ",", "logging", ".", "WARNING", ")", "for", "mod", "in", "modules", ":", "name", "=", "mod", ".", "__name__"...
47.6
0.008247
def make_figure_hcurves(extractors, what): """ $ oq plot 'hcurves?kind=mean&imt=PGA&site_id=0' """ import matplotlib.pyplot as plt fig = plt.figure() got = {} # (calc_id, kind) -> curves for i, ex in enumerate(extractors): hcurves = ex.get(what) for kind in hcurves.kind: ...
[ "def", "make_figure_hcurves", "(", "extractors", ",", "what", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "fig", "=", "plt", ".", "figure", "(", ")", "got", "=", "{", "}", "# (calc_id, kind) -> curves", "for", "i", ",", "ex", "in", "enu...
35.37931
0.000949
def from_config(config): """ Generate a matrix from a configuration dictionary. """ matrix = {} variables = config.keys() for entries in product(*config.values()): combination = dict(zip(variables, entries)) include = True for value in combination.values(): fo...
[ "def", "from_config", "(", "config", ")", ":", "matrix", "=", "{", "}", "variables", "=", "config", ".", "keys", "(", ")", "for", "entries", "in", "product", "(", "*", "config", ".", "values", "(", ")", ")", ":", "combination", "=", "dict", "(", "z...
39.115385
0.001919
def signin(request, auth_form=AuthenticationForm, template_name='accounts/signin_form.html', redirect_field_name=REDIRECT_FIELD_NAME, redirect_signin_function=signin_redirect, extra_context=None): """ Signin using email or username with password. Signs a user in by combinin...
[ "def", "signin", "(", "request", ",", "auth_form", "=", "AuthenticationForm", ",", "template_name", "=", "'accounts/signin_form.html'", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "redirect_signin_function", "=", "signin_redirect", ",", "extra_context", "...
39.682927
0.0009
def get_grp_name(self, code): """Return group and name for an evidence code.""" nt_code = self.code2nt.get(code.strip(), None) if nt_code is not None: return nt_code.group, nt_code.name return "", ""
[ "def", "get_grp_name", "(", "self", ",", "code", ")", ":", "nt_code", "=", "self", ".", "code2nt", ".", "get", "(", "code", ".", "strip", "(", ")", ",", "None", ")", "if", "nt_code", "is", "not", "None", ":", "return", "nt_code", ".", "group", ",",...
39.666667
0.00823
def add_config(self, config, config_filename): """ Updates the content types database with the given configuration. :param config: The configuration dictionary. :param config_filename: The path of the configuration file. """ content_types = config...
[ "def", "add_config", "(", "self", ",", "config", ",", "config_filename", ")", ":", "content_types", "=", "config", "[", "'content-types'", "]", "comment_groups", "=", "config", "[", "'comment-groups'", "]", "self", ".", "_comment_groups", ".", "update", "(", "...
42.34375
0.001443
def ap(u, d, M, step, K, eps=0.001, leak=0, initCoeffs=None, N=None, returnCoeffs=False): """ Perform affine projection (AP) adaptive filtering on u to minimize error given by e=d-y, where y is the output of the adaptive filter. Parameters ---------- u : array-like One-dimensiona...
[ "def", "ap", "(", "u", ",", "d", ",", "M", ",", "step", ",", "K", ",", "eps", "=", "0.001", ",", "leak", "=", "0", ",", "initCoeffs", "=", "None", ",", "N", "=", "None", ",", "returnCoeffs", "=", "False", ")", ":", "# Check epsilon", "_pchk", "...
31.22093
0.000361
def get_conv_name(conv, truncate=False, show_unread=False): """Return a readable name for a conversation. If the conversation has a custom name, use the custom name. Otherwise, for one-to-one conversations, the name is the full name of the other user. For group conversations, the name is a comma-separa...
[ "def", "get_conv_name", "(", "conv", ",", "truncate", "=", "False", ",", "show_unread", "=", "False", ")", ":", "num_unread", "=", "len", "(", "[", "conv_event", "for", "conv_event", "in", "conv", ".", "unread_events", "if", "isinstance", "(", "conv_event", ...
43.540541
0.000607
def aliasByNode(requestContext, seriesList, *nodes): """ Takes a seriesList and applies an alias derived from one or more "node" portion/s of the target name. Node indices are 0 indexed. Example:: &target=aliasByNode(ganglia.*.cpu.load5,1) """ for series in seriesList: pathExp...
[ "def", "aliasByNode", "(", "requestContext", ",", "seriesList", ",", "*", "nodes", ")", ":", "for", "series", "in", "seriesList", ":", "pathExpression", "=", "_getFirstPathExpression", "(", "series", ".", "name", ")", "metric_pieces", "=", "pathExpression", ".",...
32.533333
0.001992
def ibm_to_ieee(ibm): ''' Translate IBM-format floating point numbers (as bytes) to IEEE 754 64-bit floating point format (as Python float). ''' # IBM mainframe: sign * 0.mantissa * 16 ** (exponent - 64) # Python uses IEEE: sign * 1.mantissa * 2 ** (exponent - 1023) # Pad-out to 8 bytes ...
[ "def", "ibm_to_ieee", "(", "ibm", ")", ":", "# IBM mainframe: sign * 0.mantissa * 16 ** (exponent - 64)", "# Python uses IEEE: sign * 1.mantissa * 2 ** (exponent - 1023)", "# Pad-out to 8 bytes if necessary. We expect 2 to 8 bytes, but", "# there's no need to check; bizarre sizes will cause a s...
36.885246
0.000433
def security_group_create(auth=None, **kwargs): ''' Create a security group. Use security_group_get to create default. project_id The project ID on which this security group will be created CLI Example: .. code-block:: bash salt '*' neutronng.security_group_create name=secgroup1 ...
[ "def", "security_group_create", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "keep_name", "=", "True", ",", "*", "*", "kwargs", ")", "return", "clo...
32.047619
0.001443
def _rendered_size(text, point_size, font_file): """ Return a (width, height) pair representing the size of *text* in English Metric Units (EMU) when rendered at *point_size* in the font defined in *font_file*. """ emu_per_inch = 914400 px_per_inch = 72.0 font = _Fonts.font(font_file, p...
[ "def", "_rendered_size", "(", "text", ",", "point_size", ",", "font_file", ")", ":", "emu_per_inch", "=", "914400", "px_per_inch", "=", "72.0", "font", "=", "_Fonts", ".", "font", "(", "font_file", ",", "point_size", ")", "px_width", ",", "px_height", "=", ...
32.1875
0.001887
def reset_password(self, action_token, signed_data): """Reset the user password. It was triggered by LOST-PASSWORD """ try: action = "reset-password" user = get_user_by_action_token(action, action_token) if not user or not user.signed_data_match(signed_data, action): ...
[ "def", "reset_password", "(", "self", ",", "action_token", ",", "signed_data", ")", ":", "try", ":", "action", "=", "\"reset-password\"", "user", "=", "get_user_by_action_token", "(", "action", ",", "action_token", ")", "if", "not", "user", "or", "not", "user"...
47.033333
0.001389
def initialize(self): """Create the laboratory directories.""" mkdir_p(self.archive_path) mkdir_p(self.bin_path) mkdir_p(self.codebase_path) mkdir_p(self.input_basepath)
[ "def", "initialize", "(", "self", ")", ":", "mkdir_p", "(", "self", ".", "archive_path", ")", "mkdir_p", "(", "self", ".", "bin_path", ")", "mkdir_p", "(", "self", ".", "codebase_path", ")", "mkdir_p", "(", "self", ".", "input_basepath", ")" ]
34
0.009569
def reshift(I): """ Transforms the given number element into a range of [-180, 180], which covers all possible angle differences. This method reshifts larger or smaller numbers that might be the output of other angular calculations into that range by adding or subtracting 360, respectively. To...
[ "def", "reshift", "(", "I", ")", ":", "# Output -180 to +180", "if", "type", "(", "I", ")", "==", "list", ":", "I", "=", "np", ".", "array", "(", "I", ")", "return", "(", "(", "I", "-", "180", ")", "%", "360", ")", "-", "180" ]
35.227273
0.013819
def table_columns(self): '''Yields column names.''' with self.conn.cursor() as cur: cur.execute(self.TABLE_COLUMNS_QUERY % self.database) for row in cur: yield row
[ "def", "table_columns", "(", "self", ")", ":", "with", "self", ".", "conn", ".", "cursor", "(", ")", "as", "cur", ":", "cur", ".", "execute", "(", "self", ".", "TABLE_COLUMNS_QUERY", "%", "self", ".", "database", ")", "for", "row", "in", "cur", ":", ...
35.666667
0.009132
def compute_layer(cls, data, params, layout): """ Calculate statistics for this layers This is the top-most computation method for the stat. It does not do any computations, but it knows how to verify the data, partition it call the next computation method and merge resu...
[ "def", "compute_layer", "(", "cls", ",", "data", ",", "params", ",", "layout", ")", ":", "check_required_aesthetics", "(", "cls", ".", "REQUIRED_AES", ",", "list", "(", "data", ".", "columns", ")", "+", "list", "(", "params", ".", "keys", "(", ")", ")"...
32.044444
0.001346
def gen_input_edit(sig_dic): ''' Editing for HTML input control. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_edit_download'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=si...
[ "def", "gen_input_edit", "(", "sig_dic", ")", ":", "if", "sig_dic", "[", "'en'", "]", "==", "'tag_file_download'", ":", "html_str", "=", "HTML_TPL_DICT", "[", "'input_edit_download'", "]", ".", "format", "(", "sig_en", "=", "sig_dic", "[", "'en'", "]", ",", ...
29.684211
0.001718
def do_map(*args, **kwargs): """Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it. The basic usage is mapping on an attribute. Imagine you have a list of users but you ar...
[ "def", "do_map", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "context", "=", "args", "[", "0", "]", "seq", "=", "args", "[", "1", "]", "if", "len", "(", "args", ")", "==", "2", "and", "'attribute'", "in", "kwargs", ":", "attribute", "=...
33.348837
0.002033
def discover_satellite(cli, deploy=True, timeout=5): """Looks to make sure a satellite exists, returns endpoint First makes sure we have dotcloud account credentials. Then it looks up the environment for the satellite app. This will contain host and port to construct an endpoint. However, if app doesn'...
[ "def", "discover_satellite", "(", "cli", ",", "deploy", "=", "True", ",", "timeout", "=", "5", ")", ":", "if", "not", "cli", ".", "global_config", ".", "loaded", ":", "cli", ".", "die", "(", "\"Please setup skypipe by running `skypipe --setup`\"", ")", "try", ...
42.217391
0.001007
def validate_spec(self, file: h5py.File) -> bool: """ Validate the LoomConnection object against the format specification. Args: file: h5py File object Returns: True if the file conforms to the specs, else False Remarks: Upon return, the instance attributes 'self.errors' and 'self.warnings' ...
[ "def", "validate_spec", "(", "self", ",", "file", ":", "h5py", ".", "File", ")", "->", "bool", ":", "matrix_types", "=", "[", "\"float16\"", ",", "\"float32\"", ",", "\"float64\"", ",", "\"int8\"", ",", "\"int16\"", ",", "\"int32\"", ",", "\"int64\"", ",",...
58.754237
0.020142
async def recv(self, nbytes: int = -1, **kwargs) -> bytes: ''' Receives some data on the socket. ''' return await asynclib.recv(self.sock, nbytes, **kwargs)
[ "async", "def", "recv", "(", "self", ",", "nbytes", ":", "int", "=", "-", "1", ",", "*", "*", "kwargs", ")", "->", "bytes", ":", "return", "await", "asynclib", ".", "recv", "(", "self", ".", "sock", ",", "nbytes", ",", "*", "*", "kwargs", ")" ]
36.8
0.010638
def setup_experiment(debug=True, verbose=False, app=None): """Check the app and, if it's compatible with Wallace, freeze its state.""" print_header() # Verify that the package is usable. log("Verifying that directory is compatible with Wallace...") if not verify_package(verbose=verbose): ra...
[ "def", "setup_experiment", "(", "debug", "=", "True", ",", "verbose", "=", "False", ",", "app", "=", "None", ")", ":", "print_header", "(", ")", "# Verify that the package is usable.", "log", "(", "\"Verifying that directory is compatible with Wallace...\"", ")", "if"...
28.992701
0.000487
def _kaiser(n, beta): """Independant Kaiser window For the definition of the Kaiser window, see A. V. Oppenheim & R. W. Schafer, "Discrete-Time Signal Processing". The continuous version of width n centered about x=0 is: .. note:: 2 times slower than scipy.kaiser """ from scipy.special import...
[ "def", "_kaiser", "(", "n", ",", "beta", ")", ":", "from", "scipy", ".", "special", "import", "iv", "as", "besselI", "m", "=", "n", "-", "1", "k", "=", "arange", "(", "0", ",", "m", ")", "k", "=", "2.", "*", "beta", "/", "m", "*", "sqrt", "...
30.266667
0.010684
def anneal(self, mode, matches, orig_matches): """ Perform post-processing. Return True when any changes were applied. """ changed = False def dupes_in_matches(): """Generator for index of matches that are dupes.""" items_by_path = config.engine.grou...
[ "def", "anneal", "(", "self", ",", "mode", ",", "matches", ",", "orig_matches", ")", ":", "changed", "=", "False", "def", "dupes_in_matches", "(", ")", ":", "\"\"\"Generator for index of matches that are dupes.\"\"\"", "items_by_path", "=", "config", ".", "engine", ...
39.864407
0.001245
def _get_upload_cmd(self, mirror=False): """Generate the S3 CLI upload command Args: mirror (bool): If true, uses a flat directory structure instead of nesting under a version. Returns: str: The full CLI command to run. """ if mirror: dest_ur...
[ "def", "_get_upload_cmd", "(", "self", ",", "mirror", "=", "False", ")", ":", "if", "mirror", ":", "dest_uri", "=", "self", ".", "s3_mirror_uri", "else", ":", "dest_uri", "=", "self", ".", "s3_version_uri", "cmd", "=", "'aws s3 sync {} {} --delete --exact-timest...
35.705882
0.008026
def dist_in_usersite(dist): """ Return True if given Distribution is installed in user site. """ if user_site: return normalize_path(dist_location(dist)).startswith(normalize_path(user_site)) else: return False
[ "def", "dist_in_usersite", "(", "dist", ")", ":", "if", "user_site", ":", "return", "normalize_path", "(", "dist_location", "(", "dist", ")", ")", ".", "startswith", "(", "normalize_path", "(", "user_site", ")", ")", "else", ":", "return", "False" ]
29.875
0.00813
def get_validation_fields(self): '''get_validation_fields returns a list of tuples (each a field) we only require the exp_id to coincide with the folder name, for the sake of reproducibility (given that all are served from sample image or Github organization). All other fields a...
[ "def", "get_validation_fields", "(", "self", ")", ":", "return", "[", "(", "\"name\"", ",", "1", ",", "str", ")", ",", "# required", "(", "\"time\"", ",", "1", ",", "int", ")", ",", "(", "\"url\"", ",", "1", ",", "str", ")", ",", "(", "\"descriptio...
44.75
0.025524
def preview(self, path=None, extra_context=None, publish=False): """ Serve up a project path """ try: self.call_hook("preview", self) if path is None: path = 'index.html' # Detect files filepath, mimetype = self._resolve_p...
[ "def", "preview", "(", "self", ",", "path", "=", "None", ",", "extra_context", "=", "None", ",", "publish", "=", "False", ")", ":", "try", ":", "self", ".", "call_hook", "(", "\"preview\"", ",", "self", ")", "if", "path", "is", "None", ":", "path", ...
36.671233
0.002183
def SETPO(cpu, dest): """ Sets byte if parity odd. :param cpu: current CPU. :param dest: destination operand. """ dest.write(Operators.ITEBV(dest.size, cpu.PF == False, 1, 0))
[ "def", "SETPO", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "PF", "==", "False", ",", "1", ",", "0", ")", ")" ]
27.125
0.013393
def _autofollow(api, action, dry_run): ''' Follow back or unfollow the friends/followers of user authenicated in 'api'. :api twitter_bot_utils.api.API :dry_run bool don't actually (un)follow, just report ''' try: # get the last 5000 followers followers = api.followers_ids() ...
[ "def", "_autofollow", "(", "api", ",", "action", ",", "dry_run", ")", ":", "try", ":", "# get the last 5000 followers", "followers", "=", "api", ".", "followers_ids", "(", ")", "# Get the last 5000 people user has followed", "friends", "=", "api", ".", "friends_ids"...
31.722222
0.002265
def is_armable(self): """ Returns ``True`` if the vehicle is ready to arm, false otherwise (``Boolean``). This attribute wraps a number of pre-arm checks, ensuring that the vehicle has booted, has a good GPS fix, and that the EKF pre-arm is complete. """ # check that mod...
[ "def", "is_armable", "(", "self", ")", ":", "# check that mode is not INITIALSING", "# check that we have a GPS fix", "# check that EKF pre-arm is complete", "return", "self", ".", "mode", "!=", "'INITIALISING'", "and", "(", "self", ".", "gps_0", ".", "fix_type", "is", ...
50.272727
0.008881
def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol)
[ "def", "dposition", "(", "self", ",", "node", ",", "dcol", "=", "0", ")", ":", "nnode", "=", "self", ".", "dnode", "(", "node", ")", "return", "(", "nnode", ".", "lineno", ",", "nnode", ".", "col_offset", "+", "dcol", ")" ]
41.75
0.011765
def curve4_bezier(p1, p2, p3, p4): """ Generate the vertices for a third order Bezier curve. The vertices returned by this function can be passed to a LineVisual or ArrowVisual. Parameters ---------- p1 : array 2D coordinates of the start point p2 : array 2D coordinates...
[ "def", "curve4_bezier", "(", "p1", ",", "p2", ",", "p3", ",", "p4", ")", ":", "x1", ",", "y1", "=", "p1", "x2", ",", "y2", "=", "p2", "x3", ",", "y3", "=", "p3", "x4", ",", "y4", "=", "p4", "points", "=", "[", "]", "_curve4_recursive_bezier", ...
23.918367
0.00082
def stationary_distribution(H, pi=None, P=None): """Computes the stationary distribution of a random walk on the given hypergraph using the iterative approach explained in the paper: Aurelien Ducournau, Alain Bretto, Random walks in directed hypergraphs and application to semi-supervised image segmentat...
[ "def", "stationary_distribution", "(", "H", ",", "pi", "=", "None", ",", "P", "=", "None", ")", ":", "if", "not", "isinstance", "(", "H", ",", "DirectedHypergraph", ")", ":", "raise", "TypeError", "(", "\"Algorithm only applicable to undirected hypergraphs\"", "...
43.469388
0.000459
def delete_table(self, table, retry=DEFAULT_RETRY, not_found_ok=False): """Delete a table See https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/delete Args: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`...
[ "def", "delete_table", "(", "self", ",", "table", ",", "retry", "=", "DEFAULT_RETRY", ",", "not_found_ok", "=", "False", ")", ":", "table", "=", "_table_arg_to_table_ref", "(", "table", ",", "default_project", "=", "self", ".", "project", ")", "if", "not", ...
42.290323
0.002237
def apply_dataset_vfunc( func, *args, signature, join='inner', dataset_join='exact', fill_value=_NO_FILL_VALUE, exclude_dims=frozenset(), keep_attrs=False ): """Apply a variable level function over Dataset, dict of DataArray, DataArray, Variable and/or ndarray objects. """ ...
[ "def", "apply_dataset_vfunc", "(", "func", ",", "*", "args", ",", "signature", ",", "join", "=", "'inner'", ",", "dataset_join", "=", "'exact'", ",", "fill_value", "=", "_NO_FILL_VALUE", ",", "exclude_dims", "=", "frozenset", "(", ")", ",", "keep_attrs", "="...
34.73913
0.000609
def analysis_info(self, webid): """ Show the status and most important attributes of an analysis. """ response = self._post(self.apiurl + "/v2/analysis/info", data={'apikey': self.apikey, 'webid': webid}) return self._raise_or_extract(response)
[ "def", "analysis_info", "(", "self", ",", "webid", ")", ":", "response", "=", "self", ".", "_post", "(", "self", ".", "apiurl", "+", "\"/v2/analysis/info\"", ",", "data", "=", "{", "'apikey'", ":", "self", ".", "apikey", ",", "'webid'", ":", "webid", "...
39.857143
0.010526
def topNBottomN(self, column=0, nPercent=10, grabTopN=-1): """ Given a column name or one column index, a percent N, this function will return the top or bottom N% of the values of the column of a frame. The column must be a numerical column. :param column: a string for column nam...
[ "def", "topNBottomN", "(", "self", ",", "column", "=", "0", ",", "nPercent", "=", "10", ",", "grabTopN", "=", "-", "1", ")", ":", "assert", "(", "nPercent", ">=", "0", ")", "and", "(", "nPercent", "<=", "100.0", ")", ",", "\"nPercent must be between 0....
53.133333
0.009858
def _upgrade(self): """ Upgrade the serialized object if necessary. Raises: FutureVersionError: file was written by a future version of the software. """ logging.debug("[FeedbackResultsSeries]._upgrade()") version = Version.fromstring(self.ver...
[ "def", "_upgrade", "(", "self", ")", ":", "logging", ".", "debug", "(", "\"[FeedbackResultsSeries]._upgrade()\"", ")", "version", "=", "Version", ".", "fromstring", "(", "self", ".", "version", ")", "logging", ".", "debug", "(", "'[FeedbackResultsSeries] version=%...
45.1
0.002172
def _Download(campaign, subcampaign): ''' Download all stars from a given campaign. This is called from ``missions/k2/download.pbs`` ''' # Are we doing a subcampaign? if subcampaign != -1: campaign = campaign + 0.1 * subcampaign # Get all star IDs for this campaign stars = [s[0...
[ "def", "_Download", "(", "campaign", ",", "subcampaign", ")", ":", "# Are we doing a subcampaign?", "if", "subcampaign", "!=", "-", "1", ":", "campaign", "=", "campaign", "+", "0.1", "*", "subcampaign", "# Get all star IDs for this campaign", "stars", "=", "[", "s...
39.911765
0.001439
def count(self): """Count the number of elements created, modified and deleted by the changeset and analyses if it is a possible import, mass modification or a mass deletion. """ xml = get_changeset(self.id) actions = [action.tag for action in xml.getchildren()] s...
[ "def", "count", "(", "self", ")", ":", "xml", "=", "get_changeset", "(", "self", ".", "id", ")", "actions", "=", "[", "action", ".", "tag", "for", "action", "in", "xml", ".", "getchildren", "(", ")", "]", "self", ".", "create", "=", "actions", ".",...
47.846154
0.002364
def to_json(self): """ Writes the complete Morse-Smale merge hierarchy to a string object. @ Out, a string object storing the entire merge hierarchy of all minima and maxima. """ capsule = {} capsule["Hierarchy"] = [] for ( dying, ...
[ "def", "to_json", "(", "self", ")", ":", "capsule", "=", "{", "}", "capsule", "[", "\"Hierarchy\"", "]", "=", "[", "]", "for", "(", "dying", ",", "(", "persistence", ",", "surviving", ",", "saddle", ")", ",", ")", "in", "self", ".", "merge_sequence",...
35.111111
0.002053
def ctmc(data, numstates, transintv=1.0, toltime=1e-8, debug=False): """ Continous Time Markov Chain Parameters ---------- data : list of lists A python list of N examples (e.g. rating histories of N companies, the event data of N basketball games, etc.). The i-th example consis...
[ "def", "ctmc", "(", "data", ",", "numstates", ",", "transintv", "=", "1.0", ",", "toltime", "=", "1e-8", ",", "debug", "=", "False", ")", ":", "# raise an exception if the data format is wrong", "if", "debug", ":", "datacheck", "(", "data", ",", "numstates", ...
27.897959
0.000353
def handle_import(self, options): """ Gets posts from Blogger. """ blog_id = options.get("blog_id") if blog_id is None: raise CommandError("Usage is import_blogger %s" % self.args) try: from gdata import service except ImportError: ...
[ "def", "handle_import", "(", "self", ",", "options", ")", ":", "blog_id", "=", "options", ".", "get", "(", "\"blog_id\"", ")", "if", "blog_id", "is", "None", ":", "raise", "CommandError", "(", "\"Usage is import_blogger %s\"", "%", "self", ".", "args", ")", ...
38.573034
0.001136
def print_exc_plus(stream=sys.stdout): '''print normal traceback information with some local arg values''' # code of this mothod is mainly from <Python Cookbook> write = stream.write # assert the mothod exists flush = stream.flush tp, value, tb = sys.exc_info() while tb.tb_next: tb = ...
[ "def", "print_exc_plus", "(", "stream", "=", "sys", ".", "stdout", ")", ":", "# code of this mothod is mainly from <Python Cookbook>", "write", "=", "stream", ".", "write", "# assert the mothod exists", "flush", "=", "stream", ".", "flush", "tp", ",", "value", ",", ...
32.8
0.000846
def python_value(self, value): """Convert the database value to a pythonic value.""" value = coerce_to_bytes(value) obj = HashValue(value) obj.field = self return obj
[ "def", "python_value", "(", "self", ",", "value", ")", ":", "value", "=", "coerce_to_bytes", "(", "value", ")", "obj", "=", "HashValue", "(", "value", ")", "obj", ".", "field", "=", "self", "return", "obj" ]
33.5
0.009709
def parseExtensionArgs(self, args, strict=False): """Parse the provider authentication policy arguments into the internal state of this object @param args: unqualified provider authentication policy arguments @param strict: Whether to raise an exception when bad data is ...
[ "def", "parseExtensionArgs", "(", "self", ",", "args", ",", "strict", "=", "False", ")", ":", "policies_str", "=", "args", ".", "get", "(", "'auth_policies'", ")", "if", "policies_str", "and", "policies_str", "!=", "'none'", ":", "self", ".", "auth_policies"...
36.72973
0.002151
def visible_to_user(self, element, *ignorable): """ Determines whether an element is visible to the user. A list of ignorable elements can be passed to this function. These would typically be things like invisible layers sitting atop other elements. This function ignores these el...
[ "def", "visible_to_user", "(", "self", ",", "element", ",", "*", "ignorable", ")", ":", "if", "not", "element", ".", "is_displayed", "(", ")", ":", "return", "False", "return", "self", ".", "driver", ".", "execute_script", "(", "\"\"\"\n var el = argume...
40.725806
0.000773
def reshape_range(tensor, i, j, shape): """Reshapes a tensor between dimensions i and j.""" t_shape = common_layers.shape_list(tensor) target_shape = t_shape[:i] + shape + t_shape[j:] return tf.reshape(tensor, target_shape)
[ "def", "reshape_range", "(", "tensor", ",", "i", ",", "j", ",", "shape", ")", ":", "t_shape", "=", "common_layers", ".", "shape_list", "(", "tensor", ")", "target_shape", "=", "t_shape", "[", ":", "i", "]", "+", "shape", "+", "t_shape", "[", "j", ":"...
45.4
0.021645
def format_next(self, i): """Get next format char.""" c = next(i) return self.format_references(next(i), i) if c == '\\' else c
[ "def", "format_next", "(", "self", ",", "i", ")", ":", "c", "=", "next", "(", "i", ")", "return", "self", ".", "format_references", "(", "next", "(", "i", ")", ",", "i", ")", "if", "c", "==", "'\\\\'", "else", "c" ]
29.6
0.013158
def _call_analysis_function(options, module): """ Call function from module and get result, using inputs from options Parameters ---------- options : dict Option names and values for analysis module : str Short name of module within macroeco containing analysis function Ret...
[ "def", "_call_analysis_function", "(", "options", ",", "module", ")", ":", "args", ",", "kwargs", "=", "_get_args_kwargs", "(", "options", ",", "module", ")", "return", "eval", "(", "\"%s.%s(*args, **kwargs)\"", "%", "(", "module", ",", "options", "[", "'analy...
34.130435
0.001239
def addIcon(self, iconActor, pos=3, size=0.08): """Add an inset icon mesh into the same renderer. :param pos: icon position in the range [1-4] indicating one of the 4 corners, or it can be a tuple (x,y) as a fraction of the renderer size. :param float size: size of the squar...
[ "def", "addIcon", "(", "self", ",", "iconActor", ",", "pos", "=", "3", ",", "size", "=", "0.08", ")", ":", "return", "addons", ".", "addIcon", "(", "iconActor", ",", "pos", ",", "size", ")" ]
42
0.009324
def visit_Name(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s id.""" return node.id
[ "def", "visit_Name", "(", "self", ",", "node", ":", "AST", ",", "dfltChaining", ":", "bool", "=", "True", ")", "->", "str", ":", "return", "node", ".", "id" ]
40
0.016393
async def delTrigger(self, iden): ''' Deletes a trigger from the cortex ''' trig = self.cell.triggers.get(iden) self._trig_auth_check(trig.get('useriden')) self.cell.triggers.delete(iden)
[ "async", "def", "delTrigger", "(", "self", ",", "iden", ")", ":", "trig", "=", "self", ".", "cell", ".", "triggers", ".", "get", "(", "iden", ")", "self", ".", "_trig_auth_check", "(", "trig", ".", "get", "(", "'useriden'", ")", ")", "self", ".", "...
32.714286
0.008511
def diffvalues(t1, t2, f): """ Return the difference between the values under the given field in the two tables, e.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['a', 1], ... ['b', 3]] >>> table2 = [['bar', 'foo'], ... ...
[ "def", "diffvalues", "(", "t1", ",", "t2", ",", "f", ")", ":", "t1v", "=", "set", "(", "values", "(", "t1", ",", "f", ")", ")", "t2v", "=", "set", "(", "values", "(", "t2", ",", "f", ")", ")", "return", "t2v", "-", "t1v", ",", "t1v", "-", ...
24.608696
0.001701
def _argsdicts( args, mydict ): """A utility generator that pads argument list and dictionary values, will only be called with len( args ) = 0, 1.""" if len( args ) == 0: args = None, elif len( args ) == 1: args = _totuple( args[0] ) else: raise Exception( "We should have n...
[ "def", "_argsdicts", "(", "args", ",", "mydict", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "args", "=", "None", ",", "elif", "len", "(", "args", ")", "==", "1", ":", "args", "=", "_totuple", "(", "args", "[", "0", "]", ")", "el...
30.571429
0.046433
def matrix_to_marching_cubes(matrix, pitch, origin): """ Convert an (n,m,p) matrix into a mesh, using marching_cubes. Parameters ----------- matrix: (n,m,p) bool, voxel matrix pitch: float, what pitch was the voxel matrix computed with origin: (3,) float, what is the origin of the voxel mat...
[ "def", "matrix_to_marching_cubes", "(", "matrix", ",", "pitch", ",", "origin", ")", ":", "from", "skimage", "import", "measure", "from", ".", "base", "import", "Trimesh", "matrix", "=", "np", ".", "asanyarray", "(", "matrix", ",", "dtype", "=", "np", ".", ...
33
0.000499
def fetch(clobber=False): """ Downloads the Marshall et al. (2006) dust map, which is based on 2MASS stellar photometry. Args: clobber (Optional[:obj:`bool`]): If ``True``, any existing file will be overwritten, even if it appears to match. If ``False`` (the default), :o...
[ "def", "fetch", "(", "clobber", "=", "False", ")", ":", "table_dir", "=", "os", ".", "path", ".", "join", "(", "data_dir", "(", ")", ",", "'marshall'", ")", "# Check if file already exists", "if", "not", "clobber", ":", "h5_fname", "=", "os", ".", "path"...
35.584906
0.002064
def copyMakeBorder(src, top, bot, left, right, *args, **kwargs): """Pad image border with OpenCV. Parameters ---------- src : NDArray source image top : int, required Top margin. bot : int, required Bottom margin. left : int, required Left margin. right :...
[ "def", "copyMakeBorder", "(", "src", ",", "top", ",", "bot", ",", "left", ",", "right", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_internal", ".", "_cvcopyMakeBorder", "(", "src", ",", "top", ",", "bot", ",", "left", ",", "rig...
34.627451
0.001652
def delete_with_retention(self, num_to_retain): """ Retain the num_to_retain most recent backups and delete all data before them. """ base_backup_sentinel_depth = self.layout.basebackups().count('/') + 1 # Sweep over base backup files, collecting sentinel files from ...
[ "def", "delete_with_retention", "(", "self", ",", "num_to_retain", ")", ":", "base_backup_sentinel_depth", "=", "self", ".", "layout", ".", "basebackups", "(", ")", ".", "count", "(", "'/'", ")", "+", "1", "# Sweep over base backup files, collecting sentinel files fro...
41.467532
0.000612
def create_api_docs(code_path, api_docs_path, max_depth=2): """Function for generating .rst file for all .py file in dir_path folder. :param code_path: Path of the source code. :type code_path: str :param api_docs_path: Path of the api documentation directory. :type api_docs_path: str :param ...
[ "def", "create_api_docs", "(", "code_path", ",", "api_docs_path", ",", "max_depth", "=", "2", ")", ":", "base_path", "=", "os", ".", "path", ".", "split", "(", "code_path", ")", "[", "0", "]", "for", "package", ",", "subpackages", ",", "candidate_files", ...
38.132075
0.000482
def wrap_non_picklable_objects(obj, keep_wrapper=True): """Wrapper for non-picklable object to use cloudpickle to serialize them. Note that this wrapper tends to slow down the serialization process as it is done with cloudpickle which is typically slower compared to pickle. The proper way to solve seri...
[ "def", "wrap_non_picklable_objects", "(", "obj", ",", "keep_wrapper", "=", "True", ")", ":", "if", "not", "cloudpickle", ":", "raise", "ImportError", "(", "\"could not import cloudpickle. Please install \"", "\"cloudpickle to allow extended serialization. \"", "\"(`pip install ...
48.178571
0.000727
def safe(f): """ A decorator that catches uncaught exceptions and return the response in JSON format (inspired on Superset code) """ def wraps(self, *args, **kwargs): try: return f(self, *args, **kwargs) except BadRequest as e: return self.response_400(messag...
[ "def", "safe", "(", "f", ")", ":", "def", "wraps", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "BadRequest", "as", "e", ":...
30.4375
0.001992
def _render_content(self): """Renders the content according to the ``content_format``.""" if self.content_format == "rst" and docutils_publish is not None: doc_parts = docutils_publish( source=self.raw_content, writer_name="html4css1" ) ...
[ "def", "_render_content", "(", "self", ")", ":", "if", "self", ".", "content_format", "==", "\"rst\"", "and", "docutils_publish", "is", "not", "None", ":", "doc_parts", "=", "docutils_publish", "(", "source", "=", "self", ".", "raw_content", ",", "writer_name"...
53.5625
0.002294
def uuidify(val): """Takes an integer and transforms it to a UUID format. returns: UUID formatted version of input. """ if uuidutils.is_uuid_like(val): return val else: try: int_val = int(val, 16) except ValueError: with excutils.save_and_reraise_exce...
[ "def", "uuidify", "(", "val", ")", ":", "if", "uuidutils", ".", "is_uuid_like", "(", "val", ")", ":", "return", "val", "else", ":", "try", ":", "int_val", "=", "int", "(", "val", ",", "16", ")", "except", "ValueError", ":", "with", "excutils", ".", ...
33.777778
0.0016