text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def filter_oauth_params(params): """Removes all non oauth parameters from a dict or a list of params.""" is_oauth = lambda kv: kv[0].startswith("oauth_") if isinstance(params, dict): return list(filter(is_oauth, list(params.items()))) else: return list(filter(is_oauth, params))
[ "def", "filter_oauth_params", "(", "params", ")", ":", "is_oauth", "=", "lambda", "kv", ":", "kv", "[", "0", "]", ".", "startswith", "(", "\"oauth_\"", ")", "if", "isinstance", "(", "params", ",", "dict", ")", ":", "return", "list", "(", "filter", "(",...
43.428571
11.857143
def _handle_error(response): """Raise exceptions in response to any http errors Args: response: A Response object Raises: BadRequest: if HTTP error code 400 returned. UnauthorizedAccess: if HTTP error code 401 returned. ForbiddenAccess: if HTTP e...
[ "def", "_handle_error", "(", "response", ")", ":", "code", "=", "response", ".", "status_code", "if", "200", "<=", "code", "<", "400", ":", "return", "if", "code", "==", "400", ":", "sys", ".", "stderr", ".", "write", "(", "response", ".", "text", "+...
38.763636
14.2
def list_joined_groups(self, user_alias=None): """ 已加入的小组列表 :param user_alias: 用户名,默认为当前用户名 :return: 单页列表 """ xml = self.api.xml(API_GROUP_LIST_JOINED_GROUPS % (user_alias or self.api.user_alias)) xml_results = xml.xpath('//div[@class="group-list group-ca...
[ "def", "list_joined_groups", "(", "self", ",", "user_alias", "=", "None", ")", ":", "xml", "=", "self", ".", "api", ".", "xml", "(", "API_GROUP_LIST_JOINED_GROUPS", "%", "(", "user_alias", "or", "self", ".", "api", ".", "user_alias", ")", ")", "xml_results...
39.607143
16.107143
def detect_intent(self, session, query_input, query_params=None, output_audio_config=None, input_audio=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=go...
[ "def", "detect_intent", "(", "self", ",", "session", ",", "query_input", ",", "query_params", "=", "None", ",", "output_audio_config", "=", "None", ",", "input_audio", "=", "None", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method",...
54.282828
29.89899
def make_vcf(data, samples, ipyclient, full=0): """ Write the full VCF for loci passing filtering. Other vcf formats are possible, like SNPs-only, or with filtered loci included but the filter explicitly labeled. These are not yet supported, however. """ ## start vcf progress bar start = tim...
[ "def", "make_vcf", "(", "data", ",", "samples", ",", "ipyclient", ",", "full", "=", "0", ")", ":", "## start vcf progress bar", "start", "=", "time", ".", "time", "(", ")", "printstr", "=", "\" building vcf file | {} | s7 |\"", "LOGGER", ".", "info", "(", ...
38.77
20.25
async def _handle_detailed_info(self, message): """ Updates the current status with the received detailed information: msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo; """ # TODO https://goo.gl/VvpCC6 msg_i...
[ "async", "def", "_handle_detailed_info", "(", "self", ",", "message", ")", ":", "# TODO https://goo.gl/VvpCC6", "msg_id", "=", "message", ".", "obj", ".", "answer_msg_id", "self", ".", "_log", ".", "debug", "(", "'Handling detailed info for message %d'", ",", "msg_i...
40.909091
14.727273
def _pop(self, key, default=None): """ Subclasses may override this method. """ value = default if key in self: value = self[key] del self[key] return value
[ "def", "_pop", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "value", "=", "default", "if", "key", "in", "self", ":", "value", "=", "self", "[", "key", "]", "del", "self", "[", "key", "]", "return", "value" ]
24.444444
10
def _column_resized(self, col, old_width, new_width): """Update the column width.""" self.dataTable.setColumnWidth(col, new_width) self._update_layout()
[ "def", "_column_resized", "(", "self", ",", "col", ",", "old_width", ",", "new_width", ")", ":", "self", ".", "dataTable", ".", "setColumnWidth", "(", "col", ",", "new_width", ")", "self", ".", "_update_layout", "(", ")" ]
44
9.75
def start(self, s): # type: (Optional[Type[Nonterminal]]) -> None """ Set start symbol of the grammar. :param s: Start symbol to set. :raise NonterminalDoesNotExistsException: If the start symbol is not in nonterminals. """ if s is not None and s not in self.nonte...
[ "def", "start", "(", "self", ",", "s", ")", ":", "# type: (Optional[Type[Nonterminal]]) -> None", "if", "s", "is", "not", "None", "and", "s", "not", "in", "self", ".", "nonterminals", ":", "raise", "NonterminalDoesNotExistsException", "(", "None", ",", "s", ",...
41.7
14.1
def setup(app): """Map methods to states of the documentation build.""" app.connect("builder-inited", build_configuration_parameters) app.connect("autodoc-skip-member", skip_slots) app.add_stylesheet("css/custom.css")
[ "def", "setup", "(", "app", ")", ":", "app", ".", "connect", "(", "\"builder-inited\"", ",", "build_configuration_parameters", ")", "app", ".", "connect", "(", "\"autodoc-skip-member\"", ",", "skip_slots", ")", "app", ".", "add_stylesheet", "(", "\"css/custom.css\...
45.8
12
def is_trivial_worker(self, state): """ If it's not an assistant having only tasks that are without requirements. We have to pass the state parameter for optimization reasons. """ if self.assistant: return False return all(not task.resources for task ...
[ "def", "is_trivial_worker", "(", "self", ",", "state", ")", ":", "if", "self", ".", "assistant", ":", "return", "False", "return", "all", "(", "not", "task", ".", "resources", "for", "task", "in", "self", ".", "get_tasks", "(", "state", ",", "PENDING", ...
34.5
19.1
def _respond(self, resp): """Respond to the person waiting""" response_queue = self._response_queues.get(timeout=0.1) response_queue.put(resp) self._completed_response_lines = [] self._is_multiline = None
[ "def", "_respond", "(", "self", ",", "resp", ")", ":", "response_queue", "=", "self", ".", "_response_queues", ".", "get", "(", "timeout", "=", "0.1", ")", "response_queue", ".", "put", "(", "resp", ")", "self", ".", "_completed_response_lines", "=", "[", ...
39.833333
9.333333
def add(self, obj): """ Add an instance of :class:`Component <hl7apy.core.Component>` to the list of children :param obj: an instance of :class:`Component <hl7apy.core.Component>` >>> f = Field('PID_5') >>> f.xpn_1 = 'EVERYMAN' >>> c = Component('XPN_2') >>> c.v...
[ "def", "add", "(", "self", ",", "obj", ")", ":", "# base datatype components can't have more than one child", "if", "self", ".", "name", "and", "is_base_datatype", "(", "self", ".", "datatype", ",", "self", ".", "version", ")", "and", "len", "(", "self", ".", ...
34
19.6
def add_curves_from_lasio(self, l, remap=None, funcs=None): """ Given a LAS file, add curves from it to the current well instance. Essentially just wraps ``add_curves_from_lasio()``. Args: fname (str): The path of the LAS file to read curves from. remap (dict): O...
[ "def", "add_curves_from_lasio", "(", "self", ",", "l", ",", "remap", "=", "None", ",", "funcs", "=", "None", ")", ":", "params", "=", "{", "}", "for", "field", ",", "(", "sect", ",", "code", ")", "in", "LAS_FIELDS", "[", "'data'", "]", ".", "items"...
38.310345
21.827586
def download_file_powershell(url, target, headers={}): """ Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. """ target = os.path.abspath(target) powershell_cmd = "$request = (new-object System.Net.WebClient);" ...
[ "def", "download_file_powershell", "(", "url", ",", "target", ",", "headers", "=", "{", "}", ")", ":", "target", "=", "os", ".", "path", ".", "abspath", "(", "target", ")", "powershell_cmd", "=", "\"$request = (new-object System.Net.WebClient);\"", "for", "k", ...
31.157895
22.421053
async def inject_request_id(app, handler): """aiohttp middleware: ensures each request has a unique request ID. See: ``inject_request_id``. """ async def trace_request(request): request['x-request-id'] = \ request.headers.get('x-request-id') or str(uuid.uuid4()) return awai...
[ "async", "def", "inject_request_id", "(", "app", ",", "handler", ")", ":", "async", "def", "trace_request", "(", "request", ")", ":", "request", "[", "'x-request-id'", "]", "=", "request", ".", "headers", ".", "get", "(", "'x-request-id'", ")", "or", "str"...
29.416667
15.5
def splitpasswd(user): '''urllib.splitpasswd(), but six's support of this is missing''' _passwdprog = re.compile('^([^:]*):(.*)$', re.S) match = _passwdprog.match(user) if match: return match.group(1, 2) return user, None
[ "def", "splitpasswd", "(", "user", ")", ":", "_passwdprog", "=", "re", ".", "compile", "(", "'^([^:]*):(.*)$'", ",", "re", ".", "S", ")", "match", "=", "_passwdprog", ".", "match", "(", "user", ")", "if", "match", ":", "return", "match", ".", "group", ...
34.714286
16.714286
def find_quality(positions): """ Find a quality consists of positions :param list[int] positions: note positions :rtype: str|None """ for q, p in QUALITY_DICT.items(): if positions == list(p): return q return None
[ "def", "find_quality", "(", "positions", ")", ":", "for", "q", ",", "p", "in", "QUALITY_DICT", ".", "items", "(", ")", ":", "if", "positions", "==", "list", "(", "p", ")", ":", "return", "q", "return", "None" ]
24.9
13.4
def get_remote(self, key, default=None, scope=None): """ Get data from the remote end(s) of the :class:`Conversation` with the given scope. In Python, this is equivalent to:: relation.conversation(scope).get_remote(key, default) See :meth:`conversation` and :meth:`Conversa...
[ "def", "get_remote", "(", "self", ",", "key", ",", "default", "=", "None", ",", "scope", "=", "None", ")", ":", "return", "self", ".", "conversation", "(", "scope", ")", ".", "get_remote", "(", "key", ",", "default", ")" ]
36.727273
23.818182
def seed_non_shared_migrate(disks, force=False): ''' Non shared migration requires that the disks be present on the migration destination, pass the disks information via this function, to the migration destination before executing the migration. :param disks: the list of disk data as provided by vi...
[ "def", "seed_non_shared_migrate", "(", "disks", ",", "force", "=", "False", ")", ":", "for", "_", ",", "data", "in", "six", ".", "iteritems", "(", "disks", ")", ":", "fn_", "=", "data", "[", "'file'", "]", "form", "=", "data", "[", "'file format'", "...
43.157895
21.789474
def p_generate_named_block(self, p): 'generate_block : BEGIN COLON ID generate_items END' p[0] = Block(p[4], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_generate_named_block", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Block", "(", "p", "[", "4", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "...
46
10
def REVSH(self, params): """ REVSH Reverse the byte order in the lower half word in Rb and store the result in Ra. If the result of the result is signed, then sign extend """ Ra, Rb = self.get_two_parameters(r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*', params) ...
[ "def", "REVSH", "(", "self", ",", "params", ")", ":", "Ra", ",", "Rb", "=", "self", ".", "get_two_parameters", "(", "r'\\s*([^\\s,]*),\\s*([^\\s,]*)(,\\s*[^\\s,]*)*\\s*'", ",", "params", ")", "self", ".", "check_arguments", "(", "low_registers", "=", "(", "Ra", ...
35.777778
24.888889
def move_directory(self, relativePath, relativeDestination, replace=False, verbose=True): """ Move a directory in the repository from one place to another. It insures moving all the files and subdirectories in the system. :Parameters: #. relativePath (string): The relative t...
[ "def", "move_directory", "(", "self", ",", "relativePath", ",", "relativeDestination", ",", "replace", "=", "False", ",", "verbose", "=", "True", ")", ":", "# normalize path", "relativePath", "=", "os", ".", "path", ".", "normpath", "(", "relativePath", ")", ...
53.666667
26.111111
def _find_folders(self, folder_name): """Return a list of sub-directories.""" found_folders = [] for app_config in apps.get_app_configs(): folder_path = os.path.join(app_config.path, folder_name) if os.path.isdir(folder_path): found_folders.append(folder_p...
[ "def", "_find_folders", "(", "self", ",", "folder_name", ")", ":", "found_folders", "=", "[", "]", "for", "app_config", "in", "apps", ".", "get_app_configs", "(", ")", ":", "folder_path", "=", "os", ".", "path", ".", "join", "(", "app_config", ".", "path...
43.25
9.625
def email_users(users, subject, text_body, html_body=None, sender=None, configuration=None, **kwargs): # type: (List['User'], str, str, Optional[str], Optional[str], Optional[Configuration], Any) -> None """Email a list of users Args: users (List[User]): List of users su...
[ "def", "email_users", "(", "users", ",", "subject", ",", "text_body", ",", "html_body", "=", "None", ",", "sender", "=", "None", ",", "configuration", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (List['User'], str, str, Optional[str], Optional[str], O...
47.076923
25.192308
def resend_email_changed_message(self, user, base_url): """ Regenerate email confirmation link and resend message """ user.require_email_confirmation() self.save(user) self.send_email_changed_message(user, base_url)
[ "def", "resend_email_changed_message", "(", "self", ",", "user", ",", "base_url", ")", ":", "user", ".", "require_email_confirmation", "(", ")", "self", ".", "save", "(", "user", ")", "self", ".", "send_email_changed_message", "(", "user", ",", "base_url", ")"...
48.6
9.6
def text_list_to_colors_simple(names): ''' Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors. ''' uNames = list(set(names)) uNames.sort() textToColor = [ uNames.index(n) for n in names ] textToColor = np.array(textToColor) textTo...
[ "def", "text_list_to_colors_simple", "(", "names", ")", ":", "uNames", "=", "list", "(", "set", "(", "names", ")", ")", "uNames", ".", "sort", "(", ")", "textToColor", "=", "[", "uNames", ".", "index", "(", "n", ")", "for", "n", "in", "names", "]", ...
40.230769
20.538462
def _dict_native_ok(d): """ This checks if a dictionary can be saved natively as HDF5 groups. If it can't, it will be pickled. """ if len(d) >= 256: return False # All keys must be strings for k in d: if not isinstance(k, six.string_types): return False ret...
[ "def", "_dict_native_ok", "(", "d", ")", ":", "if", "len", "(", "d", ")", ">=", "256", ":", "return", "False", "# All keys must be strings", "for", "k", "in", "d", ":", "if", "not", "isinstance", "(", "k", ",", "six", ".", "string_types", ")", ":", "...
20.933333
19.466667
def parse_xml_jtl(self, granularity): """ Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics :param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second' :return: status...
[ "def", "parse_xml_jtl", "(", "self", ",", "granularity", ")", ":", "data", "=", "defaultdict", "(", "list", ")", "processed_data", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "list", ")", ")", ")", "for", ...
53.918919
26.297297
def close(self): """ Close the client connection. Raises: Exception: if an error occurs while trying to close the connection """ if not self._is_open: return else: try: self.proxy.close() self._is_open =...
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "_is_open", ":", "return", "else", ":", "try", ":", "self", ".", "proxy", ".", "close", "(", ")", "self", ".", "_is_open", "=", "False", "except", "Exception", "as", "e", ":", "self",...
27.875
17.875
def set_infra_led_config(self, mode, callback=None): ''' Set Infrared LED configuration cmd: setInfraLedConfig mode(0,1): 0=Auto mode, 1=Manual mode ''' params = {'mode': mode} return self.execute_command('setInfraLedConfig', params, callback=callback)
[ "def", "set_infra_led_config", "(", "self", ",", "mode", ",", "callback", "=", "None", ")", ":", "params", "=", "{", "'mode'", ":", "mode", "}", "return", "self", ".", "execute_command", "(", "'setInfraLedConfig'", ",", "params", ",", "callback", "=", "cal...
37.625
17.375
def retrieve(cls, *args, **kwargs): """Return parent method.""" return super(Card, cls).retrieve(*args, **kwargs)
[ "def", "retrieve", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "Card", ",", "cls", ")", ".", "retrieve", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
42.333333
7.333333
def is_user_accepted_by_access_control(self, user_info): """ Returns True if the user is allowed by the ACL """ if self.get_access_control_method() is None: return True elif not user_info: return False elif self.get_access_control_method() == "username": ...
[ "def", "is_user_accepted_by_access_control", "(", "self", ",", "user_info", ")", ":", "if", "self", ".", "get_access_control_method", "(", ")", "is", "None", ":", "return", "True", "elif", "not", "user_info", ":", "return", "False", "elif", "self", ".", "get_a...
52.846154
21.307692
def add(self, target, args=None, kwargs=None, **options): """Add an Async job to this context. Like Context.add(): creates an Async and adds it to our list of tasks. but also calls _auto_insert_check() to add tasks to queues automatically. """ # In superclass, add new t...
[ "def", "add", "(", "self", ",", "target", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "*", "*", "options", ")", ":", "# In superclass, add new task to our list of tasks", "target", "=", "super", "(", "AutoContext", ",", "self", ")", ".", "ad...
32
23.133333
def substitute_harmonic(progression, substitute_index, ignore_suffix=False): """Do simple harmonic substitutions. Return a list of possible substitions for progression[substitute_index]. If ignore_suffix is set to True the suffix of the chord being substituted will be ignored. Otherwise only progressio...
[ "def", "substitute_harmonic", "(", "progression", ",", "substitute_index", ",", "ignore_suffix", "=", "False", ")", ":", "simple_substitutions", "=", "[", "(", "'I'", ",", "'III'", ")", ",", "(", "'I'", ",", "'VI'", ")", ",", "(", "'IV'", ",", "'II'", ")...
38.964286
18.642857
def protocol_version_to_kmip_version(value): """ Convert a ProtocolVersion struct to its KMIPVersion enumeration equivalent. Args: value (ProtocolVersion): A ProtocolVersion struct to be converted into a KMIPVersion enumeration. Returns: KMIPVersion: The enumeration equival...
[ "def", "protocol_version_to_kmip_version", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "ProtocolVersion", ")", ":", "return", "None", "if", "value", ".", "major", "==", "1", ":", "if", "value", ".", "minor", "==", "0", ":", "ret...
31.633333
18.233333
def dfs(self): ''' Depth-first search generator. Yields `(node, parent)` for every node in the tree, beginning with `(self.root, None)`. ''' yield (self.root, None) todo = [(self.root[char], self.root) for char in self.root] while todo: current, paren...
[ "def", "dfs", "(", "self", ")", ":", "yield", "(", "self", ".", "root", ",", "None", ")", "todo", "=", "[", "(", "self", ".", "root", "[", "char", "]", ",", "self", ".", "root", ")", "for", "char", "in", "self", ".", "root", "]", "while", "to...
37.166667
18.333333
def run(self): """Start the FTP Server for pulsar search.""" self._log.info('Starting Pulsar Search Interface') # Instantiate a dummy authorizer for managing 'virtual' users authorizer = DummyAuthorizer() # Define a new user having full r/w permissions and a read-only # ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_log", ".", "info", "(", "'Starting Pulsar Search Interface'", ")", "# Instantiate a dummy authorizer for managing 'virtual' users", "authorizer", "=", "DummyAuthorizer", "(", ")", "# Define a new user having full r/w permiss...
37.9375
18.90625
def binarize(x, values, threshold=None, included_in='upper'): """Binarizes the values of x. Parameters ---------- values : tuple of two floats The lower and upper value to which the inputs are mapped. threshold : float The threshold; defaults to (values[0] + values[1]) / 2 if None. ...
[ "def", "binarize", "(", "x", ",", "values", ",", "threshold", "=", "None", ",", "included_in", "=", "'upper'", ")", ":", "lower", ",", "upper", "=", "values", "if", "threshold", "is", "None", ":", "threshold", "=", "(", "lower", "+", "upper", ")", "/...
28.034483
19.482759
def update_customer_group_by_id(cls, customer_group_id, customer_group, **kwargs): """Update CustomerGroup Update attributes of CustomerGroup This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.up...
[ "def", "update_customer_group_by_id", "(", "cls", ",", "customer_group_id", ",", "customer_group", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", ...
49.818182
26.545455
def copy_to_tmp(source): """ Copies ``source`` to a temporary directory, and returns the copied location. If source is a file, the copied location is also a file. """ tmp_dir = tempfile.mkdtemp() # Use pathlib because os.path.basename is different depending on whether # the path ends in...
[ "def", "copy_to_tmp", "(", "source", ")", ":", "tmp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "# Use pathlib because os.path.basename is different depending on whether", "# the path ends in a /", "p", "=", "pathlib", ".", "Path", "(", "source", ")", "dirname", ...
30.555556
15.777778
def multivariate_normal(x, mu, L): """ Computes the log-density of a multivariate normal. :param x : Dx1 or DxN sample(s) for which we want the density :param mu : Dx1 or DxN mean(s) of the normal distribution :param L : DxD Cholesky decomposition of the covariance matrix :return p : (1,) or (...
[ "def", "multivariate_normal", "(", "x", ",", "mu", ",", "L", ")", ":", "mu_ndims", "=", "mu", ".", "shape", ".", "ndims", "x_ndims", "=", "x", ".", "shape", ".", "ndims", "if", "x_ndims", "is", "not", "None", "and", "x_ndims", "!=", "2", ":", "rais...
43.344828
18.172414
def groupby(iterable, key=None): """ Group items from iterable by key and return a dictionary where values are the lists of items from the iterable having the same key. :param key: function to apply to each element of the iterable. If not specified or is None key defaults to identity function and...
[ "def", "groupby", "(", "iterable", ",", "key", "=", "None", ")", ":", "groups", "=", "{", "}", "for", "item", "in", "iterable", ":", "if", "key", "is", "None", ":", "key_value", "=", "item", "else", ":", "key_value", "=", "key", "(", "item", ")", ...
31.666667
18.809524
def _create_intermediate_target(self, address, suffix): """ :param string address: A target address. :param string suffix: A string used as a suffix of the intermediate target name. :returns: The address of a synthetic intermediary target. """ if not isinstance(address, string_types): rais...
[ "def", "_create_intermediate_target", "(", "self", ",", "address", ",", "suffix", ")", ":", "if", "not", "isinstance", "(", "address", ",", "string_types", ")", ":", "raise", "self", ".", "ExpectedAddressError", "(", "\"Expected string address argument, got type {type...
40.166667
23.7
def get_completion_args(self, is_completion=False, comp_line=None): # pylint: disable=no-self-use """ Get the args that will be used to tab completion if completion is active. """ is_completion = is_completion or os.environ.get(ARGCOMPLETE_ENV_NAME) comp_line = comp_line or os.environ.get('COMP...
[ "def", "get_completion_args", "(", "self", ",", "is_completion", "=", "False", ",", "comp_line", "=", "None", ")", ":", "# pylint: disable=no-self-use", "is_completion", "=", "is_completion", "or", "os", ".", "environ", ".", "get", "(", "ARGCOMPLETE_ENV_NAME", ")"...
76.166667
28
def cur_iter_done(self): """Checks if all iterations have completed. TODO(rliaw): also check that `t.iterations == self._r`""" return all( self._get_result_time(result) >= self._cumul_r for result in self._live_trials.values())
[ "def", "cur_iter_done", "(", "self", ")", ":", "return", "all", "(", "self", ".", "_get_result_time", "(", "result", ")", ">=", "self", ".", "_cumul_r", "for", "result", "in", "self", ".", "_live_trials", ".", "values", "(", ")", ")" ]
38.571429
15.428571
def do_get_pages_with_tag(parser, token): """ Return Pages with given tag Syntax:: {% get_pages_with_tag <tag name> as <varname> %} Example use: {% get_pages_with_tag "footer" as pages %} """ bits = token.split_contents() if 4 != len(bits): raise TemplateSyntaxErro...
[ "def", "do_get_pages_with_tag", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "4", "!=", "len", "(", "bits", ")", ":", "raise", "TemplateSyntaxError", "(", "'%r expects 2 arguments'", "%", "bits", "[", ...
28.47619
16.761905
def get_config(config, default_config): '''Load configuration from file if in config, else use default''' if not config: logging.warning('Using default config: %s', default_config) config = default_config try: with open(config, 'r') as config_file: return yaml.load(confi...
[ "def", "get_config", "(", "config", ",", "default_config", ")", ":", "if", "not", "config", ":", "logging", ".", "warning", "(", "'Using default config: %s'", ",", "default_config", ")", "config", "=", "default_config", "try", ":", "with", "open", "(", "config...
38.230769
15.461538
def disable_attribute_or_dryrun(*args, **kwargs): """ Comments-out a line containing an attribute. The inverse of enable_attribute_or_dryrun(). """ dryrun = get_dryrun(kwargs.get('dryrun')) if 'dryrun' in kwargs: del kwargs['dryrun'] use_sudo = kwargs.pop('use_sudo', False) run...
[ "def", "disable_attribute_or_dryrun", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "dryrun", "=", "get_dryrun", "(", "kwargs", ".", "get", "(", "'dryrun'", ")", ")", "if", "'dryrun'", "in", "kwargs", ":", "del", "kwargs", "[", "'dryrun'", "]", ...
35.807692
25.5
def new_port(): """Find a free local port and allocate it""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) for i in range(12042, 16042): try: s.bind(('127.0.0.1', i)) s.close() return i except socket.error: pass ...
[ "def", "new_port", "(", ")", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ",", "socket", ".", "IPPROTO_TCP", ")", "for", "i", "in", "range", "(", "12042", ",", "16042", ")", ":", "try", "...
32
16.545455
def producer(cfg_uri, queue, logger=None): """ 分布式爬虫的任务端(将任务加入Queue) 注意: 被包装的函数需要返回一个可迭代的对象 :param cfg_uri: 读取任务的路径 :param queue: Queue的名字 :param logger: 日志记录工具 """ _info, _exception = _deal_logger(logger) cfg_uri = _deal_uri(cfg_uri) def decorator(function): @...
[ "def", "producer", "(", "cfg_uri", ",", "queue", ",", "logger", "=", "None", ")", ":", "_info", ",", "_exception", "=", "_deal_logger", "(", "logger", ")", "cfg_uri", "=", "_deal_uri", "(", "cfg_uri", ")", "def", "decorator", "(", "function", ")", ":", ...
31.235294
14.647059
def on_mouse_wheel(self, event): """Zoom with the mouse wheel.""" # NOTE: not called on OS X because of touchpad if event.modifiers: return dx = np.sign(event.delta[1]) * self._wheel_coeff # Zoom toward the mouse pointer. x0, y0 = self._normalize(event.pos) ...
[ "def", "on_mouse_wheel", "(", "self", ",", "event", ")", ":", "# NOTE: not called on OS X because of touchpad", "if", "event", ".", "modifiers", ":", "return", "dx", "=", "np", ".", "sign", "(", "event", ".", "delta", "[", "1", "]", ")", "*", "self", ".", ...
39.222222
8.777778
def _get_errors(self): """ Gets errors from HTTP response """ errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
[ "def", "_get_errors", "(", "self", ")", ":", "errors", "=", "self", ".", "json", ".", "get", "(", "'data'", ")", ".", "get", "(", "'failures'", ")", "if", "errors", ":", "logger", ".", "error", "(", "errors", ")", "return", "errors" ]
25.875
10.375
def _parse_message(self, data): """ Parses the raw message from the device. :param data: message data :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError` """ try: _, values = data.split(':') self.serial_number, ...
[ "def", "_parse_message", "(", "self", ",", "data", ")", ":", "try", ":", "_", ",", "values", "=", "data", ".", "split", "(", "':'", ")", "self", ".", "serial_number", ",", "self", ".", "value", "=", "values", ".", "split", "(", "','", ")", "self", ...
31.851852
15.851852
def execute(self, write_concern=None): """Execute all provided operations. :Parameters: - write_concern (optional): the write concern for this bulk execution. """ if write_concern is not None: validate_is_mapping("write_concern", write_concern) ...
[ "def", "execute", "(", "self", ",", "write_concern", "=", "None", ")", ":", "if", "write_concern", "is", "not", "None", ":", "validate_is_mapping", "(", "\"write_concern\"", ",", "write_concern", ")", "return", "self", ".", "__bulk", ".", "execute", "(", "wr...
35.2
14.4
def set_entry(key, value): """ Set a configuration entry :param key: key name :param value: value for this key :raises KeyError: if key is not str """ if type(key) != str: raise KeyError('key must be str') _config[key] = value
[ "def", "set_entry", "(", "key", ",", "value", ")", ":", "if", "type", "(", "key", ")", "!=", "str", ":", "raise", "KeyError", "(", "'key must be str'", ")", "_config", "[", "key", "]", "=", "value" ]
23.363636
10.818182
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c): """ finds spike containers in multi spike containers collection offspring """ if 'parent' in self.meta: return (self.meta['parent'],self.meta['parent'].find(cell_designation,cell_filter=cell...
[ "def", "find", "(", "self", ",", "cell_designation", ",", "cell_filter", "=", "lambda", "x", ",", "c", ":", "'c'", "in", "x", "and", "x", "[", "'c'", "]", "==", "c", ")", ":", "if", "'parent'", "in", "self", ".", "meta", ":", "return", "(", "self...
54
26
def _count_localizations(df): """ count the most likely localization for each depentent peptide. :param df: allPeptides.txt table. """ grp = df.groupby(_index_columns) counts = grp['DP AA'].apply(lambda x: count(x.str.split(';').values)) counts.index = counts.index.set_names('DP AA', level=4) ...
[ "def", "_count_localizations", "(", "df", ")", ":", "grp", "=", "df", ".", "groupby", "(", "_index_columns", ")", "counts", "=", "grp", "[", "'DP AA'", "]", ".", "apply", "(", "lambda", "x", ":", "count", "(", "x", ".", "str", ".", "split", "(", "'...
46.9
15
def write_items(self, calendar): """ Write all events to the calendar """ for item in self.items: event = Event() for ifield, efield in ITEM_EVENT_FIELD_MAP: val = item.get(ifield) if val is not None: event.add(e...
[ "def", "write_items", "(", "self", ",", "calendar", ")", ":", "for", "item", "in", "self", ".", "items", ":", "event", "=", "Event", "(", ")", "for", "ifield", ",", "efield", "in", "ITEM_EVENT_FIELD_MAP", ":", "val", "=", "item", ".", "get", "(", "if...
33
5
def camel_case(string): """ Converts a string to camel case. For example:: camel_case('one_two_three') -> 'oneTwoThree' """ if not string: return string parts = snake_case(string).split('_') rv = '' while parts: part = parts.pop(0) rv += part or '_' i...
[ "def", "camel_case", "(", "string", ")", ":", "if", "not", "string", ":", "return", "string", "parts", "=", "snake_case", "(", "string", ")", ".", "split", "(", "'_'", ")", "rv", "=", "''", "while", "parts", ":", "part", "=", "parts", ".", "pop", "...
23.75
16.125
def current_length(self): # type: () -> int ''' Calculate the current length of this symlink record. Parameters: None. Returns: Length of this symlink record. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalError(...
[ "def", "current_length", "(", "self", ")", ":", "# type: () -> int", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'SL record not yet initialized!'", ")", "strlist", "=", "[", "]", "for", "comp", "in...
27
21.222222
def tac(label=''): """@brief This function prints in the screen the difference between the time saved with function tic.py and current time. @param label String: if something is desired to print (default = ''). @see also tic() """ global _tic delta_t = time.time() - _tic if label !=...
[ "def", "tac", "(", "label", "=", "''", ")", ":", "global", "_tic", "delta_t", "=", "time", ".", "time", "(", ")", "-", "_tic", "if", "label", "!=", "''", ":", "print", "(", "'%s - %3.4f s'", "%", "(", "label", ",", "delta_t", ")", ")", "else", ":...
23.647059
23.058824
def compute(cls, observation, prediction): """Compute a Cohen's D from an observation and a prediction.""" assert isinstance(observation, dict) assert isinstance(prediction, dict) p_mean = prediction['mean'] # Use the prediction's mean. p_std = prediction['std'] o_mean =...
[ "def", "compute", "(", "cls", ",", "observation", ",", "prediction", ")", ":", "assert", "isinstance", "(", "observation", ",", "dict", ")", "assert", "isinstance", "(", "prediction", ",", "dict", ")", "p_mean", "=", "prediction", "[", "'mean'", "]", "# Us...
46.705882
9.823529
def clear(self): """ Clears the display and resets the cursor position to ``(0, 0)``. """ self._cx, self._cy = (0, 0) self._canvas.rectangle(self._device.bounding_box, fill=self.default_bgcolor) self.flush()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_cx", ",", "self", ".", "_cy", "=", "(", "0", ",", "0", ")", "self", ".", "_canvas", ".", "rectangle", "(", "self", ".", "_device", ".", "bounding_box", ",", "fill", "=", "self", ".", "default_...
34.875
14.375
def context(self): """Device context of the array. Examples -------- >>> x = mx.nd.array([1, 2, 3, 4]) >>> x.context cpu(0) >>> type(x.context) <class 'mxnet.context.Context'> >>> y = mx.nd.zeros((2,3), mx.gpu(0)) >>> y.context gpu...
[ "def", "context", "(", "self", ")", ":", "dev_typeid", "=", "ctypes", ".", "c_int", "(", ")", "dev_id", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXNDArrayGetContext", "(", "self", ".", "handle", ",", "ctypes", ".", "byref...
30.526316
16.105263
def purcell(target, r_toroid, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', diameter='throat.diameter'): r""" Computes the throat capillary entry pressure assuming the throat is a toroid. Parameters ---------- target : OpenPNM Object ...
[ "def", "purcell", "(", "target", ",", "r_toroid", ",", "surface_tension", "=", "'pore.surface_tension'", ",", "contact_angle", "=", "'pore.contact_angle'", ",", "diameter", "=", "'throat.diameter'", ")", ":", "network", "=", "target", ".", "project", ".", "network...
40.348485
23.666667
def visualize(self, filename="mydask", format=None, **kwargs): """Render the task graph for this parameter search using ``graphviz``. Requires ``graphviz`` to be installed. Parameters ---------- filename : str or None, optional The name (without an extension) of the...
[ "def", "visualize", "(", "self", ",", "filename", "=", "\"mydask\"", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "check_is_fitted", "(", "self", ",", "\"dask_graph_\"", ")", "return", "dask", ".", "visualize", "(", "self", ".", "dask_g...
39.230769
20.730769
def pick_coda_from_decimal(decimal): """Picks only a coda from a decimal.""" decimal = Decimal(decimal) __, digits, exp = decimal.as_tuple() if exp < 0: return DIGIT_CODAS[digits[-1]] __, digits, exp = decimal.normalize().as_tuple() index = bisect_right(EXP_INDICES, exp) - 1 if index...
[ "def", "pick_coda_from_decimal", "(", "decimal", ")", ":", "decimal", "=", "Decimal", "(", "decimal", ")", "__", ",", "digits", ",", "exp", "=", "decimal", ".", "as_tuple", "(", ")", "if", "exp", "<", "0", ":", "return", "DIGIT_CODAS", "[", "digits", "...
34
9.916667
def load(self, cls, run_id): """ Load a workflow cls - workflow class (to get __name__ from) run_id - id given to the specific run """ id_code = self.generate_load_identifier(cls, run_id) inst = self.store.load(id_code) return inst
[ "def", "load", "(", "self", ",", "cls", ",", "run_id", ")", ":", "id_code", "=", "self", ".", "generate_load_identifier", "(", "cls", ",", "run_id", ")", "inst", "=", "self", ".", "store", ".", "load", "(", "id_code", ")", "return", "inst" ]
31.888889
9.666667
def draw_uppercase_key(self, surface, key): """Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'\u21e7' if key.is_activated(): key.v...
[ "def", "draw_uppercase_key", "(", "self", ",", "surface", ",", "key", ")", ":", "key", ".", "value", "=", "u'\\u21e7'", "if", "key", ".", "is_activated", "(", ")", ":", "key", ".", "value", "=", "u'\\u21ea'", "self", ".", "draw_character_key", "(", "surf...
37.9
10.6
def delete_project(self, pid): """Delete project from Jira. :param pid: JIRA projectID or Project or slug :type pid: str :return: True if project was deleted :rtype: bool :raises JIRAError: If project not found or not enough permissions :raises ValueError: If pi...
[ "def", "delete_project", "(", "self", ",", "pid", ")", ":", "# allows us to call it with Project objects", "if", "hasattr", "(", "pid", ",", "'id'", ")", ":", "pid", "=", "pid", ".", "id", "# Check if pid is a number - then we assume that it is", "# projectID", "try",...
35.717391
17.652174
def convert2(self, imtls, sids): """ Convert a probability map into a composite array of shape (N,) and dtype `imtls.dt`. :param imtls: DictArray instance :param sids: the IDs of the sites we are interested in :returns: an array of cur...
[ "def", "convert2", "(", "self", ",", "imtls", ",", "sids", ")", ":", "assert", "self", ".", "shape_z", "==", "1", ",", "self", ".", "shape_z", "curves", "=", "numpy", ".", "zeros", "(", "len", "(", "sids", ")", ",", "imtls", ".", "dt", ")", "for"...
33.666667
12.916667
def find_emails_by_subject(self, subject, limit=50, match_recipient=None): """ Searches for Email by Subject. Returns email's imap message IDs as a list if matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - L...
[ "def", "find_emails_by_subject", "(", "self", ",", "subject", ",", "limit", "=", "50", ",", "match_recipient", "=", "None", ")", ":", "# Select inbox to fetch the latest mail on server.", "self", ".", "_mail", ".", "select", "(", "\"inbox\"", ")", "matching_uids", ...
32.565217
24.391304
def on_cluster_update(self, name, new_config): """ Callback hook for when a cluster is updated. Or main concern when a cluster is updated is whether or not the associated discovery method changed. If it did, we make sure that the old discovery method stops watching for the clus...
[ "def", "on_cluster_update", "(", "self", ",", "name", ",", "new_config", ")", ":", "cluster", "=", "self", ".", "configurables", "[", "Cluster", "]", "[", "name", "]", "old_discovery", "=", "cluster", ".", "discovery", "new_discovery", "=", "new_config", "["...
37.613636
21.204545
def inject_positional_args(self, method): """Decorator for injecting positional arguments from the configuration. This decorator wraps the given method, so that any positional arguments are passed with corresponding values from the configuration. The name of the positional argument must match the conf...
[ "def", "inject_positional_args", "(", "self", ",", "method", ")", ":", "inspect", "=", "self", ".", "_modules", "[", "'inspect'", "]", "argspec", "=", "inspect", ".", "getargspec", "(", "method", ")", "# Index in argspec.args of the first keyword argument. This index...
45.465753
23.849315
def is_unitary(self, atol=None, rtol=None): """Return True if QuantumChannel is a unitary channel.""" try: op = self.to_operator() return op.is_unitary(atol=atol, rtol=rtol) except QiskitError: return False
[ "def", "is_unitary", "(", "self", ",", "atol", "=", "None", ",", "rtol", "=", "None", ")", ":", "try", ":", "op", "=", "self", ".", "to_operator", "(", ")", "return", "op", ".", "is_unitary", "(", "atol", "=", "atol", ",", "rtol", "=", "rtol", ")...
37.142857
11.285714
def _add_gene_associations(self, r_id, r_genes, gene_ids, r_tag): """Adds all the different kinds of genes into a list.""" genes = ET.SubElement( r_tag, _tag('geneProductAssociation', FBC_V2)) if isinstance(r_genes, list): e = Expression(And(*(Variable(i) for i in r_genes...
[ "def", "_add_gene_associations", "(", "self", ",", "r_id", ",", "r_genes", ",", "gene_ids", ",", "r_tag", ")", ":", "genes", "=", "ET", ".", "SubElement", "(", "r_tag", ",", "_tag", "(", "'geneProductAssociation'", ",", "FBC_V2", ")", ")", "if", "isinstanc...
48.961538
12.5
def upsert_link_set(self, link_type, link_set): """ Remove an item altogether by setting link_list to None. Currently, only links can contain multiple children of the same type. :param link_type: :param link_set: :return: """ if link_set is None: ...
[ "def", "upsert_link_set", "(", "self", ",", "link_type", ",", "link_set", ")", ":", "if", "link_set", "is", "None", ":", "self", ".", "links", ".", "pop", "(", "link_type", ",", "None", ")", "return", "links", "=", "copy", ".", "deepcopy", "(", "self",...
33.785714
12.642857
def pop(self, key, default=MISSING): """ 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised' """ try: val = self[key] except KeyError: if default is...
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "MISSING", ")", ":", "try", ":", "val", "=", "self", "[", "key", "]", "except", "KeyError", ":", "if", "default", "is", "MISSING", ":", "raise", "val", "=", "default", "else", ":", "del", ...
30.214286
17.928571
def gradient(self): """Gradient operator of the functional.""" functional = self class KLCrossEntCCGradient(Operator): """The gradient operator of this functional.""" def __init__(self): """Initialize a new instance.""" super(KLCrossEntC...
[ "def", "gradient", "(", "self", ")", ":", "functional", "=", "self", "class", "KLCrossEntCCGradient", "(", "Operator", ")", ":", "\"\"\"The gradient operator of this functional.\"\"\"", "def", "__init__", "(", "self", ")", ":", "\"\"\"Initialize a new instance.\"\"\"", ...
34.333333
17.47619
def listBlocks(self, **kwargs): """ API to list a block in DBS. At least one of the parameters block_name, dataset, data_tier_name or logical_file_name are required. If data_tier_name is provided, min_cdate and max_cdate have to be specified and the difference in time have to be less tha...
[ "def", "listBlocks", "(", "self", ",", "*", "*", "kwargs", ")", ":", "validParameters", "=", "[", "'dataset'", ",", "'block_name'", ",", "'data_tier_name'", ",", "'origin_site_name'", ",", "'logical_file_name'", ",", "'run_num'", ",", "'open_for_writing'", ",", ...
54.038462
30.423077
def service_info(self, name): """Pull descriptive info of a service by name. Information returned includes the service's user friendly name and whether it was preregistered or added dynamically. Returns: dict: A dictionary of service information with the following keys ...
[ "def", "service_info", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_loop", ".", "run_coroutine", "(", "self", ".", "_client", ".", "service_info", "(", "name", ")", ")" ]
40.933333
25.266667
def checkout_default_branch(self): """ git checkout default branch """ set_state(WORKFLOW_STATES.CHECKING_OUT_DEFAULT_BRANCH) cmd = "git", "checkout", self.config["default_branch"] self.run_cmd(cmd) set_state(WORKFLOW_STATES.CHECKED_OUT_DEFAULT_BRANCH)
[ "def", "checkout_default_branch", "(", "self", ")", ":", "set_state", "(", "WORKFLOW_STATES", ".", "CHECKING_OUT_DEFAULT_BRANCH", ")", "cmd", "=", "\"git\"", ",", "\"checkout\"", ",", "self", ".", "config", "[", "\"default_branch\"", "]", "self", ".", "run_cmd", ...
35.875
20.75
def remove(name=None, pkgs=None, **kwargs): ''' Removes packages with ``port uninstall``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ``name`` parameter will be ignored if th...
[ "def", "remove", "(", "name", "=", "None", ",", "pkgs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "pkg_params", "=", "__salt__", "[", "'pkg_resource.parse_targets'", "]", "(", "name", ",", "pkgs", ",", "*", "*", "kwargs", ")", "[", "0", "]", ...
25.851852
23.259259
def read_task_file_as_string( batch_client, job_id, task_id, file_name, encoding=None): """Reads the specified file as a string. Originally in azure-batch-samples.Python.Batch.common.helpers :param batch_client: The batch client to use. :type batch_client: `batchserviceclient.BatchServiceClient...
[ "def", "read_task_file_as_string", "(", "batch_client", ",", "job_id", ",", "task_id", ",", "file_name", ",", "encoding", "=", "None", ")", ":", "stream", "=", "batch_client", ".", "file", ".", "get_from_task", "(", "job_id", ",", "task_id", ",", "file_name", ...
43.8125
16.375
def create_list_stories( list_id_stories, number_of_stories, shuffle, max_threads ): """Show in a formatted way the stories for each item of the list.""" list_stories = [] with ThreadPoolExecutor(max_workers=max_threads) as executor: futures = { executor.submit(get_story, new) ...
[ "def", "create_list_stories", "(", "list_id_stories", ",", "number_of_stories", ",", "shuffle", ",", "max_threads", ")", ":", "list_stories", "=", "[", "]", "with", "ThreadPoolExecutor", "(", "max_workers", "=", "max_threads", ")", "as", "executor", ":", "futures"...
28.454545
19.727273
def purge_stream(self, stream_id, remove_definition=False, sandbox=None): """ Purge the stream :param stream_id: The stream identifier :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox for this stream :return: None ...
[ "def", "purge_stream", "(", "self", ",", "stream_id", ",", "remove_definition", "=", "False", ",", "sandbox", "=", "None", ")", ":", "# TODO: Add time interval to this", "if", "sandbox", "is", "not", "None", ":", "raise", "NotImplementedError", "if", "stream_id", ...
35.612903
20
def plot_dir(ZED, pars, datablock, angle): """ function to put the great circle on the equal area projection and plot start and end points of calculation DEPRECATED (used in zeq_magic) """ # # find start and end points from datablock # if pars["calculation_type"] == 'DE-FM': x, y = [], ...
[ "def", "plot_dir", "(", "ZED", ",", "pars", ",", "datablock", ",", "angle", ")", ":", "#", "# find start and end points from datablock", "#", "if", "pars", "[", "\"calculation_type\"", "]", "==", "'DE-FM'", ":", "x", ",", "y", "=", "[", "]", ",", "[", "]...
35.429825
13.745614
def listen_error_messages_raylet(worker, task_error_queue, threads_stopped): """Listen to error messages in the background on the driver. This runs in a separate thread on the driver and pushes (error, time) tuples to the output queue. Args: worker: The worker class that this thread belongs to...
[ "def", "listen_error_messages_raylet", "(", "worker", ",", "task_error_queue", ",", "threads_stopped", ")", ":", "worker", ".", "error_message_pubsub_client", "=", "worker", ".", "redis_client", ".", "pubsub", "(", "ignore_subscribe_messages", "=", "True", ")", "# Exp...
44.015873
21.52381
def reconfigure_medium_attachments(self, attachments): """Reconfigure all specified medium attachments in one go, making sure the current state corresponds to the specified medium. in attachments of type :class:`IMediumAttachment` Array containing the medium attachments which need t...
[ "def", "reconfigure_medium_attachments", "(", "self", ",", "attachments", ")", ":", "if", "not", "isinstance", "(", "attachments", ",", "list", ")", ":", "raise", "TypeError", "(", "\"attachments can only be an instance of type list\"", ")", "for", "a", "in", "attac...
41.869565
16.608696
def streams(self, public=False, downlink=False, visible=True): """Returns the list of streams that belong to the user. The list can optionally be filtered in 3 ways: - public: when True, returns only streams belonging to public devices - downlink: If True, returns only downlink s...
[ "def", "streams", "(", "self", ",", "public", "=", "False", ",", "downlink", "=", "False", ",", "visible", "=", "True", ")", ":", "result", "=", "self", ".", "db", ".", "read", "(", "self", ".", "path", ",", "{", "\"q\"", ":", "\"streams\"", ",", ...
46.9
20.3
def get_devices(self): """ Helper that retuns a dict of devices for this server. :return: Returns a tuple of two elements: - dict<tango class name : list of device names> - dict<device names : tango class name> :rtype: tuple<dict, dict> ""...
[ "def", "get_devices", "(", "self", ")", ":", "if", "self", ".", "__util", "is", "None", ":", "import", "tango", "db", "=", "tango", ".", "Database", "(", ")", "else", ":", "db", "=", "self", ".", "__util", ".", "get_database", "(", ")", "server", "...
36.076923
11.615385
def plot_pipeline(self, pipeline, *args, **kwargs): ''' Plots the light curve for the target de-trended with a given pipeline. :param str pipeline: The name of the pipeline (lowercase). Options \ are 'everest2', 'everest1', and other mission-specific \ pipelines. F...
[ "def", "plot_pipeline", "(", "self", ",", "pipeline", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "pipeline", "!=", "'everest2'", ":", "return", "getattr", "(", "missions", ",", "self", ".", "mission", ")", ".", "pipelines", ".", "plot",...
36.355263
21.592105
def contains(self, em): ''' contains - Check if #em occurs within any of the elements within this list, as themselves or as a child, any number of levels down. To check if JUST an element is contained within this list directly, use the "in" operator. ...
[ "def", "contains", "(", "self", ",", "em", ")", ":", "for", "node", "in", "self", ":", "if", "node", ".", "contains", "(", "em", ")", ":", "return", "True", "return", "False" ]
32
29.764706
def update_many(self, **kwargs): """ Update multiple objects from collection. First ES is queried, then the results are used to query DB. This is done to make sure updated objects are those filtered by ES in the 'index' method (so user updates what he saw). """ db_object...
[ "def", "update_many", "(", "self", ",", "*", "*", "kwargs", ")", ":", "db_objects", "=", "self", ".", "get_dbcollection_with_es", "(", "*", "*", "kwargs", ")", "return", "self", ".", "Model", ".", "_update_many", "(", "db_objects", ",", "self", ".", "_js...
45.1
16.6
def pos_to_linecol(text, pos): """Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ line_start = text.rfind("\n", 0, pos) + 1 line = text.count("\n", 0, line_start) + 1 col = pos - line_start...
[ "def", "pos_to_linecol", "(", "text", ",", "pos", ")", ":", "line_start", "=", "text", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "pos", ")", "+", "1", "line", "=", "text", ".", "count", "(", "\"\\n\"", ",", "0", ",", "line_start", ")", "+", "1...
27.5
15.583333
def peek_lock_subscription_message(self, topic_name, subscription_name, timeout='60'): ''' This operation is used to atomically retrieve and lock a message for processing. The message is guaranteed not to be delivered to other receivers during the l...
[ "def", "peek_lock_subscription_message", "(", "self", ",", "topic_name", ",", "subscription_name", ",", "timeout", "=", "'60'", ")", ":", "_validate_not_none", "(", "'topic_name'", ",", "topic_name", ")", "_validate_not_none", "(", "'subscription_name'", ",", "subscri...
50.72973
25
def iterate_pages(self): """Iterate Pages. A generator which iterates over all pages. Keep in mind that Amazon limits the number of pages it makes available. :return: Yields lxml root elements. """ try: while not self.is_last_page: ...
[ "def", "iterate_pages", "(", "self", ")", ":", "try", ":", "while", "not", "self", ".", "is_last_page", ":", "self", ".", "current_page", "+=", "1", "yield", "self", ".", "_query", "(", "ItemPage", "=", "self", ".", "current_page", ",", "*", "*", "self...
30.133333
18.266667
def run_app(self): """Run the App as a subprocess.""" # Update system arguments sys.argv[0] = sys.executable sys.argv[1] = '{}.py'.format(sys.argv[1]) # Make sure to exit with the return value from the subprocess call self._app_process = subprocess.Popen(sys.argv) ...
[ "def", "run_app", "(", "self", ")", ":", "# Update system arguments", "sys", ".", "argv", "[", "0", "]", "=", "sys", ".", "executable", "sys", ".", "argv", "[", "1", "]", "=", "'{}.py'", ".", "format", "(", "sys", ".", "argv", "[", "1", "]", ")", ...
38.333333
14.555556
def server_console_output(request, instance_id, tail_length=None): """Gets console output of an instance.""" nc = _nova.novaclient(request) return nc.servers.get_console_output(instance_id, length=tail_length)
[ "def", "server_console_output", "(", "request", ",", "instance_id", ",", "tail_length", "=", "None", ")", ":", "nc", "=", "_nova", ".", "novaclient", "(", "request", ")", "return", "nc", ".", "servers", ".", "get_console_output", "(", "instance_id", ",", "le...
54.5
16.25