text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def prepare_metadata(self): # type: () -> None """Ensure that project metadata is available. Under PEP 517, call the backend hook to prepare the metadata. Under legacy processing, call setup.py egg-info. """ assert self.source_dir with indent_log(): ...
[ "def", "prepare_metadata", "(", "self", ")", ":", "# type: () -> None", "assert", "self", ".", "source_dir", "with", "indent_log", "(", ")", ":", "if", "self", ".", "use_pep517", ":", "self", ".", "prepare_pep517_metadata", "(", ")", "else", ":", "self", "."...
34.421053
17
def is_data_diverging(data_container): """ We want to use this to check whether the data are diverging or not. This is a simple check, can be made much more sophisticated. :param data_container: A generic container of data points. :type data_container: `iterable` """ assert infer_data_type...
[ "def", "is_data_diverging", "(", "data_container", ")", ":", "assert", "infer_data_type", "(", "data_container", ")", "in", "[", "\"ordinal\"", ",", "\"continuous\"", ",", "]", ",", "\"Data type should be ordinal or continuous\"", "# Check whether the data contains negative a...
28.730769
18.038462
def ConsultarUltimoComprobante(self, tipo_cbte=151, pto_vta=1): "Consulta el último No de Comprobante registrado" ret = self.client.consultarUltimoNroComprobantePorPtoVta( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit...
[ "def", "ConsultarUltimoComprobante", "(", "self", ",", "tipo_cbte", "=", "151", ",", "pto_vta", "=", "1", ")", ":", "ret", "=", "self", ".", "client", ".", "consultarUltimoNroComprobantePorPtoVta", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token",...
43.357143
14.357143
def delta(n, d=None, center=0): """ Create TT-vector for delta-function :math:`\\delta(x - x_0)`. """ if isinstance(n, six.integer_types): n = [n] if d is None: n0 = _np.asanyarray(n, dtype=_np.int32) else: n0 = _np.array(n * d, dtype=_np.int32) d = n0.size if center < 0...
[ "def", "delta", "(", "n", ",", "d", "=", "None", ",", "center", "=", "0", ")", ":", "if", "isinstance", "(", "n", ",", "six", ".", "integer_types", ")", ":", "n", "=", "[", "n", "]", "if", "d", "is", "None", ":", "n0", "=", "_np", ".", "asa...
27.16
15.44
def run_canu(self): '''Runs canu instead of spades''' cmd = self._make_canu_command(self.outdir,'canu') ok, errs = common.syscall(cmd, verbose=self.verbose, allow_fail=False) if not ok: raise Error('Error running Canu.') original_contigs = os.path.join(self.outdir, '...
[ "def", "run_canu", "(", "self", ")", ":", "cmd", "=", "self", ".", "_make_canu_command", "(", "self", ".", "outdir", ",", "'canu'", ")", "ok", ",", "errs", "=", "common", ".", "syscall", "(", "cmd", ",", "verbose", "=", "self", ".", "verbose", ",", ...
49.846154
22.615385
def main(): """ Simple command-line program for powering on virtual machines on a system. """ args = GetArgs() if args.password: password = args.password else: password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user)) try: vmnames = ar...
[ "def", "main", "(", ")", ":", "args", "=", "GetArgs", "(", ")", "if", "args", ".", "password", ":", "password", "=", "args", ".", "password", "else", ":", "password", "=", "getpass", ".", "getpass", "(", "prompt", "=", "'Enter password for host %s and user...
32.823529
20.941176
def _make_connect(module, args, kwargs): """ Returns a function capable of making connections with a particular driver given the supplied credentials. """ # pylint: disable-msg=W0142 return functools.partial(module.connect, *args, **kwargs)
[ "def", "_make_connect", "(", "module", ",", "args", ",", "kwargs", ")", ":", "# pylint: disable-msg=W0142", "return", "functools", ".", "partial", "(", "module", ".", "connect", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
36.857143
8.857143
def update_cb(self, context, t, idx, userdata): """A sink property changed, calls request_update""" if t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK == PA_SUBSCRIPTION_EVENT_SERVER: pa_operation_unref( pa_context_get_server_info(context, self._server_info_cb, None)) self....
[ "def", "update_cb", "(", "self", ",", "context", ",", "t", ",", "idx", ",", "userdata", ")", ":", "if", "t", "&", "PA_SUBSCRIPTION_EVENT_FACILITY_MASK", "==", "PA_SUBSCRIPTION_EVENT_SERVER", ":", "pa_operation_unref", "(", "pa_context_get_server_info", "(", "context...
42
22.875
def _set_scripts(self, host_metadata, scripts): """ Temporary method to set the host scripts TODO: remove once the "ovirt-scripts" option gets deprecated Args: host_metadata(dict): host metadata to set scripts in Returns: dict: the updated m...
[ "def", "_set_scripts", "(", "self", ",", "host_metadata", ",", "scripts", ")", ":", "scripts_key", "=", "'deploy-scripts'", "if", "'ovirt-scritps'", "in", "host_metadata", ":", "scripts_key", "=", "'ovirt-scripts'", "host_metadata", "[", "scripts_key", "]", "=", "...
27.473684
17.263158
def node_get_args(node): """Return an ordered mapping from params to args""" obj = node[OBJ] key = node[KEY] boundargs = obj.formula.signature.bind(*key) boundargs.apply_defaults() return boundargs.arguments
[ "def", "node_get_args", "(", "node", ")", ":", "obj", "=", "node", "[", "OBJ", "]", "key", "=", "node", "[", "KEY", "]", "boundargs", "=", "obj", ".", "formula", ".", "signature", ".", "bind", "(", "*", "key", ")", "boundargs", ".", "apply_defaults",...
32.142857
12.285714
def calculate_sun(self, month, day, hour, is_solar_time=False): """Get Sun data for an hour of the year. Args: month: An integer between 1-12 day: An integer between 1-31 hour: A positive number between 0..23 is_solar_time: A boolean to indicate if the in...
[ "def", "calculate_sun", "(", "self", ",", "month", ",", "day", ",", "hour", ",", "is_solar_time", "=", "False", ")", ":", "datetime", "=", "DateTime", "(", "month", ",", "day", ",", "*", "self", ".", "_calculate_hour_and_minute", "(", "hour", ")", ",", ...
40.75
19.4375
def _cached_css_compile(pattern, namespaces, custom, flags): """Cached CSS compile.""" custom_selectors = process_custom(custom) return cm.SoupSieve( pattern, CSSParser(pattern, custom=custom_selectors, flags=flags).process_selectors(), namespaces, custom, flags ...
[ "def", "_cached_css_compile", "(", "pattern", ",", "namespaces", ",", "custom", ",", "flags", ")", ":", "custom_selectors", "=", "process_custom", "(", "custom", ")", "return", "cm", ".", "SoupSieve", "(", "pattern", ",", "CSSParser", "(", "pattern", ",", "c...
28.272727
23.454545
def _get_convergence_plans(project, service_names): ''' Get action executed for each container :param project: :param service_names: :return: ''' ret = {} plans = project._get_convergence_plans(project.get_services(service_names), ConvergenceSt...
[ "def", "_get_convergence_plans", "(", "project", ",", "service_names", ")", ":", "ret", "=", "{", "}", "plans", "=", "project", ".", "_get_convergence_plans", "(", "project", ".", "get_services", "(", "service_names", ")", ",", "ConvergenceStrategy", ".", "chang...
32.318182
17.5
def token_perplexity_micro(eval_data, predictions, scores, learner='ignored'): ''' Return the micro-averaged per-token perplexity `exp(-score / num_tokens)` computed over the entire corpus, as a length-1 list of floats. The log scores in `scores` should be base e (`exp`, `log`). >>> refs = [Instanc...
[ "def", "token_perplexity_micro", "(", "eval_data", ",", "predictions", ",", "scores", ",", "learner", "=", "'ignored'", ")", ":", "lens", "=", "np", ".", "array", "(", "[", "len", "(", "_maybe_tokenize", "(", "inst", ".", "output", ")", ")", "+", "1", ...
45.157895
21.263158
def buy(self, currencyPair, rate, amount, fillOrKill=None, immediateOrCancel=None, postOnly=None): """Places a limit buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. You may...
[ "def", "buy", "(", "self", ",", "currencyPair", ",", "rate", ",", "amount", ",", "fillOrKill", "=", "None", ",", "immediateOrCancel", "=", "None", ",", "postOnly", "=", "None", ")", ":", "return", "self", ".", "_private", "(", "'buy'", ",", "currencyPair...
65.411765
23.470588
def get_all_modified_on(chebi_ids): '''Returns all modified on''' all_modified_ons = [get_modified_on(chebi_id) for chebi_id in chebi_ids] all_modified_ons = [modified_on for modified_on in all_modified_ons if modified_on is not None] return None if len(all_modified_ons) == 0 els...
[ "def", "get_all_modified_on", "(", "chebi_ids", ")", ":", "all_modified_ons", "=", "[", "get_modified_on", "(", "chebi_id", ")", "for", "chebi_id", "in", "chebi_ids", "]", "all_modified_ons", "=", "[", "modified_on", "for", "modified_on", "in", "all_modified_ons", ...
57.5
21.5
def tobool(obj, default=False): ''' Returns a bool representation of `obj`: if `obj` is not a string, it is returned cast to a boolean by calling `bool()`. Otherwise, it is checked for "truthy" or "falsy" values, and that is returned. If it is not truthy or falsy, `default` is returned (which defaults to ``...
[ "def", "tobool", "(", "obj", ",", "default", "=", "False", ")", ":", "if", "isinstance", "(", "obj", ",", "bool", ")", ":", "return", "obj", "if", "not", "isstr", "(", "obj", ")", ":", "return", "bool", "(", "obj", ")", "lobj", "=", "obj", ".", ...
31.272727
24
def generate_options_map(): """Generate an ``options_map` to pass to ``extract_from_dir`` This is the options_map that's used to generate a Jinja2 environment. We want to generate and environment for extraction that's the same as the environment we use for rendering. This allows developers to expl...
[ "def", "generate_options_map", "(", ")", ":", "try", ":", "return", "settings", ".", "PUENTE", "[", "'JINJA2_CONFIG'", "]", "except", "KeyError", ":", "pass", "# If using Django 1.8+, we can skim the TEMPLATES for a backend that we", "# know about and extract the settings from ...
32.921569
21.666667
def make_pdb(self): """Generates a PDB string for the `Monomer`.""" pdb_str = write_pdb( [self], ' ' if not self.ampal_parent else self.ampal_parent.id) return pdb_str
[ "def", "make_pdb", "(", "self", ")", ":", "pdb_str", "=", "write_pdb", "(", "[", "self", "]", ",", "' '", "if", "not", "self", ".", "ampal_parent", "else", "self", ".", "ampal_parent", ".", "id", ")", "return", "pdb_str" ]
39.8
17.2
def clean_bytes(line): """ Cleans a byte sequence of shell directives and decodes it. """ text = line.decode('utf-8').replace('\r', '').strip('\n') return re.sub(r'\x1b[^m]*m', '', text).replace("``", "`\u200b`").strip('\n')
[ "def", "clean_bytes", "(", "line", ")", ":", "text", "=", "line", ".", "decode", "(", "'utf-8'", ")", ".", "replace", "(", "'\\r'", ",", "''", ")", ".", "strip", "(", "'\\n'", ")", "return", "re", ".", "sub", "(", "r'\\x1b[^m]*m'", ",", "''", ",", ...
37
21.857143
def setPalette(self, palette): """ Sets the palette for this widget and the scroll area. :param palette | <QPalette> """ super(XPopupWidget, self).setPalette(palette) self._scrollArea.setPalette(palette)
[ "def", "setPalette", "(", "self", ",", "palette", ")", ":", "super", "(", "XPopupWidget", ",", "self", ")", ".", "setPalette", "(", "palette", ")", "self", ".", "_scrollArea", ".", "setPalette", "(", "palette", ")" ]
33.125
10.125
def _check_cv(self, val, random_state=None): """ Validate the cv method passed in. Returns the split strategy if no validation exception is raised. """ # Use default splitter in this case if val is None: val = 0.1 if isinstance(val, float) and val <= 1.0: ...
[ "def", "_check_cv", "(", "self", ",", "val", ",", "random_state", "=", "None", ")", ":", "# Use default splitter in this case", "if", "val", "is", "None", ":", "val", "=", "0.1", "if", "isinstance", "(", "val", ",", "float", ")", "and", "val", "<=", "1.0...
34.904762
18.238095
def label(self, label): """ set the label """ if self.direction in ['i'] and label is not None: raise ValueError("label not accepted for indep dimension") if label is None: self._label = label return if not isinstance(label, str): ...
[ "def", "label", "(", "self", ",", "label", ")", ":", "if", "self", ".", "direction", "in", "[", "'i'", "]", "and", "label", "is", "not", "None", ":", "raise", "ValueError", "(", "\"label not accepted for indep dimension\"", ")", "if", "label", "is", "None"...
24.263158
19.736842
def _trace_filename(self): """ Creates trace filename. """ dir_stub = '' if self.output_directory is not None: dir_stub = self.output_directory if self.each_time: filename = '{0}_{1}.json'.format( self.output_file_name, self.counter...
[ "def", "_trace_filename", "(", "self", ")", ":", "dir_stub", "=", "''", "if", "self", ".", "output_directory", "is", "not", "None", ":", "dir_stub", "=", "self", ".", "output_directory", "if", "self", ".", "each_time", ":", "filename", "=", "'{0}_{1}.json'",...
33.461538
10.692308
async def set_reply_markup(msg: Dict, request: 'Request', stack: 'Stack') \ -> None: """ Add the "reply markup" to a message from the layers :param msg: Message dictionary :param request: Current request being replied :param stack: Stack to analyze """ from bernard.platforms.telegr...
[ "async", "def", "set_reply_markup", "(", "msg", ":", "Dict", ",", "request", ":", "'Request'", ",", "stack", ":", "'Stack'", ")", "->", "None", ":", "from", "bernard", ".", "platforms", ".", "telegram", ".", "layers", "import", "InlineKeyboard", ",", "Repl...
27.125
21.5625
def graph(self, ASres=None, padding=0, vspread=0.75, title="Multi-Traceroute Probe (MTR)", timestamp="", rtt=1, **kargs): """x.graph(ASres=conf.AS_resolver, other args): ASres = None : Use AS default resolver => 'conf.AS_resolver' ASres = AS_resolver() : default whois AS resolver (riswh...
[ "def", "graph", "(", "self", ",", "ASres", "=", "None", ",", "padding", "=", "0", ",", "vspread", "=", "0.75", ",", "title", "=", "\"Multi-Traceroute Probe (MTR)\"", ",", "timestamp", "=", "\"\"", ",", "rtt", "=", "1", ",", "*", "*", "kargs", ")", ":...
60.869565
24.173913
def controlMsg(self, requestType, request, buffer, value = 0, index = 0, timeout = 100): r"""Perform a control request to the default control pipe on a device. Arguments: requestType: specifies the direction of data flow, the type of request, and the recipient. ...
[ "def", "controlMsg", "(", "self", ",", "requestType", ",", "request", ",", "buffer", ",", "value", "=", "0", ",", "index", "=", "0", ",", "timeout", "=", "100", ")", ":", "return", "self", ".", "dev", ".", "ctrl_transfer", "(", "requestType", ",", "r...
48.863636
17.727273
def compute_group_colors(self): """Computes the group colors according to node colors""" seen = set() self.group_label_color = [ x for x in self.node_colors if not (x in seen or seen.add(x)) ]
[ "def", "compute_group_colors", "(", "self", ")", ":", "seen", "=", "set", "(", ")", "self", ".", "group_label_color", "=", "[", "x", "for", "x", "in", "self", ".", "node_colors", "if", "not", "(", "x", "in", "seen", "or", "seen", ".", "add", "(", "...
38.5
16.5
def get_arrays(self, type_img): ''' Return arrays the region of interest Args: type_img (str): Either lola or wac. Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values ...
[ "def", "get_arrays", "(", "self", ",", "type_img", ")", ":", "if", "type_img", ".", "lower", "(", ")", "==", "'lola'", ":", "return", "LolaMap", "(", "self", ".", "ppdlola", ",", "*", "self", ".", "window", ",", "path_pdsfile", "=", "self", ".", "pat...
37.208333
26.041667
def fix_tags_on_cands_missing_reals(user_id, vos_dir, property): "At the moment this just checks for a single user's missing reals. Easy to generalise it to all users." con = context.get_context(vos_dir) user_progress = [] listing = con.get_listing(tasks.get_suffix('reals')) mpc_listing = con.get_li...
[ "def", "fix_tags_on_cands_missing_reals", "(", "user_id", ",", "vos_dir", ",", "property", ")", ":", "con", "=", "context", ".", "get_context", "(", "vos_dir", ")", "user_progress", "=", "[", "]", "listing", "=", "con", ".", "get_listing", "(", "tasks", ".",...
47.833333
23.833333
def mine(self): # pragma: no cover """ Search for domain or URL related to the original URL or domain. :return: The mined domains or URL. :rtype: dict """ if PyFunceble.CONFIGURATION["mining"]: # The mining is activated. try: # ...
[ "def", "mine", "(", "self", ")", ":", "# pragma: no cover", "if", "PyFunceble", ".", "CONFIGURATION", "[", "\"mining\"", "]", ":", "# The mining is activated.", "try", ":", "# We get the history.", "history", "=", "PyFunceble", ".", "requests", ".", "get", "(", ...
35.771084
21
def command_line_parsed( self, available_plugins: Set[Type[Plugin]], args_command_list: Any, malformed_servers: List[ServerStringParsingError] ) -> None: """The CLI was just started and successfully parsed the command line. """
[ "def", "command_line_parsed", "(", "self", ",", "available_plugins", ":", "Set", "[", "Type", "[", "Plugin", "]", "]", ",", "args_command_list", ":", "Any", ",", "malformed_servers", ":", "List", "[", "ServerStringParsingError", "]", ")", "->", "None", ":" ]
36
12.5
def cmd_ssh_user(tar_aminame, inst_name): """Calculate instance login-username based on image-name. Args: tar_aminame (str): name of the image instance created with. inst_name (str): name of the instance. Returns: username (str): name for ssh based on AMI-name. """ if tar_a...
[ "def", "cmd_ssh_user", "(", "tar_aminame", ",", "inst_name", ")", ":", "if", "tar_aminame", "==", "\"Unknown\"", ":", "tar_aminame", "=", "inst_name", "# first 5 chars of AMI-name can be anywhere in AMI-Name", "userlu", "=", "{", "\"ubunt\"", ":", "\"ubuntu\"", ",", "...
39.809524
17.238095
def sphinx_class(self): """Redefine sphinx class so documentation links to instance_class""" classdoc = ':class:`{cls} <{pref}.{cls}>`'.format( cls=self.instance_class.__name__, pref=self.instance_class.__module__, ) return classdoc
[ "def", "sphinx_class", "(", "self", ")", ":", "classdoc", "=", "':class:`{cls} <{pref}.{cls}>`'", ".", "format", "(", "cls", "=", "self", ".", "instance_class", ".", "__name__", ",", "pref", "=", "self", ".", "instance_class", ".", "__module__", ",", ")", "r...
40.285714
13.714286
def random_sent(self, index): """ Get one sample from corpus consisting of two sentences. With prob. 50% these are two subsequent sentences from one doc. With 50% the second sentence will be a random one from another doc. :param index: int, index of sample. :return: (str, str, in...
[ "def", "random_sent", "(", "self", ",", "index", ")", ":", "t1", ",", "t2", "=", "self", ".", "get_corpus_line", "(", "index", ")", "if", "random", ".", "random", "(", ")", ">", "0.5", ":", "label", "=", "0", "else", ":", "t2", "=", "self", ".", ...
36.764706
19.470588
async def createTask(self, *args, **kwargs): """ Create New Task Create a new task, this is an **idempotent** operation, so repeat it if you get an internal server error or network connection is dropped. **Task `deadline`**: the deadline property can be no more than 5 days ...
[ "async", "def", "createTask", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"createTask\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
49.767442
32.697674
def categorical_partition_data(data): """Convenience method for creating weights from categorical data. Args: data (list-like): The data from which to construct the estimate. Returns: A new partition object:: { "partition": (list) The categorical values present...
[ "def", "categorical_partition_data", "(", "data", ")", ":", "# Make dropna explicit (even though it defaults to true)", "series", "=", "pd", ".", "Series", "(", "data", ")", "value_counts", "=", "series", ".", "value_counts", "(", "dropna", "=", "True", ")", "# Comp...
30.035714
22.964286
def query_flag(ifo, name, start_time, end_time, source='any', server="segments.ligo.org", veto_definer=None, cache=False): """Return the times where the flag is active Parameters ---------- ifo: string The interferometer to query (H1, L1). name: string ...
[ "def", "query_flag", "(", "ifo", ",", "name", ",", "start_time", ",", "end_time", ",", "source", "=", "'any'", ",", "server", "=", "\"segments.ligo.org\"", ",", "veto_definer", "=", "None", ",", "cache", "=", "False", ")", ":", "info", "=", "name", ".", ...
38.055118
20.582677
def load_lynx(as_series=False): """Annual numbers of lynx trappings for 1821–1934 in Canada. This time-series records the number of skins of predators (lynx) that were collected over several years by the Hudson's Bay Company. The dataset was taken from Brockwell & Davis (1991) and appears to be the ser...
[ "def", "load_lynx", "(", "as_series", "=", "False", ")", ":", "rslt", "=", "np", ".", "array", "(", "[", "269", ",", "321", ",", "585", ",", "871", ",", "1475", ",", "2821", ",", "3928", ",", "5943", ",", "4950", ",", "2577", ",", "523", ",", ...
42.068493
26.438356
def makeResetPacket(ID, param): """ Resets a servo to one of 3 reset states: XL320_RESET_ALL = 0xFF XL320_RESET_ALL_BUT_ID = 0x01 XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02 """ if param not in [0x01, 0x02, 0xff]: raise Exception('Packet.makeResetPacket invalide parameter {}'.format(par...
[ "def", "makeResetPacket", "(", "ID", ",", "param", ")", ":", "if", "param", "not", "in", "[", "0x01", ",", "0x02", ",", "0xff", "]", ":", "raise", "Exception", "(", "'Packet.makeResetPacket invalide parameter {}'", ".", "format", "(", "param", ")", ")", "#...
33.384615
11.538462
def getRoles(self): """Get all :class:`rtcclient.models.Role` objects in this project area If no :class:`Roles` are retrieved, `None` is returned. :return: a :class:`list` that contains all :class:`rtcclient.models.Role` objects :rtype: list """ # n...
[ "def", "getRoles", "(", "self", ")", ":", "# no need to retrieve all the entries from _get_paged_resources", "# role raw data is very simple that contains no other links", "self", ".", "log", ".", "info", "(", "\"Get all the roles in <ProjectArea %s>\"", ",", "self", ")", "roles_...
35.864865
17.972973
def flatten(d, reducer='tuple', inverse=False): """Flatten dict-like object. Parameters ---------- d: dict-like object The dict that will be flattened. reducer: {'tuple', 'path', function} (default: 'tuple') The key joining method. If a function is given, the function will be ...
[ "def", "flatten", "(", "d", ",", "reducer", "=", "'tuple'", ",", "inverse", "=", "False", ")", ":", "if", "isinstance", "(", "reducer", ",", "str", ")", ":", "reducer", "=", "REDUCER_DICT", "[", "reducer", "]", "flat_dict", "=", "{", "}", "def", "_fl...
31.675676
17.108108
def refresh(self): """Refreshes the editor panels (resize and update margins).""" logger.debug('Refresh panels') self.resize() self._update(self.editor.contentsRect(), 0, force_update_margins=True)
[ "def", "refresh", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Refresh panels'", ")", "self", ".", "resize", "(", ")", "self", ".", "_update", "(", "self", ".", "editor", ".", "contentsRect", "(", ")", ",", "0", ",", "force_update_margins", "=...
40.833333
10.166667
def check_user_can_view_comments(user_info, recid): """Check if the user is authorized to view comments for given recid. Returns the same type as acc_authorize_action """ # Check user can view the record itself first (auth_code, auth_msg) = check_user_can_view_record(user_info, recid) if au...
[ "def", "check_user_can_view_comments", "(", "user_info", ",", "recid", ")", ":", "# Check user can view the record itself first", "(", "auth_code", ",", "auth_msg", ")", "=", "check_user_can_view_record", "(", "user_info", ",", "recid", ")", "if", "auth_code", ":", "r...
35.85
16.55
def get_args(self, state, all_params, remainder, argspec, im_self): ''' Determines the arguments for a controller based upon parameters passed the argument specification for the controller. ''' args = [] varargs = [] kwargs = dict() valid_args = argspec.ar...
[ "def", "get_args", "(", "self", ",", "state", ",", "all_params", ",", "remainder", ",", "argspec", ",", "im_self", ")", ":", "args", "=", "[", "]", "varargs", "=", "[", "]", "kwargs", "=", "dict", "(", ")", "valid_args", "=", "argspec", ".", "args", ...
32.684211
16.54386
def hue(self, img1, img2): """Applies the hue blend mode. Hues image img1 with image img2. The hue filter replaces the hues of pixels in img1 with the hues of pixels in img2. Returns a composite image with the alpha channel retained. """ import col...
[ "def", "hue", "(", "self", ",", "img1", ",", "img2", ")", ":", "import", "colorsys", "p1", "=", "list", "(", "img1", ".", "getdata", "(", ")", ")", "p2", "=", "list", "(", "img2", ".", "getdata", "(", ")", ")", "for", "i", "in", "range", "(", ...
26.55
17.625
def _read_widget(self): """Returns the value currently stored into the widget, after transforming it accordingly to possibly specified function. This is implemented by calling the getter provided by the user. This method can raise InvalidValue (raised by the getter) when the val...
[ "def", "_read_widget", "(", "self", ")", ":", "getter", "=", "self", ".", "_wid_info", "[", "self", ".", "_wid", "]", "[", "0", "]", "return", "getter", "(", "self", ".", "_wid", ")" ]
45
17.5
def add_JSscript(self, js_script, js_loc): """add (highcharts) javascript in the beginning or at the end of script use only if necessary """ if js_loc == 'head': self.jscript_head_flag = True if self.jscript_head: self.jscript_head = self.jscript_h...
[ "def", "add_JSscript", "(", "self", ",", "js_script", ",", "js_loc", ")", ":", "if", "js_loc", "==", "'head'", ":", "self", ".", "jscript_head_flag", "=", "True", "if", "self", ".", "jscript_head", ":", "self", ".", "jscript_head", "=", "self", ".", "jsc...
41.105263
13.421053
def upload_file(self, session, output, serverdir): """ Upload a file to koji :return: str, pathname on server """ name = output.metadata['filename'] self.log.debug("uploading %r to %r as %r", output.file.name, serverdir, name) kwargs = {} ...
[ "def", "upload_file", "(", "self", ",", "session", ",", "output", ",", "serverdir", ")", ":", "name", "=", "output", ".", "metadata", "[", "'filename'", "]", "self", ".", "log", ".", "debug", "(", "\"uploading %r to %r as %r\"", ",", "output", ".", "file",...
36
15.428571
def base64_encode_as_string(obj): # noqa # type: (any) -> str """Encode object to base64 :param any obj: object to encode :rtype: str :return: base64 encoded string """ if on_python2(): return base64.b64encode(obj) else: return str(base64.b64encode(obj), 'ascii')
[ "def", "base64_encode_as_string", "(", "obj", ")", ":", "# noqa", "# type: (any) -> str", "if", "on_python2", "(", ")", ":", "return", "base64", ".", "b64encode", "(", "obj", ")", "else", ":", "return", "str", "(", "base64", ".", "b64encode", "(", "obj", "...
27.454545
10.636364
def patch(self, url, data=None, **kwargs): """ Shorthand for self.oauth_request(url, 'patch') :param str url: url to send patch oauth request to :param dict data: patch data to update the service :param kwargs: extra params to send to request api :return: Response of the request...
[ "def", "patch", "(", "self", ",", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "oauth_request", "(", "url", ",", "'patch'", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
42.6
13.1
def init_app(self, app): """Initialize application in Flask-RBAC. Adds (RBAC, app) to flask extensions. Adds hook to authenticate permission before request. :param app: Flask object """ app.config.setdefault('RBAC_USE_WHITE', False) self.use_white = app.config['...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "app", ".", "config", ".", "setdefault", "(", "'RBAC_USE_WHITE'", ",", "False", ")", "self", ".", "use_white", "=", "app", ".", "config", "[", "'RBAC_USE_WHITE'", "]", "if", "not", "hasattr", "(", "...
31.526316
17.157895
def set_selinux_context(path, user=None, role=None, type=None, # pylint: disable=W0622 range=None, # pylint: disable=W0622 persist=False): ''' .. versionchanged:: Neon Added pers...
[ "def", "set_selinux_context", "(", "path", ",", "user", "=", "None", ",", "role", "=", "None", ",", "type", "=", "None", ",", "# pylint: disable=W0622", "range", "=", "None", ",", "# pylint: disable=W0622", "persist", "=", "False", ")", ":", "if", "not", "...
28.8125
22.604167
def packetToDict(pkt): """ Given a packet, this turns it into a dictionary ... is this useful? in: packet, array of numbers out: dictionary (key, value) """ d = { 'id': pkt[4], # 'instruction': xl320.InstrToStr[pkt[7]], # 'length': (pkt[6] << 8) + pkt[5], # 'params': pkt[8:-2], 'Model Number': (pkt[10...
[ "def", "packetToDict", "(", "pkt", ")", ":", "d", "=", "{", "'id'", ":", "pkt", "[", "4", "]", ",", "# 'instruction': xl320.InstrToStr[pkt[7]],", "# 'length': (pkt[6] << 8) + pkt[5],", "# 'params': pkt[8:-2],", "'Model Number'", ":", "(", "pkt", "[", "10", "]", "<...
20.7
19.1
def Verify(self, mempool): """ Verify the transaction. Args: mempool: Returns: bool: True if verified. False otherwise. """ logger.info("Verifying transaction: %s " % self.Hash.ToBytes()) return Helper.VerifyScripts(self)
[ "def", "Verify", "(", "self", ",", "mempool", ")", ":", "logger", ".", "info", "(", "\"Verifying transaction: %s \"", "%", "self", ".", "Hash", ".", "ToBytes", "(", ")", ")", "return", "Helper", ".", "VerifyScripts", "(", "self", ")" ]
22.461538
19.846154
def _filterize(name, value): """ Turn a `name` and `value` into a string expression compatible the ``DataFrame.query`` method. Parameters ---------- name : str Should be the name of a column in the table to which the filter will be applied. A suffix of '_max' will resul...
[ "def", "_filterize", "(", "name", ",", "value", ")", ":", "if", "name", ".", "endswith", "(", "'_min'", ")", ":", "name", "=", "name", "[", ":", "-", "4", "]", "comp", "=", "'>='", "elif", "name", ".", "endswith", "(", "'_max'", ")", ":", "name",...
26.638889
22.194444
def save(keystorerc=None, keystore=None, files=[], verbose=False): '''create a keystore, compress and encrypt to file''' config = None if keystorerc: config = config_reader.read(keystorerc) if not config: print('No configuration found.', file=sys.stderr) sys.exit(-1) elif keystore and len(f...
[ "def", "save", "(", "keystorerc", "=", "None", ",", "keystore", "=", "None", ",", "files", "=", "[", "]", ",", "verbose", "=", "False", ")", ":", "config", "=", "None", "if", "keystorerc", ":", "config", "=", "config_reader", ".", "read", "(", "keyst...
37.123894
23.265487
def ani_depthplot(spec_file='specimens.txt', samp_file='samples.txt', meas_file='measurements.txt', site_file='sites.txt', age_file="", sum_file="", fmt='svg', dmin=-1, dmax=-1, depth_scale='core_depth', dir_path='.', contribution=None): """ returns matplotl...
[ "def", "ani_depthplot", "(", "spec_file", "=", "'specimens.txt'", ",", "samp_file", "=", "'samples.txt'", ",", "meas_file", "=", "'measurements.txt'", ",", "site_file", "=", "'sites.txt'", ",", "age_file", "=", "\"\"", ",", "sum_file", "=", "\"\"", ",", "fmt", ...
38.464968
18.248408
def get_enrollments_for_section_by_sis_id(self, sis_section_id, params={}): """ Return a list of all enrollments for the passed section sis id. """ return self.get_enrollments_for_section( self._sis_id(sis_section_id, sis_field="section"), params)
[ "def", "get_enrollments_for_section_by_sis_id", "(", "self", ",", "sis_section_id", ",", "params", "=", "{", "}", ")", ":", "return", "self", ".", "get_enrollments_for_section", "(", "self", ".", "_sis_id", "(", "sis_section_id", ",", "sis_field", "=", "\"section\...
47.666667
17.333333
def lrem(self, key, count, value): """Removes the first count occurrences of elements equal to value from the list stored at key. :raises TypeError: if count is not int """ if not isinstance(count, int): raise TypeError("count argument must be int") return se...
[ "def", "lrem", "(", "self", ",", "key", ",", "count", ",", "value", ")", ":", "if", "not", "isinstance", "(", "count", ",", "int", ")", ":", "raise", "TypeError", "(", "\"count argument must be int\"", ")", "return", "self", ".", "execute", "(", "b'LREM'...
38.888889
10
def unjoin_domain(username=None, password=None, domain=None, workgroup='WORKGROUP', disable=False, restart=False): # pylint: disable=anomalous-backslash-in-string ''' Unjoin a computer from an Active Directory Domain. ...
[ "def", "unjoin_domain", "(", "username", "=", "None", ",", "password", "=", "None", ",", "domain", "=", "None", ",", "workgroup", "=", "'WORKGROUP'", ",", "disable", "=", "False", ",", "restart", "=", "False", ")", ":", "# pylint: disable=anomalous-backslash-i...
33.424528
22.971698
def get_sds_in_faultset(self, faultSetObj): """ Get list of SDS objects attached to a specific ScaleIO Faultset :param faultSetObj: ScaleIO Faultset object :rtype: list of SDS in specified Faultset """ self.conn.connection._check_login() response = self.conn.conne...
[ "def", "get_sds_in_faultset", "(", "self", ",", "faultSetObj", ")", ":", "self", ".", "conn", ".", "connection", ".", "_check_login", "(", ")", "response", "=", "self", ".", "conn", ".", "connection", ".", "_do_get", "(", "\"{}/{}{}/{}\"", ".", "format", "...
42.142857
19.428571
def transmute(df, *keep_columns, **kwargs): """ Creates columns and then returns those new columns and optionally specified original columns from the DataFrame. This works like `mutate`, but designed to discard the original columns used to create the new ones. Args: *keep_columns: Colu...
[ "def", "transmute", "(", "df", ",", "*", "keep_columns", ",", "*", "*", "kwargs", ")", ":", "keep_cols", "=", "[", "]", "for", "col", "in", "flatten", "(", "keep_columns", ")", ":", "try", ":", "keep_cols", ".", "append", "(", "col", ".", "name", "...
29.473684
20.421053
def CreateSignatureScanner(cls, specification_store): """Creates a signature scanner for format specifications with signatures. Args: specification_store (FormatSpecificationStore): format specifications with signatures. Returns: pysigscan.scanner: signature scanner. """ scan...
[ "def", "CreateSignatureScanner", "(", "cls", ",", "specification_store", ")", ":", "scanner_object", "=", "pysigscan", ".", "scanner", "(", ")", "for", "format_specification", "in", "specification_store", ".", "specifications", ":", "for", "signature", "in", "format...
33.758621
20.793103
def random(self): """ Draws a new value for a stoch conditional on its parents and returns it. Raises an error if no 'random' argument was passed to __init__. """ if self._random: # Get current values of parents for use as arguments for _random() ...
[ "def", "random", "(", "self", ")", ":", "if", "self", ".", "_random", ":", "# Get current values of parents for use as arguments for _random()", "r", "=", "self", ".", "_random", "(", "*", "*", "self", ".", "parents", ".", "value", ")", "else", ":", "raise", ...
28.48
20.8
def visit(H, source_node): """Executes the 'Visit' algorithm described in the paper: Giorgio Gallo, Giustino Longo, Stefano Pallottino, Sang Nguyen, Directed hypergraphs and applications, Discrete Applied Mathematics, Volume 42, Issues 2-3, 27 April 1993, Pages 177-201, ISSN 0166-218X, http://dx.doi...
[ "def", "visit", "(", "H", ",", "source_node", ")", ":", "if", "not", "isinstance", "(", "H", ",", "DirectedHypergraph", ")", ":", "raise", "TypeError", "(", "\"Algorithm only applicable to directed hypergraphs\"", ")", "node_set", "=", "H", ".", "get_node_set", ...
43.20339
21.271186
def _load_debugger_subcommands(self, name): """ Create an instance of each of the debugger subcommands. Commands are found by importing files in the directory 'name' + 'sub'. Some files are excluded via an array set in __init__. For each of the remaining files, we import them an...
[ "def", "_load_debugger_subcommands", "(", "self", ",", "name", ")", ":", "# Initialization", "cmd_instances", "=", "[", "]", "class_prefix", "=", "capitalize", "(", "name", ")", "# e.g. Info, Set, or Show", "module_dir", "=", "'trepan.processor.command.%s_subcmd'", "%",...
45.617021
20.978723
def _get_torrent_category(self, tag, result=None): """Given a tag containing torrent details try to find category of torrent. In search pages the category is found in links of the form <a href='/tv/'>TV</a> with TV replaced with movies, books etc. For the home page I will use the result number to ...
[ "def", "_get_torrent_category", "(", "self", ",", "tag", ",", "result", "=", "None", ")", ":", "hrefs", "=", "[", "\"/movies/\"", ",", "\"/tv/\"", ",", "\"/music/\"", ",", "\"/games/\"", ",", "\"/applications/\"", ",", "\"/anime/\"", ",", "\"/books/\"", ",", ...
39
18.631579
def wraps(__fn, **kw): """Like ``functools.wraps``, with support for annotations.""" kw['assigned'] = kw.get('assigned', WRAPPER_ASSIGNMENTS) return functools.wraps(__fn, **kw)
[ "def", "wraps", "(", "__fn", ",", "*", "*", "kw", ")", ":", "kw", "[", "'assigned'", "]", "=", "kw", ".", "get", "(", "'assigned'", ",", "WRAPPER_ASSIGNMENTS", ")", "return", "functools", ".", "wraps", "(", "__fn", ",", "*", "*", "kw", ")" ]
49.25
11
def from_signed_raw(cls: Type[CertificationType], signed_raw: str) -> CertificationType: """ Return Certification instance from signed raw document :param signed_raw: Signed raw document :return: """ n = 0 lines = signed_raw.splitlines(True) version = in...
[ "def", "from_signed_raw", "(", "cls", ":", "Type", "[", "CertificationType", "]", ",", "signed_raw", ":", "str", ")", "->", "CertificationType", ":", "n", "=", "0", "lines", "=", "signed_raw", ".", "splitlines", "(", "True", ")", "version", "=", "int", "...
32.190476
31.904762
def getRandomSequence(length=500): """Generates a random name and sequence. """ fastaHeader = "" for i in xrange(int(random.random()*100)): fastaHeader = fastaHeader + random.choice([ 'A', 'C', '0', '9', ' ', '\t' ]) return (fastaHeader, \ "".join([ random.choice([ 'A', 'C', 'T',...
[ "def", "getRandomSequence", "(", "length", "=", "500", ")", ":", "fastaHeader", "=", "\"\"", "for", "i", "in", "xrange", "(", "int", "(", "random", ".", "random", "(", ")", "*", "100", ")", ")", ":", "fastaHeader", "=", "fastaHeader", "+", "random", ...
57.125
30.75
def get_target_state(): """SDP target State. Returns the target state; allowed target states and time updated """ sdp_state = SDPState() errval, errdict = _check_status(sdp_state) if errval == "error": LOG.debug(errdict['reason']) return dict( current_target_state="u...
[ "def", "get_target_state", "(", ")", ":", "sdp_state", "=", "SDPState", "(", ")", "errval", ",", "errdict", "=", "_check_status", "(", "sdp_state", ")", "if", "errval", "==", "\"error\"", ":", "LOG", ".", "debug", "(", "errdict", "[", "'reason'", "]", ")...
33.681818
12.272727
def syllabified_str(self, separator="."): """ Returns: str: Syllabified word in string format Examples: >>> Word('conseil').syllabified_str() 'con.seil' You can also specify the separator('.' by default) >>> Word('sikerly').syllabif...
[ "def", "syllabified_str", "(", "self", ",", "separator", "=", "\".\"", ")", ":", "return", "separator", ".", "join", "(", "self", ".", "syllabified", "if", "self", ".", "syllabified", "else", "self", ".", "syllabify", "(", ")", ")" ]
30.4
21.2
def load_configs(self): """load config files""" self.statemgr_config.set_state_locations(self.configs[STATEMGRS_KEY]) if EXTRA_LINKS_KEY in self.configs: for extra_link in self.configs[EXTRA_LINKS_KEY]: self.extra_links.append(self.validate_extra_link(extra_link))
[ "def", "load_configs", "(", "self", ")", ":", "self", ".", "statemgr_config", ".", "set_state_locations", "(", "self", ".", "configs", "[", "STATEMGRS_KEY", "]", ")", "if", "EXTRA_LINKS_KEY", "in", "self", ".", "configs", ":", "for", "extra_link", "in", "sel...
47.5
15.666667
def find_all(pattern=None): """ Returns all serial ports present. :param pattern: pattern to search for when retrieving serial ports :type pattern: string :returns: list of devices :raises: :py:class:`~alarmdecoder.util.CommError` """ devices = [] ...
[ "def", "find_all", "(", "pattern", "=", "None", ")", ":", "devices", "=", "[", "]", "try", ":", "if", "pattern", ":", "devices", "=", "serial", ".", "tools", ".", "list_ports", ".", "grep", "(", "pattern", ")", "else", ":", "devices", "=", "serial", ...
28.863636
22.136364
def _convert_folded_blocks(folded_ir_blocks): """Convert Filter/Traverse blocks and LocalField expressions within @fold to Gremlin objects.""" new_folded_ir_blocks = [] def folded_context_visitor(expression): """Transform LocalField objects into their Gremlin-specific counterpart.""" if not...
[ "def", "_convert_folded_blocks", "(", "folded_ir_blocks", ")", ":", "new_folded_ir_blocks", "=", "[", "]", "def", "folded_context_visitor", "(", "expression", ")", ":", "\"\"\"Transform LocalField objects into their Gremlin-specific counterpart.\"\"\"", "if", "not", "isinstance...
43.266667
22.633333
def _from_metadata(self, urlpath): """Return set of local URLs if files already exist""" md = self.get_metadata(urlpath) if md is not None: return [e['cache_path'] for e in md]
[ "def", "_from_metadata", "(", "self", ",", "urlpath", ")", ":", "md", "=", "self", ".", "get_metadata", "(", "urlpath", ")", "if", "md", "is", "not", "None", ":", "return", "[", "e", "[", "'cache_path'", "]", "for", "e", "in", "md", "]" ]
41.6
5.8
def from_api_repr(cls, resource): """Factory: construct a dataset reference given its API representation Args: resource (Dict[str, str]): Dataset reference resource representation returned from the API Returns: google.cloud.bigquery.dataset.DatasetRefere...
[ "def", "from_api_repr", "(", "cls", ",", "resource", ")", ":", "project", "=", "resource", "[", "\"projectId\"", "]", "dataset_id", "=", "resource", "[", "\"datasetId\"", "]", "return", "cls", "(", "project", ",", "dataset_id", ")" ]
36.142857
15.785714
def _set_hide_mac_acl_ext(self, v, load=False): """ Setter method for hide_mac_acl_ext, mapped from YANG variable /mac/access_list/extended/hide_mac_acl_ext (container) If this variable is read-only (config: false) in the source YANG file, then _set_hide_mac_acl_ext is considered as a private method...
[ "def", "_set_hide_mac_acl_ext", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
79.409091
37.181818
def receiver_blueprint_for(self, name): """ Get a Flask blueprint for the named provider that handles incoming messages & status reports Note: this requires Flask microframework. :rtype: flask.blueprints.Blueprint :returns: Flask Blueprint, fully functional :rai...
[ "def", "receiver_blueprint_for", "(", "self", ",", "name", ")", ":", "# Get the provider & blueprint", "provider", "=", "self", ".", "get_provider", "(", "name", ")", "bp", "=", "provider", ".", "make_receiver_blueprint", "(", ")", "# Register a Flask handler that ini...
38.666667
21.375
def _get_file_alignment_for_new_binary_file(self, file: File) -> int: """Detects alignment requirements for binary files with new nn::util::BinaryFileHeader.""" if len(file.data) <= 0x20: return 0 bom = file.data[0xc:0xc+2] if bom != b'\xff\xfe' and bom != b'\xfe\xff': ...
[ "def", "_get_file_alignment_for_new_binary_file", "(", "self", ",", "file", ":", "File", ")", "->", "int", ":", "if", "len", "(", "file", ".", "data", ")", "<=", "0x20", ":", "return", "0", "bom", "=", "file", ".", "data", "[", "0xc", ":", "0xc", "+"...
42.692308
17.923077
def int_id(self): "int: This key's numeric id." id_or_name = self.id_or_name if id_or_name is not None and isinstance(id_or_name, int): return id_or_name return None
[ "def", "int_id", "(", "self", ")", ":", "id_or_name", "=", "self", ".", "id_or_name", "if", "id_or_name", "is", "not", "None", "and", "isinstance", "(", "id_or_name", ",", "int", ")", ":", "return", "id_or_name", "return", "None" ]
34
14.666667
def get_key_from_request(self): '''Return a key for the current request url. :return: The storage key for the current url :rettype: string ''' path = "result:%s" % self.context.request.url if self.is_auto_webp(): path += '/webp' return path
[ "def", "get_key_from_request", "(", "self", ")", ":", "path", "=", "\"result:%s\"", "%", "self", ".", "context", ".", "request", ".", "url", "if", "self", ".", "is_auto_webp", "(", ")", ":", "path", "+=", "'/webp'", "return", "path" ]
23.076923
22.615385
def rotate(self, angle, direction='z', axis=None): """ Returns a new Surface which is the same but rotated about a given axis. If the axis given is ``None``, the rotation will be computed about the Surface's centroid. :param angle: Rotation angl...
[ "def", "rotate", "(", "self", ",", "angle", ",", "direction", "=", "'z'", ",", "axis", "=", "None", ")", ":", "return", "Space", "(", "Place", "(", "self", ")", ")", ".", "rotate", "(", "angle", ",", "direction", ",", "axis", ")", "[", "0", "]", ...
39.588235
16.176471
def print_summary(self, strm): """Print summary of lint.""" nerr = 0 nerr += LintHelper._print_summary_map(strm, self.cpp_header_map, 'cpp-header') nerr += LintHelper._print_summary_map(strm, self.cpp_src_map, 'cpp-soruce') nerr += LintHelper._print_summary_map(strm, self.python_...
[ "def", "print_summary", "(", "self", ",", "strm", ")", ":", "nerr", "=", "0", "nerr", "+=", "LintHelper", ".", "_print_summary_map", "(", "strm", ",", "self", ".", "cpp_header_map", ",", "'cpp-header'", ")", "nerr", "+=", "LintHelper", ".", "_print_summary_m...
43.272727
22.181818
def get(self, x, y): """Get the state of a pixel. Returns bool. :param x: x coordinate of the pixel :param y: y coordinate of the pixel """ x = normalize(x) y = normalize(y) dot_index = pixel_map[y % 4][x % 2] col, row = get_pos(x, y) char = self....
[ "def", "get", "(", "self", ",", "x", ",", "y", ")", ":", "x", "=", "normalize", "(", "x", ")", "y", "=", "normalize", "(", "y", ")", "dot_index", "=", "pixel_map", "[", "y", "%", "4", "]", "[", "x", "%", "2", "]", "col", ",", "row", "=", ...
24.736842
15.947368
def serialCmdPwdAuth(self, password_str): """ Password step of set commands This method is normally called within another serial command, so it does not issue a termination string. Any default password is set in the caller parameter list, never here. Args: password...
[ "def", "serialCmdPwdAuth", "(", "self", ",", "password_str", ")", ":", "result", "=", "False", "try", ":", "req_start", "=", "\"0150310228\"", "+", "binascii", ".", "hexlify", "(", "password_str", ")", "+", "\"2903\"", "req_crc", "=", "self", ".", "calc_crc1...
38.5
24.433333
def range_hourly(start=None, stop=None, timezone='UTC', count=None): """ This an alternative way to generating sets of Delorean objects with HOURLY stops """ return stops(start=start, stop=stop, freq=HOURLY, timezone=timezone, count=count)
[ "def", "range_hourly", "(", "start", "=", "None", ",", "stop", "=", "None", ",", "timezone", "=", "'UTC'", ",", "count", "=", "None", ")", ":", "return", "stops", "(", "start", "=", "start", ",", "stop", "=", "stop", ",", "freq", "=", "HOURLY", ","...
42.333333
21.333333
def _calc_dic(self): """Calculates deviance information Criterion""" # Find mean deviance mean_deviance = np.mean(self.db.trace('deviance')(), axis=0) # Set values of all parameters to their mean for stochastic in self.stochastics: # Calculate mean of paramter ...
[ "def", "_calc_dic", "(", "self", ")", ":", "# Find mean deviance", "mean_deviance", "=", "np", ".", "mean", "(", "self", ".", "db", ".", "trace", "(", "'deviance'", ")", "(", ")", ",", "axis", "=", "0", ")", "# Set values of all parameters to their mean", "f...
32.4375
17.34375
def list_media_services(access_token, subscription_id): '''List the media services in a subscription. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. Returns: HTTP response. JSON body. ''' endpoint = ''.join([get_r...
[ "def", "list_media_services", "(", "access_token", ",", "subscription_id", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/providers/microsoft.media/mediaservices?api-version=...
36.785714
22.357143
def slaveof(self, host=None, port=None): """ Set the server to be a replicated slave of the instance identified by the ``host`` and ``port``. If called without arguments, the instance is promoted to a master instead. """ if host is None and port is None: retur...
[ "def", "slaveof", "(", "self", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "if", "host", "is", "None", "and", "port", "is", "None", ":", "return", "self", ".", "execute_command", "(", "'SLAVEOF'", ",", "Token", ".", "get_token", "("...
49
14.8
def _get_boll(cls, df): """ Get Bollinger bands. boll_ub means the upper band of the Bollinger bands boll_lb means the lower band of the Bollinger bands boll_ub = MA + Kσ boll_lb = MA − Kσ M = BOLL_PERIOD K = BOLL_STD_TIMES :param df: data ...
[ "def", "_get_boll", "(", "cls", ",", "df", ")", ":", "moving_avg", "=", "df", "[", "'close_{}_sma'", ".", "format", "(", "cls", ".", "BOLL_PERIOD", ")", "]", "moving_std", "=", "df", "[", "'close_{}_mstd'", ".", "format", "(", "cls", ".", "BOLL_PERIOD", ...
40.791667
15.583333
def split_sequence_file_on_sample_ids_to_files(seqs, outdir): """Split FASTA file on sample IDs. Parameters ---------- seqs: file handler file handler to demultiplexed FASTA file outdir: string dirpath to output split FASTA files ""...
[ "def", "split_sequence_file_on_sample_ids_to_files", "(", "seqs", ",", "outdir", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'split_sequence_file_on_sample_ids_to_files'", "' for file %s into dir %s'", "%", "(...
32.769231
17.653846
def recalculate_psd(self): """ Recalculate the psd """ seg_len = self.sample_rate * self.psd_segment_length e = len(self.strain) s = e - ((self.psd_samples + 1) * self.psd_segment_length / 2) * self.sample_rate psd = pycbc.psd.welch(self.strain[s:e], seg_len=seg_len, seg...
[ "def", "recalculate_psd", "(", "self", ")", ":", "seg_len", "=", "self", ".", "sample_rate", "*", "self", ".", "psd_segment_length", "e", "=", "len", "(", "self", ".", "strain", ")", "s", "=", "e", "-", "(", "(", "self", ".", "psd_samples", "+", "1",...
46.1875
27.875
def emit_answer_event(sender, instance, **kwargs): """ Save answer event to log file. """ if not issubclass(sender, Answer) or not kwargs['created']: return logger = get_events_logger() logger.emit('answer', { "user_id": instance.user_id, "is_correct": instance.item_asked...
[ "def", "emit_answer_event", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "not", "issubclass", "(", "sender", ",", "Answer", ")", "or", "not", "kwargs", "[", "'created'", "]", ":", "return", "logger", "=", "get_events_logger", ...
36.1
14.5
def get_average_color(colors): """Calculate the average color from the list of colors, where each color is a 3-tuple of (r, g, b) values. """ c = reduce(color_reducer, colors) total = len(colors) return tuple(v / total for v in c)
[ "def", "get_average_color", "(", "colors", ")", ":", "c", "=", "reduce", "(", "color_reducer", ",", "colors", ")", "total", "=", "len", "(", "colors", ")", "return", "tuple", "(", "v", "/", "total", "for", "v", "in", "c", ")" ]
35.428571
5
def transform_api_header_authorization(param, value): """Transform a username:password value into a base64 string.""" try: username, password = value.split(":", 1) except ValueError: raise click.BadParameter( "Authorization header needs to be Authorization=username:password", ...
[ "def", "transform_api_header_authorization", "(", "param", ",", "value", ")", ":", "try", ":", "username", ",", "password", "=", "value", ".", "split", "(", "\":\"", ",", "1", ")", "except", "ValueError", ":", "raise", "click", ".", "BadParameter", "(", "\...
37.615385
17.692308
def parameterize(string, separator='-'): """ Replace special characters in a string so that it may be used as part of a 'pretty' URL. Example:: >>> parameterize(u"Donald E. Knuth") 'donald-e-knuth' """ string = transliterate(string) # Turn unwanted chars into the separator ...
[ "def", "parameterize", "(", "string", ",", "separator", "=", "'-'", ")", ":", "string", "=", "transliterate", "(", "string", ")", "# Turn unwanted chars into the separator", "string", "=", "re", ".", "sub", "(", "r\"(?i)[^a-z0-9\\-_]+\"", ",", "separator", ",", ...
36.052632
15.631579
def get_node_by_coord(self, coord, relative=False): """Get a node from a node coord. :param coord: the coordinates of the required node. :type coord: tuple or list :param relative: `True` if coord is relative to the node instance, `False` for absolute coordinates. :...
[ "def", "get_node_by_coord", "(", "self", ",", "coord", ",", "relative", "=", "False", ")", ":", "if", "not", "isinstance", "(", "coord", ",", "(", "list", ",", "tuple", ")", ")", "or", "False", "in", "list", "(", "map", "(", "lambda", "i", ":", "ty...
46.208333
25.041667
def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. """ cj2 = cookiejar_from_dict(cookie_dict) cj.update(cj2) return cj
[ "def", "add_dict_to_cookiejar", "(", "cj", ",", "cookie_dict", ")", ":", "cj2", "=", "cookiejar_from_dict", "(", "cookie_dict", ")", "cj", ".", "update", "(", "cj2", ")", "return", "cj" ]
29.4
17