text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def search(self, query, search_type, payload=None): '''Search implementation''' url = self.url + search_type headers = {'User-Agent': self.user_agent} if payload is not None: payload['Query'] = quote(query) else: payload = {'Query': quote(query)} ...
[ "def", "search", "(", "self", ",", "query", ",", "search_type", ",", "payload", "=", "None", ")", ":", "url", "=", "self", ".", "url", "+", "search_type", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "}", "if", "payload", "is", ...
34
17.833333
def bhattacharyya_distance(pca1,pca2): """ A measure of the distance between two probability distributions """ u1 = pca1.coefficients s1 = pca1.covariance_matrix u2 = pca2.coefficients s2 = pca2.covariance_matrix sigma = (s1+s2)/2 assert all(u1 > 0) assert all(u2 > 0) asser...
[ "def", "bhattacharyya_distance", "(", "pca1", ",", "pca2", ")", ":", "u1", "=", "pca1", ".", "coefficients", "s1", "=", "pca1", ".", "covariance_matrix", "u2", "=", "pca2", ".", "coefficients", "s2", "=", "pca2", ".", "covariance_matrix", "sigma", "=", "("...
26.631579
17.789474
def sprint(text, *colors): """Format text with color or other effects into ANSI escaped string.""" return "\33[{}m{content}\33[{}m".format(";".join([str(color) for color in colors]), RESET, content=text) if IS_ANSI_TERMINAL and colors else text
[ "def", "sprint", "(", "text", ",", "*", "colors", ")", ":", "return", "\"\\33[{}m{content}\\33[{}m\"", ".", "format", "(", "\";\"", ".", "join", "(", "[", "str", "(", "color", ")", "for", "color", "in", "colors", "]", ")", ",", "RESET", ",", "content",...
83.333333
41
def build_configuration_parameters(app): """Create documentation for configuration parameters.""" env = Environment(loader=FileSystemLoader("{0}/_data_templates".format(BASEPATH))) template_file = env.get_template("configuration-parameters.j2") data = {} data["schema"] = Config.schema() rendered...
[ "def", "build_configuration_parameters", "(", "app", ")", ":", "env", "=", "Environment", "(", "loader", "=", "FileSystemLoader", "(", "\"{0}/_data_templates\"", ".", "format", "(", "BASEPATH", ")", ")", ")", "template_file", "=", "env", ".", "get_template", "("...
51.5
16.9
def _dict_from_terse_tabular( names: List[str], inp: str, transformers: Dict[str, Callable[[str], Any]] = {})\ -> List[Dict[str, Any]]: """ Parse NMCLI terse tabular output into a list of Python dict. ``names`` is a list of strings of field names to apply to the input data, ...
[ "def", "_dict_from_terse_tabular", "(", "names", ":", "List", "[", "str", "]", ",", "inp", ":", "str", ",", "transformers", ":", "Dict", "[", "str", ",", "Callable", "[", "[", "str", "]", ",", "Any", "]", "]", "=", "{", "}", ")", "->", "List", "[...
37.193548
20.903226
def clone(self): """Deepclone the entity, but reset state""" clone_copy = copy.deepcopy(self) clone_copy.state_ = EntityState() return clone_copy
[ "def", "clone", "(", "self", ")", ":", "clone_copy", "=", "copy", ".", "deepcopy", "(", "self", ")", "clone_copy", ".", "state_", "=", "EntityState", "(", ")", "return", "clone_copy" ]
28.833333
13.333333
def redirect_if_blocked(course_run_ids, user=None, ip_address=None, url=None): """ Return redirect to embargo error page if the given user is blocked. """ for course_run_id in course_run_ids: redirect_url = embargo_api.redirect_if_blocked( CourseKey.from_strin...
[ "def", "redirect_if_blocked", "(", "course_run_ids", ",", "user", "=", "None", ",", "ip_address", "=", "None", ",", "url", "=", "None", ")", ":", "for", "course_run_id", "in", "course_run_ids", ":", "redirect_url", "=", "embargo_api", ".", "redirect_if_blocked",...
38
14.307692
def _datetime_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, datetime.datetime): value = value.strftime(_RFC3339_MICROS_NO_ZULU) return value
[ "def", "_datetime_to_json", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "value", "=", "value", ".", "strftime", "(", "_RFC3339_MICROS_NO_ZULU", ")", "return", "value" ]
41.2
10.8
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this block.""" self.validate() template_data = { 'direction': self.direction, 'edge_name': self.edge_name, 'inverse_direction': 'in' if self.direction == 'out' else 'out' ...
[ "def", "to_gremlin", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "template_data", "=", "{", "'direction'", ":", "self", ".", "direction", ",", "'edge_name'", ":", "self", ".", "edge_name", ",", "'inverse_direction'", ":", "'in'", "if", "self"...
45.545455
16.454545
def create(cls, data, id_=None): """Create a deposit. Initialize the follow information inside the deposit: .. code-block:: python deposit['_deposit'] = { 'id': pid_value, 'status': 'draft', 'owners': [user_id], 'crea...
[ "def", "create", "(", "cls", ",", "data", ",", "id_", "=", "None", ")", ":", "data", ".", "setdefault", "(", "'$schema'", ",", "current_jsonschemas", ".", "path_to_url", "(", "current_app", ".", "config", "[", "'DEPOSIT_DEFAULT_JSONSCHEMA'", "]", ")", ")", ...
31.864865
18.486486
def HasTable(self, table_name): """Determines if a specific table exists. Args: table_name (str): name of the table. Returns: bool: True if the column exists. Raises: IOError: if the database file is not opened. OSError: if the database file is not opened. """ if not s...
[ "def", "HasTable", "(", "self", ",", "table_name", ")", ":", "if", "not", "self", ".", "_connection", ":", "raise", "IOError", "(", "'Not opened.'", ")", "if", "not", "table_name", ":", "return", "False", "if", "self", ".", "_table_names", "is", "None", ...
24.4
18.914286
def next(self): """next(self) -> Link""" CheckParent(self) val = _fitz.Link_next(self) if val: val.thisown = True val.parent = self.parent # copy owning page from prev link val.parent._annot_refs[id(val)] = val if self.xref > 0: # prev li...
[ "def", "next", "(", "self", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Link_next", "(", "self", ")", "if", "val", ":", "val", ".", "thisown", "=", "True", "val", ".", "parent", "=", "self", ".", "parent", "# copy owning pag...
28.315789
20
def single(self): """ Return the associated node. :return: node """ nodes = super(One, self).all() if nodes: if len(nodes) == 1: return nodes[0] else: raise CardinalityViolation(self, len(nodes)) else: ...
[ "def", "single", "(", "self", ")", ":", "nodes", "=", "super", "(", "One", ",", "self", ")", ".", "all", "(", ")", "if", "nodes", ":", "if", "len", "(", "nodes", ")", "==", "1", ":", "return", "nodes", "[", "0", "]", "else", ":", "raise", "Ca...
25.285714
15.142857
def _is_packed_binary(self, data): ''' Check if data is hexadecimal packed :param data: :return: ''' packed = False if isinstance(data, bytes) and len(data) == 16 and b':' not in data: try: packed = bool(int(binascii.hexlify(data), 16)...
[ "def", "_is_packed_binary", "(", "self", ",", "data", ")", ":", "packed", "=", "False", "if", "isinstance", "(", "data", ",", "bytes", ")", "and", "len", "(", "data", ")", "==", "16", "and", "b':'", "not", "in", "data", ":", "try", ":", "packed", "...
26.333333
22.2
def output_tap(self): """Output analysis results in TAP format.""" tracker = Tracker(streaming=True, stream=sys.stdout) for group in self.config.analysis_groups: n_providers = len(group.providers) n_checkers = len(group.checkers) if not group.providers and gro...
[ "def", "output_tap", "(", "self", ")", ":", "tracker", "=", "Tracker", "(", "streaming", "=", "True", ",", "stream", "=", "sys", ".", "stdout", ")", "for", "group", "in", "self", ".", "config", ".", "analysis_groups", ":", "n_providers", "=", "len", "(...
49.027778
15.305556
def get_nehrp_classes(self, sites): """ Site classification threshholds from Section 4 "Site correction coefficients" p. 205. Note that site classes E and F are not supported. """ classes = sorted(self.NEHRP_VS30_UPPER_BOUNDS.keys()) bounds = [self.NEHRP_VS30_UPP...
[ "def", "get_nehrp_classes", "(", "self", ",", "sites", ")", ":", "classes", "=", "sorted", "(", "self", ".", "NEHRP_VS30_UPPER_BOUNDS", ".", "keys", "(", ")", ")", "bounds", "=", "[", "self", ".", "NEHRP_VS30_UPPER_BOUNDS", "[", "item", "]", "for", "item",...
40.571429
20
def get_selected_thread(self): """returns currently selected :class:`~alot.db.Thread`""" threadlinewidget = self.get_selected_threadline() thread = None if threadlinewidget: thread = threadlinewidget.get_thread() return thread
[ "def", "get_selected_thread", "(", "self", ")", ":", "threadlinewidget", "=", "self", ".", "get_selected_threadline", "(", ")", "thread", "=", "None", "if", "threadlinewidget", ":", "thread", "=", "threadlinewidget", ".", "get_thread", "(", ")", "return", "threa...
38.857143
12.428571
def delete(self, key_name): """Delete a key if it exists. """ self._assert_valid_stash() if key_name == 'stored_passphrase': raise GhostError( '`stored_passphrase` is a reserved ghost key name ' 'which cannot be deleted') # TODO: Opti...
[ "def", "delete", "(", "self", ",", "key_name", ")", ":", "self", ".", "_assert_valid_stash", "(", ")", "if", "key_name", "==", "'stored_passphrase'", ":", "raise", "GhostError", "(", "'`stored_passphrase` is a reserved ghost key name '", "'which cannot be deleted'", ")"...
35.142857
18.785714
def _setup_logging(conf): """ Configure the logging framework. If run in CLI mode then all log output is simply written to stdout. """ if conf['verbose']: level = logging.DEBUG else: level = logging.INFO fname = conf['logfile'] if conf['logfile'] != "-" else None logg...
[ "def", "_setup_logging", "(", "conf", ")", ":", "if", "conf", "[", "'verbose'", "]", ":", "level", "=", "logging", ".", "DEBUG", "else", ":", "level", "=", "logging", ".", "INFO", "fname", "=", "conf", "[", "'logfile'", "]", "if", "conf", "[", "'logf...
33.363636
22.727273
def list(self, before_id=None, since_id=None, after_id=None, limit=20): """Return a page of group messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``, or ``after_id``. :param str before_id: message ID for paging b...
[ "def", "list", "(", "self", ",", "before_id", "=", "None", ",", "since_id", "=", "None", ",", "after_id", "=", "None", ",", "limit", "=", "20", ")", ":", "return", "pagers", ".", "MessageList", "(", "self", ",", "self", ".", "_raw_list", ",", "before...
49.875
22.625
def _trim_fields(self, docs): ''' Removes ignore fields from the data that we got from Solr. ''' for doc in docs: for field in self._ignore_fields: if field in doc: del(doc[field]) return docs
[ "def", "_trim_fields", "(", "self", ",", "docs", ")", ":", "for", "doc", "in", "docs", ":", "for", "field", "in", "self", ".", "_ignore_fields", ":", "if", "field", "in", "doc", ":", "del", "(", "doc", "[", "field", "]", ")", "return", "docs" ]
31.111111
16.222222
def from_array(array): """ Deserialize a new StickerSet from a given dictionary. :return: new StickerSet instance. :rtype: StickerSet """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="arr...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "from", "pytgbot", ".", "api...
33.47619
18.047619
def _getkey(self, args, kwargs): """Get hash key from args and kwargs. args and kwargs must be hashable. :param tuple args: called vargs. :param dict kwargs: called keywords. :return: hash(tuple(args) + tuple((key, val) for key in sorted(kwargs)). :rtype: int.""" ...
[ "def", "_getkey", "(", "self", ",", "args", ",", "kwargs", ")", ":", "values", "=", "list", "(", "args", ")", "keys", "=", "sorted", "(", "list", "(", "kwargs", ")", ")", "for", "key", "in", "keys", ":", "values", ".", "append", "(", "(", "key", ...
24.65
19.75
def get_processors(self): "Read the default class processors if none have been set." procs_x,procs_y = listify(self.train.x._processor),listify(self.train.y._processor) xp = ifnone(self.train.x.processor, [p(ds=self.train.x) for p in procs_x]) yp = ifnone(self.train.y.processor, [p(ds=se...
[ "def", "get_processors", "(", "self", ")", ":", "procs_x", ",", "procs_y", "=", "listify", "(", "self", ".", "train", ".", "x", ".", "_processor", ")", ",", "listify", "(", "self", ".", "train", ".", "y", ".", "_processor", ")", "xp", "=", "ifnone", ...
61
32.666667
def set_source_quandl(self, quandl_token): """ Set data source to Quandl """ self.data_worker = data_worker self.worker_args = {"function": Quandl.get, "input": self.input_queue, "output": self.output_map, "token": quandl_token} self.source_nam...
[ "def", "set_source_quandl", "(", "self", ",", "quandl_token", ")", ":", "self", ".", "data_worker", "=", "data_worker", "self", ".", "worker_args", "=", "{", "\"function\"", ":", "Quandl", ".", "get", ",", "\"input\"", ":", "self", ".", "input_queue", ",", ...
40.625
11.375
def mark_sentence_boundaries(sequences, drop=0.0): # pragma: no cover """Pad sentence sequences with EOL markers.""" for sequence in sequences: sequence.insert(0, "-EOL-") sequence.insert(0, "-EOL-") sequence.append("-EOL-") sequence.append("-EOL-") return sequences, None
[ "def", "mark_sentence_boundaries", "(", "sequences", ",", "drop", "=", "0.0", ")", ":", "# pragma: no cover", "for", "sequence", "in", "sequences", ":", "sequence", ".", "insert", "(", "0", ",", "\"-EOL-\"", ")", "sequence", ".", "insert", "(", "0", ",", "...
38.75
10
def make_mecard_data(name, reading=None, email=None, phone=None, videophone=None, memo=None, nickname=None, birthday=None, url=None, pobox=None, roomno=None, houseno=None, city=None, prefecture=None, zipcode=None, country=None): """\ Creates a strin...
[ "def", "make_mecard_data", "(", "name", ",", "reading", "=", "None", ",", "email", "=", "None", ",", "phone", "=", "None", ",", "videophone", "=", "None", ",", "memo", "=", "None", ",", "nickname", "=", "None", ",", "birthday", "=", "None", ",", "url...
44.274194
19.451613
def trim_extrema(im, h, mode='maxima'): r""" Trims local extrema in greyscale values by a specified amount. This essentially decapitates peaks and/or floods valleys. Parameters ---------- im : ND-array The image whose extrema are to be removed h : float The height to remov...
[ "def", "trim_extrema", "(", "im", ",", "h", ",", "mode", "=", "'maxima'", ")", ":", "result", "=", "im", "if", "mode", "in", "[", "'maxima'", ",", "'extrema'", "]", ":", "result", "=", "reconstruction", "(", "seed", "=", "im", "-", "h", ",", "mask"...
27.969697
24.787879
def generate(extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3', absonly=True, compress='gzip'): ''' Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma...
[ "def", "generate", "(", "extra_mods", "=", "''", ",", "overwrite", "=", "False", ",", "so_mods", "=", "''", ",", "python2_bin", "=", "'python2'", ",", "python3_bin", "=", "'python3'", ",", "absonly", "=", "True", ",", "compress", "=", "'gzip'", ")", ":",...
37.517241
19.172414
def get_output_shapes(self): """Get the shapes of the outputs.""" outputs = self.execs[0].outputs shapes = [out.shape for out in outputs] concat_shapes = [] for key, the_shape, axis in zip(self.symbol.list_outputs(), shapes, self.output_layouts): the_shape = list(the...
[ "def", "get_output_shapes", "(", "self", ")", ":", "outputs", "=", "self", ".", "execs", "[", "0", "]", ".", "outputs", "shapes", "=", "[", "out", ".", "shape", "for", "out", "in", "outputs", "]", "concat_shapes", "=", "[", "]", "for", "key", ",", ...
39.916667
15.416667
def add_user(self, username, email, directoryId=1, password=None, fullname=None, notify=False, active=True, ignore_existing=False, application_keys=None, ...
[ "def", "add_user", "(", "self", ",", "username", ",", "email", ",", "directoryId", "=", "1", ",", "password", "=", "None", ",", "fullname", "=", "None", ",", "notify", "=", "False", ",", "active", "=", "True", ",", "ignore_existing", "=", "False", ",",...
37.850746
19.955224
def add(self, name, mech, usage='both', init_lifetime=None, accept_lifetime=None, impersonator=None, store=None): """Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mecha...
[ "def", "add", "(", "self", ",", "name", ",", "mech", ",", "usage", "=", "'both'", ",", "init_lifetime", "=", "None", ",", "accept_lifetime", "=", "None", ",", "impersonator", "=", "None", ",", "store", "=", "None", ")", ":", "if", "store", "is", "not...
45.642857
23.952381
def handle_options(): '''Handle options. ''' parser = OptionParser() parser.set_defaults(aniso=False) parser.add_option("--dobs", dest="d_obs", help="field data", metavar="file", default="mod/volt.dat", ...
[ "def", "handle_options", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "set_defaults", "(", "aniso", "=", "False", ")", "parser", ".", "add_option", "(", "\"--dobs\"", ",", "dest", "=", "\"d_obs\"", ",", "help", "=", "\"field data\...
31.515152
12.787879
def send_vcard(self, number, name, data): """ Send location message :param str number: phone number with cc (country code) :param str name: indentifier for the location :param str data: vcard format i.e. BEGIN:VCARD VERSION:3.0 N:;Home;;; FN:Home ...
[ "def", "send_vcard", "(", "self", ",", "number", ",", "name", ",", "data", ")", ":", "vcard_message", "=", "VCardMediaMessageProtocolEntity", "(", "name", ",", "data", ",", "to", "=", "self", ".", "normalize_jid", "(", "number", ")", ")", "self", ".", "t...
32.764706
15.117647
def to_json(self, filename): """ Writes the experimental setup to a JSON file Parameters ---------- filename : str Absolute path where to write the JSON file """ with open(filename, 'w') as fp: json.dump(dict(stimuli=self.stimuli, inhibito...
[ "def", "to_json", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fp", ":", "json", ".", "dump", "(", "dict", "(", "stimuli", "=", "self", ".", "stimuli", ",", "inhibitors", "=", "self", ".", "inhibi...
32.545455
18.727273
def save_as_json(total: list, name='data.json', sort_by: str = None, no_duplicate=False, order='asc'): """Save what you crawled as a json file. Args: total (list): Total of data you crawled. name (str, optional): Defaults to 'd...
[ "def", "save_as_json", "(", "total", ":", "list", ",", "name", "=", "'data.json'", ",", "sort_by", ":", "str", "=", "None", ",", "no_duplicate", "=", "False", ",", "order", "=", "'asc'", ")", ":", "if", "sort_by", ":", "reverse", "=", "order", "==", ...
42.571429
18.904762
def forget_area(self, area_uuid): """ Remove an Upload Area from out cache of known areas. :param str area_uuid: The RFC4122-compliant UUID of the Upload Area. """ if self._config.upload.current_area == area_uuid: self._config.upload.current_area = None if are...
[ "def", "forget_area", "(", "self", ",", "area_uuid", ")", ":", "if", "self", ".", "_config", ".", "upload", ".", "current_area", "==", "area_uuid", ":", "self", ".", "_config", ".", "upload", ".", "current_area", "=", "None", "if", "area_uuid", "in", "se...
42.4
13
def remove_prefix(self, args): """ Remove a prefix. Valid keys in the `args`-struct: * `auth` [struct] Authentication options passed to the :class:`AuthFactory`. * `prefix` [struct] Attributes used to select what prefix to remove. ...
[ "def", "remove_prefix", "(", "self", ",", "args", ")", ":", "try", ":", "return", "self", ".", "nip", ".", "remove_prefix", "(", "args", ".", "get", "(", "'auth'", ")", ",", "args", ".", "get", "(", "'prefix'", ")", ",", "args", ".", "get", "(", ...
38.823529
18.058824
def follow_all_url(parser, token): """ Renders the URL to follow an object as both actor and target :: <a href="{% follow_all_url other_user %}"> {% if request.user|is_following:other_user %} stop following {% else %} follow {% en...
[ "def", "follow_all_url", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "3", ":", "raise", "TemplateSyntaxError", "(", "\"Accepted format {% follow_all_url [instance] %} or {% follo...
30.333333
21.060606
def total_ingredient_amounts(self): """ Returns: dict: In the form { (item_id, metadata) -> amount } """ totals = defaultdict(int) for id, meta, amount in self.ingredients: totals[(id, meta)] += amount return totals
[ "def", "total_ingredient_amounts", "(", "self", ")", ":", "totals", "=", "defaultdict", "(", "int", ")", "for", "id", ",", "meta", ",", "amount", "in", "self", ".", "ingredients", ":", "totals", "[", "(", "id", ",", "meta", ")", "]", "+=", "amount", ...
31
9.666667
def convert_gempak_table(infile, outfile): r"""Convert a GEMPAK color table to one MetPy can read. Reads lines from a GEMPAK-style color table file, and writes them to another file in a format that MetPy can parse. Parameters ---------- infile : file-like object The file-like object to...
[ "def", "convert_gempak_table", "(", "infile", ",", "outfile", ")", ":", "for", "line", "in", "infile", ":", "if", "not", "line", ".", "startswith", "(", "'!'", ")", "and", "line", ".", "strip", "(", ")", ":", "r", ",", "g", ",", "b", "=", "map", ...
33.555556
18.333333
def _read_call_freqs(in_file, sample_name): """Identify frequencies for calls in the input file. """ from bcbio.heterogeneity import bubbletree out = {} with VariantFile(in_file) as call_in: for rec in call_in: if rec.filter.keys() == ["PASS"]: for name, sample in...
[ "def", "_read_call_freqs", "(", "in_file", ",", "sample_name", ")", ":", "from", "bcbio", ".", "heterogeneity", "import", "bubbletree", "out", "=", "{", "}", "with", "VariantFile", "(", "in_file", ")", "as", "call_in", ":", "for", "rec", "in", "call_in", "...
41
11.785714
def __read(self, i: int) -> bytes: """Returns a set number (i) of bytes from self.data.""" b = self.data[self.idx: self.idx + i] self.idx += i if len(b) != i: raise bencodepy.DecodingError( "Incorrect byte length returned between indexes of {0} and {1}. Possib...
[ "def", "__read", "(", "self", ",", "i", ":", "int", ")", "->", "bytes", ":", "b", "=", "self", ".", "data", "[", "self", ".", "idx", ":", "self", ".", "idx", "+", "i", "]", "self", ".", "idx", "+=", "i", "if", "len", "(", "b", ")", "!=", ...
46.555556
18.666667
def c2s(self, p=None): """Convert from canvas to screen coordinates""" if not p: p = [0, 0] return p[0] - self.canvasx(self.cx1), p[1] - self.canvasy(self.cy2)
[ "def", "c2s", "(", "self", ",", "p", "=", "None", ")", ":", "if", "not", "p", ":", "p", "=", "[", "0", ",", "0", "]", "return", "p", "[", "0", "]", "-", "self", ".", "canvasx", "(", "self", ".", "cx1", ")", ",", "p", "[", "1", "]", "-",...
31.833333
22.333333
def thermostat_info(self): """:return: A thermostatinfo object modeled as a named tuple""" info = self._state['thermostatInfo'] return ThermostatInfo(info.get('activeState'), info.get('boilerModuleConnected'), info.get('burnerInfo'), ...
[ "def", "thermostat_info", "(", "self", ")", ":", "info", "=", "self", ".", "_state", "[", "'thermostatInfo'", "]", "return", "ThermostatInfo", "(", "info", ".", "get", "(", "'activeState'", ")", ",", "info", ".", "get", "(", "'boilerModuleConnected'", ")", ...
54.55
14.4
def secgroup_create(self, name, description): ''' Create a security group ''' nt_ks = self.compute_conn nt_ks.security_groups.create(name, description) ret = {'name': name, 'description': description} return ret
[ "def", "secgroup_create", "(", "self", ",", "name", ",", "description", ")", ":", "nt_ks", "=", "self", ".", "compute_conn", "nt_ks", ".", "security_groups", ".", "create", "(", "name", ",", "description", ")", "ret", "=", "{", "'name'", ":", "name", ","...
32.5
16.5
def get_options_from_file(self, file_path): """ Return the options parsed from a JSON file. """ # read options JSON file with open(file_path) as options_file: options_dict = json.load(options_file) options = [] for opt_name in options_dict: ...
[ "def", "get_options_from_file", "(", "self", ",", "file_path", ")", ":", "# read options JSON file", "with", "open", "(", "file_path", ")", "as", "options_file", ":", "options_dict", "=", "json", ".", "load", "(", "options_file", ")", "options", "=", "[", "]",...
35.416667
6.25
def read_cpp_source_file(self, source_file): """ Reads C++ source file and returns declarations tree :param source_file: path to C++ source file :type source_file: str """ xml_file = '' try: ffname = self.__file_full_name(source_file) se...
[ "def", "read_cpp_source_file", "(", "self", ",", "source_file", ")", ":", "xml_file", "=", "''", "try", ":", "ffname", "=", "self", ".", "__file_full_name", "(", "source_file", ")", "self", ".", "logger", ".", "debug", "(", "\"Reading source file: [%s].\"", ",...
35.181818
19.242424
def OnUpdate(self, event): """Menu state update""" if wx.ID_UNDO in self.id2menuitem: undo_item = self.id2menuitem[wx.ID_UNDO] undo_item.Enable(undo.stack().canundo()) if wx.ID_REDO in self.id2menuitem: redo_item = self.id2menuitem[wx.ID_REDO] re...
[ "def", "OnUpdate", "(", "self", ",", "event", ")", ":", "if", "wx", ".", "ID_UNDO", "in", "self", ".", "id2menuitem", ":", "undo_item", "=", "self", ".", "id2menuitem", "[", "wx", ".", "ID_UNDO", "]", "undo_item", ".", "Enable", "(", "undo", ".", "st...
30.75
17.166667
def list(self, request, *args, **kwargs): """ Each customer is associated with a group of users that represent customer owners. The link is maintained through **api/customer-permissions/** endpoint. To list all visible links, run a **GET** query against a list. Response will con...
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "CustomerPermissionViewSet", ",", "self", ")", ".", "list", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
42.916667
29.416667
def command(f=None, dtype_in=None, dformat_in=None, doc_in="", dtype_out=None, dformat_out=None, doc_out="", display_level=None, polling_period=None, green_mode=None): """ Declares a new tango command in a :class:`Device`. To be used like a decorator in the methods you wa...
[ "def", "command", "(", "f", "=", "None", ",", "dtype_in", "=", "None", ",", "dformat_in", "=", "None", ",", "doc_in", "=", "\"\"", ",", "dtype_out", "=", "None", ",", "dformat_out", "=", "None", ",", "doc_out", "=", "\"\"", ",", "display_level", "=", ...
36.163462
21.298077
def _postQueuedEvents(self, interval=0.01): """Private method to post queued events (e.g. Quartz events). Each event in queue is a tuple (event call, args to event call). """ while len(self.eventList) > 0: (nextEvent, args) = self.eventList.popleft() nextEvent(*a...
[ "def", "_postQueuedEvents", "(", "self", ",", "interval", "=", "0.01", ")", ":", "while", "len", "(", "self", ".", "eventList", ")", ">", "0", ":", "(", "nextEvent", ",", "args", ")", "=", "self", ".", "eventList", ".", "popleft", "(", ")", "nextEven...
38.777778
12.555556
def add_button(self, grid_lang, ass, row, column): """ The function is used for creating button with all features like signal on tooltip and signal on clicked The function does not have any menu. Button is add to the Gtk.Grid on specific row and column """ #print ...
[ "def", "add_button", "(", "self", ",", "grid_lang", ",", "ass", ",", "row", ",", "column", ")", ":", "#print \"gui_helper add_button\"", "image_name", "=", "ass", "[", "0", "]", ".", "icon_path", "label", "=", "\"<b>\"", "+", "ass", "[", "0", "]", ".", ...
40.666667
13.851852
def send_video_note(chat_id, video_note, duration=None, length=None, reply_to_message_id=None, reply_markup=None, disable_notification=False, **kwargs): """ Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). ...
[ "def", "send_video_note", "(", "chat_id", ",", "video_note", ",", "duration", "=", "None", ",", "length", "=", "None", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ",", "disable_notification", "=", "False", ",", "*", "*", "kwarg...
44.814815
29.333333
def connect(server, port, username, password): """This function might be something coming from your ORM""" print("-" * 79) print("Connecting to: {}".format(server)) print("At port: {}".format(port)) print("Using username: {}".format(username)) print("Using password: {}".format(password)) pri...
[ "def", "connect", "(", "server", ",", "port", ",", "username", ",", "password", ")", ":", "print", "(", "\"-\"", "*", "79", ")", "print", "(", "\"Connecting to: {}\"", ".", "format", "(", "server", ")", ")", "print", "(", "\"At port: {}\"", ".", "format"...
40.625
9
def flow_orifice(Diam, Height, RatioVCOrifice): """Return the flow rate of the orifice.""" #Checking input validity ut.check_range([Diam, ">0", "Diameter"], [RatioVCOrifice, "0-1", "VC orifice ratio"]) if Height > 0: return (RatioVCOrifice * area_circle(Diam).magnitude ...
[ "def", "flow_orifice", "(", "Diam", ",", "Height", ",", "RatioVCOrifice", ")", ":", "#Checking input validity", "ut", ".", "check_range", "(", "[", "Diam", ",", "\">0\"", ",", "\"Diameter\"", "]", ",", "[", "RatioVCOrifice", ",", "\"0-1\"", ",", "\"VC orifice ...
38.9
16.1
def ctr_counter(nonce, f, start = 0): """ Return an infinite iterator that starts at `start` and iterates by 1 over integers between 0 and 2^64 - 1 cyclically, returning on each iteration the result of combining each number with `nonce` using function `f`. `nonce` should be an random 64-bit integer that is...
[ "def", "ctr_counter", "(", "nonce", ",", "f", ",", "start", "=", "0", ")", ":", "for", "n", "in", "range", "(", "start", ",", "2", "**", "64", ")", ":", "yield", "f", "(", "nonce", ",", "n", ")", "while", "True", ":", "for", "n", "in", "range...
36.15
22.75
def AddSpecification(self, specification): """Adds a format specification. Args: specification (FormatSpecification): format specification. Raises: KeyError: if the store already contains a specification with the same identifier. """ if specification.identifier in self....
[ "def", "AddSpecification", "(", "self", ",", "specification", ")", ":", "if", "specification", ".", "identifier", "in", "self", ".", "_format_specifications", ":", "raise", "KeyError", "(", "'Format specification {0:s} is already defined in store.'", ".", "format", "(",...
34.965517
21.724138
def is_dimensionless_standard_name(xml_tree, standard_name): ''' Returns True if the units for the associated standard name are dimensionless. Dimensionless standard names include those that have no units and units that are defined as constant units in the CF standard name table i.e. '1', or '1e-3'...
[ "def", "is_dimensionless_standard_name", "(", "xml_tree", ",", "standard_name", ")", ":", "# standard_name must be string, so if it is not, it is *wrong* by default", "if", "not", "isinstance", "(", "standard_name", ",", "basestring", ")", ":", "return", "False", "found_stand...
51.826087
24.695652
def get_encoding_from_reponse(r): """获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码 """ encoding = requests.utils.get_encodings_from_content(r.text) return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers)
[ "def", "get_encoding_from_reponse", "(", "r", ")", ":", "encoding", "=", "requests", ".", "utils", ".", "get_encodings_from_content", "(", "r", ".", "text", ")", "return", "encoding", "[", "0", "]", "if", "encoding", "else", "requests", ".", "utils", ".", ...
26.727273
23.272727
async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]: """ Get encryption key to encrypt an S3 object :return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key """ if self.public_key is None: raise ValueError('Public k...
[ "async", "def", "get_encryption_aes_key", "(", "self", ")", "->", "Tuple", "[", "bytes", ",", "Dict", "[", "str", ",", "str", "]", ",", "str", "]", ":", "if", "self", ".", "public_key", "is", "None", ":", "raise", "ValueError", "(", "'Public key not prov...
42.266667
28.533333
def visibleCount(self): """ Returns the number of visible items in this list. :return <int> """ return sum(int(not self.item(i).isHidden()) for i in range(self.count()))
[ "def", "visibleCount", "(", "self", ")", ":", "return", "sum", "(", "int", "(", "not", "self", ".", "item", "(", "i", ")", ".", "isHidden", "(", ")", ")", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ")" ]
31.714286
17.142857
def _trim_adapters(fastq_files, out_dir, data): """ for small insert sizes, the read length can be longer than the insert resulting in the reverse complement of the 3' adapter being sequenced. this takes adapter sequences and trims the only the reverse complement of the adapter MYSEQUENCEAAAARE...
[ "def", "_trim_adapters", "(", "fastq_files", ",", "out_dir", ",", "data", ")", ":", "to_trim", "=", "_get_sequences_to_trim", "(", "data", "[", "\"config\"", "]", ",", "SUPPORTED_ADAPTERS", ")", "if", "dd", ".", "get_trim_reads", "(", "data", ")", "==", "\"f...
51.041667
24.458333
def query_entries( queryset=None, year=None, month=None, day=None, category=None, category_slug=None, tag=None, tag_slug=None, author=None, author_slug=None, future=False, order=None, orderby=None, limit=None, ): """ Query the entries using a set of predefined filters. Th...
[ "def", "query_entries", "(", "queryset", "=", "None", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "category", "=", "None", ",", "category_slug", "=", "None", ",", "tag", "=", "None", ",", "tag_slug", "=", "None"...
30.178082
20.534247
def validate(self, value, model=None, context=None): """ Validate Perform value validation and return result :param value: value to check :param model: parent model being validated :param context: object or None, validation context :re...
[ "def", "validate", "(", "self", ",", "value", ",", "model", "=", "None", ",", "context", "=", "None", ")", ":", "# ok if non-empty string", "if", "type", "(", "value", ")", "is", "str", ":", "value", "=", "value", ".", "strip", "(", ")", "if", "value...
28.516129
16.774194
def _rect_to_css(rect): """ Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order :param rect: a dlib 'rect' object :return: a plain tuple representation of the rect in (top, right, bottom, left) order """ return rect.top(), rect.right(), rect.bottom(), rect.left()
[ "def", "_rect_to_css", "(", "rect", ")", ":", "return", "rect", ".", "top", "(", ")", ",", "rect", ".", "right", "(", ")", ",", "rect", ".", "bottom", "(", ")", ",", "rect", ".", "left", "(", ")" ]
38.875
22.125
def _set_packet_encap_info_list(self, v, load=False): """ Setter method for packet_encap_info_list, mapped from YANG variable /packet_encap_processing_state/packet_encap_info_list (container) If this variable is read-only (config: false) in the source YANG file, then _set_packet_encap_info_list is consi...
[ "def", "_set_packet_encap_info_list", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
82.291667
40.416667
def create_groups(self, *names, **kwargs): """Convenience method to create multiple groups in a single call.""" return tuple(self.create_group(name, **kwargs) for name in names)
[ "def", "create_groups", "(", "self", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "return", "tuple", "(", "self", ".", "create_group", "(", "name", ",", "*", "*", "kwargs", ")", "for", "name", "in", "names", ")" ]
63.666667
11.666667
def set_value(instance, path, value, ref=None): """ Set `value` on `instance` at the given `path` and create missing intermediate objects. Parameters ---------- instance : dict or list instance from which to retrieve a value path : str path to retrieve a value from value : ...
[ "def", "set_value", "(", "instance", ",", "path", ",", "value", ",", "ref", "=", "None", ")", ":", "", "*", "head", ",", "tail", "=", "split_path", "(", "path", ",", "ref", ")", "for", "part", "in", "head", ":", "instance", "=", "instance", ".", ...
28.105263
16.421053
def compare_annotations(ref_sample, test_sample, window_width, signal=None): """ Compare a set of reference annotation locations against a set of test annotation locations. See the Comparitor class docstring for more information. Parameters ---------- ref_sample : 1d numpy array A...
[ "def", "compare_annotations", "(", "ref_sample", ",", "test_sample", ",", "window_width", ",", "signal", "=", "None", ")", ":", "comparitor", "=", "Comparitor", "(", "ref_sample", "=", "ref_sample", ",", "test_sample", "=", "test_sample", ",", "window_width", "=...
33.5
22.541667
def add(self, *blocks, indentation=0) -> "CodeBlock": """ Adds sub-blocks at the specified indentation level, which defaults to 0. Nones are skipped. Returns the parent block itself, useful for chaining. """ for block in blocks: if block is not None: ...
[ "def", "add", "(", "self", ",", "*", "blocks", ",", "indentation", "=", "0", ")", "->", "\"CodeBlock\"", ":", "for", "block", "in", "blocks", ":", "if", "block", "is", "not", "None", ":", "self", ".", "_blocks", ".", "append", "(", "(", "indentation"...
29.153846
20.384615
def _comments(self, lines): ''' comments is a wrapper for comment, intended to be given a list of comments. Parameters ========== lines: the list of lines to parse ''' for line in lines: comment = self._comment(line) ...
[ "def", "_comments", "(", "self", ",", "lines", ")", ":", "for", "line", "in", "lines", ":", "comment", "=", "self", ".", "_comment", "(", "line", ")", "self", ".", "comments", ".", "append", "(", "comment", ")" ]
28.583333
18.916667
def cooccurrences(self, domains): """Get the domains related to input domains. Args: domains: an enumerable of strings domain names Returns: An enumerable of string domain names """ api_name = 'opendns-cooccurrences' fmt_url_path = u'recommendatio...
[ "def", "cooccurrences", "(", "self", ",", "domains", ")", ":", "api_name", "=", "'opendns-cooccurrences'", "fmt_url_path", "=", "u'recommendations/name/{0}.json'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "domains", ")" ]
35.545455
14.909091
def es_required(fun): """Wrap a callable and return None if ES_DISABLED is False. This also adds an additional `es` argument to the callable giving you an ElasticSearch instance to use. """ @wraps(fun) def wrapper(*args, **kw): if getattr(settings, 'ES_DISABLED', False): lo...
[ "def", "es_required", "(", "fun", ")", ":", "@", "wraps", "(", "fun", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "getattr", "(", "settings", ",", "'ES_DISABLED'", ",", "False", ")", ":", "log", ".", "debug", "("...
28.666667
18.533333
def get_public_key_hex_from_tx( inputs, address ): """ Given a list of inputs and the address of one of the inputs, find the public key. This only works for p2pkh scripts. We only really need this for NAMESPACE_REVEAL, but we included it in other transactions' consensus data for legacy reason...
[ "def", "get_public_key_hex_from_tx", "(", "inputs", ",", "address", ")", ":", "ret", "=", "None", "for", "inp", "in", "inputs", ":", "input_scriptsig", "=", "inp", "[", "'script'", "]", "input_script_code", "=", "virtualchain", ".", "btc_script_deserialize", "("...
31.176471
19.176471
def inputfiles(self, inputtemplate=None): """Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate.""" if isinstance(inputtemplate, InputTemplate): #ID suffices: inputtemplate = inputtempl...
[ "def", "inputfiles", "(", "self", ",", "inputtemplate", "=", "None", ")", ":", "if", "isinstance", "(", "inputtemplate", ",", "InputTemplate", ")", ":", "#ID suffices:", "inputtemplate", "=", "inputtemplate", ".", "id", "for", "inputfile", "in", "self", ".", ...
59.375
11.375
def _parse_filter_string(filter_string): """ parse a filter string into a key-value pair """ assert "=" in filter_string, "filter string requires an '=', got {0}".format(filter_string) split_values = filter_string.split('=') assert len(split_values) == 2, "more than one equals found in filter string {0}...
[ "def", "_parse_filter_string", "(", "filter_string", ")", ":", "assert", "\"=\"", "in", "filter_string", ",", "\"filter string requires an '=', got {0}\"", ".", "format", "(", "filter_string", ")", "split_values", "=", "filter_string", ".", "split", "(", "'='", ")", ...
60.5
23.666667
def runCommand(command): """Run a command. :param command: the command to run. :type command: list Tries to run a command. If it fails, raise a :py:class:`ProgramError`. This function uses the :py:mod:`subprocess` module. .. warning:: The variable ``command`` should be a list of stri...
[ "def", "runCommand", "(", "command", ")", ":", "output", "=", "None", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "command", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "shell", "=", "False", ",", ")", "except", "subproce...
25.916667
20.75
def do_imageplaceholder(parser, token): """ Method that parse the imageplaceholder template tag. """ name, params = parse_placeholder(parser, token) return ImagePlaceholderNode(name, **params)
[ "def", "do_imageplaceholder", "(", "parser", ",", "token", ")", ":", "name", ",", "params", "=", "parse_placeholder", "(", "parser", ",", "token", ")", "return", "ImagePlaceholderNode", "(", "name", ",", "*", "*", "params", ")" ]
34.5
5.833333
def throw_punch(self, args, tries=1): """ Attempt to open a hole by TCP hole punching. This function is called by the simultaneous fight function and its the code that handles doing the actual hole punching / connecting. """ # Parse arguments. if...
[ "def", "throw_punch", "(", "self", ",", "args", ",", "tries", "=", "1", ")", ":", "# Parse arguments.\r", "if", "len", "(", "args", ")", "!=", "3", ":", "return", "0", "sock", ",", "node_ip", ",", "remote_port", "=", "args", "if", "sock", "is", "None...
36.246154
19.846154
def _run_quiet(cmd, cwd=None, stdin=None, output_encoding=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, ...
[ "def", "_run_quiet", "(", "cmd", ",", "cwd", "=", "None", ",", "stdin", "=", "None", ",", "output_encoding", "=", "None", ",", "runas", "=", "None", ",", "shell", "=", "DEFAULT_SHELL", ",", "python_shell", "=", "False", ",", "env", "=", "None", ",", ...
33.285714
10.761905
def create(self, root=None, namespace=None): """Create a sequence element with the given root. @param root: The C{etree.Element} to root the sequence at, if C{None} a new one will be created.. @result: A L{SequenceItem} with the given root. @raises L{ECResponseError}: If the...
[ "def", "create", "(", "self", ",", "root", "=", "None", ",", "namespace", "=", "None", ")", ":", "if", "root", "is", "not", "None", ":", "tag", "=", "root", ".", "tag", "if", "root", ".", "nsmap", ":", "namespace", "=", "root", ".", "nsmap", "[",...
44.529412
16.058824
def get_number_header_lines(docbody, page_break_posns): """Try to guess the number of header lines each page of a document has. The positions of the page breaks in the document are used to try to guess the number of header lines. @param docbody: (list) of strings - each string being a line in t...
[ "def", "get_number_header_lines", "(", "docbody", ",", "page_break_posns", ")", ":", "remaining_breaks", "=", "len", "(", "page_break_posns", ")", "-", "1", "num_header_lines", "=", "empty_line", "=", "0", "# pattern to search for a word in a line:", "p_wordSearch", "="...
45.164179
15.850746
def create_server(self, admin_login, admin_password, location): ''' Create a new Azure SQL Database server. admin_login: The administrator login name for the new server. admin_password: The administrator login password for the new server. location: ...
[ "def", "create_server", "(", "self", ",", "admin_login", ",", "admin_password", ",", "location", ")", ":", "_validate_not_none", "(", "'admin_login'", ",", "admin_login", ")", "_validate_not_none", "(", "'admin_password'", ",", "admin_password", ")", "_validate_not_no...
34.6
19.64
def add_layer(self, formula='', thickness=np.NaN, density=np.NaN): """provide another way to define the layers (stack) Parameters: =========== formula: string ex: 'CoAg2' ex: 'Al' thickness: float (in mm) density: float (g/cm3) """ i...
[ "def", "add_layer", "(", "self", ",", "formula", "=", "''", ",", "thickness", "=", "np", ".", "NaN", ",", "density", "=", "np", ".", "NaN", ")", ":", "if", "formula", "==", "''", ":", "return", "_new_stack", "=", "_utilities", ".", "formula_to_dictiona...
36.653846
21.884615
def edit_channel_info(self, new_ch_name, ch_dct): """Parent widget calls this whenever the user edits channel info. """ self.ch_name = new_ch_name self.dct = ch_dct if ch_dct['type'] == 'analog': fmter = fmt.green else: fmter = fmt.blue sel...
[ "def", "edit_channel_info", "(", "self", ",", "new_ch_name", ",", "ch_dct", ")", ":", "self", ".", "ch_name", "=", "new_ch_name", "self", ".", "dct", "=", "ch_dct", "if", "ch_dct", "[", "'type'", "]", "==", "'analog'", ":", "fmter", "=", "fmt", ".", "g...
35.636364
10.363636
def get_or_create_element(self, ns, name): """ Attempt to get the only child element from this SLDNode. If the node does not exist, create the element, attach it to the DOM, and return the class object that wraps the node. @type ns: string @param ns: The namespace o...
[ "def", "get_or_create_element", "(", "self", ",", "ns", ",", "name", ")", ":", "if", "len", "(", "self", ".", "_node", ".", "xpath", "(", "'%s:%s'", "%", "(", "ns", ",", "name", ")", ",", "namespaces", "=", "SLDNode", ".", "_nsmap", ")", ")", "==",...
41.111111
17.888889
def sample_number_of_occurrences(self, n=1): """ See :meth:`superclass method <.rupture.BaseRupture.sample_number_of_occurrences>` for spec of input and result values. Uses 'Inverse Transform Sampling' method. """ # compute cdf from pmf cdf = numpy.cumsum...
[ "def", "sample_number_of_occurrences", "(", "self", ",", "n", "=", "1", ")", ":", "# compute cdf from pmf", "cdf", "=", "numpy", ".", "cumsum", "(", "self", ".", "probs_occur", ")", "n_occ", "=", "numpy", ".", "digitize", "(", "numpy", ".", "random", ".", ...
34
11.166667
def check_output_directory(self, path): """ If the given directory cannot be written, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the output directory :type path: string (path) :rtype: bool """ if not os.path.i...
[ "def", "check_output_directory", "(", "self", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "self", ".", "print_error", "(", "u\"Directory '%s' does not exist\"", "%", "(", "path", ")", ")", "return", "False", ...
42.833333
19.944444
def get_by_id(self, id_networkv4): """Get IPv4 network :param id_networkv4: ID for NetworkIPv4 :return: IPv4 Network """ uri = 'api/networkv4/%s/' % id_networkv4 return super(ApiNetworkIPv4, self).get(uri)
[ "def", "get_by_id", "(", "self", ",", "id_networkv4", ")", ":", "uri", "=", "'api/networkv4/%s/'", "%", "id_networkv4", "return", "super", "(", "ApiNetworkIPv4", ",", "self", ")", ".", "get", "(", "uri", ")" ]
22.454545
18.454545
def check_minions(self, expr, tgt_type='glob', delimiter=DEFAULT_TARGET_DELIM, greedy=True): ''' Check the passed regex against the available minions' public keys stored for authentication. This should return...
[ "def", "check_minions", "(", "self", ",", "expr", ",", "tgt_type", "=", "'glob'", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "greedy", "=", "True", ")", ":", "try", ":", "if", "expr", "is", "None", ":", "expr", "=", "''", "check_func", "=", "g...
43.128205
17.692308
def get_instructions(self): """ Get all instructions from a basic block. :rtype: Return all instructions in the current basic block """ tmp_ins = [] idx = 0 for i in self.method.get_instructions(): if idx >= self.start and idx < self.end: ...
[ "def", "get_instructions", "(", "self", ")", ":", "tmp_ins", "=", "[", "]", "idx", "=", "0", "for", "i", "in", "self", ".", "method", ".", "get_instructions", "(", ")", ":", "if", "idx", ">=", "self", ".", "start", "and", "idx", "<", "self", ".", ...
27.428571
16
def result(self, line=''): """Print the result of the last asynchronous %px command. This lets you recall the results of %px computations after asynchronous submission (block=False). Examples -------- :: In [23]: %px os.getpid() Async pa...
[ "def", "result", "(", "self", ",", "line", "=", "''", ")", ":", "args", "=", "magic_arguments", ".", "parse_argstring", "(", "self", ".", "result", ",", "line", ")", "if", "self", ".", "last_result", "is", "None", ":", "raise", "UsageError", "(", "NO_L...
28.884615
18.423077
def validate(self, url): ''' takes in a Github repository for validation of preview and runtime (and possibly tests passing? ''' # Preview must provide the live URL of the repository if not url.startswith('http') or not 'github' in url: bot.error('Test of previe...
[ "def", "validate", "(", "self", ",", "url", ")", ":", "# Preview must provide the live URL of the repository", "if", "not", "url", ".", "startswith", "(", "'http'", ")", "or", "not", "'github'", "in", "url", ":", "bot", ".", "error", "(", "'Test of preview must ...
33
24.142857
def _publish_raw_metrics(self, metric, dat, tags, is_pod, depth=0): """ Recusively parses and submit metrics for a given entity, until reaching self.max_depth. Nested metric names are flattened: memory/usage -> memory.usage :param: metric: parent's metric name (check namespace fo...
[ "def", "_publish_raw_metrics", "(", "self", ",", "metric", ",", "dat", ",", "tags", ",", "is_pod", ",", "depth", "=", "0", ")", ":", "if", "depth", ">=", "self", ".", "max_depth", ":", "self", ".", "log", ".", "warning", "(", "'Reached max depth on metri...
45.857143
21.514286
def unzoom(self, event=None, set_bounds=True): """ zoom out 1 level, or to full data range """ lims = None if len(self.conf.zoom_lims) > 1: lims = self.conf.zoom_lims.pop() ax = self.axes if lims is None: # auto scale self.conf.zoom_lims = [None] ...
[ "def", "unzoom", "(", "self", ",", "event", "=", "None", ",", "set_bounds", "=", "True", ")", ":", "lims", "=", "None", "if", "len", "(", "self", ".", "conf", ".", "zoom_lims", ")", ">", "1", ":", "lims", "=", "self", ".", "conf", ".", "zoom_lims...
38.833333
8.75
def _re_flatten(p): ''' Turn all capturing groups in a regular expression pattern into non-capturing groups. ''' if '(' not in p: return p return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))', lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p)
[ "def", "_re_flatten", "(", "p", ")", ":", "if", "'('", "not", "in", "p", ":", "return", "p", "return", "re", ".", "sub", "(", "r'(\\\\*)(\\(\\?P<[^>]+>|\\((?!\\?))'", ",", "lambda", "m", ":", "m", ".", "group", "(", "0", ")", "if", "len", "(", "m", ...
46.666667
19.666667
def get_or_create(self, qualifier, new_parameter, **kwargs): """ Get a :class:`Parameter` from the ParameterSet, if it does not exist, create and attach it. Note: running this on a ParameterSet that is NOT a :class:`phoebe.frontend.bundle.Bundle`, will NOT add the Parame...
[ "def", "get_or_create", "(", "self", ",", "qualifier", ",", "new_parameter", ",", "*", "*", "kwargs", ")", ":", "ps", "=", "self", ".", "filter_or_get", "(", "qualifier", "=", "qualifier", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "ps", ",...
42.147059
21.029412
def _standardize_data( model: pd.DataFrame, data: pd.DataFrame, batch_key: str, ) -> Tuple[pd.DataFrame, pd.DataFrame, np.ndarray, np.ndarray]: """ Standardizes the data per gene. The aim here is to make mean and variance be comparable across batches. Parameters -------- model ...
[ "def", "_standardize_data", "(", "model", ":", "pd", ".", "DataFrame", ",", "data", ":", "pd", ".", "DataFrame", ",", "batch_key", ":", "str", ",", ")", "->", "Tuple", "[", "pd", ".", "DataFrame", ",", "pd", ".", "DataFrame", ",", "np", ".", "ndarray...
31.727273
20.424242
def selectionComponents(self): """Returns the names of the component types in this selection""" comps = [] model = self.model() for comp in self._selectedComponents: index = model.indexByComponent(comp) if index is not None: comps.append(comp) ...
[ "def", "selectionComponents", "(", "self", ")", ":", "comps", "=", "[", "]", "model", "=", "self", ".", "model", "(", ")", "for", "comp", "in", "self", ".", "_selectedComponents", ":", "index", "=", "model", ".", "indexByComponent", "(", "comp", ")", "...
36.444444
10