text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def idle_task(self): '''handle mavlink packets''' if self.accelcal_count != -1: if self.accelcal_wait_enter and self.empty_input_count != self.mpstate.empty_input_count: self.accelcal_wait_enter = False self.accelcal_count += 1 # tell the APM t...
[ "def", "idle_task", "(", "self", ")", ":", "if", "self", ".", "accelcal_count", "!=", "-", "1", ":", "if", "self", ".", "accelcal_wait_enter", "and", "self", ".", "empty_input_count", "!=", "self", ".", "mpstate", ".", "empty_input_count", ":", "self", "."...
47.941176
16.411765
def submit_design_run(self, data_view_id, num_candidates, effort, target=None, constraints=[], sampler="Default"): """ Submits a new experimental design run. :param data_view_id: The ID number of the data view to which the run belongs, as a string :type data_view_id: str ...
[ "def", "submit_design_run", "(", "self", ",", "data_view_id", ",", "num_candidates", ",", "effort", ",", "target", "=", "None", ",", "constraints", "=", "[", "]", ",", "sampler", "=", "\"Default\"", ")", ":", "if", "effort", ">", "30", ":", "raise", "Cit...
38.761905
21.714286
def sample(self, size=(), rule="R", antithetic=None): """ Create pseudo-random generated samples. By default, the samples are created using standard (pseudo-)random samples. However, if needed, the samples can also be created by either low-discrepancy sequences, and/or variance ...
[ "def", "sample", "(", "self", ",", "size", "=", "(", ")", ",", "rule", "=", "\"R\"", ",", "antithetic", "=", "None", ")", ":", "size_", "=", "numpy", ".", "prod", "(", "size", ",", "dtype", "=", "int", ")", "dim", "=", "len", "(", "self", ")", ...
44.410959
23.315068
def make_rendition(self, width, height): '''build a rendition 0 x 0 -> will give master URL only width -> will make a renditions with master's aspect ratio width x height -> will make an image potentialy cropped ''' image = Image.open(self.master) format = image....
[ "def", "make_rendition", "(", "self", ",", "width", ",", "height", ")", ":", "image", "=", "Image", ".", "open", "(", "self", ".", "master", ")", "format", "=", "image", ".", "format", "target_w", "=", "float", "(", "width", ")", "target_h", "=", "fl...
32.067797
19.254237
def watch_active_servings(dk_api, kitchen, period): """ returns a string. :param dk_api: -- api object :param kitchen: string :param period: integer :rtype: string """ print 'period', period # try: # p = int(period) # except Va...
[ "def", "watch_active_servings", "(", "dk_api", ",", "kitchen", ",", "period", ")", ":", "print", "'period'", ",", "period", "# try:", "# p = int(period)", "# except ValueError:", "# return 'DKCloudCommand.watch_active_servings requires an integer for the period'", "if", ...
35.227273
19.318182
def ssh_to_task(task) -> paramiko.SSHClient: """Create ssh connection to task's machine returns Paramiko SSH client connected to host. """ username = task.ssh_username hostname = task.public_ip ssh_key_fn = get_keypair_fn() print(f"ssh -i {ssh_key_fn} {username}@{hostname}") pkey = paramiko.RSAKey.fr...
[ "def", "ssh_to_task", "(", "task", ")", "->", "paramiko", ".", "SSHClient", ":", "username", "=", "task", ".", "ssh_username", "hostname", "=", "task", ".", "public_ip", "ssh_key_fn", "=", "get_keypair_fn", "(", ")", "print", "(", "f\"ssh -i {ssh_key_fn} {userna...
29.833333
23.333333
def traverse_data(obj, key_target): ''' will traverse nested list and dicts until key_target equals the current dict key ''' if isinstance(obj, str) and '.json' in str(obj): obj = json.load(open(obj, 'r')) if isinstance(obj, list): queue = obj.copy() elif isinstance(obj, dict): q...
[ "def", "traverse_data", "(", "obj", ",", "key_target", ")", ":", "if", "isinstance", "(", "obj", ",", "str", ")", "and", "'.json'", "in", "str", "(", "obj", ")", ":", "obj", "=", "json", ".", "load", "(", "open", "(", "obj", ",", "'r'", ")", ")",...
34.259259
13.444444
def _product_file_hash(self, product=None): """ Get the hash of the each product file """ if self.hasher is None: return None else: products = self._rectify_products(product) product_file_hash = [ util_hash.hash_file(p, hasher=s...
[ "def", "_product_file_hash", "(", "self", ",", "product", "=", "None", ")", ":", "if", "self", ".", "hasher", "is", "None", ":", "return", "None", "else", ":", "products", "=", "self", ".", "_rectify_products", "(", "product", ")", "product_file_hash", "="...
32
11.538462
def dimensions(self): """Iterate over the dimension columns, regardless of parent/child status """ from ambry.valuetype.core import ROLE for c in self.columns: if c.role == ROLE.DIMENSION: yield c
[ "def", "dimensions", "(", "self", ")", ":", "from", "ambry", ".", "valuetype", ".", "core", "import", "ROLE", "for", "c", "in", "self", ".", "columns", ":", "if", "c", ".", "role", "==", "ROLE", ".", "DIMENSION", ":", "yield", "c" ]
25
17.1
def assignBranchRegisters(inodes, registerMaker): """Assign temporary registers to each of the branch nodes. """ for node in inodes: node.reg = registerMaker(node, temporary=True)
[ "def", "assignBranchRegisters", "(", "inodes", ",", "registerMaker", ")", ":", "for", "node", "in", "inodes", ":", "node", ".", "reg", "=", "registerMaker", "(", "node", ",", "temporary", "=", "True", ")" ]
39
8
def delete_cluster_role_binding(self, name, **kwargs): # noqa: E501 """delete_cluster_role_binding # noqa: E501 delete a ClusterRoleBinding # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >...
[ "def", "delete_cluster_role_binding", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", ...
93.481481
66.407407
def money_receipts(pronac, dt): """ Checks how many items are in a same receipt when payment type is withdraw/money - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt """ df = verified_repeated_...
[ "def", "money_receipts", "(", "pronac", ",", "dt", ")", ":", "df", "=", "verified_repeated_receipts_for_pronac", "(", "pronac", ")", "comprovantes_saque", "=", "df", "[", "df", "[", "'tpFormaDePagamento'", "]", "==", "3.0", "]", "return", "metric_return", "(", ...
40.363636
19.272727
def stop(self): """ Stop the container gracefully. First all entrypoints are asked to ``stop()``. This ensures that no new worker threads are started. It is the extensions' responsibility to gracefully shut down when ``stop()`` is called on them and only return when they have s...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_died", ".", "ready", "(", ")", ":", "_log", ".", "debug", "(", "'already stopped %s'", ",", "self", ")", "return", "if", "self", ".", "_being_killed", ":", "# this race condition can happen when a co...
36.311475
22.557377
def cublasDsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc): """ Matrix-matrix product for real symmetric matrix. """ status = _libcublas.cublasDsymm_v2(handle, _CUBLAS_SIDE_MODE[side], _CUBLAS_FILL_M...
[ "def", "cublasDsymm", "(", "handle", ",", "side", ",", "uplo", ",", "m", ",", "n", ",", "alpha", ",", "A", ",", "lda", ",", "B", ",", "ldb", ",", "beta", ",", "C", ",", "ldc", ")", ":", "status", "=", "_libcublas", ".", "cublasDsymm_v2", "(", "...
44.642857
21.785714
def cluster_types(types, max_clust=12): """ Generates a dictionary mapping each binary number in types to an integer from 0 to max_clust. Hierarchical clustering is used to determine which which binary numbers should map to the same integer. """ if len(types) < max_clust: max_clust = le...
[ "def", "cluster_types", "(", "types", ",", "max_clust", "=", "12", ")", ":", "if", "len", "(", "types", ")", "<", "max_clust", ":", "max_clust", "=", "len", "(", "types", ")", "# Do actual clustering", "cluster_dict", "=", "do_clustering", "(", "types", ",...
30.47619
18.380952
def eliminate_implications(s): """Change >>, <<, and <=> into &, |, and ~. That is, return an Expr that is equivalent to s, but has only &, |, and ~ as logical operators. >>> eliminate_implications(A >> (~B << C)) ((~B | ~C) | ~A) >>> eliminate_implications(A ^ B) ((A & ~B) | (~A & B)) """ ...
[ "def", "eliminate_implications", "(", "s", ")", ":", "if", "not", "s", ".", "args", "or", "is_symbol", "(", "s", ".", "op", ")", ":", "return", "s", "## (Atoms are unchanged.)", "args", "=", "map", "(", "eliminate_implications", ",", "s", ".", "args", ")...
34.913043
14.217391
def get_setting(connection, key): """Get key from connection or default to settings.""" if key in connection.settings_dict: return connection.settings_dict[key] else: return getattr(settings, key)
[ "def", "get_setting", "(", "connection", ",", "key", ")", ":", "if", "key", "in", "connection", ".", "settings_dict", ":", "return", "connection", ".", "settings_dict", "[", "key", "]", "else", ":", "return", "getattr", "(", "settings", ",", "key", ")" ]
36.5
7.666667
def list_absent(name, value, delimiter=DEFAULT_TARGET_DELIM): ''' Delete a value from a grain formed as a list. .. versionadded:: 2014.1.0 name The grain name. value The value to delete from the grain list. delimiter A delimiter different from the default ``:`` can be ...
[ "def", "list_absent", "(", "name", ",", "value", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ")", ":", "name", "=", "re", ".", "sub", "(", "delimiter", ",", "DEFAULT_TARGET_DELIM", ",", "name", ")", "ret", "=", "{", "'name'", ":", "name", ",", "'chang...
31.891892
21.864865
def find_all(self, collection): """ Search a collection for all available items. Args: collection: The db collection. See main class documentation. Returns: List of all items in the collection. """ obj = getattr(self.db, collection) result...
[ "def", "find_all", "(", "self", ",", "collection", ")", ":", "obj", "=", "getattr", "(", "self", ".", "db", ",", "collection", ")", "result", "=", "obj", ".", "find", "(", ")", "return", "result" ]
28.666667
15.5
def log(self, level, *args, **kwargs): """Log something. .. seealso:: Proxy: :class:`.Logger`.level """ target = getattr(self.__logger, level) target(*args, **kwargs)
[ "def", "log", "(", "self", ",", "level", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "target", "=", "getattr", "(", "self", ".", "__logger", ",", "level", ")", "target", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
26.5
9.5
def lock_file(self, fpath, after_setup=False, wait=False): """Locks the specified file. :param str|unicode fpath: File path. :param bool after_setup: True - after logging/daemon setup False - before starting :param bool wait: True - wait if locked...
[ "def", "lock_file", "(", "self", ",", "fpath", ",", "after_setup", "=", "False", ",", "wait", "=", "False", ")", ":", "command", "=", "'flock-wait'", "if", "wait", "else", "'flock'", "if", "after_setup", ":", "command", "=", "'%s2'", "%", "command", "sel...
23.954545
18.090909
def relpath(path, start): """Get relative path to start. Note: Modeled after python2.6 :meth:`os.path.relpath`. """ path_items = path_list(path) start_items = path_list(start) # Find common parts of path. common = [] for pth, stt in zip(path_items, start_items): if pth != stt: ...
[ "def", "relpath", "(", "path", ",", "start", ")", ":", "path_items", "=", "path_list", "(", "path", ")", "start_items", "=", "path_list", "(", "start", ")", "# Find common parts of path.", "common", "=", "[", "]", "for", "pth", ",", "stt", "in", "zip", "...
28
16.863636
def _import_modules(dir_path): """ Attempts to import modules in the specified directory path. `dir_path` Base directory path to attempt to import modules. """ def _import_module(module): """ Imports the specified module. """ # already loaded, skip ...
[ "def", "_import_modules", "(", "dir_path", ")", ":", "def", "_import_module", "(", "module", ")", ":", "\"\"\" Imports the specified module.\n \"\"\"", "# already loaded, skip", "if", "module", "in", "mods_loaded", ":", "return", "False", "__import__", "(", "...
26.829268
17.170732
def _parse_file(self): """Preprocess and parse C file into an AST""" # We need to set the CPU type to pull in the right register definitions # only preprocess the file (-E) and get rid of gcc extensions that aren't # supported in ISO C. args = utilities.build_includes(self.arch....
[ "def", "_parse_file", "(", "self", ")", ":", "# We need to set the CPU type to pull in the right register definitions", "# only preprocess the file (-E) and get rid of gcc extensions that aren't", "# supported in ISO C.", "args", "=", "utilities", ".", "build_includes", "(", "self", ...
45.846154
24.076923
def check_cluster( cluster_config, data_path, java_home, check_replicas, batch_size, minutes, start_time, end_time, ): """Check the integrity of the Kafka log files in a cluster. start_time and end_time should be in the format specified by TIME_FORMAT_REGEX. :param data...
[ "def", "check_cluster", "(", "cluster_config", ",", "data_path", ",", "java_home", ",", "check_replicas", ",", "batch_size", ",", "minutes", ",", "start_time", ",", "end_time", ",", ")", ":", "brokers", "=", "get_broker_list", "(", "cluster_config", ")", "broker...
32.766667
17.566667
def create_comment_browser(self, layout): """Create a comment browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` ...
[ "def", "create_comment_browser", "(", "self", ",", "layout", ")", ":", "brws", "=", "CommentBrowser", "(", "1", ",", "headers", "=", "[", "'Comments:'", "]", ")", "layout", ".", "insertWidget", "(", "1", ",", "brws", ")", "return", "brws" ]
37.333333
13.5
def send_mass_video(self, group_or_users, media_id, title=None, description=None, is_to_all=False, preview=False, send_ignore_reprint=0, client_msg_id=None): """ 群发视频消息 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1481187827_i0l21 :pa...
[ "def", "send_mass_video", "(", "self", ",", "group_or_users", ",", "media_id", ",", "title", "=", "None", ",", "description", "=", "None", ",", "is_to_all", "=", "False", ",", "preview", "=", "False", ",", "send_ignore_reprint", "=", "0", ",", "client_msg_id...
36.531915
19.765957
def template_global(self, name=None): """A decorator that is used to register a custom template global function. You can specify a name for the global function, otherwise the function name will be used. Example:: @app.template_global() def double(n): retu...
[ "def", "template_global", "(", "self", ",", "name", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "add_template_global", "(", "f", ",", "name", "=", "name", ")", "return", "f", "return", "decorator" ]
33.611111
17.333333
def list_all_credit_card_payments(cls, **kwargs): """List CreditCardPayments Return a list of CreditCardPayments This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_credit_card_payments(a...
[ "def", "list_all_credit_card_payments", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_credit_card_payments_with_h...
39.565217
15.869565
def cli_head(context, path=None): """ Performs a HEAD on the item (account, container, or object). See :py:mod:`swiftly.cli.head` for context usage information. See :py:class:`CLIHead` for more information. """ path = path.lstrip('/') if path else None with context.client_manager.with_clie...
[ "def", "cli_head", "(", "context", ",", "path", "=", "None", ")", ":", "path", "=", "path", ".", "lstrip", "(", "'/'", ")", "if", "path", "else", "None", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "if...
41.170732
17.365854
def substitute(dict_, source): """ Perform re.sub with the patterns in the given dict Args: dict_: {pattern: repl} source: str """ d_esc = (re.escape(k) for k in dict_.keys()) pattern = re.compile('|'.join(d_esc)) return pattern.sub(lambda x: dict_[x.group()], source)
[ "def", "substitute", "(", "dict_", ",", "source", ")", ":", "d_esc", "=", "(", "re", ".", "escape", "(", "k", ")", "for", "k", "in", "dict_", ".", "keys", "(", ")", ")", "pattern", "=", "re", ".", "compile", "(", "'|'", ".", "join", "(", "d_esc...
32.888889
11.444444
def dump(self): """Dump the details of an ATR.""" for i in range(0, len(self.TA)): if self.TA[i] is not None: print("TA%d: %x" % (i + 1, self.TA[i])) if self.TB[i] is not None: print("TB%d: %x" % (i + 1, self.TB[i])) if self.TC[i] is n...
[ "def", "dump", "(", "self", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "TA", ")", ")", ":", "if", "self", ".", "TA", "[", "i", "]", "is", "not", "None", ":", "print", "(", "\"TA%d: %x\"", "%", "(", "i", "+"...
40.875
21.03125
def replace_apply_state(meta_graph, state_ops, feed_map): """Replaces state ops with non state Placeholder ops for the apply graph.""" for node in meta_graph.graph_def.node: keys_to_purge = [] tensor_name = node.name + ":0" # Verify that the node is a state op and that its due to be rewired # in the...
[ "def", "replace_apply_state", "(", "meta_graph", ",", "state_ops", ",", "feed_map", ")", ":", "for", "node", "in", "meta_graph", ".", "graph_def", ".", "node", ":", "keys_to_purge", "=", "[", "]", "tensor_name", "=", "node", ".", "name", "+", "\":0\"", "# ...
41.176471
14
def send(self, message_type, task_id, message): """ Sends a message to the UDP receiver Parameter --------- message_type: monitoring.MessageType (enum) In this case message type is RESOURCE_INFO most often task_id: int Task identifier of the task for whi...
[ "def", "send", "(", "self", ",", "message_type", ",", "task_id", ",", "message", ")", ":", "x", "=", "0", "try", ":", "buffer", "=", "pickle", ".", "dumps", "(", "(", "self", ".", "source_id", ",", "# Identifier for manager", "int", "(", "time", ".", ...
33.25
21.9375
def _set_rowcount(self, query_results): """Set the rowcount from query results. Normally, this sets rowcount to the number of rows returned by the query, but if it was a DML statement, it sets rowcount to the number of modified rows. :type query_results: :class:`~go...
[ "def", "_set_rowcount", "(", "self", ",", "query_results", ")", ":", "total_rows", "=", "0", "num_dml_affected_rows", "=", "query_results", ".", "num_dml_affected_rows", "if", "query_results", ".", "total_rows", "is", "not", "None", "and", "query_results", ".", "t...
41.315789
20.578947
def enable_svc_check(self, service): """Enable checks for a service Format of the line that triggers function call:: ENABLE_SVC_CHECK;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service :return: None "...
[ "def", "enable_svc_check", "(", "self", ",", "service", ")", ":", "if", "not", "service", ".", "active_checks_enabled", ":", "service", ".", "modified_attributes", "|=", "DICT_MODATTR", "[", "\"MODATTR_ACTIVE_CHECKS_ENABLED\"", "]", ".", "value", "service", ".", "...
38.866667
14.8
def users_lookupByEmail(self, *, email: str, **kwargs) -> SlackResponse: """Find a user with an email address. Args: email (str): An email address belonging to a user in the workspace. e.g. 'spengler@ghostbusters.example.com' """ kwargs.update({"email": email...
[ "def", "users_lookupByEmail", "(", "self", ",", "*", ",", "email", ":", "str", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "kwargs", ".", "update", "(", "{", "\"email\"", ":", "email", "}", ")", "return", "self", ".", "api_call", "(", "...
44.222222
22
def watch(self, pipeline=None, full_document='default', resume_after=None, max_await_time_ms=None, batch_size=None, collation=None, start_at_operation_time=None, session=None): """Watch changes on this database. Performs an aggregation with an implicit initial ``$changeStrea...
[ "def", "watch", "(", "self", ",", "pipeline", "=", "None", ",", "full_document", "=", "'default'", ",", "resume_after", "=", "None", ",", "max_await_time_ms", "=", "None", ",", "batch_size", "=", "None", ",", "collation", "=", "None", ",", "start_at_operatio...
46.154762
25.357143
def _xorterm_prime(lexer): """Return an xor term' expression, eliminates left recursion.""" tok = next(lexer) # '^' PRODTERM XORTERM' if isinstance(tok, OP_xor): prodterm = _prodterm(lexer) xorterm_prime = _xorterm_prime(lexer) if xorterm_prime is None: return prodter...
[ "def", "_xorterm_prime", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# '^' PRODTERM XORTERM'", "if", "isinstance", "(", "tok", ",", "OP_xor", ")", ":", "prodterm", "=", "_prodterm", "(", "lexer", ")", "xorterm_prime", "=", "_xorterm_prime...
29.666667
14.333333
def parse_options(): """ Parses command-line option """ try: opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx', ['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo', 'minimize', 'solver=', 'trim=', 'verbose']) except getopt.GetoptErro...
[ "def", "parse_options", "(", ")", ":", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'ac:e:hilms:t:vx'", ",", "[", "'adapt'", ",", "'comp='", ",", "'enum='", ",", "'exhaust'", ",", ...
27.517241
16.862069
def semantic_parent(self): """Return the semantic parent for this cursor.""" if not hasattr(self, '_semantic_parent'): self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) return self._semantic_parent
[ "def", "semantic_parent", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_semantic_parent'", ")", ":", "self", ".", "_semantic_parent", "=", "conf", ".", "lib", ".", "clang_getCursorSemanticParent", "(", "self", ")", "return", "self", "."...
41.333333
17.833333
def print_descr(rect, annot): """Print a short description to the right of an annot rect.""" annot.parent.insertText(rect.br + (10, 0), "'%s' annotation" % annot.type[1], color = red)
[ "def", "print_descr", "(", "rect", ",", "annot", ")", ":", "annot", ".", "parent", ".", "insertText", "(", "rect", ".", "br", "+", "(", "10", ",", "0", ")", ",", "\"'%s' annotation\"", "%", "annot", ".", "type", "[", "1", "]", ",", "color", "=", ...
52
11
def _plot_graph(G, vertex_color, vertex_size, highlight, edges, edge_color, edge_width, indices, colorbar, limits, ax, title, backend): r"""Plot a graph with signals as color or vertex size. Parameters ---------- vertex_color : array_like or color Signal to plot ...
[ "def", "_plot_graph", "(", "G", ",", "vertex_color", ",", "vertex_size", ",", "highlight", ",", "edges", ",", "edge_color", ",", "edge_width", ",", "indices", ",", "colorbar", ",", "limits", ",", "ax", ",", "title", ",", "backend", ")", ":", "if", "not",...
41.661765
19.759804
def write_image(filename, image): """ Write image data to PNG, JPG file :param filename: name of PNG or JPG file to write data to :type filename: str :param image: image data to write to file :type image: numpy array """ data_format = get_data_format(filename) if data_format is MimeType...
[ "def", "write_image", "(", "filename", ",", "image", ")", ":", "data_format", "=", "get_data_format", "(", "filename", ")", "if", "data_format", "is", "MimeType", ".", "JPG", ":", "LOGGER", ".", "warning", "(", "'Warning: jpeg is a lossy format therefore saved data ...
38.333333
14.5
def track_locations(locations): """ Return an iterator tweets from users in these locations. See https://dev.twitter.com/streaming/overview/request-parameters#locations Params: locations...list of bounding box locations of the form: southwest_longitude, southwest_latitude, northeast_longitud...
[ "def", "track_locations", "(", "locations", ")", ":", "if", "len", "(", "locations", ")", "%", "4", "!=", "0", ":", "raise", "Exception", "(", "'length of bounding box list should be a multiple of four'", ")", "results", "=", "twapi", ".", "request", "(", "'stat...
54.090909
24.727273
def _all_combos(self): """ RETURN AN ITERATOR OF ALL COORDINATES """ combos = _product(self.dims) if not combos: return calc = [(coalesce(_product(self.dims[i+1:]), 1), mm) for i, mm in enumerate(self.dims)] for c in xrange(combos): yield...
[ "def", "_all_combos", "(", "self", ")", ":", "combos", "=", "_product", "(", "self", ".", "dims", ")", "if", "not", "combos", ":", "return", "calc", "=", "[", "(", "coalesce", "(", "_product", "(", "self", ".", "dims", "[", "i", "+", "1", ":", "]...
29.333333
19.166667
def _reset_docs(self): """ Helper to clear the docs on RESET or filter mismatch. """ _LOGGER.debug("resetting documents") self.change_map.clear() self.resume_token = None # Mark each document as deleted. If documents are not deleted # they will be sent ag...
[ "def", "_reset_docs", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"resetting documents\"", ")", "self", ".", "change_map", ".", "clear", "(", ")", "self", ".", "resume_token", "=", "None", "# Mark each document as deleted. If documents are not deleted", "...
33.866667
14.666667
def read_partial_map(filenames, column, fullsky=True, **kwargs): """ Read a partial HEALPix file(s) and return pixels and values/map. Can handle 3D healpix maps (pix, value, zdim). Returned array has shape (dimz,npix). Parameters: ----------- filenames : list of input filenames colu...
[ "def", "read_partial_map", "(", "filenames", ",", "column", ",", "fullsky", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Make sure that PIXEL is in columns", "#kwargs['columns'] = ['PIXEL',column]", "kwargs", "[", "'columns'", "]", "=", "[", "'PIXEL'", "]", ...
31.478261
18.782609
def save_user(self, uid, user_password, user_email='', user_channels=None, user_roles=None, user_views=None, disable_account=False): ''' a method to add or update an authorized user to the bucket :param uid: string with id to assign to user :param user_password: string ...
[ "def", "save_user", "(", "self", ",", "uid", ",", "user_password", ",", "user_email", "=", "''", ",", "user_channels", "=", "None", ",", "user_roles", "=", "None", ",", "user_views", "=", "None", ",", "disable_account", "=", "False", ")", ":", "# https://d...
39.761194
25.134328
def declare_type(self, declared_type): # type: (TypeDef) -> TypeDef """Add this type to our collection, if needed.""" if declared_type not in self.collected_types: self.collected_types[declared_type.name] = declared_type return declared_type
[ "def", "declare_type", "(", "self", ",", "declared_type", ")", ":", "# type: (TypeDef) -> TypeDef", "if", "declared_type", "not", "in", "self", ".", "collected_types", ":", "self", ".", "collected_types", "[", "declared_type", ".", "name", "]", "=", "declared_type...
54.8
16.2
def arduino_path(): """expanded root path, ARDUINO_HOME env var or arduino_default_path()""" x = _ARDUINO_PATH if not x: x = os.environ.get('ARDUINO_HOME') if not x: x = arduino_default_path() assert x, str(x) x = path(x).expand().abspath() assert x.exists(), 'arduino pa...
[ "def", "arduino_path", "(", ")", ":", "x", "=", "_ARDUINO_PATH", "if", "not", "x", ":", "x", "=", "os", ".", "environ", ".", "get", "(", "'ARDUINO_HOME'", ")", "if", "not", "x", ":", "x", "=", "arduino_default_path", "(", ")", "assert", "x", ",", "...
21.3125
23.3125
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return b'<style type="text/css">\n' + b"\n".join(css_embe...
[ "def", "render_embed_css", "(", "self", ",", "css_embed", ":", "Iterable", "[", "bytes", "]", ")", "->", "bytes", ":", "return", "b'<style type=\"text/css\">\\n'", "+", "b\"\\n\"", ".", "join", "(", "css_embed", ")", "+", "b\"\\n</style>\"" ]
47.428571
22.857143
def parameterize_notebook(nb, parameters, report_mode=False): """Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object parameters : dict Arbitrary keyword arguments to pass as notebook parameters rep...
[ "def", "parameterize_notebook", "(", "nb", ",", "parameters", ",", "report_mode", "=", "False", ")", ":", "# Load from a file if 'parameters' is a string.", "if", "isinstance", "(", "parameters", ",", "six", ".", "string_types", ")", ":", "parameters", "=", "read_ya...
36.230769
20.115385
def iterate(self): """ Must be called regularly when using an external event loop. """ if not self._inLoop: raise RuntimeError('run loop not started') elif self._driverLoop: raise RuntimeError('iterate not valid in driver run loop') self.proxy.iter...
[ "def", "iterate", "(", "self", ")", ":", "if", "not", "self", ".", "_inLoop", ":", "raise", "RuntimeError", "(", "'run loop not started'", ")", "elif", "self", ".", "_driverLoop", ":", "raise", "RuntimeError", "(", "'iterate not valid in driver run loop'", ")", ...
35.222222
14.111111
def _etextno_to_uri_subdirectory(etextno): """Returns the subdirectory that an etextno will be found in a gutenberg mirror. Generally, one finds the subdirectory by separating out each digit of the etext number, and uses it for a directory. The exception here is for etext numbers less than 10, which are...
[ "def", "_etextno_to_uri_subdirectory", "(", "etextno", ")", ":", "str_etextno", "=", "str", "(", "etextno", ")", ".", "zfill", "(", "2", ")", "all_but_last_digit", "=", "list", "(", "str_etextno", "[", ":", "-", "1", "]", ")", "subdir_part", "=", "\"/\"", ...
39.736842
17.789474
def execute(self, eopatch): """ Add cloud binary mask and (optionally) cloud probability map to input eopatch :param eopatch: Input `EOPatch` instance :return: `EOPatch` with additional cloud maps """ # Downsample or make request if not eopatch.data: raise Va...
[ "def", "execute", "(", "self", ",", "eopatch", ")", ":", "# Downsample or make request", "if", "not", "eopatch", ".", "data", ":", "raise", "ValueError", "(", "'EOPatch must contain some data feature'", ")", "if", "self", ".", "data_feature", "in", "eopatch", ".",...
52.5
29.388889
def set_cache_url(self): """ The cache url is a comma separated list of emails. """ emails = u",".join(sorted(self.addresses)) self.cache_url = u"%s:%s" % (self.scheme, emails)
[ "def", "set_cache_url", "(", "self", ")", ":", "emails", "=", "u\",\"", ".", "join", "(", "sorted", "(", "self", ".", "addresses", ")", ")", "self", ".", "cache_url", "=", "u\"%s:%s\"", "%", "(", "self", ".", "scheme", ",", "emails", ")" ]
35.166667
10.166667
def get_algs_from_ciphersuite_name(ciphersuite_name): """ Return the 3-tuple made of the Key Exchange Algorithm class, the Cipher class and the HMAC class, through the parsing of the ciphersuite name. """ tls1_3 = False if ciphersuite_name.startswith("TLS"): s = ciphersuite_name[4:] ...
[ "def", "get_algs_from_ciphersuite_name", "(", "ciphersuite_name", ")", ":", "tls1_3", "=", "False", "if", "ciphersuite_name", ".", "startswith", "(", "\"TLS\"", ")", ":", "s", "=", "ciphersuite_name", "[", "4", ":", "]", "if", "s", ".", "endswith", "(", "\"C...
36.638298
16.638298
def extract_file_config(content): """ Pull out the file-specific config specified in the docstring. """ prop_pat = re.compile( r"^\s*#\s*sphinx_gallery_([A-Za-z0-9_]+)\s*=\s*(.+)\s*$", re.MULTILINE) file_conf = {} for match in re.finditer(prop_pat, content): name = match...
[ "def", "extract_file_config", "(", "content", ")", ":", "prop_pat", "=", "re", ".", "compile", "(", "r\"^\\s*#\\s*sphinx_gallery_([A-Za-z0-9_]+)\\s*=\\s*(.+)\\s*$\"", ",", "re", ".", "MULTILINE", ")", "file_conf", "=", "{", "}", "for", "match", "in", "re", ".", ...
30.428571
15.285714
def get_service_plan_for_service(self, service_name): """ Return the service plans available for a given service. """ services = self.get_services() for service in services['resources']: if service['entity']['label'] == service_name: response = self.ap...
[ "def", "get_service_plan_for_service", "(", "self", ",", "service_name", ")", ":", "services", "=", "self", ".", "get_services", "(", ")", "for", "service", "in", "services", "[", "'resources'", "]", ":", "if", "service", "[", "'entity'", "]", "[", "'label'"...
44.666667
11.555556
def readTable(self, tableName): """ Read the table corresponding to the specified name, equivalent to the AMPL statement: .. code-block:: ampl read table tableName; Args: tableName: Name of the table to be read. """ lock_and_call( ...
[ "def", "readTable", "(", "self", ",", "tableName", ")", ":", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "readTable", "(", "tableName", ")", ",", "self", ".", "_lock", ")" ]
24
20
def terminate(self): """Properly terminates this player instance. Preferably use this instead of relying on python's garbage collector to cause this to be called from the object's destructor. """ self.handle, handle = None, self.handle if threading.current_thread() is self._event...
[ "def", "terminate", "(", "self", ")", ":", "self", ".", "handle", ",", "handle", "=", "None", ",", "self", ".", "handle", "if", "threading", ".", "current_thread", "(", ")", "is", "self", ".", "_event_thread", ":", "# Handle special case to allow event handle ...
52.214286
18.071429
def list_vpnservices(retrieve_all=True, profile=None, **kwargs): ''' Fetches a list of all configured VPN services for a tenant CLI Example: .. code-block:: bash salt '*' neutron.list_vpnservices :param retrieve_all: True or False, default: True (Optional) :param profile: Profile to ...
[ "def", "list_vpnservices", "(", "retrieve_all", "=", "True", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "_auth", "(", "profile", ")", "return", "conn", ".", "list_vpnservices", "(", "retrieve_all", ",", "*", "*", "kwargs...
28
24.125
def run(self, shell=True, cmdline=False, echo=True): """Run FIO job""" if env(): return 1 cmd = ["fio"] + self.__parse_parms() if cmdline: cij.emph("cij.fio.run: shell: %r, cmd: %r" % (shell, cmd)) return cij.ssh.command(cmd, shell, echo)
[ "def", "run", "(", "self", ",", "shell", "=", "True", ",", "cmdline", "=", "False", ",", "echo", "=", "True", ")", ":", "if", "env", "(", ")", ":", "return", "1", "cmd", "=", "[", "\"fio\"", "]", "+", "self", ".", "__parse_parms", "(", ")", "if...
26.818182
21.636364
def new_conn(self): """ Create a new ConnectionWrapper instance :return: """ """ :return: """ logger.debug("Opening new connection to rethinkdb with args=%s" % self._conn_args) return ConnectionWrapper(self._pool, **self._conn_args)
[ "def", "new_conn", "(", "self", ")", ":", "\"\"\"\n :return:\n \"\"\"", "logger", ".", "debug", "(", "\"Opening new connection to rethinkdb with args=%s\"", "%", "self", ".", "_conn_args", ")", "return", "ConnectionWrapper", "(", "self", ".", "_pool", ",",...
29.5
14.9
def identifier(self, mask: str = '##-##/##') -> str: """Generate a random identifier by mask. With this method you can generate any identifiers that you need. Simply select the mask that you need. :param mask: The mask. Here ``@`` is a placeholder for characters and ``#`` i...
[ "def", "identifier", "(", "self", ",", "mask", ":", "str", "=", "'##-##/##'", ")", "->", "str", ":", "return", "self", ".", "random", ".", "custom_code", "(", "mask", "=", "mask", ")" ]
31.8
19.466667
def record_entering(self, time, code, frame_key, parent_stats): """Entered to a function call.""" stats = parent_stats.ensure_child(code, RecordingStatistics) self._times_entered[(code, frame_key)] = time stats.own_hits += 1
[ "def", "record_entering", "(", "self", ",", "time", ",", "code", ",", "frame_key", ",", "parent_stats", ")", ":", "stats", "=", "parent_stats", ".", "ensure_child", "(", "code", ",", "RecordingStatistics", ")", "self", ".", "_times_entered", "[", "(", "code"...
50.4
15.4
def paste(**kwargs): """Returns system clipboard contents.""" window = Tk() window.withdraw() d = window.selection_get(selection = 'CLIPBOARD') return d
[ "def", "paste", "(", "*", "*", "kwargs", ")", ":", "window", "=", "Tk", "(", ")", "window", ".", "withdraw", "(", ")", "d", "=", "window", ".", "selection_get", "(", "selection", "=", "'CLIPBOARD'", ")", "return", "d" ]
27.833333
17.166667
def stop(self): """ Stops the service. """ if self.log_file != PIPE and not (self.log_file == DEVNULL and _HAS_NATIVE_DEVNULL): try: self.log_file.close() except Exception: pass if self.process is None: return ...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "log_file", "!=", "PIPE", "and", "not", "(", "self", ".", "log_file", "==", "DEVNULL", "and", "_HAS_NATIVE_DEVNULL", ")", ":", "try", ":", "self", ".", "log_file", ".", "close", "(", ")", "exce...
27.757576
16.181818
def afterContext(self): """Pop my mod stack and restore sys.modules to the state it was in when mod stack was pushed. """ mods = self._mod_stack.pop() to_del = [ m for m in sys.modules.keys() if m not in mods ] if to_del: log.debug('removing sys modules entrie...
[ "def", "afterContext", "(", "self", ")", ":", "mods", "=", "self", ".", "_mod_stack", ".", "pop", "(", ")", "to_del", "=", "[", "m", "for", "m", "in", "sys", ".", "modules", ".", "keys", "(", ")", "if", "m", "not", "in", "mods", "]", "if", "to_...
38.727273
11
def block(self, **kwargs): """Block the user. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabBlockError: If the user could not be blocked Returns: ...
[ "def", "block", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'/users/%s/block'", "%", "self", ".", "id", "server_data", "=", "self", ".", "manager", ".", "gitlab", ".", "http_post", "(", "path", ",", "*", "*", "kwargs", ")", "if", ...
32.055556
20.333333
def convert_dense(net, node, module, builder): """Convert a dense layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural ...
[ "def", "convert_dense", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "has_bias", "=", "True", "name", "=", "node", "[", "'name'", "]", "in...
22.475
20.35
def _difference(self, original_keys, updated_keys, name, item_index): """Calculate difference between the original and updated sets of keys. Removed items will be removed from item_index, new items should have been added by the discovery process. (?help or ?sensor-list) This method is ...
[ "def", "_difference", "(", "self", ",", "original_keys", ",", "updated_keys", ",", "name", ",", "item_index", ")", ":", "original_keys", "=", "set", "(", "original_keys", ")", "updated_keys", "=", "set", "(", "updated_keys", ")", "added_keys", "=", "updated_ke...
35.825
19.4
def create_authentication_string(username, password): ''' Creates an authentication string from the username and password. :username: Username. :password: Password. :return: The encoded string. ''' username_utf8 = username.encode('utf-8') userpw_utf8 = password.encode('utf-8') user...
[ "def", "create_authentication_string", "(", "username", ",", "password", ")", ":", "username_utf8", "=", "username", ".", "encode", "(", "'utf-8'", ")", "userpw_utf8", "=", "password", ".", "encode", "(", "'utf-8'", ")", "username_perc", "=", "quote", "(", "us...
32.647059
20.647059
def comment_expression(self): """doc: http://open.youku.com/docs/doc?id=92 """ url = 'https://openapi.youku.com/v2/schemas/comment/expression.json' r = requests.get(url) check_error(r) return r.json()
[ "def", "comment_expression", "(", "self", ")", ":", "url", "=", "'https://openapi.youku.com/v2/schemas/comment/expression.json'", "r", "=", "requests", ".", "get", "(", "url", ")", "check_error", "(", "r", ")", "return", "r", ".", "json", "(", ")" ]
34.571429
13.285714
def add_neighbor(self, edge: "Edge") -> None: """ Adds a new neighbor to the node. Arguments: edge (Edge): The edge that would connect this node with its neighbor. """ if edge is None or (edge.source != self and edge.target != self): return ...
[ "def", "add_neighbor", "(", "self", ",", "edge", ":", "\"Edge\"", ")", "->", "None", ":", "if", "edge", "is", "None", "or", "(", "edge", ".", "source", "!=", "self", "and", "edge", ".", "target", "!=", "self", ")", ":", "return", "if", "edge", ".",...
36.56
21.28
def kmc(forward_in, database_name, min_occurrences=1, reverse_in='NA', k=31, cleanup=True, returncmd=False, tmpdir='tmp', **kwargs): """ Runs kmc to count kmers. :param forward_in: Forward input reads. Assumed to be fastq. :param database_name: Name for output kmc database. :param min_occurr...
[ "def", "kmc", "(", "forward_in", ",", "database_name", ",", "min_occurrences", "=", "1", ",", "reverse_in", "=", "'NA'", ",", "k", "=", "31", ",", "cleanup", "=", "True", ",", "returncmd", "=", "False", ",", "tmpdir", "=", "'tmp'", ",", "*", "*", "kw...
49.926829
21.878049
def read_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_horizontal_pod_autoscaler_status # noqa: E501 read status of the specified HorizontalPodAutoscaler # noqa: E501 This method makes a synchronous HTTP request by default. To m...
[ "def", "read_namespaced_horizontal_pod_autoscaler_status", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ...
57.695652
30.304348
def gen_radio_view(sig_dic): ''' for checkbox ''' view_zuoxiang = ''' <div class="col-sm-4"><span class="des">{0}</span></div> <div class="col-sm-8"> '''.format(sig_dic['zh']) dic_tmp = sig_dic['dic'] for key in dic_tmp.keys(): tmp_str = '''<span class="input_text"> ...
[ "def", "gen_radio_view", "(", "sig_dic", ")", ":", "view_zuoxiang", "=", "'''\n <div class=\"col-sm-4\"><span class=\"des\">{0}</span></div>\n <div class=\"col-sm-8\">\n '''", ".", "format", "(", "sig_dic", "[", "'zh'", "]", ")", "dic_tmp", "=", "sig_dic", "[", "'d...
28.2
20.7
def generate(converter, input_file, format='xml', encoding='utf8'): """ Given a converter (as returned by compile()), this function reads the given input file and converts it to the requested output format. Supported output formats are 'xml', 'yaml', 'json', or 'none'. :type converter: compiler.C...
[ "def", "generate", "(", "converter", ",", "input_file", ",", "format", "=", "'xml'", ",", "encoding", "=", "'utf8'", ")", ":", "with", "codecs", ".", "open", "(", "input_file", ",", "encoding", "=", "encoding", ")", "as", "thefile", ":", "return", "gener...
38.6
18.2
def _process_glsl_template(template, colors): """Replace $color_i by color #i in the GLSL template.""" for i in range(len(colors) - 1, -1, -1): color = colors[i] assert len(color) == 4 vec4_color = 'vec4(%.3f, %.3f, %.3f, %.3f)' % tuple(color) template = template.replace('$color_...
[ "def", "_process_glsl_template", "(", "template", ",", "colors", ")", ":", "for", "i", "in", "range", "(", "len", "(", "colors", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "color", "=", "colors", "[", "i", "]", "assert", "len", "(", ...
44.125
13.125
def get_language_progress(self, lang): """Get informations about user's progression in a language.""" if not self._is_current_language(lang): self._switch_language(lang) fields = ['streak', 'language_string', 'level_progress', 'num_skills_learned', 'level_percent',...
[ "def", "get_language_progress", "(", "self", ",", "lang", ")", ":", "if", "not", "self", ".", "_is_current_language", "(", "lang", ")", ":", "self", ".", "_switch_language", "(", "lang", ")", "fields", "=", "[", "'streak'", ",", "'language_string'", ",", "...
48.090909
20.454545
def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) r...
[ "def", "load", "(", "input_filename", ")", ":", "try", ":", "pil_img", "=", "Image", ".", "open", "(", "input_filename", ")", "except", "IOError", ":", "sys", ".", "stderr", ".", "write", "(", "'warning: error opening {}\\n'", ".", "format", "(", "input_file...
23.304348
22
def move_up(lines=1, file=sys.stdout): """ Move the cursor up a number of lines. Esc[ValueA: Moves the cursor up by the specified number of lines without changing columns. If the cursor is already on the top line, ANSI.SYS ignores this sequence. """ move.up(lines).write(file...
[ "def", "move_up", "(", "lines", "=", "1", ",", "file", "=", "sys", ".", "stdout", ")", ":", "move", ".", "up", "(", "lines", ")", ".", "write", "(", "file", "=", "file", ")" ]
35.333333
17.555556
async def createAnswer(self): """ Create an SDP answer to an offer received from a remote peer during the offer/answer negotiation of a WebRTC connection. :rtype: :class:`RTCSessionDescription` """ # check state is valid self.__assertNotClosed() if self.s...
[ "async", "def", "createAnswer", "(", "self", ")", ":", "# check state is valid", "self", ".", "__assertNotClosed", "(", ")", "if", "self", ".", "signalingState", "not", "in", "[", "'have-remote-offer'", ",", "'have-local-pranswer'", "]", ":", "raise", "InvalidStat...
44.175
20.975
def postag( X, ax=None, tagset="penn_treebank", colormap=None, colors=None, frequency=False, **kwargs ): """ Display a barchart with the counts of different parts of speech in X, which consists of a part-of-speech-tagged corpus, which the visualizer expects to be a list of li...
[ "def", "postag", "(", "X", ",", "ax", "=", "None", ",", "tagset", "=", "\"penn_treebank\"", ",", "colormap", "=", "None", ",", "colors", "=", "None", ",", "frequency", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Instantiate the visualizer", "visu...
33
21.264151
def upgrade(refresh=True): ''' Upgrade all of the packages to the latest available version. Returns a dict containing the changes:: {'<package>': {'old': '<old-version>', 'new': '<new-version>'}} CLI Example: .. code-block:: bash salt '*' pkgutil.upgrade ...
[ "def", "upgrade", "(", "refresh", "=", "True", ")", ":", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "refresh", ")", ":", "refresh_db", "(", ")", "old", "=", "list_pkgs", "(", ")", "# Install or upgrade the package", "# If package is alread...
23.962963
19.888889
def arguments_from_optionable(parser, component, prefix=""): """ Add argparse arguments from all options of one :class:`Optionable` >>> # Let's build a dummy optionable component: >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> comp.ad...
[ "def", "arguments_from_optionable", "(", "parser", ",", "component", ",", "prefix", "=", "\"\"", ")", ":", "for", "option", "in", "component", ".", "options", ":", "if", "component", ".", "options", "[", "option", "]", ".", "hidden", ":", "continue", "argu...
38.022727
19.363636
def from_url(url, format=None): """ Returns the crs object from a string interpreted as a specified format, located at a given url site. Arguments: - *url*: The url where the crs string is to be read from. - *format* (optional): Which format to parse the crs string as. One of "ogc wkt", "esri wkt...
[ "def", "from_url", "(", "url", ",", "format", "=", "None", ")", ":", "# first get string from url", "string", "=", "urllib2", ".", "urlopen", "(", "url", ")", ".", "read", "(", ")", "if", "PY3", "is", "True", ":", "# decode str into string", "string", "=",...
26.939394
23.30303
def _serialize_function(obj): """ Still needing this much try-except stuff. We should find a way to get rid of this. :param obj: :return: """ try: obj = inspect.getsource(obj) except (TypeError, IOError): try: obj = marshal.dumps(obj) except ValueError: ...
[ "def", "_serialize_function", "(", "obj", ")", ":", "try", ":", "obj", "=", "inspect", ".", "getsource", "(", "obj", ")", "except", "(", "TypeError", ",", "IOError", ")", ":", "try", ":", "obj", "=", "marshal", ".", "dumps", "(", "obj", ")", "except"...
27.4
15.8
def derived_contracts(self): ''' list(Contract): Return the list of contracts derived from self ''' candidates = self.slither.contracts return [c for c in candidates if self in c.inheritance]
[ "def", "derived_contracts", "(", "self", ")", ":", "candidates", "=", "self", ".", "slither", ".", "contracts", "return", "[", "c", "for", "c", "in", "candidates", "if", "self", "in", "c", ".", "inheritance", "]" ]
38.333333
21.666667
def ssh_interface(vm_): ''' Return the ssh_interface type to connect to. Either 'public_ips' (default) or 'private_ips'. ''' ret = config.get_cloud_config_value( 'ssh_interface', vm_, __opts__, default='public_ips', search_global=False ) if ret not in ('public_ips', 'private_...
[ "def", "ssh_interface", "(", "vm_", ")", ":", "ret", "=", "config", ".", "get_cloud_config_value", "(", "'ssh_interface'", ",", "vm_", ",", "__opts__", ",", "default", "=", "'public_ips'", ",", "search_global", "=", "False", ")", "if", "ret", "not", "in", ...
31.647059
20
def get_pin_and_cookie_name(app): """Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in th...
[ "def", "get_pin_and_cookie_name", "(", "app", ")", ":", "pin", "=", "os", ".", "environ", ".", "get", "(", "\"WERKZEUG_DEBUG_PIN\"", ")", "rv", "=", "None", "num", "=", "None", "# Pin was explicitly disabled", "if", "pin", "==", "\"off\"", ":", "return", "No...
32.654321
21.049383
def simBirth(self,which_agents): ''' Makes new Markov consumer by drawing initial normalized assets, permanent income levels, and discrete states. Calls IndShockConsumerType.simBirth, then draws from initial Markov distribution. Parameters ---------- which_agents : np.ar...
[ "def", "simBirth", "(", "self", ",", "which_agents", ")", ":", "IndShockConsumerType", ".", "simBirth", "(", "self", ",", "which_agents", ")", "# Get initial assets and permanent income", "if", "not", "self", ".", "global_markov", ":", "#Markov state is not changed if i...
45.85
33.35
def execute_command(self, *args, **options): """Execute a command and return a parsed response""" pool = self.connection_pool command_name = args[0] for i in _xrange(self.execution_attempts): connection = pool.get_connection(command_name, **options) try: ...
[ "def", "execute_command", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "pool", "=", "self", ".", "connection_pool", "command_name", "=", "args", "[", "0", "]", "for", "i", "in", "_xrange", "(", "self", ".", "execution_attempts", "...
42.933333
11.6
def create( self, name, command_to_run, container_image, container_type, description="", logs_path="", results_path="", environment_variables=None, required_arguments=None, required_arguments_default_values=None, extra_data_...
[ "def", "create", "(", "self", ",", "name", ",", "command_to_run", ",", "container_image", ",", "container_type", ",", "description", "=", "\"\"", ",", "logs_path", "=", "\"\"", ",", "results_path", "=", "\"\"", ",", "environment_variables", "=", "None", ",", ...
40.075758
19.212121
def mcycle(return_X_y=True): """motorcyle acceleration dataset Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) OR Pandas DataFrame...
[ "def", "mcycle", "(", "return_X_y", "=", "True", ")", ":", "# y is real", "# recommend LinearGAM", "motor", "=", "pd", ".", "read_csv", "(", "PATH", "+", "'/mcycle.csv'", ",", "index_col", "=", "0", ")", "if", "return_X_y", ":", "X", "=", "motor", ".", "...
22.709677
20.967742
def close(self): """Toggle state to closed switch disconnector""" self._state = 'closed' self.grid.graph.add_edge( self._nodes[0], self._nodes[1], {'line': self._line})
[ "def", "close", "(", "self", ")", ":", "self", ".", "_state", "=", "'closed'", "self", ".", "grid", ".", "graph", ".", "add_edge", "(", "self", ".", "_nodes", "[", "0", "]", ",", "self", ".", "_nodes", "[", "1", "]", ",", "{", "'line'", ":", "s...
40
13.2
def run_checks(collector): """Just run the checks for our modules""" artifact = collector.configuration["dashmat"].artifact chosen = artifact if chosen in (None, "", NotSpecified): chosen = None dashmat = collector.configuration["dashmat"] modules = collector.configuration["__active_mod...
[ "def", "run_checks", "(", "collector", ")", ":", "artifact", "=", "collector", ".", "configuration", "[", "\"dashmat\"", "]", ".", "artifact", "chosen", "=", "artifact", "if", "chosen", "in", "(", "None", ",", "\"\"", ",", "NotSpecified", ")", ":", "chosen...
36.375
19.333333
def get_cutout(self, resource, resolution, x_range, y_range, z_range, time_range=None, id_list=[], no_cache=None, access_mode=CacheMode.no_cache, **kwargs): """Get a cutout from the volume service. Note that access_mode=no_cache is desirable when reading large amounts of data at onc...
[ "def", "get_cutout", "(", "self", ",", "resource", ",", "resolution", ",", "x_range", ",", "y_range", ",", "z_range", ",", "time_range", "=", "None", ",", "id_list", "=", "[", "]", ",", "no_cache", "=", "None", ",", "access_mode", "=", "CacheMode", ".", ...
64.130435
39.5