text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def set_level(self, level=1): """Set the logging level Parameters ---------- level : `int` or `bool` (optional, default: 1) If False or 0, prints WARNING and higher messages. If True or 1, prints INFO and higher messages. If 2 or higher, prints all me...
[ "def", "set_level", "(", "self", ",", "level", "=", "1", ")", ":", "if", "level", "is", "True", "or", "level", "==", "1", ":", "level", "=", "logging", ".", "INFO", "level_name", "=", "\"INFO\"", "elif", "level", "is", "False", "or", "level", "<=", ...
35.393939
0.001667
def resize(self, rows=None, cols=None): """Resizes the worksheet. Specify one of ``rows`` or ``cols``. :param rows: (optional) New number of rows. :type rows: int :param cols: (optional) New number columns. :type cols: int """ grid_properties = {} if row...
[ "def", "resize", "(", "self", ",", "rows", "=", "None", ",", "cols", "=", "None", ")", ":", "grid_properties", "=", "{", "}", "if", "rows", "is", "not", "None", ":", "grid_properties", "[", "'rowCount'", "]", "=", "rows", "if", "cols", "is", "not", ...
28.388889
0.001892
def add_global(self, globalvalue): """ Add a new global value. """ assert globalvalue.name not in self.globals self.globals[globalvalue.name] = globalvalue
[ "def", "add_global", "(", "self", ",", "globalvalue", ")", ":", "assert", "globalvalue", ".", "name", "not", "in", "self", ".", "globals", "self", ".", "globals", "[", "globalvalue", ".", "name", "]", "=", "globalvalue" ]
31.666667
0.010256
def build_attr_string(attrs, supported=True): '''Build a string that will turn any ANSI shell output the desired colour. attrs should be a list of keys into the term_attributes table. ''' if not supported: return '' if type(attrs) == str: attrs = [attrs] result =...
[ "def", "build_attr_string", "(", "attrs", ",", "supported", "=", "True", ")", ":", "if", "not", "supported", ":", "return", "''", "if", "type", "(", "attrs", ")", "==", "str", ":", "attrs", "=", "[", "attrs", "]", "result", "=", "'\\033['", "for", "a...
27.666667
0.002331
def set_version(db, name, major_version, minor_version): """ Set database migration version :param db: connetion object :param name: associated name :param major_version: integer major version of migration :param minor_version: integer minor version of migration """ ...
[ "def", "set_version", "(", "db", ",", "name", ",", "major_version", ",", "minor_version", ")", ":", "version", "=", "pack_version", "(", "major_version", ",", "minor_version", ")", "db", ".", "execute", "(", "SET_VERSION_SQL", ",", "dict", "(", "name", "=", ...
42.9
0.002283
def make_package_tree(matrix=None,labels=None,width=25,height=10,title=None,font_size=None): '''make package tree will make a dendrogram comparing a matrix of packages :param matrix: a pandas df of packages, with names in index and columns :param labels: a list of labels corresponding to row names, will be ...
[ "def", "make_package_tree", "(", "matrix", "=", "None", ",", "labels", "=", "None", ",", "width", "=", "25", ",", "height", "=", "10", ",", "title", "=", "None", ",", "font_size", "=", "None", ")", ":", "from", "matplotlib", "import", "pyplot", "as", ...
33.813953
0.008021
def ekcii(table, cindex, lenout=_default_len_out): """ Return attribute information about a column belonging to a loaded EK table, specifying the column by table and index. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekcii_c.html :param table: Name of table containing column. :type...
[ "def", "ekcii", "(", "table", ",", "cindex", ",", "lenout", "=", "_default_len_out", ")", ":", "table", "=", "stypes", ".", "stringToCharP", "(", "table", ")", "cindex", "=", "ctypes", ".", "c_int", "(", "cindex", ")", "lenout", "=", "ctypes", ".", "c_...
38.727273
0.001145
def file_exists(self, filename, shutit_pexpect_child=None, directory=False, note=None, loglevel=logging.DEBUG): """Return True if file exists on the target host, else False @param filename: Filename to determine the existence of...
[ "def", "file_exists", "(", "self", ",", "filename", ",", "shutit_pexpect_child", "=", "None", ",", "directory", "=", "False", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", "."...
40.136364
0.039823
def Wait(self, timeout): """Wait for the specified timeout.""" time.sleep(timeout - int(timeout)) # Split a long sleep interval into 1 second intervals so we can heartbeat. for _ in range(int(timeout)): time.sleep(1) if self.heart_beat_cb: self.heart_beat_cb()
[ "def", "Wait", "(", "self", ",", "timeout", ")", ":", "time", ".", "sleep", "(", "timeout", "-", "int", "(", "timeout", ")", ")", "# Split a long sleep interval into 1 second intervals so we can heartbeat.", "for", "_", "in", "range", "(", "int", "(", "timeout",...
28.9
0.010067
def missing(self, *args, **kwds): """Return whether an output is considered missing or not.""" from functools import reduce indexer = kwds['indexer'] freq = kwds['freq'] or generic.default_freq(**indexer) miss = (checks.missing_any(generic.select_time(da, **indexer), freq) for ...
[ "def", "missing", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "from", "functools", "import", "reduce", "indexer", "=", "kwds", "[", "'indexer'", "]", "freq", "=", "kwds", "[", "'freq'", "]", "or", "generic", ".", "default_freq", "...
40.666667
0.008021
def move_to_start(self, column_label): """Move a column to the first in order.""" self._columns.move_to_end(column_label, last=False) return self
[ "def", "move_to_start", "(", "self", ",", "column_label", ")", ":", "self", ".", "_columns", ".", "move_to_end", "(", "column_label", ",", "last", "=", "False", ")", "return", "self" ]
41.5
0.011834
def created(self): 'return datetime.datetime' return dateutil.parser.parse(str(self.f.currentRevision.created))
[ "def", "created", "(", "self", ")", ":", "return", "dateutil", ".", "parser", ".", "parse", "(", "str", "(", "self", ".", "f", ".", "currentRevision", ".", "created", ")", ")" ]
41.666667
0.015748
def parse_kwargs(kwargs, *keys, **keyvalues): """Return dict with keys from keys|keyvals and values from kwargs|keyvals. Existing keys are deleted from kwargs. >>> kwargs = {'one': 1, 'two': 2, 'four': 4} >>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5) >>> kwargs == {'one': 1...
[ "def", "parse_kwargs", "(", "kwargs", ",", "*", "keys", ",", "*", "*", "keyvalues", ")", ":", "result", "=", "{", "}", "for", "key", "in", "keys", ":", "if", "key", "in", "kwargs", ":", "result", "[", "key", "]", "=", "kwargs", "[", "key", "]", ...
28.08
0.001377
def transform(self, translation, theta, method='opencv'): """Create a new image by translating and rotating the current image. Parameters ---------- translation : :obj:`numpy.ndarray` of float The XY translation vector. theta : float Rotation angle in rad...
[ "def", "transform", "(", "self", ",", "translation", ",", "theta", ",", "method", "=", "'opencv'", ")", ":", "# transform channels separately", "color_im_tf", "=", "self", ".", "color", ".", "transform", "(", "translation", ",", "theta", ",", "method", "=", ...
39.043478
0.002174
def hold(name=None, pkgs=None, **kwargs): ''' Add a package lock. Specify packages to lock by exact name. root operate on a different root directory. CLI Example: .. code-block:: bash salt '*' pkg.add_lock <package name> salt '*' pkg.add_lock <package1>,<package2>,<packag...
[ "def", "hold", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "root", "=", "kwargs", ".", "get", "(", "'root'", ")", "if", "(", "not", "name", "and", "not", "pkgs", ")", "or", "(",...
26.978261
0.001555
def correlation_model(prediction, fm): """ wraps numpy.corrcoef functionality for model evaluation input: prediction: 2D Matrix the model salience map fm: fixmat Used to compute a FDM to which the prediction is compared. """ (_, r_x) = calc_resize_factor(pred...
[ "def", "correlation_model", "(", "prediction", ",", "fm", ")", ":", "(", "_", ",", "r_x", ")", "=", "calc_resize_factor", "(", "prediction", ",", "fm", ".", "image_size", ")", "fdm", "=", "compute_fdm", "(", "fm", ",", "scale_factor", "=", "r_x", ")", ...
33.923077
0.00883
def _ar_data(self, ar): """ Returns a dict that represents the analysis request """ if not ar: return {} if ar.portal_type == "AnalysisRequest": return {'obj': ar, 'id': ar.getId(), 'date_received': self.ulocalized_time( ...
[ "def", "_ar_data", "(", "self", ",", "ar", ")", ":", "if", "not", "ar", ":", "return", "{", "}", "if", "ar", ".", "portal_type", "==", "\"AnalysisRequest\"", ":", "return", "{", "'obj'", ":", "ar", ",", "'id'", ":", "ar", ".", "getId", "(", ")", ...
40.5
0.001723
def show_workspace(self, name): """Show specific workspace.""" if not self.workspace.exists(name): raise ValueError("Workspace `%s` doesn't exists." % name) color = Color() workspaces = self.workspace.list() self.logger.info("<== %s workspace ==>" % color.colored(na...
[ "def", "show_workspace", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "workspace", ".", "exists", "(", "name", ")", ":", "raise", "ValueError", "(", "\"Workspace `%s` doesn't exists.\"", "%", "name", ")", "color", "=", "Color", "(", ")", ...
41.058824
0.0014
def get_context_data(self, **kwargs): """ Returns the context data to provide to the template. """ context = super().get_context_data(**kwargs) context['forum_url'] = self.get_forum_url() return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", "[", "'forum_url'", "]", "=", "self", ".", "get_forum_url", "(", ")", "retur...
46
0.008547
def mendel_errors(parent_genotypes, progeny_genotypes): """Locate genotype calls not consistent with Mendelian transmission of alleles. Parameters ---------- parent_genotypes : array_like, int, shape (n_variants, 2, 2) Genotype calls for the two parents. progeny_genotypes : array_like, ...
[ "def", "mendel_errors", "(", "parent_genotypes", ",", "progeny_genotypes", ")", ":", "# setup", "parent_genotypes", "=", "GenotypeArray", "(", "parent_genotypes", ")", "progeny_genotypes", "=", "GenotypeArray", "(", "progeny_genotypes", ")", "check_ploidy", "(", "parent...
40.431373
0.000355
def channels_add_all(self, room_id, **kwargs): """Adds all of the users of the Rocket.Chat server to the channel.""" return self.__call_api_post('channels.addAll', roomId=room_id, kwargs=kwargs)
[ "def", "channels_add_all", "(", "self", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'channels.addAll'", ",", "roomId", "=", "room_id", ",", "kwargs", "=", "kwargs", ")" ]
69.333333
0.014286
def clean_key_name(key): """ Makes ``key`` a valid and appropriate SQL column name: 1. Replaces illegal characters in column names with ``_`` 2. Prevents name from beginning with a digit (prepends ``_``) 3. Lowercases name. If you want case-sensitive table or column names, you are a bad pers...
[ "def", "clean_key_name", "(", "key", ")", ":", "result", "=", "_illegal_in_column_name", ".", "sub", "(", "\"_\"", ",", "key", ".", "strip", "(", ")", ")", "if", "result", "[", "0", "]", ".", "isdigit", "(", ")", ":", "result", "=", "'_%s'", "%", "...
32.823529
0.001742
def draw(self, painter, options, widget): """ Handle the draw event for the widget. """ self.declaration.draw(painter, options, widget)
[ "def", "draw", "(", "self", ",", "painter", ",", "options", ",", "widget", ")", ":", "self", ".", "declaration", ".", "draw", "(", "painter", ",", "options", ",", "widget", ")" ]
31.2
0.0125
def get_exclude_regions(items): """Retrieve regions to exclude from a set of items. Includes back compatibility for older custom ways of specifying different exclusions. """ def _get_sample_excludes(d): excludes = dd.get_exclude_regions(d) # back compatible if tz.get_in(("co...
[ "def", "get_exclude_regions", "(", "items", ")", ":", "def", "_get_sample_excludes", "(", "d", ")", ":", "excludes", "=", "dd", ".", "get_exclude_regions", "(", "d", ")", "# back compatible", "if", "tz", ".", "get_in", "(", "(", "\"config\"", ",", "\"algorit...
37
0.001883
def runfile(filename, args=None, wdir=None, namespace=None, post_mortem=False): """ Run filename args: command line arguments (string) wdir: working directory post_mortem: boolean, whether to enter post-mortem mode on error """ try: filename = filename.decode('utf-8') except (Uni...
[ "def", "runfile", "(", "filename", ",", "args", "=", "None", ",", "wdir", "=", "None", ",", "namespace", "=", "None", ",", "post_mortem", "=", "False", ")", ":", "try", ":", "filename", "=", "filename", ".", "decode", "(", "'utf-8'", ")", "except", "...
33.156863
0.000574
def _parse(yr, mo, day): """ Basic parser to deal with date format of the Kp file. """ yr = '20'+yr yr = int(yr) mo = int(mo) day = int(day) return pds.datetime(yr, mo, day)
[ "def", "_parse", "(", "yr", ",", "mo", ",", "day", ")", ":", "yr", "=", "'20'", "+", "yr", "yr", "=", "int", "(", "yr", ")", "mo", "=", "int", "(", "mo", ")", "day", "=", "int", "(", "day", ")", "return", "pds", ".", "datetime", "(", "yr", ...
20.1
0.009524
def _validate(self): """Assure this is a valid VLAN header instance.""" if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ): raise UnpackException return
[ "def", "_validate", "(", "self", ")", ":", "if", "self", ".", "tpid", ".", "value", "not", "in", "(", "EtherType", ".", "VLAN", ",", "EtherType", ".", "VLAN_QINQ", ")", ":", "raise", "UnpackException", "return" ]
39.4
0.00995
def rest_put(url, data, timeout): '''Call rest put method''' try: response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) return response except Exception as e: print('Get ex...
[ "def", "rest_put", "(", "url", ",", "data", ",", "timeout", ")", ":", "try", ":", "response", "=", "requests", ".", "put", "(", "url", ",", "headers", "=", "{", "'Accept'", ":", "'application/json'", ",", "'Content-Type'", ":", "'application/json'", "}", ...
44.222222
0.009852
def get_analysisrequests_section(self): """ Returns the section dictionary related with Analysis Requests, that contains some informative panels (like ARs to be verified, ARs to be published, etc.) """ out = [] catalog = getToolByName(self.context, CATALOG_ANALYSI...
[ "def", "get_analysisrequests_section", "(", "self", ")", ":", "out", "=", "[", "]", "catalog", "=", "getToolByName", "(", "self", ".", "context", ",", "CATALOG_ANALYSIS_REQUEST_LISTING", ")", "query", "=", "{", "'portal_type'", ":", "\"AnalysisRequest\"", ",", "...
44.858586
0.002203
def get_upload_params(request): """Authorises user and validates given file properties.""" file_name = request.POST['name'] file_type = request.POST['type'] file_size = int(request.POST['size']) dest = get_s3direct_destinations().get( request.POST.get('dest', None), None) if not dest: ...
[ "def", "get_upload_params", "(", "request", ")", ":", "file_name", "=", "request", ".", "POST", "[", "'name'", "]", "file_type", "=", "request", ".", "POST", "[", "'type'", "]", "file_size", "=", "int", "(", "request", ".", "POST", "[", "'size'", "]", ...
41.4125
0.00059
def darker(self, color, step): """returns color darker by step (where step is in range 0..255)""" hls = colorsys.rgb_to_hls(*self.rgb(color)) return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2])
[ "def", "darker", "(", "self", ",", "color", ",", "step", ")", ":", "hls", "=", "colorsys", ".", "rgb_to_hls", "(", "*", "self", ".", "rgb", "(", "color", ")", ")", "return", "colorsys", ".", "hls_to_rgb", "(", "hls", "[", "0", "]", ",", "hls", "[...
55
0.008969
def _get_funcs(self): """ Returns a 32-bit value stating supported I2C functions. :rtype: int """ f = c_uint32() ioctl(self.fd, I2C_FUNCS, f) return f.value
[ "def", "_get_funcs", "(", "self", ")", ":", "f", "=", "c_uint32", "(", ")", "ioctl", "(", "self", ".", "fd", ",", "I2C_FUNCS", ",", "f", ")", "return", "f", ".", "value" ]
22.777778
0.00939
def send_templated_email(recipients, template_path, context=None, from_email=settings.DEFAULT_FROM_EMAIL, fail_silently=False, extra_headers=None): """ recipients can be either a list of emails or a list of users, if it is users the system will change to the l...
[ "def", "send_templated_email", "(", "recipients", ",", "template_path", ",", "context", "=", "None", ",", "from_email", "=", "settings", ".", "DEFAULT_FROM_EMAIL", ",", "fail_silently", "=", "False", ",", "extra_headers", "=", "None", ")", ":", "recipient_pks", ...
49.933333
0.009174
def EXt(self, xp): """compute E[x_t|x_{t-1}]""" return (1. - self.rho) * self.mu + self.rho * xp
[ "def", "EXt", "(", "self", ",", "xp", ")", ":", "return", "(", "1.", "-", "self", ".", "rho", ")", "*", "self", ".", "mu", "+", "self", ".", "rho", "*", "xp" ]
36.666667
0.017857
def get_group_partition(group, partition_count): """Given a group name, return the partition number of the consumer offset topic containing the data associated to that group.""" def java_string_hashcode(s): h = 0 for c in s: h = (31 * h + ord(c)) & 0xFFFFFFFF return ((h +...
[ "def", "get_group_partition", "(", "group", ",", "partition_count", ")", ":", "def", "java_string_hashcode", "(", "s", ")", ":", "h", "=", "0", "for", "c", "in", "s", ":", "h", "=", "(", "31", "*", "h", "+", "ord", "(", "c", ")", ")", "&", "0xFFF...
45.888889
0.002375
def to_sympy_matrix(value): """ Converts value to a `sympy.Matrix` object, if possible. Leaves the value as `sympy.Matrix` if it already was :param value: value to convert :return: :rtype: `sympy.Matrix` """ if isinstance(value, sympy.Matrix): return value try: return...
[ "def", "to_sympy_matrix", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "sympy", ".", "Matrix", ")", ":", "return", "value", "try", ":", "return", "sympy", ".", "Matrix", "(", "value", ")", "except", "ValueError", "as", "original_exception...
37.88
0.00206
def intranges_contain(int_, ranges): """Determine if `int_` falls into one of the ranges in `ranges`.""" tuple_ = _encode_range(int_, 0) pos = bisect.bisect_left(ranges, tuple_) # we could be immediately ahead of a tuple (start, end) # with start < int_ <= end if pos > 0: left, right = _...
[ "def", "intranges_contain", "(", "int_", ",", "ranges", ")", ":", "tuple_", "=", "_encode_range", "(", "int_", ",", "0", ")", "pos", "=", "bisect", ".", "bisect_left", "(", "ranges", ",", "tuple_", ")", "# we could be immediately ahead of a tuple (start, end)", ...
36.625
0.001664
def com_google_fonts_check_name_unwanted_chars(ttFont): """Substitute copyright, registered and trademark symbols in name table entries.""" failed = False replacement_map = [("\u00a9", '(c)'), ("\u00ae", '(r)'), ("\u2122", '(tm)')] for name in ttFont['name'].names:...
[ "def", "com_google_fonts_check_name_unwanted_chars", "(", "ttFont", ")", ":", "failed", "=", "False", "replacement_map", "=", "[", "(", "\"\\u00a9\"", ",", "'(c)'", ")", ",", "(", "\"\\u00ae\"", ",", "'(r)'", ")", ",", "(", "\"\\u2122\"", ",", "'(tm)'", ")", ...
45.263158
0.009112
def typo(src, tar, metric='euclidean', cost=(1, 1, 0.5, 0.5), layout='QWERTY'): """Return the typo distance between two strings. This is a wrapper for :py:meth:`Typo.typo`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison m...
[ "def", "typo", "(", "src", ",", "tar", ",", "metric", "=", "'euclidean'", ",", "cost", "=", "(", "1", ",", "1", ",", "0.5", ",", "0.5", ")", ",", "layout", "=", "'QWERTY'", ")", ":", "return", "Typo", "(", ")", ".", "dist_abs", "(", "src", ",",...
27.983333
0.000575
def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, **kwargs): """ Present the PTY of the container inside the current process. This is just a wrapper for PseudoTerminal(client, container).start() """ PseudoTerminal(client, container, interactive=interactive, stdou...
[ "def", "start", "(", "client", ",", "container", ",", "interactive", "=", "True", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ",", "stdin", "=", "None", ",", "*", "*", "kwargs", ")", ":", "PseudoTerminal", "(", "client", ",", "container", ...
45.75
0.008043
def visit_Assign(self, node, **kwargs): """Visit assignments in the correct order.""" self.visit(node.node, **kwargs) self.visit(node.target, **kwargs)
[ "def", "visit_Assign", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "self", ".", "visit", "(", "node", ".", "node", ",", "*", "*", "kwargs", ")", "self", ".", "visit", "(", "node", ".", "target", ",", "*", "*", "kwargs", ")" ]
43
0.011429
def wcspt_to_datapt(self, wcspt, coords='data', naxispath=None): """ Convert multiple WCS to data points. Parameters ---------- wcspt : array-like WCS coordinates in the format of ``[[ra0, dec0, ...], [ra1, dec1, ...], ..., [ran, decn, ...]]``. c...
[ "def", "wcspt_to_datapt", "(", "self", ",", "wcspt", ",", "coords", "=", "'data'", ",", "naxispath", "=", "None", ")", ":", "# We provide a list comprehension version for WCS packages that", "# don't support array operations.", "if", "naxispath", ":", "raise", "NotImpleme...
33.7
0.001923
def scramble_string(s, key): """ s is the puzzle's solution in column-major order, omitting black squares: i.e. if the puzzle is: C A T # # A # # R solution is CATAR Key is a 4-digit number in the range 1000 <= key <= 9999 """ key = key_digits(key) for k in key...
[ "def", "scramble_string", "(", "s", ",", "key", ")", ":", "key", "=", "key_digits", "(", "key", ")", "for", "k", "in", "key", ":", "# foreach digit in the key", "s", "=", "shift", "(", "s", ",", "key", ")", "# for each char by each digit in the key in sequence...
27.95
0.00173
def KernelVersion(): """Gets the kernel version as string, eg. "5.1.2600". Returns: The kernel version, or "unknown" in the case of failure. """ rtl_osversioninfoexw = RtlOSVersionInfoExw() try: RtlGetVersion(rtl_osversioninfoexw) except OSError: return "unknown" return "%d.%d.%d" % (rtl_osv...
[ "def", "KernelVersion", "(", ")", ":", "rtl_osversioninfoexw", "=", "RtlOSVersionInfoExw", "(", ")", "try", ":", "RtlGetVersion", "(", "rtl_osversioninfoexw", ")", "except", "OSError", ":", "return", "\"unknown\"", "return", "\"%d.%d.%d\"", "%", "(", "rtl_osversioni...
30.266667
0.012821
def hex_color_to_rgba(hex_color, normalize_to=255): ''' Convert a hex-formatted number (i.e., `"#RGB[A]"` or `"#RRGGBB[AA]"`) to an RGBA tuple (i.e., `(<r>, <g>, <b>, <a>)`). Args: hex_color (str) : hex-formatted number (e.g., `"#2fc"`, `"#3c2f8611"`) normalize_to (int, float) : Factor...
[ "def", "hex_color_to_rgba", "(", "hex_color", ",", "normalize_to", "=", "255", ")", ":", "color_pattern_one_digit", "=", "(", "r'#(?P<R>[\\da-fA-F])(?P<G>[\\da-fA-F])'", "r'(?P<B>[\\da-fA-F])(?P<A>[\\da-fA-F])?'", ")", "color_pattern_two_digit", "=", "(", "r'#(?P<R>[\\da-fA-F]{...
37.4
0.000651
def QA_SU_save_future_day(client=DATABASE, ui_log=None, ui_progress=None): ''' save future_day 保存日线数据 :param client: :param ui_log: 给GUI qt 界面使用 :param ui_progress: 给GUI qt 界面使用 :param ui_progress_int_value: 给GUI qt 界面使用 :return: ''' future_list = [ item for item in QA_...
[ "def", "QA_SU_save_future_day", "(", "client", "=", "DATABASE", ",", "ui_log", "=", "None", ",", "ui_progress", "=", "None", ")", ":", "future_list", "=", "[", "item", "for", "item", "in", "QA_fetch_get_future_list", "(", ")", ".", "code", ".", "unique", "...
32.801887
0.000838
def get_argval(argstr, type_=None, default=None): r""" Returns a value of an argument specified on the command line after some flag CommandLine: python -c "import utool; print([(type(x), x) for x in [utool.get_argval('--quest')]])" --quest="holy grail" python -c "import utool; print([(type(...
[ "def", "get_argval", "(", "argstr", ",", "type_", "=", "None", ",", "default", "=", "None", ")", ":", "arg_after", "=", "default", "if", "type_", "is", "bool", ":", "arg_after", "=", "False", "if", "default", "is", "None", "else", "default", "try", ":"...
42.878049
0.000556
def create_mask(indexer, shape, chunks_hint=None): """Create a mask for indexing with a fill-value. Parameters ---------- indexer : ExplicitIndexer Indexer with -1 in integer or ndarray value to indicate locations in the result that should be masked. shape : tuple Shape of t...
[ "def", "create_mask", "(", "indexer", ",", "shape", ",", "chunks_hint", "=", "None", ")", ":", "if", "isinstance", "(", "indexer", ",", "OuterIndexer", ")", ":", "key", "=", "_outer_to_vectorized_indexer", "(", "indexer", ",", "shape", ")", ".", "tuple", "...
38.340909
0.000578
def get_endtime(jid): ''' Retrieve the stored endtime for a given job Returns False if no endtime is present ''' jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type']) etpath = os.path.join(jid_dir, ENDTIME) if not os.path.exists(etpath): return False with salt...
[ "def", "get_endtime", "(", "jid", ")", ":", "jid_dir", "=", "salt", ".", "utils", ".", "jid", ".", "jid_dir", "(", "jid", ",", "_job_dir", "(", ")", ",", "__opts__", "[", "'hash_type'", "]", ")", "etpath", "=", "os", ".", "path", ".", "join", "(", ...
34.461538
0.002174
def load_and_set_file_content(self, file_system_path): """ Implements the abstract method of the ExternalEditor class. """ semantic_data = load_data_file(os.path.join(file_system_path, storage.SEMANTIC_DATA_FILE)) self.model.state.semantic_data = semantic_data
[ "def", "load_and_set_file_content", "(", "self", ",", "file_system_path", ")", ":", "semantic_data", "=", "load_data_file", "(", "os", ".", "path", ".", "join", "(", "file_system_path", ",", "storage", ".", "SEMANTIC_DATA_FILE", ")", ")", "self", ".", "model", ...
57.6
0.010274
def _build_block_element_list(self): """Return a list of block elements, ordered from highest priority to lowest. """ return sorted( [e for e in self.block_elements.values() if not e.virtual], key=lambda e: e.priority, reverse=True )
[ "def", "_build_block_element_list", "(", "self", ")", ":", "return", "sorted", "(", "[", "e", "for", "e", "in", "self", ".", "block_elements", ".", "values", "(", ")", "if", "not", "e", ".", "virtual", "]", ",", "key", "=", "lambda", "e", ":", "e", ...
36.75
0.009967
def add_crop_resize(self, name, input_names, output_name, target_height=1, target_width=1, mode='STRICT_ALIGN_ENDPOINTS_MODE', normalized_roi=False, box_indices_mode='CORNERS_HEIGHT_FIRST', spatial_scale=1.0)...
[ "def", "add_crop_resize", "(", "self", ",", "name", ",", "input_names", ",", "output_name", ",", "target_height", "=", "1", ",", "target_width", "=", "1", ",", "mode", "=", "'STRICT_ALIGN_ENDPOINTS_MODE'", ",", "normalized_roi", "=", "False", ",", "box_indices_m...
62.831579
0.009896
def register(self, result): """ Register an EventualResult. May be called in any thread. """ if self._stopped: raise ReactorStopped() self._results.add(result)
[ "def", "register", "(", "self", ",", "result", ")", ":", "if", "self", ".", "_stopped", ":", "raise", "ReactorStopped", "(", ")", "self", ".", "_results", ".", "add", "(", "result", ")" ]
23.555556
0.009091
def save_user(self, request, user, form, commit=True): """ Saves a new `User` instance using information provided in the signup form. """ from .utils import user_username, user_email, user_field data = form.cleaned_data first_name = data.get('first_name') ...
[ "def", "save_user", "(", "self", ",", "request", ",", "user", ",", "form", ",", "commit", "=", "True", ")", ":", "from", ".", "utils", "import", "user_username", ",", "user_email", ",", "user_field", "data", "=", "form", ".", "cleaned_data", "first_name", ...
34.75
0.002
def get(self, key, default) -> Union[Uniform, UniformBlock, Subroutine, Attribute, Varying]: ''' Returns a Uniform, UniformBlock, Subroutine, Attribute or Varying. Args: default: This is the value to be returned in case key does not exist. Returns: ...
[ "def", "get", "(", "self", ",", "key", ",", "default", ")", "->", "Union", "[", "Uniform", ",", "UniformBlock", ",", "Subroutine", ",", "Attribute", ",", "Varying", "]", ":", "return", "self", ".", "_members", ".", "get", "(", "key", ",", "default", ...
38.923077
0.009653
def get(self, params, **options): """Dispatches a GET request to /events of the API to get a set of recent changes to a resource.""" options = self.client._merge_options({ 'full_payload': True }) return self.client.get('/events', params, **options)
[ "def", "get", "(", "self", ",", "params", ",", "*", "*", "options", ")", ":", "options", "=", "self", ".", "client", ".", "_merge_options", "(", "{", "'full_payload'", ":", "True", "}", ")", "return", "self", ".", "client", ".", "get", "(", "'/events...
67.25
0.018382
def __split_file(self): ''' Splits combined SAR output file (in ASCII format) in order to extract info we need for it, in the format we want. :return: ``List``-style of SAR file sections separated by the type of info they contain (SAR file sections) without ...
[ "def", "__split_file", "(", "self", ")", ":", "# Filename passed checks through __init__", "if", "(", "self", ".", "__filename", "and", "os", ".", "access", "(", "self", ".", "__filename", ",", "os", ".", "R_OK", ")", ")", ":", "fhandle", "=", "None", "try...
33.591837
0.001771
def model_fields_form_factory(model): ''' Creates a form for specifying fields from a model to display. ''' fields = model._meta.get_fields() choices = [] for field in fields: if hasattr(field, "verbose_name"): choices.append((field.name, field.verbose_name)) class ModelFields...
[ "def", "model_fields_form_factory", "(", "model", ")", ":", "fields", "=", "model", ".", "_meta", ".", "get_fields", "(", ")", "choices", "=", "[", "]", "for", "field", "in", "fields", ":", "if", "hasattr", "(", "field", ",", "\"verbose_name\"", ")", ":"...
27.058824
0.002101
def format(self, link_resolver, output): """ Banana banana """ if not output: return self.tree.format(link_resolver, output, self.extensions) self.formatted_signal(self)
[ "def", "format", "(", "self", ",", "link_resolver", ",", "output", ")", ":", "if", "not", "output", ":", "return", "self", ".", "tree", ".", "format", "(", "link_resolver", ",", "output", ",", "self", ".", "extensions", ")", "self", ".", "formatted_signa...
24.666667
0.008696
def _parse_impact_header(hdr_dict): """Parse fields for impact, taken from vcf2db """ desc = hdr_dict["Description"] if hdr_dict["ID"] == "ANN": parts = [x.strip("\"'") for x in re.split("\s*\|\s*", desc.split(":", 1)[1].strip('" '))] elif hdr_dict["ID"] == "EFF": parts = [x.strip(" ...
[ "def", "_parse_impact_header", "(", "hdr_dict", ")", ":", "desc", "=", "hdr_dict", "[", "\"Description\"", "]", "if", "hdr_dict", "[", "\"ID\"", "]", "==", "\"ANN\"", ":", "parts", "=", "[", "x", ".", "strip", "(", "\"\\\"'\"", ")", "for", "x", "in", "...
48.533333
0.01752
def rbh_network(id2desc, rbh, file_name, thresholds = [False, False, False, False]): """ make the network based on rbhs and score thresholds """ g = nx.Graph() # network graph for storing rbhs filtered = {} e_thresh, bit_thresh, length_thresh, norm_thresh = thresholds for genome in rbh: ...
[ "def", "rbh_network", "(", "id2desc", ",", "rbh", ",", "file_name", ",", "thresholds", "=", "[", "False", ",", "False", ",", "False", ",", "False", "]", ")", ":", "g", "=", "nx", ".", "Graph", "(", ")", "# network graph for storing rbhs", "filtered", "="...
47.737705
0.016487
def timeit(stat_tracker_func, name): """ Pass in a function and the name of the stat Will time the function that this is a decorator to and send the `name` as well as the value (in seconds) to `stat_tracker_func` `stat_tracker_func` can be used to either print out the data or save it """ de...
[ "def", "timeit", "(", "stat_tracker_func", ",", "name", ")", ":", "def", "_timeit", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "result", "=", "func", ...
31.263158
0.001634
def _find_monitor(monitors, handle): """Find all devices and events with a given monitor installed.""" found_devs = set() found_events = set() for conn_string, device in monitors.items(): for event, handles in device.items(): if handle in handles: found_events.add(e...
[ "def", "_find_monitor", "(", "monitors", ",", "handle", ")", ":", "found_devs", "=", "set", "(", ")", "found_events", "=", "set", "(", ")", "for", "conn_string", ",", "device", "in", "monitors", ".", "items", "(", ")", ":", "for", "event", ",", "handle...
30.307692
0.002463
def render(self): """Render html page and atom feed""" context = GLOBAL_TEMPLATE_CONTEXT.copy() context['tag'] = self entries = list(self.entries) entries.sort(key=operator.attrgetter('date'), reverse=True) context['entries'] = entries # render html page ...
[ "def", "render", "(", "self", ")", ":", "context", "=", "GLOBAL_TEMPLATE_CONTEXT", ".", "copy", "(", ")", "context", "[", "'tag'", "]", "=", "self", "entries", "=", "list", "(", "self", ".", "entries", ")", "entries", ".", "sort", "(", "key", "=", "o...
41.25
0.00237
def get_windows_tz(iana_tz): """ Returns a valid windows TimeZone from a given pytz TimeZone (Iana/Olson Timezones) Note: Windows Timezones are SHIT!... no ... really THEY ARE HOLY FUCKING SHIT!. """ timezone = IANA_TO_WIN.get( iana_tz.zone if isinstance(iana_tz, tzinfo) else iana_tz) ...
[ "def", "get_windows_tz", "(", "iana_tz", ")", ":", "timezone", "=", "IANA_TO_WIN", ".", "get", "(", "iana_tz", ".", "zone", "if", "isinstance", "(", "iana_tz", ",", "tzinfo", ")", "else", "iana_tz", ")", "if", "timezone", "is", "None", ":", "raise", "pyt...
34.461538
0.002174
def run(self, options): """ In general, you don't need to overwrite this method. :param options: :return: """ self.set_signal() self.check_exclusive_mode() slot = self.Handle(self) # start thread i = 0 while i < options.threads:...
[ "def", "run", "(", "self", ",", "options", ")", ":", "self", ".", "set_signal", "(", ")", "self", ".", "check_exclusive_mode", "(", ")", "slot", "=", "self", ".", "Handle", "(", "self", ")", "# start thread", "i", "=", "0", "while", "i", "<", "option...
24.916667
0.002146
def register_plugin(self, plugin): """ Register a new plugin with the PluginManager. `plugin` is a subclass of scruffy's Plugin class. This is called by __init__(), but may also be called by the debugger host to load a specific plugin at runtime. """ if hasattr(...
[ "def", "register_plugin", "(", "self", ",", "plugin", ")", ":", "if", "hasattr", "(", "plugin", ",", "'initialise'", ")", ":", "plugin", ".", "initialise", "(", ")", "if", "self", ".", "valid_api_plugin", "(", "plugin", ")", ":", "log", ".", "debug", "...
46.933333
0.002088
def create_key_bindings(editor): """ Create custom key bindings. This starts with the key bindings, defined by `prompt-toolkit`, but adds the ones which are specific for the editor. """ kb = KeyBindings() # Filters. @Condition def vi_buffer_focussed(): app = get_app() ...
[ "def", "create_key_bindings", "(", "editor", ")", ":", "kb", "=", "KeyBindings", "(", ")", "# Filters.", "@", "Condition", "def", "vi_buffer_focussed", "(", ")", ":", "app", "=", "get_app", "(", ")", "if", "app", ".", "layout", ".", "has_focus", "(", "ed...
29.838926
0.001306
def ida_spawn(ida_binary, filename, port=18861, mode='oneshot', processor_type=None, logfile=None): """ Open IDA on the the file we want to analyse. :param ida_binary: The binary name or path to ida :param filename: The filename to open in IDA :param port: The port on which...
[ "def", "ida_spawn", "(", "ida_binary", ",", "filename", ",", "port", "=", "18861", ",", "mode", "=", "'oneshot'", ",", "processor_type", "=", "None", ",", "logfile", "=", "None", ")", ":", "ida_progname", "=", "_which", "(", "ida_binary", ")", "if", "ida...
39.419355
0.002395
def save_file(path, data, readable=False): """ Save to file :param path: File path to save :type path: str | unicode :param data: Data to save :type data: None | int | float | str | unicode | list | dict :param readable: Format file to be human readable (default: False) :type readable: ...
[ "def", "save_file", "(", "path", ",", "data", ",", "readable", "=", "False", ")", ":", "if", "not", "path", ":", "IOError", "(", "\"No path specified to save\"", ")", "try", ":", "with", "io", ".", "open", "(", "path", ",", "\"w\"", ",", "encoding", "=...
29.5
0.001026
def draw_line( self, x0:float, y0:float, x1:float, y1:float, *, stroke:Color, stroke_width:float=1, stroke_dash:typing.Sequence=None ) -> None: """Draws the given line.""" pass
[ "def", "draw_line", "(", "self", ",", "x0", ":", "float", ",", "y0", ":", "float", ",", "x1", ":", "float", ",", "y1", ":", "float", ",", "*", ",", "stroke", ":", "Color", ",", "stroke_width", ":", "float", "=", "1", ",", "stroke_dash", ":", "typ...
30.625
0.051587
def warn_deprecated(since, message='', name='', alternative='', pending=False, obj_type='attribute', addendum=''): """Display deprecation warning in a standard way. Parameters ---------- since : str The release at which this API became deprecated. message : str, optiona...
[ "def", "warn_deprecated", "(", "since", ",", "message", "=", "''", ",", "name", "=", "''", ",", "alternative", "=", "''", ",", "pending", "=", "False", ",", "obj_type", "=", "'attribute'", ",", "addendum", "=", "''", ")", ":", "message", "=", "_generat...
34.979167
0.000579
def _add_prefix(self, split_names, start_node, group_type_name): """Adds the correct sub branch prefix to a given name. Usually the prefix is the full name of the parent node. In case items are added directly to the trajectory the prefixes are chosen according to the matching subbranch. ...
[ "def", "_add_prefix", "(", "self", ",", "split_names", ",", "start_node", ",", "group_type_name", ")", ":", "root", "=", "self", ".", "_root_instance", "# If the start node of our insertion is root or one below root", "# we might need to add prefixes.", "# In case of derived pa...
37.879121
0.002262
def close(self, ulBuffer): """closes a previously opened or created buffer""" fn = self.function_table.close result = fn(ulBuffer) return result
[ "def", "close", "(", "self", ",", "ulBuffer", ")", ":", "fn", "=", "self", ".", "function_table", ".", "close", "result", "=", "fn", "(", "ulBuffer", ")", "return", "result" ]
28.666667
0.011299
def batch_stats(self, funcs:Collection[Callable]=None, ds_type:DatasetType=DatasetType.Train)->Tensor: "Grab a batch of data and call reduction function `func` per channel" funcs = ifnone(funcs, [torch.mean,torch.std]) x = self.one_batch(ds_type=ds_type, denorm=False)[0].cpu() return [fu...
[ "def", "batch_stats", "(", "self", ",", "funcs", ":", "Collection", "[", "Callable", "]", "=", "None", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Train", ")", "->", "Tensor", ":", "funcs", "=", "ifnone", "(", "funcs", ",", "[", "torc...
71.4
0.030471
def plot_topo(axis, topo, topomap, crange=None, offset=(0,0), plot_locations=True, plot_head=True): """Draw a topoplot in given axis. .. note:: Parameter `topo` is modified by the function by calling :func:`~eegtopo.topoplot.Topoplot.set_map`. Parameters ---------- axis : axis ...
[ "def", "plot_topo", "(", "axis", ",", "topo", ",", "topomap", ",", "crange", "=", "None", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "plot_locations", "=", "True", ",", "plot_head", "=", "True", ")", ":", "topo", ".", "set_map", "(", "topoma...
32.666667
0.002477
def cleaner(self, coro): """ Function decorator for a cleanup coroutine. """ if not asyncio.iscoroutinefunction(coro): coro = asyncio.coroutine(coro) self.add_cleaner(coro) return coro
[ "def", "cleaner", "(", "self", ",", "coro", ")", ":", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "coro", ")", ":", "coro", "=", "asyncio", ".", "coroutine", "(", "coro", ")", "self", ".", "add_cleaner", "(", "coro", ")", "return", "coro" ...
37.166667
0.008772
async def write_register(self, address, value, skip_encode=False): """Write a modbus register.""" await self._request('write_registers', address, value, skip_encode=skip_encode)
[ "async", "def", "write_register", "(", "self", ",", "address", ",", "value", ",", "skip_encode", "=", "False", ")", ":", "await", "self", ".", "_request", "(", "'write_registers'", ",", "address", ",", "value", ",", "skip_encode", "=", "skip_encode", ")" ]
63.666667
0.015544
def _update_threads(self): """Update available thread count post-construction. To be called any number of times from run() method""" if self.remaining_clusters is not None: self.threads = max(1,self.threads_total//self.remaining_clusters.value) #otherwise just keep the curren...
[ "def", "_update_threads", "(", "self", ")", ":", "if", "self", ".", "remaining_clusters", "is", "not", "None", ":", "self", ".", "threads", "=", "max", "(", "1", ",", "self", ".", "threads_total", "//", "self", ".", "remaining_clusters", ".", "value", ")...
62.571429
0.02027
def calcTemperature(self): """ Calculates the temperature using which uses equations.MeanPlanetTemp, albedo assumption and potentially equations.starTemperature. issues - you cant get the albedo assumption without temp but you need it to calculate the temp. """ try: ...
[ "def", "calcTemperature", "(", "self", ")", ":", "try", ":", "return", "eq", ".", "MeanPlanetTemp", "(", "self", ".", "albedo", ",", "self", ".", "star", ".", "T", ",", "self", ".", "star", ".", "R", ",", "self", ".", "a", ")", ".", "T_p", "excep...
45.727273
0.011696
def write_bubble(self, filename:str): """Write in given filename the lines of bubble describing this instance""" from bubbletools import converter converter.tree_to_bubble(self, filename)
[ "def", "write_bubble", "(", "self", ",", "filename", ":", "str", ")", ":", "from", "bubbletools", "import", "converter", "converter", ".", "tree_to_bubble", "(", "self", ",", "filename", ")" ]
52
0.018957
def plot_decay_curve(self, filename=None, index_nor=None, index_rec=None, nr_id=None, abmn=None, return_fig=False): """Plot decay curve Input scheme: We recognize three ways to specify the quadrupoles to plot (in descending priority): ...
[ "def", "plot_decay_curve", "(", "self", ",", "filename", "=", "None", ",", "index_nor", "=", "None", ",", "index_rec", "=", "None", ",", "nr_id", "=", "None", ",", "abmn", "=", "None", ",", "return_fig", "=", "False", ")", ":", "def", "get_indices_for_id...
33.80303
0.000871
def set_visible(self, visible): """ Set the visibility of the widget. """ v = View.VISIBILITY_VISIBLE if visible else View.VISIBILITY_GONE self.widget.setVisibility(v)
[ "def", "set_visible", "(", "self", ",", "visible", ")", ":", "v", "=", "View", ".", "VISIBILITY_VISIBLE", "if", "visible", "else", "View", ".", "VISIBILITY_GONE", "self", ".", "widget", ".", "setVisibility", "(", "v", ")" ]
32.5
0.01
def home(): '''Serve the status page of the capture agent. ''' # Get IDs of existing preview images preview = config()['capture']['preview'] previewdir = config()['capture']['preview_dir'] preview = [p.replace('{{previewdir}}', previewdir) for p in preview] preview = zip(preview, range(len(p...
[ "def", "home", "(", ")", ":", "# Get IDs of existing preview images", "preview", "=", "config", "(", ")", "[", "'capture'", "]", "[", "'preview'", "]", "previewdir", "=", "config", "(", ")", "[", "'capture'", "]", "[", "'preview_dir'", "]", "preview", "=", ...
44.263158
0.000582
def chi2_adaptive_binning(features_0,features_1,number_of_splits_list,systematics_fraction=0.0,title = "title", name="name", PLOT = True, DEBUG = False, transform='StandardScalar'): """This function takes in two 2D arrays with all features being columns""" max_number_of_splits = np.max(number_of_splits_list) #deter...
[ "def", "chi2_adaptive_binning", "(", "features_0", ",", "features_1", ",", "number_of_splits_list", ",", "systematics_fraction", "=", "0.0", ",", "title", "=", "\"title\"", ",", "name", "=", "\"name\"", ",", "PLOT", "=", "True", ",", "DEBUG", "=", "False", ","...
43.491979
0.044957
def read_contents(self, schema, name, conn): '''Read table columns''' sql = ''' with schemas as (select n.oid, n.nspname as name from pg_catalog.pg_namespace n), tables as (select c.oid, c.relnamespace as schema_oid, c.relname as name from pg_catalog.pg_class c where c.relkin...
[ "def", "read_contents", "(", "self", ",", "schema", ",", "name", ",", "conn", ")", ":", "sql", "=", "'''\nwith schemas as\n(select n.oid,\n n.nspname as name\n from pg_catalog.pg_namespace n),\ntables as\n(select c.oid,\n c.relnamespace as schema_oid,\n c.relname as...
32.368421
0.001579
def export_tour(tour_steps, name=None, filename="my_tour.js", url=None): """ Exports a tour as a JS file. It will include necessary resources as well, such as jQuery. You'll be able to copy the tour directly into the Console of any web browser to play the tour outside of SeleniumBase runs. "...
[ "def", "export_tour", "(", "tour_steps", ",", "name", "=", "None", ",", "filename", "=", "\"my_tour.js\"", ",", "url", "=", "None", ")", ":", "if", "not", "name", ":", "name", "=", "\"default\"", "if", "name", "not", "in", "tour_steps", ":", "raise", "...
41.242775
0.000137
def truncate_array(array1, array2, position): """Truncate array1 by finding the overlap with array2 when the array1 center is located at the given position in array2.""" slices = [] for i in range(array1.ndim): xmin = 0 xmax = array1.shape[i] dxlo = array1.shape[i] // 2 ...
[ "def", "truncate_array", "(", "array1", ",", "array2", ",", "position", ")", ":", "slices", "=", "[", "]", "for", "i", "in", "range", "(", "array1", ".", "ndim", ")", ":", "xmin", "=", "0", "xmax", "=", "array1", ".", "shape", "[", "i", "]", "dxl...
33.421053
0.001531
def controversial(self, limit=None): """GETs controversial links from this subreddit. Calls :meth:`narwal.Reddit.controversial`. :param limit: max number of links to return """ return self._reddit.controversial(self.display_name, limit=limit)
[ "def", "controversial", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "controversial", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
46.5
0.014085
def show_qos_policy(self, qos_policy, **_params): """Fetches information of a certain qos policy.""" return self.get(self.qos_policy_path % qos_policy, params=_params)
[ "def", "show_qos_policy", "(", "self", ",", "qos_policy", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "qos_policy_path", "%", "qos_policy", ",", "params", "=", "_params", ")" ]
51
0.009662
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Attempt to lock. Returns an awaitable. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ return self._block.acquire(time...
[ "def", "acquire", "(", "self", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ")", "->", "Awaitable", "[", "_ReleasingContextManager", "]", ":", "return", "self", ".", "_block", ".", "acquire", "(", "time...
35.111111
0.009259
def basic_client(): """Returns an Elasticsearch basic client that is responsive to the environment variable ELASTICSEARCH_ENDPOINT""" es_connected = False while not es_connected: try: ES = Elasticsearch( hosts=[HOSTNAME] ) es_connected = True ...
[ "def", "basic_client", "(", ")", ":", "es_connected", "=", "False", "while", "not", "es_connected", ":", "try", ":", "ES", "=", "Elasticsearch", "(", "hosts", "=", "[", "HOSTNAME", "]", ")", "es_connected", "=", "True", "except", "TransportError", "as", "e...
32.214286
0.002155
def check_AP_deriv(abf,n=10): """X""" timePoints=get_AP_timepoints(abf)[:10] #first 10 if len(timePoints)==0: return swhlab.plot.new(abf,True,title="AP velocity (n=%d)"%n,xlabel="ms",ylabel="V/S") pylab.axhline(-50,color='r',lw=2,ls="--",alpha=.2) pylab.axhline(-100,color='r',lw=2,ls="--...
[ "def", "check_AP_deriv", "(", "abf", ",", "n", "=", "10", ")", ":", "timePoints", "=", "get_AP_timepoints", "(", "abf", ")", "[", ":", "10", "]", "#first 10", "if", "len", "(", "timePoints", ")", "==", "0", ":", "return", "swhlab", ".", "plot", ".", ...
42.214286
0.054636
def shorten(s, max_len=16): """Attempt to shorten a phrase by deleting words at the end of the phrase >>> shorten('Hello World!') 'Hello World' >>> shorten("Hello World! I'll talk your ear off!", 15) 'Hello World' """ short = s words = [abbreviate(word) for word in get_words(s)] for...
[ "def", "shorten", "(", "s", ",", "max_len", "=", "16", ")", ":", "short", "=", "s", "words", "=", "[", "abbreviate", "(", "word", ")", "for", "word", "in", "get_words", "(", "s", ")", "]", "for", "i", "in", "range", "(", "len", "(", "words", ")...
30.133333
0.002146
def meter_data_from_json(data, orient="list"): """ Load meter data from json. Default format:: [ ['2017-01-01T00:00:00+00:00', 3.5], ['2017-02-01T00:00:00+00:00', 0.4], ['2017-03-01T00:00:00+00:00', 0.46], ] Parameters ---------- data : :any:`li...
[ "def", "meter_data_from_json", "(", "data", ",", "orient", "=", "\"list\"", ")", ":", "if", "orient", "==", "\"list\"", ":", "df", "=", "pd", ".", "DataFrame", "(", "data", ",", "columns", "=", "[", "\"start\"", ",", "\"value\"", "]", ")", "df", "[", ...
26.758621
0.001244
def cookies(self): '''Simplified Cookie access''' return { key: self.raw_cookies[key].value for key in self.raw_cookies.keys() }
[ "def", "cookies", "(", "self", ")", ":", "return", "{", "key", ":", "self", ".", "raw_cookies", "[", "key", "]", ".", "value", "for", "key", "in", "self", ".", "raw_cookies", ".", "keys", "(", ")", "}" ]
28.5
0.011364
def _start_trial(self, trial, checkpoint=None): """Starts trial and restores last result if trial was paused. Raises: ValueError if restoring from checkpoint fails. """ prior_status = trial.status self.set_status(trial, Trial.RUNNING) trial.runner = self._set...
[ "def", "_start_trial", "(", "self", ",", "trial", ",", "checkpoint", "=", "None", ")", ":", "prior_status", "=", "trial", ".", "status", "self", ".", "set_status", "(", "trial", ",", "Trial", ".", "RUNNING", ")", "trial", ".", "runner", "=", "self", "....
40.28
0.00194
def gen(id_=None, keysize=2048): r''' Generate a key pair. No keys are stored on the master. A key pair is returned as a dict containing pub and priv keys. Returns a dictionary containing the the ``pub`` and ``priv`` keys with their generated values. id\_ Set a name to generate a key pair f...
[ "def", "gen", "(", "id_", "=", "None", ",", "keysize", "=", "2048", ")", ":", "if", "id_", "is", "None", ":", "id_", "=", "hashlib", ".", "sha512", "(", "os", ".", "urandom", "(", "32", ")", ")", ".", "hexdigest", "(", ")", "else", ":", "id_", ...
36.469388
0.001635
def _port_action_vlan(self, port, segment, func, vni): """Verify configuration and then process event.""" # Verify segment. if not self._is_valid_segment(segment): return device_id = self._get_port_uuid(port) if nexus_help.is_baremetal(port): host_id = ...
[ "def", "_port_action_vlan", "(", "self", ",", "port", ",", "segment", ",", "func", ",", "vni", ")", ":", "# Verify segment.", "if", "not", "self", ".", "_is_valid_segment", "(", "segment", ")", ":", "return", "device_id", "=", "self", ".", "_get_port_uuid", ...
35.814815
0.002014
def get_abbreviations(self, combine=False): """ TODO: if `combine==True`, concatenate with author abbreviation(s) Get abbreviations of the titles of the work. :return: a list of strings (empty list if no abbreviations available). """ abbreviations = [] try: ...
[ "def", "get_abbreviations", "(", "self", ",", "combine", "=", "False", ")", ":", "abbreviations", "=", "[", "]", "try", ":", "type_abbreviation", "=", "self", ".", "session", ".", "get_resource", "(", "BASE_URI_TYPES", "%", "\"abbreviation\"", ",", "self", "...
57.851852
0.015113