text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _normalize_timestamps(self, timestamp, intervals, config): ''' Helper for the subclasses to generate a list of timestamps. ''' rval = [timestamp] if intervals<0: while intervals<0: rval.append( config['i_calc'].normalize(timestamp, intervals) ) intervals += 1 elif inter...
[ "def", "_normalize_timestamps", "(", "self", ",", "timestamp", ",", "intervals", ",", "config", ")", ":", "rval", "=", "[", "timestamp", "]", "if", "intervals", "<", "0", ":", "while", "intervals", "<", "0", ":", "rval", ".", "append", "(", "config", "...
32.142857
23.142857
def rotateCD(self,orient): """ Rotates WCS CD matrix to new orientation given by 'orient' """ # Determine where member CRVAL position falls in ref frame # Find out whether this needs to be rotated to align with # reference frame. _delta = self.get_orient() - orient ...
[ "def", "rotateCD", "(", "self", ",", "orient", ")", ":", "# Determine where member CRVAL position falls in ref frame", "# Find out whether this needs to be rotated to align with", "# reference frame.", "_delta", "=", "self", ".", "get_orient", "(", ")", "-", "orient", "if", ...
37.190476
16
def prepare_graph_for_ui(graph, limit_attr_size=1024, large_attrs_key='_too_large_attrs'): """Prepares (modifies in-place) the graph to be served to the front-end. For now, it supports filtering out attributes that are too large to be shown in the graph UI. Args: graph: The GraphD...
[ "def", "prepare_graph_for_ui", "(", "graph", ",", "limit_attr_size", "=", "1024", ",", "large_attrs_key", "=", "'_too_large_attrs'", ")", ":", "# Check input for validity.", "if", "limit_attr_size", "is", "not", "None", ":", "if", "large_attrs_key", "is", "None", ":...
41.727273
19.75
def load_dataset(data_name): """Load sentiment dataset.""" if data_name == 'MR' or data_name == 'Subj': train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vo...
[ "def", "load_dataset", "(", "data_name", ")", ":", "if", "data_name", "==", "'MR'", "or", "data_name", "==", "'Subj'", ":", "train_dataset", ",", "output_size", "=", "_load_file", "(", "data_name", ")", "vocab", ",", "max_len", "=", "_build_vocab", "(", "dat...
62.428571
30.214286
def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool: """ Returns True if you have vision on a grid point. """ # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3...
[ "def", "is_visible", "(", "self", ",", "pos", ":", "Union", "[", "Point2", ",", "Point3", ",", "Unit", "]", ")", "->", "bool", ":", "# more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19", "ass...
68.166667
24.833333
def write_body(self, file, length=None): '''Send the request's content body. Coroutine. ''' _logger.debug('Sending body.') file_is_async = (asyncio.iscoroutine(file.read) or asyncio.iscoroutinefunction(file.read)) _logger.debug(__('Body is asyn...
[ "def", "write_body", "(", "self", ",", "file", ",", "length", "=", "None", ")", ":", "_logger", ".", "debug", "(", "'Sending body.'", ")", "file_is_async", "=", "(", "asyncio", ".", "iscoroutine", "(", "file", ".", "read", ")", "or", "asyncio", ".", "i...
29.222222
20.822222
def query_retrieve_comments_or_remarks( recID, display_order='od', display_since='0000-00-00 00:00:00', ranking=0, limit='all', user_info=None): """ Private function Retrieve tuple of comments or remarks from the database :param recID: record id :param...
[ "def", "query_retrieve_comments_or_remarks", "(", "recID", ",", "display_order", "=", "'od'", ",", "display_since", "=", "'0000-00-00 00:00:00'", ",", "ranking", "=", "0", ",", "limit", "=", "'all'", ",", "user_info", "=", "None", ")", ":", "display_since", "=",...
41.672897
19.915888
def parse_single_computer(entry): """ Parse the entry into a computer object. """ computer = Computer(dns_hostname=get_field(entry, 'dNSHostName'), description=get_field( entry, 'description'), os=get_field(entry, 'operatingSystem'), group_id=get_field(entry, 'primaryGroupID')) try: ...
[ "def", "parse_single_computer", "(", "entry", ")", ":", "computer", "=", "Computer", "(", "dns_hostname", "=", "get_field", "(", "entry", ",", "'dNSHostName'", ")", ",", "description", "=", "get_field", "(", "entry", ",", "'description'", ")", ",", "os", "="...
34.3125
23.1875
def _sm_stop_from_no_pain(self, *args, **kwargs): """ Stop chaos when there is no current blockade operation """ # Just stop the timer. It is possible that it was too late and the # timer is about to run _logger.info("Stopping chaos for blockade %s" % self._blockade_name...
[ "def", "_sm_stop_from_no_pain", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Just stop the timer. It is possible that it was too late and the", "# timer is about to run", "_logger", ".", "info", "(", "\"Stopping chaos for blockade %s\"", "%", "self"...
42.875
15.375
def link_types(self, base_dir: str, types: list, conf: Config) -> int: """Link all artifacts with types `types` under `base_dir` and return the number of linked artifacts.""" num_linked = 0 for kind in types: artifact_map = self._artifacts.get(kind) if not arti...
[ "def", "link_types", "(", "self", ",", "base_dir", ":", "str", ",", "types", ":", "list", ",", "conf", ":", "Config", ")", "->", "int", ":", "num_linked", "=", "0", "for", "kind", "in", "types", ":", "artifact_map", "=", "self", ".", "_artifacts", "....
45.818182
15
def SerializeExclusiveData(self, writer): """ Serialize object. Args: writer (neo.IO.BinaryWriter): """ self.Code.Serialize(writer) if self.Version >= 1: writer.WriteBool(self.NeedStorage) writer.WriteVarString(self.Name) writer....
[ "def", "SerializeExclusiveData", "(", "self", ",", "writer", ")", ":", "self", ".", "Code", ".", "Serialize", "(", "writer", ")", "if", "self", ".", "Version", ">=", "1", ":", "writer", ".", "WriteBool", "(", "self", ".", "NeedStorage", ")", "writer", ...
27.588235
11.941176
def get_r128_loudness(audio_filepaths, *, calc_peak=True, enable_ffmpeg_threading=True, ffmpeg_path=None): """ Get R128 loudness loudness level and sample peak. """ logger().info("Analyzing loudness of file%s %s..." % ("s" if (len(audio_filepaths) > 1) else "", ...
[ "def", "get_r128_loudness", "(", "audio_filepaths", ",", "*", ",", "calc_peak", "=", "True", ",", "enable_ffmpeg_threading", "=", "True", ",", "ffmpeg_path", "=", "None", ")", ":", "logger", "(", ")", ".", "info", "(", "\"Analyzing loudness of file%s %s...\"", "...
50.822785
26.835443
def _ssgc_prepare_data_and_run_computation( self, # voxels1, voxels2, hard_constraints=True, area_weight=1, ): """ Setting of data. You need set seeds if you want use hard_constraints. """ # from PyQt4.QtCore import pyqtRemoveInputHook ...
[ "def", "_ssgc_prepare_data_and_run_computation", "(", "self", ",", "# voxels1, voxels2,", "hard_constraints", "=", "True", ",", "area_weight", "=", "1", ",", ")", ":", "# from PyQt4.QtCore import pyqtRemoveInputHook", "# pyqtRemoveInputHook()", "# import pdb; pdb.set_trace() # BR...
36.557377
19.04918
def encode_id_token(self, id_token): """ Return encoded ID token. """ # Encode the ID token using the `client_secret`. # # TODO: Using the `client_secret` is not ideal, since it is transmitted # over the wire in some authentication flows. A better alternative i...
[ "def", "encode_id_token", "(", "self", ",", "id_token", ")", ":", "# Encode the ID token using the `client_secret`.", "#", "# TODO: Using the `client_secret` is not ideal, since it is transmitted", "# over the wire in some authentication flows. A better alternative is", "# to use the public...
36.352941
23.882353
def parse_url(arg, extract, key=None): """ Returns the portion of a URL corresponding to a part specified by 'extract' Can optionally specify a key to retrieve an associated value if extract parameter is 'QUERY' Parameters ---------- extract : one of {'PROTOCOL', 'HOST', 'PATH', 'REF', ...
[ "def", "parse_url", "(", "arg", ",", "extract", ",", "key", "=", "None", ")", ":", "return", "ops", ".", "ParseURL", "(", "arg", ",", "extract", ",", "key", ")", ".", "to_expr", "(", ")" ]
27.333333
21
def _SetYaraRules(self, yara_rules_string): """Sets the Yara rules. Args: yara_rules_string (str): unparsed Yara rule definitions. """ if not yara_rules_string: return analyzer_object = analyzers_manager.AnalyzersManager.GetAnalyzerInstance( 'yara') analyzer_object.SetRules...
[ "def", "_SetYaraRules", "(", "self", ",", "yara_rules_string", ")", ":", "if", "not", "yara_rules_string", ":", "return", "analyzer_object", "=", "analyzers_manager", ".", "AnalyzersManager", ".", "GetAnalyzerInstance", "(", "'yara'", ")", "analyzer_object", ".", "S...
28.538462
19
def groupdict(self, default=None): """Return a dictionary containing all the named subgroups of the match. The default argument is used for groups that did not participate in the match (defaults to None).""" groupdict = {} for key, value in self.re.groupindex.items(): ...
[ "def", "groupdict", "(", "self", ",", "default", "=", "None", ")", ":", "groupdict", "=", "{", "}", "for", "key", ",", "value", "in", "self", ".", "re", ".", "groupindex", ".", "items", "(", ")", ":", "groupdict", "[", "key", "]", "=", "self", "....
48.375
14
def save(self): """Over-rides the default save function for PlugEvents. If a sacrifice date is set for an object in this model, then Active is set to False.""" if self.SacrificeDate: self.Active = False super(PlugEvents, self).save()
[ "def", "save", "(", "self", ")", ":", "if", "self", ".", "SacrificeDate", ":", "self", ".", "Active", "=", "False", "super", "(", "PlugEvents", ",", "self", ")", ".", "save", "(", ")" ]
38.857143
12.285714
def coastal_coords(): """ A coastal coord is a 2-tuple: (tile id, direction). An edge is coastal if it is on the grid's border. :return: list( (tile_id, direction) ) """ coast = list() for tile_id in coastal_tile_ids(): tile_coord = tile_id_to_coord(tile_id) for edge_coord ...
[ "def", "coastal_coords", "(", ")", ":", "coast", "=", "list", "(", ")", "for", "tile_id", "in", "coastal_tile_ids", "(", ")", ":", "tile_coord", "=", "tile_id_to_coord", "(", "tile_id", ")", "for", "edge_coord", "in", "coastal_edges", "(", "tile_id", ")", ...
33.705882
14.882353
def print_search_results(self, search_results, buf=sys.stdout): """Print formatted search results. Args: search_results (list of `ResourceSearchResult`): Search to format. """ formatted_lines = self.format_search_results(search_results) pr = Printer(buf) for...
[ "def", "print_search_results", "(", "self", ",", "search_results", ",", "buf", "=", "sys", ".", "stdout", ")", ":", "formatted_lines", "=", "self", ".", "format_search_results", "(", "search_results", ")", "pr", "=", "Printer", "(", "buf", ")", "for", "txt",...
33.454545
20.636364
def copy_file_if_update_required(source_file, target_file): """Copies source_file to target_file if latter one in not existing or outdated :param source_file: Source file of the copy operation :param target_file: Target file of the copy operation """ if file_needs_update(target_file, source_file): ...
[ "def", "copy_file_if_update_required", "(", "source_file", ",", "target_file", ")", ":", "if", "file_needs_update", "(", "target_file", ",", "source_file", ")", ":", "shutil", ".", "copy", "(", "source_file", ",", "target_file", ")" ]
44.75
13.625
def register_view(self, view): """Called when the View was registered Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application """ super(SingleWidgetWindowController, self).register_view(view) self.shortcut_manager = ShortcutManager(sel...
[ "def", "register_view", "(", "self", ",", "view", ")", ":", "super", "(", "SingleWidgetWindowController", ",", "self", ")", ".", "register_view", "(", "view", ")", "self", ".", "shortcut_manager", "=", "ShortcutManager", "(", "self", ".", "view", "[", "'main...
44.9
25.2
def getParameter(self, parameterName, index=-1): """ Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameter`. Most parameters are handled automatically by PyRegion's parameter get mechanism. The ones that need special treatment are explicitly handled here. """ if parame...
[ "def", "getParameter", "(", "self", ",", "parameterName", ",", "index", "=", "-", "1", ")", ":", "if", "parameterName", "==", "'activeOutputCount'", ":", "return", "self", ".", "columnCount", "elif", "parameterName", "==", "'spatialPoolerInput'", ":", "return", ...
40.633333
15.766667
def generate_cont(self, max_length, state_size, reply_to, backward, dataset): """Generate texts from start/end. Parameters ---------- max_length : `int` or `None` Maximum sentence length. state_size : `int` State size. reply_...
[ "def", "generate_cont", "(", "self", ",", "max_length", ",", "state_size", ",", "reply_to", ",", "backward", ",", "dataset", ")", ":", "state", "=", "self", ".", "get_cont_state", "(", "reply_to", ",", "backward", ")", "while", "True", ":", "parts", "=", ...
31.5
14.875
def parts( self ): """ Returns the parts that are used for this system. :return [<str>, ..] """ path = nativestring(self.text()).strip(self.separator()) if ( not path ): return [] return path.split(self.separator())
[ "def", "parts", "(", "self", ")", ":", "path", "=", "nativestring", "(", "self", ".", "text", "(", ")", ")", ".", "strip", "(", "self", ".", "separator", "(", ")", ")", "if", "(", "not", "path", ")", ":", "return", "[", "]", "return", "path", "...
28.7
14.1
def get_optionals_without_choices(self, actions): """ All actions which are: (a) Optional, but without required choices (b) Not of a "boolean" type (storeTrue, etc..) (c) Of type _AppendAction e.g. anything which has an argument style like: >>> -f myfilename.txt """ boolean...
[ "def", "get_optionals_without_choices", "(", "self", ",", "actions", ")", ":", "boolean_actions", "=", "(", "_StoreConstAction", ",", "_StoreFalseAction", ",", "_StoreTrueAction", ")", "return", "[", "action", "for", "action", "in", "actions", "if", "action", ".",...
31.809524
12.47619
def _make_jsmin(python_only=False): """ Generate JS minifier based on `jsmin.c by Douglas Crockford`_ .. _jsmin.c by Douglas Crockford: http://www.crockford.com/javascript/jsmin.c :Parameters: `python_only` : ``bool`` Use only the python variant. If true, the c extension is not ev...
[ "def", "_make_jsmin", "(", "python_only", "=", "False", ")", ":", "# pylint: disable = R0912, R0914, W0612", "if", "not", "python_only", ":", "try", ":", "import", "_rjsmin", "except", "ImportError", ":", "pass", "else", ":", "return", "_rjsmin", ".", "jsmin", "...
32.806452
16.509677
def get_thin_rect_vertices(ox, oy, dx, dy, r): """Given the starting point, ending point, and width, return a list of vertex coordinates at the corners of the line segment (really a thin rectangle). """ if ox < dx: leftx = ox rightx = dx xco = 1 elif ox > dx: lef...
[ "def", "get_thin_rect_vertices", "(", "ox", ",", "oy", ",", "dx", ",", "dy", ",", "r", ")", ":", "if", "ox", "<", "dx", ":", "leftx", "=", "ox", "rightx", "=", "dx", "xco", "=", "1", "elif", "ox", ">", "dx", ":", "leftx", "=", "ox", "*", "-",...
21.192982
19.631579
def process_next_position(data, cgi_input, header, reference, var_only): """ Determine appropriate processing to get data, then convert it to VCF There are two types of lines in the var file: - "full position": single allele (hemizygous) or all-allele line All alleles at this position are repre...
[ "def", "process_next_position", "(", "data", ",", "cgi_input", ",", "header", ",", "reference", ",", "var_only", ")", ":", "if", "data", "[", "2", "]", "==", "\"all\"", "or", "data", "[", "1", "]", "==", "\"1\"", ":", "# The output from process_full_position...
52.02381
24.928571
def init_app(self, app): """Initializes your mail settings from the application settings. You can use this if you want to set up your Mail instance at configuration time. :param app: Flask application instance """ state = self.init_mail(app.config, app.debug, app.testin...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "state", "=", "self", ".", "init_mail", "(", "app", ".", "config", ",", "app", ".", "debug", ",", "app", ".", "testing", ")", "# register extension with app", "app", ".", "extensions", "=", "getattr",...
33.142857
17.357143
def reset(self): """ Reset all fields of this object to class defaults """ for name in self.__dict__: if name.startswith("_"): continue attr = getattr(self, name) setattr(self, name, attr and attr.__class__())
[ "def", "reset", "(", "self", ")", ":", "for", "name", "in", "self", ".", "__dict__", ":", "if", "name", ".", "startswith", "(", "\"_\"", ")", ":", "continue", "attr", "=", "getattr", "(", "self", ",", "name", ")", "setattr", "(", "self", ",", "name...
28.5
12.7
def assemble_cyjs(): """Assemble INDRA Statements and return Cytoscape JS network.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) cja = CyJ...
[ "def", "assemble_cyjs", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
34.153846
9.538462
def make_marketplace_registration_url(self, returnURL, pipelineName, maxFixedFee=0.0, maxVariableFee=0.0, recipientPaysFee=True, **params): """ Generate the URL with the signature required for signing up a recipient ...
[ "def", "make_marketplace_registration_url", "(", "self", ",", "returnURL", ",", "pipelineName", ",", "maxFixedFee", "=", "0.0", ",", "maxVariableFee", "=", "0.0", ",", "recipientPaysFee", "=", "True", ",", "*", "*", "params", ")", ":", "# use the sandbox authoriza...
40.6
18.2
def load_filters(): """ Loads and returns all filters. """ all_filters = {} for m in JINJA_FILTERS: if hasattr(m, "filters"): all_filters.update(m.filters()) return all_filters
[ "def", "load_filters", "(", ")", ":", "all_filters", "=", "{", "}", "for", "m", "in", "JINJA_FILTERS", ":", "if", "hasattr", "(", "m", ",", "\"filters\"", ")", ":", "all_filters", ".", "update", "(", "m", ".", "filters", "(", ")", ")", "return", "all...
23.555556
9.777778
def callToThread(method): """ Wrap call to method to send it to WebCacheThread. """ def func_wrapped(self, *args, **kwargs): self.thread.execute_queue.put_nowait((threading.get_ident(), method, args, kwargs)) return self.waitResult() return func_wrapped
[ "def", "callToThread", "(", "method", ")", ":", "def", "func_wrapped", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "thread", ".", "execute_queue", ".", "put_nowait", "(", "(", "threading", ".", "get_ident", "(", ")", ...
45.333333
15.833333
def beta(self): """ The result :math:`\\beta` of the linear least squares """ if self._beta is None: # This is the linear least squares matrix formalism self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y) return self._beta
[ "def", "beta", "(", "self", ")", ":", "if", "self", ".", "_beta", "is", "None", ":", "# This is the linear least squares matrix formalism", "self", ".", "_beta", "=", "_np", ".", "dot", "(", "_np", ".", "linalg", ".", "pinv", "(", "self", ".", "X", ")", ...
35.25
15
def synchronize_clock(self, offset): """Persistently synchronize the clock to UTC time. Args: offset (int): The number of seconds since 1/1/2000 00:00Z """ self.time_offset = offset - self.uptime self.is_utc = True if self.has_rtc: self.stored_o...
[ "def", "synchronize_clock", "(", "self", ",", "offset", ")", ":", "self", ".", "time_offset", "=", "offset", "-", "self", ".", "uptime", "self", ".", "is_utc", "=", "True", "if", "self", ".", "has_rtc", ":", "self", ".", "stored_offset", "=", "self", "...
27.75
18.833333
def grad(self, x): r"""Compute the gradient of a signal defined on the vertices. The gradient :math:`y` of a signal :math:`x` is defined as .. math:: y = \nabla_\mathcal{G} x = D^\top x, where :math:`D` is the differential operator :attr:`D`. The value of the gradient on the ...
[ "def", "grad", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "_check_signal", "(", "x", ")", "return", "self", ".", "D", ".", "T", ".", "dot", "(", "x", ")" ]
32.74026
23.935065
def evaluate(self, epoch, iteration, summary): """ Runs evaluation on test dataset. :param epoch: index of the current epoch :param iteration: index of the current iteration :param summary: if True prints summary """ batch_time = AverageMeter(False) tot_t...
[ "def", "evaluate", "(", "self", ",", "epoch", ",", "iteration", ",", "summary", ")", ":", "batch_time", "=", "AverageMeter", "(", "False", ")", "tot_tok_per_sec", "=", "AverageMeter", "(", "False", ")", "iterations", "=", "AverageMeter", "(", "False", ")", ...
37.458716
18.302752
def is_smooth_from(self, previous, warning_on=True): """[Warning: The name of this method is somewhat misleading (yet kept for compatibility with scripts created using svg.path 2.0). This method is meant only for d string creation and should not be used to check for kinks. To check a s...
[ "def", "is_smooth_from", "(", "self", ",", "previous", ",", "warning_on", "=", "True", ")", ":", "if", "warning_on", ":", "warn", "(", "_is_smooth_from_warning", ")", "if", "isinstance", "(", "previous", ",", "CubicBezier", ")", ":", "return", "(", "self", ...
52.142857
15.285714
def ReadTif(tifFile): """Reads a tif file to a 2D NumPy array""" img = Image.open(tifFile) img = np.array(img) return img
[ "def", "ReadTif", "(", "tifFile", ")", ":", "img", "=", "Image", ".", "open", "(", "tifFile", ")", "img", "=", "np", ".", "array", "(", "img", ")", "return", "img" ]
29.8
12.2
def _format_filename(self, prefix, year, week): """Construct the file name based on the path and options.""" return "{}{}_{}-{}.csv".format(self.base_path, prefix, year, week)
[ "def", "_format_filename", "(", "self", ",", "prefix", ",", "year", ",", "week", ")", ":", "return", "\"{}{}_{}-{}.csv\"", ".", "format", "(", "self", ".", "base_path", ",", "prefix", ",", "year", ",", "week", ")" ]
63
13.666667
def download(asset_type, dest, limit, sort, search_id, dry_run, activate_only, quiet, **kw): '''Activate and download''' cl = clientv1() page_size = min(limit or 250, 250) asset_type = list(chain.from_iterable(asset_type)) # even though we're using functionality from click.Path, this wa...
[ "def", "download", "(", "asset_type", ",", "dest", ",", "limit", ",", "sort", ",", "search_id", ",", "dry_run", ",", "activate_only", ",", "quiet", ",", "*", "*", "kw", ")", ":", "cl", "=", "clientv1", "(", ")", "page_size", "=", "min", "(", "limit",...
40.698113
18.09434
def _scan_step(self, vars): """ Internal scan with dummy input variables. """ from neural_var import NeuralVariable if not self._loop_vars: raise Exception("The loop is not initialized. To initialize the loop, use `with loop as vars`") replace_map = {} ...
[ "def", "_scan_step", "(", "self", ",", "vars", ")", ":", "from", "neural_var", "import", "NeuralVariable", "if", "not", "self", ".", "_loop_vars", ":", "raise", "Exception", "(", "\"The loop is not initialized. To initialize the loop, use `with loop as vars`\"", ")", "r...
43.722222
17.944444
def expanded_callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value ''' Form an expanded callback. This function registers the callback function, and sets an internal flag that mandates that all callbacks are passed the enhanced arguments. ...
[ "def", "expanded_callback", "(", "self", ",", "output", ",", "inputs", "=", "[", "]", ",", "state", "=", "[", "]", ",", "events", "=", "[", "]", ")", ":", "# pylint: disable=dangerous-default-value", "self", ".", "_expanded_callbacks", "=", "True", "return",...
46.555556
29.888889
def get_version(): """ Return BROTLI_VERSION string as defined in 'common/version.h' file. """ version_file_path = os.path.join(CURR_DIR, 'c', 'common', 'version.h') version = 0 with open(version_file_path, 'r') as f: for line in f: m = re.match(r'#define\sBROTLI_VERSION\s+0x([0-9a-f...
[ "def", "get_version", "(", ")", ":", "version_file_path", "=", "os", ".", "path", ".", "join", "(", "CURR_DIR", ",", "'c'", ",", "'common'", ",", "'version.h'", ")", "version", "=", "0", "with", "open", "(", "version_file_path", ",", "'r'", ")", "as", ...
40.25
18.3125
def get(self, key): """ Returns attribute value. :param key :returns value """ if not self.is_loaded: self.retrieve() self.is_loaded = True if self.has(key=key): return self.data[key] else: r...
[ "def", "get", "(", "self", ",", "key", ")", ":", "if", "not", "self", ".", "is_loaded", ":", "self", ".", "retrieve", "(", ")", "self", ".", "is_loaded", "=", "True", "if", "self", ".", "has", "(", "key", "=", "key", ")", ":", "return", "self", ...
17.388889
19.388889
def _check_bearer_validity(decorated_func): """Check API Bearer token validity. Isogeo ID delivers authentication bearers which are valid during a certain time. So this decorator checks the validity of the token comparing with actual datetime (UTC) and renews it if necessary. Se...
[ "def", "_check_bearer_validity", "(", "decorated_func", ")", ":", "@", "wraps", "(", "decorated_func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# compare token expiration date and ask for a new one if it's expired", "...
39.96
23.48
def get(self, sid): """ Constructs a BindingContext :param sid: The unique string that identifies the resource :returns: twilio.rest.notify.v1.service.binding.BindingContext :rtype: twilio.rest.notify.v1.service.binding.BindingContext """ return BindingContext(s...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "BindingContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
37.8
24.8
def now(self): """ Capture time. """ if self._now is None: # Compute the current time only once per instance self._now = datetime.utcnow() return self._now
[ "def", "now", "(", "self", ")", ":", "if", "self", ".", "_now", "is", "None", ":", "# Compute the current time only once per instance", "self", ".", "_now", "=", "datetime", ".", "utcnow", "(", ")", "return", "self", ".", "_now" ]
33
12.5
def emit(self, event, data=None, namespace=None, callback=None): """Emit a custom event to one or more connected clients. :param event: The event name. It can be any string. The event names ``'connect'``, ``'message'`` and ``'disconnect'`` are reserved and sh...
[ "def", "emit", "(", "self", ",", "event", ",", "data", "=", "None", ",", "namespace", "=", "None", ",", "callback", "=", "None", ")", ":", "namespace", "=", "namespace", "or", "'/'", "self", ".", "logger", ".", "info", "(", "'Emitting event \"%s\" [%s]'"...
49.794872
22.128205
def setup(self, helper=None, **run_kwargs): """ Creates the container, starts it, and waits for it to completely start. :param helper: The resource helper to use, if one was not provided when this container definition was created. :param **run_kwargs: Keyword arg...
[ "def", "setup", "(", "self", ",", "helper", "=", "None", ",", "*", "*", "run_kwargs", ")", ":", "if", "self", ".", "created", ":", "return", "self", ".", "set_helper", "(", "helper", ")", "self", ".", "run", "(", "*", "*", "run_kwargs", ")", "self"...
32.818182
21.818182
def getRemoteObject(self, busName, objectPath, interfaces=None, replaceKnownInterfaces=False): """ Creates a L{objects.RemoteDBusObject} instance to represent the specified DBus object. If explicit interfaces are not supplied, DBus object introspection will be us...
[ "def", "getRemoteObject", "(", "self", ",", "busName", ",", "objectPath", ",", "interfaces", "=", "None", ",", "replaceKnownInterfaces", "=", "False", ")", ":", "return", "self", ".", "objHandler", ".", "getRemoteObject", "(", "busName", ",", "objectPath", ","...
47.576923
22.884615
def as_cwd(): """ Use workdir.options.path as a temporary working directory """ _set_log_level() owd = os.getcwd() logger.debug('entering working directory: ' + options.path) os.chdir(os.path.expanduser(options.path)) yield logger.debug('returning to original directory: ' + owd) os.chdir...
[ "def", "as_cwd", "(", ")", ":", "_set_log_level", "(", ")", "owd", "=", "os", ".", "getcwd", "(", ")", "logger", ".", "debug", "(", "'entering working directory: '", "+", "options", ".", "path", ")", "os", ".", "chdir", "(", "os", ".", "path", ".", "...
35.222222
18.666667
def get_dependencies_from_json(ireq): """Retrieves dependencies for the given install requirement from the json api. :param ireq: A single InstallRequirement :type ireq: :class:`~pip._internal.req.req_install.InstallRequirement` :return: A set of dependency lines for generating new InstallRequirements....
[ "def", "get_dependencies_from_json", "(", "ireq", ")", ":", "if", "ireq", ".", "editable", "or", "not", "is_pinned_requirement", "(", "ireq", ")", ":", "return", "# It is technically possible to parse extras out of the JSON API's", "# requirement format, but it is such a chore ...
34.361702
20.893617
def prepare(self): """ This uploads the protocol functions nessecary to do binary chunked transfer """ log.info('Preparing esp for transfer.') for func in LUA_FUNCTIONS: detected = self.__exchange('print({0})'.format(func)) if detected.find('funct...
[ "def", "prepare", "(", "self", ")", ":", "log", ".", "info", "(", "'Preparing esp for transfer.'", ")", "for", "func", "in", "LUA_FUNCTIONS", ":", "detected", "=", "self", ".", "__exchange", "(", "'print({0})'", ".", "format", "(", "func", ")", ")", "if", ...
36.28125
19.34375
def run(self, refant=[], antsel=[], uvrange='', fluxname='', fluxname_full='', band='', spw0='', spw1='', flaglist=[]): """ Run calibration pipeline. Assumes L-band. refant is list of antenna name strings (e.g., ['ea10']). default is to calculate based on distance from array center. antsel is li...
[ "def", "run", "(", "self", ",", "refant", "=", "[", "]", ",", "antsel", "=", "[", "]", ",", "uvrange", "=", "''", ",", "fluxname", "=", "''", ",", "fluxname_full", "=", "''", ",", "band", "=", "''", ",", "spw0", "=", "''", ",", "spw1", "=", "...
36.5625
13.90625
def angle_to_distance(angle, units='metric'): """Convert angle in to distance along a great circle. Args: angle (float): Angle in degrees to convert to distance units (str): Unit type to be used for distances Returns: float: Distance in ``units`` Raises: ValueError: Un...
[ "def", "angle_to_distance", "(", "angle", ",", "units", "=", "'metric'", ")", ":", "distance", "=", "math", ".", "radians", "(", "angle", ")", "*", "BODY_RADIUS", "if", "units", "in", "(", "'km'", ",", "'metric'", ")", ":", "return", "distance", "elif", ...
29.478261
17.391304
def _handle_processing_error(err, errstream, client): """Handle ProcessingError exceptions.""" errors = sorted(err.events, key=operator.attrgetter("index")) failed = [e.event for e in errors] silent = all(isinstance(e.error, OutOfOrderError) for e in errors) if errstream: _deliver_errored_e...
[ "def", "_handle_processing_error", "(", "err", ",", "errstream", ",", "client", ")", ":", "errors", "=", "sorted", "(", "err", ".", "events", ",", "key", "=", "operator", ".", "attrgetter", "(", "\"index\"", ")", ")", "failed", "=", "[", "e", ".", "eve...
36.2
15.24
def set_allowed(self, initial_state, *allowed_states): # type: (str, *str) -> None """Add an allowed transition from initial_state to allowed_states""" allowed_states = list(allowed_states) self._allowed.setdefault(initial_state, set()).update(allowed_states) for state in allowed...
[ "def", "set_allowed", "(", "self", ",", "initial_state", ",", "*", "allowed_states", ")", ":", "# type: (str, *str) -> None", "allowed_states", "=", "list", "(", "allowed_states", ")", "self", ".", "_allowed", ".", "setdefault", "(", "initial_state", ",", "set", ...
55
11.75
def circstd(dts, axis=2): """Circular standard deviation""" R = np.abs(np.exp(1.0j * dts).mean(axis=axis)) return np.sqrt(-2.0 * np.log(R))
[ "def", "circstd", "(", "dts", ",", "axis", "=", "2", ")", ":", "R", "=", "np", ".", "abs", "(", "np", ".", "exp", "(", "1.0j", "*", "dts", ")", ".", "mean", "(", "axis", "=", "axis", ")", ")", "return", "np", ".", "sqrt", "(", "-", "2.0", ...
37
7.25
def sb_vgp_calc(dataframe, site_correction='yes', dec_tc='dec_tc', inc_tc='inc_tc'): """ This function calculates the angular dispersion of VGPs and corrects for within site dispersion (unless site_correction = 'no') to return a value S_b. The input data needs to be within a pandas Dataframe. Param...
[ "def", "sb_vgp_calc", "(", "dataframe", ",", "site_correction", "=", "'yes'", ",", "dec_tc", "=", "'dec_tc'", ",", "inc_tc", "=", "'inc_tc'", ")", ":", "# calculate the mean from the directional data", "dataframe_dirs", "=", "[", "]", "for", "n", "in", "range", ...
40.487805
23.121951
def expect_column_kl_divergence_to_be_less_than(self, column, partition_object=None, threshold=None, tail_weight...
[ "def", "expect_column_kl_divergence_to_be_less_than", "(", "self", ",", "column", ",", "partition_object", "=", "None", ",", "threshold", "=", "None", ",", "tail_weight_holdout", "=", "0", ",", "internal_weight_holdout", "=", "0", ",", "result_format", "=", "None", ...
62.787037
41.555556
def __request(self, *args, **kwargs): """ Call method on server side """ with self.lock: parent = xmlrpc.client.ServerProxy # pylint: disable=E1101 return parent._ServerProxy__request(self, *args, **kwargs)
[ "def", "__request", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "lock", ":", "parent", "=", "xmlrpc", ".", "client", ".", "ServerProxy", "# pylint: disable=E1101", "return", "parent", ".", "_ServerProxy__request", ...
29.666667
11.888889
def bls_snr(blsdict, times, mags, errs, assumeserialbls=False, magsarefluxes=False, sigclip=10.0, npeaks=None, perioddeltapercent=10, ingressdurationfraction=0.1, verbose=True): '''Calculates the ...
[ "def", "bls_snr", "(", "blsdict", ",", "times", ",", "mags", ",", "errs", ",", "assumeserialbls", "=", "False", ",", "magsarefluxes", "=", "False", ",", "sigclip", "=", "10.0", ",", "npeaks", "=", "None", ",", "perioddeltapercent", "=", "10", ",", "ingre...
40.455319
22.225532
def send_response(self, response): """Send a unicode object as reply to the most recently-issued command """ response_bytes = response.encode(config.CODEC) log.debug("About to send reponse: %r", response_bytes) self.socket.send(response_bytes)
[ "def", "send_response", "(", "self", ",", "response", ")", ":", "response_bytes", "=", "response", ".", "encode", "(", "config", ".", "CODEC", ")", "log", ".", "debug", "(", "\"About to send reponse: %r\"", ",", "response_bytes", ")", "self", ".", "socket", ...
46.333333
7
def cmd_version(self, args): '''show version''' self.master.mav.command_long_send(self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES, ...
[ "def", "cmd_version", "(", "self", ",", "args", ")", ":", "self", ".", "master", ".", "mav", ".", "command_long_send", "(", "self", ".", "settings", ".", "target_system", ",", "self", ".", "settings", ".", "target_component", ",", "mavutil", ".", "mavlink"...
57.142857
24.571429
def cache_file(package, mode): """ Yields a file-like object for the purpose of writing to or reading from the cache. The code: with cache_file(...) as f: # do stuff with f is guaranteed to convert any exceptions to warnings (*), both in the cache_file(...) call and the 'd...
[ "def", "cache_file", "(", "package", ",", "mode", ")", ":", "f", "=", "DummyFile", "(", ")", "# We have to wrap the whole function body in this block to guarantee", "# catching all exceptions. In particular the yield needs to be inside", "# to catch exceptions coming from the with bloc...
36.3
23.65
def create(self, container, instances=None, map_name=None, **kwargs): """ Creates container instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance name to create. If not specified, will create all inst...
[ "def", "create", "(", "self", ",", "container", ",", "instances", "=", "None", ",", "map_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "run_actions", "(", "'create'", ",", "container", ",", "instances", "=", "instances", ...
55.117647
24.411765
def getAttributeUri(self, index): """ Returns the numeric ID for the namespace URI of an attribute """ offset = self._get_attribute_offset(index) uri = self.m_attributes[offset + ATTRIBUTE_IX_NAMESPACE_URI] return uri
[ "def", "getAttributeUri", "(", "self", ",", "index", ")", ":", "offset", "=", "self", ".", "_get_attribute_offset", "(", "index", ")", "uri", "=", "self", ".", "m_attributes", "[", "offset", "+", "ATTRIBUTE_IX_NAMESPACE_URI", "]", "return", "uri" ]
32.375
16.875
def get_descriptives(data): """Get mean, SD, and mean and SD of log values. Parameters ---------- data : ndarray Data with segment as first dimension and all other dimensions raveled into second dimension. Returns ------- dict of ndarray each entry is a 1-D vector o...
[ "def", "get_descriptives", "(", "data", ")", ":", "output", "=", "{", "}", "dat_log", "=", "log", "(", "abs", "(", "data", ")", ")", "output", "[", "'mean'", "]", "=", "nanmean", "(", "data", ",", "axis", "=", "0", ")", "output", "[", "'sd'", "]"...
26.727273
19.272727
def create_position_tear_sheet(returns, positions, show_and_plot_top_pos=2, hide_positions=False, return_fig=False, sector_mappings=None, transactions=None, estimate_intraday='infer'): """ Generate a number of plots for...
[ "def", "create_position_tear_sheet", "(", "returns", ",", "positions", ",", "show_and_plot_top_pos", "=", "2", ",", "hide_positions", "=", "False", ",", "return_fig", "=", "False", ",", "sector_mappings", "=", "None", ",", "transactions", "=", "None", ",", "esti...
41.097826
20.51087
def manage_signal(self, sig, frame): # pylint: disable=unused-argument """Manage signals caught by the daemon signal.SIGUSR1 : dump_environment signal.SIGUSR2 : dump_object (nothing) signal.SIGTERM, signal.SIGINT : terminate process :param sig: signal caught by daemon :...
[ "def", "manage_signal", "(", "self", ",", "sig", ",", "frame", ")", ":", "# pylint: disable=unused-argument", "logger", ".", "info", "(", "\"received a signal: %s\"", ",", "SIGNALS_TO_NAMES_DICT", "[", "sig", "]", ")", "if", "sig", "==", "signal", ".", "SIGUSR1"...
43.590909
13.909091
def discover(): """ Import all experiments listed in PLUGINS_EXPERIMENTS. Tests: >>> from benchbuild.settings import CFG >>> from benchbuild.experiments import discover >>> import logging as lg >>> import sys >>> l = lg.getLogger('benchbuild') >>> lg.getLogge...
[ "def", "discover", "(", ")", ":", "if", "CFG", "[", "\"plugins\"", "]", "[", "\"autoload\"", "]", ":", "experiment_plugins", "=", "CFG", "[", "\"plugins\"", "]", "[", "\"experiments\"", "]", ".", "value", "for", "exp_plugin", "in", "experiment_plugins", ":",...
41.64
17.8
def __step3(self): """ Cover each column containing a starred zero. If K columns are covered, the starred zeros describe a complete set of unique assignments. In this case, Go to DONE, otherwise, Go to Step 4. """ n = self.n count = 0 for i in range(n): ...
[ "def", "__step3", "(", "self", ")", ":", "n", "=", "self", ".", "n", "count", "=", "0", "for", "i", "in", "range", "(", "n", ")", ":", "for", "j", "in", "range", "(", "n", ")", ":", "if", "self", ".", "marked", "[", "i", "]", "[", "j", "]...
27.9
18.8
def slot_add_nio_binding(self, slot_number, port_number, nio): """ Adds a slot NIO binding. :param slot_number: slot number :param port_number: port number :param nio: NIO instance to add to the slot/port """ try: adapter = self._slots[slot_number] ...
[ "def", "slot_add_nio_binding", "(", "self", ",", "slot_number", ",", "port_number", ",", "nio", ")", ":", "try", ":", "adapter", "=", "self", ".", "_slots", "[", "slot_number", "]", "except", "IndexError", ":", "raise", "DynamipsError", "(", "'Slot {slot_numbe...
74.577778
52.933333
def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ ...
[ "def", "post", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Look for a wizard_prev_step element in the posted data which", "# contains a valid step name. If one was found, render the requested", "# form. (This makes stepping back a lot easier).", "wizard_prev_...
46.833333
21.5
def _handle_func_def(self, node, scope, ctxt, stream): """Handle FuncDef nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling function definition") func = self._handle_node(node.decl, scope, ctxt, strea...
[ "def", "_handle_func_def", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling function definition\"", ")", "func", "=", "self", ".", "_handle_node", "(", "node", ".", "decl", ",", "scope", ...
26.153846
18.307692
def perform(self): """ Performs all stored actions. """ if self._driver.w3c: self.w3c_actions.perform() else: for action in self._actions: action()
[ "def", "perform", "(", "self", ")", ":", "if", "self", ".", "_driver", ".", "w3c", ":", "self", ".", "w3c_actions", ".", "perform", "(", ")", "else", ":", "for", "action", "in", "self", ".", "_actions", ":", "action", "(", ")" ]
24.333333
9.222222
def _base_placeholder(self): """ Return the layout placeholder this slide placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily). """ layout, idx = self.part.slide_layout, self._element.ph_idx return layout.placeholders.g...
[ "def", "_base_placeholder", "(", "self", ")", ":", "layout", ",", "idx", "=", "self", ".", "part", ".", "slide_layout", ",", "self", ".", "_element", ".", "ph_idx", "return", "layout", ".", "placeholders", ".", "get", "(", "idx", "=", "idx", ")" ]
40.5
15.25
def connect( database: Union[str, Path], *, loop: asyncio.AbstractEventLoop = None, **kwargs: Any ) -> Connection: """Create and return a connection proxy to the sqlite database.""" if loop is None: loop = asyncio.get_event_loop() def connector() -> sqlite3.Connection: if isinstance(dat...
[ "def", "connect", "(", "database", ":", "Union", "[", "str", ",", "Path", "]", ",", "*", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Connection", ":", "if", "loop", "is", "Non...
31.111111
17
def _autoSave(self): """save state into 'autosave' """ a = 'autoSave' path = self.path if not path: path = self.dir.join('%s.%s' % (a, self.FTYPE)) self._createdAutosaveFile = path self.tmp_dir_save_session = self.tmp_dir_session.join(a).mkdir() ...
[ "def", "_autoSave", "(", "self", ")", ":", "a", "=", "'autoSave'", "path", "=", "self", ".", "path", "if", "not", "path", ":", "path", "=", "self", ".", "dir", ".", "join", "(", "'%s.%s'", "%", "(", "a", ",", "self", ".", "FTYPE", ")", ")", "se...
37.444444
15.666667
def visual_callback_3d(fig=None, plot_each=1): """ Returns a callback than can be passed as the argument `iter_callback` of `morphological_geodesic_active_contour` and `morphological_chan_vese` for visualizing the evolution of the levelsets. Only works for 3D images. Parameters --------...
[ "def", "visual_callback_3d", "(", "fig", "=", "None", ",", "plot_each", "=", "1", ")", ":", "from", "mpl_toolkits", ".", "mplot3d", "import", "Axes3D", "# PyMCubes package is required for `visual_callback_3d`", "try", ":", "import", "mcubes", "except", "ImportError", ...
29.298246
21.403509
def add_mongo_config(app, simple_connection_string, mongo_uri, collection_name): """ Configure the application to use MongoDB. :param app: Flask application :param simple_connection_string: Expects host:port:database_name or database_name Mutally_exc...
[ "def", "add_mongo_config", "(", "app", ",", "simple_connection_string", ",", "mongo_uri", ",", "collection_name", ")", ":", "if", "mongo_uri", "!=", "(", "None", ",", "None", ")", ":", "add_mongo_config_with_uri", "(", "app", ",", "mongo_uri", "[", "0", "]", ...
45.807692
17.346154
def webhoneypotsummary(date, return_format=None): """API data for `Webhoneypot: Web Server Log Project <https://dshield.org/webhoneypot/>`_. :param date: string or datetime.date() (required) """ uri = 'webhoneypotsummary' try: uri = '/'.join([uri, date.strftime("%Y-%m-%d")]) except ...
[ "def", "webhoneypotsummary", "(", "date", ",", "return_format", "=", "None", ")", ":", "uri", "=", "'webhoneypotsummary'", "try", ":", "uri", "=", "'/'", ".", "join", "(", "[", "uri", ",", "date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "]", ")", "e...
33
12.083333
def bandnames(self, names): """ set the names of the raster bands Parameters ---------- names: list of str the names to be set; must be of same length as the number of bands Returns ------- """ if not isinstance(names, list): ...
[ "def", "bandnames", "(", "self", ",", "names", ")", ":", "if", "not", "isinstance", "(", "names", ",", "list", ")", ":", "raise", "TypeError", "(", "'the names to be set must be of type list'", ")", "if", "len", "(", "names", ")", "!=", "self", ".", "bands...
30.578947
21.526316
def allocate_sync_ensembles(self, steps): """! @brief Allocate clusters in line with ensembles of synchronous neurons where each synchronous ensemble corresponds to only one cluster. @param[in] steps (double): Amount of steps from the end that is used for analysis. During spe...
[ "def", "allocate_sync_ensembles", "(", "self", ",", "steps", ")", ":", "iterations", "=", "steps", "if", "iterations", ">=", "len", "(", "self", ".", "output", ")", ":", "iterations", "=", "len", "(", "self", ".", "output", ")", "ensembles", "=", "[", ...
39.190476
24.5
def _add_creator(self): """ Add a ``_new_{prop_name}()`` method to the element class that creates a new, empty element of the correct type, having no attributes. """ creator = self._creator creator.__doc__ = ( 'Return a "loose", newly created ``<%s>`` element ...
[ "def", "_add_creator", "(", "self", ")", ":", "creator", "=", "self", ".", "_creator", "creator", ".", "__doc__", "=", "(", "'Return a \"loose\", newly created ``<%s>`` element having no attri'", "'butes, text, or children.'", "%", "self", ".", "_nsptagname", ")", "self...
41.272727
19.272727
def from_json_compatible(schema, dct): "Load from json-encodable" kwargs = {} for key in dct: field_type = schema._fields.get(key) if field_type is None: raise ParseError("Unexpected field encountered in line for record %s: %s" % (schema.__name__, key)) kwargs[key] = fie...
[ "def", "from_json_compatible", "(", "schema", ",", "dct", ")", ":", "kwargs", "=", "{", "}", "for", "key", "in", "dct", ":", "field_type", "=", "schema", ".", "_fields", ".", "get", "(", "key", ")", "if", "field_type", "is", "None", ":", "raise", "Pa...
32.818182
22.090909
def simple_pattern_exists_in_gcs(file_pattern, credentials=None): """True iff an object exists matching the input GCS pattern. The GCS pattern must be a full object reference or a "simple pattern" that conforms to the dsub input and output parameter restrictions: * No support for **, ? wildcards or [] chara...
[ "def", "simple_pattern_exists_in_gcs", "(", "file_pattern", ",", "credentials", "=", "None", ")", ":", "if", "'*'", "not", "in", "file_pattern", ":", "return", "_file_exists_in_gcs", "(", "file_pattern", ",", "credentials", ")", "if", "not", "file_pattern", ".", ...
39.368421
20.184211
def sort_protein_sequences(protein_sequences): """ Sort protein sequences in decreasing order of priority """ return list( sorted( protein_sequences, key=ProteinSequence.ascending_sort_key, reverse=True))
[ "def", "sort_protein_sequences", "(", "protein_sequences", ")", ":", "return", "list", "(", "sorted", "(", "protein_sequences", ",", "key", "=", "ProteinSequence", ".", "ascending_sort_key", ",", "reverse", "=", "True", ")", ")" ]
28.444444
12
def create_datafeed(self): ''' create datafeed ''' response, status_code = self.__agent__.Datafeed.post_v4_datafeed_create( sessionToken=self.__session__, keyManagerToken=self.__keymngr__ ).result() # return the token self.logger.debug('%s: %s' % (status_c...
[ "def", "create_datafeed", "(", "self", ")", ":", "response", ",", "status_code", "=", "self", ".", "__agent__", ".", "Datafeed", ".", "post_v4_datafeed_create", "(", "sessionToken", "=", "self", ".", "__session__", ",", "keyManagerToken", "=", "self", ".", "__...
41.111111
14.222222
def _eight_byte_real_to_float(value): """ Convert a number from GDSII 8 byte real format to float. Parameters ---------- value : string The GDSII binary string representation of the number. Returns ------- out : float The number represented by ``value``. """ sho...
[ "def", "_eight_byte_real_to_float", "(", "value", ")", ":", "short1", ",", "short2", ",", "long3", "=", "struct", ".", "unpack", "(", "'>HHL'", ",", "value", ")", "exponent", "=", "(", "short1", "&", "0x7f00", ")", "//", "256", "-", "64", "mantissa", "...
28.952381
17.047619
def _parsePrivateKey(self, key): ''' Generate a :class:`eth_keys.datatypes.PrivateKey` from the provided key. If the key is already of type :class:`eth_keys.datatypes.PrivateKey`, return the key. :param key: the private key from which a :class:`eth_keys.datatypes.PrivateKey` ...
[ "def", "_parsePrivateKey", "(", "self", ",", "key", ")", ":", "if", "isinstance", "(", "key", ",", "self", ".", "_keys", ".", "PrivateKey", ")", ":", "return", "key", "try", ":", "return", "self", ".", "_keys", ".", "PrivateKey", "(", "HexBytes", "(", ...
44.65
25.75
def available_products(cls, user, category=None, products=None): ''' Returns a list of all of the products that are available per flag conditions from the given categories. ''' if category is None and products is None: raise ValueError("You must provide products or a category") ...
[ "def", "available_products", "(", "cls", ",", "user", ",", "category", "=", "None", ",", "products", "=", "None", ")", ":", "if", "category", "is", "None", "and", "products", "is", "None", ":", "raise", "ValueError", "(", "\"You must provide products or a cate...
37.205882
23.794118
def encode(strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ res = '' for string in strs.split(): res += str(len(string)) + ":" + string return res
[ "def", "encode", "(", "strs", ")", ":", "res", "=", "''", "for", "string", "in", "strs", ".", "split", "(", ")", ":", "res", "+=", "str", "(", "len", "(", "string", ")", ")", "+", "\":\"", "+", "string", "return", "res" ]
24.333333
14.666667
def gen_ipa_data(self): """ Generator for iterating over the IPA strings found in the dataset file. Yields the IPA data string paired with the respective line number. """ dialect = self.get_dialect() f = self._open() try: if dialect: for res in self._gen_csv_data(f, dialect): yield res els...
[ "def", "gen_ipa_data", "(", "self", ")", ":", "dialect", "=", "self", ".", "get_dialect", "(", ")", "f", "=", "self", ".", "_open", "(", ")", "try", ":", "if", "dialect", ":", "for", "res", "in", "self", ".", "_gen_csv_data", "(", "f", ",", "dialec...
21.277778
22.277778
def set_chassis_datacenter(location, host=None, admin_username=None, admin_password=None): ''' Set the location of the chassis. location The name of the datacenter to be set on the chassis. host The chassis host...
[ "def", "set_chassis_datacenter", "(", "location", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "return", "set_general", "(", "'cfgLocation'", ",", "'cfgLocationDatacenter'", ",", "location", ",", "ho...
27.233333
24.433333
def Convert(self, metadata, grr_message, token=None): """Converts GrrMessage into a set of RDFValues. Args: metadata: ExportedMetadata to be used for conversion. grr_message: GrrMessage to be converted. token: Security token. Returns: List or generator with resulting RDFValues. ...
[ "def", "Convert", "(", "self", ",", "metadata", ",", "grr_message", ",", "token", "=", "None", ")", ":", "return", "self", ".", "BatchConvert", "(", "[", "(", "metadata", ",", "grr_message", ")", "]", ",", "token", "=", "token", ")" ]
31.833333
18.833333
def Next(self): """Advance to the next item in a repeated section. Raises: StopIteration if there are no more elements """ stacktop = self.stack[-1] # Now we're iterating -- push a new mutable object onto the stack if stacktop.index == -1: stacktop = _...
[ "def", "Next", "(", "self", ")", ":", "stacktop", "=", "self", ".", "stack", "[", "-", "1", "]", "# Now we're iterating -- push a new mutable object onto the stack", "if", "stacktop", ".", "index", "==", "-", "1", ":", "stacktop", "=", "_Frame", "(", "None", ...
28.521739
17.434783