text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _parent_prefix(prefix): """Identify a parent prefix we should add to resources if present in a caller name. """ def run(algs): for alg in algs: vcs = alg.get("variantcaller") if vcs: if isinstance(vcs, dict): vcs = reduce(operator.add, ...
[ "def", "_parent_prefix", "(", "prefix", ")", ":", "def", "run", "(", "algs", ")", ":", "for", "alg", "in", "algs", ":", "vcs", "=", "alg", ".", "get", "(", "\"variantcaller\"", ")", "if", "vcs", ":", "if", "isinstance", "(", "vcs", ",", "dict", ")"...
37.923077
13.307692
def get_link_pages(links): """ Given a list of links, separate them into pages that can be displayed to the user and navigated using the 1-9 and 0 number keys. """ link_pages = [] i = 0 while i < len(links): link_page = [] while i < len(lin...
[ "def", "get_link_pages", "(", "links", ")", ":", "link_pages", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "links", ")", ":", "link_page", "=", "[", "]", "while", "i", "<", "len", "(", "links", ")", "and", "len", "(", "link_page"...
33.428571
14.142857
def HandleWellKnownFlows(self, messages): """Hands off messages to well known flows.""" msgs_by_wkf = {} result = [] for msg in messages: # Regular message - queue it. if msg.response_id != 0: result.append(msg) continue # Well known flows: flow_name = msg.sessio...
[ "def", "HandleWellKnownFlows", "(", "self", ",", "messages", ")", ":", "msgs_by_wkf", "=", "{", "}", "result", "=", "[", "]", "for", "msg", "in", "messages", ":", "# Regular message - queue it.", "if", "msg", ".", "response_id", "!=", "0", ":", "result", "...
33.575
20.5
def _get_distance_scaling_term(self, C, mag, rrup): """ Returns the distance scaling parameter """ return (C["r1"] + C["r2"] * mag) * np.log10(rrup + C["r3"])
[ "def", "_get_distance_scaling_term", "(", "self", ",", "C", ",", "mag", ",", "rrup", ")", ":", "return", "(", "C", "[", "\"r1\"", "]", "+", "C", "[", "\"r2\"", "]", "*", "mag", ")", "*", "np", ".", "log10", "(", "rrup", "+", "C", "[", "\"r3\"", ...
37.2
8.8
def make_bar(percentage): """ Draws a bar made of unicode box characters. :param percentage: A value between 0 and 100 :returns: Bar as a string """ bars = [' ', '▏', '▎', '▍', '▌', '▋', '▋', '▊', '▊', '█'] tens = int(percentage / 10) ones = int(percentage) - tens * 10 result = ten...
[ "def", "make_bar", "(", "percentage", ")", ":", "bars", "=", "[", "' '", ",", "'▏', ", "'", "', '▍", "'", " '▌',", " ", "▋', '", "▋", ", '▊'", ",", "'▊', ", "'", "']", "", "", "", "", "", "tens", "=", "int", "(", "percentage", "/", "10", ")", ...
27.0625
14.0625
def get_system_config_directory(): """ Return platform specific config directory. """ if platform.system().lower() == 'windows': _cfg_directory = Path(os.getenv('APPDATA') or '~') elif platform.system().lower() == 'darwin': _cfg_directory = Path('~', 'Library', 'Preferences') ...
[ "def", "get_system_config_directory", "(", ")", ":", "if", "platform", ".", "system", "(", ")", ".", "lower", "(", ")", "==", "'windows'", ":", "_cfg_directory", "=", "Path", "(", "os", ".", "getenv", "(", "'APPDATA'", ")", "or", "'~'", ")", "elif", "p...
40.142857
15.285714
def fstab_present(name, fs_file, fs_vfstype, fs_mntops='defaults', fs_freq=0, fs_passno=0, mount_by=None, config='/etc/fstab', mount=True, match_on='auto'): ''' Makes sure that a fstab mount point is pressent. name The name of block device. Can be any valid fs_sp...
[ "def", "fstab_present", "(", "name", ",", "fs_file", ",", "fs_vfstype", ",", "fs_mntops", "=", "'defaults'", ",", "fs_freq", "=", "0", ",", "fs_passno", "=", "0", ",", "mount_by", "=", "None", ",", "config", "=", "'/etc/fstab'", ",", "mount", "=", "True"...
40.335329
21.580838
def fstype(device): ''' Return the filesystem name of the specified device .. versionadded:: 2016.11.0 device The name of the device CLI Example: .. code-block:: bash salt '*' disk.fstype /dev/sdX1 ''' if salt.utils.path.which('lsblk'): lsblk_out = __salt__['...
[ "def", "fstype", "(", "device", ")", ":", "if", "salt", ".", "utils", ".", "path", ".", "which", "(", "'lsblk'", ")", ":", "lsblk_out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'lsblk -o fstype {0}'", ".", "format", "(", "device", ")", ")", ".", ...
29.820513
22.282051
def create_from_pointer(cls, pointer): """ :type pointer: Pointer """ instance = cls.__new__(cls) instance.pointer = pointer instance.label_monetary_account = LabelMonetaryAccount() instance.label_monetary_account._iban = pointer.value instance.label_mone...
[ "def", "create_from_pointer", "(", "cls", ",", "pointer", ")", ":", "instance", "=", "cls", ".", "__new__", "(", "cls", ")", "instance", ".", "pointer", "=", "pointer", "instance", ".", "label_monetary_account", "=", "LabelMonetaryAccount", "(", ")", "instance...
31.25
16.083333
def render(self): """Render field as HTML. """ self.widget.attrs = { k: v for k, v in self.attrs.items() if k[0] != "_" } self.set_input() if not self.attrs.get("_no_wrapper"): self.set_label() self.set_help() self.set_errors() self.set_classes() self.set_icon() # Must be th...
[ "def", "render", "(", "self", ")", ":", "self", ".", "widget", ".", "attrs", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "attrs", ".", "items", "(", ")", "if", "k", "[", "0", "]", "!=", "\"_\"", "}", "self", ".", "set_...
27.368421
18.894737
def validate(self, bigchain, current_transactions=[]): """Validate election transaction NOTE: * A valid election is initiated by an existing validator. * A valid election is one where voters are validators and votes are allocated according to the voting power of each validato...
[ "def", "validate", "(", "self", ",", "bigchain", ",", "current_transactions", "=", "[", "]", ")", ":", "input_conditions", "=", "[", "]", "duplicates", "=", "any", "(", "txn", "for", "txn", "in", "current_transactions", "if", "txn", ".", "id", "==", "sel...
43.844444
31.822222
def simple_separated_format(separator): """Construct a simple TableFormat with columns separated by a separator. >>> tsv = simple_separated_format("\\t") ; \ tabulate([["foo", 1], ["spam", 23]], tablefmt=tsv) == 'foo \\t 1\\nspam\\t23' True """ return TableFormat(None, None, None, None, ...
[ "def", "simple_separated_format", "(", "separator", ")", ":", "return", "TableFormat", "(", "None", ",", "None", ",", "None", ",", "None", ",", "headerrow", "=", "DataRow", "(", "''", ",", "separator", ",", "''", ")", ",", "datarow", "=", "DataRow", "(",...
40.25
18.833333
def copy(self, parent=None, name=None, verbose=True): """Create a copy under parent. All children are copied as well. Parameters ---------- parent : WrightTools Collection (optional) Parent to copy within. If None, copy is created in root of new tempfile...
[ "def", "copy", "(", "self", ",", "parent", "=", "None", ",", "name", "=", "None", ",", "verbose", "=", "True", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "natural_name", "if", "parent", "is", "None", ":", "from", ".", "_...
31.113636
17.181818
def parse_devicelist(data_str): """Parse the BT Home Hub 5 data format.""" p = HTMLTableParser() p.feed(data_str) known_devices = p.tables[9] devices = {} for device in known_devices: if len(device) == 5 and device[2] != '': devices[device[2]] = device[1] return devi...
[ "def", "parse_devicelist", "(", "data_str", ")", ":", "p", "=", "HTMLTableParser", "(", ")", "p", ".", "feed", "(", "data_str", ")", "known_devices", "=", "p", ".", "tables", "[", "9", "]", "devices", "=", "{", "}", "for", "device", "in", "known_device...
20.6
21.133333
def query_kinds(self, kind): """Query kinds.""" logging.debug(_('querying %s'), kind) if kind is None: return self._kind_id_to_name.items() if kind.isdigit(): kind_name = self.kind_id_to_name(int(kind)) if kind_name: kind = (kind, kind_...
[ "def", "query_kinds", "(", "self", ",", "kind", ")", ":", "logging", ".", "debug", "(", "_", "(", "'querying %s'", ")", ",", "kind", ")", "if", "kind", "is", "None", ":", "return", "self", ".", "_kind_id_to_name", ".", "items", "(", ")", "if", "kind"...
33.5
13.6
def _get_fields_info(self, cols, model_schema, filter_rel_fields, **kwargs): """ Returns a dict with fields detail from a marshmallow schema :param cols: list of columns to show info for :param model_schema: Marshmallow model schema :param filter_rel_fields: expe...
[ "def", "_get_fields_info", "(", "self", ",", "cols", ",", "model_schema", ",", "filter_rel_fields", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "list", "(", ")", "for", "col", "in", "cols", ":", "page", "=", "page_size", "=", "None", "col_args", "="...
38.285714
14.785714
def normalized_rgb(self): r""" Returns a tuples of the normalized values of the red, green, and blue channels of the Colour. Returns: tuple: the rgb values of the colour (with values normalized between 0.0 and 1.0) .. note:: Uses the ...
[ "def", "normalized_rgb", "(", "self", ")", ":", "r1", "=", "self", ".", "_r", "/", "255", "g1", "=", "self", ".", "_g", "/", "255", "b1", "=", "self", ".", "_b", "/", "255", "if", "r1", "<=", "0.03928", ":", "r2", "=", "r1", "/", "12.92", "el...
27.878049
21.95122
def _process_protocol_v2(self, argv, ifile, ofile): """ Processes records on the `input stream optionally writing records to the output stream. :param ifile: Input file object. :type ifile: file or InputType :param ofile: Output file object. :type ofile: file or OutputType ...
[ "def", "_process_protocol_v2", "(", "self", ",", "argv", ",", "ifile", ",", "ofile", ")", ":", "debug", "=", "environment", ".", "splunklib_logger", ".", "debug", "class_name", "=", "self", ".", "__class__", ".", "__name__", "debug", "(", "'%s.process started ...
35.675325
22.792208
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv # setup command line parser parser = U.OptionParser(version="%prog version: $Id$", usage=usage, ...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "# setup command line parser", "parser", "=", "U", ".", "OptionParser", "(", "version", "=", "\"%prog version: $Id$\"", ",", "usage", "=", ...
32.094595
22.581081
def list_active_vms(**kwargs): ''' Return a list of names for active virtual machine on the minion :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :p...
[ "def", "list_active_vms", "(", "*", "*", "kwargs", ")", ":", "vms", "=", "[", "]", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "for", "dom", "in", "_get_domain", "(", "conn", ",", "iterable", "=", "True", ",", "inactive", "=", "False", ...
25.192308
24.730769
def required_validator(validator, req, instance, schema): """Swagger 1.2 expects `required` to be a bool in the Parameter object, but a list of properties in a Model object. """ if schema.get('paramType'): if req is True and not instance: return [ValidationError("%s is required" % sc...
[ "def", "required_validator", "(", "validator", ",", "req", ",", "instance", ",", "schema", ")", ":", "if", "schema", ".", "get", "(", "'paramType'", ")", ":", "if", "req", "is", "True", "and", "not", "instance", ":", "return", "[", "ValidationError", "("...
46.333333
12.777778
def find(self, obj): """Returns the index of the given object in the queue, it might be string which will be searched inside each task. :arg obj: object we are looking :return: -1 if the object is not found or else the location of the task """ if not self.connected: ...
[ "def", "find", "(", "self", ",", "obj", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "ConnectionError", "(", "'Queue is not connected'", ")", "data", "=", "self", ".", "rdb", ".", "lrange", "(", "self", ".", "_name", ",", "0", ",", ...
33.6875
16.6875
def max_time_ms(self, max_time_ms): """Specifies a time limit for a query operation. If the specified time is exceeded, the operation will be aborted and :exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms` is ``None`` no limit is applied. Raises :exc:`TypeError` ...
[ "def", "max_time_ms", "(", "self", ",", "max_time_ms", ")", ":", "if", "(", "not", "isinstance", "(", "max_time_ms", ",", "integer_types", ")", "and", "max_time_ms", "is", "not", "None", ")", ":", "raise", "TypeError", "(", "\"max_time_ms must be an integer or N...
42.05
19.85
def _find_boxscore_tables(self, boxscore): """ Find all tables with boxscore information on the page. Iterate through all tables on the page and see if any of them are boxscore pages by checking if the ID is prefixed with 'box_'. If so, add it to a list and return the final list...
[ "def", "_find_boxscore_tables", "(", "self", ",", "boxscore", ")", ":", "tables", "=", "[", "]", "for", "table", "in", "boxscore", "(", "'table'", ")", ".", "items", "(", ")", ":", "try", ":", "if", "'box_'", "in", "table", ".", "attr", "[", "'id'", ...
31.857143
20.285714
def stream_request(self, request, out_future): """send the given request and response is not required""" request.close_argstreams() def on_done(future): if future.exception() and out_future.running(): out_future.set_exc_info(future.exc_info()) request.clo...
[ "def", "stream_request", "(", "self", ",", "request", ",", "out_future", ")", ":", "request", ".", "close_argstreams", "(", ")", "def", "on_done", "(", "future", ")", ":", "if", "future", ".", "exception", "(", ")", "and", "out_future", ".", "running", "...
40.75
17
def write(self, garbage=0, clean=0, deflate=0, ascii=0, expand=0, linear=0, pretty=0, decrypt=1): """Write document to a bytes object.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") if self.pageCount < 1: raise V...
[ "def", "write", "(", "self", ",", "garbage", "=", "0", ",", "clean", "=", "0", ",", "deflate", "=", "0", ",", "ascii", "=", "0", ",", "expand", "=", "0", ",", "linear", "=", "0", ",", "pretty", "=", "0", ",", "decrypt", "=", "1", ")", ":", ...
46.1
31.4
def allow(self, comment, content_object, request): """Moderates comments.""" POST = urlencode({ "blog": settings.AKISMET_BLOG.encode("utf-8"), "user_ip": comment.ip_address, "user_agent": request.META.get('HTTP_USER_AGENT', ""). ...
[ "def", "allow", "(", "self", ",", "comment", ",", "content_object", ",", "request", ")", ":", "POST", "=", "urlencode", "(", "{", "\"blog\"", ":", "settings", ".", "AKISMET_BLOG", ".", "encode", "(", "\"utf-8\"", ")", ",", "\"user_ip\"", ":", "comment", ...
47.516129
18.064516
def selected_shells(command): """Iterator over the shells with names matching the patterns. An empty patterns matches all the shells""" if not command or command == '*': for i in dispatchers.all_instances(): yield i return selected = set() instance_found = False for p...
[ "def", "selected_shells", "(", "command", ")", ":", "if", "not", "command", "or", "command", "==", "'*'", ":", "for", "i", "in", "dispatchers", ".", "all_instances", "(", ")", ":", "yield", "i", "return", "selected", "=", "set", "(", ")", "instance_found...
38.666667
10.47619
def sample(self, logits, argmax_sampling=False): """ Sample from a probability space of all actions """ if argmax_sampling: return torch.argmax(logits, dim=-1) else: u = torch.rand_like(logits) return torch.argmax(logits - torch.log(-torch.log(u)), dim=-1)
[ "def", "sample", "(", "self", ",", "logits", ",", "argmax_sampling", "=", "False", ")", ":", "if", "argmax_sampling", ":", "return", "torch", ".", "argmax", "(", "logits", ",", "dim", "=", "-", "1", ")", "else", ":", "u", "=", "torch", ".", "rand_lik...
44.285714
12.857143
def scale(self, scalex, scaley=None, center=(0, 0)): """ Scale this object. Parameters ---------- scalex : number Scaling factor along the first axis. scaley : number or ``None`` Scaling factor along the second axis. If ``None``, same as ...
[ "def", "scale", "(", "self", ",", "scalex", ",", "scaley", "=", "None", ",", "center", "=", "(", "0", ",", "0", ")", ")", ":", "c0", "=", "numpy", ".", "array", "(", "center", ")", "s", "=", "scalex", "if", "scaley", "is", "None", "else", "nump...
30.304348
18.391304
def _d2kvmatrix(d): ''' d = {1: 2, 3: {'a': 'b'}} km,vm = _d2kvmatrix(d) d = {1: {2:{22:222}}, 3: {'a': 'b'}} km,vm = _d2kvmatrix(d) ## km: 按照层次存储pathlist,层次从0开始, { 1: 2, 3: { 'a': 'b' } } ...
[ "def", "_d2kvmatrix", "(", "d", ")", ":", "km", "=", "[", "]", "vm", "=", "[", "list", "(", "d", ".", "values", "(", ")", ")", "]", "vm_history", "=", "{", "0", ":", "[", "0", "]", "}", "unhandled", "=", "[", "{", "'data'", ":", "d", ",", ...
30.163636
14.890909
def _create_hstore_required(self, table_name, field, key): """Creates a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_create.format( name=self.quote_name(name), ...
[ "def", "_create_hstore_required", "(", "self", ",", "table_name", ",", "field", ",", "key", ")", ":", "name", "=", "self", ".", "_required_constraint_name", "(", "table_name", ",", "field", ",", "key", ")", "sql", "=", "self", ".", "sql_hstore_required_create"...
34.692308
15.692308
def team_scores(self, team_scores, time): """Store output of team scores to a CSV file""" headers = ['Date', 'Home Team Name', 'Home Team Goals', 'Away Team Goals', 'Away Team Name'] result = [headers] result.extend([score["utcDate"].split('T')[0], ...
[ "def", "team_scores", "(", "self", ",", "team_scores", ",", "time", ")", ":", "headers", "=", "[", "'Date'", ",", "'Home Team Name'", ",", "'Home Team Goals'", ",", "'Away Team Goals'", ",", "'Away Team Name'", "]", "result", "=", "[", "headers", "]", "result"...
51.076923
12.692308
def prop_set(prop, value, extra_args=None, cibfile=None): ''' Set the value of a cluster property prop name of the property value value of the property prop extra_args additional options for the pcs property command cibfile use cibfile instead of the live CIB ...
[ "def", "prop_set", "(", "prop", ",", "value", ",", "extra_args", "=", "None", ",", "cibfile", "=", "None", ")", ":", "return", "item_create", "(", "item", "=", "'property'", ",", "item_id", "=", "'{0}={1}'", ".", "format", "(", "prop", ",", "value", ")...
28.48
21.36
def q(line, cell=None, _ns=None): """Run q code. Options: -l (dir|script) - pre-load database or script -h host:port - execute on the given host -o var - send output to a variable named var. -i var1,..,varN - input variables -1/-2 - redirect stdout/stderr """ if cell ...
[ "def", "q", "(", "line", ",", "cell", "=", "None", ",", "_ns", "=", "None", ")", ":", "if", "cell", "is", "None", ":", "return", "pyq", ".", "q", "(", "line", ")", "if", "_ns", "is", "None", ":", "_ns", "=", "vars", "(", "sys", ".", "modules"...
31.611111
13.152778
def rm(package, force=False): """ Remove a package (all instances) from the local store. """ team, owner, pkg = parse_package(package) if not force: confirmed = input("Remove {0}? (y/n) ".format(package)) if confirmed.lower() != 'y': return store = PackageStore() ...
[ "def", "rm", "(", "package", ",", "force", "=", "False", ")", ":", "team", ",", "owner", ",", "pkg", "=", "parse_package", "(", "package", ")", "if", "not", "force", ":", "confirmed", "=", "input", "(", "\"Remove {0}? (y/n) \"", ".", "format", "(", "pa...
28.133333
15.333333
def power_ratio(events, dat, s_freq, limits, ratio_thresh): """Estimate the ratio in power between spindle band and lower frequencies. Parameters ---------- events : ndarray (dtype='int') N x 3 matrix with start, peak, end samples dat : ndarray (dtype='float') vector with the origin...
[ "def", "power_ratio", "(", "events", ",", "dat", ",", "s_freq", ",", "limits", ",", "ratio_thresh", ")", ":", "ratio", "=", "empty", "(", "events", ".", "shape", "[", "0", "]", ")", "for", "i", ",", "one_event", "in", "enumerate", "(", "events", ")",...
26.425532
20.957447
def glob2re(part): """Convert a path part to regex syntax.""" return "[^/]*".join( re.escape(bit).replace(r'\[\^', '[^').replace(r'\[', '[').replace(r'\]', ']') for bit in part.split("*") )
[ "def", "glob2re", "(", "part", ")", ":", "return", "\"[^/]*\"", ".", "join", "(", "re", ".", "escape", "(", "bit", ")", ".", "replace", "(", "r'\\[\\^'", ",", "'[^'", ")", ".", "replace", "(", "r'\\['", ",", "'['", ")", ".", "replace", "(", "r'\\]'...
35.333333
20.666667
def format_author_ed(citation_elements): """Standardise to (ed.) and (eds.) e.g. Remove extra space in (ed. ) """ for el in citation_elements: if el['type'] == 'AUTH': el['auth_txt'] = el['auth_txt'].replace('(ed. )', '(ed.)') el['auth_txt'] = el['auth_txt'].replace('(ed...
[ "def", "format_author_ed", "(", "citation_elements", ")", ":", "for", "el", "in", "citation_elements", ":", "if", "el", "[", "'type'", "]", "==", "'AUTH'", ":", "el", "[", "'auth_txt'", "]", "=", "el", "[", "'auth_txt'", "]", ".", "replace", "(", "'(ed. ...
35.6
13.3
async def prover_search_credentials_for_proof_req(wallet_handle: int, proof_request_json: str, extra_query_json: Optional[str]) -> int: """ Search for credentials matching the given proof request. Instead of...
[ "async", "def", "prover_search_credentials_for_proof_req", "(", "wallet_handle", ":", "int", ",", "proof_request_json", ":", "str", ",", "extra_query_json", ":", "Optional", "[", "str", "]", ")", "->", "int", ":", "logger", "=", "logging", ".", "getLogger", "(",...
48.783333
28.983333
def get_units_regex(): """Build a compiled regex object.""" op_keys = sorted(OPERATORS.keys(), key=len, reverse=True) unit_keys = sorted(l.UNITS.keys(), key=len, reverse=True) symbol_keys = sorted(l.SYMBOLS.keys(), key=len, reverse=True) exponent = ur'(?:(?:\^?\-?[0-9%s]*)(?:\ cubed|\ squared)?)(?!...
[ "def", "get_units_regex", "(", ")", ":", "op_keys", "=", "sorted", "(", "OPERATORS", ".", "keys", "(", ")", ",", "key", "=", "len", ",", "reverse", "=", "True", ")", "unit_keys", "=", "sorted", "(", "l", ".", "UNITS", ".", "keys", "(", ")", ",", ...
43.107143
28.535714
def cli_run(): """Run the daemon from a command line interface""" options = CLI.parse_args() run(options.CONFIGURATION, options.log_level, options.log_target, options.log_journal)
[ "def", "cli_run", "(", ")", ":", "options", "=", "CLI", ".", "parse_args", "(", ")", "run", "(", "options", ".", "CONFIGURATION", ",", "options", ".", "log_level", ",", "options", ".", "log_target", ",", "options", ".", "log_journal", ")" ]
47
21.5
def is_js_date_utc(json): """Check if the string contains Date.UTC function and return match group(s) if there is """ JS_date_utc_pattern = r'Date\.UTC\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\)' re_date = re.compile(JS_date_utc_pattern, re.M) ...
[ "def", "is_js_date_utc", "(", "json", ")", ":", "JS_date_utc_pattern", "=", "r'Date\\.UTC\\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\\)'", "re_date", "=", "re", ".", "compile", "(", "JS_date_utc_pattern", ",", "re", ".", "M", ")", "if", "re_date", ".", ...
35.083333
19
def trimmed(self, pred=trimmed_pred_default): """Trim a ParseTree. A node is trimmed if pred(node) returns True. """ new_children = [] for child in self.children: if isinstance(child, ParseNode): new_child = child.trimmed(pred) else: new_child = child if not pred...
[ "def", "trimmed", "(", "self", ",", "pred", "=", "trimmed_pred_default", ")", ":", "new_children", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "if", "isinstance", "(", "child", ",", "ParseNode", ")", ":", "new_child", "=", "child",...
27.238095
13
def create_histogram(df): """ create a mg line plot Args: df (pandas.DataFrame): data to plot """ fig = Figure("/mg/histogram/", "mg_histogram") fig.layout.set_size(width=450, height=200) fig.layout.set_margin(left=40, right=40) fig.graphics.animate_on_load() # Make a h...
[ "def", "create_histogram", "(", "df", ")", ":", "fig", "=", "Figure", "(", "\"/mg/histogram/\"", ",", "\"mg_histogram\"", ")", "fig", ".", "layout", ".", "set_size", "(", "width", "=", "450", ",", "height", "=", "200", ")", "fig", ".", "layout", ".", "...
31
14.846154
def construct_rest_of_worlds(self, excluded, fp=None, use_mp=True, simplify=True): """Construct many rest-of-world geometries and optionally write to filepath ``fp``. ``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``.""" geoms = {} ...
[ "def", "construct_rest_of_worlds", "(", "self", ",", "excluded", ",", "fp", "=", "None", ",", "use_mp", "=", "True", ",", "simplify", "=", "True", ")", ":", "geoms", "=", "{", "}", "raw_data", "=", "[", "]", "for", "key", "in", "sorted", "(", "exclud...
43.607143
19.428571
def which_bin(exes): ''' Scan over some possible executables and return the first one that is found ''' if not isinstance(exes, Iterable): return None for exe in exes: path = which(exe) if not path: continue return path return None
[ "def", "which_bin", "(", "exes", ")", ":", "if", "not", "isinstance", "(", "exes", ",", "Iterable", ")", ":", "return", "None", "for", "exe", "in", "exes", ":", "path", "=", "which", "(", "exe", ")", "if", "not", "path", ":", "continue", "return", ...
24
22.333333
def _url_val(val, key, obj, **kwargs): """Function applied by `HyperlinksField` to get the correct value in the schema. """ if isinstance(val, URLFor): return val.serialize(key, obj, **kwargs) else: return val
[ "def", "_url_val", "(", "val", ",", "key", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "val", ",", "URLFor", ")", ":", "return", "val", ".", "serialize", "(", "key", ",", "obj", ",", "*", "*", "kwargs", ")", "else", ...
29.75
12.625
def as_format(item, format_str='.2f'): """ Map a format string over a pandas object. """ if isinstance(item, pd.Series): return item.map(lambda x: format(x, format_str)) elif isinstance(item, pd.DataFrame): return item.applymap(lambda x: format(x, format_str))
[ "def", "as_format", "(", "item", ",", "format_str", "=", "'.2f'", ")", ":", "if", "isinstance", "(", "item", ",", "pd", ".", "Series", ")", ":", "return", "item", ".", "map", "(", "lambda", "x", ":", "format", "(", "x", ",", "format_str", ")", ")",...
36.125
6.125
def _collect_classes(m): """ Adds entries to _classes_* Args: m: module object that must contain the following sub-modules: datatypes, vis """ from f311 import filetypes as ft from f311 import explorer as ex def _extend(classes, newclasses): """Filters out classes already p...
[ "def", "_collect_classes", "(", "m", ")", ":", "from", "f311", "import", "filetypes", "as", "ft", "from", "f311", "import", "explorer", "as", "ex", "def", "_extend", "(", "classes", ",", "newclasses", ")", ":", "\"\"\"Filters out classes already present in list.\n...
42.228571
27.485714
def guess(self, *args): self._validate() """ guess() allows a guess to be made. Before the guess is made, the method checks to see if the game has been won, lost, or there are no tries remaining. It then creates a return object stating the number of bulls (direct matches)...
[ "def", "guess", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_validate", "(", ")", "logging", ".", "debug", "(", "\"guess called.\"", ")", "logging", ".", "debug", "(", "\"Validating game object\"", ")", "self", ".", "_validate", "(", "op", "="...
43.853933
22.977528
def find_gt(a, x): """Find leftmost value greater than x.""" i = bs.bisect_right(a, x) if i != len(a): return i raise ValueError
[ "def", "find_gt", "(", "a", ",", "x", ")", ":", "i", "=", "bs", ".", "bisect_right", "(", "a", ",", "x", ")", "if", "i", "!=", "len", "(", "a", ")", ":", "return", "i", "raise", "ValueError" ]
28
13
def past_datetime(self, start_date='-30d', tzinfo=None): """ Get a DateTime object based on a random date between a given date and 1 second ago. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to "-30d" :param tzinfo: timezone, inst...
[ "def", "past_datetime", "(", "self", ",", "start_date", "=", "'-30d'", ",", "tzinfo", "=", "None", ")", ":", "return", "self", ".", "date_time_between", "(", "start_date", "=", "start_date", ",", "end_date", "=", "'-1s'", ",", "tzinfo", "=", "tzinfo", ",",...
38.571429
18.428571
def check(self, strict=False): """Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided""" self.set_metadata_version() # XXX should check the versions (if the file was loaded) missing, warnings = [], [] for attr in ('Name', ...
[ "def", "check", "(", "self", ",", "strict", "=", "False", ")", ":", "self", ".", "set_metadata_version", "(", ")", "# XXX should check the versions (if the file was loaded)", "missing", ",", "warnings", "=", "[", "]", ",", "[", "]", "for", "attr", "in", "(", ...
37.395349
18.186047
def send(self, msg, flags=0): """Send a message""" _nn_check_positive_rtn(wrapper.nn_send(self.fd, msg, flags))
[ "def", "send", "(", "self", ",", "msg", ",", "flags", "=", "0", ")", ":", "_nn_check_positive_rtn", "(", "wrapper", ".", "nn_send", "(", "self", ".", "fd", ",", "msg", ",", "flags", ")", ")" ]
41.666667
13
def login(self, username, password, disableautosave=True, print_response=True): """ :param username: :param password: :param disableautosave: boolean :param print_response: print log if required :return: status code, response data """ if type(username) != ...
[ "def", "login", "(", "self", ",", "username", ",", "password", ",", "disableautosave", "=", "True", ",", "print_response", "=", "True", ")", ":", "if", "type", "(", "username", ")", "!=", "str", ":", "return", "False", ",", "\"Username must be string\"", "...
38.535714
21.25
def to_app(app): """Serializes app to id string :param app: object to serialize :return: string id """ from sevenbridges.models.app import App if not app: raise SbgError('App is required!') elif isinstance(app, App): return app.id e...
[ "def", "to_app", "(", "app", ")", ":", "from", "sevenbridges", ".", "models", ".", "app", "import", "App", "if", "not", "app", ":", "raise", "SbgError", "(", "'App is required!'", ")", "elif", "isinstance", "(", "app", ",", "App", ")", ":", "return", "...
31.071429
11.285714
def set_default_names(data): """Sets index names to 'index' for regular, or 'level_x' for Multi""" if all(name is not None for name in data.index.names): return data data = data.copy() if data.index.nlevels > 1: names = [name if name is not None else 'level_{}'.format(i) ...
[ "def", "set_default_names", "(", "data", ")", ":", "if", "all", "(", "name", "is", "not", "None", "for", "name", "in", "data", ".", "index", ".", "names", ")", ":", "return", "data", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", ...
35.769231
18.615385
def _login(self, username, password): '''login and update cached cookies''' self.logger.debug('login ...') res = self.session.http.get(self.login_url) input_list = self._input_re.findall(res.text) if not input_list: raise PluginError('Missing input data on login webs...
[ "def", "_login", "(", "self", ",", "username", ",", "password", ")", ":", "self", ".", "logger", ".", "debug", "(", "'login ...'", ")", "res", "=", "self", ".", "session", ".", "http", ".", "get", "(", "self", ".", "login_url", ")", "input_list", "="...
34.883721
21.162791
def _try_auth(self): """Try to authenticate using the first one of allowed authentication methods left. [client only]""" if self.authenticated: self.__logger.debug("try_auth: already authenticated") return self.__logger.debug("trying auth: %r" % (self._au...
[ "def", "_try_auth", "(", "self", ")", ":", "if", "self", ".", "authenticated", ":", "self", ".", "__logger", ".", "debug", "(", "\"try_auth: already authenticated\"", ")", "return", "self", ".", "__logger", ".", "debug", "(", "\"trying auth: %r\"", "%", "(", ...
42.625
15.875
def variable_state(cls, scripts, variables): """Return the initialization state for each variable in variables. The state is determined based on the scripts passed in via the scripts parameter. If there is more than one 'when green flag clicked' script and they both modify the ...
[ "def", "variable_state", "(", "cls", ",", "scripts", ",", "variables", ")", ":", "def", "conditionally_set_not_modified", "(", ")", ":", "\"\"\"Set the variable to modified if it hasn't been altered.\"\"\"", "state", "=", "variables", ".", "get", "(", "block", ".", "a...
49.041667
19.333333
def get_deb_depends_from_setuptools_requires(requirements, on_failure="warn"): """ Suppose you can't confidently figure out a .deb which satisfies a given requirement. If on_failure == 'warn', then log a warning. If on_failure == 'raise' then raise CantSatisfyRequirement exception. If on_failure == ...
[ "def", "get_deb_depends_from_setuptools_requires", "(", "requirements", ",", "on_failure", "=", "\"warn\"", ")", ":", "assert", "on_failure", "in", "(", "\"raise\"", ",", "\"warn\"", ",", "\"guess\"", ")", ",", "on_failure", "import", "pkg_resources", "depends", "="...
43.993827
23.5
def UpdateHunt(hunt_id, client_limit=None, client_rate=None, duration=None): """Updates a hunt (it must be paused to be updated).""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED: raise OnlyPausedHuntCanBeModifiedError(hunt_obj) data_store.REL_DB....
[ "def", "UpdateHunt", "(", "hunt_id", ",", "client_limit", "=", "None", ",", "client_rate", "=", "None", ",", "duration", "=", "None", ")", ":", "hunt_obj", "=", "data_store", ".", "REL_DB", ".", "ReadHuntObject", "(", "hunt_id", ")", "if", "hunt_obj", ".",...
36.923077
17.615385
def get_tunnel_info_output_tunnel_dest_ip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_info = ET.Element("get_tunnel_info") config = get_tunnel_info output = ET.SubElement(get_tunnel_info, "output") tunnel = ET.SubElement(ou...
[ "def", "get_tunnel_info_output_tunnel_dest_ip", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_tunnel_info", "=", "ET", ".", "Element", "(", "\"get_tunnel_info\"", ")", "config", "=", "get_tunn...
39.230769
11.461538
def _live_entity_map(self, entity_type): """Return an id:Entity map of all the living entities of type ``entity_type``. """ return { entity_id: self.get_entity(entity_type, entity_id) for entity_id, history in self.state.get(entity_type, {}).items() i...
[ "def", "_live_entity_map", "(", "self", ",", "entity_type", ")", ":", "return", "{", "entity_id", ":", "self", ".", "get_entity", "(", "entity_type", ",", "entity_id", ")", "for", "entity_id", ",", "history", "in", "self", ".", "state", ".", "get", "(", ...
34.6
16.7
def _format_axes(self): """ Try to format axes if they are datelike. """ if not self.obj.index.is_unique and self.orient in ( 'index', 'columns'): raise ValueError("DataFrame index must be unique for orient=" "'{orient}'.".format(o...
[ "def", "_format_axes", "(", "self", ")", ":", "if", "not", "self", ".", "obj", ".", "index", ".", "is_unique", "and", "self", ".", "orient", "in", "(", "'index'", ",", "'columns'", ")", ":", "raise", "ValueError", "(", "\"DataFrame index must be unique for o...
48.833333
17.166667
def build_paragraph(content, hard_breaks=False): """ Returns *content* wrapped in `<p>` tags. If *hard_breaks* is `True`, all line breaks are converted to `<br />` tags. """ lines = list(filter(None, [line.strip() for line in content.split('\n')])) if hard_breaks: for line_number in range(len(lines) -...
[ "def", "build_paragraph", "(", "content", ",", "hard_breaks", "=", "False", ")", ":", "lines", "=", "list", "(", "filter", "(", "None", ",", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "content", ".", "split", "(", "'\\n'", ")", "]", ...
35.333333
18.333333
def showPDFpage( page, rect, src, pno=0, overlay=True, keep_proportion=True, rotate=0, reuse_xref=0, clip = None, ): """Show page number 'pno' of PDF 'src' in rectangle 'rect'. Args: rect: (rect-like) where to place the source ...
[ "def", "showPDFpage", "(", "page", ",", "rect", ",", "src", ",", "pno", "=", "0", ",", "overlay", "=", "True", ",", "keep_proportion", "=", "True", ",", "rotate", "=", "0", ",", "reuse_xref", "=", "0", ",", "clip", "=", "None", ",", ")", ":", "de...
32.858268
20.685039
def vpc(self): """ :rtype: VPCConnection """ if self.__vpc is None: self.__vpc = self.__aws_connect(vpc) return self.__vpc
[ "def", "vpc", "(", "self", ")", ":", "if", "self", ".", "__vpc", "is", "None", ":", "self", ".", "__vpc", "=", "self", ".", "__aws_connect", "(", "vpc", ")", "return", "self", ".", "__vpc" ]
24
10
def call_agent_side(self, method, *args, **kwargs): ''' Call the method, wrap it in Deferred and bind error handler. ''' assert not self._finalize_called, ("Attempt to call agent side code " "after finalize() method has been " ...
[ "def", "call_agent_side", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "not", "self", ".", "_finalize_called", ",", "(", "\"Attempt to call agent side code \"", "\"after finalize() method has been \"", "\"called. Method: %...
41.708333
23.791667
def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. ""...
[ "def", "output_difference", "(", "self", ",", "example", ",", "got", ",", "optionflags", ")", ":", "want", "=", "example", ".", "want", "# If <BLANKLINE>s are being used, then replace blank lines", "# with <BLANKLINE> in the actual output string.", "if", "not", "(", "opti...
48.617021
18.787234
def get_stft_kernels(n_dft): """[np] Return dft kernels for real/imagnary parts assuming the input . is real. An asymmetric hann window is used (scipy.signal.hann). Parameters ---------- n_dft : int > 0 and power of 2 [scalar] Number of dft components. Returns ------- ...
[ "def", "get_stft_kernels", "(", "n_dft", ")", ":", "assert", "n_dft", ">", "1", "and", "(", "(", "n_dft", "&", "(", "n_dft", "-", "1", ")", ")", "==", "0", ")", ",", "(", "'n_dft should be > 1 and power of 2, but n_dft == %d'", "%", "n_dft", ")", "nb_filte...
37.418605
24.069767
def on_data(self, ws, message, message_type, fin): """ Callback executed when message is received from the server. :param ws: Websocket client :param message: utf-8 string which we get from the server. :param message_type: Message type which is either ABNF.OPCODE_TEXT or ABNF.OP...
[ "def", "on_data", "(", "self", ",", "ws", ",", "message", ",", "message_type", ",", "fin", ")", ":", "try", ":", "json_object", "=", "json", ".", "loads", "(", "message", ")", "except", "Exception", ":", "self", ".", "on_error", "(", "ws", ",", "'Una...
39.803922
18.901961
def setup_service(api_name, api_version, credentials=None): """Configures genomics API client. Args: api_name: Name of the Google API (for example: "genomics") api_version: Version of the API (for example: "v2alpha1") credentials: Credentials to be used for the gcloud API calls. Returns: A confi...
[ "def", "setup_service", "(", "api_name", ",", "api_version", ",", "credentials", "=", "None", ")", ":", "if", "not", "credentials", ":", "credentials", "=", "oauth2client", ".", "client", ".", "GoogleCredentials", ".", "get_application_default", "(", ")", "retur...
35.75
23.4375
def clean_jobs(self, link, job_dict=None, clean_all=False): """ Clean up all the jobs associated with this link. Returns a `JobStatus` enum """ failed = False if job_dict is None: job_dict = link.jobs for job_details in job_dict.values(): # clean...
[ "def", "clean_jobs", "(", "self", ",", "link", ",", "job_dict", "=", "None", ",", "clean_all", "=", "False", ")", ":", "failed", "=", "False", "if", "job_dict", "is", "None", ":", "job_dict", "=", "link", ".", "jobs", "for", "job_details", "in", "job_d...
37.388889
16.888889
def set_interval(self, start, end, value, compact=False): """Set the value for the time series on an interval. If compact is True, only set the value if it's different from what it would be anyway. """ # for each interval to render for i, (s, e, v) in enumerate(self.iter...
[ "def", "set_interval", "(", "self", ",", "start", ",", "end", ",", "value", ",", "compact", "=", "False", ")", ":", "# for each interval to render", "for", "i", ",", "(", "s", ",", "e", ",", "v", ")", "in", "enumerate", "(", "self", ".", "iterperiods",...
40.684211
18.631579
def command(func): ''' A decorator to create a function with docopt arguments. It also generates a help function @command def do_myfunc(self, args): """ docopts text """ pass will create def do_myfunc(self, args, arguments): """ docopts text """ ...
[ "def", "command", "(", "func", ")", ":", "classname", "=", "inspect", ".", "getouterframes", "(", "inspect", ".", "currentframe", "(", ")", ")", "[", "1", "]", "[", "3", "]", "name", "=", "func", ".", "__name__", "help_name", "=", "name", ".", "repla...
28.189189
19.108108
def GET_parameteritemvalues(self) -> None: """Get the values of all |ChangeItem| objects handling |Parameter| objects.""" for item in state.parameteritems: self._outputs[item.name] = item.value
[ "def", "GET_parameteritemvalues", "(", "self", ")", "->", "None", ":", "for", "item", "in", "state", ".", "parameteritems", ":", "self", ".", "_outputs", "[", "item", ".", "name", "]", "=", "item", ".", "value" ]
45
2.4
def args_match(m_args, m_kwargs, default, *args, **kwargs): """ :param m_args: values to match args against :param m_kwargs: values to match kwargs against :param arg: args to match :param arg: kwargs to match """ if len(m_args) > len(args): return False for m_arg, arg in zip(m...
[ "def", "args_match", "(", "m_args", ",", "m_kwargs", ",", "default", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "m_args", ")", ">", "len", "(", "args", ")", ":", "return", "False", "for", "m_arg", ",", "arg", "in", "zi...
33.952381
11.190476
def get_geometry_from_IUPAC_symbol(self, IUPAC_symbol): """ Returns the coordination geometry of the given IUPAC symbol. :param IUPAC_symbol: The IUPAC symbol of the coordination geometry. """ for gg in self.cg_list: if gg.IUPAC_symbol == IUPAC_symbol: ...
[ "def", "get_geometry_from_IUPAC_symbol", "(", "self", ",", "IUPAC_symbol", ")", ":", "for", "gg", "in", "self", ".", "cg_list", ":", "if", "gg", ".", "IUPAC_symbol", "==", "IUPAC_symbol", ":", "return", "gg", "raise", "LookupError", "(", "'No coordination geomet...
42.454545
15.181818
def Stream(self, reader, amount=None): """Streams chunks of a given file starting at given offset. Args: reader: A `Reader` instance. amount: An upper bound on number of bytes to read. Yields: `Chunk` instances. """ if amount is None: amount = float("inf") data = reade...
[ "def", "Stream", "(", "self", ",", "reader", ",", "amount", "=", "None", ")", ":", "if", "amount", "is", "None", ":", "amount", "=", "float", "(", "\"inf\"", ")", "data", "=", "reader", ".", "Read", "(", "min", "(", "self", ".", "chunk_size", ",", ...
25.529412
21.352941
def intersect_arc(self, arc): ''' Given an arc, finds the intersection point(s) of this arc with that. Returns a list of 2x1 numpy arrays. The list has length 0, 1 or 2, depending on how many intesection points there are. Points are ordered along the arc. Intersection with the ar...
[ "def", "intersect_arc", "(", "self", ",", "arc", ")", ":", "intersections", "=", "self", ".", "intersect_circle", "(", "arc", ".", "center", ",", "arc", ".", "radius", ")", "isections", "=", "[", "pt", "for", "pt", "in", "intersections", "if", "arc", "...
61.45
36.15
def msg2agent(msg, processor=None, legacy=False, **config): """ Return the single username who is the "agent" for an event. An "agent" is the one responsible for the event taking place, for example, if one person gives karma to another, then both usernames are returned by msg2usernames, but only the on...
[ "def", "msg2agent", "(", "msg", ",", "processor", "=", "None", ",", "legacy", "=", "False", ",", "*", "*", "config", ")", ":", "if", "processor", ".", "agent", "is", "not", "NotImplemented", ":", "return", "processor", ".", "agent", "(", "msg", ",", ...
42.407407
25.37037
def injectAttribute(annotationName, depth, attr, value): """ Inject an attribute in a class from it's class frame. Use in class annnotation to create methods/properties dynamically at class creation time without dealing with metaclass. depth parameter specify the stack depth from the class definiti...
[ "def", "injectAttribute", "(", "annotationName", ",", "depth", ",", "attr", ",", "value", ")", ":", "locals", "=", "reflect", ".", "class_locals", "(", "depth", ",", "annotationName", ")", "injections", "=", "locals", ".", "get", "(", "_ATTRIBUTE_INJECTIONS_AT...
41.785714
16.642857
def write(self, row, col, data, style=None): """ Write data to row, col of worksheet (ws) using the style information. Again, I'm wrapping this because you'll have to do it if you create large amounts of formatted entries in your spreadsheet (else Excel, but probably not...
[ "def", "write", "(", "self", ",", "row", ",", "col", ",", "data", ",", "style", "=", "None", ")", ":", "ws", "=", "self", ".", "ws", "if", "not", "ws", ":", "raise", "Exception", "(", "'you must use set_sheet() before write()'", ")", "if", "style", ":"...
32.857143
18
def WriteForemanRule(self, rule, cursor=None): """Writes a foreman rule to the database.""" query = ("INSERT INTO foreman_rules " " (hunt_id, expiration_time, rule) " "VALUES (%s, FROM_UNIXTIME(%s), %s) " "ON DUPLICATE KEY UPDATE " " expiration_time=FROM_UNI...
[ "def", "WriteForemanRule", "(", "self", ",", "rule", ",", "cursor", "=", "None", ")", ":", "query", "=", "(", "\"INSERT INTO foreman_rules \"", "\" (hunt_id, expiration_time, rule) \"", "\"VALUES (%s, FROM_UNIXTIME(%s), %s) \"", "\"ON DUPLICATE KEY UPDATE \"", "\" expiration_...
47.545455
14.454545
def delete(self, path, auth=None, **kwargs): """ Manually make a DELETE request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the ...
[ "def", "delete", "(", "self", ",", "path", ",", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_check_ok", "(", "self", ".", "_delete", "(", "path", ",", "auth", "=", "auth", ",", "*", "*", "kwargs", ")", ")" ]
51.666667
23.333333
def save_list(lst, path): """ Save items from list to the file. """ with open(path, 'wb') as out: lines = [] for item in lst: if isinstance(item, (six.text_type, six.binary_type)): lines.append(make_str(item)) else: lines.append(ma...
[ "def", "save_list", "(", "lst", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "out", ":", "lines", "=", "[", "]", "for", "item", "in", "lst", ":", "if", "isinstance", "(", "item", ",", "(", "six", ".", "text_type", ...
29.076923
13.538462
def get_commands_in_namespace(namespace=None, level=1): """Get commands in namespace. Args: namespace (dict|module): Typically a module. If not passed, the globals from the call site will be used. level (int): If not called from the global scope, set this appropriately t...
[ "def", "get_commands_in_namespace", "(", "namespace", "=", "None", ",", "level", "=", "1", ")", ":", "from", ".", ".", "command", "import", "Command", "# noqa: Avoid circular import", "commands", "=", "{", "}", "if", "namespace", "is", "None", ":", "frame", ...
33.133333
19.133333
def course_register_user(self, course, username=None, password=None, force=False): """ Register a user to the course :param course: a Course object :param username: The username of the user that we want to register. If None, uses self.session_username() :param password: Password ...
[ "def", "course_register_user", "(", "self", ",", "course", ",", "username", "=", "None", ",", "password", "=", "None", ",", "force", "=", "False", ")", ":", "if", "username", "is", "None", ":", "username", "=", "self", ".", "session_username", "(", ")", ...
50.888889
31.888889
def _standardize(structure): ''' Return standardized format for lists/dictionaries. Lists of dictionaries are sorted by the value of the dictionary at its primary key ('id' or 'key'). OrderedDict's are converted to basic dictionaries. ''' def mutating_helper(structure): if isinstanc...
[ "def", "_standardize", "(", "structure", ")", ":", "def", "mutating_helper", "(", "structure", ")", ":", "if", "isinstance", "(", "structure", ",", "list", ")", ":", "structure", ".", "sort", "(", "key", "=", "_id_or_key", ")", "for", "each", "in", "stru...
33.727273
14.181818
def density2d(data, channels=[0,1], bins=1024, mode='mesh', normed=False, smooth=True, sigma=10.0, colorbar=False, xscale='logicle', yscale='logicle', xlabel=None, y...
[ "def", "density2d", "(", "data", ",", "channels", "=", "[", "0", ",", "1", "]", ",", "bins", "=", "1024", ",", "mode", "=", "'mesh'", ",", "normed", "=", "False", ",", "smooth", "=", "True", ",", "sigma", "=", "10.0", ",", "colorbar", "=", "False...
37.860558
20.697211
def download_images(urls:Collection[str], dest:PathOrStr, max_pics:int=1000, max_workers:int=8, timeout=4): "Download images listed in text file `urls` to path `dest`, at most `max_pics`" urls = open(urls).read().strip().split("\n")[:max_pics] dest = Path(dest) dest.mkdir(exist_ok=True) parallel(par...
[ "def", "download_images", "(", "urls", ":", "Collection", "[", "str", "]", ",", "dest", ":", "PathOrStr", ",", "max_pics", ":", "int", "=", "1000", ",", "max_workers", ":", "int", "=", "8", ",", "timeout", "=", "4", ")", ":", "urls", "=", "open", "...
66.166667
36.166667
def _check_for_degenerate_interesting_groups(items): """ Make sure interesting_groups specify existing metadata and that the interesting_group is not all of the same for all of the samples """ igkey = ("algorithm", "bcbiornaseq", "interesting_groups") interesting_groups = tz.get_in(igkey, items[0], ...
[ "def", "_check_for_degenerate_interesting_groups", "(", "items", ")", ":", "igkey", "=", "(", "\"algorithm\"", ",", "\"bcbiornaseq\"", ",", "\"interesting_groups\"", ")", "interesting_groups", "=", "tz", ".", "get_in", "(", "igkey", ",", "items", "[", "0", "]", ...
56.875
17.5
def train( self, true_sampler, generative_model, discriminative_model, iter_n=100, k_step=10 ): ''' Train. Args: true_sampler: Sampler which draws samples from the `true` distribution. generative_...
[ "def", "train", "(", "self", ",", "true_sampler", ",", "generative_model", ",", "discriminative_model", ",", "iter_n", "=", "100", ",", "k_step", "=", "10", ")", ":", "if", "isinstance", "(", "true_sampler", ",", "TrueSampler", ")", "is", "False", ":", "ra...
37.734177
22.316456
def validate_password_strength(value): """Validates that a password is as least 7 characters long and has at least 1 digit and 1 letter. """ min_length = 7 if len(value) < min_length: raise ValidationError(_('Password must be at least {0} characters ' 'long.'...
[ "def", "validate_password_strength", "(", "value", ")", ":", "min_length", "=", "7", "if", "len", "(", "value", ")", "<", "min_length", ":", "raise", "ValidationError", "(", "_", "(", "'Password must be at least {0} characters '", "'long.'", ")", ".", "format", ...
36.764706
20.529412
def casefold_with_i_dots(text): """ Convert capital I's and capital dotted İ's to lowercase in the way that's appropriate for Turkish and related languages, then case-fold the rest of the letters. """ text = unicodedata.normalize('NFC', text).replace('İ', 'i').replace('I', 'ı') return text.c...
[ "def", "casefold_with_i_dots", "(", "text", ")", ":", "text", "=", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "text", ")", ".", "replace", "(", "'İ',", " ", "i')", ".", "r", "eplace(", "'", "I',", " ", "ı')", "", "return", "text", ".", "case...
40.25
17.25
def _fix_alert_poster(self, state, shard): ''' Called after agent has switched a shard. Alert poster needs an update in this case, bacause otherwise its posting to lobby instead of the shard exchange. ''' recp = recipient.Broadcast(AlertPoster.protocol_id, shard) ...
[ "def", "_fix_alert_poster", "(", "self", ",", "state", ",", "shard", ")", ":", "recp", "=", "recipient", ".", "Broadcast", "(", "AlertPoster", ".", "protocol_id", ",", "shard", ")", "state", ".", "alerter", ".", "update_recipients", "(", "recp", ")" ]
43.75
22.5
def p_expr_plus_expr(p): """ expr : expr PLUS expr """ p[0] = make_binary(p.lineno(2), 'PLUS', p[1], p[3], lambda x, y: x + y)
[ "def", "p_expr_plus_expr", "(", "p", ")", ":", "p", "[", "0", "]", "=", "make_binary", "(", "p", ".", "lineno", "(", "2", ")", ",", "'PLUS'", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lambda", "x", ",", "y", ":", "x", "+", "...
33.75
12.75
def dist_euclidean(src, tar, qval=2, alphabet=None): """Return the normalized Euclidean distance between two strings. This is a wrapper for :py:meth:`Euclidean.dist`. Parameters ---------- src : str Source string (or QGrams/Counter objects) for comparison tar : str Target strin...
[ "def", "dist_euclidean", "(", "src", ",", "tar", ",", "qval", "=", "2", ",", "alphabet", "=", "None", ")", ":", "return", "Euclidean", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "qval", ",", "alphabet", ")" ]
26.588235
21.264706