text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def add_record(self, record): """Add a record to the community. :param record: Record object. :type record: `invenio_records.api.Record` """ key = current_app.config['COMMUNITIES_RECORD_KEY'] record.setdefault(key, []) if self.has_record(record): cur...
[ "def", "add_record", "(", "self", ",", "record", ")", ":", "key", "=", "current_app", ".", "config", "[", "'COMMUNITIES_RECORD_KEY'", "]", "record", ".", "setdefault", "(", "key", ",", "[", "]", ")", "if", "self", ".", "has_record", "(", "record", ")", ...
38.105263
13.684211
def issue_command(self, cmd, *args): """ Sends and receives a message to/from the server """ self._writeline(cmd) self._writeline(str(len(args))) for arg in args: arg = str(arg) self._writeline(str(len(arg))) self._sock.sendall(arg.encode("utf-8")) return self._read_response()
[ "def", "issue_command", "(", "self", ",", "cmd", ",", "*", "args", ")", ":", "self", ".", "_writeline", "(", "cmd", ")", "self", ".", "_writeline", "(", "str", "(", "len", "(", "args", ")", ")", ")", "for", "arg", "in", "args", ":", "arg", "=", ...
30.7
12.2
def analytics_query(self, query, host, *args, **kwargs): """ Execute an Analytics query. This method is mainly a wrapper around the :class:`~.AnalyticsQuery` and :class:`~.AnalyticsRequest` objects, which contain the inputs and outputs of the query. Using an explicit :c...
[ "def", "analytics_query", "(", "self", ",", "query", ",", "host", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "query", ",", "AnalyticsQuery", ")", ":", "query", "=", "AnalyticsQuery", "(", "query", ",", "*", "...
42.388889
22
def clear_secure_boot_keys(self): """Reset all keys. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server. """ if self._is_boot_mode_uefi(): self._change_secure_boot_settings('Re...
[ "def", "clear_secure_boot_keys", "(", "self", ")", ":", "if", "self", ".", "_is_boot_mode_uefi", "(", ")", ":", "self", ".", "_change_secure_boot_settings", "(", "'ResetAllKeys'", ",", "True", ")", "else", ":", "msg", "=", "(", "'System is not in UEFI boot mode. \...
41.076923
17.615385
def compute_stats(self, incremental=False): """ Invoke Impala COMPUTE STATS command to compute column, table, and partition statistics. See also ImpalaClient.compute_stats """ return self._client.compute_stats( self._qualified_name, incremental=incremental ...
[ "def", "compute_stats", "(", "self", ",", "incremental", "=", "False", ")", ":", "return", "self", ".", "_client", ".", "compute_stats", "(", "self", ".", "_qualified_name", ",", "incremental", "=", "incremental", ")" ]
31.8
14
def find_template_from_path(filepath, paths=None): """ Return resolved path of given template file :param filepath: (Base) filepath of template file :param paths: A list of template search paths """ if paths is None or not paths: paths = [os.path.dirname(filepath), os.curdir] for p...
[ "def", "find_template_from_path", "(", "filepath", ",", "paths", "=", "None", ")", ":", "if", "paths", "is", "None", "or", "not", "paths", ":", "paths", "=", "[", "os", ".", "path", ".", "dirname", "(", "filepath", ")", ",", "os", ".", "curdir", "]",...
31.058824
16.588235
def check_sla(self, sla, diff_metric): """ Check whether the SLA has passed or failed """ try: if sla.display is '%': diff_val = float(diff_metric['percent_diff']) else: diff_val = float(diff_metric['absolute_diff']) except ValueError: return False if not (sla.c...
[ "def", "check_sla", "(", "self", ",", "sla", ",", "diff_metric", ")", ":", "try", ":", "if", "sla", ".", "display", "is", "'%'", ":", "diff_val", "=", "float", "(", "diff_metric", "[", "'percent_diff'", "]", ")", "else", ":", "diff_val", "=", "float", ...
29.8
14.466667
def period(self): """Period of the orbit as a timedelta """ return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu))
[ "def", "period", "(", "self", ")", ":", "return", "timedelta", "(", "seconds", "=", "2", "*", "np", ".", "pi", "*", "np", ".", "sqrt", "(", "self", ".", "kep", ".", "a", "**", "3", "/", "self", ".", "mu", ")", ")" ]
38.25
15.75
def secret_key_name(path, key, opt): """Renders a Secret key name appropriately""" value = key if opt.merge_path: norm_path = [x for x in path.split('/') if x] value = "%s_%s" % ('_'.join(norm_path), key) if opt.add_prefix: value = "%s%s" % (opt.add_prefix, value) if opt.ad...
[ "def", "secret_key_name", "(", "path", ",", "key", ",", "opt", ")", ":", "value", "=", "key", "if", "opt", ".", "merge_path", ":", "norm_path", "=", "[", "x", "for", "x", "in", "path", ".", "split", "(", "'/'", ")", "if", "x", "]", "value", "=", ...
27.357143
19.142857
def create(context, name, type, canonical_project_name, data, title, message, url, topic_id, export_control, active): """create(context, name, type, canonical_project_name, data, title, message, url, topic_id, export_control, active) # noqa Create a component. >>> dcictl component-create [OPTI...
[ "def", "create", "(", "context", ",", "name", ",", "type", ",", "canonical_project_name", ",", "data", ",", "title", ",", "message", ",", "url", ",", "topic_id", ",", "export_control", ",", "active", ")", ":", "state", "=", "utils", ".", "active_string", ...
41.666667
17.733333
def parse(self, lines = None): '''Parses the PDB file into a indexed representation (a tagged list of lines, see constructor docstring). A set of Atoms is created, including x, y, z coordinates when applicable. These atoms are grouped into Residues. Finally, the limits of the 3D space are ...
[ "def", "parse", "(", "self", ",", "lines", "=", "None", ")", ":", "indexed_lines", "=", "[", "]", "MODEL_count", "=", "0", "records_types_with_atom_serial_numbers", "=", "set", "(", "[", "'ATOM'", ",", "'HETATM'", ",", "'TER'", ",", "'ANISOU'", "]", ")", ...
60.04
37.293333
def set_unit_property(self, unit_id, property_name, value): '''This function adds a unit property data set under the given property name to the given unit. Parameters ---------- unit_id: int The unit id for which the property will be set property_name: str ...
[ "def", "set_unit_property", "(", "self", ",", "unit_id", ",", "property_name", ",", "value", ")", ":", "if", "isinstance", "(", "unit_id", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "if", "unit_id", "in", "self", ".", "get_unit_ids", "(...
42.192308
21.576923
def main(opts): """Program entry point.""" term = Terminal() style = Style() # if the terminal supports colors, use a Style instance with some # standout colors (magenta, cyan). if term.number_of_colors: style = Style(attr_major=term.magenta, attr_minor=term.bright...
[ "def", "main", "(", "opts", ")", ":", "term", "=", "Terminal", "(", ")", "style", "=", "Style", "(", ")", "# if the terminal supports colors, use a Style instance with some", "# standout colors (magenta, cyan).", "if", "term", ".", "number_of_colors", ":", "style", "=...
33.55
17.05
def pawn_from_dummy(self, dummy): """Make a real thing and its pawn from a dummy pawn. Create a new :class:`board.Pawn` instance, along with the underlying :class:`LiSE.Place` instance, and give it the name, location, and imagery of the provided dummy. """ dummy.pos = s...
[ "def", "pawn_from_dummy", "(", "self", ",", "dummy", ")", ":", "dummy", ".", "pos", "=", "self", ".", "to_local", "(", "*", "dummy", ".", "pos", ")", "for", "spot", "in", "self", ".", "board", ".", "spotlayout", ".", "children", ":", "if", "spot", ...
31.96
15.84
def download_gcs_file(path, out_fname=None, prefix_filter=None): """Download a file from GCS, optionally to a file.""" url = posixpath.join(GCS_BUCKET, path) if prefix_filter: url += "?prefix=%s" % prefix_filter stream = bool(out_fname) resp = requests.get(url, stream=stream) if not resp.ok: raise V...
[ "def", "download_gcs_file", "(", "path", ",", "out_fname", "=", "None", ",", "prefix_filter", "=", "None", ")", ":", "url", "=", "posixpath", ".", "join", "(", "GCS_BUCKET", ",", "path", ")", "if", "prefix_filter", ":", "url", "+=", "\"?prefix=%s\"", "%", ...
33.8
13.066667
def status(self, head): """Get status from server. head - Ping the the head node if True. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if head: sock.connect((self.server, self.port)) else: sock.connect((self.server2, self.port2)) ...
[ "def", "status", "(", "self", ",", "head", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "if", "head", ":", "sock", ".", "connect", "(", "(", "self", ".", "server", ",", "self...
32.4
16.333333
def segment_allocation_find(context, lock_mode=False, **filters): """Query for segment allocations.""" range_ids = filters.pop("segment_allocation_range_ids", None) query = context.session.query(models.SegmentAllocation) if lock_mode: query = query.with_lockmode("update") query = query.fil...
[ "def", "segment_allocation_find", "(", "context", ",", "lock_mode", "=", "False", ",", "*", "*", "filters", ")", ":", "range_ids", "=", "filters", ".", "pop", "(", "\"segment_allocation_range_ids\"", ",", "None", ")", "query", "=", "context", ".", "session", ...
33.0625
21.0625
def calculate_simple_interest(entries, rate_pct: Decimal, interest_date: date or None=None, begin: date or None=None) -> Decimal: """ Calculates simple interest of specified entries over time. Does not accumulate interest to interest. :param entries: AccountEntry iterable (e.g. list/QuerySet) ordered by...
[ "def", "calculate_simple_interest", "(", "entries", ",", "rate_pct", ":", "Decimal", ",", "interest_date", ":", "date", "or", "None", "=", "None", ",", "begin", ":", "date", "or", "None", "=", "None", ")", "->", "Decimal", ":", "if", "interest_date", "is",...
38.25
18.357143
def round_to_quarter(start_time, end_time): """ Return the duration between `start_time` and `end_time` :class:`datetime.time` objects, rounded to 15 minutes. """ # We don't care about the date (only about the time) but Python # can substract only datetime objects, not time ones today = datetime...
[ "def", "round_to_quarter", "(", "start_time", ",", "end_time", ")", ":", "# We don't care about the date (only about the time) but Python", "# can substract only datetime objects, not time ones", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", "start_date", "="...
39.666667
22.222222
def get(feature, obj, **kwargs): '''Obtain a feature from a set of morphology objects Parameters: feature(string): feature to extract obj: a neuron, population or neurite tree **kwargs: parameters to forward to underlying worker functions Returns: features as a 1D or 2D num...
[ "def", "get", "(", "feature", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "feature", "=", "(", "NEURITEFEATURES", "[", "feature", "]", "if", "feature", "in", "NEURITEFEATURES", "else", "NEURONFEATURES", "[", "feature", "]", ")", "return", "_np", ".", ...
28.823529
23.411765
def get_json_shift(year, month, day, unit, count, period, symbol): """ Gets JSON from shifted date by the Poloniex API Args: year: Int between 1 and 9999. month: Int between 1 and 12. day: Int between 1 and 31. unit: String of time period unit for count argument. How...
[ "def", "get_json_shift", "(", "year", ",", "month", ",", "day", ",", "unit", ",", "count", ",", "period", ",", "symbol", ")", ":", "epochs", "=", "date", ".", "get_end_start_epochs", "(", "year", ",", "month", ",", "day", ",", "'last'", ",", "unit", ...
44.95
19.45
def compute_performance(SC, verbose=True, output='dict'): """ Return some performance value for comparison. Parameters ------- SC: SortingComparison instance The SortingComparison verbose: bool Display on console or not output: dict or pandas Returns ---------- ...
[ "def", "compute_performance", "(", "SC", ",", "verbose", "=", "True", ",", "output", "=", "'dict'", ")", ":", "counts", "=", "SC", ".", "_counts", "tp_rate", "=", "float", "(", "counts", "[", "'TP'", "]", ")", "/", "counts", "[", "'TOT_ST1'", "]", "*...
30.468085
24.212766
def extract(self, high_bit, low_bit): """ Operation extract - A cheap hack is implemented: a copy of self is returned if (high_bit - low_bit + 1 == self.bits), which is a ValueSet instance. Otherwise a StridedInterval is returned. :param high_bit: :param low_bit: ...
[ "def", "extract", "(", "self", ",", "high_bit", ",", "low_bit", ")", ":", "if", "high_bit", "-", "low_bit", "+", "1", "==", "self", ".", "bits", ":", "return", "self", ".", "copy", "(", ")", "if", "(", "'global'", "in", "self", ".", "_regions", "an...
31.714286
23.071429
def get_file(self, filename): """Get file source from cache""" import linecache # Hack for frozen importlib bootstrap if filename == '<frozen importlib._bootstrap>': filename = os.path.join( os.path.dirname(linecache.__file__), 'importlib', '_b...
[ "def", "get_file", "(", "self", ",", "filename", ")", ":", "import", "linecache", "# Hack for frozen importlib bootstrap", "if", "filename", "==", "'<frozen importlib._bootstrap>'", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", "....
36.583333
14.083333
def read_map(fname): """ reads a saved text file to list """ lst = [] with open(fname, "r") as f: for line in f: lst.append(line) return lst
[ "def", "read_map", "(", "fname", ")", ":", "lst", "=", "[", "]", "with", "open", "(", "fname", ",", "\"r\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "lst", ".", "append", "(", "line", ")", "return", "lst" ]
19.555556
13.111111
def search_show_top_unite(self, category, genre=None, area=None, year=None, orderby=None, headnum=1, tailnum=1, onesiteflag=None, page=1, count=20): """doc: http://open.youku.com/docs/doc?id=86 """ url = 'h...
[ "def", "search_show_top_unite", "(", "self", ",", "category", ",", "genre", "=", "None", ",", "area", "=", "None", ",", "year", "=", "None", ",", "orderby", "=", "None", ",", "headnum", "=", "1", ",", "tailnum", "=", "1", ",", "onesiteflag", "=", "No...
35.916667
12.875
def maximum_size_estimated(self, sz): """ Set the CoRE Link Format sz attribute of the resource. :param sz: the CoRE Link Format sz attribute """ if not isinstance(sz, str): sz = str(sz) self._attributes["sz"] = sz
[ "def", "maximum_size_estimated", "(", "self", ",", "sz", ")", ":", "if", "not", "isinstance", "(", "sz", ",", "str", ")", ":", "sz", "=", "str", "(", "sz", ")", "self", ".", "_attributes", "[", "\"sz\"", "]", "=", "sz" ]
29.666667
11.444444
def skypipe_input_stream(endpoint, name=None): """Returns a context manager for streaming data into skypipe""" name = name or '' class context_manager(object): def __enter__(self): self.socket = ctx.socket(zmq.DEALER) self.socket.connect(endpoint) return self ...
[ "def", "skypipe_input_stream", "(", "endpoint", ",", "name", "=", "None", ")", ":", "name", "=", "name", "or", "''", "class", "context_manager", "(", "object", ")", ":", "def", "__enter__", "(", "self", ")", ":", "self", ".", "socket", "=", "ctx", ".",...
34.157895
14.421053
def get_rejected_variables(self, threshold=0.9): """Return a list of variable names being rejected for high correlation with one of remaining variables. Parameters: ---------- threshold : float Correlation value which is above the threshold are rejected ...
[ "def", "get_rejected_variables", "(", "self", ",", "threshold", "=", "0.9", ")", ":", "variable_profile", "=", "self", ".", "description_set", "[", "'variables'", "]", "result", "=", "[", "]", "if", "hasattr", "(", "variable_profile", ",", "'correlation'", ")"...
37.263158
23.421053
def update(self) -> None: """Reference the actual |Indexer.timeofyear| array of the |Indexer| object available in module |pub|. >>> from hydpy import pub >>> pub.timegrids = '27.02.2004', '3.03.2004', '1d' >>> from hydpy.core.parametertools import TOYParameter >>> toypar...
[ "def", "update", "(", "self", ")", "->", "None", ":", "indexarray", "=", "hydpy", ".", "pub", ".", "indexer", ".", "timeofyear", "self", ".", "shape", "=", "indexarray", ".", "shape", "self", ".", "values", "=", "indexarray" ]
37.733333
10.8
def _get_condition_instances(data): """ Returns a list of OrderingCondition instances created from the passed data structure. The structure should be a list of dicts containing the necessary information: [ dict( name='featureA', subject='featureB', ctype='afte...
[ "def", "_get_condition_instances", "(", "data", ")", ":", "conditions", "=", "list", "(", ")", "for", "cond", "in", "data", ":", "conditions", ".", "append", "(", "OrderingCondition", "(", "name", "=", "cond", ".", "get", "(", "'name'", ")", ",", "subjec...
28.086957
18.434783
def do_OP_LEFT(vm): """ >>> s = [b'abcdef', b'\3'] >>> do_OP_LEFT(s, require_minimal=True) >>> print(len(s)==1 and s[0]==b'abc') True >>> s = [b'abcdef', b''] >>> do_OP_LEFT(s, require_minimal=True) >>> print(len(s) ==1 and s[0]==b'') True """ pos = vm.pop_nonnegative() v...
[ "def", "do_OP_LEFT", "(", "vm", ")", ":", "pos", "=", "vm", ".", "pop_nonnegative", "(", ")", "vm", ".", "append", "(", "vm", ".", "pop", "(", ")", "[", ":", "pos", "]", ")" ]
25.538462
10.461538
def _split_tidy(self, string, maxsplit=None): """Rstrips string for \n and splits string for \t""" if maxsplit is None: return string.rstrip("\n").split("\t") else: return string.rstrip("\n").split("\t", maxsplit)
[ "def", "_split_tidy", "(", "self", ",", "string", ",", "maxsplit", "=", "None", ")", ":", "if", "maxsplit", "is", "None", ":", "return", "string", ".", "rstrip", "(", "\"\\n\"", ")", ".", "split", "(", "\"\\t\"", ")", "else", ":", "return", "string", ...
36.571429
16.285714
def __setup_remote_paths(self): """ Actually create the working directory and copy the module into it. Note: the script has to be readable by Hadoop; though this may not generally be a problem on HDFS, where the Hadoop user is usually the superuser, things may be different if ou...
[ "def", "__setup_remote_paths", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"remote_wd: %s\"", ",", "self", ".", "remote_wd", ")", "self", ".", "logger", ".", "debug", "(", "\"remote_exe: %s\"", ",", "self", ".", "remote_exe", ")", "s...
49.451613
18.935484
def build_absolute_uri(request, location, protocol=None): """request.build_absolute_uri() helper Like request.build_absolute_uri, but gracefully handling the case where request is None. """ from .account import app_settings as account_settings if request is None: site = Site.objects.ge...
[ "def", "build_absolute_uri", "(", "request", ",", "location", ",", "protocol", "=", "None", ")", ":", "from", ".", "account", "import", "app_settings", "as", "account_settings", "if", "request", "is", "None", ":", "site", "=", "Site", ".", "objects", ".", ...
39.787879
18.909091
def set_cached_output(self, placeholder_name, instance, output): """ .. versionadded:: 0.9 Store the cached output for a rendered item. This method can be overwritten to implement custom caching mechanisms. By default, this function generates the cache key using :func:`...
[ "def", "set_cached_output", "(", "self", ",", "placeholder_name", ",", "instance", ",", "output", ")", ":", "cachekey", "=", "self", ".", "get_output_cache_key", "(", "placeholder_name", ",", "instance", ")", "if", "self", ".", "cache_timeout", "is", "not", "D...
50.333333
29.095238
def load(self, dtype_conversion=None): """ Load the data table and corresponding validation schema. Parameters ---------- dtype_conversion : dict Column names as keys and corresponding type for loading the data. Please take a look at the `pandas documenta...
[ "def", "load", "(", "self", ",", "dtype_conversion", "=", "None", ")", ":", "if", "dtype_conversion", "is", "None", ":", "dtype_conversion", "=", "{", "\"growth\"", ":", "str", "}", "super", "(", "GrowthExperiment", ",", "self", ")", ".", "load", "(", "d...
40.529412
20.529412
def hasReaders(self, ulBuffer): """inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes.""" fn = self.function_table.hasReaders result = fn(ulBuffer) return result
[ "def", "hasReaders", "(", "self", ",", "ulBuffer", ")", ":", "fn", "=", "self", ".", "function_table", ".", "hasReaders", "result", "=", "fn", "(", "ulBuffer", ")", "return", "result" ]
40.166667
13.666667
def setFigForm(): """set the rcparams to EmulateApJ columnwidth=245.26 pts """ fig_width_pt = 245.26*2 inches_per_pt = 1.0/72.27 golden_mean = (math.sqrt(5.)-1.0)/2.0 fig_width = fig_width_pt*inches_per_pt fig_height = fig_width*golden_mean fig_size = [1.5*fig_width, fig_height] pa...
[ "def", "setFigForm", "(", ")", ":", "fig_width_pt", "=", "245.26", "*", "2", "inches_per_pt", "=", "1.0", "/", "72.27", "golden_mean", "=", "(", "math", ".", "sqrt", "(", "5.", ")", "-", "1.0", ")", "/", "2.0", "fig_width", "=", "fig_width_pt", "*", ...
32.846154
9.153846
def template_slave_hcl(cl_args, masters): ''' Template slave config file ''' slave_config_template = "%s/standalone/templates/slave.template.hcl" % cl_args["config_path"] slave_config_actual = "%s/standalone/resources/slave.hcl" % cl_args["config_path"] masters_in_quotes = ['"%s"' % master for master in mas...
[ "def", "template_slave_hcl", "(", "cl_args", ",", "masters", ")", ":", "slave_config_template", "=", "\"%s/standalone/templates/slave.template.hcl\"", "%", "cl_args", "[", "\"config_path\"", "]", "slave_config_actual", "=", "\"%s/standalone/resources/slave.hcl\"", "%", "cl_ar...
50.666667
28.888889
def do_auth(self, block_address, force=False): """ Calls RFID card_auth() with saved auth information if needed. Returns error state from method call. """ auth_data = (block_address, self.method, self.key, self.uid) if (self.last_auth != auth_data) or force: i...
[ "def", "do_auth", "(", "self", ",", "block_address", ",", "force", "=", "False", ")", ":", "auth_data", "=", "(", "block_address", ",", "self", ".", "method", ",", "self", ".", "key", ",", "self", ".", "uid", ")", "if", "(", "self", ".", "last_auth",...
40.125
17.875
def serialize(self) -> dict: """ Serialize the message for sending to slack API Returns: serialized message """ data = {**self} if "attachments" in self: data["attachments"] = json.dumps(self["attachments"]) return data
[ "def", "serialize", "(", "self", ")", "->", "dict", ":", "data", "=", "{", "*", "*", "self", "}", "if", "\"attachments\"", "in", "self", ":", "data", "[", "\"attachments\"", "]", "=", "json", ".", "dumps", "(", "self", "[", "\"attachments\"", "]", ")...
26.363636
15.454545
def md_to_obj(cls, file_path=None, text='', columns=None, key_on=None, ignore_code_blocks=True, eval_cells=True): """ This will convert a mark down file to a seaborn table :param file_path: str of the path to the file :param text: str of the mark down text :para...
[ "def", "md_to_obj", "(", "cls", ",", "file_path", "=", "None", ",", "text", "=", "''", ",", "columns", "=", "None", ",", "key_on", "=", "None", ",", "ignore_code_blocks", "=", "True", ",", "eval_cells", "=", "True", ")", ":", "return", "cls", ".", "m...
51.705882
17.235294
def _set_lossless_priority(self, v, load=False): """ Setter method for lossless_priority, mapped from YANG variable /cee_map/remap/lossless_priority (container) If this variable is read-only (config: false) in the source YANG file, then _set_lossless_priority is considered as a private method. Backe...
[ "def", "_set_lossless_priority", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",",...
77.681818
36.090909
def row_to_dict(cls, row): """ Converts a raw input record to a dictionary of observation data. :param cls: current class :param row: a single observation as a list or tuple """ comment_code = row[3] if comment_code.lower() == 'na': comment_code = '' ...
[ "def", "row_to_dict", "(", "cls", ",", "row", ")", ":", "comment_code", "=", "row", "[", "3", "]", "if", "comment_code", ".", "lower", "(", ")", "==", "'na'", ":", "comment_code", "=", "''", "comp1", "=", "row", "[", "4", "]", "if", "comp1", ".", ...
27.4375
14
def get_author(self): """Gets author :return: author of commit """ author = self.commit.author out = "" if author.name is not None: out += author.name if author.email is not None: out += " (" + author.email + ")" return out
[ "def", "get_author", "(", "self", ")", ":", "author", "=", "self", ".", "commit", ".", "author", "out", "=", "\"\"", "if", "author", ".", "name", "is", "not", "None", ":", "out", "+=", "author", ".", "name", "if", "author", ".", "email", "is", "not...
20.066667
17.333333
def get_fno_lot_sizes(self, cached=True, as_json=False): """ returns a dictionary with key as stock code and value as stock name. It also implements cache functionality and hits the server only if user insists or cache is empty :return: dict """ url = self.fno_lot...
[ "def", "get_fno_lot_sizes", "(", "self", ",", "cached", "=", "True", ",", "as_json", "=", "False", ")", ":", "url", "=", "self", ".", "fno_lot_size_url", "req", "=", "Request", "(", "url", ",", "None", ",", "self", ".", "headers", ")", "res_dict", "=",...
47.923077
16.076923
def load_into(self, obj, name, data, inplace=True, context=None): """Deserialize data from primitive types updating existing object. Raises :exc:`~lollipop.errors.ValidationError` if data is invalid. :param obj: Object to update with deserialized data. :param str name: Name of attribute...
[ "def", "load_into", "(", "self", ",", "obj", ",", "name", ",", "data", ",", "inplace", "=", "True", ",", "context", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "raise", "ValueError", "(", "'Load target should not be None'", ")", "value", "=", ...
43.25
20.857143
def count_entities_or_keys(self, *args, forward=None): """Return the number of keys an entity has, if you specify an entity. Otherwise return the number of entities. """ if forward is None: forward = self.db._forward entity = args[:-3] branch, turn, tick = a...
[ "def", "count_entities_or_keys", "(", "self", ",", "*", "args", ",", "forward", "=", "None", ")", ":", "if", "forward", "is", "None", ":", "forward", "=", "self", ".", "db", ".", "_forward", "entity", "=", "args", "[", ":", "-", "3", "]", "branch", ...
39.461538
18.076923
def delete_tenant(self, tenant_id): """ Asynchronously deletes a tenant and all the data associated with the tenant. :param tenant_id: Tenant id to be sent for deletion process """ self._delete(self._get_single_id_url(self._get_tenants_url(), tenant_id))
[ "def", "delete_tenant", "(", "self", ",", "tenant_id", ")", ":", "self", ".", "_delete", "(", "self", ".", "_get_single_id_url", "(", "self", ".", "_get_tenants_url", "(", ")", ",", "tenant_id", ")", ")" ]
48.166667
19.5
def plot_return_on_dollar(rets, title='Return on $1', show_maxdd=0, figsize=None, ax=None, append=0, label=None, **plot_args): """ Show the cumulative return of specified rets and max drawdowns if selected.""" crets = (1. + returns_cumulative(rets, expanding=1)) if isinstance(crets, pd.DataFrame): t...
[ "def", "plot_return_on_dollar", "(", "rets", ",", "title", "=", "'Return on $1'", ",", "show_maxdd", "=", "0", ",", "figsize", "=", "None", ",", "ax", "=", "None", ",", "append", "=", "0", ",", "label", "=", "None", ",", "*", "*", "plot_args", ")", "...
39
17.685714
def fitNorm_v2(self, specVals): """Fit the normalization given a set of spectral values that define a spectral shape. This version uses `scipy.optimize.fmin`. Parameters ---------- specVals : an array of (nebin values that define a spectral shape xlims : f...
[ "def", "fitNorm_v2", "(", "self", ",", "specVals", ")", ":", "from", "scipy", ".", "optimize", "import", "fmin", "def", "fToMin", "(", "x", ")", ":", "return", "self", ".", "__call__", "(", "specVals", "*", "x", ")", "result", "=", "fmin", "(", "fToM...
28.52381
18.380952
def _updateTargetFromNode(self): """ Applies the configuration to the target axis it monitors. The axis label will be set to the configValue. If the configValue equals PgAxisLabelCti.NO_LABEL, the label will be hidden. """ rtiInfo = self.collector.rtiInfo self.pl...
[ "def", "_updateTargetFromNode", "(", "self", ")", ":", "rtiInfo", "=", "self", ".", "collector", ".", "rtiInfo", "self", ".", "plotItem", ".", "setLabel", "(", "self", ".", "axisPosition", ",", "self", ".", "configValue", ".", "format", "(", "*", "*", "r...
58.625
20.625
def _drawBullet(canvas, offset, cur_y, bulletText, style): """ draw a bullet text could be a simple string or a frag list """ tx2 = canvas.beginText(style.bulletIndent, cur_y + getattr(style, "bulletOffsetY", 0)) tx2.setFont(style.bulletFontName, style.bulletFontSize) tx2.setFillColor(hasattr(s...
[ "def", "_drawBullet", "(", "canvas", ",", "offset", ",", "cur_y", ",", "bulletText", ",", "style", ")", ":", "tx2", "=", "canvas", ".", "beginText", "(", "style", ".", "bulletIndent", ",", "cur_y", "+", "getattr", "(", "style", ",", "\"bulletOffsetY\"", ...
39.171429
14.714286
def validate(filename): """ Use W3C validator service: https://bitbucket.org/nmb10/py_w3c/ . :param filename: the filename to validate """ import HTMLParser from py_w3c.validators.html.validator import HTMLValidator h = HTMLParser.HTMLParser() # for unescaping WC3 messages vld = HTMLV...
[ "def", "validate", "(", "filename", ")", ":", "import", "HTMLParser", "from", "py_w3c", ".", "validators", ".", "html", ".", "validator", "import", "HTMLValidator", "h", "=", "HTMLParser", ".", "HTMLParser", "(", ")", "# for unescaping WC3 messages", "vld", "=",...
32.72
20.08
def _clean_dirty(self, obj=None): """ Recursively clean self and all child objects. """ obj = obj or self obj.__dict__['_dirty_attributes'].clear() obj._dirty = False for key, val in vars(obj).items(): if isinstance(val, BaseObject): self._clean_dirty(...
[ "def", "_clean_dirty", "(", "self", ",", "obj", "=", "None", ")", ":", "obj", "=", "obj", "or", "self", "obj", ".", "__dict__", "[", "'_dirty_attributes'", "]", ".", "clear", "(", ")", "obj", ".", "_dirty", "=", "False", "for", "key", ",", "val", "...
37.583333
9.333333
def clean(self, algorithm=None): '''Create a new :class:`TimeSeries` with missing data removed or replaced by the *algorithm* provided''' # all dates original_dates = list(self.dates()) series = [] all_dates = set() for serie in self.series(): dstart, ...
[ "def", "clean", "(", "self", ",", "algorithm", "=", "None", ")", ":", "# all dates\r", "original_dates", "=", "list", "(", "self", ".", "dates", "(", ")", ")", "series", "=", "[", "]", "all_dates", "=", "set", "(", ")", "for", "serie", "in", "self", ...
37.980392
11.196078
def execv(self, argv, **kwargs): """ Starts a new process for debugging. This method uses a list of arguments. To use a command line string instead, use L{execl}. @see: L{attach}, L{detach} @type argv: list( str... ) @param argv: List of command line arguments...
[ "def", "execv", "(", "self", ",", "argv", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "argv", ")", "in", "(", "str", ",", "compat", ".", "unicode", ")", ":", "raise", "TypeError", "(", "\"Debug.execv expects a list, not a string\"", ")", "lpCmd...
45.144578
25.240964
def parse_comments_for_file(filename): """ Return a list of all parsed comments in a file. Mostly for testing & interactive use. """ return [parse_comment(strip_stars(comment), next_line) for comment, next_line in get_doc_comments(read_file(filename))]
[ "def", "parse_comments_for_file", "(", "filename", ")", ":", "return", "[", "parse_comment", "(", "strip_stars", "(", "comment", ")", ",", "next_line", ")", "for", "comment", ",", "next_line", "in", "get_doc_comments", "(", "read_file", "(", "filename", ")", "...
39.857143
15.571429
def assert_text_equal(self, selector, value, testid=None, **kwargs): """Assert that the element's text is equal to the provided value Args: selector (str): the selector used to find the element value (str): the value that will be compare with the element.text val...
[ "def", "assert_text_equal", "(", "self", ",", "selector", ",", "value", ",", "testid", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "info_log", "(", "\"Assert text equal selector(%s) testid(%s)\"", "%", "(", "selector", ",", "testid", ")", ")...
33.47541
21.327869
def allow_migrate(self, db, model): """ Make sure the auth app only appears in the 'duashttp' database. """ if db == DUAS_DB_ROUTE_PREFIX: return model._meta.app_label == 'duashttp' elif model._meta.app_label == 'duashttp': return False ret...
[ "def", "allow_migrate", "(", "self", ",", "db", ",", "model", ")", ":", "if", "db", "==", "DUAS_DB_ROUTE_PREFIX", ":", "return", "model", ".", "_meta", ".", "app_label", "==", "'duashttp'", "elif", "model", ".", "_meta", ".", "app_label", "==", "'duashttp'...
31.9
11.1
def get(self, id): """id or slug""" info = super(Images, self).get(id) return ImageActions(self.api, parent=self, **info)
[ "def", "get", "(", "self", ",", "id", ")", ":", "info", "=", "super", "(", "Images", ",", "self", ")", ".", "get", "(", "id", ")", "return", "ImageActions", "(", "self", ".", "api", ",", "parent", "=", "self", ",", "*", "*", "info", ")" ]
35.5
10.5
def save_or_overwrite_slice( self, args, slc, slice_add_perm, slice_overwrite_perm, slice_download_perm, datasource_id, datasource_type, datasource_name): """Save or overwrite a slice""" slice_name = args.get('slice_name') action = args.get('action') form_data = g...
[ "def", "save_or_overwrite_slice", "(", "self", ",", "args", ",", "slc", ",", "slice_add_perm", ",", "slice_overwrite_perm", ",", "slice_download_perm", ",", "datasource_id", ",", "datasource_type", ",", "datasource_name", ")", ":", "slice_name", "=", "args", ".", ...
38.47561
17.414634
async def process_lander_page(session, github_api_token, ltd_product_data, mongo_collection=None): """Extract, transform, and load metadata from Lander-based projects. Parameters ---------- session : `aiohttp.ClientSession` Your application's aiohttp client session...
[ "async", "def", "process_lander_page", "(", "session", ",", "github_api_token", ",", "ltd_product_data", ",", "mongo_collection", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "# Try to download metadata.jsonld from the Landing...
39.368421
20.754386
def relation_path_for(from_name, to_name, identifier_type, identifier_key=None): """ Get a path relating a thing to another. """ return "/{}/<{}:{}>/{}".format( name_for(from_name), identifier_type, identifier_key or "{}_id".format(name_for(from_name)), name_for(to_name)...
[ "def", "relation_path_for", "(", "from_name", ",", "to_name", ",", "identifier_type", ",", "identifier_key", "=", "None", ")", ":", "return", "\"/{}/<{}:{}>/{}\"", ".", "format", "(", "name_for", "(", "from_name", ")", ",", "identifier_type", ",", "identifier_key"...
28.818182
17
def associate_notification_template(self, job_template, notification_template, status): """Associate a notification template from this job template. =====API DOCS===== Associate a notification template from this job template. :param job_template:...
[ "def", "associate_notification_template", "(", "self", ",", "job_template", ",", "notification_template", ",", "status", ")", ":", "return", "self", ".", "_assoc", "(", "'notification_templates_%s'", "%", "status", ",", "job_template", ",", "notification_template", ")...
45.45
24.7
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1,extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional ""...
[ "def", "parse", "(", "cls", ",", "src", ",", "dist", "=", "None", ")", ":", "try", ":", "attrs", "=", "extras", "=", "(", ")", "name", ",", "value", "=", "src", ".", "split", "(", "'='", ",", "1", ")", "if", "'['", "in", "value", ":", "value"...
35.366667
15.833333
def create_entity_type(self, parent, entity_type, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, ...
[ "def", "create_entity_type", "(", "self", ",", "parent", ",", "entity_type", ",", "language_code", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", "....
48.352113
24.352113
def set_data(self, index, data): """Set the complete data for a single line strip. Parameters ---------- index : int The index of the line strip to be replaced. data : array-like The data to assign to the selected line strip. """ s...
[ "def", "set_data", "(", "self", ",", "index", ",", "data", ")", ":", "self", ".", "_pos_tex", "[", "index", ",", ":", "]", "=", "data", "self", ".", "update", "(", ")" ]
30
14.5
def paga_compare_paths(adata1, adata2, adjacency_key='connectivities', adjacency_key2=None): """Compare paths in abstracted graphs in two datasets. Compute the fraction of consistent paths between leafs, a measure for the topological similarity between graphs. By increasing the ...
[ "def", "paga_compare_paths", "(", "adata1", ",", "adata2", ",", "adjacency_key", "=", "'connectivities'", ",", "adjacency_key2", "=", "None", ")", ":", "import", "networkx", "as", "nx", "g1", "=", "nx", ".", "Graph", "(", "adata1", ".", "uns", "[", "'paga'...
47.59854
22.963504
def build(obj: Dict[str, Any], *fns: Callable[..., Any]) -> Dict[str, Any]: """ Wrapper function to pipe manifest through build functions. Does not validate the manifest by default. """ return pipe(obj, *fns)
[ "def", "build", "(", "obj", ":", "Dict", "[", "str", ",", "Any", "]", ",", "*", "fns", ":", "Callable", "[", "...", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "pipe", "(", "obj", ",", "*", "fns", ")" ]
37.166667
12.833333
def main(): """The main function of the module. These are the steps: 1. Reads the population file (:py:func:`readPopulations`). 2. Extracts the MDS values (:py:func:`extractData`). 3. Plots the MDS values (:py:func:`plotMDS`). """ # Getting and checking the options args = parseArgs() ...
[ "def", "main", "(", ")", ":", "# Getting and checking the options", "args", "=", "parseArgs", "(", ")", "checkArgs", "(", "args", ")", "# Reads the population file", "populations", "=", "readPopulations", "(", "args", ".", "population_file", ",", "args", ".", "pop...
32.038462
22.115385
def is_line_layer(layer): """Check if a QGIS layer is vector and its geometries are lines. :param layer: A vector layer. :type layer: QgsVectorLayer, QgsMapLayer :returns: True if the layer contains lines, otherwise False. :rtype: bool """ try: return (layer.type() == QgsMapLayer....
[ "def", "is_line_layer", "(", "layer", ")", ":", "try", ":", "return", "(", "layer", ".", "type", "(", ")", "==", "QgsMapLayer", ".", "VectorLayer", ")", "and", "(", "layer", ".", "geometryType", "(", ")", "==", "QgsWkbTypes", ".", "LineGeometry", ")", ...
28.933333
20.2
def record_take(self, model, env_instance, device, take_number): """ Record a single movie and store it on hard drive """ frames = [] observation = env_instance.reset() if model.is_recurrent: hidden_state = model.zero_state(1).to(device) frames.append(env_instance....
[ "def", "record_take", "(", "self", ",", "model", ",", "env_instance", ",", "device", ",", "take_number", ")", ":", "frames", "=", "[", "]", "observation", "=", "env_instance", ".", "reset", "(", ")", "if", "model", ".", "is_recurrent", ":", "hidden_state",...
37.755556
27.755556
def _repack_options(options): ''' Repack the options data ''' return dict( [ (six.text_type(x), _normalize(y)) for x, y in six.iteritems(salt.utils.data.repack_dictlist(options)) ] )
[ "def", "_repack_options", "(", "options", ")", ":", "return", "dict", "(", "[", "(", "six", ".", "text_type", "(", "x", ")", ",", "_normalize", "(", "y", ")", ")", "for", "x", ",", "y", "in", "six", ".", "iteritems", "(", "salt", ".", "utils", "....
23.3
25.5
def _paint_margins(self, event): """ Paints the right margin after editor paint event. """ font = QtGui.QFont(self.editor.font_name, self.editor.font_size + self.editor.zoom_level) metrics = QtGui.QFontMetricsF(font) painter = QtGui.QPainter(self.editor.viewpor...
[ "def", "_paint_margins", "(", "self", ",", "event", ")", ":", "font", "=", "QtGui", ".", "QFont", "(", "self", ".", "editor", ".", "font_name", ",", "self", ".", "editor", ".", "font_size", "+", "self", ".", "editor", ".", "zoom_level", ")", "metrics",...
47.666667
13.2
def fmt(msg, *args, **kw): # type: (str, *Any, **Any) -> str """ Generate shell color opcodes from a pretty coloring syntax. """ global is_tty if len(args) or len(kw): msg = msg.format(*args, **kw) opcode_subst = '\x1b[\\1m' if is_tty else '' return re.sub(r'<(\d{1,2})>', opcode_subst,...
[ "def", "fmt", "(", "msg", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# type: (str, *Any, **Any) -> str", "global", "is_tty", "if", "len", "(", "args", ")", "or", "len", "(", "kw", ")", ":", "msg", "=", "msg", ".", "format", "(", "*", "args",...
31.6
15.5
def convert_to_id(s, id_set): """ Some parts of .wxs need an Id attribute (for example: The File and Directory directives. The charset is limited to A-Z, a-z, digits, underscores, periods. Each Id must begin with a letter or with a underscore. Google for "CNDL0015" for information about this. Requi...
[ "def", "convert_to_id", "(", "s", ",", "id_set", ")", ":", "charset", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.'", "if", "s", "[", "0", "]", "in", "'0123456789.'", ":", "s", "+=", "'_'", "+", "s", "id", "=", "[", "c", "for", "c",...
38.621622
22.810811
def set_project_pid(project, old_pid, new_pid): """ Project's PID was changed. """ for datastore in _get_datastores(): datastore.save_project(project) datastore.set_project_pid(project, old_pid, new_pid)
[ "def", "set_project_pid", "(", "project", ",", "old_pid", ",", "new_pid", ")", ":", "for", "datastore", "in", "_get_datastores", "(", ")", ":", "datastore", ".", "save_project", "(", "project", ")", "datastore", ".", "set_project_pid", "(", "project", ",", "...
44.6
5.8
def save(self, *args, **kwargs): """ Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard. """ if self.publish_date is None: self.publish_da...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "publish_date", "is", "None", ":", "self", ".", "publish_date", "=", "now", "(", ")", "super", "(", "Displayable", ",", "self", ")", ".", "save", ...
41.888889
11.444444
def check_regularizers(regularizers, keys): """Checks the given regularizers. This checks that `regularizers` is a dictionary that only contains keys in `keys`, and furthermore the entries in `regularizers` are functions or further dictionaries (the latter used, for example, in passing regularizers to module...
[ "def", "check_regularizers", "(", "regularizers", ",", "keys", ")", ":", "if", "regularizers", "is", "None", ":", "return", "{", "}", "_assert_is_dictlike", "(", "regularizers", ",", "valid_keys", "=", "keys", ")", "keys", "=", "set", "(", "keys", ")", "if...
34.307692
24
def exists(self, path): """ Check if a given path exists on the filesystem. :type path: str :param path: the path to look for :rtype: bool :return: :obj:`True` if ``path`` exists """ _complain_ifclosed(self.closed) return self.fs.exists(path)
[ "def", "exists", "(", "self", ",", "path", ")", ":", "_complain_ifclosed", "(", "self", ".", "closed", ")", "return", "self", ".", "fs", ".", "exists", "(", "path", ")" ]
27.727273
11.181818
def wait_with_ioloop(self, ioloop, timeout=None): """Do blocking wait until condition is event is set. Parameters ---------- ioloop : tornadio.ioloop.IOLoop instance MUST be the same ioloop that set() / clear() is called from timeout : float, int or None ...
[ "def", "wait_with_ioloop", "(", "self", ",", "ioloop", ",", "timeout", "=", "None", ")", ":", "f", "=", "Future", "(", ")", "def", "cb", "(", ")", ":", "return", "gen", ".", "chain_future", "(", "self", ".", "until_set", "(", ")", ",", "f", ")", ...
28.310345
21.241379
def get_vpc_id_from_mac_address(): """Gets the VPC ID for this EC2 instance :return: String instance ID or None """ log = logging.getLogger(mod_logger + '.get_vpc_id') # Exit if not running on AWS if not is_aws(): log.info('This machine is not running in AWS, exiting...') retur...
[ "def", "get_vpc_id_from_mac_address", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.get_vpc_id'", ")", "# Exit if not running on AWS", "if", "not", "is_aws", "(", ")", ":", "log", ".", "info", "(", "'This machine is not running...
34.512821
22.897436
def get_first(): """ return first droplet """ client = po.connect() # this depends on the DIGITALOCEAN_API_KEY envvar all_droplets = client.droplets.list() id = all_droplets[0]['id'] # I'm cheating because I only have one droplet return client.droplets.get(id)
[ "def", "get_first", "(", ")", ":", "client", "=", "po", ".", "connect", "(", ")", "# this depends on the DIGITALOCEAN_API_KEY envvar", "all_droplets", "=", "client", ".", "droplets", ".", "list", "(", ")", "id", "=", "all_droplets", "[", "0", "]", "[", "'id'...
35.125
14.875
def delete(self, obj): """Required functionality.""" del_id = obj.get_id() if not del_id: return cur = self._conn().cursor() tabname = obj.__class__.get_table_name() query = 'delete from {0} where id = %s;'.format(tabname) with self._conn() as conn:...
[ "def", "delete", "(", "self", ",", "obj", ")", ":", "del_id", "=", "obj", ".", "get_id", "(", ")", "if", "not", "del_id", ":", "return", "cur", "=", "self", ".", "_conn", "(", ")", ".", "cursor", "(", ")", "tabname", "=", "obj", ".", "__class__",...
28
17.071429
def store_many(self, sql, values): """Abstraction over executemany method""" cursor = self.get_cursor() cursor.executemany(sql, values) self.conn.commit()
[ "def", "store_many", "(", "self", ",", "sql", ",", "values", ")", ":", "cursor", "=", "self", ".", "get_cursor", "(", ")", "cursor", ".", "executemany", "(", "sql", ",", "values", ")", "self", ".", "conn", ".", "commit", "(", ")" ]
36.4
5.4
def hasoriginal(self,allowempty=False): """Does the correction record the old annotations prior to correction?""" for e in self.select(Original,None,False, False): if not allowempty and len(e) == 0: continue return True return False
[ "def", "hasoriginal", "(", "self", ",", "allowempty", "=", "False", ")", ":", "for", "e", "in", "self", ".", "select", "(", "Original", ",", "None", ",", "False", ",", "False", ")", ":", "if", "not", "allowempty", "and", "len", "(", "e", ")", "==",...
45.833333
11.666667
def find_name(name, state, high): ''' Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match Note: if `state` is sls, then we are looking for all IDs that match the given SLS ''' ext_id = [] if name in high: ext_id.append((name, state)) ...
[ "def", "find_name", "(", "name", ",", "state", ",", "high", ")", ":", "ext_id", "=", "[", "]", "if", "name", "in", "high", ":", "ext_id", ".", "append", "(", "(", "name", ",", "state", ")", ")", "# if we are requiring an entire SLS, then we need to add ourse...
40.392857
19.321429
def read(fname, merge_duplicate_shots=False, encoding='windows-1252'): """Read a PocketTopo .TXT file and produce a `TxtFile` object which represents it""" return PocketTopoTxtParser(fname, merge_duplicate_shots, encoding).parse()
[ "def", "read", "(", "fname", ",", "merge_duplicate_shots", "=", "False", ",", "encoding", "=", "'windows-1252'", ")", ":", "return", "PocketTopoTxtParser", "(", "fname", ",", "merge_duplicate_shots", ",", "encoding", ")", ".", "parse", "(", ")" ]
81.333333
24
def _add_to_spec(self, name): """The spec of the mirrored mock object is updated whenever the mirror gains new attributes""" self._spec.add(name) self._mock.mock_add_spec(list(self._spec), True)
[ "def", "_add_to_spec", "(", "self", ",", "name", ")", ":", "self", ".", "_spec", ".", "add", "(", "name", ")", "self", ".", "_mock", ".", "mock_add_spec", "(", "list", "(", "self", ".", "_spec", ")", ",", "True", ")" ]
44.4
7.8
def dereference(self, session, ref, allow_none=False): """ Dereference a pymongo "DBRef" to this field's underlying type """ from ommongo.document import collection_registry # TODO: namespace support ref.type = collection_registry['global'][ref.collection] obj = session.dereferen...
[ "def", "dereference", "(", "self", ",", "session", ",", "ref", ",", "allow_none", "=", "False", ")", ":", "from", "ommongo", ".", "document", "import", "collection_registry", "# TODO: namespace support", "ref", ".", "type", "=", "collection_registry", "[", "'glo...
51.857143
14.857143
def _convert_to_df(in_file, freq, raw_file): """ convert data frame into table with pandas """ dat = defaultdict(Counter) if isinstance(in_file, (str, unicode)): with open(in_file) as in_handle: for line in in_handle: cols = line.strip().split("\t") ...
[ "def", "_convert_to_df", "(", "in_file", ",", "freq", ",", "raw_file", ")", ":", "dat", "=", "defaultdict", "(", "Counter", ")", "if", "isinstance", "(", "in_file", ",", "(", "str", ",", "unicode", ")", ")", ":", "with", "open", "(", "in_file", ")", ...
36.875
17.208333
def ip6_address(self): """Returns the IPv6 address of the network interface. If multiple interfaces are provided, the address of the first found is returned. """ if self._ip6_address is None and self.network is not None: self._ip6_address = self._get_ip_address( ...
[ "def", "ip6_address", "(", "self", ")", ":", "if", "self", ".", "_ip6_address", "is", "None", "and", "self", ".", "network", "is", "not", "None", ":", "self", ".", "_ip6_address", "=", "self", ".", "_get_ip_address", "(", "libvirt", ".", "VIR_IP_ADDR_TYPE_...
32.166667
17.166667
def seconds_str(num, prefix=None): r""" Returns: str Example: >>> # ENABLE_DOCTEST >>> from utool.util_str import * # NOQA >>> import utool as ut >>> num_list = sorted([4.2 / (10.0 ** exp_) >>> for exp_ in range(-13, 13, 4)]) >>> s...
[ "def", "seconds_str", "(", "num", ",", "prefix", "=", "None", ")", ":", "exponent_list", "=", "[", "-", "12", ",", "-", "9", ",", "-", "6", ",", "-", "3", ",", "0", ",", "3", ",", "6", ",", "9", ",", "12", "]", "small_prefix_list", "=", "[", ...
36.214286
18.892857
def can_read(self, timeout=0): "Poll the socket to see if there's data that can be read." sock = self._sock if not sock: self.connect() sock = self._sock return self._parser.can_read() or \ bool(select([sock], [], [], timeout)[0])
[ "def", "can_read", "(", "self", ",", "timeout", "=", "0", ")", ":", "sock", "=", "self", ".", "_sock", "if", "not", "sock", ":", "self", ".", "connect", "(", ")", "sock", "=", "self", ".", "_sock", "return", "self", ".", "_parser", ".", "can_read",...
36.375
13.875
def plot_haplotype_frequencies(h, palette='Paired', singleton_color='w', ax=None): """Plot haplotype frequencies. Parameters ---------- h : array_like, int, shape (n_variants, n_haplotypes) Haplotype array. palette : string, optional A Seaborn palette ...
[ "def", "plot_haplotype_frequencies", "(", "h", ",", "palette", "=", "'Paired'", ",", "singleton_color", "=", "'w'", ",", "ax", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "seaborn", "as", "sns", "# check inputs", "h",...
23.189655
20.241379
def from_segment_xml(cls, xml_file, **kwargs): """ Read a ligo.segments.segmentlist from the file object file containing an xml segment table. Parameters ----------- xml_file : file object file object for segment xml file """ # load xmldocumen...
[ "def", "from_segment_xml", "(", "cls", ",", "xml_file", ",", "*", "*", "kwargs", ")", ":", "# load xmldocument and SegmentDefTable and SegmentTables", "fp", "=", "open", "(", "xml_file", ",", "'r'", ")", "xmldoc", ",", "_", "=", "ligolw_utils", ".", "load_fileob...
42.789474
21.982456
def new(self, command, attach=""): """ Creates a new Process Attach: If attach=True it will return a rendezvous connection point, for streaming stdout/stderr Command: The actual command it will run """ r = self._h._http_resource( method='POST', res...
[ "def", "new", "(", "self", ",", "command", ",", "attach", "=", "\"\"", ")", ":", "r", "=", "self", ".", "_h", ".", "_http_resource", "(", "method", "=", "'POST'", ",", "resource", "=", "(", "'apps'", ",", "self", ".", "app", ".", "name", ",", "'p...
35.357143
16.5
def get(self, sid): """ Constructs a FeedbackSummaryContext :param sid: A string that uniquely identifies this feedback summary resource :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext :rtype: twilio.rest.api.v2010.account.call.feedback_summ...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "FeedbackSummaryContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
45.6
31.6