text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def getfigs(*fig_nums): """Get a list of matplotlib figures by figure numbers. If no arguments are given, all available figures are returned. If the argument list contains references to invalid figures, a warning is printed but the function continues pasting further figures. Parameters ------...
[ "def", "getfigs", "(", "*", "fig_nums", ")", ":", "from", "matplotlib", ".", "_pylab_helpers", "import", "Gcf", "if", "not", "fig_nums", ":", "fig_managers", "=", "Gcf", ".", "get_all_fig_managers", "(", ")", "return", "[", "fm", ".", "canvas", ".", "figur...
33.6
20.2
def rectToArray(self, swapWH = False): """! \~english Rectangles converted to array of coordinates @return: an array of rect points. eg. (x1,y1,x2,y2) \~chinese 矩形数据转换为矩形坐标数组 @return: 矩形座标数组, 例如: ( x1,y1,x2,y2 ) """ if swapWH == False: ...
[ "def", "rectToArray", "(", "self", ",", "swapWH", "=", "False", ")", ":", "if", "swapWH", "==", "False", ":", "return", "[", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "x", "+", "self", ".", "width", ",", "self", ".", "y", "+", ...
33.357143
18.428571
def set_prekeys_as_sent(self, prekeyIds): """ :param prekeyIds: :type prekeyIds: list :return: :rtype: """ logger.debug("set_prekeys_as_sent(prekeyIds=[%d prekeyIds])" % len(prekeyIds)) self._store.preKeyStore.setAsSent([prekey.getId() for prekey in prekey...
[ "def", "set_prekeys_as_sent", "(", "self", ",", "prekeyIds", ")", ":", "logger", ".", "debug", "(", "\"set_prekeys_as_sent(prekeyIds=[%d prekeyIds])\"", "%", "len", "(", "prekeyIds", ")", ")", "self", ".", "_store", ".", "preKeyStore", ".", "setAsSent", "(", "["...
35.222222
18.333333
def find_encrypt_data_assertion_list(self, _assertions): """ Verifies if a list of assertions contains encrypted data in the advice element. :param _assertions: A list of assertions. :return: True encrypted data exists otherwise false. """ for _assertion in _assertions: ...
[ "def", "find_encrypt_data_assertion_list", "(", "self", ",", "_assertions", ")", ":", "for", "_assertion", "in", "_assertions", ":", "if", "_assertion", ".", "advice", ":", "if", "_assertion", ".", "advice", ".", "encrypted_assertion", ":", "res", "=", "self", ...
41.785714
13.357143
def get_traffic_meter(self): """ Return dict of traffic meter stats. Returns None if error occurred. """ _LOGGER.info("Get traffic meter") def parse_text(text): """ there are three kinds of values in the returned data This fun...
[ "def", "get_traffic_meter", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"Get traffic meter\"", ")", "def", "parse_text", "(", "text", ")", ":", "\"\"\"\n there are three kinds of values in the returned data\n This function parses the differ...
34.342105
17.131579
def setup_statemachine(self): """Setup and start state machine""" machine = QtCore.QStateMachine() # _______________ # | | # | | # | | # |_______________| # group = util.QState("group", QtCore.QState.Par...
[ "def", "setup_statemachine", "(", "self", ")", ":", "machine", "=", "QtCore", ".", "QStateMachine", "(", ")", "# _______________", "# | |", "# | |", "# | |", "# |_______________|", "#", "group", "=", "util", ".", "QState", "(...
33.013333
17.566667
def _example_stock_basic(quote_ctx): """ 获取股票信息,输出 股票代码,股票名,每手数量,股票类型,子类型所属正股 """ ret_status, ret_data = quote_ctx.get_stock_basicinfo(ft.Market.HK, ft.SecurityType.STOCK) if ret_status != ft.RET_OK: print(ret_data) exit() print("stock_basic") print(ret_data)
[ "def", "_example_stock_basic", "(", "quote_ctx", ")", ":", "ret_status", ",", "ret_data", "=", "quote_ctx", ".", "get_stock_basicinfo", "(", "ft", ".", "Market", ".", "HK", ",", "ft", ".", "SecurityType", ".", "STOCK", ")", "if", "ret_status", "!=", "ft", ...
29.4
14.6
def send(self, buf, flags=0): """ Send data on the connection. NOTE: If you get one of the WantRead, WantWrite or WantX509Lookup exceptions on this, you have to call the method again with the SAME buffer. :param buf: The string, buffer or memoryview to send :param flags:...
[ "def", "send", "(", "self", ",", "buf", ",", "flags", "=", "0", ")", ":", "# Backward compatibility", "buf", "=", "_text_to_bytes_and_warn", "(", "\"buf\"", ",", "buf", ")", "if", "isinstance", "(", "buf", ",", "memoryview", ")", ":", "buf", "=", "buf", ...
39.769231
17
def plot_time_elapsed(filename, elapsed=False, unit='s', plot_kwargs=None): '''Plot series data from MonitorTimeElapsed output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. elapsed (bool): If ``True``, it plots the total elapsed time....
[ "def", "plot_time_elapsed", "(", "filename", ",", "elapsed", "=", "False", ",", "unit", "=", "'s'", ",", "plot_kwargs", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "if", "plot_kwargs", "is", "None", ":", "plot_kwargs", "=", ...
31.861111
24.25
def count_subgraph_sizes(graph: BELGraph, annotation: str = 'Subgraph') -> Counter[int]: """Count the number of nodes in each subgraph induced by an annotation. :param annotation: The annotation to group by and compare. Defaults to 'Subgraph' :return: A dictionary from {annotation value: number of nodes} ...
[ "def", "count_subgraph_sizes", "(", "graph", ":", "BELGraph", ",", "annotation", ":", "str", "=", "'Subgraph'", ")", "->", "Counter", "[", "int", "]", ":", "return", "count_dict_values", "(", "group_nodes_by_annotation", "(", "graph", ",", "annotation", ")", "...
56.428571
27.571429
def list_tickets(self, **kwargs): """List all tickets, optionally filtered by a view. Specify filters as keyword arguments, such as: filter_name = one of ['all_tickets', 'new_my_open', 'spam', 'deleted', None] (defaults to 'all_tickets'; passing None u...
[ "def", "list_tickets", "(", "self", ",", "*", "*", "kwargs", ")", ":", "filter_name", "=", "'all_tickets'", "if", "'filter_name'", "in", "kwargs", "and", "kwargs", "[", "'filter_name'", "]", "is", "not", "None", ":", "filter_name", "=", "kwargs", "[", "'fi...
35.034483
20.931034
def pegasus_node_placer_2d(G, scale=1., center=None, dim=2, crosses=False): """Generates a function that converts Pegasus indices to x, y coordinates for a plot. Parameters ---------- G : NetworkX graph Should be a Pegasus graph or a subgraph of a Pegasus graph. This should be the p...
[ "def", "pegasus_node_placer_2d", "(", "G", ",", "scale", "=", "1.", ",", "center", "=", "None", ",", "dim", "=", "2", ",", "crosses", "=", "False", ")", ":", "import", "numpy", "as", "np", "m", "=", "G", ".", "graph", ".", "get", "(", "'rows'", "...
29.679487
24.884615
def lineage(self, tax_id=None, tax_name=None): """Public method for returning a lineage; includes tax_name and rank """ if not bool(tax_id) ^ bool(tax_name): msg = 'Exactly one of tax_id and tax_name may be provided.' raise ValueError(msg) if tax_name: ...
[ "def", "lineage", "(", "self", ",", "tax_id", "=", "None", ",", "tax_name", "=", "None", ")", ":", "if", "not", "bool", "(", "tax_id", ")", "^", "bool", "(", "tax_name", ")", ":", "msg", "=", "'Exactly one of tax_id and tax_name may be provided.'", "raise", ...
32.758621
21.965517
def demo_update(self): """ Performs a demonstration update by calling the demo optimization operation. Note that the batch data does not have to be fetched from the demo memory as this is now part of the TensorFlow operation of the demo update. """ fetches = self.demo_opt...
[ "def", "demo_update", "(", "self", ")", ":", "fetches", "=", "self", ".", "demo_optimization_output", "self", ".", "monitored_session", ".", "run", "(", "fetches", "=", "fetches", ")" ]
42.333333
21.666667
def download_file(image_name, output_path, width=DEFAULT_WIDTH): """Download a given Wikimedia Commons file.""" image_name = clean_up_filename(image_name) logging.info("Downloading %s with width %s", image_name, width) try: contents, output_file_name = get_thumbnail_of_file(image_name, width) ...
[ "def", "download_file", "(", "image_name", ",", "output_path", ",", "width", "=", "DEFAULT_WIDTH", ")", ":", "image_name", "=", "clean_up_filename", "(", "image_name", ")", "logging", ".", "info", "(", "\"Downloading %s with width %s\"", ",", "image_name", ",", "w...
47.64
18.52
def eval(self, x, y, z): """Evaluate the function in (x, y, z). The function is rotationally symmetric around z. """ ro = np.sqrt(x**2 + y**2) zs, xs = ro.shape v = self.eval_xz(ro.ravel(), z.ravel()) return v.reshape(zs, xs)
[ "def", "eval", "(", "self", ",", "x", ",", "y", ",", "z", ")", ":", "ro", "=", "np", ".", "sqrt", "(", "x", "**", "2", "+", "y", "**", "2", ")", "zs", ",", "xs", "=", "ro", ".", "shape", "v", "=", "self", ".", "eval_xz", "(", "ro", ".",...
34.25
8.625
def list_staged_files(self) -> typing.List[str]: """ :return: staged files :rtype: list of str """ staged_files: typing.List[str] = [x.a_path for x in self.repo.index.diff('HEAD')] LOGGER.debug('staged files: %s', staged_files) return staged_files
[ "def", "list_staged_files", "(", "self", ")", "->", "typing", ".", "List", "[", "str", "]", ":", "staged_files", ":", "typing", ".", "List", "[", "str", "]", "=", "[", "x", ".", "a_path", "for", "x", "in", "self", ".", "repo", ".", "index", ".", ...
37
13.5
def _bsp_traverse( node_iter: Iterable[tcod.bsp.BSP], callback: Callable[[tcod.bsp.BSP, Any], None], userData: Any, ) -> None: """pack callback into a handle for use with the callback _pycall_bsp_callback """ for node in node_iter: callback(node, userData)
[ "def", "_bsp_traverse", "(", "node_iter", ":", "Iterable", "[", "tcod", ".", "bsp", ".", "BSP", "]", ",", "callback", ":", "Callable", "[", "[", "tcod", ".", "bsp", ".", "BSP", ",", "Any", "]", ",", "None", "]", ",", "userData", ":", "Any", ",", ...
28.3
12.4
def remove(self, path, recursive=False, use_sudo=False): """ Remove a file or directory """ func = use_sudo and run_as_root or self.run options = '-r ' if recursive else '' func('/bin/rm {0}{1}'.format(options, quote(path)))
[ "def", "remove", "(", "self", ",", "path", ",", "recursive", "=", "False", ",", "use_sudo", "=", "False", ")", ":", "func", "=", "use_sudo", "and", "run_as_root", "or", "self", ".", "run", "options", "=", "'-r '", "if", "recursive", "else", "''", "func...
38
8
def add(self, data): """ Adds a new data node to the front list. The provided data will be encapsulated into a new instance of LinkedListNode class and linked list pointers will be updated, as well as list's size. :param data: the data to be inserted in the new list node ...
[ "def", "add", "(", "self", ",", "data", ")", ":", "node", "=", "LinkedListNode", "(", "data", ",", "None", ")", "if", "self", ".", "_size", "==", "0", ":", "self", ".", "_first_node", "=", "node", "self", ".", "_last_node", "=", "node", "else", ":"...
34
16.736842
def __connect(self): """ Connect to the database. """ self.__methods = _get_methods_by_uri(self.sqluri) uri_connect_method = self.__methods[METHOD_CONNECT] self.__dbapi2_conn = uri_connect_method(self.sqluri)
[ "def", "__connect", "(", "self", ")", ":", "self", ".", "__methods", "=", "_get_methods_by_uri", "(", "self", ".", "sqluri", ")", "uri_connect_method", "=", "self", ".", "__methods", "[", "METHOD_CONNECT", "]", "self", ".", "__dbapi2_conn", "=", "uri_connect_m...
31.75
16
def set_val(self, direct, section, val): """ set the config values """ if val is not None: self.config.set(direct, section, val) self.update()
[ "def", "set_val", "(", "self", ",", "direct", ",", "section", ",", "val", ")", ":", "if", "val", "is", "not", "None", ":", "self", ".", "config", ".", "set", "(", "direct", ",", "section", ",", "val", ")", "self", ".", "update", "(", ")" ]
35.6
7.4
def get_price_as_price(reward): """ Returns a Price data structure from either a float or a Price """ if isinstance(reward, Price): final_price = reward else: final_price = Price(reward) return final_price
[ "def", "get_price_as_price", "(", "reward", ")", ":", "if", "isinstance", "(", "reward", ",", "Price", ")", ":", "final_price", "=", "reward", "else", ":", "final_price", "=", "Price", "(", "reward", ")", "return", "final_price" ]
29.888889
10.111111
def code_deparse_around_offset(name, offset, co, out=StringIO(), version=None, is_pypy=None, debug_opts=DEFAULT_DEBUG_OPTS): """ Like deparse_code(), but given a function/module name and offset, finds the node closest to offset. If offset is not...
[ "def", "code_deparse_around_offset", "(", "name", ",", "offset", ",", "co", ",", "out", "=", "StringIO", "(", ")", ",", "version", "=", "None", ",", "is_pypy", "=", "None", ",", "debug_opts", "=", "DEFAULT_DEBUG_OPTS", ")", ":", "assert", "iscode", "(", ...
36.740741
21.037037
def send(self, message, envelope_from=None): """Verifies and sends message. :param message: Message instance. :param envelope_from: Email address to be used in MAIL FROM command. """ assert message.send_to, "No recipients have been added" assert message.sender, ( ...
[ "def", "send", "(", "self", ",", "message", ",", "envelope_from", "=", "None", ")", ":", "assert", "message", ".", "send_to", ",", "\"No recipients have been added\"", "assert", "message", ".", "sender", ",", "(", "\"The message does not specify a sender and a default...
31.25641
19.487179
def create_adv_by_name(model, x, attack_type, sess, dataset, y=None, **kwargs): """ Creates the symbolic graph of an adversarial example given the name of an attack. Simplifies creating the symbolic graph of an attack by defining dataset-specific parameters. Dataset-specific default parameters are used unless...
[ "def", "create_adv_by_name", "(", "model", ",", "x", ",", "attack_type", ",", "sess", ",", "dataset", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# TODO: black box attacks", "attack_names", "=", "{", "'FGSM'", ":", "FastGradientMethod", ",", ...
38.72549
20.019608
def selection_pos(self): """Return start and end positions of the visual selection respectively.""" buff = self._vim.current.buffer beg = buff.mark('<') end = buff.mark('>') return beg, end
[ "def", "selection_pos", "(", "self", ")", ":", "buff", "=", "self", ".", "_vim", ".", "current", ".", "buffer", "beg", "=", "buff", ".", "mark", "(", "'<'", ")", "end", "=", "buff", ".", "mark", "(", "'>'", ")", "return", "beg", ",", "end" ]
37.333333
9.666667
def _port_postfix(self): """ Returns empty string for the default port and ':port' otherwise """ port = self.real_connection.port default_port = {'https': 443, 'http': 80}[self._protocol] return ':{}'.format(port) if port != default_port else ''
[ "def", "_port_postfix", "(", "self", ")", ":", "port", "=", "self", ".", "real_connection", ".", "port", "default_port", "=", "{", "'https'", ":", "443", ",", "'http'", ":", "80", "}", "[", "self", ".", "_protocol", "]", "return", "':{}'", ".", "format...
41
13.857143
def _check_channel_state_for_update( self, channel_identifier: ChannelID, closer: Address, update_nonce: Nonce, block_identifier: BlockSpecification, ) -> Optional[str]: """Check the channel state on chain to see if it has been updated. Co...
[ "def", "_check_channel_state_for_update", "(", "self", ",", "channel_identifier", ":", "ChannelID", ",", "closer", ":", "Address", ",", "update_nonce", ":", "Nonce", ",", "block_identifier", ":", "BlockSpecification", ",", ")", "->", "Optional", "[", "str", "]", ...
36.206897
18.310345
def encode(self, V, P, X, CC, seqNum, M, PT, SSRC, payload): """Encode the RTP packet with header fields and payload.""" timestamp = int(time()) header = bytearray(HEADER_SIZE) # Fill the header bytearray with RTP header fields # ... header[0] = header[0] | V << 6; ...
[ "def", "encode", "(", "self", ",", "V", ",", "P", ",", "X", ",", "CC", ",", "seqNum", ",", "M", ",", "PT", ",", "SSRC", ",", "payload", ")", ":", "timestamp", "=", "int", "(", "time", "(", ")", ")", "header", "=", "bytearray", "(", "HEADER_SIZE...
35.928571
9.035714
def encode_mv(vals): """For multivalues, values are wrapped in '$' and separated using ';' Literal '$' values are represented with '$$'""" s = "" for val in vals: val = val.replace('$', '$$') if len(s) > 0: s += ';' s += '$' + val + '$' return s
[ "def", "encode_mv", "(", "vals", ")", ":", "s", "=", "\"\"", "for", "val", "in", "vals", ":", "val", "=", "val", ".", "replace", "(", "'$'", ",", "'$$'", ")", "if", "len", "(", "s", ")", ">", "0", ":", "s", "+=", "';'", "s", "+=", "'$'", "+...
26.545455
17.454545
def ngrams(path, elem, ignore_hash=True): """ Yields N-grams from a JSTOR DfR dataset. Parameters ---------- path : string Path to unzipped JSTOR DfR folder containing N-grams. elem : string Name of subdirectory containing N-grams. (e.g. 'bigrams'). ignore_hash : bool ...
[ "def", "ngrams", "(", "path", ",", "elem", ",", "ignore_hash", "=", "True", ")", ":", "grams", "=", "GramGenerator", "(", "path", ",", "elem", ",", "ignore_hash", "=", "ignore_hash", ")", "return", "FeatureSet", "(", "{", "k", ":", "Feature", "(", "f",...
26.714286
22.333333
def predict_proba(self, X, raw_score=False, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs): """Return the predicted probability for each class for each sample. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_featur...
[ "def", "predict_proba", "(", "self", ",", "X", ",", "raw_score", "=", "False", ",", "num_iteration", "=", "None", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "LGBMCl...
49.644444
26.133333
def run_daemon(self): """ Used as daemon starter. Warning: DO NOT OVERRIDE THIS. """ try: self.daemon_runner.do_action() except daemon.runner.DaemonRunnerStopFailureError: self.onStopFail() except SystemExit: self.o...
[ "def", "run_daemon", "(", "self", ")", ":", "try", ":", "self", ".", "daemon_runner", ".", "do_action", "(", ")", "except", "daemon", ".", "runner", ".", "DaemonRunnerStopFailureError", ":", "self", ".", "onStopFail", "(", ")", "except", "SystemExit", ":", ...
24.230769
14.384615
def get_initial(self): """ Supply user object as initial data for the specified user_field(s). """ data = super(UserViewMixin, self).get_initial() for k in self.user_field: data[k] = self.request.user return data
[ "def", "get_initial", "(", "self", ")", ":", "data", "=", "super", "(", "UserViewMixin", ",", "self", ")", ".", "get_initial", "(", ")", "for", "k", "in", "self", ".", "user_field", ":", "data", "[", "k", "]", "=", "self", ".", "request", ".", "use...
26.5
17.7
def from_set(cls, database, key, data, clear=False): """ Create and populate a Set object from a data set. """ s = cls(database, key) if clear: s.clear() s.add(*data) return s
[ "def", "from_set", "(", "cls", ",", "database", ",", "key", ",", "data", ",", "clear", "=", "False", ")", ":", "s", "=", "cls", "(", "database", ",", "key", ")", "if", "clear", ":", "s", ".", "clear", "(", ")", "s", ".", "add", "(", "*", "dat...
26.111111
13.888889
def load_image(name, n, m=None, gpu=None, square=None): """Function to load images with certain size.""" if m is None: m = n if gpu is None: gpu = 0 if square is None: square = 0 command = ('Shearlab.load_image("{}", {}, {}, {}, {})'.format(name, n, m, gpu, squ...
[ "def", "load_image", "(", "name", ",", "n", ",", "m", "=", "None", ",", "gpu", "=", "None", ",", "square", "=", "None", ")", ":", "if", "m", "is", "None", ":", "m", "=", "n", "if", "gpu", "is", "None", ":", "gpu", "=", "0", "if", "square", ...
31.090909
18.363636
def _from_dict(cls, _dict): """Initialize a SourceOptions object from a json dictionary.""" args = {} if 'folders' in _dict: args['folders'] = [ SourceOptionsFolder._from_dict(x) for x in (_dict.get('folders')) ] if 'objects' in _di...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'folders'", "in", "_dict", ":", "args", "[", "'folders'", "]", "=", "[", "SourceOptionsFolder", ".", "_from_dict", "(", "x", ")", "for", "x", "in", "(", "_dict", ...
36.966667
13.8
def select_by_ctime(self, min_time=0, max_time=ts_2100, recursive=True): """ Select file path by create time. :param min_time: lower bound timestamp :param max_time: upper bound timestamp **中文文档** 选择所有 :attr:`pathlib_mate.pathlib2.Path.ctime` 在一...
[ "def", "select_by_ctime", "(", "self", ",", "min_time", "=", "0", ",", "max_time", "=", "ts_2100", ",", "recursive", "=", "True", ")", ":", "def", "filters", "(", "p", ")", ":", "return", "min_time", "<=", "p", ".", "ctime", "<=", "max_time", "return",...
27.625
19.25
def get_labs(format): """Gets Repair Cafe data from repairecafe.org.""" data = data_from_repaircafe_org() repaircafes = {} # Load all the Repair Cafes for i in data: # Create a lab current_lab = RepairCafe() # Add existing data from first scraping current_lab.name ...
[ "def", "get_labs", "(", "format", ")", ":", "data", "=", "data_from_repaircafe_org", "(", ")", "repaircafes", "=", "{", "}", "# Load all the Repair Cafes", "for", "i", "in", "data", ":", "# Create a lab", "current_lab", "=", "RepairCafe", "(", ")", "# Add existi...
39.932331
15.789474
def readline(self, size=None): """Reads a single line of text. The functions reads one entire line from the file-like object. A trailing end-of-line indicator (newline by default) is kept in the byte string (but may be absent when a file ends with an incomplete line). An empty byte string is return...
[ "def", "readline", "(", "self", ",", "size", "=", "None", ")", ":", "if", "size", "is", "not", "None", "and", "size", "<", "0", ":", "raise", "ValueError", "(", "'Invalid size value smaller than zero.'", ")", "if", "size", "is", "not", "None", "and", "si...
32.573333
23.506667
def calc_expiry_time(minutes_valid): """Return specific time an auth_hash will expire.""" return ( timezone.now() + datetime.timedelta(minutes=minutes_valid + 1) ).replace(second=0, microsecond=0)
[ "def", "calc_expiry_time", "(", "minutes_valid", ")", ":", "return", "(", "timezone", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "minutes", "=", "minutes_valid", "+", "1", ")", ")", ".", "replace", "(", "second", "=", "0", ",", "micr...
42.4
12.8
def _scaling_func_list(bdry_fracs, exponent): """Return a list of lists of scaling functions for the boundary.""" def scaling(factor): def scaling_func(x): return x * factor return scaling_func func_list = [] for frac_l, frac_r in bdry_fracs: func_list_entry = [] ...
[ "def", "_scaling_func_list", "(", "bdry_fracs", ",", "exponent", ")", ":", "def", "scaling", "(", "factor", ")", ":", "def", "scaling_func", "(", "x", ")", ":", "return", "x", "*", "factor", "return", "scaling_func", "func_list", "=", "[", "]", "for", "f...
31
16.227273
def receive(self, data): """ Create and return a message from data, also triggers the **receive** event Returns: - Message: message object """ self.log_debug("Received: %s" % (data)) message = self.make_message(data) self.trigger("receive", ...
[ "def", "receive", "(", "self", ",", "data", ")", ":", "self", ".", "log_debug", "(", "\"Received: %s\"", "%", "(", "data", ")", ")", "message", "=", "self", ".", "make_message", "(", "data", ")", "self", ".", "trigger", "(", "\"receive\"", ",", "data",...
27.538462
16
def chunkiter(iterable, chunksize): """break an iterable into chunks and yield those chunks as lists until there's nothing left to yeild. """ iterator = iter(iterable) for chunk in iter(lambda: list(itertools.islice(iterator, chunksize)), []): yield chunk
[ "def", "chunkiter", "(", "iterable", ",", "chunksize", ")", ":", "iterator", "=", "iter", "(", "iterable", ")", "for", "chunk", "in", "iter", "(", "lambda", ":", "list", "(", "itertools", ".", "islice", "(", "iterator", ",", "chunksize", ")", ")", ",",...
39.571429
10.857143
def add_coeffs(self, Tmin, Tmax, coeffs): '''Called internally during the parsing of the Zabransky database, to add coefficients as they are read one per line''' self.n += 1 if not self.Ts: self.Ts = [Tmin, Tmax] self.coeff_sets = [coeffs] else: ...
[ "def", "add_coeffs", "(", "self", ",", "Tmin", ",", "Tmax", ",", "coeffs", ")", ":", "self", ".", "n", "+=", "1", "if", "not", "self", ".", "Ts", ":", "self", ".", "Ts", "=", "[", "Tmin", ",", "Tmax", "]", "self", ".", "coeff_sets", "=", "[", ...
42.176471
14.764706
def patch_api_service_status(self, name, body, **kwargs): """ partially update status of the specified APIService This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_api_service_status(na...
[ "def", "patch_api_service_status", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "pa...
75.96
47.48
def percentSame(image1, image2): ''' Returns the percent of pixels that are equal @author: catshoes ''' # If the images differ in size, return 0% same. size_x1, size_y1 = image1.size size_x2, size_y2 = image2.size if (size_x1 != size_x2 or ...
[ "def", "percentSame", "(", "image1", ",", "image2", ")", ":", "# If the images differ in size, return 0% same.", "size_x1", ",", "size_y1", "=", "image1", ".", "size", "size_x2", ",", "size_y2", "=", "image2", ".", "size", "if", "(", "size_x1", "!=", "size_x2", ...
30.964286
16.321429
def _unsigned_mul_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a * b +00000000000000000 +00000000000000001 +0000000003fffffff +0000000007fffffff +000000000...
[ "def", "_unsigned_mul_overflow", "(", "state", ",", "a", ",", "b", ")", ":", "mul", "=", "Operators", ".", "SEXTEND", "(", "a", ",", "256", ",", "512", ")", "*", "Operators", ".", "SEXTEND", "(", "b", ",", "256", ",", "512", ")", "cond", "=", "Op...
89.833333
64.277778
def __coord_cqt_hz(n, fmin=None, bins_per_octave=12, **_kwargs): '''Get CQT bin frequencies''' if fmin is None: fmin = core.note_to_hz('C1') # we drop by half a bin so that CQT bins are centered vertically return core.cqt_frequencies(n+1, fmin=fmin / 2.0**(0.5/bi...
[ "def", "__coord_cqt_hz", "(", "n", ",", "fmin", "=", "None", ",", "bins_per_octave", "=", "12", ",", "*", "*", "_kwargs", ")", ":", "if", "fmin", "is", "None", ":", "fmin", "=", "core", ".", "note_to_hz", "(", "'C1'", ")", "# we drop by half a bin so tha...
43.555556
20.222222
def create_update_parameter(task_params, parameter_map): """ Builds the code block for the GPTool UpdateParameter method based on the input task_params. :param task_params: A list of task parameters from the task info structure. :return: A string representing the code block to the GPTool UpdateParamete...
[ "def", "create_update_parameter", "(", "task_params", ",", "parameter_map", ")", ":", "gp_params", "=", "[", "]", "for", "param", "in", "task_params", ":", "if", "param", "[", "'direction'", "]", ".", "upper", "(", ")", "==", "'OUTPUT'", ":", "continue", "...
35.142857
22.571429
def visitBaseDecl(self, ctx: ShExDocParser.BaseDeclContext): """ baseDecl: KW_BASE IRIREF """ self.context.base = None self.context.base = self.context.iriref_to_shexj_iriref(ctx.IRIREF())
[ "def", "visitBaseDecl", "(", "self", ",", "ctx", ":", "ShExDocParser", ".", "BaseDeclContext", ")", ":", "self", ".", "context", ".", "base", "=", "None", "self", ".", "context", ".", "base", "=", "self", ".", "context", ".", "iriref_to_shexj_iriref", "(",...
52.25
16.25
def update_payload(self, fields=None): """Wrap submitted data within an extra dict.""" payload = super(ConfigTemplate, self).update_payload(fields) if 'template_combinations' in payload: payload['template_combinations_attributes'] = payload.pop( 'template_combinations...
[ "def", "update_payload", "(", "self", ",", "fields", "=", "None", ")", ":", "payload", "=", "super", "(", "ConfigTemplate", ",", "self", ")", ".", "update_payload", "(", "fields", ")", "if", "'template_combinations'", "in", "payload", ":", "payload", "[", ...
51.571429
10
def _get_asym_hel(self,d): """ Find the asymmetry of each helicity. """ # get data 1+ 2+ 1- 2- d0 = d[0]; d1 = d[2]; d2 = d[1]; d3 = d[3] # pre-calcs denom1 = d0+d1; denom2 = d2+d3 # check for div by zero denom1[den...
[ "def", "_get_asym_hel", "(", "self", ",", "d", ")", ":", "# get data 1+ 2+ 1- 2-", "d0", "=", "d", "[", "0", "]", "d1", "=", "d", "[", "2", "]", "d2", "=", "d", "[", "1", "]", "d3", "=", "d", "[", "3", "]", "# pre-calcs", "denom1", "=", "d0", ...
34.545455
20.242424
def replace(self, scaling_group, name, cooldown, min_entities, max_entities, metadata=None): """ Replace an existing ScalingGroup configuration. All of the attributes must be specified. If you wish to delete any of the optional attributes, pass them in as None. """ ...
[ "def", "replace", "(", "self", ",", "scaling_group", ",", "name", ",", "cooldown", ",", "min_entities", ",", "max_entities", ",", "metadata", "=", "None", ")", ":", "return", "self", ".", "_manager", ".", "replace", "(", "scaling_group", ",", "name", ",", ...
48.888889
15.333333
def generate_certificate( ctx, slot, management_key, pin, public_key, subject, valid_days): """ Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key need to exist in the slot. \b SLOT P...
[ "def", "generate_certificate", "(", "ctx", ",", "slot", ",", "management_key", ",", "pin", ",", "public_key", ",", "subject", ",", "valid_days", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",...
34.28125
20.46875
def get_langids(dev): r"""Retrieve the list of supported Language IDs from the device. Most client code should not call this function directly, but instead use the langids property on the Device object, which will call this function as needed and cache the result. USB LANGIDs are 16-bit integers f...
[ "def", "get_langids", "(", "dev", ")", ":", "from", "usb", ".", "control", "import", "get_descriptor", "buf", "=", "get_descriptor", "(", "dev", ",", "254", ",", "DESC_TYPE_STRING", ",", "0", ")", "# The array is retrieved by asking for string descriptor zero, which i...
49.673469
29.530612
def rules(self): """ Returns a sorted list of firewall rules. Returns: list """ list_of_rules = [] for main_row in self.dict_rules: if 'rules' in main_row: for rule_row in main_row['rules']: if 'grants' in rule...
[ "def", "rules", "(", "self", ")", ":", "list_of_rules", "=", "[", "]", "for", "main_row", "in", "self", ".", "dict_rules", ":", "if", "'rules'", "in", "main_row", ":", "for", "rule_row", "in", "main_row", "[", "'rules'", "]", ":", "if", "'grants'", "in...
49.878049
21.146341
def getClassAllSupers(self, aURI): """ note: requires SPARQL 1.1 2015-06-04: currenlty not used, inferred from above """ aURI = aURI try: qres = self.rdfgraph.query( """SELECT DISTINCT ?x WHERE { ...
[ "def", "getClassAllSupers", "(", "self", ",", "aURI", ")", ":", "aURI", "=", "aURI", "try", ":", "qres", "=", "self", ".", "rdfgraph", ".", "query", "(", "\"\"\"SELECT DISTINCT ?x\n WHERE {\n { <%s> rdfs:subClassOf+ ?x }\n ...
34
14.5
def _handle_tag_defineshape4(self): """Handle the DefineShape4 tag.""" obj = _make_object("DefineShape4") obj.ShapeId = unpack_ui16(self._src) obj.ShapeBounds = self._get_struct_rect() obj.EdgeBounds = self._get_struct_rect() bc = BitConsumer(self._src) bc.u_get(...
[ "def", "_handle_tag_defineshape4", "(", "self", ")", ":", "obj", "=", "_make_object", "(", "\"DefineShape4\"", ")", "obj", ".", "ShapeId", "=", "unpack_ui16", "(", "self", ".", "_src", ")", "obj", ".", "ShapeBounds", "=", "self", ".", "_get_struct_rect", "("...
38.214286
9.642857
def _determine_stream_spread_single(sigomatrixEig, thetasTrack, sigOmega, sigAngle, allinvjacsTrack): """sigAngle input may either be a function that returns the dispersion...
[ "def", "_determine_stream_spread_single", "(", "sigomatrixEig", ",", "thetasTrack", ",", "sigOmega", ",", "sigAngle", ",", "allinvjacsTrack", ")", ":", "#Estimate the spread in all frequencies and angles", "sigObig2", "=", "sigOmega", "(", "thetasTrack", ")", "**", "2.", ...
46.972973
12.837838
def copy_recurse(lib_path, copy_filt_func = None, copied_libs = None): """ Analyze `lib_path` for library dependencies and copy libraries `lib_path` is a directory containing libraries. The libraries might themselves have dependencies. This function analyzes the dependencies and copies library depend...
[ "def", "copy_recurse", "(", "lib_path", ",", "copy_filt_func", "=", "None", ",", "copied_libs", "=", "None", ")", ":", "if", "copied_libs", "is", "None", ":", "copied_libs", "=", "{", "}", "else", ":", "copied_libs", "=", "dict", "(", "copied_libs", ")", ...
42.954545
24.568182
def _generate_cfgnode(self, cfg_job, current_function_addr): """ Generate a CFGNode that starts at `cfg_job.addr`. Since lifting machine code to IRSBs is slow, self._nodes is used as a cache of CFGNodes. If the current architecture is ARM, this method will try to lift the block in the ...
[ "def", "_generate_cfgnode", "(", "self", ",", "cfg_job", ",", "current_function_addr", ")", ":", "addr", "=", "cfg_job", ".", "addr", "try", ":", "if", "addr", "in", "self", ".", "_nodes", ":", "cfg_node", "=", "self", ".", "_nodes", "[", "addr", "]", ...
45.853801
22.684211
def autocompleter(): """Return autocompleter results""" # set blocked engines disabled_engines = request.preferences.engines.get_disabled() # parse query if PY3: raw_text_query = RawTextQuery(request.form.get('q', b''), disabled_engines) else: raw_text_query = RawTextQuery(requ...
[ "def", "autocompleter", "(", ")", ":", "# set blocked engines", "disabled_engines", "=", "request", ".", "preferences", ".", "engines", ".", "get_disabled", "(", ")", "# parse query", "if", "PY3", ":", "raw_text_query", "=", "RawTextQuery", "(", "request", ".", ...
34.816327
22.530612
def ctxtResetPush(self, chunk, size, filename, encoding): """Reset a push parser context """ ret = libxml2mod.xmlCtxtResetPush(self._o, chunk, size, filename, encoding) return ret
[ "def", "ctxtResetPush", "(", "self", ",", "chunk", ",", "size", ",", "filename", ",", "encoding", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCtxtResetPush", "(", "self", ".", "_o", ",", "chunk", ",", "size", ",", "filename", ",", "encoding", ")", "re...
50
20.5
def _getGroundTruth(self, inferenceElement): """ Get the actual value for this field Parameters: ----------------------------------------------------------------------- sensorInputElement: The inference element (part of the inference) that is being used for this me...
[ "def", "_getGroundTruth", "(", "self", ",", "inferenceElement", ")", ":", "sensorInputElement", "=", "InferenceElement", ".", "getInputElement", "(", "inferenceElement", ")", "if", "sensorInputElement", "is", "None", ":", "return", "None", "return", "getattr", "(", ...
40.538462
20.230769
def get_subject(self): """ The assertion must contain a Subject """ assert self.assertion.subject subject = self.assertion.subject subjconf = [] if not self.verify_attesting_entity(subject.subject_confirmation): raise VerificationError("No valid attesting add...
[ "def", "get_subject", "(", "self", ")", ":", "assert", "self", ".", "assertion", ".", "subject", "subject", "=", "self", ".", "assertion", ".", "subject", "subjconf", "=", "[", "]", "if", "not", "self", ".", "verify_attesting_entity", "(", "subject", ".", ...
36.469388
20.163265
def validate_is_not_none(config_val, evar): """ If the value is ``None``, fail validation. :param str config_val: The env var value. :param EnvironmentVariable evar: The EVar object we are validating a value for. :raises: ValueError if the config value is None. """ if config_val is ...
[ "def", "validate_is_not_none", "(", "config_val", ",", "evar", ")", ":", "if", "config_val", "is", "None", ":", "raise", "ValueError", "(", "\"Value for environment variable '{evar_name}' can't \"", "\"be empty.\"", ".", "format", "(", "evar_name", "=", "evar", ".", ...
34.214286
14.357143
def compute_gas_limit_bounds(parent: BlockHeader) -> Tuple[int, int]: """ Compute the boundaries for the block gas limit based on the parent block. """ boundary_range = parent.gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR upper_bound = parent.gas_limit + boundary_range lower_bound = max(GAS_LIMIT_MIN...
[ "def", "compute_gas_limit_bounds", "(", "parent", ":", "BlockHeader", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "boundary_range", "=", "parent", ".", "gas_limit", "//", "GAS_LIMIT_ADJUSTMENT_FACTOR", "upper_bound", "=", "parent", ".", "gas_limit", "+...
48.625
18.125
def defaults(features): """ Returns the default property values for the given features. """ assert is_iterable_typed(features, Feature) # FIXME: should merge feature and property modules. from . import property result = [] for f in features: if not f.free and not f.optional and f.de...
[ "def", "defaults", "(", "features", ")", ":", "assert", "is_iterable_typed", "(", "features", ",", "Feature", ")", "# FIXME: should merge feature and property modules.", "from", ".", "import", "property", "result", "=", "[", "]", "for", "f", "in", "features", ":",...
30.153846
17.846154
def _insert_optional_roles(cursor, model, ident): """Inserts the optional roles if values for the optional roles exist. """ optional_roles = [ # (<metadata-attr>, <db-role-id>,), ('translators', 4,), ('editors', 5,), ] for attr, role_id in optional_roles: roles = ...
[ "def", "_insert_optional_roles", "(", "cursor", ",", "model", ",", "ident", ")", ":", "optional_roles", "=", "[", "# (<metadata-attr>, <db-role-id>,),", "(", "'translators'", ",", "4", ",", ")", ",", "(", "'editors'", ",", "5", ",", ")", ",", "]", "for", "...
34.833333
11.888889
def check_presence_of_mandatory_args(args, mandatory_args): ''' Checks whether all mandatory arguments are passed. This function aims at methods with many arguments which are passed as kwargs so that the order in which the are passed does not matter. :args: The dictionary passed as arg...
[ "def", "check_presence_of_mandatory_args", "(", "args", ",", "mandatory_args", ")", ":", "missing_args", "=", "[", "]", "for", "name", "in", "mandatory_args", ":", "if", "name", "not", "in", "args", ".", "keys", "(", ")", ":", "missing_args", ".", "append", ...
32.916667
18.75
def abs(self): """Apply an absolute value function to all numeric columns. Returns: A new DataFrame with the applied absolute value. """ self._validate_dtypes(numeric_only=True) return self.__constructor__(query_compiler=self._query_compiler.abs())
[ "def", "abs", "(", "self", ")", ":", "self", ".", "_validate_dtypes", "(", "numeric_only", "=", "True", ")", "return", "self", ".", "__constructor__", "(", "query_compiler", "=", "self", ".", "_query_compiler", ".", "abs", "(", ")", ")" ]
37.625
19.375
async def async_set_switch_state( self, switch_number: SwitchNumber, state: bool) -> None: """ Turn a switch on or off. :param switch_number: the switch to be set. :param state: True to turn on, False to turn off. """ await self._protocol.async_execute( ...
[ "async", "def", "async_set_switch_state", "(", "self", ",", "switch_number", ":", "SwitchNumber", ",", "state", ":", "bool", ")", "->", "None", ":", "await", "self", ".", "_protocol", ".", "async_execute", "(", "SetSwitchCommand", "(", "switch_number", ",", "S...
32.846154
15.153846
def remote(ctx): """Display repo github path """ with command(): m = RepoManager(ctx.obj['agile']) click.echo(m.github_repo().repo_path)
[ "def", "remote", "(", "ctx", ")", ":", "with", "command", "(", ")", ":", "m", "=", "RepoManager", "(", "ctx", ".", "obj", "[", "'agile'", "]", ")", "click", ".", "echo", "(", "m", ".", "github_repo", "(", ")", ".", "repo_path", ")" ]
26.5
8.5
def _input_stmt(self, stmt: Statement, sctx: SchemaContext) -> None: """Handle RPC or action input statement.""" self.get_child("input")._handle_substatements(stmt, sctx)
[ "def", "_input_stmt", "(", "self", ",", "stmt", ":", "Statement", ",", "sctx", ":", "SchemaContext", ")", "->", "None", ":", "self", ".", "get_child", "(", "\"input\"", ")", ".", "_handle_substatements", "(", "stmt", ",", "sctx", ")" ]
61.333333
17.666667
def add_query_occurrence(self, report): """Adds a report to the report aggregation""" initial_millis = int(report['parsed']['stats']['millis']) mask = report['queryMask'] existing_report = self._get_existing_report(mask, report) if existing_report is not None: self...
[ "def", "add_query_occurrence", "(", "self", ",", "report", ")", ":", "initial_millis", "=", "int", "(", "report", "[", "'parsed'", "]", "[", "'stats'", "]", "[", "'millis'", "]", ")", "mask", "=", "report", "[", "'queryMask'", "]", "existing_report", "=", ...
43
17.208333
def duplicates(*iterables, **kwargs): """ Yield duplicate items from any number of sorted iterables of items >>> items_a = [1, 2, 3] >>> items_b = [0, 3, 4, 5, 6] >>> list(duplicates(items_a, items_b)) [(3, 3)] It won't behave as you expect if the iterables aren't ordered >>> items_b.append(1) >>> list(dupl...
[ "def", "duplicates", "(", "*", "iterables", ",", "*", "*", "kwargs", ")", ":", "key", "=", "kwargs", ".", "pop", "(", "'key'", ",", "lambda", "x", ":", "x", ")", "assert", "not", "kwargs", "zipped", "=", "more_itertools", ".", "collate", "(", "*", ...
25.714286
22.047619
def squeeze(attrs, inputs, proto_obj): """Remove single-dimensional entries from the shape of a tensor.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes' : 'axis'}) return 'squeeze', new_attrs, inputs
[ "def", "squeeze", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'axes'", ":", "'axis'", "}", ")", "return", "'squeeze'", ",", "new_attrs", ",", "inputs" ]
56.4
11.4
def standard_system_dimensions(num_boards): """Calculate the standard network dimensions (in chips) for a full torus system with the specified number of SpiNN-5 boards. Returns ------- (w, h) Width and height of the network in chips. Standard SpiNNaker systems are constructed as sq...
[ "def", "standard_system_dimensions", "(", "num_boards", ")", ":", "# Special case to avoid division by 0", "if", "num_boards", "==", "0", ":", "return", "(", "0", ",", "0", ")", "# Special case: meaningful systems with 1 board can exist", "if", "num_boards", "==", "1", ...
31.804878
22.707317
def create_affinity_group(kwargs=None, conn=None, call=None): ''' .. versionadded:: 2015.8.0 Create a new affinity group CLI Example: .. code-block:: bash salt-cloud -f create_affinity_group my-azure name=my_affinity_group ''' if call != 'function': raise SaltCloudSystemE...
[ "def", "create_affinity_group", "(", "kwargs", "=", "None", ",", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_affinity_group function must be called with -f or --funct...
28.714286
26.47619
def sevenths(reference_labels, estimated_labels): """Compare chords along MIREX 'sevenths' rules. Chords with qualities outside [maj, maj7, 7, min, min7, N] are ignored. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (est_intervals...
[ "def", "sevenths", "(", "reference_labels", ",", "estimated_labels", ")", ":", "validate", "(", "reference_labels", ",", "estimated_labels", ")", "seventh_qualities", "=", "[", "'maj'", ",", "'min'", ",", "'maj7'", ",", "'7'", ",", "'min7'", ",", "''", "]", ...
40.09434
22.811321
def get_config(ini_path=None, rootdir=None): """ Load configuration from INI. :return Namespace: """ config = Namespace() config.default_section = 'pylama' if not ini_path: path = get_default_config_file(rootdir) if path: config.read(path) else: config....
[ "def", "get_config", "(", "ini_path", "=", "None", ",", "rootdir", "=", "None", ")", ":", "config", "=", "Namespace", "(", ")", "config", ".", "default_section", "=", "'pylama'", "if", "not", "ini_path", ":", "path", "=", "get_default_config_file", "(", "r...
19.823529
19.294118
def makeicons(source): """ Create all the neccessary icons from source image """ im = Image.open(source) for name, (_, w, h, func) in icon_sizes.iteritems(): print('Making icon %s...' % name) tn = func(im, (w, h)) bg = Image.new('RGBA', (w, h), (255, 255, 255)) x = (w...
[ "def", "makeicons", "(", "source", ")", ":", "im", "=", "Image", ".", "open", "(", "source", ")", "for", "name", ",", "(", "_", ",", "w", ",", "h", ",", "func", ")", "in", "icon_sizes", ".", "iteritems", "(", ")", ":", "print", "(", "'Making icon...
31.571429
10.285714
def comm_grid(patch, cols, splits, divs, metric='Sorensen'): """ Calculates commonality as a function of distance for a gridded patch Parameters ---------- {0} divs : str Description of how to divide x_col and y_col. Unlike SAR and EAR, only one division can be given at a time. ...
[ "def", "comm_grid", "(", "patch", ",", "cols", ",", "splits", ",", "divs", ",", "metric", "=", "'Sorensen'", ")", ":", "(", "spp_col", ",", "count_col", ",", "x_col", ",", "y_col", ")", ",", "patch", "=", "_get_cols", "(", "[", "'spp_col'", ",", "'co...
34.986842
24.644737
def v2010(self): """ :returns: Version v2010 of api :rtype: twilio.rest.api.v2010.V2010 """ if self._v2010 is None: self._v2010 = V2010(self) return self._v2010
[ "def", "v2010", "(", "self", ")", ":", "if", "self", ".", "_v2010", "is", "None", ":", "self", ".", "_v2010", "=", "V2010", "(", "self", ")", "return", "self", ".", "_v2010" ]
26.625
6.875
def wait( self, timeout = -1 ): """Wait for all pending results to be finished. If timeout is set, return after this many seconds regardless. :param timeout: timeout period in seconds (defaults to forever) :returns: True if all the results completed""" # we can't use ipyparalle...
[ "def", "wait", "(", "self", ",", "timeout", "=", "-", "1", ")", ":", "# we can't use ipyparallel.Client.wait() for this, because that", "# method only works for cases where the Client object is the one that", "# submitted the jobs to the cluster hub -- and therefore has the", "# necessar...
49.754717
22.509434
def get_inputs(self): """Get all inputs.""" self.request(EP_GET_INPUTS) return {} if self.last_response is None else self.last_response.get('payload').get('devices')
[ "def", "get_inputs", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_INPUTS", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get", "(...
46.5
21.25
def media_download(self, mxcurl, allow_remote=True): """Download raw media from provided mxc URL. Args: mxcurl (str): mxc media URL. allow_remote (bool): indicates to the server that it should not attempt to fetch the media if it is deemed remote. Defaults ...
[ "def", "media_download", "(", "self", ",", "mxcurl", ",", "allow_remote", "=", "True", ")", ":", "query_params", "=", "{", "}", "if", "not", "allow_remote", ":", "query_params", "[", "\"allow_remote\"", "]", "=", "False", "if", "mxcurl", ".", "startswith", ...
35.956522
14.956522
def sample_path(alpha, A, pobs, T=None): """ Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations ) Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. A : ndarra...
[ "def", "sample_path", "(", "alpha", ",", "A", ",", "pobs", ",", "T", "=", "None", ")", ":", "if", "__impl__", "==", "__IMPL_PYTHON__", ":", "return", "ip", ".", "sample_path", "(", "alpha", ",", "A", ",", "pobs", ",", "T", "=", "T", ",", "dtype", ...
36.5
20.769231
def fillDataProducts(self, dps): """Fills listview with existing data products""" item = None for dp in dps: if not dp.ignored: item = self._makeDPItem(self, dp, item) # ensure combobox widgets are made self._itemComboBox(item, self.Col...
[ "def", "fillDataProducts", "(", "self", ",", "dps", ")", ":", "item", "=", "None", "for", "dp", "in", "dps", ":", "if", "not", "dp", ".", "ignored", ":", "item", "=", "self", ".", "_makeDPItem", "(", "self", ",", "dp", ",", "item", ")", "# ensure c...
41.777778
12.666667
def Page_getResourceContent(self, frameId, url): """ Function path: Page.getResourceContent Domain: Page Method name: getResourceContent WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'frameId' (type: FrameId) -> Frame id to get resource for. 'url' (...
[ "def", "Page_getResourceContent", "(", "self", ",", "frameId", ",", "url", ")", ":", "assert", "isinstance", "(", "url", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'url' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "url", ")", "subd...
33.5
20.083333
def merge_likelihood_headers(filenames, outfile): """ Merge header information from likelihood files. Parameters: ----------- filenames : input filenames oufile : the merged file to write Returns: -------- data : the data being written """ filenames = np.atleas...
[ "def", "merge_likelihood_headers", "(", "filenames", ",", "outfile", ")", ":", "filenames", "=", "np", ".", "atleast_1d", "(", "filenames", ")", "ext", "=", "'PIX_DATA'", "nside", "=", "fitsio", ".", "read_header", "(", "filenames", "[", "0", "]", ",", "ex...
26.85
19.25
def getPort(self): """ Helper method for testing; returns the TCP port used for this registration, even if it was specified as 0 and thus allocated by the OS. """ disp = self.pbmanager.dispatchers[self.portstr] return disp.port.getHost().port
[ "def", "getPort", "(", "self", ")", ":", "disp", "=", "self", ".", "pbmanager", ".", "dispatchers", "[", "self", ".", "portstr", "]", "return", "disp", ".", "port", ".", "getHost", "(", ")", ".", "port" ]
36.375
16.625
def get_instance_by_bin_uuid(model, bin_uuid): """Get an instance by binary uuid. :param model: a string, model name in rio.models. :param bin_uuid: a 16-bytes binary string. :return: None or a SQLAlchemy instance. """ try: model = get_model(model) except ImportError: return...
[ "def", "get_instance_by_bin_uuid", "(", "model", ",", "bin_uuid", ")", ":", "try", ":", "model", "=", "get_model", "(", "model", ")", "except", "ImportError", ":", "return", "None", "return", "model", ".", "query", ".", "filter_by", "(", "*", "*", "{", "...
29.307692
16.307692
def get_uris(config): """ returns a tuple of total file size in bytes, and the list of files """ file_names = [] if config.INPUT_DATA is None: sys.stderr.write("you need to provide INPUT_DATA in config\n") sys.exit(1) if isinstance(config.INPUT_DATA, basestring): config.INPUT_DAT...
[ "def", "get_uris", "(", "config", ")", ":", "file_names", "=", "[", "]", "if", "config", ".", "INPUT_DATA", "is", "None", ":", "sys", ".", "stderr", ".", "write", "(", "\"you need to provide INPUT_DATA in config\\n\"", ")", "sys", ".", "exit", "(", "1", ")...
39.882353
14.588235
def get(cls, database, conditions=""): """ Get all data from system.parts table :param database: A database object to fetch data from. :param conditions: WHERE clause conditions. Database condition is added automatically :return: A list of SystemPart objects """ ...
[ "def", "get", "(", "cls", ",", "database", ",", "conditions", "=", "\"\"", ")", ":", "assert", "isinstance", "(", "database", ",", "Database", ")", ",", "\"database must be database.Database class instance\"", "assert", "isinstance", "(", "conditions", ",", "strin...
55.785714
23.357143
def unassign_assessment_taken_from_bank(self, assessment_taken_id, bank_id): """Removes an ``AssessmentTaken`` from a ``Bank``. arg: assessment_taken_id (osid.id.Id): the ``Id`` of the ``AssessmentTaken`` arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank`` raise:...
[ "def", "unassign_assessment_taken_from_bank", "(", "self", ",", "assessment_taken_id", ",", "bank_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinAssignmentSession.unassign_resource_from_bin", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'...
52.136364
23.090909
def coordinate_filter(self, query, mongo_query): """ Adds genomic coordinated-related filters to the query object Args: query(dict): a dictionary of query filters specified by the users mongo_query(dict): the query that is going to be submitted to the database Returns: ...
[ "def", "coordinate_filter", "(", "self", ",", "query", ",", "mongo_query", ")", ":", "LOG", ".", "debug", "(", "'Adding genomic coordinates to the query'", ")", "chromosome", "=", "query", "[", "'chrom'", "]", "mongo_query", "[", "'chromosome'", "]", "=", "chrom...
37.2
24.05
def visit_Rep1N(self, node: parsing.Rep0N) -> [ast.stmt]: """Generates python code for a clause repeated 1 or more times. <code for the clause> while True: <code for the clause> """ clause = self.visit(node.pt) if isinstance(clause, ast.expr): ret...
[ "def", "visit_Rep1N", "(", "self", ",", "node", ":", "parsing", ".", "Rep0N", ")", "->", "[", "ast", ".", "stmt", "]", ":", "clause", "=", "self", ".", "visit", "(", "node", ".", "pt", ")", "if", "isinstance", "(", "clause", ",", "ast", ".", "exp...
38.533333
13.466667