text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def set_value(self, field_name, value): """ sets an attribute value for a given field name """ if field_name in self.fields: if not value is None: self._dict['attributes'][field_name] = _unicode_convert(value) else: pass elif field_name.upp...
[ "def", "set_value", "(", "self", ",", "field_name", ",", "value", ")", ":", "if", "field_name", "in", "self", ".", "fields", ":", "if", "not", "value", "is", "None", ":", "self", ".", "_dict", "[", "'attributes'", "]", "[", "field_name", "]", "=", "_...
46.16
16.88
def n_tanks(Q_plant, sed_inputs=sed_dict): """Return the number of sedimentation tanks required for a given flow rate. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calcul...
[ "def", "n_tanks", "(", "Q_plant", ",", "sed_inputs", "=", "sed_dict", ")", ":", "q", "=", "q_tank", "(", "sed_inputs", ")", ".", "magnitude", "return", "(", "int", "(", "np", ".", "ceil", "(", "Q_plant", "/", "q", ")", ")", ")" ]
29.5
18.4
def generate_cloudformation_args(stack_name, parameters, tags, template, capabilities=DEFAULT_CAPABILITIES, change_set_type=None, service_role=None, stack_policy=None, ...
[ "def", "generate_cloudformation_args", "(", "stack_name", ",", "parameters", ",", "tags", ",", "template", ",", "capabilities", "=", "DEFAULT_CAPABILITIES", ",", "change_set_type", "=", "None", ",", "service_role", "=", "None", ",", "stack_policy", "=", "None", ",...
37.868852
22.180328
def _update_awareness(self): """Make sure all metabolites and genes that are associated with this reaction are aware of it. """ for x in self._metabolites: x._reaction.add(self) for x in self._genes: x._reaction.add(self)
[ "def", "_update_awareness", "(", "self", ")", ":", "for", "x", "in", "self", ".", "_metabolites", ":", "x", ".", "_reaction", ".", "add", "(", "self", ")", "for", "x", "in", "self", ".", "_genes", ":", "x", ".", "_reaction", ".", "add", "(", "self"...
30.888889
9.333333
def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS): """ If `text` is an SArray of strings or an SArray of lists of strings, the occurances of word are counted for each row in the SArray. If `text` is an SArray of dictionaries, the keys are tokenized and the values are the counts. C...
[ "def", "count_words", "(", "text", ",", "to_lower", "=", "True", ",", "delimiters", "=", "DEFAULT_DELIMITERS", ")", ":", "_raise_error_if_not_sarray", "(", "text", ",", "\"text\"", ")", "## Compute word counts", "sf", "=", "_turicreate", ".", "SFrame", "(", "{",...
35.457447
26.542553
def print_to_stdout(level, str_out): """ The default debug function """ if level == NOTICE: col = Fore.GREEN elif level == WARNING: col = Fore.RED else: col = Fore.YELLOW if not is_py3: str_out = str_out.encode(encoding, 'replace') print((col + str_out + Fore.RESE...
[ "def", "print_to_stdout", "(", "level", ",", "str_out", ")", ":", "if", "level", "==", "NOTICE", ":", "col", "=", "Fore", ".", "GREEN", "elif", "level", "==", "WARNING", ":", "col", "=", "Fore", ".", "RED", "else", ":", "col", "=", "Fore", ".", "YE...
28.454545
13.727273
def getDateFields(fc): """ Returns a list of fields that are of type DATE Input: fc - feature class or table path Output: List of date field names as strings """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") return [fie...
[ "def", "getDateFields", "(", "fc", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "return", "[", "field", ".", "name", "for", "field", "in", "arcpy", ".", "ListFields", "(", "fc",...
33.727273
15
def copy_previous_results(self): """Use the latest valid results_dir as the starting contents of the current results_dir. Should be called after the cache is checked, since previous_results are not useful if there is a cached artifact. """ # TODO(mateo): This should probably be managed by the task,...
[ "def", "copy_previous_results", "(", "self", ")", ":", "# TODO(mateo): This should probably be managed by the task, which manages the rest of the", "# incremental support.", "if", "not", "self", ".", "previous_cache_key", ":", "return", "None", "previous_path", "=", "self", "."...
48.894737
20.526316
def clean_queues(self): # pylint: disable=too-many-locals """Reduces internal list size to max allowed * checks and broks : 5 * length of hosts + services * actions : 5 * length of hosts + services + contacts :return: None """ # If we set the interval at 0, we b...
[ "def", "clean_queues", "(", "self", ")", ":", "# pylint: disable=too-many-locals", "# If we set the interval at 0, we bail out", "if", "getattr", "(", "self", ".", "pushed_conf", ",", "'tick_clean_queues'", ",", "0", ")", "==", "0", ":", "logger", ".", "debug", "(",...
50.847222
22.027778
def setColor(self, typeID, color): """setColor(string, (integer, integer, integer, integer)) -> None Sets the color of this type. """ self._connection._beginMessage( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_COLOR, typeID, 1 + 1 + 1 + 1 + 1) self._connection._string +=...
[ "def", "setColor", "(", "self", ",", "typeID", ",", "color", ")", ":", "self", ".", "_connection", ".", "_beginMessage", "(", "tc", ".", "CMD_SET_VEHICLETYPE_VARIABLE", ",", "tc", ".", "VAR_COLOR", ",", "typeID", ",", "1", "+", "1", "+", "1", "+", "1",...
45.9
16.3
def git_fetch(repo_dir, remote=None, refspec=None, verbose=False, tags=True): """Do a git fetch of `refspec` in `repo_dir`. If 'remote' is None, all remotes will be fetched. """ command = ['git', 'fetch'] if not remote: command.append('--all') else: remote = pipes.quote(remote) ...
[ "def", "git_fetch", "(", "repo_dir", ",", "remote", "=", "None", ",", "refspec", "=", "None", ",", "verbose", "=", "False", ",", "tags", "=", "True", ")", ":", "command", "=", "[", "'git'", ",", "'fetch'", "]", "if", "not", "remote", ":", "command", ...
29.6
16
def p_expr_pre_incdec(p): '''expr : INC variable | DEC variable''' p[0] = ast.PreIncDecOp(p[1], p[2], lineno=p.lineno(1))
[ "def", "p_expr_pre_incdec", "(", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "PreIncDecOp", "(", "p", "[", "1", "]", ",", "p", "[", "2", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")" ]
34.5
14.5
def parse_sentence(obj: dict) -> BioCSentence: """Deserialize a dict obj to a BioCSentence object""" sentence = BioCSentence() sentence.offset = obj['offset'] sentence.infons = obj['infons'] sentence.text = obj['text'] for annotation in obj['annotations']: sentence.add_annotation(...
[ "def", "parse_sentence", "(", "obj", ":", "dict", ")", "->", "BioCSentence", ":", "sentence", "=", "BioCSentence", "(", ")", "sentence", ".", "offset", "=", "obj", "[", "'offset'", "]", "sentence", ".", "infons", "=", "obj", "[", "'infons'", "]", "senten...
41.454545
8.727273
def set_jobs(self, jobs): """Set --jobs.""" if jobs == "sys": self.jobs = None else: try: jobs = int(jobs) except ValueError: jobs = -1 # will raise error below if jobs < 0: raise CoconutException("-...
[ "def", "set_jobs", "(", "self", ",", "jobs", ")", ":", "if", "jobs", "==", "\"sys\"", ":", "self", ".", "jobs", "=", "None", "else", ":", "try", ":", "jobs", "=", "int", "(", "jobs", ")", "except", "ValueError", ":", "jobs", "=", "-", "1", "# wil...
31.5
15.916667
def _normalize(number): """Normalizes a string of characters representing a phone number. This performs the following conversions: - Punctuation is stripped. - For ALPHA/VANITY numbers: - Letters are converted to their numeric representation on a telephone keypad. The keypad used he...
[ "def", "_normalize", "(", "number", ")", ":", "m", "=", "fullmatch", "(", "_VALID_ALPHA_PHONE_PATTERN", ",", "number", ")", "if", "m", ":", "return", "_normalize_helper", "(", "number", ",", "_ALPHA_PHONE_MAPPINGS", ",", "True", ")", "else", ":", "return", "...
39.769231
21.538462
def create_gre_tunnel_endpoint(cls, endpoint=None, tunnel_interface=None, remote_address=None): """ Create the GRE tunnel mode or no encryption mode endpoint. If the GRE tunnel mode endpoint is an SMC managed device, both an endpoint and a tunnel interf...
[ "def", "create_gre_tunnel_endpoint", "(", "cls", ",", "endpoint", "=", "None", ",", "tunnel_interface", "=", "None", ",", "remote_address", "=", "None", ")", ":", "tunnel_interface", "=", "tunnel_interface", ".", "href", "if", "tunnel_interface", "else", "None", ...
50.590909
18.681818
def count_peaks(ts): """ Toggle counter for gas boilers Counts the number of times the gas consumption increases with more than 3kW Parameters ---------- ts: Pandas Series Gas consumption in minute resolution Returns ------- int """ on_toggles = ts.diff() > 3000 ...
[ "def", "count_peaks", "(", "ts", ")", ":", "on_toggles", "=", "ts", ".", "diff", "(", ")", ">", "3000", "shifted", "=", "np", ".", "logical_not", "(", "on_toggles", ".", "shift", "(", "1", ")", ")", "result", "=", "on_toggles", "&", "shifted", "count...
20.190476
21.619048
def to_svg(self, instruction_or_id, i_promise_not_to_change_the_result=False): """Return the SVG for an instruction. :param instruction_or_id: either an :class:`~knittingpattern.Instruction.Instruction` or an id returned by :meth:`get_instruction_id` :param bo...
[ "def", "to_svg", "(", "self", ",", "instruction_or_id", ",", "i_promise_not_to_change_the_result", "=", "False", ")", ":", "return", "self", ".", "_new_svg_dumper", "(", "lambda", ":", "self", ".", "instruction_to_svg_dict", "(", "instruction_or_id", ",", "not", "...
44.5
20.944444
def _api_request(self, endpoint, http_method, *args, **kwargs): """Private method for api requests""" logger.debug(' > Sending API request to endpoint: %s' % endpoint) auth = self._build_http_auth() headers = self._build_request_headers(kwargs.get('headers')) logger.debug('\the...
[ "def", "_api_request", "(", "self", ",", "endpoint", ",", "http_method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "' > Sending API request to endpoint: %s'", "%", "endpoint", ")", "auth", "=", "self", ".", "_build_htt...
32.891304
18.695652
def _print_download_progress_msg(self, msg, flush=False): """Prints a message about download progress either to the console or TF log. Args: msg: Message to print. flush: Indicates whether to flush the output (only used in interactive mode). """ if self._interactive_mode(): ...
[ "def", "_print_download_progress_msg", "(", "self", ",", "msg", ",", "flush", "=", "False", ")", ":", "if", "self", ".", "_interactive_mode", "(", ")", ":", "# Print progress message to console overwriting previous progress", "# message.", "self", ".", "_max_prog_str", ...
35.35
21.2
def copy_resources(self): """Copies the relevant resources to a resources subdirectory""" if not os.path.isdir('resources'): os.mkdir('resources') resource_dir = os.path.join(os.getcwd(), 'resources', '') copied_resources = [] for resource in self.resources: ...
[ "def", "copy_resources", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "'resources'", ")", ":", "os", ".", "mkdir", "(", "'resources'", ")", "resource_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", ...
36.55
16.1
def difference(iterable, func=sub): """By default, compute the first difference of *iterable* using :func:`operator.sub`. >>> iterable = [0, 1, 3, 6, 10] >>> list(difference(iterable)) [0, 1, 2, 3, 4] This is the opposite of :func:`accumulate`'s default behavior: >>> from ...
[ "def", "difference", "(", "iterable", ",", "func", "=", "sub", ")", ":", "a", ",", "b", "=", "tee", "(", "iterable", ")", "try", ":", "item", "=", "next", "(", "b", ")", "except", "StopIteration", ":", "return", "iter", "(", "[", "]", ")", "retur...
30.277778
19
def search_by(lookup, tgt_type='compound', minion_id=None): ''' Search a dictionary of target strings for matching targets This is the inverse of :py:func:`match.filter_by <salt.modules.match.filter_by>` and allows matching values instead of matching keys. A minion can be matched by multiple entrie...
[ "def", "search_by", "(", "lookup", ",", "tgt_type", "=", "'compound'", ",", "minion_id", "=", "None", ")", ":", "expr_funcs", "=", "dict", "(", "inspect", ".", "getmembers", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "predicate", "=", "inspec...
29.475
23.225
def get_stp_mst_detail_output_msti_port_oper_bpdu_guard(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
[ "def", "get_stp_mst_detail_output_msti_port_oper_bpdu_guard", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_stp_mst_detail", "=", "ET", ".", "Element", "(", "\"get_stp_mst_detail\"", ")", "config"...
45
14.5625
def invalid_config_error_message(action, key, val): """Returns a better error message when invalid configuration option is provided.""" if action in ('store_true', 'store_false'): return ("{0} is not a valid value for {1} option, " "please specify a boolean value like yes/no, " ...
[ "def", "invalid_config_error_message", "(", "action", ",", "key", ",", "val", ")", ":", "if", "action", "in", "(", "'store_true'", ",", "'store_false'", ")", ":", "return", "(", "\"{0} is not a valid value for {1} option, \"", "\"please specify a boolean value like yes/no...
47.454545
13.818182
def send(self, transactions): """ Package up transactions into a batch and send them to the network via the provided batch_sender. :param transactions: list of transactions to package and broadcast. :return: None """ txn_signatures = [txn.header_signature for txn in trans...
[ "def", "send", "(", "self", ",", "transactions", ")", ":", "txn_signatures", "=", "[", "txn", ".", "header_signature", "for", "txn", "in", "transactions", "]", "header", "=", "BatchHeader", "(", "signer_public_key", "=", "self", ".", "_identity_signer", ".", ...
37.736842
15.526316
def wallet_destroy(self, wallet): """ Destroys **wallet** and all contained accounts .. enable_control required :param wallet: Wallet to destroy :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_destroy( ... wallet="000D1BAE...
[ "def", "wallet_destroy", "(", "self", ",", "wallet", ")", ":", "wallet", "=", "self", ".", "_process_value", "(", "wallet", ",", "'wallet'", ")", "payload", "=", "{", "\"wallet\"", ":", "wallet", "}", "resp", "=", "self", ".", "call", "(", "'wallet_destr...
23.625
21.958333
def write_table_to_file(self, dtype, custom_name=None, append=False, dir_path=None): """ Write out a MagIC table to file, using custom filename as specified in self.filenames. Parameters ---------- dtype : str magic table name """ if custom_na...
[ "def", "write_table_to_file", "(", "self", ",", "dtype", ",", "custom_name", "=", "None", ",", "append", "=", "False", ",", "dir_path", "=", "None", ")", ":", "if", "custom_name", ":", "fname", "=", "custom_name", "else", ":", "fname", "=", "self", ".", ...
36.136364
18.590909
def read_data_sets(data_dir): """ Parse or download movielens 1m data if train_dir is empty. :param data_dir: The directory storing the movielens data :return: a 2D numpy array with user index and item index in each row """ WHOLE_DATA = 'ml-1m.zip' local_file = base.maybe_download(WHOLE_D...
[ "def", "read_data_sets", "(", "data_dir", ")", ":", "WHOLE_DATA", "=", "'ml-1m.zip'", "local_file", "=", "base", ".", "maybe_download", "(", "WHOLE_DATA", ",", "data_dir", ",", "SOURCE_URL", "+", "WHOLE_DATA", ")", "zip_ref", "=", "zipfile", ".", "ZipFile", "(...
41.7
18.9
def _get_cache_name(function): """ returns a name for the module's cache db. """ module_name = _inspect.getfile(function) module_name = _os.path.abspath(module_name) cache_name = module_name # fix for '<string>' or '<stdin>' in exec or interpreter usage. cache_name = cache_name.replace(...
[ "def", "_get_cache_name", "(", "function", ")", ":", "module_name", "=", "_inspect", ".", "getfile", "(", "function", ")", "module_name", "=", "_os", ".", "path", ".", "abspath", "(", "module_name", ")", "cache_name", "=", "module_name", "# fix for '<string>' or...
32.555556
18.555556
def hook_wrapper_23(stdin, stdout, prompt): u'''Wrap a Python readline so it behaves like GNU readline.''' try: # call the Python hook res = ensure_str(readline_hook(prompt)) # make sure it returned the right sort of thing if res and not isinstance(res, str): r...
[ "def", "hook_wrapper_23", "(", "stdin", ",", "stdout", ",", "prompt", ")", ":", "try", ":", "# call the Python hook\r", "res", "=", "ensure_str", "(", "readline_hook", "(", "prompt", ")", ")", "# make sure it returned the right sort of thing\r", "if", "res", "and", ...
36.913043
16.652174
def parse(self): """Get new data, parses it and returns a device.""" # fetch data sess = requests.session() request = sess.get('https://{}/{}'.format(self.locale, self.product_id), allow_redirects=True, ...
[ "def", "parse", "(", "self", ")", ":", "# fetch data", "sess", "=", "requests", ".", "session", "(", ")", "request", "=", "sess", ".", "get", "(", "'https://{}/{}'", ".", "format", "(", "self", ".", "locale", ",", "self", ".", "product_id", ")", ",", ...
36.454545
20.181818
def BVC(self, params): """ BVC label Branch to the instruction at label if the V flag is not set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BVC label def BVC_func(): if not se...
[ "def", "BVC", "(", "self", ",", "params", ")", ":", "label", "=", "self", ".", "get_one_parameter", "(", "self", ".", "ONE_PARAMETER", ",", "params", ")", "self", ".", "check_arguments", "(", "label_exists", "=", "(", "label", ",", ")", ")", "# BVC label...
25.0625
21.3125
def get_available_voices(self, language=None, gender=None): """ Returns a list of available voices, via 'ListVoices' endpoint Docs: http://developer.ivona.com/en/speechcloud/actions.html#ListVoices :param language: returned voices language :type language: str ...
[ "def", "get_available_voices", "(", "self", ",", "language", "=", "None", ",", "gender", "=", "None", ")", ":", "endpoint", "=", "'ListVoices'", "data", "=", "dict", "(", ")", "if", "language", ":", "data", ".", "update", "(", "{", "'Voice'", ":", "{",...
27.192308
22.192308
def Henry_H_at_T(T, H, Tderiv, T0=None, units=None, backend=None): """ Evaluate Henry's constant H at temperature T Parameters ---------- T: float Temperature (with units), assumed to be in Kelvin if ``units == None`` H: float Henry's constant Tderiv: float (optional) dl...
[ "def", "Henry_H_at_T", "(", "T", ",", "H", ",", "Tderiv", ",", "T0", "=", "None", ",", "units", "=", "None", ",", "backend", "=", "None", ")", ":", "be", "=", "get_backend", "(", "backend", ")", "if", "units", "is", "None", ":", "K", "=", "1", ...
30.107143
21.142857
def htmlABF(ID,group,d,folder,overwrite=False): """given an ID and the dict of files, generate a static html for that abf.""" fname=folder+"/swhlab4/%s_index.html"%ID if overwrite is False and os.path.exists(fname): return html=TEMPLATES['abf'] html=html.replace("~ID~",ID) html=html.repl...
[ "def", "htmlABF", "(", "ID", ",", "group", ",", "d", ",", "folder", ",", "overwrite", "=", "False", ")", ":", "fname", "=", "folder", "+", "\"/swhlab4/%s_index.html\"", "%", "ID", "if", "overwrite", "is", "False", "and", "os", ".", "path", ".", "exists...
39.166667
13.75
def target(self, hosts): """Temporarily retarget the client for one call. This is useful when having to deal with a subset of hosts for one call. """ if self.__is_retargeted: raise TypeError('Cannot use target more than once.') rv = FanoutClient(hosts, connection_poo...
[ "def", "target", "(", "self", ",", "hosts", ")", ":", "if", "self", ".", "__is_retargeted", ":", "raise", "TypeError", "(", "'Cannot use target more than once.'", ")", "rv", "=", "FanoutClient", "(", "hosts", ",", "connection_pool", "=", "self", ".", "connecti...
44.181818
14.636364
def strace_set_buffer_size(self, size): """Sets the STRACE buffer size. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error. """ size = ctypes.c_uint32(size) res = self._dll.JLINK_STRACE_C...
[ "def", "strace_set_buffer_size", "(", "self", ",", "size", ")", ":", "size", "=", "ctypes", ".", "c_uint32", "(", "size", ")", "res", "=", "self", ".", "_dll", ".", "JLINK_STRACE_Control", "(", "enums", ".", "JLinkStraceCommand", ".", "SET_BUFFER_SIZE", ",",...
26.611111
22.722222
def spa_tmplt_precondition(length, delta_f, kmin=0): """Return the amplitude portion of the TaylorF2 approximant, used to precondition the strain data. The result is cached, and so should not be modified only read. """ global _prec if _prec is None or _prec.delta_f != delta_f or len(_prec) < length:...
[ "def", "spa_tmplt_precondition", "(", "length", ",", "delta_f", ",", "kmin", "=", "0", ")", ":", "global", "_prec", "if", "_prec", "is", "None", "or", "_prec", ".", "delta_f", "!=", "delta_f", "or", "len", "(", "_prec", ")", "<", "length", ":", "v", ...
52.2
16.6
def apply_update(self, doc, update_spec): """Override DocManagerBase.apply_update to have flat documents.""" # Replace a whole document if not '$set' in update_spec and not '$unset' in update_spec: # update_spec contains the new document. # Update the key in Solr based on...
[ "def", "apply_update", "(", "self", ",", "doc", ",", "update_spec", ")", ":", "# Replace a whole document", "if", "not", "'$set'", "in", "update_spec", "and", "not", "'$unset'", "in", "update_spec", ":", "# update_spec contains the new document.", "# Update the key in S...
44.5
13.1875
def add_attribute(self, name, value): """ Adds given attribute to the node. Usage:: >>> node_a = AbstractNode() >>> node_a.add_attribute("attributeA", Attribute()) True >>> node_a.list_attributes() [u'attributeA'] :param name...
[ "def", "add_attribute", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "issubclass", "(", "value", ".", "__class__", ",", "Attribute", ")", ":", "raise", "foundations", ".", "exceptions", ".", "NodeAttributeTypeError", "(", "\"Node attribute va...
31.413793
20.931034
def entrypoint(func): """ A decorator for your main() function. Really a combination of @autorun and @acceptargv, so will run the function if __name__ == '__main__' with arguments extricated from argparse. As with @acceptargv, this must either be the innermost decorator, or...
[ "def", "entrypoint", "(", "func", ")", ":", "frame_local", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_locals", "if", "'__name__'", "in", "frame_local", "and", "frame_local", "[", "'__name__'", "]", "==", "'__main__'", ":", "argv", "=", "sys", "...
31.960784
19.72549
def add_colons(s): """Add colons after every second digit. This function is used in functions to prettify serials. >>> add_colons('teststring') 'te:st:st:ri:ng' """ return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)])
[ "def", "add_colons", "(", "s", ")", ":", "return", "':'", ".", "join", "(", "[", "s", "[", "i", ":", "i", "+", "2", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "s", ")", ",", "2", ")", "]", ")" ]
26.777778
19
def correct_scanpy(adatas, **kwargs): """Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of paramet...
[ "def", "correct_scanpy", "(", "adatas", ",", "*", "*", "kwargs", ")", ":", "if", "'return_dimred'", "in", "kwargs", "and", "kwargs", "[", "'return_dimred'", "]", ":", "datasets_dimred", ",", "datasets", ",", "genes", "=", "correct", "(", "[", "adata", ".",...
32.155556
20.577778
def layers(self): """ similar as parent images, except that it uses /history API endpoint :return: """ # sample output: # { # "Created": 1457116802, # "Id": "sha256:507cb13a216097710f0d234668bf64a4c92949c573ba15eba13d05aad392fe04", # "S...
[ "def", "layers", "(", "self", ")", ":", "# sample output:", "# {", "# \"Created\": 1457116802,", "# \"Id\": \"sha256:507cb13a216097710f0d234668bf64a4c92949c573ba15eba13d05aad392fe04\",", "# \"Size\": 204692029,", "# \"Tags\": [", "# \"docker.io/fedora:latest\"", "# ...
32.896552
18.689655
def compile_dependencies(self, sourcepath, include_self=True): """ Same as inherit method but the default value for keyword argument ``ìnclude_self`` is ``True``. """ return super(SassProjectEventHandler, self).compile_dependencies( sourcepath, include_sel...
[ "def", "compile_dependencies", "(", "self", ",", "sourcepath", ",", "include_self", "=", "True", ")", ":", "return", "super", "(", "SassProjectEventHandler", ",", "self", ")", ".", "compile_dependencies", "(", "sourcepath", ",", "include_self", "=", "include_self"...
37.333333
15.777778
def store_shot(self): """Store current cregs to shots_result""" def to_str(cregs): return ''.join(str(b) for b in cregs) key = to_str(self.cregs) self.shots_result[key] = self.shots_result.get(key, 0) + 1
[ "def", "store_shot", "(", "self", ")", ":", "def", "to_str", "(", "cregs", ")", ":", "return", "''", ".", "join", "(", "str", "(", "b", ")", "for", "b", "in", "cregs", ")", "key", "=", "to_str", "(", "self", ".", "cregs", ")", "self", ".", "sho...
40.5
12.666667
def job_factory(self): """ Create concrete jobs. The concrete jobs is following dictionary. jobs = { 'PLUGINNAME-build_items': { 'method': FUNCTION_OBJECT, 'interval': INTERVAL_TIME , } ... } If ConcreteJob insta...
[ "def", "job_factory", "(", "self", ")", ":", "jobs", "=", "dict", "(", ")", "for", "section", ",", "options", "in", "self", ".", "config", ".", "items", "(", ")", ":", "if", "section", "==", "'global'", ":", "continue", "# Since validate in utils/configrea...
35.209524
17.838095
def multipart_content(*files): """Returns a mutlipart content. Note: This script was clearly inspired by write-mime-multipart. """ outer = MIMEMultipart() for fname in files: mtype = get_type(fname) maintype, subtype = mtype.split('/', 1) with open(fname) as f: ...
[ "def", "multipart_content", "(", "*", "files", ")", ":", "outer", "=", "MIMEMultipart", "(", ")", "for", "fname", "in", "files", ":", "mtype", "=", "get_type", "(", "fname", ")", "maintype", ",", "subtype", "=", "mtype", ".", "split", "(", "'/'", ",", ...
35
13.133333
def on_menu(self, event): '''called on menu event''' state = self.state if self.popup_menu is not None: ret = self.popup_menu.find_selected(event) if ret is not None: ret.popup_pos = self.popup_pos if ret.returnkey == 'fitWindow': ...
[ "def", "on_menu", "(", "self", ",", "event", ")", ":", "state", "=", "self", ".", "state", "if", "self", ".", "popup_menu", "is", "not", "None", ":", "ret", "=", "self", ".", "popup_menu", ".", "find_selected", "(", "event", ")", "if", "ret", "is", ...
36.263158
8.894737
def seek(self, relative_position): """ Seek the video by `relative_position` seconds Args: relative_position (float): The position in seconds to seek to. """ self._player_interface.Seek(Int64(1000.0 * 1000 * relative_position)) self.seekEvent(self, relative_p...
[ "def", "seek", "(", "self", ",", "relative_position", ")", ":", "self", ".", "_player_interface", ".", "Seek", "(", "Int64", "(", "1000.0", "*", "1000", "*", "relative_position", ")", ")", "self", ".", "seekEvent", "(", "self", ",", "relative_position", ")...
35.555556
18.222222
def posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None): """ Returns an estimate of the marginal distribution of a given model parameter, based on taking the derivative of the interpolated cdf. :param int idx_param: Index of parameter to be margin...
[ "def", "posterior_marginal", "(", "self", ",", "idx_param", "=", "0", ",", "res", "=", "100", ",", "smoothing", "=", "0", ",", "range_min", "=", "None", ",", "range_max", "=", "None", ")", ":", "# We need to sort the particles to get cumsum to make sense.", "# i...
39.888889
24.155556
def getStringForBytes(self, s): """ Returns the corresponding string for the supplied utf-8 encoded bytes. If there is no string object, one is created. @since: 0.6 """ h = hash(s) u = self._unicodes.get(h, None) if u is not None: return u ...
[ "def", "getStringForBytes", "(", "self", ",", "s", ")", ":", "h", "=", "hash", "(", "s", ")", "u", "=", "self", ".", "_unicodes", ".", "get", "(", "h", ",", "None", ")", "if", "u", "is", "not", "None", ":", "return", "u", "u", "=", "self", "....
23.1875
20.6875
def extract_subset(self, subset, contract=True): """ Return all nodes in a subset. We assume the oboInOwl encoding of subsets, and subset IDs are IRIs, or IR fragments """ return [n for n in self.nodes() if subset in self.subsets(n, contract=contract)]
[ "def", "extract_subset", "(", "self", ",", "subset", ",", "contract", "=", "True", ")", ":", "return", "[", "n", "for", "n", "in", "self", ".", "nodes", "(", ")", "if", "subset", "in", "self", ".", "subsets", "(", "n", ",", "contract", "=", "contra...
41
21.571429
def check_errors(self, uri, response): ''' Check HTTP reponse for known errors ''' if response.status == 401: raise trolly.Unauthorised(uri, response) if response.status != 200: raise trolly.ResourceUnavailable(uri, response)
[ "def", "check_errors", "(", "self", ",", "uri", ",", "response", ")", ":", "if", "response", ".", "status", "==", "401", ":", "raise", "trolly", ".", "Unauthorised", "(", "uri", ",", "response", ")", "if", "response", ".", "status", "!=", "200", ":", ...
31.333333
16.222222
def collect_request_parameters(self, request): """Collect parameters in an object for convenient access""" class OAuthParameters(object): """Used as a parameter container since plain object()s can't""" pass # Collect parameters query = urlparse(request.url.decod...
[ "def", "collect_request_parameters", "(", "self", ",", "request", ")", ":", "class", "OAuthParameters", "(", "object", ")", ":", "\"\"\"Used as a parameter container since plain object()s can't\"\"\"", "pass", "# Collect parameters", "query", "=", "urlparse", "(", "request"...
46.413793
20.344828
def set_stderrthreshold(s): """Sets the stderr threshold to the value passed in. Args: s: str|int, valid strings values are case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'; valid integer values are logging.DEBUG|INFO|WARNING|ERROR|FATAL. Raises: ValueError: Raised whe...
[ "def", "set_stderrthreshold", "(", "s", ")", ":", "if", "s", "in", "converter", ".", "ABSL_LEVELS", ":", "FLAGS", ".", "stderrthreshold", "=", "converter", ".", "ABSL_LEVELS", "[", "s", "]", "elif", "isinstance", "(", "s", ",", "str", ")", "and", "s", ...
37.285714
20
def get_scope_by_name(self, scope_name): """GetScopeByName. [Preview API] :param str scope_name: :rtype: :class:`<IdentityScope> <azure.devops.v5_0.identity.models.IdentityScope>` """ query_parameters = {} if scope_name is not None: query_parameters['s...
[ "def", "get_scope_by_name", "(", "self", ",", "scope_name", ")", ":", "query_parameters", "=", "{", "}", "if", "scope_name", "is", "not", "None", ":", "query_parameters", "[", "'scopeName'", "]", "=", "self", ".", "_serialize", ".", "query", "(", "'scope_nam...
48.928571
18.571429
def to_native(self, obj, name, value): # pylint:disable=unused-argument """Transform the MongoDB value into a Marrow Mongo value.""" if self.mapping: for original, new in self.mapping.items(): value = value.replace(original, new) return load(value, self.namespace)
[ "def", "to_native", "(", "self", ",", "obj", ",", "name", ",", "value", ")", ":", "# pylint:disable=unused-argument", "if", "self", ".", "mapping", ":", "for", "original", ",", "new", "in", "self", ".", "mapping", ".", "items", "(", ")", ":", "value", ...
34.625
17.375
def request_ocsp(self): """ Called to request that the server sends stapled OCSP data, if available. If this is not called on the client side then the server will not send OCSP data. Should be used in conjunction with :meth:`Context.set_ocsp_client_callback`. """ ...
[ "def", "request_ocsp", "(", "self", ")", ":", "rc", "=", "_lib", ".", "SSL_set_tlsext_status_type", "(", "self", ".", "_ssl", ",", "_lib", ".", "TLSEXT_STATUSTYPE_ocsp", ")", "_openssl_assert", "(", "rc", "==", "1", ")" ]
40.090909
15.545455
def get_object(self, request, object_id, *args, **kwargs): """ Make sure the object is fetched in the correct language. """ obj = super(TranslatableAdmin, self).get_object(request, object_id, *args, **kwargs) if obj is not None and self._has_translatable_model(): # Allow fallba...
[ "def", "get_object", "(", "self", ",", "request", ",", "object_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "super", "(", "TranslatableAdmin", ",", "self", ")", ".", "get_object", "(", "request", ",", "object_id", ",", "*", "...
43.6
29.8
def createEditor(self, parent, column, operator, value): """ Creates a new editor for the system. """ editor = super(EnumPlugin, self).createEditor(parent, column, operator, ...
[ "def", "createEditor", "(", "self", ",", "parent", ",", "column", ",", "operator", ",", "value", ")", ":", "editor", "=", "super", "(", "EnumPlugin", ",", "self", ")", ".", "createEditor", "(", "parent", ",", "column", ",", "operator", ",", "value", ")...
39
14.333333
def receive(self): """Receive TCP response, looping to get whole thing or timeout.""" try: buffer = self._socket.recv(BUFFER_SIZE) except socket.timeout as error: # Something is wrong, assume it's offline temporarily _LOGGER.error("Error receiving: %s", error)...
[ "def", "receive", "(", "self", ")", ":", "try", ":", "buffer", "=", "self", ".", "_socket", ".", "recv", "(", "BUFFER_SIZE", ")", "except", "socket", ".", "timeout", "as", "error", ":", "# Something is wrong, assume it's offline temporarily", "_LOGGER", ".", "...
34.928571
14.071429
def mouseDrag(self, x, y, step=1): """ Move the mouse point to position (x, y) in increments of step """ log.debug('mouseDrag %d,%d', x, y) if x < self.x: xsteps = [self.x - i for i in range(step, self.x - x + 1, step)] else: xsteps = range(self.x, x, step...
[ "def", "mouseDrag", "(", "self", ",", "x", ",", "y", ",", "step", "=", "1", ")", ":", "log", ".", "debug", "(", "'mouseDrag %d,%d'", ",", "x", ",", "y", ")", "if", "x", "<", "self", ".", "x", ":", "xsteps", "=", "[", "self", ".", "x", "-", ...
28.04
18.52
def grading_status_text(self): ''' A rendering of the grading that is an answer on the question "Is grading finished?". Used in duplicate view and submission list on the teacher backend. ''' if self.assignment.is_graded(): if self.is_grading_finished(): ...
[ "def", "grading_status_text", "(", "self", ")", ":", "if", "self", ".", "assignment", ".", "is_graded", "(", ")", ":", "if", "self", ".", "is_grading_finished", "(", ")", ":", "return", "str", "(", "'Yes ({0})'", ".", "format", "(", "self", ".", "grading...
35.692308
17.230769
def _log_in(self): '''Connect and login. Coroutine. ''' username = self._request.url_info.username or self._request.username or 'anonymous' password = self._request.url_info.password or self._request.password or '-wpull@' cached_login = self._login_table.get(self._contr...
[ "def", "_log_in", "(", "self", ")", ":", "username", "=", "self", ".", "_request", ".", "url_info", ".", "username", "or", "self", ".", "_request", ".", "username", "or", "'anonymous'", "password", "=", "self", ".", "_request", ".", "url_info", ".", "pas...
35.619048
28.857143
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the CreateKeyPair response payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supportin...
[ "def", "read", "(", "self", ",", "input_buffer", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "CreateKeyPairResponsePayload", ",", "self", ")", ".", "read", "(", "input_buffer", ",", "kmip_version", "=", "km...
37.388235
20.047059
def create_dialog_node(self, workspace_id, dialog_node, description=None, conditions=None, parent=None, previous_sibling=None, outp...
[ "def", "create_dialog_node", "(", "self", ",", "workspace_id", ",", "dialog_node", ",", "description", "=", "None", ",", "conditions", "=", "None", ",", "parent", "=", "None", ",", "previous_sibling", "=", "None", ",", "output", "=", "None", ",", "context", ...
45.238095
19.126984
def to_element(self): """Return an ElementTree Element based on this resource. Returns: ~xml.etree.ElementTree.Element: an Element. """ if not self.protocol_info: raise DIDLMetadataError('Could not create Element for this' 'res...
[ "def", "to_element", "(", "self", ")", ":", "if", "not", "self", ".", "protocol_info", ":", "raise", "DIDLMetadataError", "(", "'Could not create Element for this'", "'resource:'", "'protocolInfo not set (required).'", ")", "root", "=", "XML", ".", "Element", "(", "...
40.763158
15.105263
def _logging_env_conf_overrides(log_init_warnings=None): """Returns a dictionary that is empty or has a "logging" key that refers to the (up to 3) key-value pairs that pertain to logging and are read from the env. This is mainly a convenience function for ConfigWrapper so that it can accurately repo...
[ "def", "_logging_env_conf_overrides", "(", "log_init_warnings", "=", "None", ")", ":", "# This is called from a locked section of _read_logging_config, so don't call that function or you'll get deadlock", "global", "_LOGGING_ENV_CONF_OVERRIDES", "if", "_LOGGING_ENV_CONF_OVERRIDES", "is", ...
56.578947
22.263158
def transform_qubits(self: TSelf_Operation, func: Callable[[Qid], Qid]) -> TSelf_Operation: """Returns the same operation, but with different qubits. Args: func: The function to use to turn each current qubit into a desired new qubit. Return...
[ "def", "transform_qubits", "(", "self", ":", "TSelf_Operation", ",", "func", ":", "Callable", "[", "[", "Qid", "]", ",", "Qid", "]", ")", "->", "TSelf_Operation", ":", "return", "self", ".", "with_qubits", "(", "*", "(", "func", "(", "q", ")", "for", ...
37.692308
22.615385
def get_golden_topics(self, lang): """Return the topics mastered ("golden") by a user in a language.""" return [topic['title'] for topic in self.user_data.language_data[lang]['skills'] if topic['learned'] and topic['strength'] == 1.0]
[ "def", "get_golden_topics", "(", "self", ",", "lang", ")", ":", "return", "[", "topic", "[", "'title'", "]", "for", "topic", "in", "self", ".", "user_data", ".", "language_data", "[", "lang", "]", "[", "'skills'", "]", "if", "topic", "[", "'learned'", ...
55.6
14.8
def find_by_dynamic_locator(self, template_locator, variables, find_all=False, search_object=None): ''' Find with dynamic locator @type template_locator: webdriverwrapper.support.locator.Locator @param template_locator: Template locator w/ formatting bits to insert ...
[ "def", "find_by_dynamic_locator", "(", "self", ",", "template_locator", ",", "variables", ",", "find_all", "=", "False", ",", "search_object", "=", "None", ")", ":", "template_variable_character", "=", "'%'", "# raise an exception if user passed non-dictionary variables", ...
55.344828
32.517241
def get_xy(self, xy, addr=True): """Get the agent with xy-coordinate in the grid. If *addr* is True, returns only the agent's address. If no such agent in the grid, returns None. :raises: :exc:`ValueError` if xy-coordinate is outside the environment's grid. ...
[ "def", "get_xy", "(", "self", ",", "xy", ",", "addr", "=", "True", ")", ":", "x", "=", "xy", "[", "0", "]", "y", "=", "xy", "[", "1", "]", "if", "x", "<", "self", ".", "origin", "[", "0", "]", "or", "x", ">=", "self", ".", "origin", "[", ...
35.227273
20.045455
def register_as_type(self, locator, object_factory): """ Registers a component using its type (a constructor function). :param locator: a locator to identify component to be created. :param object_factory: a component type. """ if locator == None: raise Exce...
[ "def", "register_as_type", "(", "self", ",", "locator", ",", "object_factory", ")", ":", "if", "locator", "==", "None", ":", "raise", "Exception", "(", "\"Locator cannot be null\"", ")", "if", "object_factory", "==", "None", ":", "raise", "Exception", "(", "\"...
32.882353
19.235294
def validate_units(self): """Ensure that wavelenth unit belongs to the correct class. There is no check for throughput because it is unitless. Raises ------ TypeError Wavelength unit is not `~pysynphot.units.WaveUnits`. """ if (not isinstance(self.wa...
[ "def", "validate_units", "(", "self", ")", ":", "if", "(", "not", "isinstance", "(", "self", ".", "waveunits", ",", "units", ".", "WaveUnits", ")", ")", ":", "raise", "TypeError", "(", "\"%s is not a valid WaveUnit\"", "%", "self", ".", "waveunits", ")" ]
34.25
22.75
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_arguments) < 2: return self.print_help() text_format = gf.safe_unicode(self.actual_arguments[0]) if text_format == u"list": ...
[ "def", "perform_command", "(", "self", ")", ":", "if", "len", "(", "self", ".", "actual_arguments", ")", "<", "2", ":", "return", "self", ".", "print_help", "(", ")", "text_format", "=", "gf", ".", "safe_unicode", "(", "self", ".", "actual_arguments", "[...
49.946429
22.446429
def get_first_record( cls, download: bool=True ) -> NistBeaconValue: """ Get the first (oldest) record available. Since the first record IS a known value in the system we can load it from constants. :param download: 'True' will always reach out to NIST to get...
[ "def", "get_first_record", "(", "cls", ",", "download", ":", "bool", "=", "True", ")", "->", "NistBeaconValue", ":", "if", "download", ":", "return", "NistBeacon", ".", "get_record", "(", "cls", ".", "_INIT_RECORD", ".", "timestamp", ")", "else", ":", "ret...
36.529412
22.764706
def _get(self, scheme, host, port, path, assert_key=None): """ Execute a ES API call. Convert response into JSON and optionally assert its structure. """ url = '%s://%s:%i/%s' % (scheme, host, port, path) try: request = urllib2.Request(url) if self...
[ "def", "_get", "(", "self", ",", "scheme", ",", "host", ",", "port", ",", "path", ",", "assert_key", "=", "None", ")", ":", "url", "=", "'%s://%s:%i/%s'", "%", "(", "scheme", ",", "host", ",", "port", ",", "path", ")", "try", ":", "request", "=", ...
41.068966
18.103448
def selectitem(self, window_name, object_name, item_name): """ Select combo box / layered pane item @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", "selectitem", "(", "self", ",", "window_name", ",", "object_name", ",", "item_name", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", ":", "ra...
43.132075
16.716981
def __fetch_1_27(self, from_date=None): """Fetch the pages from the backend url for MediaWiki >=1.27 The method retrieves, from a MediaWiki url, the wiki pages. :returns: a generator of pages """ logger.info("Looking for pages at url '%s'", self.url) npages = ...
[ "def", "__fetch_1_27", "(", "self", ",", "from_date", "=", "None", ")", ":", "logger", ".", "info", "(", "\"Looking for pages at url '%s'\"", ",", "self", ".", "url", ")", "npages", "=", "0", "# number of pages processed", "tpages", "=", "0", "# number of total ...
38.880952
24.190476
def update(self, activity_sid=values.unset, attributes=values.unset, friendly_name=values.unset, reject_pending_reservations=values.unset): """ Update the WorkerInstance :param unicode activity_sid: The activity_sid :param unicode attributes: The attributes...
[ "def", "update", "(", "self", ",", "activity_sid", "=", "values", ".", "unset", ",", "attributes", "=", "values", ".", "unset", ",", "friendly_name", "=", "values", ".", "unset", ",", "reject_pending_reservations", "=", "values", ".", "unset", ")", ":", "r...
39.75
15.85
def tag(self, resource_id): """Update the request URI to include the Tag for specific retrieval. Args: resource_id (string): The tag name. """ self._request_uri = '{}/{}'.format(self._request_uri, self.tcex.safetag(resource_id))
[ "def", "tag", "(", "self", ",", "resource_id", ")", ":", "self", ".", "_request_uri", "=", "'{}/{}'", ".", "format", "(", "self", ".", "_request_uri", ",", "self", ".", "tcex", ".", "safetag", "(", "resource_id", ")", ")" ]
38.142857
20
def build_docs(location="doc-source", target=None, library="icetea_lib"): """ Build documentation for Icetea. Start by autogenerating module documentation and finish by building html. :param location: Documentation source :param target: Documentation target path :param library: Library location...
[ "def", "build_docs", "(", "location", "=", "\"doc-source\"", ",", "target", "=", "None", ",", "library", "=", "\"icetea_lib\"", ")", ":", "cmd_ar", "=", "[", "\"sphinx-apidoc\"", ",", "\"-o\"", ",", "location", ",", "library", "]", "try", ":", "print", "("...
38.473684
19.368421
def checkpoint(global_model, local_model=None): """Checkpoint the model. This means we finished a stage of execution. Every time we call check point, there is a version number which will increase by one. Parameters ---------- global_model: anytype that can be pickled globally shared mo...
[ "def", "checkpoint", "(", "global_model", ",", "local_model", "=", "None", ")", ":", "sglobal", "=", "pickle", ".", "dumps", "(", "global_model", ")", "if", "local_model", "is", "None", ":", "_LIB", ".", "RabitCheckPoint", "(", "sglobal", ",", "len", "(", ...
36.40625
21.6875
def run_cutadapt(job, fastqs, univ_options, cutadapt_options): """ This module runs cutadapt on the input RNA fastq files and then calls the RNA aligners. ARGUMENTS 1. fastqs: Dict of list of input RNA-Seq fastqs fastqs +- 'tumor_rna': [<JSid for 1.fastq> , <JSid for 2.fastq>] ...
[ "def", "run_cutadapt", "(", "job", ",", "fastqs", ",", "univ_options", ",", "cutadapt_options", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Running cutadapt on %s'", "%", "univ_options", "[", "'patient'", "]", ")", "work_dir", "=", "job", "."...
48.488372
21.837209
def write(self, text: str): """ Prints text to the screen. Supports colors by using the color constants. To use colors, add the color before the text you want to print. :param text: The text to print. """ # Default color is NORMAL. last_color = (self._DAR...
[ "def", "write", "(", "self", ",", "text", ":", "str", ")", ":", "# Default color is NORMAL.", "last_color", "=", "(", "self", ".", "_DARK_CODE", ",", "0", ")", "# We use splitlines with keepends in order to keep the line breaks.", "# Then we split by using the console width...
45.811321
19.09434
def changePlanParticipation(self, plan, take_part=True): """ Changes participation in a plan :param plan: Plan to take part in or not :param take_part: Whether to take part in the plan :raises: FBchatException if request failed """ data = { "event_rem...
[ "def", "changePlanParticipation", "(", "self", ",", "plan", ",", "take_part", "=", "True", ")", ":", "data", "=", "{", "\"event_reminder_id\"", ":", "plan", ".", "uid", ",", "\"guest_state\"", ":", "\"GOING\"", "if", "take_part", "else", "\"DECLINED\"", ",", ...
34.375
16.875
def tropocollagen( cls, aa=28, major_radius=5.0, major_pitch=85.0, auto_build=True): """Creates a model of a collagen triple helix. Parameters ---------- aa : int, optional Number of amino acids per minor helix. major_radius : float, optional ...
[ "def", "tropocollagen", "(", "cls", ",", "aa", "=", "28", ",", "major_radius", "=", "5.0", ",", "major_pitch", "=", "85.0", ",", "auto_build", "=", "True", ")", ":", "instance", "=", "cls", ".", "from_parameters", "(", "n", "=", "3", ",", "aa", "=", ...
40.961538
16.230769
def contents(self, from_date=DEFAULT_DATETIME, offset=None, max_contents=MAX_CONTENTS): """Get the contents of a repository. This method returns an iterator that manages the pagination over contents. Take into account that the seconds of `from_date` parameter will be ig...
[ "def", "contents", "(", "self", ",", "from_date", "=", "DEFAULT_DATETIME", ",", "offset", "=", "None", ",", "max_contents", "=", "MAX_CONTENTS", ")", ":", "resource", "=", "self", ".", "RCONTENTS", "+", "'/'", "+", "self", ".", "MSEARCH", "# Set confluence q...
34.741935
19.677419
def getlist(self, section, option): """ returns the named option as a list, splitting the original value by ',' """ value = self.get(section, option) if value: return value.split(',') else: return None
[ "def", "getlist", "(", "self", ",", "section", ",", "option", ")", ":", "value", "=", "self", ".", "get", "(", "section", ",", "option", ")", "if", "value", ":", "return", "value", ".", "split", "(", "','", ")", "else", ":", "return", "None" ]
28
13.6
def write_config_static(system_dir, system_filename_pattern, model_dir, model_filename_pattern, config_file_path, system_id=None): """ Write the ROUGE configuration file, which is basically a list of system summary files and their correspon...
[ "def", "write_config_static", "(", "system_dir", ",", "system_filename_pattern", ",", "model_dir", ",", "model_filename_pattern", ",", "config_file_path", ",", "system_id", "=", "None", ")", ":", "system_filenames", "=", "[", "f", "for", "f", "in", "os", ".", "l...
48.163636
21.072727
def update_font(self): """Update font from Preferences""" font = self.get_plugin_font() for client in self.clients: client.set_font(font)
[ "def", "update_font", "(", "self", ")", ":", "font", "=", "self", ".", "get_plugin_font", "(", ")", "for", "client", "in", "self", ".", "clients", ":", "client", ".", "set_font", "(", "font", ")" ]
34.6
6
def serialize_input(input, signature_script_hex=''): """ Serializes a transaction input. """ if not (isinstance(input, dict) and 'transaction_hash' in input \ and 'output_index' in input): raise Exception('Required parameters: transaction_hash, output_index') if is_hex(str(input['tr...
[ "def", "serialize_input", "(", "input", ",", "signature_script_hex", "=", "''", ")", ":", "if", "not", "(", "isinstance", "(", "input", ",", "dict", ")", "and", "'transaction_hash'", "in", "input", "and", "'output_index'", "in", "input", ")", ":", "raise", ...
44.217391
26.391304
def find_from(path): """Find path of an .ensime config, searching recursively upward from path. Args: path (str): Path of a file or directory from where to start searching. Returns: str: Canonical path of nearest ``.ensime``, or ``None`` if not found. """ ...
[ "def", "find_from", "(", "path", ")", ":", "realpath", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "config_path", "=", "os", ".", "path", ".", "join", "(", "realpath", ",", "'.ensime'", ")", "if", "os", ".", "path", ".", "isfile", "(...
34.210526
19.421053
def GetSubkeyByIndex(self, index): """Retrieves a subkey by index. Args: index (int): index of the subkey. Returns: WinRegistryKey: Windows Registry subkey or None if not found. Raises: IndexError: if the index is out of bounds. """ if index < 0 or index >= self._pyregf_key....
[ "def", "GetSubkeyByIndex", "(", "self", ",", "index", ")", ":", "if", "index", "<", "0", "or", "index", ">=", "self", ".", "_pyregf_key", ".", "number_of_sub_keys", ":", "raise", "IndexError", "(", "'Index out of bounds.'", ")", "pyregf_key", "=", "self", "....
28.333333
22.142857
def min(a, axis=None): """ Request the minimum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose minimum is to be found. axis : None, or int, or iterable of ints Axis or ax...
[ "def", "min", "(", "a", ",", "axis", "=", "None", ")", ":", "axes", "=", "_normalise_axis", "(", "axis", ",", "a", ")", "assert", "axes", "is", "not", "None", "and", "len", "(", "axes", ")", "==", "1", "return", "_Aggregation", "(", "a", ",", "ax...
35.111111
20.296296
def view(self, start, end, max_items=None, *args, **kwargs): """ Implements the CalendarView option to FindItem. The difference between filter() and view() is that filter() only returns the master CalendarItem for recurring items, while view() unfolds recurring items and returns all CalendarItem...
[ "def", "view", "(", "self", ",", "start", ",", "end", ",", "max_items", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "qs", "=", "QuerySet", "(", "self", ")", ".", "filter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
67.75
42.5
def verify_invoice_params(self, price, currency): """ Deprecated, will be made private in 2.4 """ if re.match("^[A-Z]{3,3}$", currency) is None: raise BitPayArgumentError("Currency is invalid.") try: float(price) except: raise BitPayArgumentError("Price must be formatted as a ...
[ "def", "verify_invoice_params", "(", "self", ",", "price", ",", "currency", ")", ":", "if", "re", ".", "match", "(", "\"^[A-Z]{3,3}$\"", ",", "currency", ")", "is", "None", ":", "raise", "BitPayArgumentError", "(", "\"Currency is invalid.\"", ")", "try", ":", ...
31.8
14.8
def _handle(self, nick, target, message, **kwargs): """ client callback entrance """ for regex, (func, pattern) in self.routes.items(): match = regex.match(message) if match: self.client.loop.create_task( func(nick, target, message, match, **kw...
[ "def", "_handle", "(", "self", ",", "nick", ",", "target", ",", "message", ",", "*", "*", "kwargs", ")", ":", "for", "regex", ",", "(", "func", ",", "pattern", ")", "in", "self", ".", "routes", ".", "items", "(", ")", ":", "match", "=", "regex", ...
45.714286
11.142857