text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def addFailure(self, result): """Add a failure to the result.""" result.addFailure(self, (Exception, Exception(), None)) # Since TAP will not provide assertion data, clean up the assertion # section so it is not so spaced out. test, err = result.failures[-1] result.failur...
[ "def", "addFailure", "(", "self", ",", "result", ")", ":", "result", ".", "addFailure", "(", "self", ",", "(", "Exception", ",", "Exception", "(", ")", ",", "None", ")", ")", "# Since TAP will not provide assertion data, clean up the assertion", "# section so it is ...
47.571429
10.714286
def run_iqtree(phy, model, threads, cluster, node): """ run IQ-Tree """ # set ppn based on threads if threads > 24: ppn = 24 else: ppn = threads tree = '%s.treefile' % (phy) if check(tree) is False: if model is False: model = 'TEST' dir = os.ge...
[ "def", "run_iqtree", "(", "phy", ",", "model", ",", "threads", ",", "cluster", ",", "node", ")", ":", "# set ppn based on threads", "if", "threads", ">", "24", ":", "ppn", "=", "24", "else", ":", "ppn", "=", "threads", "tree", "=", "'%s.treefile'", "%", ...
35.285714
19
def get_error_details(self): # type: () -> Optional[Dict[str, Any]] """ Get more information about the latest X server error. """ details = {} # type: Dict[str, Any] if ERROR.details: details = {"xerror_details": ERROR.details} ERROR.details = None ...
[ "def", "get_error_details", "(", "self", ")", ":", "# type: () -> Optional[Dict[str, Any]]", "details", "=", "{", "}", "# type: Dict[str, Any]", "if", "ERROR", ".", "details", ":", "details", "=", "{", "\"xerror_details\"", ":", "ERROR", ".", "details", "}", "ERRO...
34.380952
16.047619
def file_flags(self): """Return the file flags attribute of the BFD file being processed.""" if not self._ptr: raise BfdException("BFD not initialized") return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.FILE_FLAGS)
[ "def", "file_flags", "(", "self", ")", ":", "if", "not", "self", ".", "_ptr", ":", "raise", "BfdException", "(", "\"BFD not initialized\"", ")", "return", "_bfd", ".", "get_bfd_attribute", "(", "self", ".", "_ptr", ",", "BfdAttributes", ".", "FILE_FLAGS", ")...
41.833333
20.166667
def zoning_defined_configuration_alias_alias_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") zoning = ET.SubElement(config, "zoning", xmlns="urn:brocade.com:mgmt:brocade-zone") defined_configuration = ET.SubElement(zoning, "defined-configuration") ...
[ "def", "zoning_defined_configuration_alias_alias_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "zoning", "=", "ET", ".", "SubElement", "(", "config", ",", "\"zoning\"", ",", "xmlns", "=", ...
47.25
19.166667
def snake(s): """Convert from title or camelCase to snake_case.""" if len(s) < 2: return s.lower() out = s[0].lower() for c in s[1:]: if c.isupper(): out += "_" c = c.lower() out += c return out
[ "def", "snake", "(", "s", ")", ":", "if", "len", "(", "s", ")", "<", "2", ":", "return", "s", ".", "lower", "(", ")", "out", "=", "s", "[", "0", "]", ".", "lower", "(", ")", "for", "c", "in", "s", "[", "1", ":", "]", ":", "if", "c", "...
22.909091
18.545455
def linkify_templates(self): """ Link all templates, and create the template graph too :return: None """ # First we create a list of all templates for i in itertools.chain(iter(list(self.items.values())), iter(list(self.templates.values()...
[ "def", "linkify_templates", "(", "self", ")", ":", "# First we create a list of all templates", "for", "i", "in", "itertools", ".", "chain", "(", "iter", "(", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ")", ",", "iter", "(", "list", ...
35.083333
14.75
def main(argv=None): """ben-elastic entry point""" arguments = cli_common(__doc__, argv=argv) es_export = ESExporter(arguments['CAMPAIGN-DIR'], arguments['--es']) es_export.export() if argv is not None: return es_export
[ "def", "main", "(", "argv", "=", "None", ")", ":", "arguments", "=", "cli_common", "(", "__doc__", ",", "argv", "=", "argv", ")", "es_export", "=", "ESExporter", "(", "arguments", "[", "'CAMPAIGN-DIR'", "]", ",", "arguments", "[", "'--es'", "]", ")", "...
34.428571
15.428571
def _run_model(iterator, args, tf_args): """mapPartitions function to run single-node inferencing from a checkpoint/saved_model, using the model's input/output mappings. Args: :iterator: input RDD partition iterator. :args: arguments for TFModel, in argparse format :tf_args: arguments for TensorFlow in...
[ "def", "_run_model", "(", "iterator", ",", "args", ",", "tf_args", ")", ":", "single_node_env", "(", "tf_args", ")", "logging", ".", "info", "(", "\"===== input_mapping: {}\"", ".", "format", "(", "args", ".", "input_mapping", ")", ")", "logging", ".", "info...
47.329268
27.268293
def remove_callback_for_action(self, action, callback): """ Remove a callback for a specific action This is mainly for cleanup purposes or a plugin that replaces a GUI widget. :param str action: the cation of which the callback is going to be remove :param callback: the callback to be ...
[ "def", "remove_callback_for_action", "(", "self", ",", "action", ",", "callback", ")", ":", "if", "action", "in", "self", ".", "__action_to_callbacks", ":", "if", "callback", "in", "self", ".", "__action_to_callbacks", "[", "action", "]", ":", "self", ".", "...
46.272727
22.454545
def info(self): """Gets info endpoint. Used to perform login auth.""" url = self.api_url + self.info_url resp = self.session.get(url) if resp.status_code != 200: error = {'description': "Info HTTP response not valid"} raise CFException(error, resp.status_code) ...
[ "def", "info", "(", "self", ")", ":", "url", "=", "self", ".", "api_url", "+", "self", ".", "info_url", "resp", "=", "self", ".", "session", ".", "get", "(", "url", ")", "if", "resp", ".", "status_code", "!=", "200", ":", "error", "=", "{", "'des...
41.230769
15.307692
def delete_os_dummy_rtr_nwk(self, rtr_id, net_id, subnet_id): """Delete the dummy interface to the router. """ subnet_lst = set() subnet_lst.add(subnet_id) ret = self.os_helper.delete_intf_router(None, None, rtr_id, subnet_lst) if not ret: return ret return s...
[ "def", "delete_os_dummy_rtr_nwk", "(", "self", ",", "rtr_id", ",", "net_id", ",", "subnet_id", ")", ":", "subnet_lst", "=", "set", "(", ")", "subnet_lst", ".", "add", "(", "subnet_id", ")", "ret", "=", "self", ".", "os_helper", ".", "delete_intf_router", "...
45.125
18
def _CallFlowLegacy(self, flow_name=None, next_state=None, request_data=None, client_id=None, base_session_id=None, **kwargs): """Creates a new flow and send its responses to a state. ...
[ "def", "_CallFlowLegacy", "(", "self", ",", "flow_name", "=", "None", ",", "next_state", "=", "None", ",", "request_data", "=", "None", ",", "client_id", "=", "None", ",", "base_session_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client_id", "=...
40.153846
21.192308
def set_attribute(self, name, value): """Sets the attribute of the element to a specified value @type name: str @param name: the name of the attribute @type value: str @param value: the attribute of the value """ js_executor = self.driver_wrapper.js_e...
[ "def", "set_attribute", "(", "self", ",", "name", ",", "value", ")", ":", "js_executor", "=", "self", ".", "driver_wrapper", ".", "js_executor", "def", "set_attribute_element", "(", ")", ":", "\"\"\"\n Wrapper to set attribute\n \"\"\"", "js_execut...
41.2
15.4
def range(start, finish, step): """Like built-in :func:`~builtins.range`, but with float support""" value = start while value <= finish: yield value value += step
[ "def", "range", "(", "start", ",", "finish", ",", "step", ")", ":", "value", "=", "start", "while", "value", "<=", "finish", ":", "yield", "value", "value", "+=", "step" ]
34.166667
11.666667
def _move(self, from_state=None, to_state=None, when=None, mode=None): """ Internal helper to move a task from one state to another (e.g. from QUEUED to DELAYED). The "when" argument indicates the timestamp of the task in the new state. If no to_state is specified, the task will be ...
[ "def", "_move", "(", "self", ",", "from_state", "=", "None", ",", "to_state", "=", "None", ",", "when", "=", "None", ",", "mode", "=", "None", ")", ":", "pipeline", "=", "self", ".", "tiger", ".", "connection", ".", "pipeline", "(", ")", "scripts", ...
40.506849
21.356164
def _is_dirty(dir_path): """Check whether a git repository has uncommitted changes.""" try: subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path) return False except subprocess.CalledProcessError: return True
[ "def", "_is_dirty", "(", "dir_path", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "\"git\"", ",", "\"diff\"", ",", "\"--quiet\"", "]", ",", "cwd", "=", "dir_path", ")", "return", "False", "except", "subprocess", ".", "CalledProcessError",...
35.428571
17.285714
def solver(A, config): """Generate an SA solver given matrix A and a configuration. Parameters ---------- A : array, matrix, csr_matrix, bsr_matrix Matrix to invert, CSR or BSR format preferred for efficiency config : dict A dictionary of solver configuration parameters that is used...
[ "def", "solver", "(", "A", ",", "config", ")", ":", "# Convert A to acceptable format", "A", "=", "make_csr", "(", "A", ")", "# Generate smoothed aggregation solver", "try", ":", "return", "smoothed_aggregation_solver", "(", "A", ",", "B", "=", "config", "[", "'...
38.461538
22.557692
def normalize_value(self, value, transform=True): """Prepare the given value to be stored in the index For the parameters, see BaseIndex.normalize_value Raises ------ ValueError If ``raise_if_not_float`` is True and the value cannot be casted to a float....
[ "def", "normalize_value", "(", "self", ",", "value", ",", "transform", "=", "True", ")", ":", "if", "transform", ":", "value", "=", "self", ".", "transform_value", "(", "value", ")", "try", ":", "return", "float", "(", "value", ")", "except", "(", "Val...
31.045455
18.818182
def cast_in(self, element): """encode the element into the internal tag list.""" if _debug: SequenceOfAny._debug("cast_in %r", element) # make sure it is a list if not isinstance(element, List): raise EncodingError("%r is not a list" % (element,)) t = TagList() ...
[ "def", "cast_in", "(", "self", ",", "element", ")", ":", "if", "_debug", ":", "SequenceOfAny", ".", "_debug", "(", "\"cast_in %r\"", ",", "element", ")", "# make sure it is a list", "if", "not", "isinstance", "(", "element", ",", "List", ")", ":", "raise", ...
30.833333
18.666667
def do_parse(infilename: str, jsonfilename: Optional[str], rdffilename: Optional[str], rdffmt: str, context: Optional[str] = None) -> bool: """ Parse the jsg in infilename and save the results in outfilename :param infilename: name of the file containing the ShExC :param jsonfilename: targe...
[ "def", "do_parse", "(", "infilename", ":", "str", ",", "jsonfilename", ":", "Optional", "[", "str", "]", ",", "rdffilename", ":", "Optional", "[", "str", "]", ",", "rdffmt", ":", "str", ",", "context", ":", "Optional", "[", "str", "]", "=", "None", "...
46.636364
19.545455
def encrypt_item(table_name, aws_cmk_id): """Demonstrate use of EncryptedTable to transparently encrypt an item.""" index_key = {"partition_attribute": "is this", "sort_attribute": 55} plaintext_item = { "example": "data", "some numbers": 99, "and some binary": Binary(b"\x00\x01\x02"...
[ "def", "encrypt_item", "(", "table_name", ",", "aws_cmk_id", ")", ":", "index_key", "=", "{", "\"partition_attribute\"", ":", "\"is this\"", ",", "\"sort_attribute\"", ":", "55", "}", "plaintext_item", "=", "{", "\"example\"", ":", "\"data\"", ",", "\"some numbers...
45.126761
24.070423
def load_config(json_path): """Load config info from a .json file and return it.""" with open(json_path, 'r') as json_file: config = json.loads(json_file.read()) # sanity-test the config: assert(config['tree'][0]['page'] == 'index') return config
[ "def", "load_config", "(", "json_path", ")", ":", "with", "open", "(", "json_path", ",", "'r'", ")", "as", "json_file", ":", "config", "=", "json", ".", "loads", "(", "json_file", ".", "read", "(", ")", ")", "# sanity-test the config:", "assert", "(", "c...
36.285714
8.428571
def loads(cls, data, store_password, try_decrypt_keys=True): """ See :meth:`jks.jks.KeyStore.loads`. :param bytes data: Byte string representation of the keystore to be loaded. :param str password: Keystore password string :param bool try_decrypt_keys: Whether to automatically t...
[ "def", "loads", "(", "cls", ",", "data", ",", "store_password", ",", "try_decrypt_keys", "=", "True", ")", ":", "try", ":", "pos", "=", "0", "version", "=", "b4", ".", "unpack_from", "(", "data", ",", "pos", ")", "[", "0", "]", "pos", "+=", "4", ...
54.980392
36.54902
def verify_logout_request(cls, logout_request, ticket): """verifies the single logout request came from the CAS server returns True if the logout_request is valid, False otherwise """ try: session_index = cls.get_saml_slos(logout_request) session_index = session_i...
[ "def", "verify_logout_request", "(", "cls", ",", "logout_request", ",", "ticket", ")", ":", "try", ":", "session_index", "=", "cls", ".", "get_saml_slos", "(", "logout_request", ")", "session_index", "=", "session_index", "[", "0", "]", ".", "text", "if", "s...
38.846154
13.076923
def search_cloud_integration_for_facet(self, facet, **kwargs): # noqa: E501 """Lists the values of a specific facet over the customer's non-deleted cloud integrations # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP requ...
[ "def", "search_cloud_integration_for_facet", "(", "self", ",", "facet", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ...
48.181818
21.590909
def get_members_of_group(self, gname): """Get all members of a group which name is given in parameter :param gname: name of the group :type gname: str :return: list of contacts in the group :rtype: list[alignak.objects.contact.Contact] """ contactgroup = self.fin...
[ "def", "get_members_of_group", "(", "self", ",", "gname", ")", ":", "contactgroup", "=", "self", ".", "find_by_name", "(", "gname", ")", "if", "contactgroup", ":", "return", "contactgroup", ".", "get_contacts", "(", ")", "return", "[", "]" ]
34.583333
10.833333
def from_array(array): """ Deserialize a new Message from a given dictionary. :return: new Message instance. :rtype: Message """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") ...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "from", ".", ".", "receivabl...
92.138462
60.569231
def signal_handler(signum, stackframe): """Helper function to handle caught signals.""" global g_runner global g_handling_signal if g_handling_signal: # Don't do this recursively. return g_handling_signal = True print("") print("---------------------------------------------...
[ "def", "signal_handler", "(", "signum", ",", "stackframe", ")", ":", "global", "g_runner", "global", "g_handling_signal", "if", "g_handling_signal", ":", "# Don't do this recursively.", "return", "g_handling_signal", "=", "True", "print", "(", "\"\"", ")", "print", ...
31.764706
22.647059
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao, opcao=constantes.CODIGO_ATIVACAO_REGULAR, codigo_emergencia=None): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSA...
[ "def", "trocar_codigo_de_ativacao", "(", "self", ",", "novo_codigo_ativacao", ",", "opcao", "=", "constantes", ".", "CODIGO_ATIVACAO_REGULAR", ",", "codigo_emergencia", "=", "None", ")", ":", "resp", "=", "self", ".", "_http_post", "(", "'trocarcodigodeativacao'", "...
44.785714
13.571429
def on_dummies(self, *args): """Give the dummies numbers such that, when appended to their names, they give a unique name for the resulting new :class:`board.Pawn` or :class:`board.Spot`. """ def renum_dummy(dummy, *args): dummy.num = dummynum(self.app.character, dum...
[ "def", "on_dummies", "(", "self", ",", "*", "args", ")", ":", "def", "renum_dummy", "(", "dummy", ",", "*", "args", ")", ":", "dummy", ".", "num", "=", "dummynum", "(", "self", ".", "app", ".", "character", ",", "dummy", ".", "prefix", ")", "+", ...
45.2
17.05
def delete_view(self, request, object_id, extra_context=None): """ Overrides the default to enable redirecting to the directory view after deletion of a image. we need to fetch the object and find out who the parent is before super, because super will delete the object and make ...
[ "def", "delete_view", "(", "self", ",", "request", ",", "object_id", ",", "extra_context", "=", "None", ")", ":", "try", ":", "obj", "=", "self", ".", "get_queryset", "(", "request", ")", ".", "get", "(", "pk", "=", "unquote", "(", "object_id", ")", ...
40.647059
18.470588
def closed(self, error=None): """ Notify the application that the connection has been closed. :param error: The exception which has caused the connection to be closed. If the connection has been closed due to an EOF, pass ``None``. """ ...
[ "def", "closed", "(", "self", ",", "error", "=", "None", ")", ":", "if", "self", ".", "_application", ":", "try", ":", "self", ".", "_application", ".", "closed", "(", "error", ")", "except", "Exception", ":", "# Ignore exceptions from the notification", "pa...
33.6
18.4
def parse(readDataInstance): """ Returns a new L{NtHeaders} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{NtHeaders} object. @rtype: L{NtHeaders} @return: A new L{NtHeaders} object...
[ "def", "parse", "(", "readDataInstance", ")", ":", "nt", "=", "NtHeaders", "(", ")", "nt", ".", "signature", ".", "value", "=", "readDataInstance", ".", "readDword", "(", ")", "nt", ".", "fileHeader", "=", "FileHeader", ".", "parse", "(", "readDataInstance...
36.4
17.2
def masktorgb(mask, color='lightgreen', alpha=1.0): """Convert boolean mask to RGB image object for canvas overlay. Parameters ---------- mask : ndarray Boolean mask to overlay. 2D image only. color : str Color name accepted by Ginga. alpha : float Opacity. Unmasked da...
[ "def", "masktorgb", "(", "mask", ",", "color", "=", "'lightgreen'", ",", "alpha", "=", "1.0", ")", ":", "mask", "=", "np", ".", "asarray", "(", "mask", ")", "if", "mask", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "'ndim={0} is not suppor...
22.285714
21.510204
def process_samples_array(samples, **kwargs): """Convert an array of nested sampling dead and live points of the type produced by PolyChord and MultiNest into a nestcheck nested sampling run dictionary. Parameters ---------- samples: 2d numpy array Array of dead points and any remaining...
[ "def", "process_samples_array", "(", "samples", ",", "*", "*", "kwargs", ")", ":", "samples", "=", "samples", "[", "np", ".", "argsort", "(", "samples", "[", ":", ",", "-", "2", "]", ")", "]", "ns_run", "=", "{", "}", "ns_run", "[", "'logl'", "]", ...
44.42623
18.295082
def is_excluded_for_sdesc(self, sdesc, is_tpl=False): """ Check whether this host should have the passed service *description* be "excluded" or "not included". :param sdesc: service description :type sdesc: :param is_tpl: True if service is template, otherwise False ...
[ "def", "is_excluded_for_sdesc", "(", "self", ",", "sdesc", ",", "is_tpl", "=", "False", ")", ":", "if", "not", "is_tpl", "and", "self", ".", "service_includes", ":", "return", "sdesc", "not", "in", "self", ".", "service_includes", "if", "self", ".", "servi...
39.6875
14.125
def add_package(self, name): """ Registers a single package :param name: (str) The effect package to add """ name, cls_name = parse_package_string(name) if name in self.package_map: return package = EffectPackage(name) package.load() ...
[ "def", "add_package", "(", "self", ",", "name", ")", ":", "name", ",", "cls_name", "=", "parse_package_string", "(", "name", ")", "if", "name", "in", "self", ".", "package_map", ":", "return", "package", "=", "EffectPackage", "(", "name", ")", "package", ...
24.894737
16.157895
def logical_and(self, other): """logical_and(t) = self(t) and other(t).""" return self.operation(other, lambda x, y: int(x and y))
[ "def", "logical_and", "(", "self", ",", "other", ")", ":", "return", "self", ".", "operation", "(", "other", ",", "lambda", "x", ",", "y", ":", "int", "(", "x", "and", "y", ")", ")" ]
48
11.333333
def _load_managed_entries(self): """ loads scheduler managed entries. no start-up procedures are performed """ for process_name, process_entry in context.process_context.items(): if isinstance(process_entry, ManagedProcessEntry): function = self.fire_managed_worker ...
[ "def", "_load_managed_entries", "(", "self", ")", ":", "for", "process_name", ",", "process_entry", "in", "context", ".", "process_context", ".", "items", "(", ")", ":", "if", "isinstance", "(", "process_entry", ",", "ManagedProcessEntry", ")", ":", "function", ...
53.933333
27.2
def focus0(self): ''' First focus of the ellipse, Point class. ''' f = Point(self.center) if self.xAxisIsMajor: f.x -= self.linearEccentricity else: f.y -= self.linearEccentricity return f
[ "def", "focus0", "(", "self", ")", ":", "f", "=", "Point", "(", "self", ".", "center", ")", "if", "self", ".", "xAxisIsMajor", ":", "f", ".", "x", "-=", "self", ".", "linearEccentricity", "else", ":", "f", ".", "y", "-=", "self", ".", "linearEccent...
21.583333
20.416667
def _lml_arbitrary_scale(self): """ Log of the marginal likelihood for arbitrary scale. Returns ------- lml : float Log of the marginal likelihood. """ s = self.scale D = self._D n = len(self._y) lml = -self._df * log2pi - n * ...
[ "def", "_lml_arbitrary_scale", "(", "self", ")", ":", "s", "=", "self", ".", "scale", "D", "=", "self", ".", "_D", "n", "=", "len", "(", "self", ".", "_y", ")", "lml", "=", "-", "self", ".", "_df", "*", "log2pi", "-", "n", "*", "log", "(", "s...
28.111111
17.222222
def process(self, context): import os from maya import cmds """Inject the current working file""" current_file = cmds.file(sceneName=True, query=True) # Maya returns forward-slashes by default normalised = os.path.normpath(current_file) context.set_data('curren...
[ "def", "process", "(", "self", ",", "context", ")", ":", "import", "os", "from", "maya", "import", "cmds", "current_file", "=", "cmds", ".", "file", "(", "sceneName", "=", "True", ",", "query", "=", "True", ")", "# Maya returns forward-slashes by default", "...
30.714286
20.357143
def get_tree(cls, session=None, json=False, json_fields=None, query=None): """ This method generate tree of current node table in dict or json format. You can make custom query with attribute ``query``. By default it return all nodes in table. Args: session (:mod:`sqlalchemy...
[ "def", "get_tree", "(", "cls", ",", "session", "=", "None", ",", "json", "=", "False", ",", "json_fields", "=", "None", ",", "query", "=", "None", ")", ":", "# noqa", "tree", "=", "[", "]", "nodes_of_level", "=", "{", "}", "# handle custom query", "nod...
38.644068
21.932203
async def read(self, n=None): """Read all content """ if self._streamed: return b'' buffer = [] async for body in self: buffer.append(body) return b''.join(buffer)
[ "async", "def", "read", "(", "self", ",", "n", "=", "None", ")", ":", "if", "self", ".", "_streamed", ":", "return", "b''", "buffer", "=", "[", "]", "async", "for", "body", "in", "self", ":", "buffer", ".", "append", "(", "body", ")", "return", "...
25.222222
10.111111
def _load_nucmer_hits(self, infile): '''Returns two dictionaries: 1) name=>contig length. 2) Second is dictionary of nucmer hits (ignoring self matches). contig name => list of hits''' hits = {} lengths = {} file_reader = pymummer.coords_file.reader(in...
[ "def", "_load_nucmer_hits", "(", "self", ",", "infile", ")", ":", "hits", "=", "{", "}", "lengths", "=", "{", "}", "file_reader", "=", "pymummer", ".", "coords_file", ".", "reader", "(", "infile", ")", "for", "al", "in", "file_reader", ":", "if", "al",...
38.647059
10.058824
def logout(self): """ Logout from the backend :return: return True if logout is successfull, otherwise False :rtype: bool """ logger.debug("request backend logout") if not self.authenticated: logger.warning("Unnecessary logout ...") return...
[ "def", "logout", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"request backend logout\"", ")", "if", "not", "self", ".", "authenticated", ":", "logger", ".", "warning", "(", "\"Unnecessary logout ...\"", ")", "return", "True", "endpoint", "=", "'logou...
24.3
19.9
def _SetSocketTimeouts(self): """Sets the timeouts for socket send and receive.""" # Note that timeout must be an integer value. If timeout is a float # it appears that zmq will not enforce the timeout. timeout = int(self.timeout_seconds * 1000) receive_timeout = min( self._ZMQ_SOCKET_RECEIV...
[ "def", "_SetSocketTimeouts", "(", "self", ")", ":", "# Note that timeout must be an integer value. If timeout is a float", "# it appears that zmq will not enforce the timeout.", "timeout", "=", "int", "(", "self", ".", "timeout_seconds", "*", "1000", ")", "receive_timeout", "="...
49.272727
19.636364
def getbit(self, key, offset): """Returns the bit value at offset in the string value stored at key. :raises TypeError: if offset is not int :raises ValueError: if offset is less than 0 """ if not isinstance(offset, int): raise TypeError("offset argument must be int"...
[ "def", "getbit", "(", "self", ",", "key", ",", "offset", ")", ":", "if", "not", "isinstance", "(", "offset", ",", "int", ")", ":", "raise", "TypeError", "(", "\"offset argument must be int\"", ")", "if", "offset", "<", "0", ":", "raise", "ValueError", "(...
40.818182
12.636364
def get_experiments(redis, active=True): """Gets the full list of experiments""" key = ACTIVE_EXPERIMENTS_REDIS_KEY if active else ARCHIVED_EXPERIMENTS_REDIS_KEY return [Experiment(redis, escape.to_unicode(name)) for name in redis.smembers(key)]
[ "def", "get_experiments", "(", "redis", ",", "active", "=", "True", ")", ":", "key", "=", "ACTIVE_EXPERIMENTS_REDIS_KEY", "if", "active", "else", "ARCHIVED_EXPERIMENTS_REDIS_KEY", "return", "[", "Experiment", "(", "redis", ",", "escape", ".", "to_unicode", "(", ...
50.8
26.2
def bam_to_fastq_pair(in_file, target_region, pair): """Generator to convert BAM files into name, seq, qual in a region. """ space, start, end = target_region bam_file = pysam.Samfile(in_file, "rb") for read in bam_file: if (not read.is_unmapped and not read.mate_is_unmapped ...
[ "def", "bam_to_fastq_pair", "(", "in_file", ",", "target_region", ",", "pair", ")", ":", "space", ",", "start", ",", "end", "=", "target_region", "bam_file", "=", "pysam", ".", "Samfile", "(", "in_file", ",", "\"rb\"", ")", "for", "read", "in", "bam_file",...
45.789474
10.947368
def new_array(state, element_type, size): """ Allocates a new array in memory and returns the reference to the base. """ size_bounded = SimSootExpr_NewArray._bound_array_size(state, size) # return the reference of the array base # => elements getting lazy initialized in t...
[ "def", "new_array", "(", "state", ",", "element_type", ",", "size", ")", ":", "size_bounded", "=", "SimSootExpr_NewArray", ".", "_bound_array_size", "(", "state", ",", "size", ")", "# return the reference of the array base", "# => elements getting lazy initialized in the ja...
54.6
20.4
def body_class_tag(context): """ Return CSS "class" attributes for <body>. Allows to provide a CSS namespace using urlpatterns namespace (as ``.ns-*``) and view name (as ``.vw-*``). Usage: ``{% body_class %}`` Example: ``ns-my-app vw-my-view`` or ``ns-contacts vw-list`` Requires: ``apps.core.m...
[ "def", "body_class_tag", "(", "context", ")", ":", "request", "=", "context", ".", "get", "(", "\"request\"", ")", "if", "not", "hasattr", "(", "request", ",", "\"ROUTE\"", ")", ":", "return", "\"\"", "css_classes", "=", "[", "]", "namespace", "=", "requ...
32.518519
22.37037
def rotate(curve, degs, origin=None): """Returns curve rotated by `degs` degrees (CCW) around the point `origin` (a complex number). By default origin is either `curve.point(0.5)`, or in the case that curve is an Arc object, `origin` defaults to `curve.center`. """ def transform(z): return ...
[ "def", "rotate", "(", "curve", ",", "degs", ",", "origin", "=", "None", ")", ":", "def", "transform", "(", "z", ")", ":", "return", "exp", "(", "1j", "*", "radians", "(", "degs", ")", ")", "*", "(", "z", "-", "origin", ")", "+", "origin", "if",...
42.888889
18.925926
def dagify_min_edge(g): """Input a graph and output a DAG. The heuristic is to reverse the edge with the lowest score of the cycle if possible, else remove it. Args: g (networkx.DiGraph): Graph to modify to output a DAG Returns: networkx.DiGraph: DAG made out of the input graph. ...
[ "def", "dagify_min_edge", "(", "g", ")", ":", "while", "not", "nx", ".", "is_directed_acyclic_graph", "(", "g", ")", ":", "cycle", "=", "next", "(", "nx", ".", "simple_cycles", "(", "g", ")", ")", "scores", "=", "[", "]", "edges", "=", "[", "]", "f...
29.241379
19.344828
def derive_ordering(self): """ Returns what field should be used for ordering (using a prepended '-' to indicate descending sort). If the default order of the queryset should be used, returns None """ if '_order' in self.request.GET: return self.request.GET['_order']...
[ "def", "derive_ordering", "(", "self", ")", ":", "if", "'_order'", "in", "self", ".", "request", ".", "GET", ":", "return", "self", ".", "request", ".", "GET", "[", "'_order'", "]", "elif", "self", ".", "default_order", ":", "return", "self", ".", "def...
34.833333
17.833333
def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin """Get a list of configs. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields ...
[ "def", "list", "(", "self", ",", "filter", "=", "None", ",", "type", "=", "None", ",", "sort", "=", "None", ",", "limit", "=", "None", ",", "page", "=", "None", ")", ":", "# pylint: disable=redefined-builtin", "schema", "=", "self", ".", "LIST_SCHEMA", ...
51.714286
23
def displayOutdated(modules, dependency_specs, use_colours): ''' print information about outdated modules, return 0 if there is nothing to be done and nonzero otherwise ''' if use_colours: DIM = colorama.Style.DIM #pylint: disable=no-member NORMAL = colorama.Style.NORMAL ...
[ "def", "displayOutdated", "(", "modules", ",", "dependency_specs", ",", "use_colours", ")", ":", "if", "use_colours", ":", "DIM", "=", "colorama", ".", "Style", ".", "DIM", "#pylint: disable=no-member", "NORMAL", "=", "colorama", ".", "Style", ".", "NORMAL", "...
45.026667
23.32
def create_sync_ops(self, host_device): """Create an assignment operation for each weight on all devices. The weight is assigned the value of the copy on the `host_device'. """ sync_ops = [] host_params = self.params_device[host_device] for device, params in (self.params_device).iteritems(): ...
[ "def", "create_sync_ops", "(", "self", ",", "host_device", ")", ":", "sync_ops", "=", "[", "]", "host_params", "=", "self", ".", "params_device", "[", "host_device", "]", "for", "device", ",", "params", "in", "(", "self", ".", "params_device", ")", ".", ...
39.615385
12.692308
def get_id_fields(self): """ Called to return a list of fields consisting of, at minimum, the PK field name. The output of this method is used to construct a Prefetch object with a .only() queryset when this field is not being sideloaded but we need to return a list of ID...
[ "def", "get_id_fields", "(", "self", ")", ":", "model", "=", "self", ".", "get_model", "(", ")", "out", "=", "[", "model", ".", "_meta", ".", "pk", ".", "name", "]", "# get PK field name", "# If this is being called, it means it", "# is a many-relation to its par...
39.68
16.16
def append_text(self, content): """ Append text nodes into L{Content.data} Here is where the I{true} type is used to translate the value into the proper python type. @param content: The current content being unmarshalled. @type content: L{Content} """ Core...
[ "def", "append_text", "(", "self", ",", "content", ")", ":", "Core", ".", "append_text", "(", "self", ",", "content", ")", "known", "=", "self", ".", "resolver", ".", "top", "(", ")", ".", "resolved", "content", ".", "text", "=", "self", ".", "transl...
40.181818
9.272727
def _handle_products(request, category, products, prefix): ''' Handles a products list form in the given request. Returns the form instance, the discounts applicable to this form, and whether the contents were handled. ''' current_cart = CartController.for_user(request.user) ProductsForm = forms.P...
[ "def", "_handle_products", "(", "request", ",", "category", ",", "products", ",", "prefix", ")", ":", "current_cart", "=", "CartController", ".", "for_user", "(", "request", ".", "user", ")", "ProductsForm", "=", "forms", ".", "ProductsForm", "(", "category", ...
31.344262
20.721311
def build_c(self): """Calculates the total attenuation from the total absorption and total scattering c = a + b """ lg.info('Building total attenuation C') self.c = self.a + self.b
[ "def", "build_c", "(", "self", ")", ":", "lg", ".", "info", "(", "'Building total attenuation C'", ")", "self", ".", "c", "=", "self", ".", "a", "+", "self", ".", "b" ]
30.714286
14.285714
def get_file_url(self, fid, public=None): """ Get url for the file :param string fid: File ID :param boolean public: public or internal url :rtype: string """ try: volume_id, rest = fid.strip().split(",") except ValueError: raise B...
[ "def", "get_file_url", "(", "self", ",", "fid", ",", "public", "=", "None", ")", ":", "try", ":", "volume_id", ",", "rest", "=", "fid", ".", "strip", "(", ")", ".", "split", "(", "\",\"", ")", "except", "ValueError", ":", "raise", "BadFidFormat", "("...
35.1
14.3
def nearest_point(query, root_id, get_properties, dist_fun=euclidean_dist): """Find the point in the tree that minimizes the distance to the query. This method implements the nearest_point query for any structure implementing a kd-tree. The only requirement is a function capable to extract the relevant...
[ "def", "nearest_point", "(", "query", ",", "root_id", ",", "get_properties", ",", "dist_fun", "=", "euclidean_dist", ")", ":", "k", "=", "len", "(", "query", ")", "dist", "=", "math", ".", "inf", "nearest_node_id", "=", "None", "# stack_node: stack of identifi...
34.662651
21.771084
def dimap(D, I): """ Function to map directions to x,y pairs in equal area projection Parameters ---------- D : list or array of declinations (as float) I : list or array or inclinations (as float) Returns ------- XY : x, y values of directions for equal area projection [x,y] ...
[ "def", "dimap", "(", "D", ",", "I", ")", ":", "try", ":", "D", "=", "float", "(", "D", ")", "I", "=", "float", "(", "I", ")", "except", "TypeError", ":", "# is an array", "return", "dimap_V", "(", "D", ",", "I", ")", "# DEFINE FUNCTION VARIABLES", ...
24.902439
21.04878
def checkpoint(key=0, unpickler=pickle.load, pickler=pickle.dump, work_dir=gettempdir(), refresh=False): """ A utility decorator to save intermediate results of a function. It is the caller's responsibility to specify a key naming scheme such that the output of each function call with different argument...
[ "def", "checkpoint", "(", "key", "=", "0", ",", "unpickler", "=", "pickle", ".", "load", ",", "pickler", "=", "pickle", ".", "dump", ",", "work_dir", "=", "gettempdir", "(", ")", ",", "refresh", "=", "False", ")", ":", "def", "decorator", "(", "func"...
42.257576
29.469697
def iat(x, maxlag=None): """Calculate the integrated autocorrelation time (IAT), given the trace from a Stochastic.""" if not maxlag: # Calculate maximum lag to which autocorrelation is calculated maxlag = _find_max_lag(x) acr = [autocorr(x, lag) for lag in range(1, maxlag + 1)] # Cal...
[ "def", "iat", "(", "x", ",", "maxlag", "=", "None", ")", ":", "if", "not", "maxlag", ":", "# Calculate maximum lag to which autocorrelation is calculated", "maxlag", "=", "_find_max_lag", "(", "x", ")", "acr", "=", "[", "autocorr", "(", "x", ",", "lag", ")",...
30.722222
23.111111
def error(self, correlation_id, error, message, *args, **kwargs): """ Logs recoverable application error. :param correlation_id: (optional) transaction id to trace execution through call chain. :param error: an error object associated with this message. :param message: a human...
[ "def", "error", "(", "self", ",", "correlation_id", ",", "error", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_format_and_write", "(", "LogLevel", ".", "Error", ",", "correlation_id", ",", "error", ",", "message", ...
37.333333
27.866667
def PopItem(self): """Pops an item off the queue. If no ZeroMQ socket has been created, one will be created the first time this method is called. Returns: object: item from the queue. Raises: KeyboardInterrupt: if the process is sent a KeyboardInterrupt while popping an item...
[ "def", "PopItem", "(", "self", ")", ":", "if", "not", "self", ".", "_zmq_socket", ":", "self", ".", "_CreateZMQSocket", "(", ")", "if", "not", "self", ".", "_terminate_event", ":", "raise", "RuntimeError", "(", "'Missing terminate event.'", ")", "logger", "....
29.18
21.2
def popen(fn, *args, **kwargs) -> subprocess.Popen: """ Please ensure you're not killing the process before it had started properly :param fn: :param args: :param kwargs: :return: """ args = popen_encode(fn, *args, **kwargs) logging.getLogger(__name__).debug('Start %s', args) ...
[ "def", "popen", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "subprocess", ".", "Popen", ":", "args", "=", "popen_encode", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", "logging", ".", "getLogger", "(", "__name__", ...
23
21.8
def warn(what, string, pos): """ Combines a warning with a call to errors.position(). Simple convenience function. Arguments: string (str): The string being parsed. pos (int): The index of the character that caused trouble. """ pos = position(string, pos) warnings.warn("{0} at position {1}!".format(what...
[ "def", "warn", "(", "what", ",", "string", ",", "pos", ")", ":", "pos", "=", "position", "(", "string", ",", "pos", ")", "warnings", ".", "warn", "(", "\"{0} at position {1}!\"", ".", "format", "(", "what", ",", "pos", ")", ",", "Warning", ")" ]
21.466667
21.466667
def badges(request): ''' Either displays a form containing a list of users with badges to render, or returns a .zip file containing their badges. ''' category = request.GET.getlist("category", []) product = request.GET.getlist("product", []) status = request.GET.get("status") form = forms.Invo...
[ "def", "badges", "(", "request", ")", ":", "category", "=", "request", ".", "GET", ".", "getlist", "(", "\"category\"", ",", "[", "]", ")", "product", "=", "request", ".", "GET", ".", "getlist", "(", "\"product\"", ",", "[", "]", ")", "status", "=", ...
29.029412
22.558824
def index_lists_equal(a: List[Index], b: List[Index]) -> bool: """ Are all indexes in list ``a`` equal to their counterparts in list ``b``, as per :func:`indexes_equal`? """ n = len(a) if len(b) != n: return False for i in range(n): if not indexes_equal(a[i], b[i]): ...
[ "def", "index_lists_equal", "(", "a", ":", "List", "[", "Index", "]", ",", "b", ":", "List", "[", "Index", "]", ")", "->", "bool", ":", "n", "=", "len", "(", "a", ")", "if", "len", "(", "b", ")", "!=", "n", ":", "return", "False", "for", "i",...
30.692308
16.230769
def get_center_of_mass(image): """ Compute an image center of mass in physical space which is defined as the mean of the intensity weighted voxel coordinate system. ANTsR function: `getCenterOfMass` Arguments --------- image : ANTsImage image from which center of mass will be ...
[ "def", "get_center_of_mass", "(", "image", ")", ":", "if", "image", ".", "pixeltype", "!=", "'float'", ":", "image", "=", "image", ".", "clone", "(", "'float'", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'centerOfMass%s'", "%", "image", ".", "_...
25.5
21.5
def sum(self, field): """ Returns the sum of the field in the result set of the query by wrapping the query and performing a SUM aggregate of the specified field :param field: the field to pass to the SUM aggregate :type field: str :return: The sum of the specified field...
[ "def", "sum", "(", "self", ",", "field", ")", ":", "q", "=", "Query", "(", "self", ".", "connection", ")", ".", "from_table", "(", "self", ",", "fields", "=", "[", "SumField", "(", "field", ")", "]", ")", "rows", "=", "q", ".", "select", "(", "...
35.133333
17.533333
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs): """ Inherited method should take all specified arguments. :param variable_p...
[ "def", "get", "(", "self", ",", "variable_path", ":", "str", ",", "default", ":", "t", ".", "Optional", "[", "t", ".", "Any", "]", "=", "None", ",", "coerce_type", ":", "t", ".", "Optional", "[", "t", ".", "Type", "]", "=", "None", ",", "coercer"...
42.411765
18.529412
def _pypsa_generator_timeseries(network, timesteps, mode=None): """Timeseries in PyPSA compatible format for generator instances Parameters ---------- network : Network The eDisGo grid topology model overall container timesteps : array_like Timesteps is an array-like object with ent...
[ "def", "_pypsa_generator_timeseries", "(", "network", ",", "timesteps", ",", "mode", "=", "None", ")", ":", "mv_gen_timeseries_q", "=", "[", "]", "mv_gen_timeseries_p", "=", "[", "]", "lv_gen_timeseries_q", "=", "[", "]", "lv_gen_timeseries_p", "=", "[", "]", ...
39.320755
20.54717
def percentage(a, b, precision=1, mode=0): """ >>> percentage(100, 200) '100 of 200 (50.0%)' """ _a, _b = a, b pct = "{0:.{1}f}%".format(a * 100. / b, precision) a, b = thousands(a), thousands(b) if mode == 0: return "{0} of {1} ({2})".format(a, b, pct) elif mode == 1: ...
[ "def", "percentage", "(", "a", ",", "b", ",", "precision", "=", "1", ",", "mode", "=", "0", ")", ":", "_a", ",", "_b", "=", "a", ",", "b", "pct", "=", "\"{0:.{1}f}%\"", ".", "format", "(", "a", "*", "100.", "/", "b", ",", "precision", ")", "a...
27.066667
12.266667
def token_network_connect( self, registry_address: PaymentNetworkID, token_address: TokenAddress, funds: TokenAmount, initial_channel_target: int = 3, joinable_funds_target: float = 0.4, ) -> None: """ Automatically maintain channels op...
[ "def", "token_network_connect", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "funds", ":", "TokenAmount", ",", "initial_channel_target", ":", "int", "=", "3", ",", "joinable_funds_target", ":", "float...
41.571429
22.959184
def render(self, **kwargs): """Renders the HTML representation of the element.""" return self._template.render(this=self, kwargs=kwargs)
[ "def", "render", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_template", ".", "render", "(", "this", "=", "self", ",", "kwargs", "=", "kwargs", ")" ]
50
11.666667
def atlas_make_zonefile_inventory( bit_offset, bit_length, con=None, path=None ): """ Get a summary description of the list of zonefiles we have for the given block range (a "zonefile inventory") Zonefile present/absent bits are ordered left-to-right, where the leftmost bit is the earliest zonefile...
[ "def", "atlas_make_zonefile_inventory", "(", "bit_offset", ",", "bit_length", ",", "con", "=", "None", ",", "path", "=", "None", ")", ":", "listing", "=", "atlasdb_zonefile_inv_list", "(", "bit_offset", ",", "bit_length", ",", "con", "=", "con", ",", "path", ...
34.111111
18.611111
def cigarRead(fileHandleOrFile): """Reads a list of pairwise alignments into a pairwise alignment structure. Query and target are reversed! """ fileHandle = _getFileHandle(fileHandleOrFile) #p = re.compile("cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+(...
[ "def", "cigarRead", "(", "fileHandleOrFile", ")", ":", "fileHandle", "=", "_getFileHandle", "(", "fileHandleOrFile", ")", "#p = re.compile(\"cigar:\\\\s+(.+)\\\\s+([0-9]+)\\\\s+([0-9]+)\\\\s+([\\\\+\\\\-\\\\.])\\\\s+(.+)\\\\s+([0-9]+)\\\\s+([0-9]+)\\\\s+([\\\\+\\\\-\\\\.])\\\\s+(.+)\\\\s+(.*...
46.8125
23.8125
def torrents(self, **filters): """ Returns a list of torrents matching the supplied filters. :param filter: Current status of the torrents. :param category: Fetch all torrents with the supplied label. :param sort: Sort torrents by. :param reverse: Enable reverse sorting....
[ "def", "torrents", "(", "self", ",", "*", "*", "filters", ")", ":", "params", "=", "{", "}", "for", "name", ",", "value", "in", "filters", ".", "items", "(", ")", ":", "# make sure that old 'status' argument still works", "name", "=", "'filter'", "if", "na...
38.9
17.9
def derive_child_context(self, whence): """Derives a scalar context as a child of the current context.""" return _HandlerContext( container=self.container, queue=self.queue, field_name=None, annotations=None, depth=self.depth, whenc...
[ "def", "derive_child_context", "(", "self", ",", "whence", ")", ":", "return", "_HandlerContext", "(", "container", "=", "self", ".", "container", ",", "queue", "=", "self", ".", "queue", ",", "field_name", "=", "None", ",", "annotations", "=", "None", ","...
34.692308
11.538462
def transitionStates(self,state): """ Return the indices of new states and their rates. """ newstates,rates = self.transition(state) newindices = self.getStateIndex(newstates) return newindices,rates
[ "def", "transitionStates", "(", "self", ",", "state", ")", ":", "newstates", ",", "rates", "=", "self", ".", "transition", "(", "state", ")", "newindices", "=", "self", ".", "getStateIndex", "(", "newstates", ")", "return", "newindices", ",", "rates" ]
39.571429
12.428571
def register_vcs_handler(vcs, method): # tyoe: (str, str) -> typing.Callable # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][m...
[ "def", "register_vcs_handler", "(", "vcs", ",", "method", ")", ":", "# tyoe: (str, str) -> typing.Callable # decorator", "def", "decorate", "(", "f", ")", ":", "\"\"\"Store f in HANDLERS[vcs][method].\"\"\"", "if", "vcs", "not", "in", "HANDLERS", ":", "HANDLERS", "[", ...
39.888889
15.666667
def _run_bcbio_variation(vrn_file, rm_file, rm_interval_file, base_dir, sample, caller, data): """Run validation of a caller against the truth set using bcbio.variation. """ val_config_file = _create_validate_config_file(vrn_file, rm_file, rm_interval_file, ...
[ "def", "_run_bcbio_variation", "(", "vrn_file", ",", "rm_file", ",", "rm_interval_file", ",", "base_dir", ",", "sample", ",", "caller", ",", "data", ")", ":", "val_config_file", "=", "_create_validate_config_file", "(", "vrn_file", ",", "rm_file", ",", "rm_interva...
66.266667
29.4
def get_default_connection_details(): """ Gets the connection details based on environment vars or Thanatos default settings. :return: Returns a dictionary of connection details. :rtype: dict """ return { 'host': os.environ.get('MYSQL_HOST', '127.0.0.1'), 'user': os.environ.get('MY...
[ "def", "get_default_connection_details", "(", ")", ":", "return", "{", "'host'", ":", "os", ".", "environ", ".", "get", "(", "'MYSQL_HOST'", ",", "'127.0.0.1'", ")", ",", "'user'", ":", "os", ".", "environ", ".", "get", "(", "'MYSQL_USER'", ",", "'vagrant'...
35.461538
20.230769
def hscan(key, cursor=0, match=None, count=None, host=None, port=None, db=None, password=None): ''' Incrementally iterate hash fields and associated values. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' redis.hscan foo_hash match='field_prefix_*' count=1 ''' ...
[ "def", "hscan", "(", "key", ",", "cursor", "=", "0", ",", "match", "=", "None", ",", "count", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_conn...
30.214286
29.642857
def convert(data): """ Convert from unicode to native ascii """ try: st = basestring except NameError: st = str if isinstance(data, st): return str(data) elif isinstance(data, Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, Iter...
[ "def", "convert", "(", "data", ")", ":", "try", ":", "st", "=", "basestring", "except", "NameError", ":", "st", "=", "str", "if", "isinstance", "(", "data", ",", "st", ")", ":", "return", "str", "(", "data", ")", "elif", "isinstance", "(", "data", ...
24.1875
13.6875
def _set_cam_share(self, v, load=False): """ Setter method for cam_share, mapped from YANG variable /hardware/profile/tcam/cam_share (container) If this variable is read-only (config: false) in the source YANG file, then _set_cam_share is considered as a private method. Backends looking to populate ...
[ "def", "_set_cam_share", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base...
73.227273
33.863636
def document_delete(index, doc_type, id, hosts=None, profile=None): ''' Delete a document from an index index Index name where the document resides doc_type Type of the document id Document identifier CLI example:: salt myminion elasticsearch.document_delete te...
[ "def", "document_delete", "(", "index", ",", "doc_type", ",", "id", ",", "hosts", "=", "None", ",", "profile", "=", "None", ")", ":", "es", "=", "_get_instance", "(", "hosts", ",", "profile", ")", "try", ":", "return", "es", ".", "delete", "(", "inde...
32.043478
29.173913
def diagnose_embedding(emb, source, target): """A detailed diagnostic for minor embeddings. This diagnostic produces a generator, which lists all issues with `emb`. The errors are yielded in the form ExceptionClass, arg1, arg2,... where the arguments following the class are used to construct ...
[ "def", "diagnose_embedding", "(", "emb", ",", "source", ",", "target", ")", ":", "if", "not", "hasattr", "(", "source", ",", "'edges'", ")", ":", "source", "=", "nx", ".", "Graph", "(", "source", ")", "if", "not", "hasattr", "(", "target", ",", "'edg...
37.175676
25.945946
def humanize_time_since(timestamp=None): """ Returns a fuzzy time since. Will only return the largest time. EX: 20 days, 14 min """ timeDiff = datetime.datetime.now() - timestamp days = timeDiff.days hours = timeDiff.seconds / 3600 minutes = timeDiff.seconds % 3600 / 60 seconds = timeDif...
[ "def", "humanize_time_since", "(", "timestamp", "=", "None", ")", ":", "timeDiff", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "timestamp", "days", "=", "timeDiff", ".", "days", "hours", "=", "timeDiff", ".", "seconds", "/", "3600", "min...
25.682927
16.756098
def do_handshake_with_robot(self): # type: ignore """Modified do_handshake() to send a ROBOT payload and return the result. """ try: # Start the handshake using nassl - will throw WantReadError right away self._ssl.do_handshake() except WantReadError: # Send the Client Hello ...
[ "def", "do_handshake_with_robot", "(", "self", ")", ":", "# type: ignore", "try", ":", "# Start the handshake using nassl - will throw WantReadError right away", "self", ".", "_ssl", ".", "do_handshake", "(", ")", "except", "WantReadError", ":", "# Send the Client Hello", "...
43.344444
22.366667
def get_users(self, user_ids, nid=None): """Get a listing of data for specific users `user_ids` in a network `nid` :type user_ids: list of str :param user_ids: a list of user ids. These are the same ids that are returned by get_all_users. :type nid: str :pa...
[ "def", "get_users", "(", "self", ",", "user_ids", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.get_users\"", ",", "data", "=", "{", "\"ids\"", ":", "user_ids", "}", ",", "nid", "=", "nid", ")", ...
39.65
14.95
def css_text(self, path, default=NULL, smart=False, normalize_space=True): """ Get normalized text of node which matches the css path. """ try: return get_node_text(self.css_one(path), smart=smart, normalize_space=normalize_space) exc...
[ "def", "css_text", "(", "self", ",", "path", ",", "default", "=", "NULL", ",", "smart", "=", "False", ",", "normalize_space", "=", "True", ")", ":", "try", ":", "return", "get_node_text", "(", "self", ".", "css_one", "(", "path", ")", ",", "smart", "...
32.769231
19.230769
def walk(self, dag, walk_func): """ Walks each node of the graph, in parallel if it can. The walk_func is only called when the nodes dependencies have been satisfied """ # First, we'll topologically sort all of the nodes, with nodes that # have no dependencies first. We ...
[ "def", "walk", "(", "self", ",", "dag", ",", "walk_func", ")", ":", "# First, we'll topologically sort all of the nodes, with nodes that", "# have no dependencies first. We do this to ensure that we don't call", "# .join on a thread that hasn't yet been started.", "#", "# TODO(ejholmes):...
35.754386
19.561404
def npz_generator(npz_path): """Generate data from an npz file.""" npz_data = np.load(npz_path) X = npz_data['X'] # Y is a binary maxtrix with shape=(n, k), each y will have shape=(k,) y = npz_data['Y'] n = X.shape[0] while True: i = np.random.randint(0, n) yield {'X': X[i]...
[ "def", "npz_generator", "(", "npz_path", ")", ":", "npz_data", "=", "np", ".", "load", "(", "npz_path", ")", "X", "=", "npz_data", "[", "'X'", "]", "# Y is a binary maxtrix with shape=(n, k), each y will have shape=(k,)", "y", "=", "npz_data", "[", "'Y'", "]", "...
26.75
19