text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def set_nsxcontroller_ip(self, **kwargs): """ Set nsx-controller IP Args: IP (str): IPV4 address. callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: ...
[ "def", "set_nsxcontroller_ip", "(", "self", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "ip_addr", "=", "str", "(", "(", "kwargs", ".", "pop", "(", "'ip_addr'", ",", "None", ")", ")", ")", "nsxipaddress",...
31.642857
0.002191
def on_ok(self): """ Save changes made to vent.template """ # ensure user didn't have any syntactical errors input_is_good, trimmed_input = self.valid_input(self.edit_space.value) if not input_is_good: return self.edit_space.value = trimmed_input # get the nu...
[ "def", "on_ok", "(", "self", ")", ":", "# ensure user didn't have any syntactical errors", "input_is_good", ",", "trimmed_input", "=", "self", ".", "valid_input", "(", "self", ".", "edit_space", ".", "value", ")", "if", "not", "input_is_good", ":", "return", "self...
54.105556
0.000202
def get_gz_cn(offset: int) -> str: """Get n-th(0-based) GanZhi """ return TextUtils.STEMS[offset % 10] + TextUtils.BRANCHES[offset % 12]
[ "def", "get_gz_cn", "(", "offset", ":", "int", ")", "->", "str", ":", "return", "TextUtils", ".", "STEMS", "[", "offset", "%", "10", "]", "+", "TextUtils", ".", "BRANCHES", "[", "offset", "%", "12", "]" ]
39.25
0.0125
def arrow_head(document, x0, y0, x1, y1, arrowshape): "make arrow head at (x1,y1), arrowshape is tuple (d1, d2, d3)" import math dx = x1 - x0 dy = y1 - y0 poly = document.createElement('polygon') d = math.sqrt(dx*dx + dy*dy) if d == 0.0: # XXX: equal, no "close enough" return poly try: d1, d2, d3 = l...
[ "def", "arrow_head", "(", "document", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "arrowshape", ")", ":", "import", "math", "dx", "=", "x1", "-", "x0", "dy", "=", "y1", "-", "y0", "poly", "=", "document", ".", "createElement", "(", "'polygon'"...
19.058824
0.051395
def get_rss_feed_content(url, offset=0, limit=None, exclude_items_in=None): """ Get the entries from an RSS feed """ end = limit + offset if limit is not None else None response = _get(url) try: feed_data = feedparser.parse(response.text) if not feed_data.feed: log...
[ "def", "get_rss_feed_content", "(", "url", ",", "offset", "=", "0", ",", "limit", "=", "None", ",", "exclude_items_in", "=", "None", ")", ":", "end", "=", "limit", "+", "offset", "if", "limit", "is", "not", "None", "else", "None", "response", "=", "_ge...
30
0.001009
def create_network(self, network): """Enqueue network create""" n_res = MechResource(network['id'], a_const.NETWORK_RESOURCE, a_const.CREATE) self.provision_queue.put(n_res)
[ "def", "create_network", "(", "self", ",", "network", ")", ":", "n_res", "=", "MechResource", "(", "network", "[", "'id'", "]", ",", "a_const", ".", "NETWORK_RESOURCE", ",", "a_const", ".", "CREATE", ")", "self", ".", "provision_queue", ".", "put", "(", ...
44.4
0.00885
def create_global_steps(): """Creates TF ops to track and increment global training step.""" global_step = tf.Variable(0, name="global_step", trainable=False, dtype=tf.int32) increment_step = tf.assign(global_step, tf.add(global_step, 1)) return global_step, increment_step
[ "def", "create_global_steps", "(", ")", ":", "global_step", "=", "tf", ".", "Variable", "(", "0", ",", "name", "=", "\"global_step\"", ",", "trainable", "=", "False", ",", "dtype", "=", "tf", ".", "int32", ")", "increment_step", "=", "tf", ".", "assign",...
60.2
0.009836
def parse_java_version(version_text): """Return Java version (major1, major2). >>> parse_java_version('''java version "1.6.0_65" ... Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609) ... Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)) ... ''') (1, 6) >>>...
[ "def", "parse_java_version", "(", "version_text", ")", ":", "match", "=", "re", ".", "search", "(", "JAVA_VERSION_REGEX", ",", "version_text", ")", "if", "not", "match", ":", "raise", "SystemExit", "(", "'Could not parse Java version from \"\"\"{}\"\"\".'", ".", "fo...
33
0.00128
def next_frame_emily(): """Emily's model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.video_num_input_frames = 2 hparams.video_num_target_frames = 10 hparams.learning_rate_constant = 1e-4 seq_length = hparams.video_num_input_frames + hparams.video_num_target_frames # The latent_loss_multipl...
[ "def", "next_frame_emily", "(", ")", ":", "hparams", "=", "sv2p_params", ".", "next_frame_sv2p", "(", ")", "hparams", ".", "video_num_input_frames", "=", "2", "hparams", ".", "video_num_target_frames", "=", "10", "hparams", ".", "learning_rate_constant", "=", "1e-...
40.862069
0.023908
def main(data_dir, mtype_file): # pylint: disable=too-many-locals '''Run the stuff''' # data structure to store results stuff = load_neurite_features(data_dir) sim_params = json.load(open(mtype_file)) # load histograms, distribution parameter sets and figures into arrays. # To plot figures, do...
[ "def", "main", "(", "data_dir", ",", "mtype_file", ")", ":", "# pylint: disable=too-many-locals", "# data structure to store results", "stuff", "=", "load_neurite_features", "(", "data_dir", ")", "sim_params", "=", "json", ".", "load", "(", "open", "(", "mtype_file", ...
39.404762
0.001179
def center_slab(slab): """ The goal here is to ensure the center of the slab region is centered close to c=0.5. This makes it easier to find the surface sites and apply operations like doping. There are three cases where the slab in not centered: 1. The slab region is completely between...
[ "def", "center_slab", "(", "slab", ")", ":", "# get a reasonable r cutoff to sample neighbors", "bdists", "=", "sorted", "(", "[", "nn", "[", "1", "]", "for", "nn", "in", "slab", ".", "get_neighbors", "(", "slab", "[", "0", "]", ",", "10", ")", "if", "nn...
41.170213
0.000505
def get_metric_history_as_columns(self, slugs, since=None, granularity='daily'): """Provides the same data as ``get_metric_history``, but in a columnar format. If you had the following yearly history, for example:: [ ('m:bar:y:2012', '1'...
[ "def", "get_metric_history_as_columns", "(", "self", ",", "slugs", ",", "since", "=", "None", ",", "granularity", "=", "'daily'", ")", ":", "history", "=", "self", ".", "get_metric_history", "(", "slugs", ",", "since", ",", "granularity", "=", "granularity", ...
40.276596
0.002063
def one_hot_class_label_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Apply softmax cross-entropy between outputs and targets. Args: top_out: logits Tensor with shape [batch, ...
[ "def", "one_hot_class_label_loss", "(", "top_out", ",", "targets", ",", "model_hparams", ",", "vocab_size", ",", "weights_fn", ")", ":", "del", "model_hparams", ",", "vocab_size", "# unused arg", "loss_scale", "=", "tf", ".", "losses", ".", "softmax_cross_entropy", ...
34.652174
0.008547
def _alignmentToStr(self, result): """ Make a textual representation of an alignment result. @param result: A C{dict}, as returned by C{self.createAlignment}. @return: A C{str} desription of a result. For every three lines the first and third contain the input sequences, pos...
[ "def", "_alignmentToStr", "(", "self", ",", "result", ")", ":", "if", "result", "is", "None", ":", "return", "(", "'\\nNo alignment between %s and %s\\n'", "%", "(", "self", ".", "seq1ID", ",", "self", ".", "seq2ID", ")", ")", "else", ":", "header", "=", ...
40.029412
0.001435
def _sync_repo(self, repo_url: str, revision: str or None = None) -> Path: '''Clone a Git repository to the cache dir. If it has been cloned before, update it. :param repo_url: Repository URL :param revision: Revision: branch, commit hash, or tag :returns: Path to the cloned repository...
[ "def", "_sync_repo", "(", "self", ",", "repo_url", ":", "str", ",", "revision", ":", "str", "or", "None", "=", "None", ")", "->", "Path", ":", "repo_name", "=", "repo_url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ".", "rsplit", "(", "'...
30.267857
0.002286
def get_keys_from_class(cc): """Return list of the key property names for a class """ return [prop.name for prop in cc.properties.values() \ if 'key' in prop.qualifiers]
[ "def", "get_keys_from_class", "(", "cc", ")", ":", "return", "[", "prop", ".", "name", "for", "prop", "in", "cc", ".", "properties", ".", "values", "(", ")", "if", "'key'", "in", "prop", ".", "qualifiers", "]" ]
46.5
0.010582
def write(self, brightness): """Set the brightness of the LED to `brightness`. `brightness` can be a boolean for on/off, or integer value for a specific brightness. Args: brightness (bool, int): Brightness value to set. Raises: LEDError: if an I/O or OS...
[ "def", "write", "(", "self", ",", "brightness", ")", ":", "if", "not", "isinstance", "(", "brightness", ",", "(", "bool", ",", "int", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid brightness type, should be bool or int.\"", ")", "if", "isinstance", "(",...
34.882353
0.002461
def validateMasterArgument(self, master_arg): """ Parse the <master> argument. @param master_arg: the <master> argument to parse @return: tuple of master's host and port @raise UsageError: on errors parsing the argument """ if master_arg[:5] == "http:": ...
[ "def", "validateMasterArgument", "(", "self", ",", "master_arg", ")", ":", "if", "master_arg", "[", ":", "5", "]", "==", "\"http:\"", ":", "raise", "usage", ".", "UsageError", "(", "\"<master> is not a URL - do not use URL\"", ")", "if", "\":\"", "not", "in", ...
32.035714
0.002165
def _update_tag_status(self, process, vals): """ Updates the 'submitted', 'finished', 'failed' and 'retry' status of each process/tag combination. Process/tag combinations provided to this method already appear on the trace file, so their submission status is updated based on their ...
[ "def", "_update_tag_status", "(", "self", ",", "process", ",", "vals", ")", ":", "good_status", "=", "[", "\"COMPLETED\"", ",", "\"CACHED\"", "]", "# Update status of each process", "for", "v", "in", "list", "(", "vals", ")", "[", ":", ":", "-", "1", "]", ...
38.918033
0.000822
def split_extension(path): """ A extension splitter that checks for compound extensions such as 'file.nii.gz' Parameters ---------- filename : str A filename to split into base and extension Returns ------- base : str The base part of the string, i.e. 'file' of 'fil...
[ "def", "split_extension", "(", "path", ")", ":", "for", "double_ext", "in", "double_exts", ":", "if", "path", ".", "endswith", "(", "double_ext", ")", ":", "return", "path", "[", ":", "-", "len", "(", "double_ext", ")", "]", ",", "double_ext", "dirname",...
27.2
0.001183
def load_frombuffer(buf): """Loads an array dictionary or list from a buffer See more details in ``save``. Parameters ---------- buf : str Buffer containing contents of a file as a string or bytes. Returns ------- list of NDArray, RowSparseNDArray or CSRNDArray, or \ dict ...
[ "def", "load_frombuffer", "(", "buf", ")", ":", "if", "not", "isinstance", "(", "buf", ",", "string_types", "+", "tuple", "(", "[", "bytes", "]", ")", ")", ":", "raise", "TypeError", "(", "'buf required to be a string or bytes'", ")", "out_size", "=", "mx_ui...
38.314286
0.001455
def encode(cls, line): """ Backslash escape line.value. """ if not line.encoded: line.value = cls.listSeparator.join(backslashEscape(val) for val in line.value) line.encoded=True
[ "def", "encode", "(", "cls", ",", "line", ")", ":", "if", "not", "line", ".", "encoded", ":", "line", ".", "value", "=", "cls", ".", "listSeparator", ".", "join", "(", "backslashEscape", "(", "val", ")", "for", "val", "in", "line", ".", "value", ")...
34.375
0.010638
def _get_mask(self, struct1, struct2, fu, s1_supercell): """ Returns mask for matching struct2 to struct1. If struct1 has sites a b c, and fu = 2, assumes supercells of struct2 will be ordered aabbcc (rather than abcabc) Returns: mask, struct1 translation indices, struct...
[ "def", "_get_mask", "(", "self", ",", "struct1", ",", "struct2", ",", "fu", ",", "s1_supercell", ")", ":", "mask", "=", "np", ".", "zeros", "(", "(", "len", "(", "struct2", ")", ",", "len", "(", "struct1", ")", ",", "fu", ")", ",", "dtype", "=", ...
39.333333
0.001272
def do_filesizeformat(value, binary=False): """Format the value like a 'human-readable' file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega, Giga, etc.), if the second parameter is set to `True` the binary prefixes are used (Mebi, Gibi). """ bytes = float...
[ "def", "do_filesizeformat", "(", "value", ",", "binary", "=", "False", ")", ":", "bytes", "=", "float", "(", "value", ")", "base", "=", "binary", "and", "1024", "or", "1000", "prefixes", "=", "[", "(", "binary", "and", "'KiB'", "or", "'kB'", ")", ","...
35.392857
0.000982
def earthsun_distance(unixtime, delta_t, numthreads): """ Calculates the distance from the earth to the sun using the NREL SPA algorithm described in [1]. Parameters ---------- unixtime : numpy array Array of unix/epoch timestamps to calculate solar position for. Unixtime is the...
[ "def", "earthsun_distance", "(", "unixtime", ",", "delta_t", ",", "numthreads", ")", ":", "R", "=", "solar_position", "(", "unixtime", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "delta_t", ",", "0", ",", "numthreads", ",", "esd", "=", "...
31.5
0.001925
def _get_new_ref(self, existing_refs): """Get a new reference atom for a row in the ZMatrix The reference atoms should obey the following conditions: - They must be different - They must be neighbours in the bond graph - They must have an index lower than the c...
[ "def", "_get_new_ref", "(", "self", ",", "existing_refs", ")", ":", "# ref0 is the atom whose position is defined by the current row in the", "# zmatrix.", "ref0", "=", "existing_refs", "[", "0", "]", "for", "ref", "in", "existing_refs", ":", "# try to find a neighbor of th...
44.166667
0.002216
def create_entry(self, group, **kwargs): """ Create a new Entry object. The group which should hold the entry is needed. image must be an unsigned int >0, group a Group. :param group: The associated group. :keyword title: :keyword icon: ...
[ "def", "create_entry", "(", "self", ",", "group", ",", "*", "*", "kwargs", ")", ":", "if", "group", "not", "in", "self", ".", "groups", ":", "raise", "ValueError", "(", "\"Group doesn't exist / is not bound to this database.\"", ")", "uuid", "=", "binascii", "...
30.675676
0.010248
def update_clinvar_submission_status(self, user_id, submission_id, status): """Set a clinvar submission ID to 'closed' Args: submission_id(str): the ID of the clinvar submission to close Return updated_submission(obj): the submission object with a 'close...
[ "def", "update_clinvar_submission_status", "(", "self", ",", "user_id", ",", "submission_id", ",", "status", ")", ":", "LOG", ".", "info", "(", "'closing clinvar submission \"%s\"'", ",", "submission_id", ")", "if", "status", "==", "'open'", ":", "# just close the s...
39.896552
0.014346
def alpha_(self,x): """ Create a mappable function alpha to apply to each xmin in a list of xmins. This is essentially the slow version of fplfit/cplfit, though I bet it could be speeded up with a clever use of parellel_map. Not intended to be used by users.""" def alpha(xmin,x=x): ...
[ "def", "alpha_", "(", "self", ",", "x", ")", ":", "def", "alpha", "(", "xmin", ",", "x", "=", "x", ")", ":", "\"\"\"\n given a sorted data set and a minimum, returns power law MLE fit\n data is passed as a keyword parameter so that it can be vectorized\n ...
46.611111
0.010514
def update(self, configuration_url=values.unset, configuration_method=values.unset, configuration_filters=values.unset, configuration_triggers=values.unset, configuration_flow_sid=values.unset, configuration_retry_count=values.unset, ...
[ "def", "update", "(", "self", ",", "configuration_url", "=", "values", ".", "unset", ",", "configuration_method", "=", "values", ".", "unset", ",", "configuration_filters", "=", "values", ".", "unset", ",", "configuration_triggers", "=", "values", ".", "unset", ...
58.757576
0.008625
def listEverything(matching=False): """Prints every page in the project to the console. Args: matching (str, optional): if given, only return names with this string in it """ pages=pageNames() if matching: pages=[x for x in pages if matching in x] for i,page in enumerate(pages)...
[ "def", "listEverything", "(", "matching", "=", "False", ")", ":", "pages", "=", "pageNames", "(", ")", "if", "matching", ":", "pages", "=", "[", "x", "for", "x", "in", "pages", "if", "matching", "in", "x", "]", "for", "i", ",", "page", "in", "enume...
32
0.021028
def has_unknown_attachment_error(self, page_id): """ Check has unknown attachment error on page :param page_id: :return: """ unknown_attachment_identifier = 'plugins/servlet/confluence/placeholder/unknown-attachment' result = self.get_page_by_id(page_id, expand='b...
[ "def", "has_unknown_attachment_error", "(", "self", ",", "page_id", ")", ":", "unknown_attachment_identifier", "=", "'plugins/servlet/confluence/placeholder/unknown-attachment'", "result", "=", "self", ".", "get_page_by_id", "(", "page_id", ",", "expand", "=", "'body.view'"...
43.428571
0.008052
def hist(self, *columns, overlay=True, bins=None, bin_column=None, unit=None, counts=None, group=None, side_by_side=False, width=6, height=4, **vargs): """Plots one histogram for each column in columns. If no column is specified, plot all columns. Kwargs: overlay (bool): If True, pl...
[ "def", "hist", "(", "self", ",", "*", "columns", ",", "overlay", "=", "True", ",", "bins", "=", "None", ",", "bin_column", "=", "None", ",", "unit", "=", "None", ",", "counts", "=", "None", ",", "group", "=", "None", ",", "side_by_side", "=", "Fals...
48.664948
0.00218
def get_version(): """ Get the version from version module without importing more than necessary. """ version_module_path = os.path.join( os.path.dirname(__file__), "txspinneret", "_version.py") # The version module contains a variable called __version__ with open(version_module_path...
[ "def", "get_version", "(", ")", ":", "version_module_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"txspinneret\"", ",", "\"_version.py\"", ")", "# The version module contains a variable called __v...
36.454545
0.002433
def reduce(self, op): """ Reduces average value over all workers. :param op: 'sum' or 'mean', reduction operator """ if op not in ('sum', 'mean'): raise NotImplementedError distributed = (get_world_size() > 1) if distributed: # Backward/f...
[ "def", "reduce", "(", "self", ",", "op", ")", ":", "if", "op", "not", "in", "(", "'sum'", ",", "'mean'", ")", ":", "raise", "NotImplementedError", "distributed", "=", "(", "get_world_size", "(", ")", ">", "1", ")", "if", "distributed", ":", "# Backward...
38.581395
0.002352
def percent_of(percent, whole): """Calculates the value of a percent of a number ie: 5% of 20 is what --> 1 Args: percent (float): The percent of a number whole (float): The whole of the number Returns: float: The value of a percent Example: >>> per...
[ "def", "percent_of", "(", "percent", ",", "whole", ")", ":", "percent", "=", "float", "(", "percent", ")", "whole", "=", "float", "(", "whole", ")", "return", "(", "percent", "*", "whole", ")", "/", "100" ]
21.952381
0.010395
def main(): """Main function.""" if "-h" in sys.argv or "--help" in sys.argv: print(__doc__) print("Usage: regen_libxcfunc.py path_to_libxc_docs.txt") return 0 try: path = sys.argv[1] except IndexError: print(__doc__) print("Usage: regen_libxcfunc.py path...
[ "def", "main", "(", ")", ":", "if", "\"-h\"", "in", "sys", ".", "argv", "or", "\"--help\"", "in", "sys", ".", "argv", ":", "print", "(", "__doc__", ")", "print", "(", "\"Usage: regen_libxcfunc.py path_to_libxc_docs.txt\"", ")", "return", "0", "try", ":", "...
28.755102
0.000686
def get_literal_query(statement: Union[Query, Executable], bind: Connectable = None) -> str: """ Takes an SQLAlchemy statement and produces a literal SQL version, with values filled in. As per http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query ...
[ "def", "get_literal_query", "(", "statement", ":", "Union", "[", "Query", ",", "Executable", "]", ",", "bind", ":", "Connectable", "=", "None", ")", "->", "str", ":", "# noqa", "# log.debug(\"statement: {!r}\", statement)", "# log.debug(\"statement.bind: {!r}\", stateme...
39.044444
0.000278
def IntegerSum(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Performs a sum across all dimensions :param input_vertex: the vertex to have its values summed """ return Integer(context.jvm_view().IntegerSumVertex, label, cast_to_integer_vertex(input_verte...
[ "def", "IntegerSum", "(", "input_vertex", ":", "vertex_constructor_param_types", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Vertex", ":", "return", "Integer", "(", "context", ".", "jvm_view", "(", ")", ".", "IntegerSumVertex", "...
45.285714
0.018576
def subject(sid, subjects_path=None, meta_data=None, default_alignment='MSMAll'): ''' subject(sid) yields a HCP Subject object for the subject with the given subject id; sid may be a path to a subject or a subject id, in which case the subject paths are searched for it. subject(None, path) yields a no...
[ "def", "subject", "(", "sid", ",", "subjects_path", "=", "None", ",", "meta_data", "=", "None", ",", "default_alignment", "=", "'MSMAll'", ")", ":", "if", "subjects_path", "is", "None", ":", "if", "os", ".", "path", ".", "isdir", "(", "str", "(", "sid"...
49.025641
0.008205
def _access_token(self, request: Request=None, page_id: Text=''): """ Guess the access token for that specific request. """ if not page_id: msg = request.message # type: FacebookMessage page_id = msg.get_page_id() page = self.settings() if page...
[ "def", "_access_token", "(", "self", ",", "request", ":", "Request", "=", "None", ",", "page_id", ":", "Text", "=", "''", ")", ":", "if", "not", "page_id", ":", "msg", "=", "request", ".", "message", "# type: FacebookMessage", "page_id", "=", "msg", ".",...
33.529412
0.010239
def plot(self,*args,**kwargs): """ NAME: plot PURPOSE: plot the angles vs. each other, to check whether the isochrone approximation is good INPUT: Either: a) R,vR,vT,z,vz: floats: phase-space value for single obje...
[ "def", "plot", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#Kwargs", "type", "=", "kwargs", ".", "pop", "(", "'type'", ",", "'araz'", ")", "deperiod", "=", "kwargs", ".", "pop", "(", "'deperiod'", ",", "False", ")", "downsamp...
48.490476
0.020978
def _process_mappings(self, limit=None): """ This function imports linkage mappings of various entities to genetic locations in cM or cR. Entities include sequence variants, BAC ends, cDNA, ESTs, genes, PAC ends, RAPDs, SNPs, SSLPs, and STSs. Status: NEEDS REVIEW ...
[ "def", "_process_mappings", "(", "self", ",", "limit", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"Processing chromosome mappings\"", ")", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self"...
41.727273
0.00133
def date(self, date): """Set File Occurrence date.""" self._occurrence_data['date'] = self._utils.format_datetime( date, date_format='%Y-%m-%dT%H:%M:%SZ' )
[ "def", "date", "(", "self", ",", "date", ")", ":", "self", ".", "_occurrence_data", "[", "'date'", "]", "=", "self", ".", "_utils", ".", "format_datetime", "(", "date", ",", "date_format", "=", "'%Y-%m-%dT%H:%M:%SZ'", ")" ]
37.4
0.010471
def active(context, pattern_or_urlname, class_name='active', *args, **kwargs): """Based on a URL Pattern or name, determine if it is the current page. This is useful if you're creating a navigation component and want to give the active URL a specific class for UI purposes. It will accept a named URL or...
[ "def", "active", "(", "context", ",", "pattern_or_urlname", ",", "class_name", "=", "'active'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", "=", "context", ".", "dicts", "[", "1", "]", ".", "get", "(", "'request'", ")", "try", ":"...
27.125
0.000741
def _ensure_tuple_or_list(arg_name, tuple_or_list): """Ensures an input is a tuple or list. This effectively reduces the iterable types allowed to a very short whitelist: list and tuple. :type arg_name: str :param arg_name: Name of argument to use in error message. :type tuple_or_list: sequen...
[ "def", "_ensure_tuple_or_list", "(", "arg_name", ",", "tuple_or_list", ")", ":", "if", "not", "isinstance", "(", "tuple_or_list", ",", "(", "tuple", ",", "list", ")", ")", ":", "raise", "TypeError", "(", "\"Expected %s to be a tuple or list. \"", "\"Received %r\"", ...
34.227273
0.001292
def bytes2NativeString(x, encoding='utf-8'): """ Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just ret...
[ "def", "bytes2NativeString", "(", "x", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "x", ",", "bytes", ")", "and", "str", "!=", "bytes", ":", "return", "x", ".", "decode", "(", "encoding", ")", "return", "x" ]
29.473684
0.00173
def _process_human_orthos(self, limit=None): """ This table provides ortholog mappings between zebrafish and humans. ZFIN has their own process of creating orthology mappings, that we take in addition to other orthology-calling sources (like PANTHER). We ignore the omim ids, and ...
[ "def", "_process_human_orthos", "(", "self", ",", "limit", "=", "None", ")", ":", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", ".", "graph", "LOG", ".", "info", "(", "\"Processing human o...
36.380282
0.001508
def _getReadAlignments( self, reference, start, end, readGroupSet, readGroup): """ Returns an iterator over the specified reads """ # TODO If reference is None, return against all references, # including unmapped reads. samFile = self.getFileHandle(self._dataU...
[ "def", "_getReadAlignments", "(", "self", ",", "reference", ",", "start", ",", "end", ",", "readGroupSet", ",", "readGroup", ")", ":", "# TODO If reference is None, return against all references,", "# including unmapped reads.", "samFile", "=", "self", ".", "getFileHandle...
47.75
0.001283
def _pad_data(self, yextra, xextra): """ Pad the ``data`` and ``mask`` to have an integer number of background meshes of size ``box_size`` in both dimensions. The padding is added on the top and/or right edges (this is the best option for the "zoom" interpolator). Param...
[ "def", "_pad_data", "(", "self", ",", "yextra", ",", "xextra", ")", ":", "ypad", "=", "0", "xpad", "=", "0", "if", "yextra", ">", "0", ":", "ypad", "=", "self", ".", "box_size", "[", "0", "]", "-", "yextra", "if", "xextra", ">", "0", ":", "xpad...
33.843137
0.001126
def ts_to_df(metadata): """ Create a data frame from one TimeSeries object :param dict metadata: Time Series dictionary :return dict: One data frame per table, organized in a dictionary by name """ logger_dataframes.info("enter ts_to_df") dfs = {} # Plot the variable + values vs year, a...
[ "def", "ts_to_df", "(", "metadata", ")", ":", "logger_dataframes", ".", "info", "(", "\"enter ts_to_df\"", ")", "dfs", "=", "{", "}", "# Plot the variable + values vs year, age, depth (whichever are available)", "dfs", "[", "\"paleoData\"", "]", "=", "pd", ".", "DataF...
38.576923
0.001946
def get_count_query(self): """ Default filters for model """ return ( super().get_count_query() .filter(models.DagModel.is_active) .filter(~models.DagModel.is_subdag) )
[ "def", "get_count_query", "(", "self", ")", ":", "return", "(", "super", "(", ")", ".", "get_count_query", "(", ")", ".", "filter", "(", "models", ".", "DagModel", ".", "is_active", ")", ".", "filter", "(", "~", "models", ".", "DagModel", ".", "is_subd...
26.222222
0.008197
def _readReplacementFiles(self, directory, session, spatial, spatialReferenceID): """ Check for the parameter replacement file cards (REPLACE_PARAMS and REPLACE_VALS) and read the files into database if they exist. Returns: replaceParamFile or None if it doesn't exis...
[ "def", "_readReplacementFiles", "(", "self", ",", "directory", ",", "session", ",", "spatial", ",", "spatialReferenceID", ")", ":", "# Set default", "replaceParamFile", "=", "None", "# Check for REPLACE_PARAMS card", "replaceParamCard", "=", "self", ".", "getCard", "(...
39.02439
0.001829
def print_input(i): """ Input: { } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 html - input as JSON } """ o=i.ge...
[ "def", "print_input", "(", "i", ")", ":", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "rx", "=", "dumps_json", "(", "{", "'dict'", ":", "i", ",", "'sort_keys'", ":", "'yes'", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ...
18.8
0.026316
def parse_individual(self, individual): """Converts a deap individual into a full list of parameters. Parameters ---------- individual: deap individual from optimization Details vary according to type of optimization, but parameters within deap individual are alw...
[ "def", "parse_individual", "(", "self", ",", "individual", ")", ":", "scaled_ind", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "value_means", ")", ")", ":", "scaled_ind", ".", "append", "(", "self", ".", "value_means", "[", ...
38.153846
0.001967
def _initializeEncoders(self, encoderSpec): """ Initialize the encoders""" #Initializing scalar encoder if self.encoderType in ['adaptiveScalar', 'scalar']: if 'minval' in encoderSpec: self.minval = encoderSpec.pop('minval') else: self.minval=None if 'maxval' in encoderSpec: ...
[ "def", "_initializeEncoders", "(", "self", ",", "encoderSpec", ")", ":", "#Initializing scalar encoder", "if", "self", ".", "encoderType", "in", "[", "'adaptiveScalar'", ",", "'scalar'", "]", ":", "if", "'minval'", "in", "encoderSpec", ":", "self", ".", "minval"...
44.08
0.022202
def __make_request(self, requests_session, method, url, params, data, headers, certificate): """ Encapsulate requests call """ verify = False timeout = self.timeout try: # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-54...
[ "def", "__make_request", "(", "self", ",", "requests_session", ",", "method", ",", "url", ",", "params", ",", "data", ",", "headers", ",", "certificate", ")", ":", "verify", "=", "False", "timeout", "=", "self", ".", "timeout", "try", ":", "# TODO : Remove...
46.0625
0.01196
def _make_positive_axis(axis, ndims): """Rectify possibly negatively axis. Prefer return Python list.""" axis = _make_list_or_1d_tensor(axis) ndims = tf.convert_to_tensor(value=ndims, name='ndims', dtype=tf.int32) ndims_ = tf.get_static_value(ndims) if _is_list_like(axis) and ndims_ is not None: # Stati...
[ "def", "_make_positive_axis", "(", "axis", ",", "ndims", ")", ":", "axis", "=", "_make_list_or_1d_tensor", "(", "axis", ")", "ndims", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "ndims", ",", "name", "=", "'ndims'", ",", "dtype", "=", "tf", "...
30.1
0.016103
def check_response(self, resp): """raise a descriptive exception on a "bad request" response""" if resp.status_code == 400: raise ApiException(json.loads(resp.content).get('message')) return resp
[ "def", "check_response", "(", "self", ",", "resp", ")", ":", "if", "resp", ".", "status_code", "==", "400", ":", "raise", "ApiException", "(", "json", ".", "loads", "(", "resp", ".", "content", ")", ".", "get", "(", "'message'", ")", ")", "return", "...
45.4
0.008658
def asindices(hdr, spec): """Convert the given field `spec` into a list of field indices.""" flds = list(map(text_type, hdr)) indices = list() if not isinstance(spec, (list, tuple)): spec = (spec,) for s in spec: # spec could be a field index (takes priority) if isinstance(s...
[ "def", "asindices", "(", "hdr", ",", "spec", ")", ":", "flds", "=", "list", "(", "map", "(", "text_type", ",", "hdr", ")", ")", "indices", "=", "list", "(", ")", "if", "not", "isinstance", "(", "spec", ",", "(", "list", ",", "tuple", ")", ")", ...
32.529412
0.001757
def all_api_methods(cls): """ Return a list of all the TradingAlgorithm API methods. """ return [ fn for fn in itervalues(vars(cls)) if getattr(fn, 'is_api_method', False) ]
[ "def", "all_api_methods", "(", "cls", ")", ":", "return", "[", "fn", "for", "fn", "in", "itervalues", "(", "vars", "(", "cls", ")", ")", "if", "getattr", "(", "fn", ",", "'is_api_method'", ",", "False", ")", "]" ]
28.75
0.008439
def get_default_compartment(model): """Return what the default compartment should be set to. If some compounds have no compartment, unique compartment name is returned to avoid collisions. """ default_compartment = 'c' default_key = set() for reaction in model.reactions: equation = ...
[ "def", "get_default_compartment", "(", "model", ")", ":", "default_compartment", "=", "'c'", "default_key", "=", "set", "(", ")", "for", "reaction", "in", "model", ".", "reactions", ":", "equation", "=", "reaction", ".", "equation", "if", "equation", "is", "...
32.633333
0.000992
def parang (hourangle, declination, latitude): """Calculate the parallactic angle of a sky position. This computes the parallactic angle of a sky position expressed in terms of an hour angle and declination. Arguments: hourangle The hour angle of the location on the sky. declination Th...
[ "def", "parang", "(", "hourangle", ",", "declination", ",", "latitude", ")", ":", "return", "-", "np", ".", "arctan2", "(", "-", "np", ".", "sin", "(", "hourangle", ")", ",", "np", ".", "cos", "(", "declination", ")", "*", "np", ".", "tan", "(", ...
34.15
0.011396
def _init_db(self): """Creates the database tables.""" with self._get_db() as db: with open(self.schemapath) as f: db.cursor().executescript(f.read()) db.commit()
[ "def", "_init_db", "(", "self", ")", ":", "with", "self", ".", "_get_db", "(", ")", "as", "db", ":", "with", "open", "(", "self", ".", "schemapath", ")", "as", "f", ":", "db", ".", "cursor", "(", ")", ".", "executescript", "(", "f", ".", "read", ...
35.5
0.009174
def iter_user_repos(login, type=None, sort=None, direction=None, number=-1, etag=None): """List public repositories for the specified ``login``. .. versionadded:: 0.6 .. note:: This replaces github3.iter_repos :param str login: (required) :param str type: (optional), accepted ...
[ "def", "iter_user_repos", "(", "login", ",", "type", "=", "None", ",", "sort", "=", "None", ",", "direction", "=", "None", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "if", "login", ":", "return", "gh", ".", "iter_user_repos", ...
36.551724
0.000919
def firstPass(ASTs,verbose): '''Return a dictionary of function definition nodes, a dictionary of imported object names and a dictionary of imported module names. All three dictionaries use source file paths as keys.''' fdefs=dict() cdefs=dict() imp_obj_strs=dict() imp_mods=dict() for...
[ "def", "firstPass", "(", "ASTs", ",", "verbose", ")", ":", "fdefs", "=", "dict", "(", ")", "cdefs", "=", "dict", "(", ")", "imp_obj_strs", "=", "dict", "(", ")", "imp_mods", "=", "dict", "(", ")", "for", "(", "root", ",", "path", ")", "in", "ASTs...
42.30303
0.018207
def cmd_full_return( self, tgt, fun, arg=(), timeout=None, tgt_type='glob', ret='', verbose=False, kwarg=None, **kwargs): ''' Execute a salt command and return ''' was_...
[ "def", "cmd_full_return", "(", "self", ",", "tgt", ",", "fun", ",", "arg", "=", "(", ")", ",", "timeout", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "ret", "=", "''", ",", "verbose", "=", "False", ",", "kwarg", "=", "None", ",", "*", "*", ...
28.175
0.001715
def experiments_predictions_attachments_create(self, experiment_id, run_id, resource_id, filename, mime_type=None): """Attach a given data file with a model run. The attached file is identified by the resource identifier. If a resource with the given identifier already exists it will be overwrit...
[ "def", "experiments_predictions_attachments_create", "(", "self", ",", "experiment_id", ",", "run_id", ",", "resource_id", ",", "filename", ",", "mime_type", "=", "None", ")", ":", "# Get experiment to ensure that it exists", "if", "self", ".", "experiments_get", "(", ...
36.363636
0.002435
def TEST(cpu, src1, src2): """ Logical compare. Computes the bit-wise logical AND of first operand (source 1 operand) and the second operand (source 2 operand) and sets the SF, ZF, and PF status flags according to the result. The result is then discarded:: TEMP = ...
[ "def", "TEST", "(", "cpu", ",", "src1", ",", "src2", ")", ":", "# Defined Flags: szp", "temp", "=", "src1", ".", "read", "(", ")", "&", "src2", ".", "read", "(", ")", "cpu", ".", "SF", "=", "(", "temp", "&", "(", "1", "<<", "(", "src1", ".", ...
30.533333
0.002116
def _make_local_block(x, depth, batch, heads, num_blocks, block_length): """Helper function to create a local version of the keys or values for 1d.""" prev_block = tf.slice(x, [0, 0, 0, 0, 0], [-1, -1, num_blocks - 1, -1, -1]) cur_block = tf.slice(x, [0, 0, 1, 0, 0], [-1, -1, -1, -1, -1]) ...
[ "def", "_make_local_block", "(", "x", ",", "depth", ",", "batch", ",", "heads", ",", "num_blocks", ",", "block_length", ")", ":", "prev_block", "=", "tf", ".", "slice", "(", "x", ",", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", "]", ",", ...
59.5
0.012422
def load_project_metrics(): """ Create project metrics for financial indicator Updates them if already exists """ all_metrics = FinancialIndicator.METRICS for key in all_metrics: df = getattr(data, key) pronac = 'PRONAC' if key == 'planilha_captacao': pronac =...
[ "def", "load_project_metrics", "(", ")", ":", "all_metrics", "=", "FinancialIndicator", ".", "METRICS", "for", "key", "in", "all_metrics", ":", "df", "=", "getattr", "(", "data", ",", "key", ")", "pronac", "=", "'PRONAC'", "if", "key", "==", "'planilha_capta...
32.461538
0.002304
def get_family(self, family_id=None): """Gets the ``Family`` specified by its ``Id``. In plenary mode, the exact ``Id`` is found or a ``NotFound`` results. Otherwise, the returned ``Family`` may have a different ``Id`` than requested, such as the case where a duplicate ``Id`` wa...
[ "def", "get_family", "(", "self", ",", "family_id", "=", "None", ")", ":", "if", "family_id", "is", "None", ":", "raise", "NullArgument", "(", ")", "url_path", "=", "'/handcar/services/relationship/families/'", "+", "str", "(", "family_id", ")", "return", "obj...
47
0.001986
def get_jwt_dict(jwt_bu64): """Parse Base64 encoded JWT and return as a dict. - JWTs contain a set of values serialized to a JSON dict. This decodes the JWT and returns it as a dict containing Unicode strings. - In addition, a SHA1 hash is added to the dict for convenience. Args: jwt_bu64:...
[ "def", "get_jwt_dict", "(", "jwt_bu64", ")", ":", "jwt_tup", "=", "get_jwt_tup", "(", "jwt_bu64", ")", "try", ":", "jwt_dict", "=", "json", ".", "loads", "(", "jwt_tup", "[", "0", "]", ".", "decode", "(", "'utf-8'", ")", ")", "jwt_dict", ".", "update",...
34.391304
0.00246
def forbild(space, resolution=False, ear=True, value_type='density', scale='auto'): """Standard FORBILD phantom in 2 dimensions. The FORBILD phantom is intended for testing CT algorithms and is intended to be similar to a human head. The phantom is defined using the following materials: ...
[ "def", "forbild", "(", "space", ",", "resolution", "=", "False", ",", "ear", "=", "True", ",", "value_type", "=", "'density'", ",", "scale", "=", "'auto'", ")", ":", "def", "transposeravel", "(", "arr", ")", ":", "\"\"\"Implement MATLAB's ``transpose(arr(:))``...
37.455172
0.000179
def unattach_team(context, id, team_id): """unattach_team(context, id, team_id) Unattach a team from a topic. >>> dcictl topic-unattach-team [OPTIONS] :param string id: ID of the topic to unattach from [required] :param string team_id: ID of team to unattach from this topic, default is th...
[ "def", "unattach_team", "(", "context", ",", "id", ",", "team_id", ")", ":", "team_id", "=", "team_id", "or", "identity", ".", "my_team_id", "(", "context", ")", "result", "=", "topic", ".", "unattach_team", "(", "context", ",", "id", "=", "id", ",", "...
37.411765
0.001534
def isTagValid( self, tag ): """ Checks to see if the inputed tag is valid or not. :param tag | <str> :return <bool> """ if ( self._options is not None and \ not nativestring(tag) in self._options \ and not se...
[ "def", "isTagValid", "(", "self", ",", "tag", ")", ":", "if", "(", "self", ".", "_options", "is", "not", "None", "and", "not", "nativestring", "(", "tag", ")", "in", "self", ".", "_options", "and", "not", "self", ".", "isInsertAllowed", "(", ")", ")"...
27.882353
0.028571
def doDelete(self, WHAT={}): """This function will perform the command -delete.""" if hasattr(WHAT, '_modified'): self._addDBParam('RECORDID', WHAT.RECORDID) self._addDBParam('MODID', WHAT.MODID) elif type(WHAT) == dict and WHAT.has_key('RECORDID'): self._addDBParam('RECORDID', WHAT['RECORDID']) else:...
[ "def", "doDelete", "(", "self", ",", "WHAT", "=", "{", "}", ")", ":", "if", "hasattr", "(", "WHAT", ",", "'_modified'", ")", ":", "self", ".", "_addDBParam", "(", "'RECORDID'", ",", "WHAT", ".", "RECORDID", ")", "self", ".", "_addDBParam", "(", "'MOD...
33.777778
0.032
def parse_netloc(scheme, netloc): """Parse netloc string.""" auth, _netloc = netloc.split('@') sender, token = auth.split(':') if ':' in _netloc: domain, port = _netloc.split(':') port = int(port) else: domain = _netloc if scheme == 'https': port = 443 ...
[ "def", "parse_netloc", "(", "scheme", ",", "netloc", ")", ":", "auth", ",", "_netloc", "=", "netloc", ".", "split", "(", "'@'", ")", "sender", ",", "token", "=", "auth", ".", "split", "(", "':'", ")", "if", "':'", "in", "_netloc", ":", "domain", ",...
29.214286
0.00237
def _flds_append(flds, addthese, dont_add): """Retain order of fields as we add them once to the list.""" for fld in addthese: if fld not in flds and fld not in dont_add: flds.append(fld)
[ "def", "_flds_append", "(", "flds", ",", "addthese", ",", "dont_add", ")", ":", "for", "fld", "in", "addthese", ":", "if", "fld", "not", "in", "flds", "and", "fld", "not", "in", "dont_add", ":", "flds", ".", "append", "(", "fld", ")" ]
45.4
0.008658
def listen(self): """ Listens to messages """ with Consumer(self.connection, queues=self.queue, on_message=self.on_message, auto_declare=False): for _ in eventloop(self.connection, timeout=1, ignore_timeouts=True): pass
[ "def", "listen", "(", "self", ")", ":", "with", "Consumer", "(", "self", ".", "connection", ",", "queues", "=", "self", ".", "queue", ",", "on_message", "=", "self", ".", "on_message", ",", "auto_declare", "=", "False", ")", ":", "for", "_", "in", "e...
37.25
0.016393
def p_formula(self, p): """formula : formula EQUIVALENCE formula | formula IMPLIES formula | formula OR formula | formula AND formula | formula UNTIL formula | formula RELEASE formula | EVENTUALLY f...
[ "def", "p_formula", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "if", "p", "[", "1", "]", "==", "Symbols", ".", "TRUE", ".", "value", ":", "p", "[", "0", "]", "=", "LTLfTrue", "(", ")", "elif", "p", "[", "...
36.666667
0.001042
def spawn(self, __groups, __coro_fun, *args, **kwargs): """ Start a new coroutine and add it to the pool atomically. :param groups: The groups the coroutine belongs to. :type groups: :class:`set` of group keys :param coro_fun: Coroutine function to run :param args: Posit...
[ "def", "spawn", "(", "self", ",", "__groups", ",", "__coro_fun", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# ensure the implicit group is included", "__groups", "=", "set", "(", "__groups", ")", "|", "{", "(", ")", "}", "return", "asyncio", "...
38.888889
0.001394
def _apply_mask(self,p,mat): """Create (if necessary) and apply the mask to the given matrix mat.""" mask = p.mask ms=p.mask_shape if ms is not None: mask = ms(x=p.x+p.size*(ms.x*np.cos(p.orientation)-ms.y*np.sin(p.orientation)), y=p.y+p.size*(ms.x*np.si...
[ "def", "_apply_mask", "(", "self", ",", "p", ",", "mat", ")", ":", "mask", "=", "p", ".", "mask", "ms", "=", "p", ".", "mask_shape", "if", "ms", "is", "not", "None", ":", "mask", "=", "ms", "(", "x", "=", "p", ".", "x", "+", "p", ".", "size...
51.727273
0.020725
def run(self): """ Do a single DNS query against a server """ logging.debug("Querying server {0}".format(self.server['ip'])) try: # Create a DNS resolver query rsvr = dns.resolver.Resolver() rsvr.nameservers = [self.server['ip']] ...
[ "def", "run", "(", "self", ")", ":", "logging", ".", "debug", "(", "\"Querying server {0}\"", ".", "format", "(", "self", ".", "server", "[", "'ip'", "]", ")", ")", "try", ":", "# Create a DNS resolver query", "rsvr", "=", "dns", ".", "resolver", ".", "R...
29.410256
0.001688
def forward_request(self, method, path=None, json=None, params=None, headers=None): """Makes HTTP requests to the configured nodes. Retries connection errors (e.g. DNS failures, refused connection, etc). A user may choose to retry other errors ...
[ "def", "forward_request", "(", "self", ",", "method", ",", "path", "=", "None", ",", "json", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "error_trace", "=", "[", "]", "timeout", "=", "self", ".", "timeout", "backof...
36.736842
0.001395
def truncateletters(value, arg): """ Truncates a string after a certain number of letters Argument: Number of letters to truncate after """ warnings.warn( "`django_extensions.templatetags.truncate_letters` is deprecated. " "You should use `django.template.defaultfilters.truncatechars...
[ "def", "truncateletters", "(", "value", ",", "arg", ")", ":", "warnings", ".", "warn", "(", "\"`django_extensions.templatetags.truncate_letters` is deprecated. \"", "\"You should use `django.template.defaultfilters.truncatechars` instead\"", ",", "# noqa", "RemovedInNextVersionWarnin...
35.833333
0.002268
def customchain(**kwargsChain): """ This decorator allows you to access ``ctx.peerplays`` which is an instance of Peerplays. But in contrast to @chain, this is a decorator that expects parameters that are directed right to ``PeerPlays()``. ... code-block::python @ma...
[ "def", "customchain", "(", "*", "*", "kwargsChain", ")", ":", "def", "wrap", "(", "f", ")", ":", "@", "click", ".", "pass_context", "@", "verbose", "def", "new_func", "(", "ctx", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "newoptions", "=...
30.78125
0.000984
def color_validator(input_str): """ A filter allowing only the particular colors used by the Google Calendar API Raises ValidationError otherwise. """ try: assert input_str in VALID_OVERRIDE_COLORS + [''] return input_str except AssertionError: raise ValidationError(...
[ "def", "color_validator", "(", "input_str", ")", ":", "try", ":", "assert", "input_str", "in", "VALID_OVERRIDE_COLORS", "+", "[", "''", "]", "return", "input_str", "except", "AssertionError", ":", "raise", "ValidationError", "(", "'Expected colors are: '", "+", "'...
30.533333
0.002119
def prepare_node(data): """Prepare node for catalog endpoint Parameters: data (Union[str, dict]): Node ID or node definition Returns: Tuple[str, dict]: where first is ID and second is node definition Extract from /v1/health/service/<service>:: { "Node": { ...
[ "def", "prepare_node", "(", "data", ")", ":", "if", "not", "data", ":", "return", "None", ",", "{", "}", "if", "isinstance", "(", "data", ",", "str", ")", ":", "return", "data", ",", "{", "}", "# from /v1/health/service/<service>", "if", "all", "(", "f...
26.909091
0.000815
def variance_increase_distance(cluster1, cluster2, data = None): """! @brief Calculates variance increase distance between two clusters. @details Clusters can be represented by list of coordinates (in this case data shouldn't be specified), or by list of indexes of points from the data (rep...
[ "def", "variance_increase_distance", "(", "cluster1", ",", "cluster2", ",", "data", "=", "None", ")", ":", "# calculate local sum\r", "if", "data", "is", "None", ":", "member_cluster1", "=", "[", "0.0", "]", "*", "len", "(", "cluster1", "[", "0", "]", ")",...
45.059701
0.01329
def to_binary(self): """ :return: bytes """ pre_checksum_data = self.__checksum_data() checksum = velbus.checksum(pre_checksum_data) return pre_checksum_data + checksum + bytes([velbus.END_BYTE])
[ "def", "to_binary", "(", "self", ")", ":", "pre_checksum_data", "=", "self", ".", "__checksum_data", "(", ")", "checksum", "=", "velbus", ".", "checksum", "(", "pre_checksum_data", ")", "return", "pre_checksum_data", "+", "checksum", "+", "bytes", "(", "[", ...
34.714286
0.008032
def add(self, item): """ Add an item to the set, and return whether it was newly added """ with self.lock: if item in self.set: return False self.set.add(item) return True
[ "def", "add", "(", "self", ",", "item", ")", ":", "with", "self", ".", "lock", ":", "if", "item", "in", "self", ".", "set", ":", "return", "False", "self", ".", "set", ".", "add", "(", "item", ")", "return", "True" ]
33.285714
0.008368
def mcscanx(args): """ %prog mcscanx athaliana.athaliana.last athaliana.bed Wrap around MCScanX. """ p = OptionParser(mcscanx.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) blastfile = args[0] bedfiles = args[1:] prefix = "_".jo...
[ "def", "mcscanx", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mcscanx", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "<", "2", ":", "sys", ".", "exit", "(", "...
26.181818
0.001675
def from_dict(data, ctx): """ Instantiate a new LimitOrder from a dict (generally from loading a JSON response). The data used to instantiate the LimitOrder is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ data...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'clientExtensions'", ")", "is", "not", "None", ":", "data", "[", "'clientExtensions'", "]", "=", "ctx", ".", "transacti...
33.884615
0.001655
def observable_object_keys(instance): """Ensure observable-objects keys are non-negative integers. """ digits_re = re.compile(r"^\d+$") for key in instance['objects']: if not digits_re.match(key): yield JSONError("'%s' is not a good key value. Observable Objects " ...
[ "def", "observable_object_keys", "(", "instance", ")", ":", "digits_re", "=", "re", ".", "compile", "(", "r\"^\\d+$\"", ")", "for", "key", "in", "instance", "[", "'objects'", "]", ":", "if", "not", "digits_re", ".", "match", "(", "key", ")", ":", "yield"...
49.777778
0.002193
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = SeekBar(self.get_context(), None, d.style or '@attr/seekBarStyle')
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "widget", "=", "SeekBar", "(", "self", ".", "get_context", "(", ")", ",", "None", ",", "d", ".", "style", "or", "'@attr/seekBarStyle'", ")" ]
31.571429
0.008811
def assert_between(lower_bound, upper_bound, expr, msg_fmt="{msg}"): """Fail if an expression is not between certain bounds (inclusive). >>> assert_between(5, 15, 5) >>> assert_between(5, 15, 15) >>> assert_between(5, 15, 4.9) Traceback (most recent call last): ... AssertionError: 4.9 i...
[ "def", "assert_between", "(", "lower_bound", ",", "upper_bound", ",", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "not", "lower_bound", "<=", "expr", "<=", "upper_bound", ":", "msg", "=", "\"{!r} is not between {} and {}\"", ".", "format", "(", "...
30.461538
0.001224
def augment(module_name, base_class): """Call the augment() method for all of the derived classes in the module """ for name, cls in inspect.getmembers(sys.modules[module_name], lambda x : inspect.isclass(x) and issubclass(x, base_class) ): if cls == base_class:...
[ "def", "augment", "(", "module_name", ",", "base_class", ")", ":", "for", "name", ",", "cls", "in", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "module_name", "]", ",", "lambda", "x", ":", "inspect", ".", "isclass", "(", "x", ")", ...
39.555556
0.016484
def _print_table(rows, header=True): """Print a list of lists as a pretty table. Keyword arguments: header -- if True the first row is treated as a table header inspired by http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 """ border = "=" # vertical delimiter vdelim = " |...
[ "def", "_print_table", "(", "rows", ",", "header", "=", "True", ")", ":", "border", "=", "\"=\"", "# vertical delimiter", "vdelim", "=", "\" | \"", "# padding nr. of spaces are left around the longest element in the", "# column", "padding", "=", "1", "# may be left,center...
35.655172
0.009416
def select_site_view(self, request, form_url=''): """ Display a choice form to select which site to add settings. """ if not self.has_add_permission(request): raise PermissionDenied extra_qs = '' if request.META['QUERY_STRING']: extra_qs = '&' + r...
[ "def", "select_site_view", "(", "self", ",", "request", ",", "form_url", "=", "''", ")", ":", "if", "not", "self", ".", "has_add_permission", "(", "request", ")", ":", "raise", "PermissionDenied", "extra_qs", "=", "''", "if", "request", ".", "META", "[", ...
34.209302
0.001983