text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def on_redraw(self): """ Called when the Layer should be redrawn. If a subclass uses the :py:meth:`initialize()` Method, it is very important to also call the Super Class Method to prevent crashes. """ super(WidgetLayer,self).on_redraw() if not self._initialized:...
[ "def", "on_redraw", "(", "self", ")", ":", "super", "(", "WidgetLayer", ",", "self", ")", ".", "on_redraw", "(", ")", "if", "not", "self", ".", "_initialized", ":", "self", ".", "initialize", "(", ")", "self", ".", "_initialized", "=", "True" ]
37.8
18.4
def get_slice(self, start_index=None, stop_index=None, as_list=False): """ For sorted Series will return either a Series or list of all of the rows where the index is greater than or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the ...
[ "def", "get_slice", "(", "self", ",", "start_index", "=", "None", ",", "stop_index", "=", "None", ",", "as_list", "=", "False", ")", ":", "if", "not", "self", ".", "_sort", ":", "raise", "RuntimeError", "(", "'Can only use get_slice on sorted Series'", ")", ...
55.346154
35.423077
def get_indices(self, axis=0, index_func=None, old_blocks=None): """This gets the internal indices stored in the partitions. Note: These are the global indices of the object. This is mostly useful when you have deleted rows/columns internally, but do not know which ones were del...
[ "def", "get_indices", "(", "self", ",", "axis", "=", "0", ",", "index_func", "=", "None", ",", "old_blocks", "=", "None", ")", ":", "ErrorMessage", ".", "catch_bugs_and_request_email", "(", "not", "callable", "(", "index_func", ")", ")", "func", "=", "self...
47.203125
24.609375
def find_splice(cigar): '''Takes a cigar string and finds the first splice position as an offset from the start. To find the 5' end (read coords) of the junction for a reverse read, pass in the reversed cigar tuple''' offset = 0 # a soft clip at the end of the read is taken as splicing # where ...
[ "def", "find_splice", "(", "cigar", ")", ":", "offset", "=", "0", "# a soft clip at the end of the read is taken as splicing", "# where as a soft clip at the start is not.", "if", "cigar", "[", "0", "]", "[", "0", "]", "==", "4", ":", "offset", "=", "cigar", "[", ...
31.884615
19.192308
def regexp(input, **params): """ Parses input according to pattern :param input: :param params: :return: """ PARAM_FIELD_TO_PARSE = 'input.field' PARAM_PATTERN = 'pattern' PARAM_OUTPUT = 'output' OUT_DESC_FIELD = 'field' OUT_DESC_IDX = 'idx' OUT_DESC_TYPE = 'type' re...
[ "def", "regexp", "(", "input", ",", "*", "*", "params", ")", ":", "PARAM_FIELD_TO_PARSE", "=", "'input.field'", "PARAM_PATTERN", "=", "'pattern'", "PARAM_OUTPUT", "=", "'output'", "OUT_DESC_FIELD", "=", "'field'", "OUT_DESC_IDX", "=", "'idx'", "OUT_DESC_TYPE", "="...
28.48
16.72
def get_properties(self, mode, name_list=None): """Return properties as list of 2-tuples (name, value). If mode is 'name', then None is returned for the value. name the property name in Clark notation. value may have different types, depending on the status: ...
[ "def", "get_properties", "(", "self", ",", "mode", ",", "name_list", "=", "None", ")", ":", "assert", "mode", "in", "(", "\"allprop\"", ",", "\"name\"", ",", "\"named\"", ")", "if", "mode", "in", "(", "\"allprop\"", ",", "\"name\"", ")", ":", "# TODO: 'a...
37.297872
18.829787
def parse_sections(self, offset): """Fetch the PE file sections. The sections will be readily available in the "sections" attribute. Its attributes will contain all the section information plus "data" a buffer containing the section's data. The "Characteristics" member will be ...
[ "def", "parse_sections", "(", "self", ",", "offset", ")", ":", "self", ".", "sections", "=", "[", "]", "MAX_SIMULTANEOUS_ERRORS", "=", "3", "for", "i", "in", "range", "(", "self", ".", "FILE_HEADER", ".", "NumberOfSections", ")", ":", "if", "i", ">=", ...
48.026786
26.803571
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) try: # Create Web Socket connection on block path ws_connection = client(bma.ws.block) # From the documentation ws_connection should be a ClientWebS...
[ "async", "def", "main", "(", ")", ":", "# Create Client from endpoint string in Duniter format", "client", "=", "Client", "(", "BMAS_ENDPOINT", ")", "try", ":", "# Create Web Socket connection on block path", "ws_connection", "=", "client", "(", "bma", ".", "ws", ".", ...
45.042553
22.489362
def download_version(version, url=None, verbose=False, binary=False): """Download, extract, and build Cassandra tarball. if binary == True, download precompiled tarball, otherwise build from source tarball. """ assert_jdk_valid_for_cassandra_version(version) archive_url = ARCHIVE if CCM_CONFIG...
[ "def", "download_version", "(", "version", ",", "url", "=", "None", ",", "verbose", "=", "False", ",", "binary", "=", "False", ")", ":", "assert_jdk_valid_for_cassandra_version", "(", "version", ")", "archive_url", "=", "ARCHIVE", "if", "CCM_CONFIG", ".", "has...
48.627451
29.352941
def junction_overlap(self,tx,tolerance=0): """Calculate the junction overlap between two transcripts :param tx: Other transcript :type tx: Transcript :param tolerance: how close to consider two junctions as overlapped (default=0) :type tolerance: int :return: Junction Overlap Report :rtype:...
[ "def", "junction_overlap", "(", "self", ",", "tx", ",", "tolerance", "=", "0", ")", ":", "self", ".", "_initialize", "(", ")", "return", "JunctionOverlap", "(", "self", ",", "tx", ",", "tolerance", ")" ]
34.416667
12.916667
def save_npz(object, handle): """Save dict of numpy array as npz file.""" # there is a bug where savez doesn't actually accept a file handle. log.warning("Saving npz files currently only works locally. :/") path = handle.name handle.close() if type(object) is dict: np.savez(path, **objec...
[ "def", "save_npz", "(", "object", ",", "handle", ")", ":", "# there is a bug where savez doesn't actually accept a file handle.", "log", ".", "warning", "(", "\"Saving npz files currently only works locally. :/\"", ")", "path", "=", "handle", ".", "name", "handle", ".", "...
38.307692
17.923077
def import_module(module): """ | Given a module `service`, try to import it. | It will autodiscovers all the entrypoints | and add them in `ENTRYPOINTS`. :param module: The module's name to import. :type module: str :rtype: None :raises ImportError: When the service/module to start is n...
[ "def", "import_module", "(", "module", ")", ":", "try", ":", "__import__", "(", "'{0}.service'", ".", "format", "(", "module", ")", ")", "except", "ImportError", ":", "LOGGER", ".", "error", "(", "'No module/service found. Quit.'", ")", "sys", ".", "exit", "...
29.9375
15.4375
def _getTPDynamicState(self,): """ Parameters: -------------------------------------------- retval: A dict with all the dynamic state variable names as keys and their values at this instant as values. """ tpDynamicState = dict() for variableName in self._getTPDynamicS...
[ "def", "_getTPDynamicState", "(", "self", ",", ")", ":", "tpDynamicState", "=", "dict", "(", ")", "for", "variableName", "in", "self", ".", "_getTPDynamicStateVariableNames", "(", ")", ":", "tpDynamicState", "[", "variableName", "]", "=", "copy", ".", "deepcop...
39.636364
17.090909
def get_inspection_units(logdir='', event_file='', tag=''): """Returns a list of InspectionUnit objects given either logdir or event_file. If logdir is given, the number of InspectionUnits should equal the number of directories or subdirectories that contain event files. If event_file is given, the number of ...
[ "def", "get_inspection_units", "(", "logdir", "=", "''", ",", "event_file", "=", "''", ",", "tag", "=", "''", ")", ":", "if", "logdir", ":", "subdirs", "=", "io_wrapper", ".", "GetLogdirSubdirectories", "(", "logdir", ")", "inspection_units", "=", "[", "]"...
37.489362
20.06383
def logger(): """Access global logger""" global _LOGGER if _LOGGER is None: logging.basicConfig() _LOGGER = logging.getLogger() _LOGGER.setLevel('INFO') return _LOGGER
[ "def", "logger", "(", ")", ":", "global", "_LOGGER", "if", "_LOGGER", "is", "None", ":", "logging", ".", "basicConfig", "(", ")", "_LOGGER", "=", "logging", ".", "getLogger", "(", ")", "_LOGGER", ".", "setLevel", "(", "'INFO'", ")", "return", "_LOGGER" ]
25
13.75
def creationTime(item): """ Returns the creation time of the given item. """ forThisItem = _CreationTime.createdItem == item return item.store.findUnique(_CreationTime, forThisItem).timestamp
[ "def", "creationTime", "(", "item", ")", ":", "forThisItem", "=", "_CreationTime", ".", "createdItem", "==", "item", "return", "item", ".", "store", ".", "findUnique", "(", "_CreationTime", ",", "forThisItem", ")", ".", "timestamp" ]
34.333333
11
def do_interval( sources, index, out, ref_src, start, end, seq_db, missing_data, strand ): """ Join together alignment blocks to create a semi human projected local alignment (small reference sequence deletions are kept as supported by the local alignment). """ ref_src_size = None # Make s...
[ "def", "do_interval", "(", "sources", ",", "index", ",", "out", ",", "ref_src", ",", "start", ",", "end", ",", "seq_db", ",", "missing_data", ",", "strand", ")", ":", "ref_src_size", "=", "None", "# Make sure the reference component is also the first in the source l...
52.059701
20.567164
def createInstance(self, codec=None): """ Creates an instance of the klass. @return: Instance of C{self.klass}. """ if type(self.klass) is type: return self.klass.__new__(self.klass) return self.klass()
[ "def", "createInstance", "(", "self", ",", "codec", "=", "None", ")", ":", "if", "type", "(", "self", ".", "klass", ")", "is", "type", ":", "return", "self", ".", "klass", ".", "__new__", "(", "self", ".", "klass", ")", "return", "self", ".", "klas...
25.5
11.3
def create_self_subject_access_review(self, body, **kwargs): # noqa: E501 """create_self_subject_access_review # noqa: E501 create a SelfSubjectAccessReview # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_r...
[ "def", "create_self_subject_access_review", "(", "self", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ...
62
34.708333
def url_split (url): """Split url in a tuple (scheme, hostname, port, document) where hostname is always lowercased. Precondition: url is syntactically correct URI (eg has no whitespace) """ scheme, netloc = urllib.splittype(url) host, document = urllib.splithost(netloc) port = default_ports...
[ "def", "url_split", "(", "url", ")", ":", "scheme", ",", "netloc", "=", "urllib", ".", "splittype", "(", "url", ")", "host", ",", "document", "=", "urllib", ".", "splithost", "(", "netloc", ")", "port", "=", "default_ports", ".", "get", "(", "scheme", ...
37.75
9.666667
def from_file(cls, filename): '''Create a cube object by loading data from a file. *Arguemnts:* filename The file to load. It must contain the header with the description of the grid and the molecule. ''' with open(filename) as f: ...
[ "def", "from_file", "(", "cls", ",", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "molecule", ",", "origin", ",", "axes", ",", "nrep", ",", "subtitle", ",", "nuclear_charges", "=", "read_cube_header", "(", "f", ")", "data...
35.541667
17.041667
def extract_worker_exc(*arg, **kw): """Get exception added by worker""" _self = arg[0] if not isinstance(_self, StrategyBase): # Run for StrategyBase instance only return # Iterate over workers to get their task and queue for _worker_prc, _main_q, _rslt_q in _self._workers: _...
[ "def", "extract_worker_exc", "(", "*", "arg", ",", "*", "*", "kw", ")", ":", "_self", "=", "arg", "[", "0", "]", "if", "not", "isinstance", "(", "_self", ",", "StrategyBase", ")", ":", "# Run for StrategyBase instance only", "return", "# Iterate over workers t...
34.421053
13.210526
def clean_previous_run(self): """Clean variables from previous configuration, such as schedulers, broks and external commands :return: None """ # Execute the base class treatment... super(Satellite, self).clean_previous_run() # Clean my lists del self.br...
[ "def", "clean_previous_run", "(", "self", ")", ":", "# Execute the base class treatment...", "super", "(", "Satellite", ",", "self", ")", ".", "clean_previous_run", "(", ")", "# Clean my lists", "del", "self", ".", "broks", "[", ":", "]", "del", "self", ".", "...
28.5
15.5
def btc_asset_swap(self, btc_transfer_spec, asset_id, asset_transfer_spec, fees): """ Creates a transaction for swapping assets for bitcoins. :param TransferParameters btc_transfer_spec: The parameters of the bitcoins being transferred. :param bytes asset_id: The ID of the asset being s...
[ "def", "btc_asset_swap", "(", "self", ",", "btc_transfer_spec", ",", "asset_id", ",", "asset_transfer_spec", ",", "fees", ")", ":", "return", "self", ".", "transfer", "(", "[", "(", "asset_id", ",", "asset_transfer_spec", ")", "]", ",", "btc_transfer_spec", ",...
55.25
28.75
def on_configparser_loads(self, configparser, config, content, **kwargs): """ The :mod:`configparser` loads method. :param module configparser: The ``configparser`` module :param class config: The loading config class :param str content: The content to deserialize :return: The d...
[ "def", "on_configparser_loads", "(", "self", ",", "configparser", ",", "config", ",", "content", ",", "*", "*", "kwargs", ")", ":", "return", "INIParser", ".", "from_ini", "(", "content", ")", ".", "to_dict", "(", "delimiter", "=", "kwargs", ".", "pop", ...
36.692308
18.384615
def length_curve(obj): """ Computes the approximate length of the parametric curve. Uses the following equation to compute the approximate length: .. math:: \\sum_{i=0}^{n-1} \\sqrt{P_{i + 1}^2-P_{i}^2} where :math:`n` is number of evaluated curve points and :math:`P` is the n-dimensional po...
[ "def", "length_curve", "(", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "abstract", ".", "Curve", ")", ":", "raise", "GeomdlException", "(", "\"Input shape must be an instance of abstract.Curve class\"", ")", "length", "=", "0.0", "evalpts", "=", ...
29.84
24.04
def _welch_anova(self, dv=None, between=None, export_filename=None): """Return one-way Welch ANOVA.""" aov = welch_anova(data=self, dv=dv, between=between, export_filename=export_filename) return aov
[ "def", "_welch_anova", "(", "self", ",", "dv", "=", "None", ",", "between", "=", "None", ",", "export_filename", "=", "None", ")", ":", "aov", "=", "welch_anova", "(", "data", "=", "self", ",", "dv", "=", "dv", ",", "between", "=", "between", ",", ...
45.8
16.8
def namedb_select_count_rows( cur, query, args, count_column='COUNT(*)' ): """ Execute a SELECT COUNT(*) ... query and return the number of rows. """ count_rows = namedb_query_execute( cur, query, args ) count = 0 for r in count_rows: count = r[count_column] break return...
[ "def", "namedb_select_count_rows", "(", "cur", ",", "query", ",", "args", ",", "count_column", "=", "'COUNT(*)'", ")", ":", "count_rows", "=", "namedb_query_execute", "(", "cur", ",", "query", ",", "args", ")", "count", "=", "0", "for", "r", "in", "count_r...
26.25
16.75
def get_id(self): """override get_id to generate our "magic" id that encodes scaffolding information""" waypoint_index = 0 if 'waypointIndex' in self.my_osid_object._my_map: waypoint_index = self.my_osid_object._my_map['waypointIndex'] # NOTE that the order of the dict **must...
[ "def", "get_id", "(", "self", ")", ":", "waypoint_index", "=", "0", "if", "'waypointIndex'", "in", "self", ".", "my_osid_object", ".", "_my_map", ":", "waypoint_index", "=", "self", ".", "my_osid_object", ".", "_my_map", "[", "'waypointIndex'", "]", "# NOTE th...
47.958333
20.166667
def preprocess(from_idx, to_idx, _params): """ Preprocess: Convert a video into the mouth images """ source_exts = '*.mpg' src_path = _params['src_path'] tgt_path = _params['tgt_path'] face_predictor_path = './shape_predictor_68_face_landmarks.dat' succ = set() fail = set() for ...
[ "def", "preprocess", "(", "from_idx", ",", "to_idx", ",", "_params", ")", ":", "source_exts", "=", "'*.mpg'", "src_path", "=", "_params", "[", "'src_path'", "]", "tgt_path", "=", "_params", "[", "'tgt_path'", "]", "face_predictor_path", "=", "'./shape_predictor_...
34.666667
16.428571
def get_branches(aliases): """Get unique branch names from an alias dictionary.""" ignore = ['pow', 'log10', 'sqrt', 'max'] branches = [] for k, v in aliases.items(): tokens = re.sub('[\(\)\+\*\/\,\=\<\>\&\!\-\|]', ' ', v).split() for t in tokens: if bool(re.search(r'^\d'...
[ "def", "get_branches", "(", "aliases", ")", ":", "ignore", "=", "[", "'pow'", ",", "'log10'", ",", "'sqrt'", ",", "'max'", "]", "branches", "=", "[", "]", "for", "k", ",", "v", "in", "aliases", ".", "items", "(", ")", ":", "tokens", "=", "re", "....
26.777778
23.055556
def upload_file_to_container(block_blob_client, container_name, file_path): """Uploads a local file to an Azure Blob storage container. :param block_blob_client: A blob service client. :type block_blob_client: `azure.storage.blob.BlockBlobService` :param str container_name: The name of the Azure Blob s...
[ "def", "upload_file_to_container", "(", "block_blob_client", ",", "container_name", ",", "file_path", ")", ":", "blob_name", "=", "os", ".", "path", ".", "basename", "(", "file_path", ")", "_log", ".", "info", "(", "'Uploading file {} to container [{}]...'", ".", ...
43.8
24.733333
def _get(self, *args, **kwargs): """Wrapper around Requests for GET requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.get(*args, **kwargs) r...
[ "def", "_get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'timeout'", "not", "in", "kwargs", ":", "kwargs", "[", "'timeout'", "]", "=", "self", ".", "timeout", "req", "=", "self", ".", "session", ".", "get", "(", "*"...
24.384615
16.230769
def _update_labels(self): """Updates list of available labels.""" labels = set() for page in self.get_pages(): for label in page.labels: labels.add(label) to_delete = self._labels - labels for label in labels: self._labels.add(label) ...
[ "def", "_update_labels", "(", "self", ")", ":", "labels", "=", "set", "(", ")", "for", "page", "in", "self", ".", "get_pages", "(", ")", ":", "for", "label", "in", "page", ".", "labels", ":", "labels", ".", "add", "(", "label", ")", "to_delete", "=...
34.090909
6.727273
def delete_security_group(self, name=None, group_id=None): """ Delete a security group from your account. :type name: string :param name: The name of the security group to delete. :type group_id: string :param group_id: The ID of the security group to delete within ...
[ "def", "delete_security_group", "(", "self", ",", "name", "=", "None", ",", "group_id", "=", "None", ")", ":", "params", "=", "{", "}", "if", "name", "is", "not", "None", ":", "params", "[", "'GroupName'", "]", "=", "name", "elif", "group_id", "is", ...
28.318182
19.409091
def vocabulary(self, levels=None): """ :param levels: An optional argument of declaring a single or comma-delimited list of levels is available, as seen in the example as 1. An example of a comma-delimited list of levels is 1,2,5,9. :type levels: str or None http...
[ "def", "vocabulary", "(", "self", ",", "levels", "=", "None", ")", ":", "url", "=", "WANIKANI_BASE", ".", "format", "(", "self", ".", "api_key", ",", "'vocabulary'", ")", "if", "levels", ":", "url", "+=", "'/{0}'", ".", "format", "(", "levels", ")", ...
37.047619
18.666667
def determine_type(x): """Determine the type of x""" types = (int, float, str) _type = filter(lambda a: is_type(a, x), types)[0] return _type(x)
[ "def", "determine_type", "(", "x", ")", ":", "types", "=", "(", "int", ",", "float", ",", "str", ")", "_type", "=", "filter", "(", "lambda", "a", ":", "is_type", "(", "a", ",", "x", ")", ",", "types", ")", "[", "0", "]", "return", "_type", "(",...
31.2
12.6
def _get_sm_scale_in(self, scale_sm=91.1876): """Get an estimate of the SM parameters at the input scale by running them from the EW scale using constant values for the Wilson coefficients (corresponding to their leading log approximated values at the EW scale). Note that this i...
[ "def", "_get_sm_scale_in", "(", "self", ",", "scale_sm", "=", "91.1876", ")", ":", "# intialize a copy of ourselves", "_smeft", "=", "SMEFT", "(", ")", "_smeft", ".", "set_initial", "(", "self", ".", "C_in", ",", "self", ".", "scale_in", ",", "self", ".", ...
57.111111
25.222222
def getKnownPlayers(reset=False): """identify all of the currently defined players""" global playerCache if not playerCache or reset: jsonFiles = os.path.join(c.PLAYERS_FOLDER, "*.json") for playerFilepath in glob.glob(jsonFiles): filename = os.path.basename(playerFilepath) ...
[ "def", "getKnownPlayers", "(", "reset", "=", "False", ")", ":", "global", "playerCache", "if", "not", "playerCache", "or", "reset", ":", "jsonFiles", "=", "os", ".", "path", ".", "join", "(", "c", ".", "PLAYERS_FOLDER", ",", "\"*.json\"", ")", "for", "pl...
42.666667
10.083333
def make_package_index(download_dir): """ Create a pypi server like file structure below download directory. :param download_dir: Download directory with packages. EXAMPLE BEFORE: +-- downloads/ +-- alice-1.0.zip +-- alice-1.0.tar.gz +-- bob-1.3.0.tar.gz ...
[ "def", "make_package_index", "(", "download_dir", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "download_dir", ")", ":", "raise", "ValueError", "(", "\"No such directory: %r\"", "%", "download_dir", ")", "pkg_rootdir", "=", "os", ".", "path", ...
36.081967
16.278689
async def close(self) -> None: """ Explicit exit. If so configured, populate cache to prove for any creds on schemata, cred defs, and rev regs marked of interest in configuration at initialization, archive cache, and purge prior cache archives. :return: current object ""...
[ "async", "def", "close", "(", "self", ")", "->", "None", ":", "LOGGER", ".", "debug", "(", "'Verifier.close >>>'", ")", "if", "self", ".", "cfg", ".", "get", "(", "'archive-on-close'", ",", "{", "}", ")", ":", "await", "self", ".", "load_cache", "(", ...
31.611111
20.5
def _process_phenotypicseries(self, limit): """ Creates classes from the OMIM phenotypic series list. These are grouping classes to hook the more granular OMIM diseases. # TEC what does 'hook' mean here? :param limit: :return: """ if self.test_mode: ...
[ "def", "_process_phenotypicseries", "(", "self", ",", "limit", ")", ":", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", ".", "graph", "LOG", ".", "info", "(", "\"getting phenotypic series title...
39.8125
18.1875
def _encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext :param cipher: A unicode string of "aes128", "aes192", "aes256", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-32 bytes long :param data: ...
[ "def", "_encrypt", "(", "cipher", ",", "key", ",", "data", ",", "iv", ",", "padding", ")", ":", "if", "not", "isinstance", "(", "key", ",", "byte_cls", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n key must be a byte string, not...
29.555556
22.444444
def load_obo_file(self, obo_file, optional_attrs, load_obsolete, prt): """Read obo file. Store results.""" reader = OBOReader(obo_file, optional_attrs) # Save alt_ids and their corresponding main GO ID. Add to GODag after populating GO Terms alt2rec = {} for rec in reader: ...
[ "def", "load_obo_file", "(", "self", ",", "obo_file", ",", "optional_attrs", ",", "load_obsolete", ",", "prt", ")", ":", "reader", "=", "OBOReader", "(", "obo_file", ",", "optional_attrs", ")", "# Save alt_ids and their corresponding main GO ID. Add to GODag after populat...
38.137931
16.448276
def c_to_n(self, c_interval): """convert a transcript CDS (c.) interval to a transcript cDNA (n.) interval""" if self.cds_start_i is None: # cds_start_i defined iff cds_end_i defined; see assertion above raise HGVSUsageError( "CDS is undefined for {self.tx_ac}; cannot map...
[ "def", "c_to_n", "(", "self", ",", "c_interval", ")", ":", "if", "self", ".", "cds_start_i", "is", "None", ":", "# cds_start_i defined iff cds_end_i defined; see assertion above", "raise", "HGVSUsageError", "(", "\"CDS is undefined for {self.tx_ac}; cannot map from c. coordinat...
52.529412
25.852941
def use_options(self, options, extractor=None): """ If extractor isn't specified, then just update self.values with options. Otherwise update values with whatever the result of calling extractor with our template and these options returns Also make sure all keys...
[ "def", "use_options", "(", "self", ",", "options", ",", "extractor", "=", "None", ")", ":", "# Extract if necessary", "if", "not", "extractor", ":", "extracted", "=", "options", "else", ":", "extracted", "=", "extractor", "(", "self", ".", "template", ",", ...
36.083333
17.75
def setdummies(self,e): """creates and defines all needed dummy vertices for edge e. """ v0,v1 = e.v r0,r1 = self.grx[v0].rank,self.grx[v1].rank if r0>r1: assert e in self.alt_e v0,v1 = v1,v0 r0,r1 = r1,r0 if (r1-r0)>1: # "d...
[ "def", "setdummies", "(", "self", ",", "e", ")", ":", "v0", ",", "v1", "=", "e", ".", "v", "r0", ",", "r1", "=", "self", ".", "grx", "[", "v0", "]", ".", "rank", ",", "self", ".", "grx", "[", "v1", "]", ".", "rank", "if", "r0", ">", "r1",...
32.705882
11.823529
def sha256(filepath, blocksize=65536): """Generate SHA 256 hash for file at `filepath`""" hasher = hashlib.sha256() fo = open(filepath, 'rb') buf = fo.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = fo.read(blocksize) return hasher.hexdigest()
[ "def", "sha256", "(", "filepath", ",", "blocksize", "=", "65536", ")", ":", "hasher", "=", "hashlib", ".", "sha256", "(", ")", "fo", "=", "open", "(", "filepath", ",", "'rb'", ")", "buf", "=", "fo", ".", "read", "(", "blocksize", ")", "while", "len...
32
9.555556
def _addLoggingOptions(addOptionFn): """Adds logging options """ ################################################## # BEFORE YOU ADD OR REMOVE OPTIONS TO THIS FUNCTION, KNOW THAT # YOU MAY ONLY USE VARIABLES ACCEPTED BY BOTH optparse AND argparse # FOR EXAMPLE, YOU MAY NOT USE default=%default O...
[ "def", "_addLoggingOptions", "(", "addOptionFn", ")", ":", "##################################################", "# BEFORE YOU ADD OR REMOVE OPTIONS TO THIS FUNCTION, KNOW THAT", "# YOU MAY ONLY USE VARIABLES ACCEPTED BY BOTH optparse AND argparse", "# FOR EXAMPLE, YOU MAY NOT USE default=%default...
52.64
22.56
def nodeDumpOutput(self, doc, cur, level, format, encoding): """Dump an XML node, recursive behaviour, children are printed too. Note that @format = 1 provide node indenting only if xmlIndentTreeOutput = 1 or xmlKeepBlanksDefault(0) was called """ if doc is None: doc__o = ...
[ "def", "nodeDumpOutput", "(", "self", ",", "doc", ",", "cur", ",", "level", ",", "format", ",", "encoding", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "if", "cur", "is", "None", ...
50
14.5
def saveFormatFileTo(self, cur, encoding, format): """Dump an XML document to an I/O buffer. Warning ! This call xmlOutputBufferClose() on buf which is not available after this call. """ if cur is None: cur__o = None else: cur__o = cur._o ret = libxml2mod.xmlSaveForm...
[ "def", "saveFormatFileTo", "(", "self", ",", "cur", ",", "encoding", ",", "format", ")", ":", "if", "cur", "is", "None", ":", "cur__o", "=", "None", "else", ":", "cur__o", "=", "cur", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlSaveFormatFileTo", "("...
46.875
14.125
def Decrypt(self, encrypted_data): """Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data. """ index_split = -(len(encrypted_data) % AES.block_size) if index_split: remaining_encr...
[ "def", "Decrypt", "(", "self", ",", "encrypted_data", ")", ":", "index_split", "=", "-", "(", "len", "(", "encrypted_data", ")", "%", "AES", ".", "block_size", ")", "if", "index_split", ":", "remaining_encrypted_data", "=", "encrypted_data", "[", "index_split"...
29.368421
20.947368
def raise_(exception=ABSENT, *args, **kwargs): """Raise (or re-raises) an exception. :param exception: Exception object to raise, or an exception class. In the latter case, remaining arguments are passed to the exception's constructor. If omitte...
[ "def", "raise_", "(", "exception", "=", "ABSENT", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "exception", "is", "ABSENT", ":", "raise", "else", ":", "if", "inspect", ".", "isclass", "(", "exception", ")", ":", "raise", "exception", "(...
38.833333
18.722222
def send_msg(from_addr: str, to_addrs: Union[str, List[str]], host: str, user: str, password: str, port: int = None, use_tls: bool = True, msg: email.mime.multipart.MIMEMultipart = None, msg_string: str = None) -> No...
[ "def", "send_msg", "(", "from_addr", ":", "str", ",", "to_addrs", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "host", ":", "str", ",", "user", ":", "str", ",", "password", ":", "str", ",", "port", ":", "int", "=", "None", ...
29.863014
20.60274
def abort(self): """Abort by aborting the :attr:`transport` """ if self.transport: self.transport.abort() self.event('connection_lost').fire()
[ "def", "abort", "(", "self", ")", ":", "if", "self", ".", "transport", ":", "self", ".", "transport", ".", "abort", "(", ")", "self", ".", "event", "(", "'connection_lost'", ")", ".", "fire", "(", ")" ]
30.166667
8
def _draw_messages(self, painter): """ Draw messages from all subclass of CheckerMode currently installed on the editor. :type painter: QtGui.QPainter """ checker_modes = [] for m in self.editor.modes: if isinstance(m, modes.CheckerMode): ...
[ "def", "_draw_messages", "(", "self", ",", "painter", ")", ":", "checker_modes", "=", "[", "]", "for", "m", "in", "self", ".", "editor", ".", "modes", ":", "if", "isinstance", "(", "m", ",", "modes", ".", "CheckerMode", ")", ":", "checker_modes", ".", ...
38.47619
9.52381
def server_shutdown(server_state): """ Shut down server subsystems. Remove PID file. """ set_running( False ) # stop API servers rpc_stop(server_state) api_stop(server_state) # stop atlas node server_atlas_shutdown(server_state) # stopping GC gc_stop() # clear PID...
[ "def", "server_shutdown", "(", "server_state", ")", ":", "set_running", "(", "False", ")", "# stop API servers", "rpc_stop", "(", "server_state", ")", "api_stop", "(", "server_state", ")", "# stop atlas node", "server_atlas_shutdown", "(", "server_state", ")", "# stop...
18.12
20.76
def delete(self, *args, **kwargs): """ Delete the image, along with any generated thumbnails. """ source_cache = self.get_source_cache() # First, delete any related thumbnails. self.delete_thumbnails(source_cache) # Next, delete the source image. super(Thu...
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "source_cache", "=", "self", ".", "get_source_cache", "(", ")", "# First, delete any related thumbnails.", "self", ".", "delete_thumbnails", "(", "source_cache", ")", "# Next, del...
41.5
8.5
def Poynting(self): r'''Poynting correction factor [dimensionless] for use in phase equilibria methods based on activity coefficients or other reference states. Performs the shortcut calculation assuming molar volume is independent of pressure. .. math:: \text{Poy...
[ "def", "Poynting", "(", "self", ")", ":", "Vml", ",", "Psat", "=", "self", ".", "Vml", ",", "self", ".", "Psat", "if", "Vml", "and", "Psat", ":", "return", "exp", "(", "Vml", "*", "(", "self", ".", "P", "-", "Psat", ")", "/", "R", "/", "self"...
34.058824
24.823529
def looks_like_gene(self): '''Returns true iff: length >=6, length is a multiple of 3, first codon is start, last codon is a stop and has no other stop codons''' return self.is_complete_orf() \ and len(self) >= 6 \ and len(self) %3 == 0 \ and self.seq[0:3].upper() in geneti...
[ "def", "looks_like_gene", "(", "self", ")", ":", "return", "self", ".", "is_complete_orf", "(", ")", "and", "len", "(", "self", ")", ">=", "6", "and", "len", "(", "self", ")", "%", "3", "==", "0", "and", "self", ".", "seq", "[", "0", ":", "3", ...
57.166667
27.833333
def DEFINE_multichoice(self, name, default, choices, help, constant=False): """Choose multiple options from a list.""" self.AddOption( type_info.MultiChoice( name=name, default=default, choices=choices, description=help), constant=constant)
[ "def", "DEFINE_multichoice", "(", "self", ",", "name", ",", "default", ",", "choices", ",", "help", ",", "constant", "=", "False", ")", ":", "self", ".", "AddOption", "(", "type_info", ".", "MultiChoice", "(", "name", "=", "name", ",", "default", "=", ...
45.166667
19.166667
def get_mappings(cls, index_name, doc_type): """ fetch mapped-items structure from cache """ return cache.get(cls.get_cache_item_name(index_name, doc_type), {})
[ "def", "get_mappings", "(", "cls", ",", "index_name", ",", "doc_type", ")", ":", "return", "cache", ".", "get", "(", "cls", ".", "get_cache_item_name", "(", "index_name", ",", "doc_type", ")", ",", "{", "}", ")" ]
58
13
def mmap_key(metric_name, name, labelnames, labelvalues): """Format a key for use in the mmap file.""" # ensure labels are in consistent order for identity labels = dict(zip(labelnames, labelvalues)) return json.dumps([metric_name, name, labels], sort_keys=True)
[ "def", "mmap_key", "(", "metric_name", ",", "name", ",", "labelnames", ",", "labelvalues", ")", ":", "# ensure labels are in consistent order for identity", "labels", "=", "dict", "(", "zip", "(", "labelnames", ",", "labelvalues", ")", ")", "return", "json", ".", ...
54.8
13.2
def get(self, wg_uuid, uuid, tree=False): """ Get one workgroup member.""" url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % { 'base': self.local_base_url, 'wg_uuid': wg_uuid, 'uuid': uuid } param = {} if tree: param['tree'] = True ...
[ "def", "get", "(", "self", ",", "wg_uuid", ",", "uuid", ",", "tree", "=", "False", ")", ":", "url", "=", "\"%(base)s/%(wg_uuid)s/nodes/%(uuid)s\"", "%", "{", "'base'", ":", "self", ".", "local_base_url", ",", "'wg_uuid'", ":", "wg_uuid", ",", "'uuid'", ":"...
29.6
12.533333
def on_map_long_clicked(self, pos): """ Called when the map is clicked """ d = self.declaration d.clicked({ 'click': 'long', 'position': tuple(pos) })
[ "def", "on_map_long_clicked", "(", "self", ",", "pos", ")", ":", "d", "=", "self", ".", "declaration", "d", ".", "clicked", "(", "{", "'click'", ":", "'long'", ",", "'position'", ":", "tuple", "(", "pos", ")", "}", ")" ]
28.571429
12.285714
def update_family(self, *args, **kwargs): """Pass through to provider FamilyAdminSession.update_family""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.update_bin # OSID spec does not require returning updated catalog return Family( self._p...
[ "def", "update_family", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.BinAdminSession.update_bin", "# OSID spec does not require returning updated catalog", "return", "Family", "(", "self", ".",...
47.4
14.9
def check_city(self, token): """ Check if there is a known city from our city list. Must come before the suffix. """ shortened_cities = {'saint': 'st.'} if self.city is None and self.state is not None and self.street_suffix is None: if token.lower() in self.parser.cit...
[ "def", "check_city", "(", "self", ",", "token", ")", ":", "shortened_cities", "=", "{", "'saint'", ":", "'st.'", "}", "if", "self", ".", "city", "is", "None", "and", "self", ".", "state", "is", "not", "None", "and", "self", ".", "street_suffix", "is", ...
57
26.241379
def pop_aggregations_params(self): """ Pop and return aggregation params from query string params. Aggregation params are expected to be prefixed(nested under) by any of `self._aggregations_keys`. """ from nefertari.view import BaseView self._query_params = BaseView.conv...
[ "def", "pop_aggregations_params", "(", "self", ")", ":", "from", "nefertari", ".", "view", "import", "BaseView", "self", ".", "_query_params", "=", "BaseView", ".", "convert_dotted", "(", "self", ".", "view", ".", "_query_params", ")", "for", "key", "in", "s...
39.357143
15.357143
def fixpoint(self, clamping, steps=0): """ Computes the fixpoint with respect to a given :class:`caspo.core.clamping.Clamping` Parameters ---------- clamping : :class:`caspo.core.clamping.Clamping` The clamping with respect to the fixpoint is computed steps ...
[ "def", "fixpoint", "(", "self", ",", "clamping", ",", "steps", "=", "0", ")", ":", "current", "=", "dict", ".", "fromkeys", "(", "self", ".", "variables", "(", ")", ",", "0", ")", "updated", "=", "self", ".", "step", "(", "current", ",", "clamping"...
36.142857
23.642857
def mlt(cls, like_text, fields=None, percent_terms_to_match=None, min_term_freq=None, max_query_terms=None, stop_words=None, min_doc_freq=None, max_doc_freq=None, min_word_len=None, max_word_len=None, boost_terms=None, boost=None, analyzer=None): ''' http://www.elasticsearch.org/guide/reference/query-ds...
[ "def", "mlt", "(", "cls", ",", "like_text", ",", "fields", "=", "None", ",", "percent_terms_to_match", "=", "None", ",", "min_term_freq", "=", "None", ",", "max_query_terms", "=", "None", ",", "stop_words", "=", "None", ",", "min_doc_freq", "=", "None", ",...
56.69697
27.30303
def as_conll(self): """Represent this Token as a line as a string in CoNLL-X format.""" def get(field): value = getattr(self, field) if value is None: value = '_' elif field == 'feats': value = '|'.join(value) return str(val...
[ "def", "as_conll", "(", "self", ")", ":", "def", "get", "(", "field", ")", ":", "value", "=", "getattr", "(", "self", ",", "field", ")", "if", "value", "is", "None", ":", "value", "=", "'_'", "elif", "field", "==", "'feats'", ":", "value", "=", "...
37.8
10.3
def upload(identifier, files, metadata=None, headers=None, access_key=None, secret_key=None, queue_derive=None, verbose=None, verify=None, checksum=None, delete=None, retries=None, retries_sleep=None...
[ "def", "upload", "(", "identifier", ",", "files", ",", "metadata", "=", "None", ",", "headers", "=", "None", ",", "access_key", "=", "None", ",", "secret_key", "=", "None", ",", "queue_derive", "=", "None", ",", "verbose", "=", "None", ",", "verify", "...
36.166667
22.178571
def get_quant_NAs(quantdata, quantheader): """Takes quantdata in a dict and header with quantkeys (eg iTRAQ isotopes). Returns dict of quant intensities with missing keys set to NA.""" out = {} for qkey in quantheader: out[qkey] = quantdata.get(qkey, 'NA') return out
[ "def", "get_quant_NAs", "(", "quantdata", ",", "quantheader", ")", ":", "out", "=", "{", "}", "for", "qkey", "in", "quantheader", ":", "out", "[", "qkey", "]", "=", "quantdata", ".", "get", "(", "qkey", ",", "'NA'", ")", "return", "out" ]
36.5
11.375
def trace(fn=None, profiler=None) -> Callable: ''' This decorator allows you to visually trace the steps of a function as it executes to see what happens to the data as things are being processed. If you want to use a custom profiler, use the @trace(profiler=my_custom_profil...
[ "def", "trace", "(", "fn", "=", "None", ",", "profiler", "=", "None", ")", "->", "Callable", ":", "# analyze usage", "custom_profiler", "=", "fn", "is", "None", "and", "profiler", "is", "not", "None", "no_profiler", "=", "profiler", "is", "None", "and", ...
30.296296
15.148148
def ohlc(n=100): """ Returns a DataFrame with the required format for a candlestick or ohlc plot df[['open','high','low','close']] Parameters: ----------- n : int Number of ohlc points """ index=pd.date_range('1/1/15',periods=n*288,freq='5min',tz='utc') data=np.random.randn(n*288) data[0]=np.array(...
[ "def", "ohlc", "(", "n", "=", "100", ")", ":", "index", "=", "pd", ".", "date_range", "(", "'1/1/15'", ",", "periods", "=", "n", "*", "288", ",", "freq", "=", "'5min'", ",", "tz", "=", "'utc'", ")", "data", "=", "np", ".", "random", ".", "randn...
21.772727
18.181818
def do_processlist(self, arg): """ pl - show the processes being debugged processlist - show the processes being debugged """ if self.cmdprefix: raise CmdError("prefix not allowed") if arg: raise CmdError("too many arguments") system = se...
[ "def", "do_processlist", "(", "self", ",", "arg", ")", ":", "if", "self", ".", "cmdprefix", ":", "raise", "CmdError", "(", "\"prefix not allowed\"", ")", "if", "arg", ":", "raise", "CmdError", "(", "\"too many arguments\"", ")", "system", "=", "self", ".", ...
38.045455
11.681818
def build_wheel_graph(num_nodes): """Builds a wheel graph with the specified number of nodes. Ref: http://mathworld.wolfram.com/WheelGraph.html""" # The easiest way to build a wheel graph is to build # C_n-1 and then add a hub node and spoke edges graph = build_cycle_graph(num_nodes - 1) cyc...
[ "def", "build_wheel_graph", "(", "num_nodes", ")", ":", "# The easiest way to build a wheel graph is to build", "# C_n-1 and then add a hub node and spoke edges", "graph", "=", "build_cycle_graph", "(", "num_nodes", "-", "1", ")", "cycle_graph_vertices", "=", "graph", ".", "g...
34.928571
14.928571
def _get_html_response(url, session): # type: (str, PipSession) -> Response """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large...
[ "def", "_get_html_response", "(", "url", ",", "session", ")", ":", "# type: (str, PipSession) -> Response", "if", "_is_url_like_archive", "(", "url", ")", ":", "_ensure_html_response", "(", "url", ",", "session", "=", "session", ")", "logger", ".", "debug", "(", ...
42.387755
21.693878
def gene_name(st, exclude=("ev",), sep="."): """ Helper functions in the BLAST filtering to get rid alternative splicings. This is ugly, but different annotation groups are inconsistent with respect to how the alternative splicings are named. Mostly it can be done by removing the suffix, except for ...
[ "def", "gene_name", "(", "st", ",", "exclude", "=", "(", "\"ev\"", ",", ")", ",", "sep", "=", "\".\"", ")", ":", "if", "any", "(", "st", ".", "startswith", "(", "x", ")", "for", "x", "in", "exclude", ")", ":", "sep", "=", "None", "st", "=", "...
32.772727
21.045455
def rescale_array_from_z1z2(array_rs, coef_rs=None): """Restore the values in a numpy array rescaled to the [z1,z2] interval. The transformation is carried out following the relation array = (array_rs + c_flux)/b_flux as explained in Appendix B1 of Cardiel (2009, MNRAS, 396, 680) Parameters --...
[ "def", "rescale_array_from_z1z2", "(", "array_rs", ",", "coef_rs", "=", "None", ")", ":", "if", "type", "(", "array_rs", ")", "is", "not", "np", ".", "ndarray", ":", "raise", "ValueError", "(", "\"array_rs=\"", "+", "str", "(", "array_rs", ")", "+", "\"m...
29.454545
21.606061
def show_clusters(data, clusters, noise=None): """! @brief Display CLIQUE clustering results. @param[in] data (list): Data that was used for clustering. @param[in] clusters (array_like): Clusters that were allocated by the algorithm. @param[in] noise (array_like): Noise th...
[ "def", "show_clusters", "(", "data", ",", "clusters", ",", "noise", "=", "None", ")", ":", "visualizer", "=", "cluster_visualizer", "(", ")", "visualizer", ".", "append_clusters", "(", "clusters", ",", "data", ")", "visualizer", ".", "append_cluster", "(", "...
42
20.538462
def stop_reactor(): """Stop the reactor and join the reactor thread until it stops. Call this function in teardown at the module or package level to reset the twisted system after your tests. You *must* do this if you mix tests using these tools and tests using twisted.trial. """ global _twisted...
[ "def", "stop_reactor", "(", ")", ":", "global", "_twisted_thread", "def", "stop_reactor", "(", ")", ":", "'''Helper for calling stop from withing the thread.'''", "reactor", ".", "stop", "(", ")", "reactor", ".", "callFromThread", "(", "stop_reactor", ")", "reactor_th...
33.444444
17.777778
def strip_project_url(url): """strip proto:// | openstack/ prefixes and .git | -distgit suffixes""" m = re.match(r'(?:[^:]+://)?(.*)', url) if m: url = m.group(1) if url.endswith('.git'): url, _, _ = url.rpartition('.') if url.endswith('-distgit'): url, _, _ = url.rpartition(...
[ "def", "strip_project_url", "(", "url", ")", ":", "m", "=", "re", ".", "match", "(", "r'(?:[^:]+://)?(.*)'", ",", "url", ")", "if", "m", ":", "url", "=", "m", ".", "group", "(", "1", ")", "if", "url", ".", "endswith", "(", "'.git'", ")", ":", "ur...
34.230769
9.076923
def add_view(self, request, **kwargs): """A custom add_view, to catch exceptions from 'save_model'. Just to be clear, this is very filthy. """ try: return super(ClonedRepoAdmin, self).add_view(request, **kwargs) except ValidationError: # Rerender the f...
[ "def", "add_view", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "super", "(", "ClonedRepoAdmin", ",", "self", ")", ".", "add_view", "(", "request", ",", "*", "*", "kwargs", ")", "except", "ValidationError", ":",...
38.3
14.2
def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) ...
[ "def", "_modeldesc_from_dict", "(", "self", ",", "d", ")", ":", "lhs_termlist", "=", "[", "Term", "(", "[", "LookupFactor", "(", "d", "[", "'lhs_termlist'", "]", "[", "0", "]", ")", "]", ")", "]", "rhs_termlist", "=", "[", "]", "for", "name", "in", ...
37.833333
15.666667
def connect_params(self): """Return a tuple of parameters suitable for passing to Connection.connect that can be used to make a new connection to the same controller (and model if specified. The first element in the returned tuple holds the endpoint argument; the other holds a di...
[ "def", "connect_params", "(", "self", ")", ":", "return", "{", "'endpoint'", ":", "self", ".", "endpoint", ",", "'uuid'", ":", "self", ".", "uuid", ",", "'username'", ":", "self", ".", "username", ",", "'password'", ":", "self", ".", "password", ",", "...
40
12.352941
def convert_time(time): """Convert a time string into 24-hour time.""" split_time = time.split() try: # Get rid of period in a.m./p.m. am_pm = split_time[1].replace('.', '') time_str = '{0} {1}'.format(split_time[0], am_pm) except IndexError: return time try: ...
[ "def", "convert_time", "(", "time", ")", ":", "split_time", "=", "time", ".", "split", "(", ")", "try", ":", "# Get rid of period in a.m./p.m.", "am_pm", "=", "split_time", "[", "1", "]", ".", "replace", "(", "'.'", ",", "''", ")", "time_str", "=", "'{0}...
31.8
16.333333
def remove(module, details=False): ''' Attempt to remove a Perl module that was installed from CPAN. Because the ``cpan`` command doesn't actually support "uninstall"-like functionality, this function will attempt to do what it can, with what it has from CPAN. Until this function is declared stable...
[ "def", "remove", "(", "module", ",", "details", "=", "False", ")", ":", "ret", "=", "{", "'old'", ":", "None", ",", "'new'", ":", "None", ",", "}", "info", "=", "show", "(", "module", ")", "if", "'error'", "in", "info", ":", "return", "{", "'erro...
27.2
22.369231
def _generate_graph(self, name, title, stats_data, y_name): """ Generate a downloads graph; append it to ``self._graphs``. :param name: HTML name of the graph, also used in ``self.GRAPH_KEYS`` :type name: str :param title: human-readable title for the graph :type title: ...
[ "def", "_generate_graph", "(", "self", ",", "name", ",", "title", ",", "stats_data", ",", "y_name", ")", ":", "logger", ".", "debug", "(", "'Generating chart data for %s graph'", ",", "name", ")", "orig_data", ",", "labels", "=", "self", ".", "_data_dict_to_bo...
38.962963
15.407407
def click_left(x = None, y = None, hold_time = 0): """ Simulates a mouse left click on pixel (x,y) if x and y are provided If x and y are not passed to this function, a mouse click is simulated at the current (x,y) :param x: target x-ordinate :param y: target y-ordinate :param hold_time: length...
[ "def", "click_left", "(", "x", "=", "None", ",", "y", "=", "None", ",", "hold_time", "=", "0", ")", ":", "if", "not", "x", "or", "not", "y", ":", "cursor", "=", "win32api", ".", "GetCursorPos", "(", ")", "if", "not", "x", ":", "x", "=", "cursor...
33.047619
20.571429
def log_into(self, target, before_priv_drop=True): """Simple file or UDP logging. .. note:: This doesn't require any Logger plugin and can be used if no log routing is required. :param str|unicode target: Filepath or UDP address. :param bool before_priv_drop: Whether to lo...
[ "def", "log_into", "(", "self", ",", "target", ",", "before_priv_drop", "=", "True", ")", ":", "command", "=", "'logto'", "if", "not", "before_priv_drop", ":", "command", "+=", "'2'", "self", ".", "_set", "(", "command", ",", "target", ")", "return", "se...
26.684211
23.578947
def bind(self, queue, exchange, routing_key='', nowait=True, arguments={}, ticket=None, cb=None): ''' bind to a queue. ''' nowait = nowait and self.allow_nowait() and not cb args = Writer() args.write_short(ticket or self.default_ticket).\ write_...
[ "def", "bind", "(", "self", ",", "queue", ",", "exchange", ",", "routing_key", "=", "''", ",", "nowait", "=", "True", ",", "arguments", "=", "{", "}", ",", "ticket", "=", "None", ",", "cb", "=", "None", ")", ":", "nowait", "=", "nowait", "and", "...
34.736842
17.894737
def ghz_circuit(qubits: Qubits) -> Circuit: """Returns a circuit that prepares a multi-qubit Bell state from the zero state. """ circ = Circuit() circ += H(qubits[0]) for q0 in range(0, len(qubits)-1): circ += CNOT(qubits[q0], qubits[q0+1]) return circ
[ "def", "ghz_circuit", "(", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "circ", "=", "Circuit", "(", ")", "circ", "+=", "H", "(", "qubits", "[", "0", "]", ")", "for", "q0", "in", "range", "(", "0", ",", "len", "(", "qubits", ")", "-", "1...
25.454545
16.545455
def hydrate_input_uploads(input_, input_schema, hydrate_values=True): """Hydrate input basic:upload types with upload location. Find basic:upload fields in input. Add the upload location for relative paths. """ from resolwe.flow.managers import manager files = [] for field_schema, fields ...
[ "def", "hydrate_input_uploads", "(", "input_", ",", "input_schema", ",", "hydrate_values", "=", "True", ")", ":", "from", "resolwe", ".", "flow", ".", "managers", "import", "manager", "files", "=", "[", "]", "for", "field_schema", ",", "fields", "in", "itera...
39.633333
20.633333
def pdf(self, mu): """ PDF for Laplace prior Parameters ---------- mu : float Latent variable for which the prior is being formed over Returns ---------- - p(mu) """ if self.transform is not None: mu = self.transfo...
[ "def", "pdf", "(", "self", ",", "mu", ")", ":", "if", "self", ".", "transform", "is", "not", "None", ":", "mu", "=", "self", ".", "transform", "(", "mu", ")", "return", "ss", ".", "laplace", ".", "pdf", "(", "mu", ",", "self", ".", "loc0", ",",...
24.0625
19.3125
def add_data(self, id, key, value): """Add new data item. :param str id: Entry id within ``SDfile``. :param str key: Data item key. :param str value: Data item value. :return: None. :rtype: :py:obj:`None`. """ self[str(id)]['data'].setdefault(key, []) ...
[ "def", "add_data", "(", "self", ",", "id", ",", "key", ",", "value", ")", ":", "self", "[", "str", "(", "id", ")", "]", "[", "'data'", "]", ".", "setdefault", "(", "key", ",", "[", "]", ")", "self", "[", "str", "(", "id", ")", "]", "[", "'d...
32.272727
9.363636
def efield(self): """Compute the electrostatic potential at each atom due to other atoms""" result = np.zeros((self.numc,3), float) for index1 in range(self.numc): result[index1] = self.efield_component(index1) return result
[ "def", "efield", "(", "self", ")", ":", "result", "=", "np", ".", "zeros", "(", "(", "self", ".", "numc", ",", "3", ")", ",", "float", ")", "for", "index1", "in", "range", "(", "self", ".", "numc", ")", ":", "result", "[", "index1", "]", "=", ...
43.833333
11.333333
def restore_sys_modules(scrubbed): """ Add any previously scrubbed modules back to the sys.modules cache, but only if it's safe to do so. """ clash = set(sys.modules) & set(scrubbed) if len(clash) != 0: # If several, choose one arbitrarily to raise an exception about first = list...
[ "def", "restore_sys_modules", "(", "scrubbed", ")", ":", "clash", "=", "set", "(", "sys", ".", "modules", ")", "&", "set", "(", "scrubbed", ")", "if", "len", "(", "clash", ")", "!=", "0", ":", "# If several, choose one arbitrarily to raise an exception about", ...
38.583333
11.75
def set_sni_dir_params(self, dir, ciphers=None): """Enable checking for cert/key/client_ca file in the specified directory and create a sni/ssl context on demand. Expected filenames: * <sni-name>.crt * <sni-name>.key * <sni-name>.ca - this file is optional ...
[ "def", "set_sni_dir_params", "(", "self", ",", "dir", ",", "ciphers", "=", "None", ")", ":", "self", ".", "_set", "(", "'sni-dir'", ",", "dir", ")", "self", ".", "_set", "(", "'sni-dir-ciphers'", ",", "ciphers", ")", "return", "self", ".", "_section" ]
27.962963
21
def update(self, value): """ search order for local (i.e., @variable) variables: scope, key_variable [('locals', 'local_name'), ('globals', 'local_name'), ('locals', 'key'), ('globals', 'key')] """ key = self.name # if it's a variable ...
[ "def", "update", "(", "self", ",", "value", ")", ":", "key", "=", "self", ".", "name", "# if it's a variable name (otherwise a constant)", "if", "isinstance", "(", "key", ",", "str", ")", ":", "self", ".", "env", ".", "swapkey", "(", "self", ".", "local_na...
27.058824
16.823529