text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def id(self): """A unique, stable, hashable id over the set of pinned artifacts.""" if not self._id: # NB(gmalmquist): This id is not cheap to compute if there are a large number of artifacts. # We cache it here, but invalidate the cached value if an artifact gets added or changed. self._id = ...
[ "def", "id", "(", "self", ")", ":", "if", "not", "self", ".", "_id", ":", "# NB(gmalmquist): This id is not cheap to compute if there are a large number of artifacts.", "# We cache it here, but invalidate the cached value if an artifact gets added or changed.", "self", ".", "_id", ...
51.857143
26.571429
def _append_theme_dir(self, name): """Append a theme dir to the Tk interpreter auto_path""" path = "[{}]".format(get_file_directory() + "/" + name) self.tk.call("lappend", "auto_path", path)
[ "def", "_append_theme_dir", "(", "self", ",", "name", ")", ":", "path", "=", "\"[{}]\"", ".", "format", "(", "get_file_directory", "(", ")", "+", "\"/\"", "+", "name", ")", "self", ".", "tk", ".", "call", "(", "\"lappend\"", ",", "\"auto_path\"", ",", ...
52.75
9.75
def _set_used_as_input_variables_by_entity(self) -> Dict[str, List[str]]: '''Identify and set the good input variables for the different entities''' if self.used_as_input_variables_by_entity is not None: return tax_benefit_system = self.tax_benefit_system assert set(self.us...
[ "def", "_set_used_as_input_variables_by_entity", "(", "self", ")", "->", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ":", "if", "self", ".", "used_as_input_variables_by_entity", "is", "not", "None", ":", "return", "tax_benefit_system", "=", "self", ...
45.818182
31.636364
def latch(self): """Convert the current value inside this config descriptor to a python object. The conversion proceeds by mapping the given type name to a native python class and performing the conversion. You can override what python object is used as the destination class by passing...
[ "def", "latch", "(", "self", ")", ":", "if", "len", "(", "self", ".", "current_value", ")", "==", "0", ":", "raise", "DataError", "(", "\"There was no data in a config variable during latching\"", ",", "name", "=", "self", ".", "name", ")", "# Make sure the data...
40.135593
28.355932
def handle(self, *args, **options): """ get the trigger to fire """ trigger_id = options.get('trigger_id') trigger = TriggerService.objects.filter( id=int(trigger_id), status=True, user__is_active=True, provider_failed__lt=setti...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "trigger_id", "=", "options", ".", "get", "(", "'trigger_id'", ")", "trigger", "=", "TriggerService", ".", "objects", ".", "filter", "(", "id", "=", "int", "(", "trig...
38.666667
14.333333
async def rank(self, request, origin: Optional[Text]) \ -> Tuple[ float, Optional[BaseTrigger], Optional[type], Optional[bool], ]: """ Computes the rank of this transition for a given request. It returns (in...
[ "async", "def", "rank", "(", "self", ",", "request", ",", "origin", ":", "Optional", "[", "Text", "]", ")", "->", "Tuple", "[", "float", ",", "Optional", "[", "BaseTrigger", "]", ",", "Optional", "[", "type", "]", ",", "Optional", "[", "bool", "]", ...
30.206897
16
def concept_cuts(direction, node_indices, node_labels=None): """Generator over all concept-syle cuts for these nodes.""" for partition in mip_partitions(node_indices, node_indices): yield KCut(direction, partition, node_labels)
[ "def", "concept_cuts", "(", "direction", ",", "node_indices", ",", "node_labels", "=", "None", ")", ":", "for", "partition", "in", "mip_partitions", "(", "node_indices", ",", "node_indices", ")", ":", "yield", "KCut", "(", "direction", ",", "partition", ",", ...
60
14.25
def determine_opening_indent(indent_texts): '''Determine the opening indent level for a docstring. The opening indent level is the indent level is the first non-zero indent level of a non-empty line in the docstring. Args: indent_texts: The lines of the docstring as an iterable over 2-tuples ...
[ "def", "determine_opening_indent", "(", "indent_texts", ")", ":", "num_lines", "=", "len", "(", "indent_texts", ")", "if", "num_lines", "<", "1", ":", "return", "0", "assert", "num_lines", ">=", "1", "first_line_indent", "=", "indent_texts", "[", "0", "]", "...
25.542857
23.428571
def set_backgroundcolor(self, color): '''Sets the background color of the current axes (and legend). Use 'None' (with quotes) for transparent. To get transparent background on saved figures, use: pp.savefig("fig1.svg", transparent=True) ''' ax = self.ax ...
[ "def", "set_backgroundcolor", "(", "self", ",", "color", ")", ":", "ax", "=", "self", ".", "ax", "ax", ".", "patch", ".", "set_facecolor", "(", "color", ")", "lh", "=", "ax", ".", "get_legend", "(", ")", "if", "lh", "!=", "None", ":", "lh", ".", ...
36.153846
17.846154
def distance_to(self, other_catchment): """ Returns the distance between the centroids of two catchments in kilometers. :param other_catchment: Catchment to calculate distance to :type other_catchment: :class:`.Catchment` :return: Distance between the catchments in km. :...
[ "def", "distance_to", "(", "self", ",", "other_catchment", ")", ":", "try", ":", "if", "self", ".", "country", "==", "other_catchment", ".", "country", ":", "try", ":", "return", "0.001", "*", "hypot", "(", "self", ".", "descriptors", ".", "centroid_ngr", ...
51.727273
27.545455
def check_syntax(code): """Return True if syntax is okay.""" try: return compile(code, '<string>', 'exec', dont_inherit=True) except (SyntaxError, TypeError, ValueError): return False
[ "def", "check_syntax", "(", "code", ")", ":", "try", ":", "return", "compile", "(", "code", ",", "'<string>'", ",", "'exec'", ",", "dont_inherit", "=", "True", ")", "except", "(", "SyntaxError", ",", "TypeError", ",", "ValueError", ")", ":", "return", "F...
34.333333
17.333333
def writable_stream(handle): """Test whether a stream can be written to. """ if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5): return handle.writable() try: handle.write(b'') except (io.UnsupportedOperation, IOError): return False else: return True
[ "def", "writable_stream", "(", "handle", ")", ":", "if", "isinstance", "(", "handle", ",", "io", ".", "IOBase", ")", "and", "sys", ".", "version_info", ">=", "(", "3", ",", "5", ")", ":", "return", "handle", ".", "writable", "(", ")", "try", ":", "...
28.090909
15.727273
def coordinates(self): """ Get or set the internal coordinate system. Available coordinate systems are: - ``'jacobi'`` (default) - ``'democraticheliocentric'`` - ``'whds'`` """ i = self._coordinates for name, _i in COORDINATES.items(): ...
[ "def", "coordinates", "(", "self", ")", ":", "i", "=", "self", ".", "_coordinates", "for", "name", ",", "_i", "in", "COORDINATES", ".", "items", "(", ")", ":", "if", "i", "==", "_i", ":", "return", "name", "return", "i" ]
24.133333
14
def scheme(name, bins, bin_method='quantiles'): """Return a custom scheme based on CARTOColors. Args: name (str): Name of a CARTOColor. bins (int or iterable): If an `int`, the number of bins for classifying data. CARTOColors have 7 bins max for quantitative data, and 11 max ...
[ "def", "scheme", "(", "name", ",", "bins", ",", "bin_method", "=", "'quantiles'", ")", ":", "return", "{", "'name'", ":", "name", ",", "'bins'", ":", "bins", ",", "'bin_method'", ":", "(", "bin_method", "if", "isinstance", "(", "bins", ",", "int", ")",...
39.115385
26.884615
def create(cls, selection, config, **kwargs): """Create an ROIModel instance.""" if selection['target'] is not None: return cls.create_from_source(selection['target'], config, **kwargs) else: target_skydir = wcs_utils.get_target_...
[ "def", "create", "(", "cls", ",", "selection", ",", "config", ",", "*", "*", "kwargs", ")", ":", "if", "selection", "[", "'target'", "]", "is", "not", "None", ":", "return", "cls", ".", "create_from_source", "(", "selection", "[", "'target'", "]", ",",...
45.111111
19.777778
def _get_common_params(self, user_id, attributes): """ Get params which are used same in both conversion and impression events. Args: user_id: ID for user. attributes: Dict representing user attributes and values which need to be recorded. Returns: Dict consisting of parameters common to ...
[ "def", "_get_common_params", "(", "self", ",", "user_id", ",", "attributes", ")", ":", "commonParams", "=", "{", "}", "commonParams", "[", "self", ".", "EventParams", ".", "PROJECT_ID", "]", "=", "self", ".", "_get_project_id", "(", ")", "commonParams", "[",...
39.933333
27.166667
def clear_symbols(self, index): """Clears all symbols begining with the index to the end of table""" try: del self.table[index:] except Exception: self.error() self.table_len = len(self.table)
[ "def", "clear_symbols", "(", "self", ",", "index", ")", ":", "try", ":", "del", "self", ".", "table", "[", "index", ":", "]", "except", "Exception", ":", "self", ".", "error", "(", ")", "self", ".", "table_len", "=", "len", "(", "self", ".", "table...
35.428571
9.857143
def _baseattrs(self): """A dict of members expressed in literals""" result = super()._baseattrs result["spaces"] = self.spaces._baseattrs return result
[ "def", "_baseattrs", "(", "self", ")", ":", "result", "=", "super", "(", ")", ".", "_baseattrs", "result", "[", "\"spaces\"", "]", "=", "self", ".", "spaces", ".", "_baseattrs", "return", "result" ]
29.833333
15.333333
def top_x_bleu(query_dic, mark, x=1): """ Calculate the top x average bleu value predictions ranking by item, x default is set above :param query_dic: dict, key is qid, value is (item, bleu) tuple list, which will be ranked by 'item' as key :param mark:string, which indicates which method is evaluat...
[ "def", "top_x_bleu", "(", "query_dic", ",", "mark", ",", "x", "=", "1", ")", ":", "all_total", "=", "0.0", "with", "open", "(", "top_bleu_path", "+", "mark", ",", "'w'", ")", "as", "writer", ":", "for", "k", "in", "query_dic", ":", "candidate_lst", "...
43.965517
19.758621
def get_extract_value_function(column_identifier): """ returns a function that extracts the value for a column. """ def extract_value(run_result): pos = None for i, column in enumerate(run_result.columns): if column.title == column_identifier: pos = i ...
[ "def", "get_extract_value_function", "(", "column_identifier", ")", ":", "def", "extract_value", "(", "run_result", ")", ":", "pos", "=", "None", "for", "i", ",", "column", "in", "enumerate", "(", "run_result", ".", "columns", ")", ":", "if", "column", ".", ...
36.357143
14.928571
def get_files_in_branch(profile, branch_sha): """Get all files in a branch's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ...
[ "def", "get_files_in_branch", "(", "profile", ",", "branch_sha", ")", ":", "tree_sha", "=", "get_commit_tree", "(", "profile", ",", "branch_sha", ")", "files", "=", "get_files_in_tree", "(", "profile", ",", "tree_sha", ")", "tree", "=", "[", "prepare", "(", ...
29.238095
22.52381
def _safe_call(obj, methname, *args, **kwargs): """ Safely calls the method with the given methname on the given object. Remaining positional and keyword arguments are passed to the method. The return value is None, if the method is not available, or the return value of the method. """ me...
[ "def", "_safe_call", "(", "obj", ",", "methname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "meth", "=", "getattr", "(", "obj", ",", "methname", ",", "None", ")", "if", "meth", "is", "None", "or", "not", "callable", "(", "meth", ")", "...
33.307692
16.076923
def shutdown(self, targets='all', restart=False, hub=False, block=None): """Terminates one or more engine processes, optionally including the hub. Parameters ---------- targets: list of ints or 'all' [default: all] Which engines to shutdown. hub: boo...
[ "def", "shutdown", "(", "self", ",", "targets", "=", "'all'", ",", "restart", "=", "False", ",", "hub", "=", "False", ",", "block", "=", "None", ")", ":", "if", "restart", ":", "raise", "NotImplementedError", "(", "\"Engine restart is not yet implemented\"", ...
37.72
18.84
def remove_matching_braces(latex): """ If `latex` is surrounded by matching braces, remove them. They are not necessary. Parameters ---------- latex : string Returns ------- string Examples -------- >>> remove_matching_braces('{2+2}') '2+2' >>> remove_matching_...
[ "def", "remove_matching_braces", "(", "latex", ")", ":", "if", "latex", ".", "startswith", "(", "'{'", ")", "and", "latex", ".", "endswith", "(", "'}'", ")", ":", "opened", "=", "1", "matches", "=", "True", "for", "char", "in", "latex", "[", "1", ":"...
21
19.848485
def host_dns(proxy=None): ''' Return the DNS information of the host. This grain is a dictionary having two keys: - ``A`` - ``AAAA`` .. note:: This grain is disabled by default, as the proxy startup may be slower when the lookup fails. The user can enable it using the `...
[ "def", "host_dns", "(", "proxy", "=", "None", ")", ":", "if", "not", "__opts__", ".", "get", "(", "'napalm_host_dns_grain'", ",", "False", ")", ":", "return", "device_host", "=", "host", "(", "proxy", "=", "proxy", ")", "if", "device_host", ":", "device_...
24.046875
21.859375
def compute_trans(expnums, ccd, version, prefix=None, default="WCS"): """ Pull the astrometric header for each image, compute an x/y transform and compare to trans.jmp this one overides trans.jmp if they are very different. @param expnums: @param ccd: @param version: @param prefix: @ret...
[ "def", "compute_trans", "(", "expnums", ",", "ccd", ",", "version", ",", "prefix", "=", "None", ",", "default", "=", "\"WCS\"", ")", ":", "wcs_dict", "=", "{", "}", "for", "expnum", "in", "expnums", ":", "try", ":", "# TODO This assumes that the image is alr...
46.454545
25.227273
def from_simplex(x): r""" Inteprets the last index of x as unit simplices and returns a real array of the sampe shape in logit space. Inverse to :func:`to_simplex` ; see that function for more details. :param np.ndarray: Array of unit simplices along the last index. :rtype: ``np.ndarray``...
[ "def", "from_simplex", "(", "x", ")", ":", "n", "=", "x", ".", "shape", "[", "-", "1", "]", "# z are the stick breaking fractions in [0,1]", "# the last one is always 1, so don't worry about it", "z", "=", "np", ".", "empty", "(", "shape", "=", "x", ".", "shape"...
34.478261
22.086957
def oneleft(self, window_name, object_name, iterations): """ Press scrollbar left with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to ...
[ "def", "oneleft", "(", "self", ",", "window_name", ",", "object_name", ",", "iterations", ")", ":", "if", "not", "self", ".", "verifyscrollbarhorizontal", "(", "window_name", ",", "object_name", ")", ":", "raise", "LdtpServerException", "(", "'Object not horizonta...
37.393939
18.363636
def resolved_path(path, base=None): """ Args: path (str | unicode | None): Path to resolve base (str | unicode | None): Base path to use to resolve relative paths (default: current working dir) Returns: (str): Absolute path """ if not path or path.startswith(SYMBOLIC_TMP): ...
[ "def", "resolved_path", "(", "path", ",", "base", "=", "None", ")", ":", "if", "not", "path", "or", "path", ".", "startswith", "(", "SYMBOLIC_TMP", ")", ":", "return", "path", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if",...
28.764706
19.705882
def drop_right_t(n): """ Transformation for Sequence.drop_right :param n: number to drop from right :return: transformation """ if n <= 0: end_index = None else: end_index = -n return Transformation( 'drop_right({0})'.format(n), lambda sequence: sequence[:...
[ "def", "drop_right_t", "(", "n", ")", ":", "if", "n", "<=", "0", ":", "end_index", "=", "None", "else", ":", "end_index", "=", "-", "n", "return", "Transformation", "(", "'drop_right({0})'", ".", "format", "(", "n", ")", ",", "lambda", "sequence", ":",...
22.4
14.266667
def init_read_line(self): """init_read_line() initializes fields relevant to input matching""" format_list = self._format_list self._re_cvt = self.match_input_fmt(format_list) regexp0_str = "".join([subs[0] for subs in self._re_cvt]) self._regexp_str = regexp0_str self._r...
[ "def", "init_read_line", "(", "self", ")", ":", "format_list", "=", "self", ".", "_format_list", "self", ".", "_re_cvt", "=", "self", ".", "match_input_fmt", "(", "format_list", ")", "regexp0_str", "=", "\"\"", ".", "join", "(", "[", "subs", "[", "0", "]...
44.4
16.533333
def _find_jar(self, path0=None): """ Return the location of an h2o.jar executable. :param path0: Explicitly given h2o.jar path. If provided, then we will simply check whether the file is there, otherwise we will search for an executable in locations returned by ._jar_paths(). ...
[ "def", "_find_jar", "(", "self", ",", "path0", "=", "None", ")", ":", "jar_paths", "=", "[", "path0", "]", "if", "path0", "else", "self", ".", "_jar_paths", "(", ")", "searched_paths", "=", "[", "]", "for", "jp", "in", "jar_paths", ":", "searched_paths...
45.588235
25.117647
def transaction_atomic_with_retry(num_retries=5, backoff=0.1): """ This is a decorator that will wrap the decorated method in an atomic transaction and retry the transaction a given number of times :param num_retries: How many times should we retry before we give up :param backoff: How long should ...
[ "def", "transaction_atomic_with_retry", "(", "num_retries", "=", "5", ",", "backoff", "=", "0.1", ")", ":", "# Create the decorator", "@", "wrapt", ".", "decorator", "def", "wrapper", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "# ...
33.121212
17.424242
def kms_encrypt(kms_client, service, env, secret): """ Encrypt string for use by a given service/environment Args: kms_client (boto3 kms client object): Instantiated kms client object. Usually created through create_aws_clients. service (string): name of the service that the secret is being encrypted for....
[ "def", "kms_encrypt", "(", "kms_client", ",", "service", ",", "env", ",", "secret", ")", ":", "# Converting all periods to underscores because they are invalid in KMS alias names", "key_alias", "=", "'{}-{}'", ".", "format", "(", "env", ",", "service", ".", "replace", ...
43.785714
26.285714
def list(region=None, key=None, keyid=None, profile=None): ''' List all trails Returns list of trails CLI Example: .. code-block:: yaml policies: - {...} - {...} ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) t...
[ "def", "list", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", ...
24.304348
23.869565
def groot(path=''): "Changes current directory to the root of the project (looks for README.md)." def check_filelist(l): if ('README.md' in l) or ('README' in l): return True else: return False import os, copy cwd = os.getcwd() # initial dir cwd0 = copy.cop...
[ "def", "groot", "(", "path", "=", "''", ")", ":", "def", "check_filelist", "(", "l", ")", ":", "if", "(", "'README.md'", "in", "l", ")", "or", "(", "'README'", "in", "l", ")", ":", "return", "True", "else", ":", "return", "False", "import", "os", ...
25.375
19.75
def declfuncs(self): """generator on all declaration of functions""" for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType) and not hasattr(f, 'body')): yield f
[ "def", "declfuncs", "(", "self", ")", ":", "for", "f", "in", "self", ".", "body", ":", "if", "(", "hasattr", "(", "f", ",", "'_ctype'", ")", "and", "isinstance", "(", "f", ".", "_ctype", ",", "FuncType", ")", "and", "not", "hasattr", "(", "f", ",...
34.142857
11.428571
def repetition(extractor, bounds, *, ignore_whitespace=False): """Returns a partial of _get_repetition that accepts only a text argument.""" return partial(_get_repetition, extractor, bounds=bounds, ignore_whitespace=ignore_whitespace)
[ "def", "repetition", "(", "extractor", ",", "bounds", ",", "*", ",", "ignore_whitespace", "=", "False", ")", ":", "return", "partial", "(", "_get_repetition", ",", "extractor", ",", "bounds", "=", "bounds", ",", "ignore_whitespace", "=", "ignore_whitespace", "...
79
26
def _parse(s, g): """Parses sentence 's' using CNF grammar 'g'.""" # The CYK table. Indexed with a 2-tuple: (start pos, end pos) table = defaultdict(set) # Top-level structure is similar to the CYK table. Each cell is a dict from # rule name to the best (lightest) tree for that rule. trees = def...
[ "def", "_parse", "(", "s", ",", "g", ")", ":", "# The CYK table. Indexed with a 2-tuple: (start pos, end pos)", "table", "=", "defaultdict", "(", "set", ")", "# Top-level structure is similar to the CYK table. Each cell is a dict from", "# rule name to the best (lightest) tree for th...
53.228571
20.828571
def pad_pdf_pages(pdf_name, pages_per_q) -> None: """ Checks if PDF has the correct number of pages. If it has too many, warns the user. If it has too few, adds blank pages until the right length is reached. """ pdf = PyPDF2.PdfFileReader(pdf_name) output = PyPDF2.PdfFileWriter() num_pag...
[ "def", "pad_pdf_pages", "(", "pdf_name", ",", "pages_per_q", ")", "->", "None", ":", "pdf", "=", "PyPDF2", ".", "PdfFileReader", "(", "pdf_name", ")", "output", "=", "PyPDF2", ".", "PdfFileWriter", "(", ")", "num_pages", "=", "pdf", ".", "getNumPages", "("...
34.615385
15.153846
def events(self, institute, case=None, variant_id=None, level=None, comments=False, panel=None): """Fetch events from the database. Args: institute (dict): A institute case (dict): A case variant_id (str, optional): global variant id leve...
[ "def", "events", "(", "self", ",", "institute", ",", "case", "=", "None", ",", "variant_id", "=", "None", ",", "level", "=", "None", ",", "comments", "=", "False", ",", "panel", "=", "None", ")", ":", "query", "=", "{", "}", "if", "variant_id", ":"...
37.822581
19.612903
def update_alias(FunctionName, Name, FunctionVersion=None, Description=None, region=None, key=None, keyid=None, profile=None): ''' Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. ...
[ "def", "update_alias", "(", "FunctionName", ",", "Name", ",", "FunctionVersion", "=", "None", ",", "Description", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try",...
34.78125
26.03125
def add_parameters(traj): """Adds all neuron group parameters to `traj`.""" assert(isinstance(traj,Trajectory)) scale = traj.simulation.scale traj.v_standard_parameter = Brian2Parameter model_eqs = '''dV/dt= 1.0/tau_POST * (mu - V) + I_syn : 1 mu : 1 ...
[ "def", "add_parameters", "(", "traj", ")", ":", "assert", "(", "isinstance", "(", "traj", ",", "Trajectory", ")", ")", "scale", "=", "traj", ".", "simulation", ".", "scale", "traj", ".", "v_standard_parameter", "=", "Brian2Parameter", "model_eqs", "=", "'''d...
51.297872
35.787234
def auth_required(*auth_methods): """ Decorator that protects enpoints through multiple mechanisms Example:: @app.route('/dashboard') @auth_required('token', 'session') def dashboard(): return 'Dashboard' :param auth_methods: Specified mechanisms. """ login_...
[ "def", "auth_required", "(", "*", "auth_methods", ")", ":", "login_mechanisms", "=", "{", "'token'", ":", "lambda", ":", "_check_token", "(", ")", ",", "'basic'", ":", "lambda", ":", "_check_http_auth", "(", ")", ",", "'session'", ":", "lambda", ":", "curr...
33.722222
15.555556
def connections(self): """ Returns all of the loaded connections names as a list """ conn = lambda x: str(x).replace('connection:', '') return [conn(name) for name in self.sections()]
[ "def", "connections", "(", "self", ")", ":", "conn", "=", "lambda", "x", ":", "str", "(", "x", ")", ".", "replace", "(", "'connection:'", ",", "''", ")", "return", "[", "conn", "(", "name", ")", "for", "name", "in", "self", ".", "sections", "(", ...
36.333333
12
def coding_sequence(rna): '''Extract coding sequence from an RNA template. :param seq: Sequence from which to extract a coding sequence. :type seq: coral.RNA :param material: Type of sequence ('dna' or 'rna') :type material: str :returns: The first coding sequence (start codon -> stop codon) ma...
[ "def", "coding_sequence", "(", "rna", ")", ":", "if", "isinstance", "(", "rna", ",", "coral", ".", "DNA", ")", ":", "rna", "=", "transcribe", "(", "rna", ")", "codons_left", "=", "len", "(", "rna", ")", "//", "3", "start_codon", "=", "coral", ".", ...
30.533333
18.488889
def _extractFastaHeader(fastaHeader, parser=None, forceId=False): """Parses a fasta header and returns extracted information in a dictionary. Unless a custom parser is specified, a ``Pyteomics`` function is used, which provides parsers for the formats of UniProtKB, UniRef, UniParc and UniMES (UniProt ...
[ "def", "_extractFastaHeader", "(", "fastaHeader", ",", "parser", "=", "None", ",", "forceId", "=", "False", ")", ":", "if", "parser", "is", "None", ":", "try", ":", "headerInfo", "=", "pyteomics", ".", "fasta", ".", "parse", "(", "fastaHeader", ")", "exc...
45.9
23.766667
def filter_savitzky_golay(y, window_size=5, order=2, deriv=0, rate=1): """Smooth (and optionally differentiate) with a Savitzky-Golay filter.""" try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except ValueError: raise ValueError('window_size and order mus...
[ "def", "filter_savitzky_golay", "(", "y", ",", "window_size", "=", "5", ",", "order", "=", "2", ",", "deriv", "=", "0", ",", "rate", "=", "1", ")", ":", "try", ":", "window_size", "=", "np", ".", "abs", "(", "np", ".", "int", "(", "window_size", ...
37.441176
20.764706
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: InstalledAddOnContext for this InstalledAddOnInstance :rtype: twilio.rest.preview.marketplace.ins...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "InstalledAddOnContext", "(", "self", ".", "_version", ",", "sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "re...
46.727273
26.909091
def get_sdb_keys(self, path): """Return the keys for a SDB, which are need for the full secure data path""" list_resp = get_with_retry( self.cerberus_url + '/v1/secret/' + path + '/?list=true', headers=self.HEADERS ) throw_if_bad_response(list_resp) retu...
[ "def", "get_sdb_keys", "(", "self", ",", "path", ")", ":", "list_resp", "=", "get_with_retry", "(", "self", ".", "cerberus_url", "+", "'/v1/secret/'", "+", "path", "+", "'/?list=true'", ",", "headers", "=", "self", ".", "HEADERS", ")", "throw_if_bad_response",...
34.6
17.1
def read_stats(self, *stats): """ Read stream statistics from chassis. :param stats: list of requested statistics to read, if empty - read all statistics. """ from ixexplorer.ixe_stream import IxePacketGroupStream sleep_time = 0.1 # in cases we only want few counters but very f...
[ "def", "read_stats", "(", "self", ",", "*", "stats", ")", ":", "from", "ixexplorer", ".", "ixe_stream", "import", "IxePacketGroupStream", "sleep_time", "=", "0.1", "# in cases we only want few counters but very fast we need a smaller sleep time", "if", "not", "stats", ":"...
55
25.763158
async def main(interface=None): """ Main function """ qtm_ip = await choose_qtm_instance(interface) if qtm_ip is None: return while True: connection = await qtm.connect(qtm_ip, 22223, version="1.18") if connection is None: return await connection.get_stat...
[ "async", "def", "main", "(", "interface", "=", "None", ")", ":", "qtm_ip", "=", "await", "choose_qtm_instance", "(", "interface", ")", "if", "qtm_ip", "is", "None", ":", "return", "while", "True", ":", "connection", "=", "await", "qtm", ".", "connect", "...
28.52439
22.463415
def set_credentials(self, username, password): """ Set a new username and password. :param str username: New username. :param str password: New password. """ if username is not None: self._username = username if password is not None: self...
[ "def", "set_credentials", "(", "self", ",", "username", ",", "password", ")", ":", "if", "username", "is", "not", "None", ":", "self", ".", "_username", "=", "username", "if", "password", "is", "not", "None", ":", "self", ".", "_password", "=", "password...
27.5
9.333333
def main(): """Event display for an event of station 503 Date Time Timestamp Nanoseconds 2012-03-29 10:51:36 1333018296 870008589 Number of MIPs 35.0 51.9 35.8 78.9 Arrival time 15.0 17.5 20.0 27.5 """ # Detector positions in ENU relative to the station GPS...
[ "def", "main", "(", ")", ":", "# Detector positions in ENU relative to the station GPS", "x", "=", "[", "-", "6.34", ",", "-", "2.23", ",", "-", "3.6", ",", "3.46", "]", "y", "=", "[", "6.34", ",", "2.23", ",", "-", "3.6", ",", "3.46", "]", "# Scale mi...
28.15
17.6875
def get_jid(jid): ''' Return the information returned from a specified jid ''' log.debug('sqlite3 returner <get_jid> called jid: %s', jid) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = :jid''' cur.execute(sql, {'...
[ "def", "get_jid", "(", "jid", ")", ":", "log", ".", "debug", "(", "'sqlite3 returner <get_jid> called jid: %s'", ",", "jid", ")", "conn", "=", "_get_conn", "(", "ret", "=", "None", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "'''SELECT ...
32.111111
20.222222
def get_strings(soup, tag): """Get all the string children from an html tag.""" tags = soup.find_all(tag) strings = [s.string for s in tags if s.string] return strings
[ "def", "get_strings", "(", "soup", ",", "tag", ")", ":", "tags", "=", "soup", ".", "find_all", "(", "tag", ")", "strings", "=", "[", "s", ".", "string", "for", "s", "in", "tags", "if", "s", ".", "string", "]", "return", "strings" ]
35.8
11.2
def get_stack_trace_with_labels(self, depth = 16, bMakePretty = True): """ Tries to get a stack trace for the current function. Only works for functions with standard prologue and epilogue. @type depth: int @param depth: Maximum depth of stack trace. @type bMakePretty...
[ "def", "get_stack_trace_with_labels", "(", "self", ",", "depth", "=", "16", ",", "bMakePretty", "=", "True", ")", ":", "try", ":", "trace", "=", "self", ".", "__get_stack_trace", "(", "depth", ",", "True", ",", "bMakePretty", ")", "except", "Exception", ":...
37.37931
22.551724
def service_define(self, service, ty): """ Add a service variable of type ``ty`` to this model :param str service: variable name :param type ty: variable type :return: None """ assert service not in self._data assert service not in self._algebs + self._s...
[ "def", "service_define", "(", "self", ",", "service", ",", "ty", ")", ":", "assert", "service", "not", "in", "self", ".", "_data", "assert", "service", "not", "in", "self", ".", "_algebs", "+", "self", ".", "_states", "self", ".", "_service", ".", "app...
27.642857
13.5
def strip_block_whitespace(string_list): """Treats a list of strings as a code block and strips whitespace so that the min whitespace line sits at char 0 of line.""" min_ws = min([(len(x) - len(x.lstrip())) for x in string_list if x != '\n']) return [x[min_ws:] if x != '\n' else x for x in string_li...
[ "def", "strip_block_whitespace", "(", "string_list", ")", ":", "min_ws", "=", "min", "(", "[", "(", "len", "(", "x", ")", "-", "len", "(", "x", ".", "lstrip", "(", ")", ")", ")", "for", "x", "in", "string_list", "if", "x", "!=", "'\\n'", "]", ")"...
63.8
12.8
def get_info(self): """ Return plugin information. """ plugin_infos = {} for pc in self.plugins: plugin_infos.update(pc.get_info()) return { self.get_plugin_name() : { "version" : self.get_version(), "sub-plugin...
[ "def", "get_info", "(", "self", ")", ":", "plugin_infos", "=", "{", "}", "for", "pc", "in", "self", ".", "plugins", ":", "plugin_infos", ".", "update", "(", "pc", ".", "get_info", "(", ")", ")", "return", "{", "self", ".", "get_plugin_name", "(", ")"...
27
15
def validate(cls, mapper_spec): """Validates mapper spec. Args: mapper_spec: The MapperSpec for this InputReader. Raises: BadReaderParamsError: required parameters are missing or invalid. """ if mapper_spec.input_reader_class() != cls: raise BadReaderParamsError("Input reader cla...
[ "def", "validate", "(", "cls", ",", "mapper_spec", ")", ":", "if", "mapper_spec", ".", "input_reader_class", "(", ")", "!=", "cls", ":", "raise", "BadReaderParamsError", "(", "\"Input reader class mismatch\"", ")", "params", "=", "_get_params", "(", "mapper_spec",...
34
18.526316
def set_response_handlers(self, stanza, res_handler, err_handler, timeout_handler = None, timeout = None): """Set response handler for an IQ "get" or "set" stanza. This should be called before the stanza is sent. :Parameters: - `stanza`: an IQ st...
[ "def", "set_response_handlers", "(", "self", ",", "stanza", ",", "res_handler", ",", "err_handler", ",", "timeout_handler", "=", "None", ",", "timeout", "=", "None", ")", ":", "# pylint: disable-msg=R0913", "self", ".", "lock", ".", "acquire", "(", ")", "try",...
54.5
26.09375
def parse_to_tree(text): """Parse text using CaboCha, then return Tree instance.""" xml_text = cabocha.as_xml(text) tree = Tree(xml_text) return tree
[ "def", "parse_to_tree", "(", "text", ")", ":", "xml_text", "=", "cabocha", ".", "as_xml", "(", "text", ")", "tree", "=", "Tree", "(", "xml_text", ")", "return", "tree" ]
32.2
12.2
def from_dict(cls, cls_dict, fallback_xsi_type=None): """Parse the dictionary and return an Entity instance. This will attempt to extract type information from the input dictionary and pass it to entity_class to resolve the correct class for the type. Args: cls_dict...
[ "def", "from_dict", "(", "cls", ",", "cls_dict", ",", "fallback_xsi_type", "=", "None", ")", ":", "if", "not", "cls_dict", ":", "return", "None", "if", "isinstance", "(", "cls_dict", ",", "six", ".", "string_types", ")", ":", "if", "not", "getattr", "(",...
33.035714
19.142857
def get_storage_account_keys(access_token, subscription_id, rgname, account_name): '''Get the access keys for the specified storage account. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group nam...
[ "def", "get_storage_account_keys", "(", "access_token", ",", "subscription_id", ",", "rgname", ",", "account_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/res...
43.473684
22
def looping_call(f, sleep=5, inc_sleep=0, max_sleep=60, timeout=600, exceptions=(), *args, **kwargs): """Helper function that to run looping call with fixed/dynamical interval. :param f: the looping call function or method. :param sleep: initial interval of the looping calls....
[ "def", "looping_call", "(", "f", ",", "sleep", "=", "5", ",", "inc_sleep", "=", "0", ",", "max_sleep", "=", "60", ",", "timeout", "=", "600", ",", "exceptions", "=", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "time_start", "="...
38.756757
20.027027
def are_you_sure(flag_changed, evt, parent=None, title="File has been changed", msg="Are you sure you want to exit?"): """ "Are you sure you want to exit" question dialog. If flag_changed, shows question dialog. If answer is not yes, calls evt.ignore() Arguments: flag_ch...
[ "def", "are_you_sure", "(", "flag_changed", ",", "evt", ",", "parent", "=", "None", ",", "title", "=", "\"File has been changed\"", ",", "msg", "=", "\"Are you sure you want to exit?\"", ")", ":", "if", "flag_changed", ":", "r", "=", "QMessageBox", ".", "questio...
36.619048
20.047619
def label(self, label, action='ADD', params=None): """ Adds a Security Label to a Indicator/Group or Victim Args: params: label: The name of the Security Label action: """ if params is None: params = {} if not label...
[ "def", "label", "(", "self", ",", "label", ",", "action", "=", "'ADD'", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "if", "not", "label", ":", "self", ".", "_tcex", ".", "handle_error", "(", "...
29.609756
22.268293
def _update_trsys(self, event): """Called when has changed. This allows the node and its children to react (notably, VisualNode uses this to update its TransformSystem). Note that this method is only called when one transform is replaced by another; it is not c...
[ "def", "_update_trsys", "(", "self", ",", "event", ")", ":", "for", "ch", "in", "self", ".", "children", ":", "ch", ".", "_update_trsys", "(", "event", ")", "self", ".", "events", ".", "transform_change", "(", ")", "self", ".", "update", "(", ")" ]
36.928571
17.714286
def get_port_monitor(self): """ Gets the port monitor configuration of a logical interconnect. Returns: dict: The Logical Interconnect. """ uri = "{}{}".format(self.data["uri"], self.PORT_MONITOR_PATH) return self._helper.do_get(uri)
[ "def", "get_port_monitor", "(", "self", ")", ":", "uri", "=", "\"{}{}\"", ".", "format", "(", "self", ".", "data", "[", "\"uri\"", "]", ",", "self", ".", "PORT_MONITOR_PATH", ")", "return", "self", ".", "_helper", ".", "do_get", "(", "uri", ")" ]
31.777778
15.555556
def plot_zt_mu(self, temp=600, output='eig', relaxation_time=1e-14, xlim=None): """ Plot the ZT in function of Fermi level. Args: temp: the temperature xlim: a list of min and max fermi energy by default (0, and band gap) ta...
[ "def", "plot_zt_mu", "(", "self", ",", "temp", "=", "600", ",", "output", "=", "'eig'", ",", "relaxation_time", "=", "1e-14", ",", "xlim", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "plt", ".", "figure", "(", "figsize", ...
34.470588
15.529412
def create_payload(self): """Wrap submitted data within an extra dict. For more information, see `Bugzilla #1151220 <https://bugzilla.redhat.com/show_bug.cgi?id=1151220>`_. In addition, rename the ``from_`` field to ``from``. """ payload = super(Subnet, self).create_pa...
[ "def", "create_payload", "(", "self", ")", ":", "payload", "=", "super", "(", "Subnet", ",", "self", ")", ".", "create_payload", "(", ")", "if", "'from_'", "in", "payload", ":", "payload", "[", "'from'", "]", "=", "payload", ".", "pop", "(", "'from_'",...
33.307692
17.692308
def get_message(self, id): """ Return a Message object for given id. :param id: The id of the message object to return. """ url = self._base_url + "/3/message/{0}".format(id) resp = self._send_request(url) return Message(resp, self)
[ "def", "get_message", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/message/{0}\"", ".", "format", "(", "id", ")", "resp", "=", "self", ".", "_send_request", "(", "url", ")", "return", "Message", "(", "resp", ",", ...
31.222222
11.444444
def _ChunkFactory(chunk_type, stream_rdr, offset): """ Return a |_Chunk| subclass instance appropriate to *chunk_type* parsed from *stream_rdr* at *offset*. """ chunk_cls_map = { PNG_CHUNK_TYPE.IHDR: _IHDRChunk, PNG_CHUNK_TYPE.pHYs: _pHYsChunk, } chunk_cls = chunk_cls_map.get...
[ "def", "_ChunkFactory", "(", "chunk_type", ",", "stream_rdr", ",", "offset", ")", ":", "chunk_cls_map", "=", "{", "PNG_CHUNK_TYPE", ".", "IHDR", ":", "_IHDRChunk", ",", "PNG_CHUNK_TYPE", ".", "pHYs", ":", "_pHYsChunk", ",", "}", "chunk_cls", "=", "chunk_cls_ma...
35.909091
12.818182
def _widen_states(old_state, new_state): """ Perform widen operation on the given states, and return a new one. :param old_state: :param new_state: :returns: The widened state, and whether widening has occurred """ # print old_state.dbg_print_stack() # p...
[ "def", "_widen_states", "(", "old_state", ",", "new_state", ")", ":", "# print old_state.dbg_print_stack()", "# print new_state.dbg_print_stack()", "l", ".", "debug", "(", "'Widening state at IP %s'", ",", "old_state", ".", "ip", ")", "widened_state", ",", "widening_occur...
29.4
20.6
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict """ dct = {} if self.data != self.defaultData: dct['data'] = self.data.toString() # calls QFont....
[ "def", "_nodeGetNonDefaultsDict", "(", "self", ")", ":", "dct", "=", "{", "}", "if", "self", ".", "data", "!=", "self", ".", "defaultData", ":", "dct", "[", "'data'", "]", "=", "self", ".", "data", ".", "toString", "(", ")", "# calls QFont.toString()", ...
42.75
13.875
def apply(ctx, name, verbose): """ Apply migration """ if name != 'all': # specific migration try: app_name, target_migration = name.split('/', 2) except ValueError: raise click.ClickException("NAME format is <app>/<migration> or 'all'") apps = ctx.obj[...
[ "def", "apply", "(", "ctx", ",", "name", ",", "verbose", ")", ":", "if", "name", "!=", "'all'", ":", "# specific migration", "try", ":", "app_name", ",", "target_migration", "=", "name", ".", "split", "(", "'/'", ",", "2", ")", "except", "ValueError", ...
37.75
25.725
def get_coord_idims(self, coords): """Get the slicers for the given coordinates from the base dataset This method converts `coords` to slicers (list of integers or ``slice`` objects) Parameters ---------- coords: dict A subset of the ``ds.coords`` attribute ...
[ "def", "get_coord_idims", "(", "self", ",", "coords", ")", ":", "ret", "=", "dict", "(", "(", "label", ",", "get_index_from_coord", "(", "coord", ",", "self", ".", "ds", ".", "indexes", "[", "label", "]", ")", ")", "for", "label", ",", "coord", "in",...
31.090909
20.954545
def to_dictionary(self): """Serialize an object into dictionary form. Useful if you have to serialize an array of objects into JSON. Otherwise, if you call the :meth:`to_json` method on each object in the list and then try to dump the array, you end up with an array with one string."""...
[ "def", "to_dictionary", "(", "self", ")", ":", "d", "=", "{", "'start'", ":", "self", ".", "start", ".", "isoformat", "(", ")", ",", "'end'", ":", "self", ".", "end", ".", "isoformat", "(", ")", ",", "'tz'", ":", "self", ".", "tz", ",", "'summary...
43.230769
16.692308
def bar( it, label="", width=32, hide=None, empty_char=BAR_EMPTY_CHAR, filled_char=BAR_FILLED_CHAR, expected_size=None, every=1, ): """Progress iterator. Wrap your iterables with it.""" count = len(it) if expected_size is None else expected_size with Bar( label=label,...
[ "def", "bar", "(", "it", ",", "label", "=", "\"\"", ",", "width", "=", "32", ",", "hide", "=", "None", ",", "empty_char", "=", "BAR_EMPTY_CHAR", ",", "filled_char", "=", "BAR_FILLED_CHAR", ",", "expected_size", "=", "None", ",", "every", "=", "1", ",",...
22.48
20.04
def _dispatch(self, event, listener, *args, **kwargs): """Dispatch an event to a listener. Args: event (str): The name of the event that triggered this call. listener (def or async def): The listener to trigger. *args: Any number of positional arguments. ...
[ "def", "_dispatch", "(", "self", ",", "event", ",", "listener", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "(", "asyncio", ".", "iscoroutinefunction", "(", "listener", ")", "or", "isinstance", "(", "listener", ",", "functools", ".", "pa...
41.434783
25.347826
def _decode(obj): # type: (bytes or str or unicode or object) -> unicode # noqa ignore=F821 """Decode an object to unicode. Args: obj (bytes or str or unicode or anything serializable): object to be decoded Returns: object decoded in unicode. """ if obj is None: return u'' ...
[ "def", "_decode", "(", "obj", ")", ":", "# type: (bytes or str or unicode or object) -> unicode # noqa ignore=F821", "if", "obj", "is", "None", ":", "return", "u''", "if", "six", ".", "PY3", "and", "isinstance", "(", "obj", ",", "six", ".", "binary_type", ")", "...
33.714286
15.904762
def StateOfCharge(self): """ % of Full Charge """ return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256)
[ "def", "StateOfCharge", "(", "self", ")", ":", "return", "(", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "0x02", ")", "+", "self", ".", "bus", ".", "read_byte_data", "(", "self", ".", "address", ",", "0x03", ")", "*"...
56
29.333333
def thumb(self, size=BIGTHUMB): '''Get a thumbnail as string or None if the file isnt an image size would be one of JFSFile.BIGTHUMB, .MEDIUMTHUMB, .SMALLTHUMB or .XLTHUMB''' if not self.is_image(): return None if not size in (self.BIGTHUMB, self.MEDIUMTHUMB, self.SMALLTHUMB...
[ "def", "thumb", "(", "self", ",", "size", "=", "BIGTHUMB", ")", ":", "if", "not", "self", ".", "is_image", "(", ")", ":", "return", "None", "if", "not", "size", "in", "(", "self", ".", "BIGTHUMB", ",", "self", ".", "MEDIUMTHUMB", ",", "self", ".", ...
54.090909
27.727273
def app_uninstall(self, package_name, keep_data=False): """ Uninstall package Args: - package_name(string): package name ex: com.example.demo - keep_data(bool): keep the data and cache directories """ if keep_data: return self.run_cmd('uninsta...
[ "def", "app_uninstall", "(", "self", ",", "package_name", ",", "keep_data", "=", "False", ")", ":", "if", "keep_data", ":", "return", "self", ".", "run_cmd", "(", "'uninstall'", ",", "'-k'", ",", "package_name", ")", "else", ":", "return", "self", ".", "...
33.833333
20
def parse_scoped_selector(scoped_selector): """Parse scoped selector.""" # Conver Macro (%scope/name) to (scope/name/macro.value) if scoped_selector[0] == '%': if scoped_selector.endswith('.value'): err_str = '{} is invalid cannot use % and end with .value' raise ValueError(err_str.format(scoped_s...
[ "def", "parse_scoped_selector", "(", "scoped_selector", ")", ":", "# Conver Macro (%scope/name) to (scope/name/macro.value)", "if", "scoped_selector", "[", "0", "]", "==", "'%'", ":", "if", "scoped_selector", ".", "endswith", "(", "'.value'", ")", ":", "err_str", "=",...
44.833333
10.5
def load_class(full_class_string): """ dynamically load a class from a string http://thomassileo.com/blog/2012/12/21/dynamically-load-python-modules-or-classes/ """ class_parts = full_class_string.split(".") module_path = ".".join(class_parts[:-1]) class_name = class_parts[-1] module =...
[ "def", "load_class", "(", "full_class_string", ")", ":", "class_parts", "=", "full_class_string", ".", "split", "(", "\".\"", ")", "module_path", "=", "\".\"", ".", "join", "(", "class_parts", "[", ":", "-", "1", "]", ")", "class_name", "=", "class_parts", ...
29.615385
15.615385
def train_model(extractor, data_dir, output_dir=None): """ Train an extractor model, then write train/test block-level classification performance as well as the model itself to disk in ``output_dir``. Args: extractor (:class:`Extractor`): Instance of the ``Extractor`` class to be tr...
[ "def", "train_model", "(", "extractor", ",", "data_dir", ",", "output_dir", "=", "None", ")", ":", "# set up directories and file naming", "output_dir", ",", "fname_prefix", "=", "_set_up_output_dir_and_fname_prefix", "(", "output_dir", ",", "extractor", ")", "# prepare...
43.208333
23.375
def add_bundled_jars(): """ Adds the bundled jars to the JVM's classpath. """ # determine lib directory with jars rootdir = os.path.split(os.path.dirname(__file__))[0] libdir = rootdir + os.sep + "lib" # add jars from lib directory for l in glob.glob(libdir + os.sep + "*.jar"): ...
[ "def", "add_bundled_jars", "(", ")", ":", "# determine lib directory with jars", "rootdir", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "[", "0", "]", "libdir", "=", "rootdir", "+", "os", ".", ...
32.083333
8.916667
def manipulateLattice(self, beamline, type='quad', irange='all', property='k1', opstr='+0%'): """ manipulate element with type, e.g. quad input parameters: :param beamline: beamline definition keyword :param type: element t...
[ "def", "manipulateLattice", "(", "self", ",", "beamline", ",", "type", "=", "'quad'", ",", "irange", "=", "'all'", ",", "property", "=", "'k1'", ",", "opstr", "=", "'+0%'", ")", ":", "# lattice_list = self.getFullBeamline(beamline, extend = True)", "# orderedLattice...
41.542857
19.542857
def get_params(self, token_stack): """Get params from stack of tokens""" params = {} for token in token_stack: params.update(token.params) return params
[ "def", "get_params", "(", "self", ",", "token_stack", ")", ":", "params", "=", "{", "}", "for", "token", "in", "token_stack", ":", "params", ".", "update", "(", "token", ".", "params", ")", "return", "params" ]
31.833333
9
def _render_log(): """Totally tap into Towncrier internals to get an in-memory result. """ config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, ...
[ "def", "_render_log", "(", ")", ":", "config", "=", "load_config", "(", "ROOT", ")", "definitions", "=", "config", "[", "'types'", "]", "fragments", ",", "fragment_filenames", "=", "find_fragments", "(", "pathlib", ".", "Path", "(", "config", "[", "'director...
30.789474
15.526316
def tracemessage(self, maxlen=6): """ if maxlen > 0, the message is shortened to maxlen traces. """ result = "" for i, value in enumerate(self): result += "{0}: {1}\n".format(i, get_node_repr(value)) result = result.strip("\n") lines = result.split("\...
[ "def", "tracemessage", "(", "self", ",", "maxlen", "=", "6", ")", ":", "result", "=", "\"\"", "for", "i", ",", "value", "in", "enumerate", "(", "self", ")", ":", "result", "+=", "\"{0}: {1}\\n\"", ".", "format", "(", "i", ",", "get_node_repr", "(", "...
29.941176
15.705882
def nrzi(data): ''' Packet uses NRZI (non-return to zero inverted) encoding, which means that a 0 is encoded as a change in tone, and a 1 is encoded as no change in tone. ''' current = True for bit in data: if not bit: current = not current yield current
[ "def", "nrzi", "(", "data", ")", ":", "current", "=", "True", "for", "bit", "in", "data", ":", "if", "not", "bit", ":", "current", "=", "not", "current", "yield", "current" ]
23.727273
26.090909
def add(self, v): """Add a new value.""" self._vals_added += 1 if self._mean is None: self._mean = v self._mean = self._mean + ((v - self._mean) / float(self._vals_added))
[ "def", "add", "(", "self", ",", "v", ")", ":", "self", ".", "_vals_added", "+=", "1", "if", "self", ".", "_mean", "is", "None", ":", "self", ".", "_mean", "=", "v", "self", ".", "_mean", "=", "self", ".", "_mean", "+", "(", "(", "v", "-", "se...
31.333333
17.666667
def h_L(self, L, theta, Ts, **statef): """ Calculate the average heat transfer coefficient. :param L: [m] characteristic length of the heat transfer surface :param theta: [°] angle of the surface with the vertical :param Ts: [K] heat transfer surface temperature :param T...
[ "def", "h_L", "(", "self", ",", "L", ",", "theta", ",", "Ts", ",", "*", "*", "statef", ")", ":", "Nu_L", "=", "self", ".", "Nu_L", "(", "L", ",", "theta", ",", "Ts", ",", "*", "*", "statef", ")", "k", "=", "self", ".", "_fluid", ".", "k", ...
33.066667
16.533333
def discount_rewards(r): """take 1D float array of rewards and compute discounted reward""" discounted_r = np.zeros_like(r) running_add = 0 for t in reversed(range(0, r.size)): # Reset the sum, since this was a game boundary (pong specific!). if r[t] != 0: running_add = 0 ...
[ "def", "discount_rewards", "(", "r", ")", ":", "discounted_r", "=", "np", ".", "zeros_like", "(", "r", ")", "running_add", "=", "0", "for", "t", "in", "reversed", "(", "range", "(", "0", ",", "r", ".", "size", ")", ")", ":", "# Reset the sum, since thi...
37.909091
12.272727
def do_unalias(self, arg): """unalias name Delete the specified alias. """ args = arg.split() if len(args) == 0: return if args[0] in self.aliases: del self.aliases[args[0]]
[ "def", "do_unalias", "(", "self", ",", "arg", ")", ":", "args", "=", "arg", ".", "split", "(", ")", "if", "len", "(", "args", ")", "==", "0", ":", "return", "if", "args", "[", "0", "]", "in", "self", ".", "aliases", ":", "del", "self", ".", "...
28.25
6
def if_has_delegate(delegate): """Wrap a delegated instance attribute function. Creates a decorator for methods that are delegated in the presence of a results wrapper. This enables duck-typing by ``hasattr`` returning True according to the sub-estimator. This function was adapted from scikit-lear...
[ "def", "if_has_delegate", "(", "delegate", ")", ":", "if", "isinstance", "(", "delegate", ",", "list", ")", ":", "delegate", "=", "tuple", "(", "delegate", ")", "if", "not", "isinstance", "(", "delegate", ",", "tuple", ")", ":", "delegate", "=", "(", "...
34.325
20.9
def default_ms(name, tabdesc=None, dminfo=None): """ Creates a default Measurement Set called name. Any Table Description elements in tabdesc will overwrite the corresponding element in a default Measurement Set Table Description (columns, hypercolumns and keywords). In practice, you probably want ...
[ "def", "default_ms", "(", "name", ",", "tabdesc", "=", "None", ",", "dminfo", "=", "None", ")", ":", "# Default to empty dictionaries", "if", "tabdesc", "is", "None", ":", "tabdesc", "=", "{", "}", "if", "dminfo", "is", "None", ":", "dminfo", "=", "{", ...
32.85
24.05