text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def trailing_stop_loss_replace(self, accountID, orderID, **kwargs): """ Shortcut to replace a pending Trailing Stop Loss Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Take Profit Order to replace kwargs : The arguments to...
[ "def", "trailing_stop_loss_replace", "(", "self", ",", "accountID", ",", "orderID", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "replace", "(", "accountID", ",", "orderID", ",", "order", "=", "TrailingStopLossOrderRequest", "(", "*", "*", "kwar...
33.777778
22.444444
def set_site(): """ This method is part of the prepare_data helper. Sets the site. Default implementation uses localhost. For production settings refine this helper. :return: """ from django.contrib.sites.models import Site from django.conf import settings # Initially set localhost a...
[ "def", "set_site", "(", ")", ":", "from", "django", ".", "contrib", ".", "sites", ".", "models", "import", "Site", "from", "django", ".", "conf", "import", "settings", "# Initially set localhost as default domain", "#", "site", "=", "Site", ".", "objects", "."...
31.666667
11.8
def send_ready(self): """ Returns true if data can be written to this channel without blocking. This means the channel is either closed (so any write attempt would return immediately) or there is at least one byte of space in the outbound buffer. If there is at least one byte of ...
[ "def", "send_ready", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "closed", "or", "self", ".", "eof_sent", ":", "return", "True", "return", "self", ".", "out_window_size", ">", "0", "finally", "...
38.55
20.55
def delete_additional_charge(self, recurring_billing_id): """ Remove an extra charge from an invoice. Args: recurring_billing_id: Identifier of the additional charge. Returns: """ fmt = 'recurringBillItems/{}'.format(recurring_billing_id) return sel...
[ "def", "delete_additional_charge", "(", "self", ",", "recurring_billing_id", ")", ":", "fmt", "=", "'recurringBillItems/{}'", ".", "format", "(", "recurring_billing_id", ")", "return", "self", ".", "client", ".", "_delete", "(", "self", ".", "url", "+", "fmt", ...
30.75
24.083333
def sign(self, data, nonce = None): """ Sign data using the Montgomery private key stored by this XEdDSA instance. :param data: A bytes-like object containing the data to sign. :param nonce: A bytes-like object with length 64 or None. :returns: A bytes-like object encoding the s...
[ "def", "sign", "(", "self", ",", "data", ",", "nonce", "=", "None", ")", ":", "cls", "=", "self", ".", "__class__", "if", "not", "self", ".", "__mont_priv", ":", "raise", "MissingKeyException", "(", "\"Cannot sign using this XEdDSA instance, Montgomery private key...
33.225
26.275
def keyPressEvent( self, event ): """ Handles the Ctrl+C/Ctrl+V events for copy & paste. :param event | <QKeyEvent> """ if ( event.key() == Qt.Key_C and \ event.modifiers() == Qt.ControlModifier ): self.copy() event.accept() ...
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "(", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_C", "and", "event", ".", "modifiers", "(", ")", "==", "Qt", ".", "ControlModifier", ")", ":", "self", ".", "copy", "(", "...
30.875
14.625
def gravitational_force(position_a, mass_a, position_b, mass_b): """Returns the gravitational force between the two bodies a and b.""" distance = distance_between(position_a, position_b) # Calculate the direction and magnitude of the force. angle = math.atan2(position_a[1] - position_b[1], position_a[0...
[ "def", "gravitational_force", "(", "position_a", ",", "mass_a", ",", "position_b", ",", "mass_b", ")", ":", "distance", "=", "distance_between", "(", "position_a", ",", "position_b", ")", "# Calculate the direction and magnitude of the force.", "angle", "=", "math", "...
46.571429
17.642857
def determine_override_options(selected_options: tuple, override_opts: DictLike, set_of_possible_options: tuple = ()) -> Dict[str, Any]: """ Recursively extract the dict described in override_options(). In particular, this searches for selected options in the override_opts dict. It stores only the override...
[ "def", "determine_override_options", "(", "selected_options", ":", "tuple", ",", "override_opts", ":", "DictLike", ",", "set_of_possible_options", ":", "tuple", "=", "(", ")", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "override_dict", ":", "Dict", ...
64.319149
36.361702
def activate_left(self, token): """Make a copy of the received token and call `_activate_left`.""" watchers.MATCHER.debug( "Node <%s> activated left with token %r", self, token) return self._activate_left(token.copy())
[ "def", "activate_left", "(", "self", ",", "token", ")", ":", "watchers", ".", "MATCHER", ".", "debug", "(", "\"Node <%s> activated left with token %r\"", ",", "self", ",", "token", ")", "return", "self", ".", "_activate_left", "(", "token", ".", "copy", "(", ...
50
10.4
def extract_bad_ami(e): """Handle various client side errors when describing images""" msg = e.response['Error']['Message'] error = e.response['Error']['Code'] e_ami_ids = None if error == 'InvalidAMIID.NotFound': e_ami_ids = [ e_ami_id.strip() for e_a...
[ "def", "extract_bad_ami", "(", "e", ")", ":", "msg", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Message'", "]", "error", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "e_ami_ids", "=", "None", "if", "error", "==", ...
45.642857
12.642857
def _reduce_dynamic_table(self, new_entry_size=0): # type: (int) -> None """_reduce_dynamic_table evicts entries from the dynamic table until it fits in less than the current size limit. The optional parameter, new_entry_size, allows the resize to happen so that a new entry of this ...
[ "def", "_reduce_dynamic_table", "(", "self", ",", "new_entry_size", "=", "0", ")", ":", "# type: (int) -> None", "assert", "(", "new_entry_size", ">=", "0", ")", "cur_sz", "=", "len", "(", "self", ")", "dyn_tbl_sz", "=", "len", "(", "self", ".", "_dynamic_ta...
51
19.555556
def interprocess_locked(path): """Acquires & releases a interprocess lock around call into decorated function.""" lock = InterProcessLock(path) def decorator(f): @six.wraps(f) def wrapper(*args, **kwargs): with lock: return f(*args, **kwargs) re...
[ "def", "interprocess_locked", "(", "path", ")", ":", "lock", "=", "InterProcessLock", "(", "path", ")", "def", "decorator", "(", "f", ")", ":", "@", "six", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")...
21.1875
19.6875
def parse(obj, required_properties=None, additional_properties=None, ignore_optional_property_errors=None): """Try to parse the given ``obj`` as a validator instance. :param obj: The object to be parsed. If it is a...: - :py:class:`Validator` instance, return it. - :py:class:`Validat...
[ "def", "parse", "(", "obj", ",", "required_properties", "=", "None", ",", "additional_properties", "=", "None", ",", "ignore_optional_property_errors", "=", "None", ")", ":", "if", "not", "(", "required_properties", "is", "additional_properties", "is", "ignore_optio...
43.811321
24.216981
def compute_attention_component(antecedent, total_depth, filter_width=1, padding="VALID", name="c", vars_3d_num_heads=0, layer_c...
[ "def", "compute_attention_component", "(", "antecedent", ",", "total_depth", ",", "filter_width", "=", "1", ",", "padding", "=", "\"VALID\"", ",", "name", "=", "\"c\"", ",", "vars_3d_num_heads", "=", "0", ",", "layer_collection", "=", "None", ")", ":", "if", ...
41.392157
15.431373
def t_escaped_TAB_CHAR(self, t): r'\x74' # 't' t.lexer.pop_state() t.value = unichr(0x0009) return t
[ "def", "t_escaped_TAB_CHAR", "(", "self", ",", "t", ")", ":", "# 't'", "t", ".", "lexer", ".", "pop_state", "(", ")", "t", ".", "value", "=", "unichr", "(", "0x0009", ")", "return", "t" ]
25.8
14.2
def save(self, path: str): """ Save lexicon in Numpy array format. Lexicon will be specific to Sockeye model. :param path: Path to Numpy array output file. """ with open(path, 'wb') as out: np.save(out, self.lex) logger.info("Saved top-k lexicon to \"%s\"", ...
[ "def", "save", "(", "self", ",", "path", ":", "str", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "out", ":", "np", ".", "save", "(", "out", ",", "self", ".", "lex", ")", "logger", ".", "info", "(", "\"Saved top-k lexicon to \\\"%...
35.222222
15.666667
def rename(self, oldkey, newkey): """ Change a keyname to another, without changing position in sequence. Implemented so that transformations can be made on keys, as well as on values. (used by encode and decode) Also renames comments. """ if oldkey in self.scal...
[ "def", "rename", "(", "self", ",", "oldkey", ",", "newkey", ")", ":", "if", "oldkey", "in", "self", ".", "scalars", ":", "the_list", "=", "self", ".", "scalars", "elif", "oldkey", "in", "self", ".", "sections", ":", "the_list", "=", "self", ".", "sec...
34.428571
12.285714
def get_ethernet_networks(self): """ Gets a list of associated ethernet networks of an uplink set. Args: id_or_uri: Can be either the uplink set id or the uplink set uri. Returns: list: Associated ethernet networks. """ network_uris = self.data.g...
[ "def", "get_ethernet_networks", "(", "self", ")", ":", "network_uris", "=", "self", ".", "data", ".", "get", "(", "'networkUris'", ")", "networks", "=", "[", "]", "if", "network_uris", ":", "for", "uri", "in", "network_uris", ":", "networks", ".", "append"...
31.4375
19.4375
def save_json(obj, filename, **kwargs): """ Save an object as a JSON file. Args: obj: The object to save. Must be JSON-serializable. filename: Path to the output file. **kwargs: Additional arguments to `json.dump`. """ with open(filename, 'w', encoding='utf-8') as f: ...
[ "def", "save_json", "(", "obj", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "json", ".", "dump", "(", "obj", ",", "f", ",", "*", "*", "kw...
28.166667
14.166667
def get_samples(self, init_points_count, criterion='center'): """ Generates required amount of sample points :param init_points_count: Number of samples to generate :param criterion: For details of the effect of this parameter, please refer to pyDOE.lhs documentation ...
[ "def", "get_samples", "(", "self", ",", "init_points_count", ",", "criterion", "=", "'center'", ")", ":", "samples", "=", "np", ".", "empty", "(", "(", "init_points_count", ",", "self", ".", "space", ".", "dimensionality", ")", ")", "# Use random design to fil...
44.068966
24.206897
def mkzip(source_dir, output_filename): '''Usage: p = r'D:\auto\env\ttest\ins\build\lib\rock4\softtest\support' mkzip(os.path.join(p, "appiumroot"),os.path.join(p, "appiumroot.zip")) unzip(os.path.join(p, "appiumroot.zip"),os.path.join(p, "appiumroot2")) ''' ...
[ "def", "mkzip", "(", "source_dir", ",", "output_filename", ")", ":", "zipf", "=", "zipfile", ".", "ZipFile", "(", "output_filename", ",", "'w'", ",", "zipfile", ".", "zlib", ".", "DEFLATED", ")", "pre_len", "=", "len", "(", "os", ".", "path", ".", "dir...
52.642857
22.785714
def wrap_traceback(traceback): """ For internal use only (until further notice) """ if email().format == 'html': try: from pygments import highlight from pygments.lexers import PythonTracebackLexer from pygments.formatters import HtmlFormatter with...
[ "def", "wrap_traceback", "(", "traceback", ")", ":", "if", "email", "(", ")", ".", "format", "==", "'html'", ":", "try", ":", "from", "pygments", "import", "highlight", "from", "pygments", ".", "lexers", "import", "PythonTracebackLexer", "from", "pygments", ...
29.909091
16.727273
def __get_connection_SNS(): """ Ensure connection to SNS """ region = get_global_option('region') try: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to SNS using ' ...
[ "def", "__get_connection_SNS", "(", ")", ":", "region", "=", "get_global_option", "(", "'region'", ")", "try", ":", "if", "(", "get_global_option", "(", "'aws_access_key_id'", ")", "and", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", ":", "logger"...
36.166667
17.366667
def get_engine_from_session(dbsession: Session) -> Engine: """ Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`. """ engine = dbsession.bind assert isinstance(engine, Engine) return engine
[ "def", "get_engine_from_session", "(", "dbsession", ":", "Session", ")", "->", "Engine", ":", "engine", "=", "dbsession", ".", "bind", "assert", "isinstance", "(", "engine", ",", "Engine", ")", "return", "engine" ]
32.571429
13.142857
def CheckForHeaderGuard(filename, clean_lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance...
[ "def", "CheckForHeaderGuard", "(", "filename", ",", "clean_lines", ",", "error", ")", ":", "# Don't check for header guards if there are error suppression", "# comments somewhere in this file.", "#", "# Because this is silencing a warning for a nonexistent line, we", "# only support the ...
35.950495
21.306931
def revoke_permission(user, permission_name): """ Revoke a specified permission from a user. Permissions are only revoked if they are in the scope any of the user's roles. If the permission is out of scope, a RolePermissionScopeException is raised. """ roles = get_user_roles(user) for ...
[ "def", "revoke_permission", "(", "user", ",", "permission_name", ")", ":", "roles", "=", "get_user_roles", "(", "user", ")", "for", "role", "in", "roles", ":", "if", "permission_name", "in", "role", ".", "permission_names_list", "(", ")", ":", "permission", ...
33.263158
17.684211
def build_diagonals(self): """ Builds the diagonals for the coefficient array """ ########################################################## # INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY # ########################################################## # Roll to keep the pro...
[ "def", "build_diagonals", "(", "self", ")", ":", "##########################################################\r", "# INCORPORATE BOUNDARY CONDITIONS INTO COEFFICIENT ARRAY #\r", "##########################################################\r", "# Roll to keep the proper coefficients at the proper pla...
42.470588
22.941176
def _update_enabled(self, name, enabled_value): ''' Update whether an individual beacon is enabled ''' if isinstance(self.opts['beacons'][name], dict): # Backwards compatibility self.opts['beacons'][name]['enabled'] = enabled_value else: enabl...
[ "def", "_update_enabled", "(", "self", ",", "name", ",", "enabled_value", ")", ":", "if", "isinstance", "(", "self", ".", "opts", "[", "'beacons'", "]", "[", "name", "]", ",", "dict", ")", ":", "# Backwards compatibility", "self", ".", "opts", "[", "'bea...
42
24.428571
def _needs_dependencies(p_function): """ A decorator that triggers the population of the dependency tree in a TodoList (and other administration). The decorator should be applied to methods of TodoList that require dependency information. """ def build_dependency_information(p_todolist): ...
[ "def", "_needs_dependencies", "(", "p_function", ")", ":", "def", "build_dependency_information", "(", "p_todolist", ")", ":", "for", "todo", "in", "p_todolist", ".", "_todos", ":", "p_todolist", ".", "_register_todo", "(", "todo", ")", "def", "inner", "(", "s...
31.863636
17.045455
def _compute_and_transfer_to_final_run(self, process_name, start_timeperiod, end_timeperiod, job_record): """ method computes new unit_of_work and transfers the job to STATE_FINAL_RUN it also shares _fuzzy_ DuplicateKeyError logic from _compute_and_transfer_to_progress method""" source_collectio...
[ "def", "_compute_and_transfer_to_final_run", "(", "self", ",", "process_name", ",", "start_timeperiod", ",", "end_timeperiod", ",", "job_record", ")", ":", "source_collection_name", "=", "context", ".", "process_context", "[", "process_name", "]", ".", "source", "star...
73.454545
32.909091
def release(self): """Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after ...
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "__owner", "!=", "_get_ident", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot release un-acquired lock\"", ")", "self", ".", "__count", "=", "count", "=", "self", ".", "__count", "-", "1",...
39.62963
22.407407
def get_info(certificate_id, returncertificate=False, returntype=None): ''' Retrieves information about the requested SSL certificate. Returns a dictionary of information about the SSL certificate with two keys: - **ssl** - Contains the metadata information - **certificate** - Contains the details ...
[ "def", "get_info", "(", "certificate_id", ",", "returncertificate", "=", "False", ",", "returntype", "=", "None", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.ssl.getinfo'", ")", "opts", "[", "'certificateID'...
35.918367
27.428571
def update_policy(self,defaultHeaders): """ rewrite update policy so that additional pins are added and not overwritten """ if self.inputs is not None: for k,v in defaultHeaders.items(): if k not in self.inputs: self.inputs[k] = v if k == 'pins': self.inputs[k] = self.inputs[k] + defaultHeaders...
[ "def", "update_policy", "(", "self", ",", "defaultHeaders", ")", ":", "if", "self", ".", "inputs", "is", "not", "None", ":", "for", "k", ",", "v", "in", "defaultHeaders", ".", "items", "(", ")", ":", "if", "k", "not", "in", "self", ".", "inputs", "...
33.181818
13.818182
def write_data(worksheet, data): """Writes data into worksheet. Args: worksheet: worksheet to write into data: data to be written """ if not data: return if isinstance(data, list): rows = data else: rows = [data] if isinstance(rows[0], dict): ...
[ "def", "write_data", "(", "worksheet", ",", "data", ")", ":", "if", "not", "data", ":", "return", "if", "isinstance", "(", "data", ",", "list", ")", ":", "rows", "=", "data", "else", ":", "rows", "=", "[", "data", "]", "if", "isinstance", "(", "row...
29
19.535714
def _jws_signature(signdata, privkey, algorithm): """ Produce a base64-encoded JWS signature based on the signdata specified, the privkey instance, and the algorithm passed. """ signature = algorithm.sign(privkey, signdata) return base64url_encode(signature)
[ "def", "_jws_signature", "(", "signdata", ",", "privkey", ",", "algorithm", ")", ":", "signature", "=", "algorithm", ".", "sign", "(", "privkey", ",", "signdata", ")", "return", "base64url_encode", "(", "signature", ")" ]
39.428571
9.428571
def cp_single_file(self, pool, source, target, delete_source): '''Copy a single file or a directory by adding a task into queue''' if source[-1] == PATH_SEP: if self.opt.recursive: basepath = S3URL(source).path for f in (f for f in self.s3walk(source) if not f['is_dir']): pool.co...
[ "def", "cp_single_file", "(", "self", ",", "pool", ",", "source", ",", "target", ",", "delete_source", ")", ":", "if", "source", "[", "-", "1", "]", "==", "PATH_SEP", ":", "if", "self", ".", "opt", ".", "recursive", ":", "basepath", "=", "S3URL", "("...
50.909091
26.363636
def command_mount(self, system_id, *system_ids): """Mounts the specified sftp system, unless it's already mounted. Usage: sftpman mount {id}.. """ system_ids = (system_id,) + system_ids has_failed = False for system_id in system_ids: try: syste...
[ "def", "command_mount", "(", "self", ",", "system_id", ",", "*", "system_ids", ")", ":", "system_ids", "=", "(", "system_id", ",", ")", "+", "system_ids", "has_failed", "=", "False", "for", "system_id", "in", "system_ids", ":", "try", ":", "system", "=", ...
46.666667
16.190476
def _send_content(self, content, content_type, code=200): """Send content to client.""" assert isinstance(content, bytes) self.send_response(code) self.send_header('Content-Type', content_type) self.send_header('Content-Length', str(len(content))) self.end_headers() self.wfile.write(content)
[ "def", "_send_content", "(", "self", ",", "content", ",", "content_type", ",", "code", "=", "200", ")", ":", "assert", "isinstance", "(", "content", ",", "bytes", ")", "self", ".", "send_response", "(", "code", ")", "self", ".", "send_header", "(", "'Con...
39.125
11
def _input_file_as_lines(cls, session: AppSession): '''Read lines from input file and return them.''' if session.args.input_file == sys.stdin: input_file = session.args.input_file else: reader = codecs.getreader(session.args.local_encoding or 'utf-8') input_fi...
[ "def", "_input_file_as_lines", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "if", "session", ".", "args", ".", "input_file", "==", "sys", ".", "stdin", ":", "input_file", "=", "session", ".", "args", ".", "input_file", "else", ":", "reader", ...
41.666667
19.888889
def append_with(self, obj, **properties): '''Add an item to the dictionary with the given metadata properties''' for prop, val in properties.items(): val = self.serialize(val) self._meta.setdefault(prop, {}).setdefault(val, []).append(obj) self.append(obj)
[ "def", "append_with", "(", "self", ",", "obj", ",", "*", "*", "properties", ")", ":", "for", "prop", ",", "val", "in", "properties", ".", "items", "(", ")", ":", "val", "=", "self", ".", "serialize", "(", "val", ")", "self", ".", "_meta", ".", "s...
49.833333
16.166667
def sort_stats(self, *args): """ Sort the tracked objects according to the supplied criteria. The argument is a string identifying the basis of a sort (example: 'size' or 'classname'). When more than one key is provided, then additional keys are used as secondary criteria when th...
[ "def", "sort_stats", "(", "self", ",", "*", "args", ")", ":", "criteria", "=", "(", "'classname'", ",", "'tsize'", ",", "'birth'", ",", "'death'", ",", "'name'", ",", "'repr'", ",", "'size'", ")", "if", "not", "set", "(", "criteria", ")", ".", "issup...
37.474576
22.118644
def GMailer(recipients, username, password, subject='Log message from lggr.py'): """ Sends messages as emails to the given list of recipients, from a GMail account. """ import smtplib srvr = smtplib.SMTP('smtp.gmail.com', 587) srvr.ehlo() srvr.starttls() srvr.ehlo() srvr.login(userna...
[ "def", "GMailer", "(", "recipients", ",", "username", ",", "password", ",", "subject", "=", "'Log message from lggr.py'", ")", ":", "import", "smtplib", "srvr", "=", "smtplib", ".", "SMTP", "(", "'smtp.gmail.com'", ",", "587", ")", "srvr", ".", "ehlo", "(", ...
31.423077
20.423077
def display_completions_like_readline(event): """ Key binding handler for readline-style tab completion. This is meant to be as similar as possible to the way how readline displays completions. Generate the completions immediately (blocking) and display them above the prompt in columns. Us...
[ "def", "display_completions_like_readline", "(", "event", ")", ":", "# Request completions.", "b", "=", "event", ".", "current_buffer", "if", "b", ".", "completer", "is", "None", ":", "return", "complete_event", "=", "CompleteEvent", "(", "completion_requested", "="...
35.088235
20.617647
def robots(request): """Return a simple "don't index me" robots.txt file.""" resp = request.response resp.status = '200 OK' resp.content_type = 'text/plain' resp.body = """ User-Agent: * Disallow: / """ return resp
[ "def", "robots", "(", "request", ")", ":", "resp", "=", "request", ".", "response", "resp", ".", "status", "=", "'200 OK'", "resp", ".", "content_type", "=", "'text/plain'", "resp", ".", "body", "=", "\"\"\"\nUser-Agent: *\nDisallow: /\n\"\"\"", "return", "resp"...
20.818182
15.636364
def readcfg(filepath, section): """ Reads the configuration file. If section is not available, calls create_oedb_config_file to add the new section to an existing config.ini. Parameters ---------- filepath : str Absolute path of config file including the filename itself section...
[ "def", "readcfg", "(", "filepath", ",", "section", ")", ":", "cfg", "=", "cp", ".", "ConfigParser", "(", ")", "cfg", ".", "read", "(", "filepath", ")", "if", "not", "cfg", ".", "has_section", "(", "section", ")", ":", "print", "(", "'The section \"{sec...
29.592593
20.962963
def add_property_to_response(self, code='200', prop_name='data', **kwargs): """Add a property (http://json-schema.org/latest/json-schema-validation.html#anchor64) # noqa: E501 to the schema of the response identified by the code""" self['responses'] \ .setdefault(str(code), self._ne...
[ "def", "add_property_to_response", "(", "self", ",", "code", "=", "'200'", ",", "prop_name", "=", "'data'", ",", "*", "*", "kwargs", ")", ":", "self", "[", "'responses'", "]", ".", "setdefault", "(", "str", "(", "code", ")", ",", "self", ".", "_new_ope...
55.444444
10.666667
def change_db_user_password(username, password): """Change a db user's password.""" sql = "ALTER USER %s WITH PASSWORD '%s'" % (username, password) excute_query(sql, use_sudo=True)
[ "def", "change_db_user_password", "(", "username", ",", "password", ")", ":", "sql", "=", "\"ALTER USER %s WITH PASSWORD '%s'\"", "%", "(", "username", ",", "password", ")", "excute_query", "(", "sql", ",", "use_sudo", "=", "True", ")" ]
37.8
15.8
def set_text(self, text): """Sets the text attribute of the payload :param text: (str) Text of the message :return: None """ log = logging.getLogger(self.cls_logger + '.set_text') if not isinstance(text, basestring): msg = 'text arg must be a string' ...
[ "def", "set_text", "(", "self", ",", "text", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.set_text'", ")", "if", "not", "isinstance", "(", "text", ",", "basestring", ")", ":", "msg", "=", "'text arg must be a...
35.153846
12.076923
def render_it(self, kind, num, with_tag=False, glyph=''): ''' render, no user logged in ''' all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.re...
[ "def", "render_it", "(", "self", ",", "kind", ",", "num", ",", "with_tag", "=", "False", ",", "glyph", "=", "''", ")", ":", "all_cats", "=", "MPost", ".", "query_recent", "(", "num", ",", "kind", "=", "kind", ")", "kwd", "=", "{", "'with_tag'", ":"...
34.307692
16.153846
def parse_response(response): """ parse response and return a dictionary if the content type. is json/application. :param response: HTTPRequest :return dictionary for json content type otherwise response body """ if response.headers.get('Content-Type', JSON_TYPE).startswith(JSON_TYPE): ...
[ "def", "parse_response", "(", "response", ")", ":", "if", "response", ".", "headers", ".", "get", "(", "'Content-Type'", ",", "JSON_TYPE", ")", ".", "startswith", "(", "JSON_TYPE", ")", ":", "return", "ResponseObject", "(", "json", ".", "loads", "(", "resp...
36.363636
16.545455
def ifind_first_object(self, ObjectClass, **kwargs): """ Retrieve the first object of type ``ObjectClass``, matching the specified filters in ``**kwargs`` -- case insensitive. | If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object(). | If USER_IFIND_MODE is 'if...
[ "def", "ifind_first_object", "(", "self", ",", "ObjectClass", ",", "*", "*", "kwargs", ")", ":", "# Call regular find() if USER_IFIND_MODE is nocase_collation", "if", "self", ".", "user_manager", ".", "USER_IFIND_MODE", "==", "'nocase_collation'", ":", "return", "self",...
50.647059
22.117647
def visit_Call(self, node): """ Transform call site to have normal function call. Examples -------- For methods: >> a = [1, 2, 3] >> a.append(1) Becomes >> __list__.append(a, 1) For functions: >> __builtin__.dict.fromkeys([1, ...
[ "def", "visit_Call", "(", "self", ",", "node", ")", ":", "node", "=", "self", ".", "generic_visit", "(", "node", ")", "# Only attributes function can be Pythonic and should be normalized", "if", "isinstance", "(", "node", ".", "func", ",", "ast", ".", "Attribute",...
40.666667
21.333333
def disable_svc_check(self, service): """Disable checks for a service Format of the line that triggers function call:: DISABLE_SVC_CHECK;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service :return: None ...
[ "def", "disable_svc_check", "(", "self", ",", "service", ")", ":", "if", "service", ".", "active_checks_enabled", ":", "service", ".", "disable_active_checks", "(", "self", ".", "daemon", ".", "checks", ")", "service", ".", "modified_attributes", "|=", "DICT_MOD...
39.666667
15.4
def is_email(data): """ Check if given data string is an email. Usage:: >>> is_email("john.doe@domain.com") True >>> is_email("john.doe:domain.com") False :param data: Data to check. :type data: unicode :return: Is email. :rtype: bool """ if re.mat...
[ "def", "is_email", "(", "data", ")", ":", "if", "re", ".", "match", "(", "r\"[\\w.%+-]+@[\\w.]+\\.[a-zA-Z]{2,4}\"", ",", "data", ")", ":", "LOGGER", ".", "debug", "(", "\"> {0}' is matched as email.\"", ".", "format", "(", "data", ")", ")", "return", "True", ...
22.956522
21.043478
def _xy_locs(mask): """Mask should be a set of bools from comparison with a feature layer.""" y, x = mask.nonzero() return list(zip(x, y))
[ "def", "_xy_locs", "(", "mask", ")", ":", "y", ",", "x", "=", "mask", ".", "nonzero", "(", ")", "return", "list", "(", "zip", "(", "x", ",", "y", ")", ")" ]
35.25
13.5
def to_boolean(value, ctx): """ Tries conversion of any value to a boolean """ if isinstance(value, bool): return value elif isinstance(value, int): return value != 0 elif isinstance(value, Decimal): return value != Decimal(0) elif isinstance(value, str): valu...
[ "def", "to_boolean", "(", "value", ",", "ctx", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "int", ")", ":", "return", "value", "!=", "0", "elif", "isinstance", "(", "v...
30
14.4
def trimSegments(self, minPermanence=None, minNumSyns=None): """ This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. :param minPermanence: (float) Any syn whose permanence is 0 or < ``mi...
[ "def", "trimSegments", "(", "self", ",", "minPermanence", "=", "None", ",", "minNumSyns", "=", "None", ")", ":", "# Fill in defaults", "if", "minPermanence", "is", "None", ":", "minPermanence", "=", "self", ".", "connectedPerm", "if", "minNumSyns", "is", "None...
39.918919
17.162162
def _add_task(self, task): '''Add an already existing task to the task group.''' if hasattr(task, '_task_group'): raise RuntimeError('task is already part of a group') if self._closed: raise RuntimeError('task group is closed') task._task_group = self if t...
[ "def", "_add_task", "(", "self", ",", "task", ")", ":", "if", "hasattr", "(", "task", ",", "'_task_group'", ")", ":", "raise", "RuntimeError", "(", "'task is already part of a group'", ")", "if", "self", ".", "_closed", ":", "raise", "RuntimeError", "(", "'t...
38
13.5
def upload(ctx, release, rebuild): """ Uploads distribuition files to pypi or pypitest. """ dist_path = Path(DIST_PATH) if rebuild is False: if not dist_path.exists() or not list(dist_path.glob('*')): print("No distribution files found. Please run 'build' command first") retu...
[ "def", "upload", "(", "ctx", ",", "release", ",", "rebuild", ")", ":", "dist_path", "=", "Path", "(", "DIST_PATH", ")", "if", "rebuild", "is", "False", ":", "if", "not", "dist_path", ".", "exists", "(", ")", "or", "not", "list", "(", "dist_path", "."...
31.8
21.3
def emit(self): """Get a mapping from a transcript :return: One random Transcript sequence :rtype: sequence """ i = self.options.rand.get_weighted_random_index(self._weights) return self._transcriptome.transcripts[i]
[ "def", "emit", "(", "self", ")", ":", "i", "=", "self", ".", "options", ".", "rand", ".", "get_weighted_random_index", "(", "self", ".", "_weights", ")", "return", "self", ".", "_transcriptome", ".", "transcripts", "[", "i", "]" ]
29.25
14.875
def stayOpen(self): """optional dialog restore""" if not self._wantToClose: self.show() self.setGeometry(self._geometry)
[ "def", "stayOpen", "(", "self", ")", ":", "if", "not", "self", ".", "_wantToClose", ":", "self", ".", "show", "(", ")", "self", ".", "setGeometry", "(", "self", ".", "_geometry", ")" ]
32
9.2
def to_dict_list(df, use_ordered_dict=True): """Transform each row to dict, and put them into a list. **中文文档** 将 ``pandas.DataFrame`` 转换成一个字典的列表。列表的长度与行数相同, 其中 每一个字典相当于表中的一行, 相当于一个 ``pandas.Series`` 对象。 """ if use_ordered_dict: dict = OrderedDict columns = df.columns data = li...
[ "def", "to_dict_list", "(", "df", ",", "use_ordered_dict", "=", "True", ")", ":", "if", "use_ordered_dict", ":", "dict", "=", "OrderedDict", "columns", "=", "df", ".", "columns", "data", "=", "list", "(", ")", "for", "tp", "in", "itertuple", "(", "df", ...
24.875
17.4375
def intervalleftjoin(left, right, lstart='start', lstop='stop', rstart='start', rstop='stop', lkey=None, rkey=None, include_stop=False, missing=None, lprefix=None, rprefix=None): """ Like :func:`petl.transform.intervals.intervaljoin` but rows from the left table wi...
[ "def", "intervalleftjoin", "(", "left", ",", "right", ",", "lstart", "=", "'start'", ",", "lstop", "=", "'stop'", ",", "rstart", "=", "'start'", ",", "rstop", "=", "'stop'", ",", "lkey", "=", "None", ",", "rkey", "=", "None", ",", "include_stop", "=", ...
48.017241
17.362069
def _open_connection(self): """Open a connection to the easyfire unit.""" if (self._mode == PROP_MODE_SERIAL): self._serial = serial.Serial(self._serial_device, self._serial_speed) elif (self._mode == PROP_MODE_TCP): self._socket = socket.socket(socket.AF_INET, socket.SOC...
[ "def", "_open_connection", "(", "self", ")", ":", "if", "(", "self", ".", "_mode", "==", "PROP_MODE_SERIAL", ")", ":", "self", ".", "_serial", "=", "serial", ".", "Serial", "(", "self", ".", "_serial_device", ",", "self", ".", "_serial_speed", ")", "elif...
52.777778
14.222222
def get_build_work_items_refs_from_commits(self, commit_ids, project, build_id, top=None): """GetBuildWorkItemsRefsFromCommits. Gets the work items associated with a build, filtered to specific commits. :param [str] commit_ids: A comma-delimited list of commit IDs. :param str project: Pr...
[ "def", "get_build_work_items_refs_from_commits", "(", "self", ",", "commit_ids", ",", "project", ",", "build_id", ",", "top", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "...
57.64
24
def register_drop(self, task, event_details=None): """ :meth:`.WSimpleTrackerStorage.register_drop` method implementation """ if self.record_drop() is True: record_type = WTrackerEvents.drop record = WSimpleTrackerStorage.Record(record_type, task, event_details=event_details) self.__store_record(record)
[ "def", "register_drop", "(", "self", ",", "task", ",", "event_details", "=", "None", ")", ":", "if", "self", ".", "record_drop", "(", ")", "is", "True", ":", "record_type", "=", "WTrackerEvents", ".", "drop", "record", "=", "WSimpleTrackerStorage", ".", "R...
44.714286
11.428571
def export(self, fmt, filename=None, **kargs): """ export *MDF* to other formats. The *MDF* file name is used is available, else the *filename* argument must be provided. The *pandas* export option was removed. you should use the method *to_dataframe* instead. Parameters ...
[ "def", "export", "(", "self", ",", "fmt", ",", "filename", "=", "None", ",", "*", "*", "kargs", ")", ":", "from", "time", "import", "perf_counter", "as", "pc", "header_items", "=", "(", "\"date\"", ",", "\"time\"", ",", "\"author\"", ",", "\"department\"...
38.512238
20.232517
def _baseattrs(self): """A dict of members expressed in literals""" result = super()._baseattrs result["static_spaces"] = self.static_spaces._baseattrs result["dynamic_spaces"] = self.dynamic_spaces._baseattrs result["cells"] = self.cells._baseattrs result["refs"] = self...
[ "def", "_baseattrs", "(", "self", ")", ":", "result", "=", "super", "(", ")", ".", "_baseattrs", "result", "[", "\"static_spaces\"", "]", "=", "self", ".", "static_spaces", ".", "_baseattrs", "result", "[", "\"dynamic_spaces\"", "]", "=", "self", ".", "dyn...
32.133333
19
def lsr_top1(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for top-1 data (see :ref:`data-top1`). The argument ``initial_params`` can be used to iteratively refine an e...
[ "def", "lsr_top1", "(", "n_items", ",", "data", ",", "alpha", "=", "0.0", ",", "initial_params", "=", "None", ")", ":", "weights", ",", "chain", "=", "_init_lsr", "(", "n_items", ",", "alpha", ",", "initial_params", ")", "for", "winner", ",", "losers", ...
35.973684
20.368421
def get_metrics(self, timestamp): """Get a Metric for each registered view. Convert each registered view's associated `ViewData` into a `Metric` to be exported. :type timestamp: :class: `datetime.datetime` :param timestamp: The timestamp to use for metric conversions, usually ...
[ "def", "get_metrics", "(", "self", ",", "timestamp", ")", ":", "for", "vdl", "in", "self", ".", "_measure_to_view_data_list_map", ".", "values", "(", ")", ":", "for", "vd", "in", "vdl", ":", "metric", "=", "metric_utils", ".", "view_data_to_metric", "(", "...
38.470588
21.529412
def video(request, video_id): """ Displays a video in an embed player """ # Check video availability # Available states are: processing api = Api() api.authenticate() availability = api.check_upload_status(video_id) if availability is not True: # Video is not available ...
[ "def", "video", "(", "request", ",", "video_id", ")", ":", "# Check video availability", "# Available states are: processing", "api", "=", "Api", "(", ")", "api", ".", "authenticate", "(", ")", "availability", "=", "api", ".", "check_upload_status", "(", "video_id...
33.875
19.325
def check_url(url): """ Function that verifies that the string passed is a valid url. Original regex author Diego Perini (http://www.iport.it) regex ported to Python by adamrofer (https://github.com/adamrofer) Used under MIT license. :param url: :return: Nothing """ URL_REGEX = re....
[ "def", "check_url", "(", "url", ")", ":", "URL_REGEX", "=", "re", ".", "compile", "(", "u\"^\"", "u\"(?:(?:https?|ftp)://)\"", "u\"(?:\\S+(?::\\S*)?@)?\"", "u\"(?:\"", "u\"(?!(?:10|127)(?:\\.\\d{1,3}){3})\"", "u\"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})\"", "u\"(?!172\\.(?:1...
29.647059
18.764706
def rest_del(self, url, params=None, session=None, verify=True, cert=None): """ Perform a DELETE request to url with requests.session """ res = session.delete(url, params=params, verify=verify, cert=cert) return res.text, res.status_code
[ "def", "rest_del", "(", "self", ",", "url", ",", "params", "=", "None", ",", "session", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ")", ":", "res", "=", "session", ".", "delete", "(", "url", ",", "params", "=", "params", "...
45.333333
15
def _to_corrected_pandas_type(dt): """ When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong. This method gets the corrected data type for Pandas if that type may be inferred uncorrectly. """ import numpy as np if type(dt) == ByteType: return np.int8 ...
[ "def", "_to_corrected_pandas_type", "(", "dt", ")", ":", "import", "numpy", "as", "np", "if", "type", "(", "dt", ")", "==", "ByteType", ":", "return", "np", ".", "int8", "elif", "type", "(", "dt", ")", "==", "ShortType", ":", "return", "np", ".", "in...
31.625
18.25
def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) self.K_up_to_date = False self.k.free_params = value[:self.k.num_free_params] self.noise_k.free_params = value[self.k.num_free_p...
[ "def", "free_params", "(", "self", ",", "value", ")", ":", "value", "=", "scipy", ".", "asarray", "(", "value", ",", "dtype", "=", "float", ")", "self", ".", "K_up_to_date", "=", "False", "self", ".", "k", ".", "free_params", "=", "value", "[", ":", ...
55.555556
20.888889
def decompose( cls, heights, t = None, t0 = None, interval = None, constituents = constituent.noaa, initial = None, n_period = 2, callback = None, full_output = False ): """ Return an instance of Tide which has been fitted to a series of tidal o...
[ "def", "decompose", "(", "cls", ",", "heights", ",", "t", "=", "None", ",", "t0", "=", "None", ",", "interval", "=", "None", ",", "constituents", "=", "constituent", ".", "noaa", ",", "initial", "=", "None", ",", "n_period", "=", "2", ",", "callback"...
34.360294
22.345588
def method_codes_to_geomagia(magic_method_codes,geomagia_table): """ Looks at the MagIC method code list and returns the correct GEOMAGIA code number depending on the method code list and the GEOMAGIA table specified. Returns O, GEOMAGIA's "Not specified" value, if no match. When mutiple codes are mat...
[ "def", "method_codes_to_geomagia", "(", "magic_method_codes", ",", "geomagia_table", ")", ":", "codes", "=", "magic_method_codes", "geomagia", "=", "geomagia_table", ".", "lower", "(", ")", "geomagia_code", "=", "'0'", "if", "geomagia", "==", "'alteration_monit_corr'"...
33.326733
14.079208
def hget(self, key): """Read data from Redis for the provided key. Args: key (string): The key to read in Redis. Returns: (any): The response data from Redis. """ data = self.r.hget(self.hash, key) if data is not None and not isinstance(data, str...
[ "def", "hget", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "r", ".", "hget", "(", "self", ".", "hash", ",", "key", ")", "if", "data", "is", "not", "None", "and", "not", "isinstance", "(", "data", ",", "str", ")", ":", "data", ...
30.076923
17.769231
def _footer_start_thread(self, text, time): """Display given text in the footer. Clears after <time> seconds """ footerwid = urwid.AttrMap(urwid.Text(text), 'footer') self.top.footer = footerwid load_thread = Thread(target=self._loading_thread, args=(time,)) load_thread....
[ "def", "_footer_start_thread", "(", "self", ",", "text", ",", "time", ")", ":", "footerwid", "=", "urwid", ".", "AttrMap", "(", "urwid", ".", "Text", "(", "text", ")", ",", "'footer'", ")", "self", ".", "top", ".", "footer", "=", "footerwid", "load_thr...
39.222222
13.333333
def gaussian(cls, mu=0, sigma=1): ''' :mu: mean :sigma: standard deviation :return: Point subclass Returns a point whose coordinates are picked from a Gaussian distribution with mean 'mu' and standard deviation 'sigma'. See random.gauss for further explanati...
[ "def", "gaussian", "(", "cls", ",", "mu", "=", "0", ",", "sigma", "=", "1", ")", ":", "return", "cls", "(", "random", ".", "gauss", "(", "mu", ",", "sigma", ")", ",", "random", ".", "gauss", "(", "mu", ",", "sigma", ")", ",", "random", ".", "...
36.538462
17.769231
def getexptimeimg(self,chip): """ Notes ===== Return an array representing the exposure time per pixel for the detector. This method will be overloaded for IR detectors which have their own EXP arrays, namely, WFC3/IR and NICMOS images. :units: None ...
[ "def", "getexptimeimg", "(", "self", ",", "chip", ")", ":", "sci_chip", "=", "self", ".", "_image", "[", "self", ".", "scienceExt", ",", "chip", "]", "if", "sci_chip", ".", "_wtscl_par", "==", "'expsq'", ":", "wtscl", "=", "sci_chip", ".", "_exptime", ...
30.458333
23.208333
def handle(self, *args, **options): """Run do_index_command on each specified index and log the output.""" for index in options.pop("indexes"): data = {} try: data = self.do_index_command(index, **options) except TransportError as ex: l...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "for", "index", "in", "options", ".", "pop", "(", "\"indexes\"", ")", ":", "data", "=", "{", "}", "try", ":", "data", "=", "self", ".", "do_index_command", "(", "...
45.818182
16
def do_POST(self): """ This method will be called for each POST request to one of the listener ports. It parses the CIM-XML export message and delivers the contained CIM indication to the stored listener object. """ # Accept header check described in DSP0200 ...
[ "def", "do_POST", "(", "self", ")", ":", "# Accept header check described in DSP0200", "accept", "=", "self", ".", "headers", ".", "get", "(", "'Accept'", ",", "'text/xml'", ")", "if", "accept", "not", "in", "(", "'text/xml'", ",", "'application/xml'", ",", "'...
42.228395
19.364198
def generate_protocol(self,sweep=None): """ Create (x,y) points necessary to graph protocol for the current sweep. """ #TODO: make a line protocol that's plottable if sweep is None: sweep = self.currentSweep if sweep is None: sweep = 0 if n...
[ "def", "generate_protocol", "(", "self", ",", "sweep", "=", "None", ")", ":", "#TODO: make a line protocol that's plottable", "if", "sweep", "is", "None", ":", "sweep", "=", "self", ".", "currentSweep", "if", "sweep", "is", "None", ":", "sweep", "=", "0", "i...
41.785714
13.892857
def finish(self): """Finish performing the action.""" self.status = 'completed' self.time_completed = timestamp() self.thing.action_notify(self)
[ "def", "finish", "(", "self", ")", ":", "self", ".", "status", "=", "'completed'", "self", ".", "time_completed", "=", "timestamp", "(", ")", "self", ".", "thing", ".", "action_notify", "(", "self", ")" ]
34.4
6.6
def reset(self): """ Reset the state of the instance to when it was constructed """ self.operations = [] self._last_overflow = 'WRAP' self.overflow(self._default_overflow or self._last_overflow)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "operations", "=", "[", "]", "self", ".", "_last_overflow", "=", "'WRAP'", "self", ".", "overflow", "(", "self", ".", "_default_overflow", "or", "self", ".", "_last_overflow", ")" ]
33.714286
13.428571
def main(): """ NAME uniform.py DESCRIPTION draws N directions from uniform distribution on a sphere SYNTAX uniform.py [-h][command line options] -h prints help message and quits -n N, specify N on the command line (default is 100) -F file, specify ...
[ "def", "main", "(", ")", ":", "outf", "=", "\"\"", "N", "=", "100", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "if", "'-F'", "in", "sys", ".", "argv", ":", "ind", "=",...
25.75
18.1875
def order_by(self, **kwargs): """ Orders the query by the key passed in +kwargs+. Only pass one key, as it cannot sort by multiple columns at once. Raises QueryInvalid if this method is called when there is already a custom order (i.e. this method was already called on this query...
[ "def", "order_by", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Only get one thing from kwargs (we can only order by one thing...)", "if", "self", ".", "_order_with", ":", "raise", "QueryInvalid", "(", "\"Cannot order by more than one column\"", ")", "self", ".", ...
50.083333
22.25
def setup(self, redis_conn=None, host='localhost', port=6379): ''' Set up the redis connection ''' if redis_conn is None: if host is not None and port is not None: self.redis_conn = redis.Redis(host=host, port=port) else: raise Exce...
[ "def", "setup", "(", "self", ",", "redis_conn", "=", "None", ",", "host", "=", "'localhost'", ",", "port", "=", "6379", ")", ":", "if", "redis_conn", "is", "None", ":", "if", "host", "is", "not", "None", "and", "port", "is", "not", "None", ":", "se...
34.928571
19.642857
def configure(self, listener): """ Configure a :class:`.Listener` to capture callback query """ listener.capture([ lambda msg: flavor(msg) == 'callback_query', {'message': self._chat_origin_included} ]) listener.capture([ lambda msg: f...
[ "def", "configure", "(", "self", ",", "listener", ")", ":", "listener", ".", "capture", "(", "[", "lambda", "msg", ":", "flavor", "(", "msg", ")", "==", "'callback_query'", ",", "{", "'message'", ":", "self", ".", "_chat_origin_included", "}", "]", ")", ...
31.846154
17.538462
def dumpindented(self, pn, indent=0): """ Dump all nodes of the current page with keys indented, showing how the `indent` feature works """ page = self.readpage(pn) print(" " * indent, page) if page.isindex(): print(" " * indent, end="") ...
[ "def", "dumpindented", "(", "self", ",", "pn", ",", "indent", "=", "0", ")", ":", "page", "=", "self", ".", "readpage", "(", "pn", ")", "print", "(", "\" \"", "*", "indent", ",", "page", ")", "if", "page", ".", "isindex", "(", ")", ":", "print",...
39.923077
11.153846
def tridisolve(d, e, b, overwrite_b=True): """ Symmetric tridiagonal system solver, from Golub and Van Loan, Matrix Computations pg 157 Parameters ---------- d : ndarray main diagonal stored in d[:] e : ndarray superdiagonal stored in e[:-1] b : ndarray RHS vector ...
[ "def", "tridisolve", "(", "d", ",", "e", ",", "b", ",", "overwrite_b", "=", "True", ")", ":", "N", "=", "len", "(", "b", ")", "# work vectors", "dw", "=", "d", ".", "copy", "(", ")", "ew", "=", "e", ".", "copy", "(", ")", "if", "overwrite_b", ...
22.266667
19.111111
def virtual(cls, **options): """ Allows for defining virtual columns and collectors on models -- these are objects that are defined in code and not directly in a data store. :param cls: :param options: :return: """ def wrapped(func): param_name = inflection.underscore(func.__nam...
[ "def", "virtual", "(", "cls", ",", "*", "*", "options", ")", ":", "def", "wrapped", "(", "func", ")", ":", "param_name", "=", "inflection", ".", "underscore", "(", "func", ".", "__name__", ")", "options", ".", "setdefault", "(", "'name'", ",", "param_n...
33.219512
17.268293
def describe_addresses(self, *addresses): """ List the elastic IPs allocated in this account. @param addresses: if specified, the addresses to get information about. @return: a C{list} of (address, instance_id). If the elastic IP is not associated currently, C{instance_id} ...
[ "def", "describe_addresses", "(", "self", ",", "*", "addresses", ")", ":", "address_set", "=", "{", "}", "for", "pos", ",", "address", "in", "enumerate", "(", "addresses", ")", ":", "address_set", "[", "\"PublicIp.%d\"", "%", "(", "pos", "+", "1", ")", ...
41.882353
18.823529
def make_trajectory(first, filename, restart=False): '''Factory function to easily create a trajectory object''' mode = 'w' if restart: mode = 'a' return Trajectory(first, filename, mode)
[ "def", "make_trajectory", "(", "first", ",", "filename", ",", "restart", "=", "False", ")", ":", "mode", "=", "'w'", "if", "restart", ":", "mode", "=", "'a'", "return", "Trajectory", "(", "first", ",", "filename", ",", "mode", ")" ]
26.75
23
def arg_comparitor(name): """ :param arg name :return: pair containing name, comparitor given an argument name, munge it and return a proper comparitor >>> arg_comparitor("a") a, operator.eq >>> arg_comparitor("a__in") a, operator.contains """ if name.endswith("__in"): ...
[ "def", "arg_comparitor", "(", "name", ")", ":", "if", "name", ".", "endswith", "(", "\"__in\"", ")", ":", "return", "name", "[", ":", "-", "4", "]", ",", "contains", "elif", "name", ".", "endswith", "(", "\"__ge\"", ")", ":", "return", "name", "[", ...
24.689655
15.310345
def from_arrays(cls, arrays, sortorder=None, names=None): """ Convert arrays to MultiIndex. Parameters ---------- arrays : list / sequence of array-likes Each array-like gives one level's value for each data point. len(arrays) is the number of levels. ...
[ "def", "from_arrays", "(", "cls", ",", "arrays", ",", "sortorder", "=", "None", ",", "names", "=", "None", ")", ":", "error_msg", "=", "\"Input must be a list / sequence of array-likes.\"", "if", "not", "is_list_like", "(", "arrays", ")", ":", "raise", "TypeErro...
36.966102
20.050847
def kill_process(modeladmin, request, queryset): """ restarts a dedicated process :return: """ for process in queryset: process.stop(signum=signal.SIGKILL)
[ "def", "kill_process", "(", "modeladmin", ",", "request", ",", "queryset", ")", ":", "for", "process", "in", "queryset", ":", "process", ".", "stop", "(", "signum", "=", "signal", ".", "SIGKILL", ")" ]
25.285714
8.428571
def do_scan(self, line): """ scan [:tablename] [--batch=#] [-{max}] [--count|-c] [--array|-a] [+filter_attribute:filter_value] [attributes,...] if filter_value contains '=' it's interpreted as {conditional}={value} where condtional is: eq (equal value) ne {value} (not e...
[ "def", "do_scan", "(", "self", ",", "line", ")", ":", "table", ",", "line", "=", "self", ".", "get_table_params", "(", "line", ")", "args", "=", "self", ".", "getargs", "(", "line", ")", "scan_filter", "=", "{", "}", "count", "=", "False", "as_array"...
37.236641
22.442748
def expand_as_args(args): """Returns `True` if `args` should be expanded as `*args`.""" return (isinstance(args, collections.Sequence) and not _is_namedtuple(args) and not _force_leaf(args))
[ "def", "expand_as_args", "(", "args", ")", ":", "return", "(", "isinstance", "(", "args", ",", "collections", ".", "Sequence", ")", "and", "not", "_is_namedtuple", "(", "args", ")", "and", "not", "_force_leaf", "(", "args", ")", ")" ]
50.25
12