text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def insert(self, index, value): """ Insert object before index. :param int index: index to insert in :param string value: path to insert """ self._list.insert(index, value) self._sync()
[ "def", "insert", "(", "self", ",", "index", ",", "value", ")", ":", "self", ".", "_list", ".", "insert", "(", "index", ",", "value", ")", "self", ".", "_sync", "(", ")" ]
26
9.111111
def path_deserialize(cls, serialized_path): """ Given a netstring of path parts, go and parse it back into [{'hash': ..., 'order': ...}] """ def _chomp_netstring_payload(s): try: ns_len_str, ns_body = s.split(':', 1) ns_len = int(ns_len_str) ...
[ "def", "path_deserialize", "(", "cls", ",", "serialized_path", ")", ":", "def", "_chomp_netstring_payload", "(", "s", ")", ":", "try", ":", "ns_len_str", ",", "ns_body", "=", "s", ".", "split", "(", "':'", ",", "1", ")", "ns_len", "=", "int", "(", "ns_...
36.40625
20.34375
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._contract_date_start is not None: ...
[ "def", "is_all_field_none", "(", "self", ")", ":", "if", "self", ".", "_id_", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_created", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_updated", "is", "not", "None", ...
21.055556
19.888889
def get_cursor_pos(window): """ Retrieves the last reported cursor position, relative to the client area of the window. Wrapper for: void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); """ xpos_value = ctypes.c_double(0.0) xpos = ctypes.pointer(xpos_value) ypo...
[ "def", "get_cursor_pos", "(", "window", ")", ":", "xpos_value", "=", "ctypes", ".", "c_double", "(", "0.0", ")", "xpos", "=", "ctypes", ".", "pointer", "(", "xpos_value", ")", "ypos_value", "=", "ctypes", ".", "c_double", "(", "0.0", ")", "ypos", "=", ...
33.428571
13.285714
def calc_tmean_v1(self): """Calculate the areal mean temperature of the subbasin. Required derived parameter: |RelZoneArea| Required flux sequence: |TC| Calculated flux sequences: |TMean| Examples: Prepare two zones, the first one being twice as large as the se...
[ "def", "calc_tmean_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", ...
25.361111
19
def args_to_inject(self, function, bindings, owner_key): """Inject arguments into a function. :param function: The function. :param bindings: Map of argument name to binding key to inject. :param owner_key: A key uniquely identifying the *scope* of this function. For a metho...
[ "def", "args_to_inject", "(", "self", ",", "function", ",", "bindings", ",", "owner_key", ")", ":", "dependencies", "=", "{", "}", "key", "=", "(", "owner_key", ",", "function", ",", "tuple", "(", "sorted", "(", "bindings", ".", "items", "(", ")", ")",...
36.717949
21.205128
def render_page_with_error_code_message(request, context_data, error_code, log_message): """ Return a 404 page with specified error_code after logging error and adding message to django messages. """ LOGGER.error(log_message) messages.add_generic_error_message_with_code(request, error_code) retu...
[ "def", "render_page_with_error_code_message", "(", "request", ",", "context_data", ",", "error_code", ",", "log_message", ")", ":", "LOGGER", ".", "error", "(", "log_message", ")", "messages", ".", "add_generic_error_message_with_code", "(", "request", ",", "error_cod...
35.916667
22.416667
def data_filter(self, data): """Return an instance of the Data Filter Class. A simple helper module to filter results from ThreatConnect API or other data source. For example if results need to be filtered by an unsupported field the module allows you to pass the data array/list in and...
[ "def", "data_filter", "(", "self", ",", "data", ")", ":", "try", ":", "from", ".", "tcex_data_filter", "import", "DataFilter", "return", "DataFilter", "(", "self", ",", "data", ")", "except", "ImportError", "as", "e", ":", "warn", "=", "u'Required Module is ...
37.428571
24.761905
def upload_docs( client, input_filename, language, name, account=None, progress=False ): """ Given a LuminosoClient pointing to the root of the API, and a filename to read JSON lines from, create a project from the documents in that file. """ docs = iterate_json_lines(input_filename) return ...
[ "def", "upload_docs", "(", "client", ",", "input_filename", ",", "language", ",", "name", ",", "account", "=", "None", ",", "progress", "=", "False", ")", ":", "docs", "=", "iterate_json_lines", "(", "input_filename", ")", "return", "create_project_with_docs", ...
36.909091
21.272727
def _if(cls, verb): """ A verb with a predicate function """ pred = verb.predicate data = verb.data groups = set(_get_groups(verb)) # force predicate if isinstance(pred, str): if not pred.endswith('_dtype'): pred = '{}_dtype'.f...
[ "def", "_if", "(", "cls", ",", "verb", ")", ":", "pred", "=", "verb", ".", "predicate", "data", "=", "verb", ".", "data", "groups", "=", "set", "(", "_get_groups", "(", "verb", ")", ")", "# force predicate", "if", "isinstance", "(", "pred", ",", "str...
29.363636
13.090909
def format_national_number_with_carrier_code(numobj, carrier_code): """Format a number in national format for dialing using the specified carrier. The carrier-code will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If carrier_code contains a...
[ "def", "format_national_number_with_carrier_code", "(", "numobj", ",", "carrier_code", ")", ":", "country_code", "=", "numobj", ".", "country_code", "nsn", "=", "national_significant_number", "(", "numobj", ")", "if", "not", "_has_valid_country_calling_code", "(", "coun...
54.131579
23.789474
def write_command(self, request_id, msg, docs): """A proxy for SocketInfo.write_command that handles event publishing. """ if self.publish: duration = datetime.datetime.now() - self.start_time self._start(request_id, docs) start = datetime.datetime.now() ...
[ "def", "write_command", "(", "self", ",", "request_id", ",", "msg", ",", "docs", ")", ":", "if", "self", ".", "publish", ":", "duration", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "start_time", "self", ".", "_start", "...
42.35
15.5
def leave_group(self, group_alias): """ 退出小组 :param group_alias: 小组ID :return: """ return self.api.req(API_GROUP_GROUP_HOME % group_alias, params={ 'action': 'quit', 'ck': self.api.ck(), })
[ "def", "leave_group", "(", "self", ",", "group_alias", ")", ":", "return", "self", ".", "api", ".", "req", "(", "API_GROUP_GROUP_HOME", "%", "group_alias", ",", "params", "=", "{", "'action'", ":", "'quit'", ",", "'ck'", ":", "self", ".", "api", ".", "...
24.454545
16.090909
def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None: """ Variables can be treated as numbers or strings if their type can be inferred - however, that can be difficult, so instead, we can just treat them all as values and be a bit looser on the typing we allow in ou...
[ "def", "update_grammar_with_untyped_entities", "(", "grammar_dictionary", ":", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ")", "->", "None", ":", "grammar_dictionary", "[", "\"string_set_vals\"", "]", "=", "[", "'(value ws \",\" ws string_set_vals)'", ",...
59.785714
25.642857
def is_scalar(self, typ: Type = _Any) -> bool: """Returns True iff this represents a scalar node. If a type is given, checks that the ScalarNode represents this \ type. Type may be `str`, `int`, `float`, `bool`, or `None`. If no type is given, any ScalarNode will return True. "...
[ "def", "is_scalar", "(", "self", ",", "typ", ":", "Type", "=", "_Any", ")", "->", "bool", ":", "if", "isinstance", "(", "self", ".", "yaml_node", ",", "yaml", ".", "ScalarNode", ")", ":", "if", "typ", "!=", "_Any", "and", "typ", "in", "scalar_type_to...
39.388889
19.888889
def var( type=None, # noqa default=None, name=None, title=None, description=None, required=True, examples=None, encoder=None, decoder=None, min=None, # noqa max=None, # noqa unique=None, contains=None, **kwargs, ): """ Creates a config variable. Use th...
[ "def", "var", "(", "type", "=", "None", ",", "# noqa", "default", "=", "None", ",", "name", "=", "None", ",", "title", "=", "None", ",", "description", "=", "None", ",", "required", "=", "True", ",", "examples", "=", "None", ",", "encoder", "=", "N...
37.136986
22.575342
def is_dynamic_overlay(dmap): """ Traverses a DynamicMap graph and determines if any components were overlaid dynamically (i.e. by * on a DynamicMap). """ if not isinstance(dmap, DynamicMap): return False elif dmap.callback._is_overlay: return True else: return any(is...
[ "def", "is_dynamic_overlay", "(", "dmap", ")", ":", "if", "not", "isinstance", "(", "dmap", ",", "DynamicMap", ")", ":", "return", "False", "elif", "dmap", ".", "callback", ".", "_is_overlay", ":", "return", "True", "else", ":", "return", "any", "(", "is...
32.909091
14.909091
def ls(bank): ''' Return an iterable object containing all entries stored in the specified bank. ''' _init_client() query = "SELECT etcd_key FROM {0} WHERE bank='{1}'".format( _table_name, bank) cur, _ = run_query(client, query) out = [row[0] for row in cur.fetchall()] cur.cl...
[ "def", "ls", "(", "bank", ")", ":", "_init_client", "(", ")", "query", "=", "\"SELECT etcd_key FROM {0} WHERE bank='{1}'\"", ".", "format", "(", "_table_name", ",", "bank", ")", "cur", ",", "_", "=", "run_query", "(", "client", ",", "query", ")", "out", "=...
27.416667
23.083333
def credits(self, **kwargs): """ Get the cast & crew credits for a TV season by season number. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_path('credits') response = self._GET(path, kwargs) ...
[ "def", "credits", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_series_id_season_number_path", "(", "'credits'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_value...
31.333333
18.333333
def _listdir(pth, extensions): """Non-raising listdir.""" try: return [fname for fname in os.listdir(pth) if os.path.splitext(fname)[1] in extensions] except OSError: # pragma: nocover pass
[ "def", "_listdir", "(", "pth", ",", "extensions", ")", ":", "try", ":", "return", "[", "fname", "for", "fname", "in", "os", ".", "listdir", "(", "pth", ")", "if", "os", ".", "path", ".", "splitext", "(", "fname", ")", "[", "1", "]", "in", "extens...
32.571429
14.571429
def image_show(self, image_id): ''' Show image details and metadata ''' nt_ks = self.compute_conn image = nt_ks.images.get(image_id) links = {} for link in image.links: links[link['rel']] = link['href'] ret = { 'name': image.name, ...
[ "def", "image_show", "(", "self", ",", "image_id", ")", ":", "nt_ks", "=", "self", ".", "compute_conn", "image", "=", "nt_ks", ".", "images", ".", "get", "(", "image_id", ")", "links", "=", "{", "}", "for", "link", "in", "image", ".", "links", ":", ...
29.24
11.48
def _local(self, args): ''' Process local commands ''' args.pop(0) command = args[0] if command == 'install': self._local_install(args) elif command == 'files': self._local_list_files(args) elif command == 'info': self._...
[ "def", "_local", "(", "self", ",", "args", ")", ":", "args", ".", "pop", "(", "0", ")", "command", "=", "args", "[", "0", "]", "if", "command", "==", "'install'", ":", "self", ".", "_local_install", "(", "args", ")", "elif", "command", "==", "'file...
30.214286
16.214286
def maximum(left, right): """Returns element-wise maximum of the input elements. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Parameters --------- left : Symbol or scalar First symbol to be compared. right : Symbol or scalar Second symbol to be com...
[ "def", "maximum", "(", "left", ",", "right", ")", ":", "if", "isinstance", "(", "left", ",", "Symbol", ")", "and", "isinstance", "(", "right", ",", "Symbol", ")", ":", "return", "_internal", ".", "_Maximum", "(", "left", ",", "right", ")", "if", "isi...
34.55
20.025
async def is_cn(self, client): """Return True if node at {base_url} is a CN, False if it is an MN. Raise a DataONEException if it's not a functional CN or MN. """ node_pyxb = await client.get_capabilities() return d1_common.type_conversions.pyxb_get_type_name(node_pyxb) == "Nod...
[ "async", "def", "is_cn", "(", "self", ",", "client", ")", ":", "node_pyxb", "=", "await", "client", ".", "get_capabilities", "(", ")", "return", "d1_common", ".", "type_conversions", ".", "pyxb_get_type_name", "(", "node_pyxb", ")", "==", "\"NodeList\"" ]
39.875
21.625
def _matrix3_to_dcm_array(self, m): """ Converts Matrix3 in an array :param m: Matrix3 :returns: 3x3 array """ assert(isinstance(m, Matrix3)) return np.array([[m.a.x, m.a.y, m.a.z], [m.b.x, m.b.y, m.b.z], [m.c.x, m...
[ "def", "_matrix3_to_dcm_array", "(", "self", ",", "m", ")", ":", "assert", "(", "isinstance", "(", "m", ",", "Matrix3", ")", ")", "return", "np", ".", "array", "(", "[", "[", "m", ".", "a", ".", "x", ",", "m", ".", "a", ".", "y", ",", "m", "....
32.5
6.1
def parse(file_path, content=None): """ Create a PythonFile object with specified file_path and content. If content is None then, it is loaded from the file_path method. Otherwise, file_path is only used for reporting errors. """ try: # Parso reads files in bi...
[ "def", "parse", "(", "file_path", ",", "content", "=", "None", ")", ":", "try", ":", "# Parso reads files in binary mode and converts to unicode", "# using python_bytes_to_unicode() function. As a result,", "# we no longer have information about original file encoding and", "# output o...
52.227273
19.227273
def set_split_extents_by_split_size(self): """ Sets split shape :attr:`split_shape` and split extents (:attr:`split_begs` and :attr:`split_ends`) from values in :attr:`split_size` and :attr:`split_num_slices_per_axis`. """ if self.split_size is None: if ( ...
[ "def", "set_split_extents_by_split_size", "(", "self", ")", ":", "if", "self", ".", "split_size", "is", "None", ":", "if", "(", "_np", ".", "all", "(", "[", "s", "is", "not", "None", "for", "s", "in", "self", ".", "split_num_slices_per_axis", "]", ")", ...
41.891304
17.934783
def stacked_violin(adata, var_names, groupby=None, log=False, use_raw=None, num_categories=7, figsize=None, dendrogram=False, gene_symbols=None, var_group_positions=None, var_group_labels=None, standard_scale=None, var_group_rotation=None, layer=None, stripplot=...
[ "def", "stacked_violin", "(", "adata", ",", "var_names", ",", "groupby", "=", "None", ",", "log", "=", "False", ",", "use_raw", "=", "None", ",", "num_categories", "=", "7", ",", "figsize", "=", "None", ",", "dendrogram", "=", "False", ",", "gene_symbols...
45.952703
26.929054
def reporter(self): """ Create reports of the analyses """ # Create a folder in which amplicons and raw BLAST results are to be stored detailed_reports = os.path.join(self.path, 'detailed_reports') make_path(detailed_reports) # Create the report path if necessary ...
[ "def", "reporter", "(", "self", ")", ":", "# Create a folder in which amplicons and raw BLAST results are to be stored", "detailed_reports", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'detailed_reports'", ")", "make_path", "(", "detailed_report...
64.483871
30.822581
def load_member(fqn): """Loads and returns a class for a given fully qualified name.""" modulename, member_name = split_fqn(fqn) module = __import__(modulename, globals(), locals(), member_name) return getattr(module, member_name)
[ "def", "load_member", "(", "fqn", ")", ":", "modulename", ",", "member_name", "=", "split_fqn", "(", "fqn", ")", "module", "=", "__import__", "(", "modulename", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "member_name", ")", "return", "getatt...
48.4
10.6
def main(self, *args, **kwargs): ''' Instanciate ScriptInfo before parent does to ensure the `settings` parameters is available to `create_app ''' obj = kwargs.get('obj') if obj is None: obj = ScriptInfo(create_app=self.create_app) # This is the import...
[ "def", "main", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "kwargs", ".", "get", "(", "'obj'", ")", "if", "obj", "is", "None", ":", "obj", "=", "ScriptInfo", "(", "create_app", "=", "self", ".", "create_app", ")"...
43.166667
20.666667
def create_table(self, conn): """Make table definitions""" # Make cursor cur = conn.cursor() # Drop table if it already exists, to be recreated. This # could in the future abort if table already exists, and not # recreate it from scratch. #cur.execute('''DROP TAB...
[ "def", "create_table", "(", "self", ",", "conn", ")", ":", "# Make cursor", "cur", "=", "conn", ".", "cursor", "(", ")", "# Drop table if it already exists, to be recreated. This", "# could in the future abort if table already exists, and not", "# recreate it from scratch.", "...
38.52381
14.904762
def get_gitdir(self): """Determine the git repository for this request""" if self.gitlookup is None: raise tornado.web.HTTPError(500, 'no git lookup configured') gitdir = self.gitlookup(self.request) if gitdir is None: raise tornado.web.HTTPError(404, 'unable to ...
[ "def", "get_gitdir", "(", "self", ")", ":", "if", "self", ".", "gitlookup", "is", "None", ":", "raise", "tornado", ".", "web", ".", "HTTPError", "(", "500", ",", "'no git lookup configured'", ")", "gitdir", "=", "self", ".", "gitlookup", "(", "self", "."...
36.636364
20
def remove_urls(text_string): ''' Removes all URLs within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None or text_string == "...
[ "def", "remove_urls", "(", "text_string", ")", ":", "if", "text_string", "is", "None", "or", "text_string", "==", "\"\"", ":", "return", "\"\"", "elif", "isinstance", "(", "text_string", ",", "str", ")", ":", "return", "\" \"", ".", "join", "(", "re", "....
27.722222
25.055556
def delete(self): """ Removes a container that was created earlier. """ if not self.is_created(): LOG.debug("Container was not created. Skipping deletion") return try: self.docker_client.containers\ .get(self.id)\ ...
[ "def", "delete", "(", "self", ")", ":", "if", "not", "self", ".", "is_created", "(", ")", ":", "LOG", ".", "debug", "(", "\"Container was not created. Skipping deletion\"", ")", "return", "try", ":", "self", ".", "docker_client", ".", "containers", ".", "get...
36.76
20.44
def _add_existing_weight(self, weight, trainable=None): """Calls add_weight() to register but not create an existing weight.""" if trainable is None: trainable = weight.trainable self.add_weight(name=weight.name, shape=weight.shape, dtype=weight.dtype, trainable=trainable, getter=lambda ...
[ "def", "_add_existing_weight", "(", "self", ",", "weight", ",", "trainable", "=", "None", ")", ":", "if", "trainable", "is", "None", ":", "trainable", "=", "weight", ".", "trainable", "self", ".", "add_weight", "(", "name", "=", "weight", ".", "name", ",...
66.6
19.6
def list_users(): """ List all users on the database """ echo_header("List of users") for user in current_app.appbuilder.sm.get_all_users(): click.echo( "username:{0} | email:{1} | role:{2}".format( user.username, user.email, user.roles ) )
[ "def", "list_users", "(", ")", ":", "echo_header", "(", "\"List of users\"", ")", "for", "user", "in", "current_app", ".", "appbuilder", ".", "sm", ".", "get_all_users", "(", ")", ":", "click", ".", "echo", "(", "\"username:{0} | email:{1} | role:{2}\"", ".", ...
28.181818
14.545455
def set_vm_status(self, device='FLOPPY', boot_option='BOOT_ONCE', write_protect='YES'): """Sets the Virtual Media drive status and allows the boot options for booting from the virtual media. """ return self._call_method('set_vm_status', device, boot_option, ...
[ "def", "set_vm_status", "(", "self", ",", "device", "=", "'FLOPPY'", ",", "boot_option", "=", "'BOOT_ONCE'", ",", "write_protect", "=", "'YES'", ")", ":", "return", "self", ".", "_call_method", "(", "'set_vm_status'", ",", "device", ",", "boot_option", ",", ...
44.125
15.125
def requirements_check(): """ Ensure we have programs needed to download/manipulate the data """ required_programs = [ ('samtools', 'http://samtools.sourceforge.net/'), ('bedtools', 'http://bedtools.readthedocs.org/en/latest/'), ('bigWigToBedGraph', 'ht...
[ "def", "requirements_check", "(", ")", ":", "required_programs", "=", "[", "(", "'samtools'", ",", "'http://samtools.sourceforge.net/'", ")", ",", "(", "'bedtools'", ",", "'http://bedtools.readthedocs.org/en/latest/'", ")", ",", "(", "'bigWigToBedGraph'", ",", "'http://...
35.809524
16.380952
def gaussian(times: np.ndarray, amp: complex, center: float, sigma: float, zeroed_width: Union[None, float] = None, rescale_amp: bool = False, ret_x: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: r"""Continuous unnormalized gaussian pulse. Integrated area under cu...
[ "def", "gaussian", "(", "times", ":", "np", ".", "ndarray", ",", "amp", ":", "complex", ",", "center", ":", "float", ",", "sigma", ":", "float", ",", "zeroed_width", ":", "Union", "[", "None", ",", "float", "]", "=", "None", ",", "rescale_amp", ":", ...
51.147059
28.676471
def get(self, key): """Return set of descendants of node named `key` in `target_graph`. Returns from cached dict if exists, otherwise compute over the graph and cache results in the dict. """ if key not in self: self[key] = set(get_descendants(self._target_graph, key...
[ "def", "get", "(", "self", ",", "key", ")", ":", "if", "key", "not", "in", "self", ":", "self", "[", "key", "]", "=", "set", "(", "get_descendants", "(", "self", ".", "_target_graph", ",", "key", ")", ")", "return", "self", "[", "key", "]" ]
37.666667
17.444444
def wr_hdrs(self, worksheet, row_idx): """Print row of column headers""" for col_idx, hdr in enumerate(self.hdrs): # print("ROW({R}) COL({C}) HDR({H}) FMT({F})\n".format( # R=row_idx, C=col_idx, H=hdr, F=self.fmt_hdr)) worksheet.write(row_idx, col_idx, hdr, self.f...
[ "def", "wr_hdrs", "(", "self", ",", "worksheet", ",", "row_idx", ")", ":", "for", "col_idx", ",", "hdr", "in", "enumerate", "(", "self", ".", "hdrs", ")", ":", "# print(\"ROW({R}) COL({C}) HDR({H}) FMT({F})\\n\".format(", "# R=row_idx, C=col_idx, H=hdr, F=self.fmt_h...
45.5
15.375
def get_state_actions(self, state, **kwargs): """ Restarts instance containers. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :...
[ "def", "get_state_actions", "(", "self", ",", "state", ",", "*", "*", "kwargs", ")", ":", "if", "(", "state", ".", "config_id", ".", "config_type", "==", "ItemType", ".", "CONTAINER", "and", "state", ".", "base_state", "!=", "State", ".", "ABSENT", "and"...
49.25
20
def result_pretty(self, number_of_runs=0, time_str=None, fbestever=None): """pretty print result. Returns ``self.result()`` """ if fbestever is None: fbestever = self.best.f s = (' after %i restart' + ('s' if number_of_runs > 1 else '')) \ ...
[ "def", "result_pretty", "(", "self", ",", "number_of_runs", "=", "0", ",", "time_str", "=", "None", ",", "fbestever", "=", "None", ")", ":", "if", "fbestever", "is", "None", ":", "fbestever", "=", "self", ".", "best", ".", "f", "s", "=", "(", "' afte...
50
28.416667
def __adjust_name(self, specified_name): """Given the target name specified in constructor, returns the name which should be really used, by looking at the <tag> properties. The tag properties come in two flavour: - <tag>value, - <tag>@rule-name In the first case, val...
[ "def", "__adjust_name", "(", "self", ",", "specified_name", ")", ":", "assert", "isinstance", "(", "specified_name", ",", "basestring", ")", "if", "self", ".", "action_", ":", "ps", "=", "self", ".", "action_", ".", "properties", "(", ")", "else", ":", "...
44.490566
20.54717
def create_socket(): """Creates a raw CAN socket. The socket will be returned unbound to any interface. """ sock = socket.socket(PF_CAN, socket.SOCK_RAW, CAN_RAW) log.info('Created a socket') return sock
[ "def", "create_socket", "(", ")", ":", "sock", "=", "socket", ".", "socket", "(", "PF_CAN", ",", "socket", ".", "SOCK_RAW", ",", "CAN_RAW", ")", "log", ".", "info", "(", "'Created a socket'", ")", "return", "sock" ]
24.555556
16.888889
def remove_existing_fpaths(fpath_list, verbose=VERBOSE, quiet=QUIET, strict=False, print_caller=PRINT_CALLER, lbl='files'): """ checks existance before removing. then tries to remove exisint paths """ import utool as ut if print_caller: print(uti...
[ "def", "remove_existing_fpaths", "(", "fpath_list", ",", "verbose", "=", "VERBOSE", ",", "quiet", "=", "QUIET", ",", "strict", "=", "False", ",", "print_caller", "=", "PRINT_CALLER", ",", "lbl", "=", "'files'", ")", ":", "import", "utool", "as", "ut", "if"...
49.32
16.6
def clip_global_norm(arrays, max_norm, check_isfinite=True): """Rescales NDArrays so that the sum of their 2-norm is smaller than `max_norm`. Parameters ---------- arrays : list of NDArray max_norm : float check_isfinite : bool, default True If True, check that the total_norm is finite...
[ "def", "clip_global_norm", "(", "arrays", ",", "max_norm", ",", "check_isfinite", "=", "True", ")", ":", "def", "_norm", "(", "array", ")", ":", "if", "array", ".", "stype", "==", "'default'", ":", "x", "=", "array", ".", "reshape", "(", "(", "-", "1...
35.1
17.975
def add_node(self, name, **attr): ''' API: add_node(self, name, **attr) Description: Adds node to the graph. Pre: Graph should not contain a node with this name. We do not allow multiple nodes with the same name. Input: name: Name of th...
[ "def", "add_node", "(", "self", ",", "name", ",", "*", "*", "attr", ")", ":", "if", "name", "in", "self", ".", "neighbors", ":", "raise", "MultipleNodeException", "self", ".", "neighbors", "[", "name", "]", "=", "list", "(", ")", "if", "self", ".", ...
34.73913
14.73913
def __standardize_result(status, message, data=None, debug_msg=None): ''' Standardizes all responses :param status: :param message: :param data: :param debug_msg: :return: ''' result = { 'status': status, 'message': message } if data is not None: res...
[ "def", "__standardize_result", "(", "status", ",", "message", ",", "data", "=", "None", ",", "debug_msg", "=", "None", ")", ":", "result", "=", "{", "'status'", ":", "status", ",", "'message'", ":", "message", "}", "if", "data", "is", "not", "None", ":...
18.863636
23.772727
def create_pull(self, title, base, head, body=None): """Create a pull request of ``head`` onto ``base`` branch in this repo. :param str title: (required) :param str base: (required), e.g., 'master' :param str head: (required), e.g., 'username:branch' :param str body: (optional),...
[ "def", "create_pull", "(", "self", ",", "title", ",", "base", ",", "head", ",", "body", "=", "None", ")", ":", "data", "=", "{", "'title'", ":", "title", ",", "'body'", ":", "body", ",", "'base'", ":", "base", ",", "'head'", ":", "head", "}", "re...
44.923077
14
def create_ecdsap256_key_pair(): """ Create a new ECDSAP256 key pair. :returns: a tuple of the public and private keys """ pub = ECDSAP256PublicKey() priv = ECDSAP256PrivateKey() rc = _lib.xtt_crypto_create_ecdsap256_key_pair(pub.native, priv.native) if rc == RC.SUCCESS: return...
[ "def", "create_ecdsap256_key_pair", "(", ")", ":", "pub", "=", "ECDSAP256PublicKey", "(", ")", "priv", "=", "ECDSAP256PrivateKey", "(", ")", "rc", "=", "_lib", ".", "xtt_crypto_create_ecdsap256_key_pair", "(", "pub", ".", "native", ",", "priv", ".", "native", ...
28
14.153846
def get_abi(self, hsh: bytes) -> Dict[str, Any]: """Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``. If no normal contract function has the specified selector, a dict describing the default or non-default fallback function is returned. ...
[ "def", "get_abi", "(", "self", ",", "hsh", ":", "bytes", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "if", "not", "isinstance", "(", "hsh", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "raise", "TypeError", "(", "'The selector argumen...
54
24.833333
def store(self, server, username, secret): """ Store credentials for `server`. Raises a `StoreError` if an error occurs. """ data_input = json.dumps({ 'ServerURL': server, 'Username': username, 'Secret': secret }).encode('utf-8') re...
[ "def", "store", "(", "self", ",", "server", ",", "username", ",", "secret", ")", ":", "data_input", "=", "json", ".", "dumps", "(", "{", "'ServerURL'", ":", "server", ",", "'Username'", ":", "username", ",", "'Secret'", ":", "secret", "}", ")", ".", ...
35
8
def _calc_g(w, aod700): """Calculate the g coefficient.""" g = -0.0147*np.log(w) - 0.3079*aod700**2 + 0.2846*aod700 + 0.3798 return g
[ "def", "_calc_g", "(", "w", ",", "aod700", ")", ":", "g", "=", "-", "0.0147", "*", "np", ".", "log", "(", "w", ")", "-", "0.3079", "*", "aod700", "**", "2", "+", "0.2846", "*", "aod700", "+", "0.3798", "return", "g" ]
23.666667
25.666667
def get_recent_posts(blog_id, username, password, number): """ metaWeblog.getRecentPosts(blog_id, username, password, number) => post structure[] """ user = authenticate(username, password) site = Site.objects.get_current() return [post_structure(entry, site) for entry in Entry.o...
[ "def", "get_recent_posts", "(", "blog_id", ",", "username", ",", "password", ",", "number", ")", ":", "user", "=", "authenticate", "(", "username", ",", "password", ")", "site", "=", "Site", ".", "objects", ".", "get_current", "(", ")", "return", "[", "p...
38.777778
10.777778
def _is_valid_input(self, inpt, metadata, array): """The _is_valid_input method takes three arguments: the user input to be checked, the associated osid.Metadata object containing validation requirements and a boolean value indicating whether this is an array value. """ ...
[ "def", "_is_valid_input", "(", "self", ",", "inpt", ",", "metadata", ",", "array", ")", ":", "# pylint: disable=too-many-branches,no-self-use", "# Please redesign, and move to utility module", "syntax", "=", "metadata", ".", "get_syntax", "(", ")", "# First check if this is...
39.981481
17.222222
def build_index(): """Load information from the data directory Returns ------- A namedtuple with three fields: nationalities cities countries """ nationalities = read_table(get_data_path('nationalities.txt'), sep=':') # parse http://download.geonames.org/export/dump/countryInfo.txt co...
[ "def", "build_index", "(", ")", ":", "nationalities", "=", "read_table", "(", "get_data_path", "(", "'nationalities.txt'", ")", ",", "sep", "=", "':'", ")", "# parse http://download.geonames.org/export/dump/countryInfo.txt", "countries", "=", "read_table", "(", "get_dat...
33.826087
25.304348
def localize(date_time, time_zone): """Returns a datetime adjusted to a timezone: * If dateTime is a naive datetime (datetime with no timezone information), timezone information is added but date and time remains the same. * If dateTime is not a naive datetime, a datetime object with new tzinfo att...
[ "def", "localize", "(", "date_time", ",", "time_zone", ")", ":", "if", "datetime_is_naive", "(", "date_time", ")", ":", "ret", "=", "time_zone", ".", "localize", "(", "date_time", ")", "else", ":", "ret", "=", "date_time", ".", "astimezone", "(", "time_zon...
43.384615
22.615385
def __validate_required_fields(self, document): """ Validates that required fields are not missing. :param document: The document being validated. """ try: required = set(field for field, definition in self.schema.items() if self._resolve_rules_set...
[ "def", "__validate_required_fields", "(", "self", ",", "document", ")", ":", "try", ":", "required", "=", "set", "(", "field", "for", "field", ",", "definition", "in", "self", ".", "schema", ".", "items", "(", ")", "if", "self", ".", "_resolve_rules_set", ...
43.9
19.033333
def get_layout_template(self, template_name=None): """ Returns the layout template to use when rendering the form to HTML. Preference of template selection: 1. Provided method argument `template_name` 2. Form class property `layout_template` 3. Globally defined default ...
[ "def", "get_layout_template", "(", "self", ",", "template_name", "=", "None", ")", ":", "if", "template_name", ":", "return", "template_name", "if", "self", ".", "layout_template", ":", "return", "self", ".", "layout_template", "return", "defaults", ".", "LAYOUT...
34.75
20.85
def _step(self) -> typing.Union[None, 'projects.ProjectStep']: """ Internal access to the source step. Should not be used outside of Cauldron development. :return: The ProjectStep instance that this ExposedStep represents """ import cauldron try: ...
[ "def", "_step", "(", "self", ")", "->", "typing", ".", "Union", "[", "None", ",", "'projects.ProjectStep'", "]", ":", "import", "cauldron", "try", ":", "return", "cauldron", ".", "project", ".", "get_internal_project", "(", ")", ".", "current_step", "except"...
32.692308
20.076923
def guessFormat(self, name): """ :param name: :type name: str """ name = name.lower() generator = self.generator if re.findall(r'^is[_A-Z]', name): return lambda x:generator.boolean() if re.findall(r'(_a|A)t$', name): return lambda x:generator.dateTime() ...
[ "def", "guessFormat", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "generator", "=", "self", ".", "generator", "if", "re", ".", "findall", "(", "r'^is[_A-Z]'", ",", "name", ")", ":", "return", "lambda", "x", ":", ...
54.625
29.375
def inspect_volume(self, name): """ Retrieve volume info by name. Args: name (str): volume name Returns: (dict): Volume information dictionary Raises: :py:class:`docker.errors.APIError` If the server returns an error. ...
[ "def", "inspect_volume", "(", "self", ",", "name", ")", ":", "url", "=", "self", ".", "_url", "(", "'/volumes/{0}'", ",", "name", ")", "return", "self", ".", "_result", "(", "self", ".", "_get", "(", "url", ")", ",", "True", ")" ]
24.916667
18.333333
def geocode( self, query, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL, ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param int limit: Defines the maximum...
[ "def", "geocode", "(", "self", ",", "query", ",", "limit", "=", "None", ",", "exactly_one", "=", "True", ",", "timeout", "=", "DEFAULT_SENTINEL", ",", ")", ":", "params", "=", "{", "'q'", ":", "self", ".", "format_string", "%", "query", ",", "}", "if...
33.046512
25.55814
def findrootname(filename): """ Return the rootname of the given file. """ puncloc = [filename.find(char) for char in string.punctuation] if sys.version_info[0] >= 3: val = sys.maxsize else: val = sys.maxint for num in puncloc: if num !=-1 and num < val: ...
[ "def", "findrootname", "(", "filename", ")", ":", "puncloc", "=", "[", "filename", ".", "find", "(", "char", ")", "for", "char", "in", "string", ".", "punctuation", "]", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "val", "=", "...
24.5
14.785714
def primitives(): """ Perform primitive operations for profiling """ z = randomZ(orderG1()) # G1 operations P,Q = randomG1(),randomG1() R = generatorG1() g1Add = P + Q g1ScalarMultiply = z*P g1GeneratorMultiply = z*R g1Hash = hashG1(hash_in) # G2 operations P,Q = ra...
[ "def", "primitives", "(", ")", ":", "z", "=", "randomZ", "(", "orderG1", "(", ")", ")", "# G1 operations", "P", ",", "Q", "=", "randomG1", "(", ")", ",", "randomG1", "(", ")", "R", "=", "generatorG1", "(", ")", "g1Add", "=", "P", "+", "Q", "g1Sca...
19.290323
18.967742
def plotE(self,*args,**kwargs): """ NAME: plotE PURPOSE: plot E(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS) """ if kw...
[ "def", "plotE", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "'normed'", ",", "False", ")", ":", "kwargs", "[", "'d2'", "]", "=", "'Enorm'", "else", ":", "kwargs", "[", "'d2'", "]", "=", "'E...
24.833333
12.388889
def _list_fields(self): """ List the fields stored in the model, including data, model, and training options. Each field can be queried with the ``get`` method. Returns ------- out : list List of fields queryable with the ``get`` method. """ o...
[ "def", "_list_fields", "(", "self", ")", ":", "opts", "=", "{", "'model'", ":", "self", ".", "__proxy__", ",", "'model_name'", ":", "self", ".", "__name__", "}", "response", "=", "_turicreate", ".", "extensions", ".", "_nearest_neighbors", ".", "list_fields"...
34.714286
23.285714
def create_sink( self, parent, sink, unique_writer_identity=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a sink that exports specified log entries to a desti...
[ "def", "create_sink", "(", "self", ",", "parent", ",", "sink", ",", "unique_writer_identity", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", ...
44.576923
26.576923
def _clean(value): """ Convert numpy numeric types to their python equivalents. """ if isinstance(value, np.ndarray): if value.dtype.kind == 'S': return np.char.decode(value).tolist() else: return value.tolist() elif type(value).__module__ == np.__name__: # h5...
[ "def", "_clean", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "np", ".", "ndarray", ")", ":", "if", "value", ".", "dtype", ".", "kind", "==", "'S'", ":", "return", "np", ".", "char", ".", "decode", "(", "value", ")", ".", "tolis...
45.631579
19.105263
def decode_modified_utf8(data, errors="strict"): """ Decodes a sequence of bytes to a unicode text and length using Modified UTF-8. This function is designed to be used with Python ``codecs`` module. :param data: a string of bytes in Modified UTF-8 :param errors: handle decoding errors :ret...
[ "def", "decode_modified_utf8", "(", "data", ",", "errors", "=", "\"strict\"", ")", ":", "value", ",", "length", "=", "u\"\"", ",", "0", "it", "=", "iter", "(", "decoder", "(", "data", ")", ")", "while", "True", ":", "try", ":", "value", "+=", "next",...
30.428571
13.642857
def master_call(self, **kwargs): ''' Execute a wheel function through the master network interface (eauth). ''' load = kwargs load['cmd'] = 'wheel' interface = self.opts['interface'] if interface == '0.0.0.0': interface = '127.0.0.1' master_uri...
[ "def", "master_call", "(", "self", ",", "*", "*", "kwargs", ")", ":", "load", "=", "kwargs", "load", "[", "'cmd'", "]", "=", "'wheel'", "interface", "=", "self", ".", "opts", "[", "'interface'", "]", "if", "interface", "==", "'0.0.0.0'", ":", "interfac...
39.72
18.84
def _get_input_validator(self, request): """ Return appropriate input validator. For POST requests, ``self.post_representation`` is returned if it is present, ``self.representation`` otherwise. """ method = request.method.upper() if method != 'POST': return ...
[ "def", "_get_input_validator", "(", "self", ",", "request", ")", ":", "method", "=", "request", ".", "method", ".", "upper", "(", ")", "if", "method", "!=", "'POST'", ":", "return", "self", ".", "representation", "elif", "self", ".", "post_representation", ...
33
12.571429
def fix_times(self): """ Some recordings have wrong times. Fix them so that nothing after loading a handwritten recording breaks. """ pointlist = self.get_pointlist() times = [point['time'] for stroke in pointlist for point in stroke] times_min = max(min(times), 0...
[ "def", "fix_times", "(", "self", ")", ":", "pointlist", "=", "self", ".", "get_pointlist", "(", ")", "times", "=", "[", "point", "[", "'time'", "]", "for", "stroke", "in", "pointlist", "for", "point", "in", "stroke", "]", "times_min", "=", "max", "(", ...
43.2
12.266667
def create_module_file(package, module, opts): """Build the text of the file and write the file.""" if not opts.noheadings: text = format_heading(1, '%s module' % module) else: text = '' # text += format_heading(2, ':mod:`%s` Module' % module) text += format_directive(module, package...
[ "def", "create_module_file", "(", "package", ",", "module", ",", "opts", ")", ":", "if", "not", "opts", ".", "noheadings", ":", "text", "=", "format_heading", "(", "1", ",", "'%s module'", "%", "module", ")", "else", ":", "text", "=", "''", "# text += fo...
40.777778
13.888889
def Pc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[SURF]): r'''This function handles the retrieval of a chemical's critical pressure. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Prefere...
[ "def", "Pc", "(", "CASRN", ",", "AvailableMethods", "=", "False", ",", "Method", "=", "None", ",", "IgnoreMethods", "=", "[", "SURF", "]", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "CASRN", "in", "_crit_IUPAC", "...
49.569832
25.055866
def replace_free_item_coupon_by_id(cls, free_item_coupon_id, free_item_coupon, **kwargs): """Replace FreeItemCoupon Replace all attributes of FreeItemCoupon This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> ...
[ "def", "replace_free_item_coupon_by_id", "(", "cls", ",", "free_item_coupon_id", ",", "free_item_coupon", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "ret...
51.818182
28.363636
def get_colormap(name="cfastie", format="pil"): """ Return Pillow or GDAL compatible colormap array. Attributes ---------- name : str, optional Colormap name (default: cfastie) format: str, optional Compatiblity library, should be "pil" or "gdal" (default: pil). Returns ...
[ "def", "get_colormap", "(", "name", "=", "\"cfastie\"", ",", "format", "=", "\"pil\"", ")", ":", "cmap_file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"cmap\"", ",", "\"{0}.txt\"", ".", ...
32.470588
21.352941
def get_residuals_update_tile(st, padded_tile): """ Translates a tile in the padded image to the unpadded image. Given a state and a tile that corresponds to the padded image, returns a tile that corresponds to the the corresponding pixels of the difference image Parameters ---------- ...
[ "def", "get_residuals_update_tile", "(", "st", ",", "padded_tile", ")", ":", "inner_tile", "=", "st", ".", "ishape", ".", "intersection", "(", "[", "st", ".", "ishape", ",", "padded_tile", "]", ")", "return", "inner_tile", ".", "translate", "(", "-", "st",...
31.318182
20.681818
def component_add(vec1, vec2): """Add each of the components of vec1 and vec2 together and return a new vector.""" if isinstance(vec1, Vector3) and isinstance(vec2, Vector3): addVec = Vector3() addVec.x = vec1.x + vec2.x addVec.y = vec1.y + vec2.y addVec.z = vec1.z + vec2.z ...
[ "def", "component_add", "(", "vec1", ",", "vec2", ")", ":", "if", "isinstance", "(", "vec1", ",", "Vector3", ")", "and", "isinstance", "(", "vec2", ",", "Vector3", ")", ":", "addVec", "=", "Vector3", "(", ")", "addVec", ".", "x", "=", "vec1", ".", ...
35.9375
12.75
def getISAAssay(assayNum, studyNum, pathToISATABFile): """ This function returns an Assay object given the assay and study numbers in an ISA file Typically, you should use the exploreISA function to check the contents of the ISA file and retrieve the assay and study numbers you are interested in! :p...
[ "def", "getISAAssay", "(", "assayNum", ",", "studyNum", ",", "pathToISATABFile", ")", ":", "from", "isatools", "import", "isatab", "import", "copy", "try", ":", "isa", "=", "isatab", ".", "load", "(", "pathToISATABFile", ",", "skip_load_tables", "=", "True", ...
45.47619
21.666667
def compile_schema(fields): """ joins schema fields with base solr schema :param list[str] fields: field list :return: compiled schema :rtype: byte """ path = os.path.dirname(os.path.realpath(__file__)) # path = os.path.dirname( # os.path.absp...
[ "def", "compile_schema", "(", "fields", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "# path = os.path.dirname(", "# os.path.abspath(inspect.getfile(inspect.currentframe())))", "wit...
32.421053
17.473684
def get_method(self, cls_name): """ Generator that returns all registered authenticators based on a specific authentication class. :param acr: Authentication Class :return: generator """ for id, spec in self.db.items(): if spec["method"].__class__.__n...
[ "def", "get_method", "(", "self", ",", "cls_name", ")", ":", "for", "id", ",", "spec", "in", "self", ".", "db", ".", "items", "(", ")", ":", "if", "spec", "[", "\"method\"", "]", ".", "__class__", ".", "__name__", "==", "cls_name", ":", "yield", "s...
33.181818
11
def create(self, request): """Create a new product request """ variant_id = request.data.get("variant_id", None) if variant_id is not None: variant = ProductVariant.objects.get(id=variant_id) product_request = ProductRequest(variant=variant) product_r...
[ "def", "create", "(", "self", ",", "request", ")", ":", "variant_id", "=", "request", ".", "data", ".", "get", "(", "\"variant_id\"", ",", "None", ")", "if", "variant_id", "is", "not", "None", ":", "variant", "=", "ProductVariant", ".", "objects", ".", ...
37.882353
18.235294
def parse(self, argv): """Pop, parse and return the first self.nargs items from args. if self.nargs > 1 a list of parsed values will be returned. Raise BadNumberOfArguments or BadArgument on errors. NOTE: argv may be modified in place by this method. """ ...
[ "def", "parse", "(", "self", ",", "argv", ")", ":", "if", "len", "(", "argv", ")", "<", "self", ".", "nargs", ":", "raise", "BadNumberOfArguments", "(", "self", ".", "nargs", ",", "len", "(", "argv", ")", ")", "if", "self", ".", "nargs", "==", "1...
39.785714
19.714286
def render(self, template=None): """Render the plot using a template. Once the plot is complete, it needs to be rendered. Artist uses the Jinja2 templating engine. The default template results in a LaTeX file which can be included in your document. :param template: a user-sup...
[ "def", "render", "(", "self", ",", "template", "=", "None", ")", ":", "if", "not", "template", ":", "template", "=", "self", ".", "template", "self", ".", "_prepare_data", "(", ")", "response", "=", "template", ".", "render", "(", "axis_background", "=",...
33.073171
13.487805
def call(sender, topic, *args, **kwargs): """ Invoke receiver functions according topic, it'll invoke receiver functions one by one, and it'll not return anything, so if you want to return a value, you should use get function. """ if not topic in _receivers: return items = _r...
[ "def", "call", "(", "sender", ",", "topic", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "topic", "in", "_receivers", ":", "return", "items", "=", "_receivers", "[", "topic", "]", "def", "_cmp", "(", "x", ",", "y", ")", ":", ...
33.783784
19.837838
def json(self): """Return a list of records as a JSON string. Follows the BibJSON convention.""" return json.dumps(OrderedDict([('metadata', self.metadata), ('records', self.records.values())]))
[ "def", "json", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "OrderedDict", "(", "[", "(", "'metadata'", ",", "self", ".", "metadata", ")", ",", "(", "'records'", ",", "self", ".", "records", ".", "values", "(", ")", ")", "]", ")", ...
69.333333
30
def get_text_v3(address, stream, mapped=False): """ faster way to extract strings from mdf versions 2 and 3 TextBlock Parameters ---------- address : int TextBlock address stream : handle file IO handle Returns ------- text : str unicode string """ if ...
[ "def", "get_text_v3", "(", "address", ",", "stream", ",", "mapped", "=", "False", ")", ":", "if", "address", "==", "0", ":", "return", "\"\"", "if", "mapped", ":", "size", ",", "=", "UINT16_uf", "(", "stream", ",", "address", "+", "2", ")", "text_byt...
26.533333
21.466667
def WindowsSdkDir(self): """ Microsoft Windows SDK directory. """ sdkdir = '' for ver in self.WindowsSdkVersion: # Try to get it from registry loc = os.path.join(self.ri.windows_sdk, 'v%s' % ver) sdkdir = self.ri.lookup(loc, 'installationfolder...
[ "def", "WindowsSdkDir", "(", "self", ")", ":", "sdkdir", "=", "''", "for", "ver", "in", "self", ".", "WindowsSdkVersion", ":", "# Try to get it from registry", "loc", "=", "os", ".", "path", ".", "join", "(", "self", ".", "ri", ".", "windows_sdk", ",", "...
42.888889
12.944444
def aggregate_history(self, ip, days_limit=None): """ Get the full history of an IP, aggregate the result instead of returning one line per day. :param ip: IP address to search for :param days_limit: Max amount of days to query. (None means no limit) ...
[ "def", "aggregate_history", "(", "self", ",", "ip", ",", "days_limit", "=", "None", ")", ":", "first_date", "=", "None", "last_date", "=", "None", "prec_asn", "=", "None", "prec_block", "=", "None", "for", "entry", "in", "self", ".", "history", "(", "ip"...
35.727273
14.393939
def all_events(vars, bn, e): "Yield every way of extending e with values for all vars." if not vars: yield e else: X, rest = vars[0], vars[1:] for e1 in all_events(rest, bn, e): for x in bn.variable_values(X): yield extend(e1, X, x)
[ "def", "all_events", "(", "vars", ",", "bn", ",", "e", ")", ":", "if", "not", "vars", ":", "yield", "e", "else", ":", "X", ",", "rest", "=", "vars", "[", "0", "]", ",", "vars", "[", "1", ":", "]", "for", "e1", "in", "all_events", "(", "rest",...
32
14
def draw_if_interactive(): """ This should be overriden in a windowing environment if drawing should be done in interactive python mode """ DEBUG_MSG("draw_if_interactive()", 1, None) if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: ...
[ "def", "draw_if_interactive", "(", ")", ":", "DEBUG_MSG", "(", "\"draw_if_interactive()\"", ",", "1", ",", "None", ")", "if", "matplotlib", ".", "is_interactive", "(", ")", ":", "figManager", "=", "Gcf", ".", "get_active", "(", ")", "if", "figManager", "is",...
28.75
12.25
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SyncListPermissionContext for this SyncListPermissionInstance :rtype: twilio.rest.sync.v1.service...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "SyncListPermissionContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]",...
43.875
22.375
def begin_auth(): """ Request authentication token to sign """ repository = request.headers['repository'] if repository not in config['repositories']: return fail(no_such_repo_msg) # == repository_path = config['repositories'][repository]['path'] conn = auth_db_connect(cpjoin(repository_pat...
[ "def", "begin_auth", "(", ")", ":", "repository", "=", "request", ".", "headers", "[", "'repository'", "]", "if", "repository", "not", "in", "config", "[", "'repositories'", "]", ":", "return", "fail", "(", "no_such_repo_msg", ")", "# ==", "repository_path", ...
39.352941
28.882353
def models_to_table(obj, params=True): r""" Converts a ModelsDict object to a ReST compatible table Parameters ---------- obj : OpenPNM object Any object that has a ``models`` attribute params : boolean Indicates whether or not to include a list of parameter values in t...
[ "def", "models_to_table", "(", "obj", ",", "params", "=", "True", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "'models'", ")", ":", "raise", "Exception", "(", "'Received object does not have any models'", ")", "row", "=", "'+'", "+", "'-'", "*", "4"...
38.386364
16.045455
def array_bytes(shape, dtype): """ Estimates the memory in bytes required for an array of the supplied shape and dtype """ return np.product(shape)*np.dtype(dtype).itemsize
[ "def", "array_bytes", "(", "shape", ",", "dtype", ")", ":", "return", "np", ".", "product", "(", "shape", ")", "*", "np", ".", "dtype", "(", "dtype", ")", ".", "itemsize" ]
59.333333
7.666667
def sortInternals(self): ''' Sort all internal lists (``class_like``, ``namespaces``, ``variables``, etc) mostly how doxygen would, alphabetical but also hierarchical (e.g. structs appear before classes in listings). Some internal lists are just sorted, and some are deep sorted ...
[ "def", "sortInternals", "(", "self", ")", ":", "# some of the lists only need to be sorted, some of them need to be sorted and", "# have each node sort its children", "# leaf-like lists: no child sort", "self", ".", "defines", ".", "sort", "(", ")", "self", ".", "enums", ".", ...
40.625
17.958333
def mask(mask_key, data): """ mask or unmask data. Just do xor for each byte mask_key: 4 byte string(byte). data: data to mask/unmask. """ if data is None: data = "" if isinstance(mask_key, six.text_type): mask_key = six.b(mask_key) ...
[ "def", "mask", "(", "mask_key", ",", "data", ")", ":", "if", "data", "is", "None", ":", "data", "=", "\"\"", "if", "isinstance", "(", "mask_key", ",", "six", ".", "text_type", ")", ":", "mask_key", "=", "six", ".", "b", "(", "mask_key", ")", "if", ...
31.46875
17.53125