text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def verifybamid_table(self): """ Create a table with all the columns from verify BAM ID """ # create an ordered dictionary to preserve the order of columns headers = OrderedDict() # add each column and the title and description (taken from verifyBAMID website) headers['RG'] = { 'title': 'Read Group', ...
[ "def", "verifybamid_table", "(", "self", ")", ":", "# create an ordered dictionary to preserve the order of columns", "headers", "=", "OrderedDict", "(", ")", "# add each column and the title and description (taken from verifyBAMID website)", "headers", "[", "'RG'", "]", "=", "{"...
42.84
0.033764
def compare(self, digest_2, is_hex = False): """ returns difference between the nilsimsa digests between the current object and a given digest """ # convert hex string to list of ints if is_hex: digest_2 = convert_hex_to_ints(digest_2) bit_diff = 0 ...
[ "def", "compare", "(", "self", ",", "digest_2", ",", "is_hex", "=", "False", ")", ":", "# convert hex string to list of ints", "if", "is_hex", ":", "digest_2", "=", "convert_hex_to_ints", "(", "digest_2", ")", "bit_diff", "=", "0", "for", "i", "in", "range", ...
36.428571
0.011472
def _parse_response(self, result_page): """ Takes a result page of sending the sms, returns an extracted tuple: ('numeric_err_code', '<sent_queued_message_id>', '<smsglobalmsgid>') Returns None if unable to extract info from result_page, it should be safe to assume that it wa...
[ "def", "_parse_response", "(", "self", ",", "result_page", ")", ":", "# Sample result_page, single line -> \"OK: 0; Sent queued message ID: 2063619577732703 SMSGlobalMsgID:6171799108850954\"", "resultline", "=", "result_page", ".", "splitlines", "(", ")", "[", "0", "]", "# get ...
55.411765
0.008351
def _get_date(day=None, month=None, year=None): """Returns a datetime object with optional params or today.""" now = datetime.date.today() if day is None: return now try: return datetime.date( day=int(day), month=int(month or now.month), year=int(yea...
[ "def", "_get_date", "(", "day", "=", "None", ",", "month", "=", "None", ",", "year", "=", "None", ")", ":", "now", "=", "datetime", ".", "date", ".", "today", "(", ")", "if", "day", "is", "None", ":", "return", "now", "try", ":", "return", "datet...
28.133333
0.002294
def _expand_base_distribution_mean(self): """Ensures `self.distribution.mean()` has `[batch, event]` shape.""" single_draw_shape = concat_vectors(self.batch_shape_tensor(), self.event_shape_tensor()) m = tf.reshape( self.distribution.mean(), # A scalar. ...
[ "def", "_expand_base_distribution_mean", "(", "self", ")", ":", "single_draw_shape", "=", "concat_vectors", "(", "self", ".", "batch_shape_tensor", "(", ")", ",", "self", ".", "event_shape_tensor", "(", ")", ")", "m", "=", "tf", ".", "reshape", "(", "self", ...
48.727273
0.001832
def post(self): """Dump current profiler statistics into a file.""" filename = self.get_argument('filename', 'dump.prof') CProfileWrapper.profiler.dump_stats(filename) self.finish()
[ "def", "post", "(", "self", ")", ":", "filename", "=", "self", ".", "get_argument", "(", "'filename'", ",", "'dump.prof'", ")", "CProfileWrapper", ".", "profiler", ".", "dump_stats", "(", "filename", ")", "self", ".", "finish", "(", ")" ]
41.8
0.00939
def rename_column(self, column, new_name): """ This will rename the column. The supplied column can be an integer or the old column name. """ if type(column) is not str: column = self.ckeys[column] self.ckeys[self.ckeys.index(column)] = new_name self.columns[new_n...
[ "def", "rename_column", "(", "self", ",", "column", ",", "new_name", ")", ":", "if", "type", "(", "column", ")", "is", "not", "str", ":", "column", "=", "self", ".", "ckeys", "[", "column", "]", "self", ".", "ckeys", "[", "self", ".", "ckeys", ".",...
40.333333
0.008086
def delete_comment(repo: GithubRepository, comment_id: int) -> None: """ References: https://developer.github.com/v3/issues/comments/#delete-a-comment """ url = ("https://api.github.com/repos/{}/{}/issues/comments/{}" "?access_token={}".format(repo.organization, ...
[ "def", "delete_comment", "(", "repo", ":", "GithubRepository", ",", "comment_id", ":", "int", ")", "->", "None", ":", "url", "=", "(", "\"https://api.github.com/repos/{}/{}/issues/comments/{}\"", "\"?access_token={}\"", ".", "format", "(", "repo", ".", "organization",...
44.133333
0.001479
def create_file(project: str, environment: str, feature: str, state: str) -> None: """ Create file to replay. Create file with ``rc`` command that will be called against the LaunchDarkly API when ``rc playback`` is called from the main CLI. :param project: LaunchDarkly Project :param environme...
[ "def", "create_file", "(", "project", ":", "str", ",", "environment", ":", "str", ",", "feature", ":", "str", ",", "state", ":", "str", ")", "->", "None", ":", "check_local", "(", ")", "save_path", "=", "'./replay/toDo/'", "filename", "=", "'{0}.txt'", "...
33.291667
0.002433
def _connected(self, sock): """When the socket is writtable, the socket is ready to be used.""" logger.debug('socket connected, building protocol') self.protocol = self.factory.build(self.loop) self.connection = Connection(self.loop, self.sock, self.addr, self.protocol, self)...
[ "def", "_connected", "(", "self", ",", "sock", ")", ":", "logger", ".", "debug", "(", "'socket connected, building protocol'", ")", "self", ".", "protocol", "=", "self", ".", "factory", ".", "build", "(", "self", ".", "loop", ")", "self", ".", "connection"...
49.75
0.009877
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear): """Install just the base environment, no distutils patches etc""" if sys.executable.startswith(bin_dir): print 'Please use the *system* python to run this script' return if clear: rmtree(lib_dir) ...
[ "def", "install_python", "(", "home_dir", ",", "lib_dir", ",", "inc_dir", ",", "bin_dir", ",", "site_packages", ",", "clear", ")", ":", "if", "sys", ".", "executable", ".", "startswith", "(", "bin_dir", ")", ":", "print", "'Please use the *system* python to run ...
43.348039
0.001658
def runFuture(future): """Callable greenlet in charge of running tasks.""" global debug_stats global QueueLength if scoop.DEBUG: init_debug() # in case _control is imported before scoop.DEBUG was set debug_stats[future.id]['start_time'].append(time.time()) future.waitTime = future.s...
[ "def", "runFuture", "(", "future", ")", ":", "global", "debug_stats", "global", "QueueLength", "if", "scoop", ".", "DEBUG", ":", "init_debug", "(", ")", "# in case _control is imported before scoop.DEBUG was set", "debug_stats", "[", "future", ".", "id", "]", "[", ...
37.277778
0.00242
def send_and_require(self, send, regexps, not_there=False, shutit_pexpect_child=None, echo=None, note=None, loglevel=logging.INFO): """Send string and require the i...
[ "def", "send_and_require", "(", "self", ",", "send", ",", "regexps", ",", "not_there", "=", "False", ",", "shutit_pexpect_child", "=", "None", ",", "echo", "=", "None", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "INFO", ")", ":", "...
48.3
0.043655
def add_reporting_args(parser): """Add reporting arguments to an argument parser. Parameters ---------- parser: `argparse.ArgumentParser` Returns ------- `argparse.ArgumentGroup` The argument group created. """ g = parser.add_argument_group('Reporting options') g.add_a...
[ "def", "add_reporting_args", "(", "parser", ")", ":", "g", "=", "parser", ".", "add_argument_group", "(", "'Reporting options'", ")", "g", ".", "add_argument", "(", "'-l'", ",", "'--log-file'", ",", "default", "=", "None", ",", "type", "=", "str", ",", "me...
25.344828
0.001311
def IterReferenceInstances(self, InstanceName, ResultClass=None, Role=None, IncludeQualifiers=None, IncludeClassOrigin=None, PropertyList=None, FilterQueryLanguage=None, FilterQuery=None, Operatio...
[ "def", "IterReferenceInstances", "(", "self", ",", "InstanceName", ",", "ResultClass", "=", "None", ",", "Role", "=", "None", ",", "IncludeQualifiers", "=", "None", ",", "IncludeClassOrigin", "=", "None", ",", "PropertyList", "=", "None", ",", "FilterQueryLangua...
48.154605
0.000669
def scroll_to_horizontally(self, obj, *args,**selectors): """ Scroll(horizontally) on the object: obj to specific UI object which has *selectors* attributes appears. Return true if the UI object, else return false. See `Scroll To Vertically` for more details. """ return...
[ "def", "scroll_to_horizontally", "(", "self", ",", "obj", ",", "*", "args", ",", "*", "*", "selectors", ")", ":", "return", "obj", ".", "scroll", ".", "horiz", ".", "to", "(", "*", "*", "selectors", ")" ]
38.333333
0.011331
def anisotropic_diffusion(img, niter=1, kappa=50, gamma=0.1, voxelspacing=None, option=1): r""" Edge-preserving, XD Anisotropic diffusion. Parameters ---------- img : array_like Input image (will be cast to numpy.float). niter : integer Number of iterations. kappa : integer...
[ "def", "anisotropic_diffusion", "(", "img", ",", "niter", "=", "1", ",", "kappa", "=", "50", ",", "gamma", "=", "0.1", ",", "voxelspacing", "=", "None", ",", "option", "=", "1", ")", ":", "# define conduction gradients functions", "if", "option", "==", "1"...
36.696429
0.002132
def reboot_or_dryrun(*args, **kwargs): """ An improved version of fabric.operations.reboot with better error handling. """ from fabric.state import connections verbose = get_verbose() dryrun = get_dryrun(kwargs.get('dryrun')) # Use 'wait' as max total wait time kwargs.setdefault('wait...
[ "def", "reboot_or_dryrun", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "fabric", ".", "state", "import", "connections", "verbose", "=", "get_verbose", "(", ")", "dryrun", "=", "get_dryrun", "(", "kwargs", ".", "get", "(", "'dryrun'", ")"...
35.513889
0.001903
def _convert_to_scale(self): """Convert the inner value (defined with respect to REF_SCALE) into the given scale of the object """ d = self._d s = (self._s - self._offset) % 86400. d -= int((s + self._offset) // 86400) return d, s
[ "def", "_convert_to_scale", "(", "self", ")", ":", "d", "=", "self", ".", "_d", "s", "=", "(", "self", ".", "_s", "-", "self", ".", "_offset", ")", "%", "86400.", "d", "-=", "int", "(", "(", "s", "+", "self", ".", "_offset", ")", "//", "86400",...
34.875
0.01049
def trim_phonetics(root): """Function that trims phonetic markup from the root. Parameters ---------- root: str The string to remove the phonetic markup. Returns ------- str The string with phonetic markup removed. """ global phonetic_markers global phonetic_reg...
[ "def", "trim_phonetics", "(", "root", ")", ":", "global", "phonetic_markers", "global", "phonetic_regex", "if", "root", "in", "phonetic_markers", ":", "return", "root", "else", ":", "return", "phonetic_regex", ".", "sub", "(", "''", ",", "root", ")" ]
21.631579
0.002331
def _bridge_dangling_Os(self, oh_density, thickness): """Form Si-O-Si bridges to yield desired density of reactive surface sites. References ---------- .. [1] Hartkamp, R., Siboulet, B., Dufreche, J.-F., Boasne, B. "Ion-specific adsorption and electroosmosis in charged ...
[ "def", "_bridge_dangling_Os", "(", "self", ",", "oh_density", ",", "thickness", ")", ":", "area", "=", "self", ".", "periodicity", "[", "0", "]", "*", "self", ".", "periodicity", "[", "1", "]", "target", "=", "int", "(", "oh_density", "*", "area", ")",...
40.116279
0.001698
def set_source_variable(self, source_id, variable, value): """ Change the value of a source variable. """ source_id = int(source_id) return self._send_cmd("SET S[%d].%s=\"%s\"" % ( source_id, variable, value))
[ "def", "set_source_variable", "(", "self", ",", "source_id", ",", "variable", ",", "value", ")", ":", "source_id", "=", "int", "(", "source_id", ")", "return", "self", ".", "_send_cmd", "(", "\"SET S[%d].%s=\\\"%s\\\"\"", "%", "(", "source_id", ",", "variable"...
48.2
0.008163
def routerclass(cls): """ A class decorator which parses a class, looking for an member functions which match an HTTP verb (get, post, etc) followed by an underscore and other letters, with a signature of two parameters (req and res). For example .. code: python def get_index(req, res):...
[ "def", "routerclass", "(", "cls", ")", ":", "logging", ".", "debug", "(", "\"Creating a routerclass with the class %s\"", "%", "cls", ")", "cls", ".", "__growler_router", "=", "lambda", "self", ":", "routerify", "(", "self", ")", "return", "cls" ]
36.2
0.001346
def revoke(self, paths: Union[str, Iterable[str]], users: Union[str, Iterable[str], User, Iterable[User]]): """ Revokes all access controls that are associated to the given path or collection of paths. :param paths: the paths to remove access controls on :param users: the users to revoke...
[ "def", "revoke", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "users", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", ",", "User", ",", "Iterable", "[", "User", "]", "]", ")", ":"...
61.714286
0.013699
def encloses(self, location: FileLocation ) -> Optional[FunctionDesc]: """ Returns the function, if any, that encloses a given location. """ for func in self.in_file(location.filename): if location in func.location: return fun...
[ "def", "encloses", "(", "self", ",", "location", ":", "FileLocation", ")", "->", "Optional", "[", "FunctionDesc", "]", ":", "for", "func", "in", "self", ".", "in_file", "(", "location", ".", "filename", ")", ":", "if", "location", "in", "func", ".", "l...
33.2
0.01173
def bar_pct_change(self): '返回bar的涨跌幅' res = (self.close - self.open) / self.open res.name = 'bar_pct_change' return res
[ "def", "bar_pct_change", "(", "self", ")", ":", "res", "=", "(", "self", ".", "close", "-", "self", ".", "open", ")", "/", "self", ".", "open", "res", ".", "name", "=", "'bar_pct_change'", "return", "res" ]
29.4
0.013245
def compute_fingerprint(self, target): """UnpackedJars targets need to be re-unpacked if any of its configuration changes or any of the jars they import have changed. """ if isinstance(target, UnpackedJars): hasher = sha1() for cache_key in sorted(jar.cache_key() for jar in target.all_import...
[ "def", "compute_fingerprint", "(", "self", ",", "target", ")", ":", "if", "isinstance", "(", "target", ",", "UnpackedJars", ")", ":", "hasher", "=", "sha1", "(", ")", "for", "cache_key", "in", "sorted", "(", "jar", ".", "cache_key", "(", ")", "for", "j...
48.454545
0.012891
def dump(thing, query, from_date, file_prefix, chunk_size, limit, thing_flags): """Dump data from Invenio legacy.""" init_app_context() file_prefix = file_prefix if file_prefix else '{0}_dump'.format(thing) kwargs = dict((f.strip('-').replace('-', '_'), True) for f in thing_flags) try: th...
[ "def", "dump", "(", "thing", ",", "query", ",", "from_date", ",", "file_prefix", ",", "chunk_size", ",", "limit", ",", "thing_flags", ")", ":", "init_app_context", "(", ")", "file_prefix", "=", "file_prefix", "if", "file_prefix", "else", "'{0}_dump'", ".", "...
39.536585
0.000602
def _read_coll( ctx: ReaderContext, f: Callable[[Collection[Any]], Union[llist.List, lset.Set, vector.Vector]], end_token: str, coll_name: str, ): """Read a collection from the input stream and create the collection using f.""" coll: List = [] reader = ctx.reader while True: ...
[ "def", "_read_coll", "(", "ctx", ":", "ReaderContext", ",", "f", ":", "Callable", "[", "[", "Collection", "[", "Any", "]", "]", ",", "Union", "[", "llist", ".", "List", ",", "lset", ".", "Set", ",", "vector", ".", "Vector", "]", "]", ",", "end_toke...
28.916667
0.001395
def handle(self, t_input: inference.TranslatorInput, t_output: inference.TranslatorOutput, t_walltime: float = 0.): """ :param t_input: Translator input. :param t_output: Translator output. :param t_walltime: Total wall-clock time for translat...
[ "def", "handle", "(", "self", ",", "t_input", ":", "inference", ".", "TranslatorInput", ",", "t_output", ":", "inference", ".", "TranslatorOutput", ",", "t_walltime", ":", "float", "=", "0.", ")", ":", "alignments", "=", "\" \"", ".", "join", "(", "[", "...
43.846154
0.010309
def _load_multipoint(tokens, string): """ Has similar inputs and return value to to :func:`_load_point`, except is for handling MULTIPOINT geometry. :returns: A GeoJSON `dict` MultiPoint representation of the WKT ``string``. """ open_paren = next(tokens) if not open_paren == '(': ...
[ "def", "_load_multipoint", "(", "tokens", ",", "string", ")", ":", "open_paren", "=", "next", "(", "tokens", ")", "if", "not", "open_paren", "==", "'('", ":", "raise", "ValueError", "(", "INVALID_WKT_FMT", "%", "string", ")", "coords", "=", "[", "]", "pt...
26.95122
0.000873
def get_final(self): """Return the final solution in the original coordinates""" if self.prec is None: return self.x else: return self.prec.undo(self.x)
[ "def", "get_final", "(", "self", ")", ":", "if", "self", ".", "prec", "is", "None", ":", "return", "self", ".", "x", "else", ":", "return", "self", ".", "prec", ".", "undo", "(", "self", ".", "x", ")" ]
32.5
0.01
def listFileParents(self, logical_file_name="", block_id=0, block_name=""): """ required parameter: logical_file_name or block_name returns: this_logical_file_name, parent_logical_file_name, parent_file_id """ #self.logger.debug("lfn %s, block_name %s, block_id :%s" % (logical_fi...
[ "def", "listFileParents", "(", "self", ",", "logical_file_name", "=", "\"\"", ",", "block_id", "=", "0", ",", "block_name", "=", "\"\"", ")", ":", "#self.logger.debug(\"lfn %s, block_name %s, block_id :%s\" % (logical_file_name, block_name, block_id))", "if", "not", "logica...
54.85
0.010753
def refresh_access_information(self, refresh_token): """Return updated access information for an OAuth2 authorization grant. :param refresh_token: the refresh token used to obtain the updated information :returns: A dictionary with the key/value pairs for access_token, r...
[ "def", "refresh_access_information", "(", "self", ",", "refresh_token", ")", ":", "if", "self", ".", "config", ".", "grant_type", "==", "'password'", ":", "data", "=", "{", "'grant_type'", ":", "'password'", ",", "'username'", ":", "self", ".", "config", "."...
47.76
0.001642
def save_csv(p, sheet): 'Save as single CSV file, handling column names as first line.' with p.open_text(mode='w') as fp: cw = csv.writer(fp, **csvoptions()) colnames = [col.name for col in sheet.visibleCols] if ''.join(colnames): cw.writerow(colnames) for r in Progre...
[ "def", "save_csv", "(", "p", ",", "sheet", ")", ":", "with", "p", ".", "open_text", "(", "mode", "=", "'w'", ")", "as", "fp", ":", "cw", "=", "csv", ".", "writer", "(", "fp", ",", "*", "*", "csvoptions", "(", ")", ")", "colnames", "=", "[", "...
46.222222
0.002358
def _title(fig, title, subtitle="", *, margin=1, fontsize=20, subfontsize=18): """Add a title to a figure. Parameters ---------- fig : matplotlib Figure Figure. title : string Title. subtitle : string Subtitle. margin : number (optional) Distance from top of ...
[ "def", "_title", "(", "fig", ",", "title", ",", "subtitle", "=", "\"\"", ",", "*", ",", "margin", "=", "1", ",", "fontsize", "=", "20", ",", "subfontsize", "=", "18", ")", ":", "fig", ".", "suptitle", "(", "title", ",", "fontsize", "=", "fontsize",...
32.73913
0.00129
def start_scan(self, timeout_sec=TIMEOUT_SEC): """Start scanning for BLE devices with this adapter.""" self._scan_started.clear() self._adapter.StartDiscovery() if not self._scan_started.wait(timeout_sec): raise RuntimeError('Exceeded timeout waiting for adapter to start scan...
[ "def", "start_scan", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "self", ".", "_scan_started", ".", "clear", "(", ")", "self", ".", "_adapter", ".", "StartDiscovery", "(", ")", "if", "not", "self", ".", "_scan_started", ".", "wait", "(...
53.666667
0.009174
def _update(self): r"""Update This method updates the current reconstruction Notes ----- Implements algorithm 1 from [R2012]_ """ # Calculate gradient for current iteration. self._grad.get_grad(self._x_old) # Update z values. for i in ...
[ "def", "_update", "(", "self", ")", ":", "# Calculate gradient for current iteration.", "self", ".", "_grad", ".", "get_grad", "(", "self", ".", "_x_old", ")", "# Update z values.", "for", "i", "in", "range", "(", "self", ".", "_prox_list", ".", "size", ")", ...
31.8
0.001744
def mon_status(conn, logger, hostname, args, silent=False): """ run ``ceph daemon mon.`hostname` mon_status`` on the remote end and provide not only the output, but be able to return a boolean status of what is going on. ``False`` represents a monitor that is not doing OK even if it is up and ru...
[ "def", "mon_status", "(", "conn", ",", "logger", ",", "hostname", ",", "args", ",", "silent", "=", "False", ")", ":", "mon", "=", "'mon.%s'", "%", "hostname", "try", ":", "out", "=", "mon_status_check", "(", "conn", ",", "logger", ",", "hostname", ",",...
39.454545
0.001499
def t_VAR(self, t): r'[a-zA-Z_][a-zA-Z0-9_]*' t.type = self.reserved.get(t.value.lower(), 'VAR') return t
[ "def", "t_VAR", "(", "self", ",", "t", ")", ":", "t", ".", "type", "=", "self", ".", "reserved", ".", "get", "(", "t", ".", "value", ".", "lower", "(", ")", ",", "'VAR'", ")", "return", "t" ]
31.5
0.015504
def plot_ranges_from_cli(opts): """Parses the mins and maxs arguments from the `plot_posterior` option group. Parameters ---------- opts : ArgumentParser The parsed arguments from the command line. Returns ------- mins : dict Dictionary of parameter name -> specified mi...
[ "def", "plot_ranges_from_cli", "(", "opts", ")", ":", "mins", "=", "{", "}", "for", "x", "in", "opts", ".", "mins", ":", "x", "=", "x", ".", "split", "(", "':'", ")", "if", "len", "(", "x", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"op...
33.484848
0.00088
def walk(chains, start, end, step): """ Calculates Gelman-Rubin conervergence statistic along chains of data. This function will advance along the chains and calculate the statistic for each step. Parameters ---------- chains : iterable An iterable of numpy.array instances that contain ...
[ "def", "walk", "(", "chains", ",", "start", ",", "end", ",", "step", ")", ":", "# get number of chains, parameters, and iterations", "chains", "=", "numpy", ".", "array", "(", "chains", ")", "_", ",", "nparameters", ",", "_", "=", "chains", ".", "shape", "...
30.755556
0.0007
def go(fn, *args, **kwargs): """Launch an operation on a thread and get a handle to its future result. >>> from time import sleep >>> def print_sleep_print(duration): ... sleep(duration) ... print('hello from background thread') ... sleep(duration) ... print('goodbye from ba...
[ "def", "go", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "callable", "(", "fn", ")", ":", "raise", "TypeError", "(", "'go() requires a function, not %r'", "%", "(", "fn", ",", ")", ")", "result", "=", "[", "None", "...
26.297872
0.00078
def update_context(app, pagename, templatename, context, doctree): # pylint: disable=unused-argument """ Update the page rendering context to include ``feedback_form_url``. """ context['feedback_form_url'] = feedback_form_url(app.config.project, pagename)
[ "def", "update_context", "(", "app", ",", "pagename", ",", "templatename", ",", "context", ",", "doctree", ")", ":", "# pylint: disable=unused-argument", "context", "[", "'feedback_form_url'", "]", "=", "feedback_form_url", "(", "app", ".", "config", ".", "project...
53.6
0.011029
def setup_value_mapping_panels(self, classification): """Setup value mapping panel in the right panel. :param classification: Classification definition. :type classification: dict """ # Set text in the label layer_purpose = self.parent.step_kw_purpose.selected_purpose() ...
[ "def", "setup_value_mapping_panels", "(", "self", ",", "classification", ")", ":", "# Set text in the label", "layer_purpose", "=", "self", ".", "parent", ".", "step_kw_purpose", ".", "selected_purpose", "(", ")", "layer_subcategory", "=", "self", ".", "parent", "."...
42.208054
0.000311
def junos_rpc(cmd=None, dest=None, format=None, **kwargs): ''' .. versionadded:: 2019.2.0 Execute an RPC request on the remote Junos device. cmd The RPC request to the executed. To determine the RPC request, you can check the from the command line of the device, by executing the usual ...
[ "def", "junos_rpc", "(", "cmd", "=", "None", ",", "dest", "=", "None", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "prep", "=", "_junos_prep_fun", "(", "napalm_device", ")", "# pylint: disable=undefined-variable", "if", "not", "prep", "[...
32.54386
0.00157
def _get_param_names(cls): """Get parameter names for the estimator""" # fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, 'deprecated_original', cls.__init__) if init is object.__init__: # No explicit...
[ "def", "_get_param_names", "(", "cls", ")", ":", "# fetch the constructor or the original constructor before", "# deprecation wrapping if any", "init", "=", "getattr", "(", "cls", ".", "__init__", ",", "'deprecated_original'", ",", "cls", ".", "__init__", ")", "if", "in...
49.115385
0.001536
def set_bool(_bytearray, byte_index, bool_index, value): """ Set boolean value on location in bytearray """ assert value in [0, 1, True, False] current_value = get_bool(_bytearray, byte_index, bool_index) index_value = 1 << bool_index # check if bool already has correct value if current...
[ "def", "set_bool", "(", "_bytearray", ",", "byte_index", ",", "bool_index", ",", "value", ")", ":", "assert", "value", "in", "[", "0", ",", "1", ",", "True", ",", "False", "]", "current_value", "=", "get_bool", "(", "_bytearray", ",", "byte_index", ",", ...
30.5
0.001767
def _collect_metrics(repo, path, recursive, typ, xpath, branch): """Gather all the metric outputs. Args: path (str): Path to a metric file or a directory. recursive (bool): If path is a directory, do a recursive search for metrics on the given path. typ (str): The type of me...
[ "def", "_collect_metrics", "(", "repo", ",", "path", ",", "recursive", ",", "typ", ",", "xpath", ",", "branch", ")", ":", "outs", "=", "[", "out", "for", "stage", "in", "repo", ".", "stages", "(", ")", "for", "out", "in", "stage", ".", "outs", "]",...
28.913043
0.000727
def get_auth_server(domain, allow_http=False): """Retrieve the AUTH_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always*...
[ "def", "get_auth_server", "(", "domain", ",", "allow_http", "=", "False", ")", ":", "st", "=", "get_stellar_toml", "(", "domain", ",", "allow_http", ")", "if", "not", "st", ":", "return", "None", "return", "st", ".", "get", "(", "'AUTH_SERVER'", ")" ]
36.923077
0.002033
def _create_cipher(self, password, salt, nonce = None): """ Create the cipher object to encrypt or decrypt a payload. """ from argon2.low_level import hash_secret_raw, Type from Crypto.Cipher import AES aesmode = self._get_mode(self.aesmode) if aesmode is None: ...
[ "def", "_create_cipher", "(", "self", ",", "password", ",", "salt", ",", "nonce", "=", "None", ")", ":", "from", "argon2", ".", "low_level", "import", "hash_secret_raw", ",", "Type", "from", "Crypto", ".", "Cipher", "import", "AES", "aesmode", "=", "self",...
35.047619
0.02381
def get_volumes_from(container_map, config_name, config, policy, include_volumes): """ Generates volume paths for the host config ``volumes_from`` argument during container creation. :param container_map: Container map. :type container_map: dockermap.map.config.main.ContainerMap :param config_name:...
[ "def", "get_volumes_from", "(", "container_map", ",", "config_name", ",", "config", ",", "policy", ",", "include_volumes", ")", ":", "aname", "=", "policy", ".", "aname", "cname", "=", "policy", ".", "cname", "map_name", "=", "container_map", ".", "name", "v...
44.053571
0.002379
def parse_version_info(version): """Parse version string to a VersionInfo instance. :param version: version string :return: a :class:`VersionInfo` instance :rtype: :class:`VersionInfo` >>> import semver >>> version_info = semver.parse_version_info("3.4.5-pre.2+build.4") >>> version_info.ma...
[ "def", "parse_version_info", "(", "version", ")", ":", "parts", "=", "parse", "(", "version", ")", "version_info", "=", "VersionInfo", "(", "parts", "[", "'major'", "]", ",", "parts", "[", "'minor'", "]", ",", "parts", "[", "'patch'", "]", ",", "parts", ...
25.230769
0.001468
def get_page_of_iterator(iterator, page_size, page_number): """ Get a page from an interator, handling invalid input from the page number by defaulting to the first page. """ try: page_number = validate_page_number(page_number) except (PageNotAnInteger, EmptyPage): page_number = ...
[ "def", "get_page_of_iterator", "(", "iterator", ",", "page_size", ",", "page_number", ")", ":", "try", ":", "page_number", "=", "validate_page_number", "(", "page_number", ")", "except", "(", "PageNotAnInteger", ",", "EmptyPage", ")", ":", "page_number", "=", "1...
32.458333
0.001247
def encode(self): ''' Encode and store an UNSUBACK control packet ''' header = bytearray(1) varHeader = encode16Int(self.msgId) header[0] = 0xB0 header.extend(encodeLength(len(varHeader))) header.extend(varHeader) self.encoded = header ...
[ "def", "encode", "(", "self", ")", ":", "header", "=", "bytearray", "(", "1", ")", "varHeader", "=", "encode16Int", "(", "self", ".", "msgId", ")", "header", "[", "0", "]", "=", "0xB0", "header", ".", "extend", "(", "encodeLength", "(", "len", "(", ...
32.181818
0.010989
def get_num_processors(): """ Return number of online processor cores. """ # try different strategies and use first one that succeeeds try: return os.cpu_count() # Py3 only except AttributeError: pass try: import multiprocessing return multiprocessing.cpu_cou...
[ "def", "get_num_processors", "(", ")", ":", "# try different strategies and use first one that succeeeds", "try", ":", "return", "os", ".", "cpu_count", "(", ")", "# Py3 only", "except", "AttributeError", ":", "pass", "try", ":", "import", "multiprocessing", "return", ...
29.7
0.000815
def add_screen(self, ref): """ Add Screen """ if ref not in self.screens: screen = Screen(self, ref) screen.clear() # TODO Check this is needed, new screens should be clear. self.screens[ref] = screen return self.screens[ref]
[ "def", "add_screen", "(", "self", ",", "ref", ")", ":", "if", "ref", "not", "in", "self", ".", "screens", ":", "screen", "=", "Screen", "(", "self", ",", "ref", ")", "screen", ".", "clear", "(", ")", "# TODO Check this is needed, new screens should be clear....
32.888889
0.009868
def unparse(self, pieces, defaults=None): """Join the parts of a URI back together to form a valid URI. pieces is a tuble of URI pieces. The scheme must be in pieces[0] so that the rest of the pieces can be interpreted. """ return self.parser_for(pieces[0])(defaults).unparse(p...
[ "def", "unparse", "(", "self", ",", "pieces", ",", "defaults", "=", "None", ")", ":", "return", "self", ".", "parser_for", "(", "pieces", "[", "0", "]", ")", "(", "defaults", ")", ".", "unparse", "(", "pieces", ")" ]
39.875
0.009202
def update_domain_name(self, domain_name, certificate_name=None, certificate_body=None, certificate_private_key=None, certificate_chain=None, certificate_arn=...
[ "def", "update_domain_name", "(", "self", ",", "domain_name", ",", "certificate_name", "=", "None", ",", "certificate_body", "=", "None", ",", "certificate_private_key", "=", "None", ",", "certificate_chain", "=", "None", ",", "certificate_arn", "=", "None", ",", ...
54.666667
0.011276
def fit(ts, fs=[], all_params=[], fit_vars=None, alg='leastsq', make_bounded=True): """ Use a minimization algorithm to fit a AstonSeries with analytical functions. """ if fit_vars is None: fit_vars = [f._peakargs for f in fs] initc = [min(ts.values)] for f, peak_params, to_f...
[ "def", "fit", "(", "ts", ",", "fs", "=", "[", "]", ",", "all_params", "=", "[", "]", ",", "fit_vars", "=", "None", ",", "alg", "=", "'leastsq'", ",", "make_bounded", "=", "True", ")", ":", "if", "fit_vars", "is", "None", ":", "fit_vars", "=", "["...
37
0.000321
def _writeBk(target="sentenceContainsTarget(+SID,+WID).", treeDepth="3", nodeSize="3", numOfClauses="8"): """ Writes a background file to disk. :param target: Target predicate with modes. :type target: str. :param treeDepth: Depth of the tree. :type treeDepth: str. :param nodeS...
[ "def", "_writeBk", "(", "target", "=", "\"sentenceContainsTarget(+SID,+WID).\"", ",", "treeDepth", "=", "\"3\"", ",", "nodeSize", "=", "\"3\"", ",", "numOfClauses", "=", "\"8\"", ")", ":", "with", "open", "(", "'bk.txt'", ",", "'w'", ")", "as", "bk", ":", ...
39.075
0.000624
def get_help(self, prefix='', include_special_flags=True): """Returns a help string for all known flags. Args: prefix: str, per-line output prefix. include_special_flags: bool, whether to include description of SPECIAL_FLAGS, i.e. --flagfile and --undefok. Returns: str, formatted...
[ "def", "get_help", "(", "self", ",", "prefix", "=", "''", ",", "include_special_flags", "=", "True", ")", ":", "flags_by_module", "=", "self", ".", "flags_by_module_dict", "(", ")", "if", "flags_by_module", ":", "modules", "=", "sorted", "(", "flags_by_module"...
38.034483
0.011494
def step(self, action): """Pass action to underlying environment(s) or perform special action.""" # Special codes if action in self._player_actions(): envs_step_tuples = self._player_actions()[action]() elif self._wait and action == self.name_to_action_num["NOOP"]: # Ignore no-op, do not pas...
[ "def", "step", "(", "self", ",", "action", ")", ":", "# Special codes", "if", "action", "in", "self", ".", "_player_actions", "(", ")", ":", "envs_step_tuples", "=", "self", ".", "_player_actions", "(", ")", "[", "action", "]", "(", ")", "elif", "self", ...
42.789474
0.01083
def emoticons_tag(parser, token): """ Tag for rendering emoticons. """ exclude = '' args = token.split_contents() if len(args) == 2: exclude = args[1] elif len(args) > 2: raise template.TemplateSyntaxError( 'emoticons tag has only one optional argument') node...
[ "def", "emoticons_tag", "(", "parser", ",", "token", ")", ":", "exclude", "=", "''", "args", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "args", ")", "==", "2", ":", "exclude", "=", "args", "[", "1", "]", "elif", "len", "(", ...
27.866667
0.002315
def get_assembly(name): """read a single assembly by name, returning a dictionary of assembly data >>> assy = get_assembly('GRCh37.p13') >>> assy['name'] 'GRCh37.p13' >>> assy['description'] 'Genome Reference Consortium Human Build 37 patch release 13 (GRCh37.p13)' >>> assy['refseq_ac'] ...
[ "def", "get_assembly", "(", "name", ")", ":", "fn", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "_assy_path_fmt", ".", "format", "(", "name", "=", "name", ")", ")", "return", "json", ".", "load", "(", "gzip", ".", "open", "(", ...
25.228571
0.001091
async def fetch_logical_load(self, llid): """Lookup details for a given logical load""" url = "https://production.plum.technology/v2/getLogicalLoad" data = {"llid": llid} return await self.__post(url, data)
[ "async", "def", "fetch_logical_load", "(", "self", ",", "llid", ")", ":", "url", "=", "\"https://production.plum.technology/v2/getLogicalLoad\"", "data", "=", "{", "\"llid\"", ":", "llid", "}", "return", "await", "self", ".", "__post", "(", "url", ",", "data", ...
46.8
0.008403
def process(self, query): """Returns the visualizations for query. Args: query: The query to process. Returns: A dictionary of results with processing and graph visualizations. """ tf.logging.info("Processing new query [%s]" %query) # Create the new TFDBG hook directory. hook_...
[ "def", "process", "(", "self", ",", "query", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Processing new query [%s]\"", "%", "query", ")", "# Create the new TFDBG hook directory.", "hook_dir", "=", "\"/tmp/t2t_server_dump/request_%d\"", "%", "int", "(", "tim...
35.590062
0.009508
def _find_parenthesis(self, position, forward=True): """ If 'forward' is True (resp. False), proceed forwards (resp. backwards) through the line that contains 'position' until an unmatched closing (resp. opening) parenthesis is found. Returns a tuple containing the position o...
[ "def", "_find_parenthesis", "(", "self", ",", "position", ",", "forward", "=", "True", ")", ":", "commas", "=", "depth", "=", "0", "document", "=", "self", ".", "_text_edit", ".", "document", "(", ")", "char", "=", "document", ".", "characterAt", "(", ...
42.178571
0.002483
def export_obj_str(surface, **kwargs): """ Exports surface(s) as a .obj file (string). Keyword Arguments: * ``vertex_spacing``: size of the triangle edge in terms of surface points sampled. *Default: 2* * ``vertex_normals``: if True, then computes vertex normals. *Default: False* * ``pa...
[ "def", "export_obj_str", "(", "surface", ",", "*", "*", "kwargs", ")", ":", "# Get keyword arguments", "vertex_spacing", "=", "int", "(", "kwargs", ".", "get", "(", "'vertex_spacing'", ",", "1", ")", ")", "include_vertex_normal", "=", "kwargs", ".", "get", "...
35.786517
0.002444
def updateActiveMarkupClass(self): ''' Update the active markup class based on the default class and the current filename. If the active markup class changes, the highlighter is rerun on the input text, the markup object of this tab is replaced with one of the new class and the activeMarkupChanged signal is...
[ "def", "updateActiveMarkupClass", "(", "self", ")", ":", "previousMarkupClass", "=", "self", ".", "activeMarkupClass", "self", ".", "activeMarkupClass", "=", "find_markup_class_by_name", "(", "globalSettings", ".", "defaultMarkup", ")", "if", "self", ".", "_fileName",...
35.625
0.026196
def get_one(self): """get one row from the db""" self.default_val = None o = self.default_val d = self._query('get_one') if d: o = self.orm_class(d, hydrate=True) return o
[ "def", "get_one", "(", "self", ")", ":", "self", ".", "default_val", "=", "None", "o", "=", "self", ".", "default_val", "d", "=", "self", ".", "_query", "(", "'get_one'", ")", "if", "d", ":", "o", "=", "self", ".", "orm_class", "(", "d", ",", "hy...
28
0.008658
def show_top_losses(self, k:int, max_len:int=70)->None: """ Create a tabulation showing the first `k` texts in top_losses along with their prediction, actual,loss, and probability of actual class. `max_len` is the maximum number of tokens displayed. """ from IPython.display impor...
[ "def", "show_top_losses", "(", "self", ",", "k", ":", "int", ",", "max_len", ":", "int", "=", "70", ")", "->", "None", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", "items", "=", "[", "]", "tl_val", ",", "tl_idx", "=", "...
50.608696
0.015177
def from_xml(xml): """ Convert :class:`.MARCXMLRecord` object to :class:`.EPublication` namedtuple. Args: xml (str/MARCXMLRecord): MARC XML which will be converted to EPublication. In case of str, ``<record>`` tag is required. Returns: st...
[ "def", "from_xml", "(", "xml", ")", ":", "parsed", "=", "xml", "if", "not", "isinstance", "(", "xml", ",", "MARCXMLRecord", ")", ":", "parsed", "=", "MARCXMLRecord", "(", "str", "(", "xml", ")", ")", "# check whether the document was deleted", "if", "\"DEL\"...
38.378378
0.001374
def new_method_return(self) : "creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message." result = dbus.dbus_message_new_method_return(self._dbobj) if result == None : raise CallFailed("dbus_message_new_method_return") #end if return \ ...
[ "def", "new_method_return", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_method_return", "(", "self", ".", "_dbobj", ")", "if", "result", "==", "None", ":", "raise", "CallFailed", "(", "\"dbus_message_new_method_return\"", ")", "#end if", ...
41.5
0.020649
def reload_site(self): """Reload the site from the database.""" rev = int(self.db.get('site:rev')) if rev != self.revision and self.db.exists('site:rev'): timeline = self.db.lrange('site:timeline', 0, -1) self._timeline = [] for data in timeline: ...
[ "def", "reload_site", "(", "self", ")", ":", "rev", "=", "int", "(", "self", ".", "db", ".", "get", "(", "'site:rev'", ")", ")", "if", "rev", "!=", "self", ".", "revision", "and", "self", ".", "db", ".", "exists", "(", "'site:rev'", ")", ":", "ti...
43.454545
0.002047
def chartItems(self): """ Returns the chart items that are found within this scene. :return [<XChartWidgetItem>, ..] """ from projexui.widgets.xchartwidget import XChartWidgetItem return filter(lambda x: isinstance(x, XChartWidgetItem), self.items())
[ "def", "chartItems", "(", "self", ")", ":", "from", "projexui", ".", "widgets", ".", "xchartwidget", "import", "XChartWidgetItem", "return", "filter", "(", "lambda", "x", ":", "isinstance", "(", "x", ",", "XChartWidgetItem", ")", ",", "self", ".", "items", ...
38.875
0.009434
def run(self): """ Listen for controllers. """ while True: data, sender = self.sock.recvfrom(1024) addr = sender[0] msg = data.decode('utf-8') if msg.startswith('/controller/'): try: uid = msg.split('/')[...
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "data", ",", "sender", "=", "self", ".", "sock", ".", "recvfrom", "(", "1024", ")", "addr", "=", "sender", "[", "0", "]", "msg", "=", "data", ".", "decode", "(", "'utf-8'", ")", "if", "...
39.026316
0.001316
def ignores(self, *args): """ :param args: Event objects :returns: None Any event that is ignored is acceptable but discarded """ for event in args: self._ignored.add(event.name)
[ "def", "ignores", "(", "self", ",", "*", "args", ")", ":", "for", "event", "in", "args", ":", "self", ".", "_ignored", ".", "add", "(", "event", ".", "name", ")" ]
28.875
0.008403
def compute_group_colors(self): """Computes the group colors according to node colors""" seen = set() self.group_label_color = [ x for x in self.node_colors if not (x in seen or seen.add(x)) ]
[ "def", "compute_group_colors", "(", "self", ")", ":", "seen", "=", "set", "(", ")", "self", ".", "group_label_color", "=", "[", "x", "for", "x", "in", "self", ".", "node_colors", "if", "not", "(", "x", "in", "seen", "or", "seen", ".", "add", "(", "...
38.5
0.008475
def list_active_gen(self, pattern=None): """Generator for the LIST ACTIVE command. Generates a list of active newsgroups that match the specified pattern. If no pattern is specfied then all active groups are generated. See <http://tools.ietf.org/html/rfc3977#section-7.6.3> Arg...
[ "def", "list_active_gen", "(", "self", ",", "pattern", "=", "None", ")", ":", "args", "=", "pattern", "if", "args", "is", "None", ":", "cmd", "=", "\"LIST\"", "else", ":", "cmd", "=", "\"LIST ACTIVE\"", "code", ",", "message", "=", "self", ".", "comman...
29.857143
0.002317
def color_to_rgb_or_rgba(color, alpha_float=True): """\ Returns the provided color as ``(R, G, B)`` or ``(R, G, B, A)`` tuple. If the alpha value is opaque, an RGB tuple is returned, otherwise an RGBA tuple. :param color: A web color name (i.e. ``darkblue``) or a hexadecimal value (``#...
[ "def", "color_to_rgb_or_rgba", "(", "color", ",", "alpha_float", "=", "True", ")", ":", "rgba", "=", "color_to_rgba", "(", "color", ",", "alpha_float", "=", "alpha_float", ")", "if", "rgba", "[", "3", "]", "in", "(", "1.0", ",", "255", ")", ":", "retur...
39.157895
0.001312
def adjust_for_triggers(self): """Remove trigger-related plugins when needed If there are no triggers defined, it's assumed the feature is disabled and all trigger-related plugins are removed. If there are triggers defined, and this is a custom base image, some trigger-...
[ "def", "adjust_for_triggers", "(", "self", ")", ":", "triggers", "=", "self", ".", "template", "[", "'spec'", "]", ".", "get", "(", "'triggers'", ",", "[", "]", ")", "remove_plugins", "=", "[", "(", "\"prebuild_plugins\"", ",", "\"check_and_set_rebuild\"", "...
38.368421
0.002007
def flush(self): """Empty the buffer.""" for seq in self.buffer: SeqIO.write(seq, self.handle, self.format) self.buffer = []
[ "def", "flush", "(", "self", ")", ":", "for", "seq", "in", "self", ".", "buffer", ":", "SeqIO", ".", "write", "(", "seq", ",", "self", ".", "handle", ",", "self", ".", "format", ")", "self", ".", "buffer", "=", "[", "]" ]
31.2
0.0125
def solve(self): """ Solves DC optimal power flow and returns a results dict. """ base_mva = self.om.case.base_mva Bf = self.om._Bf Pfinj = self.om._Pfinj # Unpack the OPF model. bs, ln, gn, cp = self._unpack_model(self.om) # Compute problem dimensions. ...
[ "def", "solve", "(", "self", ")", ":", "base_mva", "=", "self", ".", "om", ".", "case", ".", "base_mva", "Bf", "=", "self", ".", "om", ".", "_Bf", "Pfinj", "=", "self", ".", "om", ".", "_Pfinj", "# Unpack the OPF model.", "bs", ",", "ln", ",", "gn"...
45.4
0.001078
def _plot_depth_track(self, ax, md, kind='MD'): """ Private function. Depth track plotting. Args: ax (ax): A matplotlib axis. md (ndarray): The measured depths of the track. kind (str): The kind of track to plot. Returns: ax. """ ...
[ "def", "_plot_depth_track", "(", "self", ",", "ax", ",", "md", ",", "kind", "=", "'MD'", ")", ":", "if", "kind", "==", "'MD'", ":", "ax", ".", "set_yscale", "(", "'bounded'", ",", "vmin", "=", "md", ".", "min", "(", ")", ",", "vmax", "=", "md", ...
31.428571
0.001259
def normalize_arxiv_category(category): """Normalize arXiv category to be schema compliant. This properly capitalizes the category and replaces the dash by a dot if needed. If the category is obsolete, it also gets converted it to its current equivalent. Example: >>> from inspire_schemas.u...
[ "def", "normalize_arxiv_category", "(", "category", ")", ":", "category", "=", "_NEW_CATEGORIES", ".", "get", "(", "category", ".", "lower", "(", ")", ",", "category", ")", "for", "valid_category", "in", "valid_arxiv_categories", "(", ")", ":", "if", "(", "c...
38.894737
0.001321
def CreateDialectActions(dialect): """Create dialect specific actions.""" CompAction = SCons.Action.Action('$%sCOM ' % dialect, '$%sCOMSTR' % dialect) CompPPAction = SCons.Action.Action('$%sPPCOM ' % dialect, '$%sPPCOMSTR' % dialect) ShCompAction = SCons.Action.Action('$SH%sCOM ' % dialect, '$SH%sCOMSTR...
[ "def", "CreateDialectActions", "(", "dialect", ")", ":", "CompAction", "=", "SCons", ".", "Action", ".", "Action", "(", "'$%sCOM '", "%", "dialect", ",", "'$%sCOMSTR'", "%", "dialect", ")", "CompPPAction", "=", "SCons", ".", "Action", ".", "Action", "(", "...
60.625
0.010163
def fix_orientation(image): """ adapted from https://stackoverflow.com/a/30462851/318857 Apply Image.transpose to ensure 0th row of pixels is at the visual top of the image, and 0th column is the visual left-hand side. Return the original image if unable to determine the orientation. ...
[ "def", "fix_orientation", "(", "image", ")", ":", "exif_orientation_tag", "=", "0x0112", "exif_transpose_sequences", "=", "[", "[", "]", ",", "[", "]", ",", "[", "PIL", ".", "Image", ".", "FLIP_LEFT_RIGHT", "]", ",", "[", "PIL", ".", "Image", ".", "ROTAT...
35.484848
0.000831
def tri_value(self): """ See the class documentation. """ if self._cached_tri_val is not None: return self._cached_tri_val if self.orig_type not in _BOOL_TRISTATE: if self.orig_type: # != UNKNOWN # Would take some work to give the locatio...
[ "def", "tri_value", "(", "self", ")", ":", "if", "self", ".", "_cached_tri_val", "is", "not", "None", ":", "return", "self", ".", "_cached_tri_val", "if", "self", ".", "orig_type", "not", "in", "_BOOL_TRISTATE", ":", "if", "self", ".", "orig_type", ":", ...
36.692308
0.000681
def dependencyOrder(aMap, aList = None): """ Given descriptions of dependencies in aMap and an optional list of items in aList if not aList, aList = aMap.keys() Returns a list containing each element of aList and all its precursors so that every precursor of any element in the returned list is seen before tha...
[ "def", "dependencyOrder", "(", "aMap", ",", "aList", "=", "None", ")", ":", "dependencyMap", "=", "makeDependencyMap", "(", "aMap", ")", "outputList", "=", "[", "]", "if", "not", "aList", ":", "aList", "=", "aMap", ".", "keys", "(", ")", "items", "=", ...
34.619048
0.021419
def rtouches(self, span): """ Returns true if the start of this span touches the right (ending) side of the given span. """ if isinstance(span, list): return [sp for sp in span if self._rtouches(sp)] return self._rtouches(span)
[ "def", "rtouches", "(", "self", ",", "span", ")", ":", "if", "isinstance", "(", "span", ",", "list", ")", ":", "return", "[", "sp", "for", "sp", "in", "span", "if", "self", ".", "_rtouches", "(", "sp", ")", "]", "return", "self", ".", "_rtouches", ...
34.125
0.010714
def _get_lib_name(lib): """ Helper function to get an architecture and Python version specific library filename. """ # append any extension suffix defined by Python for current platform ext_suffix = sysconfig.get_config_var("EXT_SUFFIX") # in principle "EXT_SUFFIX" is what we want. # "SO...
[ "def", "_get_lib_name", "(", "lib", ")", ":", "# append any extension suffix defined by Python for current platform", "ext_suffix", "=", "sysconfig", ".", "get_config_var", "(", "\"EXT_SUFFIX\"", ")", "# in principle \"EXT_SUFFIX\" is what we want.", "# \"SO\" seems to be deprecated ...
37.954545
0.001168
def simulate(self, action): """Step the batch of environments. The results of the step can be accessed from the variables defined below. Args: action: Tensor holding the batch of actions to apply. Returns: Operation. """ with tf.name_scope("environment/simulate"): if action....
[ "def", "simulate", "(", "self", ",", "action", ")", ":", "with", "tf", ".", "name_scope", "(", "\"environment/simulate\"", ")", ":", "if", "action", ".", "dtype", "in", "(", "tf", ".", "float16", ",", "tf", ".", "float32", ",", "tf", ".", "float64", ...
38.46875
0.008716
def get_service(self, name): """ Locates a remote service by name. The name can be a glob-like pattern (``"project.worker.*"``). If multiple services match the given name, a random instance will be chosen. There might be multiple services that match a given name if there are mult...
[ "def", "get_service", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "discovery_strategies", ":", "raise", "ServiceConfigurationError", "(", "\"No service registry available\"", ")", "cached", "=", "self", ".", "remote_service_cache", ".", "get_entry"...
42.333333
0.001776
def date_range(cls,start_time,end_time,freq): ''' Returns a new SArray that represents a fixed frequency datetime index. Parameters ---------- start_time : datetime.datetime Left bound for generating dates. end_time : datetime.datetime Right bound fo...
[ "def", "date_range", "(", "cls", ",", "start_time", ",", "end_time", ",", "freq", ")", ":", "if", "not", "isinstance", "(", "start_time", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "\"The ``start_time`` argument must be from type dateti...
33.977778
0.008264
def _change_state(name, action, expected, *args, **kwargs): ''' Change the state of a container ''' pre = state(name) if action != 'restart' and pre == expected: return {'result': False, 'state': {'old': expected, 'new': expected}, 'comment': ('Container \'{0}...
[ "def", "_change_state", "(", "name", ",", "action", ",", "expected", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pre", "=", "state", "(", "name", ")", "if", "action", "!=", "'restart'", "and", "pre", "==", "expected", ":", "return", "{", ...
33.75
0.001441
def try_catch(func, *args, **kwargs): ''' Wrap call of provided function with try/except block and debug log statements. If an instance of 'Exception' (or one of its subclasses) is thrown by 'func', it is caught, and the exception object itself is return as a result. ''' try: return log_...
[ "def", "try_catch", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "log_debug", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "exc", ":", "logging", ".", "debug", ...
43.636364
0.008163
def start(self): """Start measuring code coverage. Coverage measurement actually occurs in functions called after `start` is invoked. Statements in the same scope as `start` won't be measured. Once you invoke `start`, you must also call `stop` eventually, or your process might...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "run_suffix", ":", "# Calling start() means we're running code, so use the run_suffix", "# as the data_suffix when we eventually save the data.", "self", ".", "data_suffix", "=", "self", ".", "run_suffix", "if", "sel...
37.976744
0.001194
def loglike(pulsar,efac=1.0,equad=None,jitter=None,Ared=None,gammared=None,marginalize=True,normalize=True,redcomponents=10,usedeleted=True): """Returns the Gaussian-process likelihood for 'pulsar'. The likelihood is evaluated at the current value of the pulsar parameters, as given by pulsar[parname].val. ...
[ "def", "loglike", "(", "pulsar", ",", "efac", "=", "1.0", ",", "equad", "=", "None", ",", "jitter", "=", "None", ",", "Ared", "=", "None", ",", "gammared", "=", "None", ",", "marginalize", "=", "True", ",", "normalize", "=", "True", ",", "redcomponen...
35.2
0.01437
def install_sql_hook(): """If installed this causes Django's queries to be captured.""" try: from django.db.backends.utils import CursorWrapper except ImportError: from django.db.backends.util import CursorWrapper try: real_execute = CursorWrapper.execute real_executeman...
[ "def", "install_sql_hook", "(", ")", ":", "try", ":", "from", "django", ".", "db", ".", "backends", ".", "utils", "import", "CursorWrapper", "except", "ImportError", ":", "from", "django", ".", "db", ".", "backends", ".", "util", "import", "CursorWrapper", ...
36.25641
0.000689