text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
async def write(self, data, eof = False, buffering = True): """ Write output to current output stream """ if not self.outputstream: self.outputstream = Stream() self._startResponse() elif (not buffering or eof) and not self._sendHeaders: self._...
[ "async", "def", "write", "(", "self", ",", "data", ",", "eof", "=", "False", ",", "buffering", "=", "True", ")", ":", "if", "not", "self", ".", "outputstream", ":", "self", ".", "outputstream", "=", "Stream", "(", ")", "self", ".", "_startResponse", ...
41.166667
9.666667
def set_output_fields(self, output_fields): """Defines where to put the dictionary output of the extractor in the doc, but renames the fields of the extracted output for the document or just filters the keys""" if isinstance(output_fields, dict) or isinstance(output_fields, list): se...
[ "def", "set_output_fields", "(", "self", ",", "output_fields", ")", ":", "if", "isinstance", "(", "output_fields", ",", "dict", ")", "or", "isinstance", "(", "output_fields", ",", "list", ")", ":", "self", ".", "output_fields", "=", "output_fields", "elif", ...
59.272727
18.818182
def cf_array_from_list(values): """ Creates a CFArrayRef object from a list of CF* type objects. :param values: A list of CF* type object :return: A CFArrayRef """ length = len(values) values = (CFTypeRef * length)(*values) retur...
[ "def", "cf_array_from_list", "(", "values", ")", ":", "length", "=", "len", "(", "values", ")", "values", "=", "(", "CFTypeRef", "*", "length", ")", "(", "*", "values", ")", "return", "CoreFoundation", ".", "CFArrayCreate", "(", "CoreFoundation", ".", "kCF...
25.736842
16.263158
def process_tokens(self, tokens): u""" Iterate other tokens to find strings and ensure that they are prefixed. :param tokens: :return: """ for (tok_type, token, (start_row, _), _, _) in tokens: if tok_type == tokenize.STRING: self._check_string...
[ "def", "process_tokens", "(", "self", ",", "tokens", ")", ":", "for", "(", "tok_type", ",", "token", ",", "(", "start_row", ",", "_", ")", ",", "_", ",", "_", ")", "in", "tokens", ":", "if", "tok_type", "==", "tokenize", ".", "STRING", ":", "self",...
36.666667
13.888889
def _send_message_with_response(self, operation, read_preference=None, exhaust=False, address=None): """Send a message to MongoDB and return a Response. :Parameters: - `operation`: a _Query or _GetMore object. - `read_preference` (optional): A Rea...
[ "def", "_send_message_with_response", "(", "self", ",", "operation", ",", "read_preference", "=", "None", ",", "exhaust", "=", "False", ",", "address", "=", "None", ")", ":", "with", "self", ".", "__lock", ":", "# If needed, restart kill-cursors thread after a fork....
42.97619
20.5
def sort_by_padding(instances: List[Instance], sorting_keys: List[Tuple[str, str]], # pylint: disable=invalid-sequence-index vocab: Vocabulary, padding_noise: float = 0.0) -> List[Instance]: """ Sorts the instances by their padding lengths, using the ...
[ "def", "sort_by_padding", "(", "instances", ":", "List", "[", "Instance", "]", ",", "sorting_keys", ":", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "# pylint: disable=invalid-sequence-index", "vocab", ":", "Vocabulary", ",", "padding_noise", ...
55.52
21.68
def create(cls, name, address, proxy_port=8080, username=None, password=None, secondary=None, comment=None): """ Create a new HTTP Proxy service. Proxy must define at least one primary address but can optionally also define a list of secondary addresses. :...
[ "def", "create", "(", "cls", ",", "name", ",", "address", ",", "proxy_port", "=", "8080", ",", "username", "=", "None", ",", "password", "=", "None", ",", "secondary", "=", "None", ",", "comment", "=", "None", ")", ":", "json", "=", "{", "'name'", ...
45.222222
18.111111
def _serialize_v1(self, macaroon): '''Serialize the macaroon in JSON format v1. @param macaroon the macaroon to serialize. @return JSON macaroon. ''' serialized = { 'identifier': utils.convert_to_string(macaroon.identifier), 'signature': macaroon.signatur...
[ "def", "_serialize_v1", "(", "self", ",", "macaroon", ")", ":", "serialized", "=", "{", "'identifier'", ":", "utils", ".", "convert_to_string", "(", "macaroon", ".", "identifier", ")", ",", "'signature'", ":", "macaroon", ".", "signature", ",", "}", "if", ...
34.941176
17.294118
def is_in_intervall(value, min_value, max_value, name='variable'): """ Raise an exception if value is not in an interval. Parameters ---------- value : orderable min_value : orderable max_value : orderable name : str Name of the variable to print in exception. """ if not...
[ "def", "is_in_intervall", "(", "value", ",", "min_value", ",", "max_value", ",", "name", "=", "'variable'", ")", ":", "if", "not", "(", "min_value", "<=", "value", "<=", "max_value", ")", ":", "raise", "ValueError", "(", "'{}={} is not in [{}, {}]'", ".", "f...
30.8
17.466667
def map(func, *iterables, **kwargs): """map(func, *iterables) Equivalent to `map(func, \*iterables, ...) <http://docs.python.org/library/functions.html#map>`_ but *func* is executed asynchronously and several calls to func may be made concurrently. This non-blocking call returns an iterator ...
[ "def", "map", "(", "func", ",", "*", "iterables", ",", "*", "*", "kwargs", ")", ":", "# TODO: Handle timeout", "futures", "=", "_mapFuture", "(", "func", ",", "*", "iterables", ")", "return", "_mapGenerator", "(", "futures", ")" ]
49.518519
22.148148
def describe_db_engine_versions(Engine=None, EngineVersion=None, DBParameterGroupFamily=None, Filters=None, MaxRecords=None, Marker=None, DefaultOnly=None, ListSupportedCharacterSets=None, ListSupportedTimezones=None): """ Returns a list of the available DB engines. See also: AWS API Documentation ...
[ "def", "describe_db_engine_versions", "(", "Engine", "=", "None", ",", "EngineVersion", "=", "None", ",", "DBParameterGroupFamily", "=", "None", ",", "Filters", "=", "None", ",", "MaxRecords", "=", "None", ",", "Marker", "=", "None", ",", "DefaultOnly", "=", ...
38.548673
27.522124
def only(it): """ >>> only([7]) 7 >>> only([1, 2]) Traceback (most recent call last): ... AssertionError: Expected one value, found 2 >>> only([]) Traceback (most recent call last): ... AssertionError: Expected one value, found 0 >>> from itertools import repeat >>> o...
[ "def", "only", "(", "it", ")", ":", "if", "isinstance", "(", "it", ",", "Sized", ")", ":", "if", "len", "(", "it", ")", "!=", "1", ":", "raise", "AssertionError", "(", "'Expected one value, found %s'", "%", "len", "(", "it", ")", ")", "# noinspection P...
27.257143
17.542857
def _main(self, client, copy_source, bucket, key, extra_args, callbacks, size): """ :param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to copy to :param key: The name of t...
[ "def", "_main", "(", "self", ",", "client", ",", "copy_source", ",", "bucket", ",", "key", ",", "extra_args", ",", "callbacks", ",", "size", ")", ":", "client", ".", "copy_object", "(", "CopySource", "=", "copy_source", ",", "Bucket", "=", "bucket", ",",...
43.555556
18.222222
def simple_response(self, status, msg=''): """Write a simple response back to the client.""" status = str(status) proto_status = '%s %s\r\n' % (self.server.protocol, status) content_length = 'Content-Length: %s\r\n' % len(msg) content_type = 'Content-Type: text/plain\r\n' ...
[ "def", "simple_response", "(", "self", ",", "status", ",", "msg", "=", "''", ")", ":", "status", "=", "str", "(", "status", ")", "proto_status", "=", "'%s %s\\r\\n'", "%", "(", "self", ".", "server", ".", "protocol", ",", "status", ")", "content_length",...
40.888889
18.083333
def active_conf_set_name(self): '''The name of the currently-active configuration set.''' with self._mutex: if not self.conf_sets: return '' if not self._active_conf_set: return '' return self._active_conf_set
[ "def", "active_conf_set_name", "(", "self", ")", ":", "with", "self", ".", "_mutex", ":", "if", "not", "self", ".", "conf_sets", ":", "return", "''", "if", "not", "self", ".", "_active_conf_set", ":", "return", "''", "return", "self", ".", "_active_conf_se...
35.75
10.75
def model_reaction_limits(model): """Yield model reaction limits as YAML dicts.""" for reaction in sorted(model.reactions, key=lambda r: r.id): equation = reaction.properties.get('equation') if equation is None: continue # Determine the default flux limits. If the value is a...
[ "def", "model_reaction_limits", "(", "model", ")", ":", "for", "reaction", "in", "sorted", "(", "model", ".", "reactions", ",", "key", "=", "lambda", "r", ":", "r", ".", "id", ")", ":", "equation", "=", "reaction", ".", "properties", ".", "get", "(", ...
39.21875
18.65625
def report_fit(self): """ Print a report of the fit results. """ if not self.fitted: print('Model not yet fit.') return print('Null Log-liklihood: {0:.3f}'.format( self.log_likelihoods['null'])) print('Log-liklihood at convergence: {0...
[ "def", "report_fit", "(", "self", ")", ":", "if", "not", "self", ".", "fitted", ":", "print", "(", "'Model not yet fit.'", ")", "return", "print", "(", "'Null Log-liklihood: {0:.3f}'", ".", "format", "(", "self", ".", "log_likelihoods", "[", "'null'", "]", "...
29.571429
18
def extract_colors( filename_or_img, min_saturation=config.MIN_SATURATION, min_distance=config.MIN_DISTANCE, max_colors=config.MAX_COLORS, min_prominence=config.MIN_PROMINENCE, n_quantized=config.N_QUANTIZED): """ Determine what the major colors are in the given image. """ if Ima...
[ "def", "extract_colors", "(", "filename_or_img", ",", "min_saturation", "=", "config", ".", "MIN_SATURATION", ",", "min_distance", "=", "config", ".", "MIN_DISTANCE", ",", "max_colors", "=", "config", ".", "MAX_COLORS", ",", "min_prominence", "=", "config", ".", ...
33.535211
19.450704
def build_tree(self, name, props, resource_name=None): """Build a tree of non-primitive typed dependency order.""" n = Node(name, props, resource_name) prop_type_list = self._get_type_list(props) if not prop_type_list: return n prop_type_list = sorted(prop_type_list) ...
[ "def", "build_tree", "(", "self", ",", "name", ",", "props", ",", "resource_name", "=", "None", ")", ":", "n", "=", "Node", "(", "name", ",", "props", ",", "resource_name", ")", "prop_type_list", "=", "self", ".", "_get_type_list", "(", "props", ")", "...
40.571429
11.357143
def match_value_by_name(expected_type, actual_value): """ Matches expected type to a type of a value. :param expected_type: an expected type name to match. :param actual_value: a value to match its type to the expected one. :return: true if types are matching and false if they...
[ "def", "match_value_by_name", "(", "expected_type", ",", "actual_value", ")", ":", "if", "expected_type", "==", "None", ":", "return", "True", "if", "actual_value", "==", "None", ":", "raise", "Exception", "(", "\"Actual value cannot be null\"", ")", "return", "Ty...
34.75
22.375
def is_blacklisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument """ Checks if the request or given credentials are blacklisted from access. """ if is_client_ip_address_blacklisted(request): return True return ...
[ "def", "is_blacklisted", "(", "self", ",", "request", ":", "AxesHttpRequest", ",", "credentials", ":", "dict", "=", "None", ")", "->", "bool", ":", "# pylint: disable=unused-argument", "if", "is_client_ip_address_blacklisted", "(", "request", ")", ":", "return", "...
35.222222
27.666667
def fmt_to_datatype_v4(fmt, shape, array=False): """convert numpy dtype format string to mdf version 4 channel data type and size Parameters ---------- fmt : numpy.dtype numpy data type shape : tuple numpy array shape array : bool disambiguate between bytearray and c...
[ "def", "fmt_to_datatype_v4", "(", "fmt", ",", "shape", ",", "array", "=", "False", ")", ":", "size", "=", "fmt", ".", "itemsize", "*", "8", "if", "not", "array", "and", "shape", "[", "1", ":", "]", "and", "fmt", ".", "itemsize", "==", "1", "and", ...
30
18.358491
def get_single(decl_matcher, decls, recursive=True): """ Returns a reference to declaration, that match `decl_matcher` defined criteria. If a unique declaration could not be found, an appropriate exception will be raised. :param decl_matcher: Python callable object, tha...
[ "def", "get_single", "(", "decl_matcher", ",", "decls", ",", "recursive", "=", "True", ")", ":", "answer", "=", "matcher", ".", "find", "(", "decl_matcher", ",", "decls", ",", "recursive", ")", "if", "len", "(", "answer", ")", "==", "1", ":", "return",...
41.909091
21.727273
def bind_sqlalchemy(provider, session, user=None, client=None, token=None, grant=None, current_user=None): """Configures the given :class:`OAuth2Provider` instance with the required getters and setters for persistence with SQLAlchemy. An example of using all models:: oauth = OA...
[ "def", "bind_sqlalchemy", "(", "provider", ",", "session", ",", "user", "=", "None", ",", "client", "=", "None", ",", "token", "=", "None", ",", "grant", "=", "None", ",", "current_user", "=", "None", ")", ":", "if", "user", ":", "user_binding", "=", ...
36.220588
21.397059
def subscribe(self, request, *args, **kwargs): """ Performs the subscribe action. """ self.object = self.get_object() self.object.subscribers.add(request.user) messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url())
[ "def", "subscribe", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "self", ".", "object", ".", "subscribers", ".", "add", "(", "request", ".", "user...
49.833333
9.166667
def parse_model_specifier(specifier): ''' Parses a string that specifies either a model or a field. The string should look like ``app.model.[field]``. >>> print parse_model_specifier('tests.TestModel') (<class 'tests.models.TestModel'>, None) >>> print parse_model_specifier('tests.TestModel.ima...
[ "def", "parse_model_specifier", "(", "specifier", ")", ":", "values", "=", "specifier", ".", "split", "(", "'.'", ")", "if", "len", "(", "values", ")", "==", "2", ":", "values", ".", "append", "(", "None", ")", "elif", "len", "(", "values", ")", "!="...
31.514286
20.142857
def next_turn(self, *args): """Advance time by one turn, if it's not blocked. Block time by setting ``engine.universal['block'] = True``""" if self.tmp_block: return eng = self.app.engine dial = self.dialoglayout if eng.universal.get('block'): Log...
[ "def", "next_turn", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "tmp_block", ":", "return", "eng", "=", "self", ".", "app", ".", "engine", "dial", "=", "self", ".", "dialoglayout", "if", "eng", ".", "universal", ".", "get", "(", "'b...
36.666667
15.714286
def manage_config(cmd, *args): """Manage genomepy config file.""" if cmd == "file": print(config.config_file) elif cmd == "show": with open(config.config_file) as f: print(f.read()) elif cmd == "generate": fname = os.path.join( user_config_dir("genomep...
[ "def", "manage_config", "(", "cmd", ",", "*", "args", ")", ":", "if", "cmd", "==", "\"file\"", ":", "print", "(", "config", ".", "config_file", ")", "elif", "cmd", "==", "\"show\"", ":", "with", "open", "(", "config", ".", "config_file", ")", "as", "...
34.842105
14.421053
def add_key_val(keyname, keyval, keytype, filename, extnum): """Add/replace FITS key Add/replace the key keyname with value keyval of type keytype in filename. Parameters: ---------- keyname : str FITS Keyword name. keyval : str FITS keyword value. keytype: str FITS...
[ "def", "add_key_val", "(", "keyname", ",", "keyval", ",", "keytype", ",", "filename", ",", "extnum", ")", ":", "funtype", "=", "{", "'int'", ":", "int", ",", "'float'", ":", "float", ",", "'str'", ":", "str", ",", "'bool'", ":", "bool", "}", "if", ...
32.814815
22.888889
def as_dictionary(self): """ Return the service agreement template as a dictionary. :return: dict """ template = { 'contractName': self.contract_name, 'events': [e.as_dictionary() for e in self.agreement_events], 'fulfillmentOrder': self.fulfi...
[ "def", "as_dictionary", "(", "self", ")", ":", "template", "=", "{", "'contractName'", ":", "self", ".", "contract_name", ",", "'events'", ":", "[", "e", ".", "as_dictionary", "(", ")", "for", "e", "in", "self", ".", "agreement_events", "]", ",", "'fulfi...
34.210526
17.789474
def parse_kegg_gene_metadata(infile): """Parse the KEGG flatfile and return a dictionary of metadata. Dictionary keys are: refseq uniprot pdbs taxonomy Args: infile: Path to KEGG flatfile Returns: dict: Dictionary of metadata """ metadata = def...
[ "def", "parse_kegg_gene_metadata", "(", "infile", ")", ":", "metadata", "=", "defaultdict", "(", "str", ")", "with", "open", "(", "infile", ")", "as", "mf", ":", "kegg_parsed", "=", "bs_kegg", ".", "parse", "(", "mf", ".", "read", "(", ")", ")", "# TOD...
29.097561
19.292683
def gen_random_bank_card(bankname, card_type): """ 通过指定的银行名称,随机生成该银行的卡号 :param: * bankname: (string) 银行名称 eg. 中国银行 * card_type:(string) 卡种类,可选 CC(信用卡)、DC(借记卡) :returns: * random_bank_card: (string) 随机生成的银行卡卡号 举例如下:: print('--- gen_random_bank_card demo ---') ...
[ "def", "gen_random_bank_card", "(", "bankname", ",", "card_type", ")", ":", "bank_info", "=", "CardBin", ".", "get_bank_info", "(", "bankname", ")", "if", "not", "bank_info", ":", "raise", "ValueError", "(", "'bankname {} error, check and try again'", ".", "format",...
23.943396
22.245283
def atlas_get_peer( peer_hostport, peer_table=None ): """ Get the given peer's info """ ret = None with AtlasPeerTableLocked(peer_table) as ptbl: ret = ptbl.get(peer_hostport, None) return ret
[ "def", "atlas_get_peer", "(", "peer_hostport", ",", "peer_table", "=", "None", ")", ":", "ret", "=", "None", "with", "AtlasPeerTableLocked", "(", "peer_table", ")", "as", "ptbl", ":", "ret", "=", "ptbl", ".", "get", "(", "peer_hostport", ",", "None", ")", ...
21.7
16.9
def get(self, adgroup_id=None, creative_ids=None, nick=None): '''xxxxx.xxxxx.creatives.get =================================== 取得一个推广组的所有创意或者根据一个创意Id列表取得一组创意; 如果同时提供了推广组Id和创意id列表,则优先使用推广组Id;''' request = TOPRequest('xxxxx.xxxxx.creatives.get') if adgroup_id!=None: request...
[ "def", "get", "(", "self", ",", "adgroup_id", "=", "None", ",", "creative_ids", "=", "None", ",", "nick", "=", "None", ")", ":", "request", "=", "TOPRequest", "(", "'xxxxx.xxxxx.creatives.get'", ")", "if", "adgroup_id", "!=", "None", ":", "request", "[", ...
50.272727
13.727273
def decodepackbits(encoded): """Decompress PackBits encoded byte string. PackBits is a simple byte-oriented run-length compression scheme. """ func = ord if sys.version[0] == '2' else lambda x: x result = [] i = 0 try: while True: n = func(encoded[i]) + 1 i ...
[ "def", "decodepackbits", "(", "encoded", ")", ":", "func", "=", "ord", "if", "sys", ".", "version", "[", "0", "]", "==", "'2'", "else", "lambda", "x", ":", "x", "result", "=", "[", "]", "i", "=", "0", "try", ":", "while", "True", ":", "n", "=",...
27.681818
19.863636
def field2range(self, field, **kwargs): """Return the dictionary of OpenAPI field attributes for a set of :class:`Range <marshmallow.validators.Range>` validators. :param Field field: A marshmallow field. :rtype: dict """ validators = [ validator ...
[ "def", "field2range", "(", "self", ",", "field", ",", "*", "*", "kwargs", ")", ":", "validators", "=", "[", "validator", "for", "validator", "in", "field", ".", "validators", "if", "(", "hasattr", "(", "validator", ",", "\"min\"", ")", "and", "hasattr", ...
37.033333
16.5
def _nth(arr, n): """ Return the nth value of array If it is missing return NaN """ try: return arr.iloc[n] except (KeyError, IndexError): return np.nan
[ "def", "_nth", "(", "arr", ",", "n", ")", ":", "try", ":", "return", "arr", ".", "iloc", "[", "n", "]", "except", "(", "KeyError", ",", "IndexError", ")", ":", "return", "np", ".", "nan" ]
18.4
15
def get_temporary_filename(extension="", use_program_temp_dir=True): """Return the string for a temporary file with the given extension or suffix. For a file extension like .pdf the dot should also be in the passed string. Caller is expected to open and close it as necessary and call os.remove on it after...
[ "def", "get_temporary_filename", "(", "extension", "=", "\"\"", ",", "use_program_temp_dir", "=", "True", ")", ":", "dir_name", "=", "None", "# uses the regular system temp dir if None", "if", "use_program_temp_dir", ":", "dir_name", "=", "program_temp_directory", "tmp_ou...
72.363636
25.363636
def get_unused_paths(self): """ Returns which include_paths or exclude_paths that were not used via include_path method. :return: [str] list of filtering paths that were not used. """ return [path for path in self.filter.paths if path not in self.seen_paths]
[ "def", "get_unused_paths", "(", "self", ")", ":", "return", "[", "path", "for", "path", "in", "self", ".", "filter", ".", "paths", "if", "path", "not", "in", "self", ".", "seen_paths", "]" ]
48.833333
22.833333
def set_subroutine(self, name, code): """Define a Python object from your program. This is equivalent to having an object defined in the RiveScript code, except your Python code is defining it instead. :param str name: The name of the object macro. :param def code: A Python fun...
[ "def", "set_subroutine", "(", "self", ",", "name", ",", "code", ")", ":", "# Do we have a Python handler?", "if", "'python'", "in", "self", ".", "_handlers", ":", "self", ".", "_handlers", "[", "'python'", "]", ".", "_objects", "[", "name", "]", "=", "code...
38.809524
19.428571
def select_args(xmrs, nodeid=None, rargname=None, value=None): """ Return the list of matching (nodeid, role, value) triples in *xmrs*. Predication arguments in *xmrs* match if the `nodeid` of the :class:`~delphin.mrs.components.ElementaryPredication` they are arguments of match *nodeid*, their rol...
[ "def", "select_args", "(", "xmrs", ",", "nodeid", "=", "None", ",", "rargname", "=", "None", ",", "value", "=", "None", ")", ":", "argmatch", "=", "lambda", "a", ":", "(", "(", "nodeid", "is", "None", "or", "a", "[", "0", "]", "==", "nodeid", ")"...
42.205128
20.410256
def upsert(self, document, cond): """ Update a document, if it exist - insert it otherwise. Note: this will update *all* documents matching the query. :param document: the document to insert or the fields to update :param cond: which document to look for :returns: a lis...
[ "def", "upsert", "(", "self", ",", "document", ",", "cond", ")", ":", "updated_docs", "=", "self", ".", "update", "(", "document", ",", "cond", ")", "if", "updated_docs", ":", "return", "updated_docs", "else", ":", "return", "[", "self", ".", "insert", ...
32.5625
18.5625
def _GetDeps(self, dependencies): """Recursively finds dependencies for file protos. Args: dependencies: The names of the files being depended on. Yields: Each direct and indirect dependency. """ for dependency in dependencies: dep_desc = self.FindFileByName(dependency) yi...
[ "def", "_GetDeps", "(", "self", ",", "dependencies", ")", ":", "for", "dependency", "in", "dependencies", ":", "dep_desc", "=", "self", ".", "FindFileByName", "(", "dependency", ")", "yield", "dep_desc", "for", "parent_dep", "in", "dep_desc", ".", "dependencie...
26
17.666667
def get_ids_from_folder(path, part_name): """ Return all ids from the given folder, which have a corresponding beamformedSignal file. """ valid_ids = set({}) for xml_file in glob.glob(os.path.join(path, '*.xml')): idx = os.path.splitext(os.path.basename(xml_file))[0]...
[ "def", "get_ids_from_folder", "(", "path", ",", "part_name", ")", ":", "valid_ids", "=", "set", "(", "{", "}", ")", "for", "xml_file", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'*.xml'", ")", ")", ":", "idx"...
32.153846
20.461538
def main(args): """docstring for main""" try: args.query = ' '.join(args.query).replace('?', '') so = SOSearch(args.query, args.tags) result = so.first_q().best_answer.code if result != None: print result else: print("Sorry I can't find your answe...
[ "def", "main", "(", "args", ")", ":", "try", ":", "args", ".", "query", "=", "' '", ".", "join", "(", "args", ".", "query", ")", ".", "replace", "(", "'?'", ",", "''", ")", "so", "=", "SOSearch", "(", "args", ".", "query", ",", "args", ".", "...
34.833333
17.666667
def error(name=None, message=''): ''' If name is None Then return empty dict Otherwise raise an exception with __name__ from name, message from message CLI Example: .. code-block:: bash salt-wheel error salt-wheel error.error name="Exception" message="This is an error." ''' ...
[ "def", "error", "(", "name", "=", "None", ",", "message", "=", "''", ")", ":", "ret", "=", "{", "}", "if", "name", "is", "not", "None", ":", "salt", ".", "utils", ".", "error", ".", "raise_error", "(", "name", "=", "name", ",", "message", "=", ...
24.705882
26.941176
def y(self,*args,**kwargs): """ NAME: y PURPOSE: return y INPUT: t - (optional) time at which to get y (can be Quantity) ro= (Object-wide default) physical scale for distances to use to convert (can be Quantity) use_physical= ...
[ "def", "y", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "out", "=", "self", ".", "_orb", ".", "y", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "len", "(", "out", ")", "==", "1", ":", "return", "out", "[", "...
19.366667
28.633333
def validate_uncles(state, block): """Validate the uncles of this block.""" # Make sure hash matches up if utils.sha3(rlp.encode(block.uncles)) != block.header.uncles_hash: raise VerificationFailed("Uncle hash mismatch") # Enforce maximum number of uncles if len(block.uncles) > state.config[...
[ "def", "validate_uncles", "(", "state", ",", "block", ")", ":", "# Make sure hash matches up", "if", "utils", ".", "sha3", "(", "rlp", ".", "encode", "(", "block", ".", "uncles", ")", ")", "!=", "block", ".", "header", ".", "uncles_hash", ":", "raise", "...
48.613636
14.431818
def search(self, search_phrase, limit=None): """ Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Generates: PartitionSearchResult instances. """ ...
[ "def", "search", "(", "self", ",", "search_phrase", ",", "limit", "=", "None", ")", ":", "query", ",", "query_params", "=", "self", ".", "_make_query_from_terms", "(", "search_phrase", ",", "limit", "=", "limit", ")", "self", ".", "_parsed_query", "=", "("...
33.208333
23
def _read_hip_para(self, length, *, version): """Read HIP parameters. Positional arguments: * length -- int, length of parameters Keyword arguments: * version -- int, HIP version Returns: * dict -- extracted HIP parameters """ count...
[ "def", "_read_hip_para", "(", "self", ",", "length", ",", "*", ",", "version", ")", ":", "counter", "=", "0", "# length of read parameters", "optkind", "=", "list", "(", ")", "# parameter type list", "options", "=", "dict", "(", ")", "# dict of parameter data", ...
34.169492
17.932203
def _save_single_attr(self, entity, value=None, schema=None, create_nulls=False, extra={}): """ Creates or updates an EAV attribute for given entity with given value. :param schema: schema for attribute. Default it current schema instance. :param create_nulls: ...
[ "def", "_save_single_attr", "(", "self", ",", "entity", ",", "value", "=", "None", ",", "schema", "=", "None", ",", "create_nulls", "=", "False", ",", "extra", "=", "{", "}", ")", ":", "# If schema is not many-to-one, the value is saved to the corresponding", "# A...
44.166667
19.25
def _parse_attributes(self, element_name, package_class, namespace=''): """ Returns an instance of the package_class instantiated with a dictionary of the attributes from element_name in the specified namespace of the RSS feed. """ return package_class( self._...
[ "def", "_parse_attributes", "(", "self", ",", "element_name", ",", "package_class", ",", "namespace", "=", "''", ")", ":", "return", "package_class", "(", "self", ".", "_channel", ".", "find", "(", "'.//{0}{1}'", ".", "format", "(", "namespace", ",", "elemen...
37.636364
16.909091
def get_open_trackers_from_local(): """Returns open trackers announce URLs list from local backup.""" with open(path.join(path.dirname(__file__), 'repo', OPEN_TRACKERS_FILENAME)) as f: open_trackers = map(str.strip, f.readlines()) return list(open_trackers)
[ "def", "get_open_trackers_from_local", "(", ")", ":", "with", "open", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "'repo'", ",", "OPEN_TRACKERS_FILENAME", ")", ")", "as", "f", ":", "open_trackers", "=", "map", "(", "...
45.5
19
def _platform(self) -> Optional[str]: """Extract platform.""" try: return str(self.journey.MainStop.BasicStop.Dep.Platform.text) except AttributeError: return None
[ "def", "_platform", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "try", ":", "return", "str", "(", "self", ".", "journey", ".", "MainStop", ".", "BasicStop", ".", "Dep", ".", "Platform", ".", "text", ")", "except", "AttributeError", ":", ...
34.333333
15.166667
def _deposit_withdraw(self, type, amount, coinbase_account_id): """`<https://docs.exchange.coinbase.com/#depositwithdraw>`_""" data = { 'type':type, 'amount':amount, 'coinbase_account_id':coinbase_account_id } return self._post('transfers', data=data)
[ "def", "_deposit_withdraw", "(", "self", ",", "type", ",", "amount", ",", "coinbase_account_id", ")", ":", "data", "=", "{", "'type'", ":", "type", ",", "'amount'", ":", "amount", ",", "'coinbase_account_id'", ":", "coinbase_account_id", "}", "return", "self",...
34.75
17.25
def module_name(self, jamfile_location): """Returns the name of module corresponding to 'jamfile-location'. If no module corresponds to location yet, associates default module name with that location.""" assert isinstance(jamfile_location, basestring) module = self.location2modul...
[ "def", "module_name", "(", "self", ",", "jamfile_location", ")", ":", "assert", "isinstance", "(", "jamfile_location", ",", "basestring", ")", "module", "=", "self", ".", "location2module", ".", "get", "(", "jamfile_location", ")", "if", "not", "module", ":", ...
52.4
14.933333
def grab_to_file(filename, childprocess=None, backend=None): """Copy the contents of the screen to a file. Internal function! Use PIL.Image.save() for saving image to file. :param filename: file for saving :param childprocess: see :py:func:`grab` :param backend: see :py:func:`grab` """ if c...
[ "def", "grab_to_file", "(", "filename", ",", "childprocess", "=", "None", ",", "backend", "=", "None", ")", ":", "if", "childprocess", "is", "None", ":", "childprocess", "=", "childprocess_default_value", "(", ")", "return", "_grab", "(", "to_file", "=", "Tr...
41
10.583333
def find_files(self, context, silent_build): """ Find the set of files from our parent_dir that we care about """ first_layer = ["'{0}'".format(thing) for thing in os.listdir(context.parent_dir)] output, status = command_output("find {0} -type l -or -type f {1} -follow -print".fo...
[ "def", "find_files", "(", "self", ",", "context", ",", "silent_build", ")", ":", "first_layer", "=", "[", "\"'{0}'\"", ".", "format", "(", "thing", ")", "for", "thing", "in", "os", ".", "listdir", "(", "context", ".", "parent_dir", ")", "]", "output", ...
46.666667
25.518519
def data(self, index, role=Qt.DisplayRole): """Qt Override.""" row = index.row() if not index.isValid() or not (0 <= row < len(self.servers)): return to_qvariant() server = self.servers[row] column = index.column() if role == Qt.DisplayRole: if c...
[ "def", "data", "(", "self", ",", "index", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "row", "=", "index", ".", "row", "(", ")", "if", "not", "index", ".", "isValid", "(", ")", "or", "not", "(", "0", "<=", "row", "<", "len", "(", "s...
40.541667
14.791667
def gradient(self): """ Return a view on the gradient, which is in the same shape as this parameter is. Note: this is not the real gradient array, it is just a view on it. To work on the real gradient array use: self.full_gradient """ if getattr(self, '_gradient_array_',...
[ "def", "gradient", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_gradient_array_'", ",", "None", ")", "is", "None", ":", "self", ".", "_gradient_array_", "=", "np", ".", "empty", "(", "self", ".", "_realshape_", ",", "dtype", "=", "np", ...
44.4
23.2
def bounds(self, axis=0): """ Get the lower and upper bounds of the binning along an axis """ if not 0 <= axis < self.GetDimension(): raise ValueError( "axis must be a non-negative integer less than " "the dimensionality of the histogram") ...
[ "def", "bounds", "(", "self", ",", "axis", "=", "0", ")", ":", "if", "not", "0", "<=", "axis", "<", "self", ".", "GetDimension", "(", ")", ":", "raise", "ValueError", "(", "\"axis must be a non-negative integer less than \"", "\"the dimensionality of the histogram...
38.066667
13
def hemispheric_difference(image, sigma_active = 7, sigma_reference = 7, cut_plane = 0, voxelspacing = None, mask = slice(None)): r""" Computes the hemispheric intensity difference between the brain hemispheres of an brain image. Cuts the image along the middle of the supplied cut-plane. This results i...
[ "def", "hemispheric_difference", "(", "image", ",", "sigma_active", "=", "7", ",", "sigma_reference", "=", "7", ",", "cut_plane", "=", "0", ",", "voxelspacing", "=", "None", ",", "mask", "=", "slice", "(", "None", ")", ")", ":", "return", "_extract_feature...
49.046154
31.753846
def psstatus(): """Shows PokerStars status such as number of players, tournaments.""" from .website.pokerstars import get_status _print_header('PokerStars status') status = get_status() _print_values( ('Info updated', status.updated), ('Tables', status.tables), ('Players', ...
[ "def", "psstatus", "(", ")", ":", "from", ".", "website", ".", "pokerstars", "import", "get_status", "_print_header", "(", "'PokerStars status'", ")", "status", "=", "get_status", "(", ")", "_print_values", "(", "(", "'Info updated'", ",", "status", ".", "upda...
35.608696
19.217391
def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk() gobject.timeout_add...
[ "def", "_wire_kernel", "(", "self", ")", ":", "self", ".", "gtk_main", ",", "self", ".", "gtk_main_quit", "=", "self", ".", "_hijack_gtk", "(", ")", "gobject", ".", "timeout_add", "(", "int", "(", "1000", "*", "self", ".", "kernel", ".", "_poll_interval"...
41.9
18.1
def augment_polar_mesh_for_colormesh(r_values, theta_values): """ Returns polar mesh for matplotlib.pyplot.pcolormesh() in polar coordinates. polar coordinates of data points -> polar mesh for colormesh polar coordinates is assumed to be equidistanced in a sense that the r_values and theta_values a...
[ "def", "augment_polar_mesh_for_colormesh", "(", "r_values", ",", "theta_values", ")", ":", "N_r", "=", "len", "(", "r_values", ")", "N_theta", "=", "len", "(", "theta_values", ")", "delta_r", "=", "(", "r_values", "[", "-", "1", "]", "-", "r_values", "[", ...
36.045455
25.681818
def parse(self, rule: str): """Parses policy to tree. Translate a policy written in the policy language into a tree of Check objects. """ # Empty rule means always accept if not rule: return checks.TrueCheck() for token, value in self._parse_tokeniz...
[ "def", "parse", "(", "self", ",", "rule", ":", "str", ")", ":", "# Empty rule means always accept", "if", "not", "rule", ":", "return", "checks", ".", "TrueCheck", "(", ")", "for", "token", ",", "value", "in", "self", ".", "_parse_tokenize", "(", "rule", ...
27.4
17.8
def set_min_string_length(self, length=None): """stub""" if self.get_min_string_length_metadata().is_read_only(): raise NoAccess() if not self.my_osid_object_form._is_valid_cardinal( length, self.get_min_string_length_metadata()): raise Inv...
[ "def", "set_min_string_length", "(", "self", ",", "length", "=", "None", ")", ":", "if", "self", ".", "get_min_string_length_metadata", "(", ")", ".", "is_read_only", "(", ")", ":", "raise", "NoAccess", "(", ")", "if", "not", "self", ".", "my_osid_object_for...
47.153846
14.846154
def main(): """ NAME qqunf.py DESCRIPTION makes qq plot from input data against uniform distribution SYNTAX qqunf.py [command line options] OPTIONS -h help message -f FILE, specify file on command line """ fmt,plot='svg',0 if '-h' in sys.argv: # c...
[ "def", "main", "(", ")", ":", "fmt", ",", "plot", "=", "'svg'", ",", "0", "if", "'-h'", "in", "sys", ".", "argv", ":", "# check if help is needed", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "# graceful quit", "elif", "'...
27.949153
18.79661
def register_gym_env(class_entry_point, version="v0", kwargs=None): """Registers the class in Gym and returns the registered name and the env.""" split_on_colon = class_entry_point.split(":") assert len(split_on_colon) == 2 class_name = split_on_colon[1] # We have to add the version to conform to gym's API....
[ "def", "register_gym_env", "(", "class_entry_point", ",", "version", "=", "\"v0\"", ",", "kwargs", "=", "None", ")", ":", "split_on_colon", "=", "class_entry_point", ".", "split", "(", "\":\"", ")", "assert", "len", "(", "split_on_colon", ")", "==", "2", "cl...
39.333333
22.2
def makedir(path): """ Make the analysis directory path and any parent directories that don't already exist. Will do nothing if path already exists. """ if path is not None and not os.path.exists(path): os.makedirs(path)
[ "def", "makedir", "(", "path", ")", ":", "if", "path", "is", "not", "None", "and", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")" ]
34.571429
14.571429
def filter(self, *, type_=None, lang=None, attrs={}): """ Return an iterable which produces a sequence of the elements inside this :class:`XSOList`, filtered by the criteria given as arguments. The function starts with a working sequence consisting of the whole list. If `type_` ...
[ "def", "filter", "(", "self", ",", "*", ",", "type_", "=", "None", ",", "lang", "=", "None", ",", "attrs", "=", "{", "}", ")", ":", "result", "=", "self", "if", "type_", "is", "not", "None", ":", "result", "=", "self", ".", "_filter_type", "(", ...
45.875
27.416667
def move(self, filename, target): ''' Move a file given its filename to another path in the storage Default implementation perform a copy then a delete. Backends should overwrite it if there is a better way. ''' self.copy(filename, target) self.delete(filename)
[ "def", "move", "(", "self", ",", "filename", ",", "target", ")", ":", "self", ".", "copy", "(", "filename", ",", "target", ")", "self", ".", "delete", "(", "filename", ")" ]
34.444444
21.333333
def blast_pdb(self, seq_ident_cutoff=0, evalue=0.0001, display_link=False, outdir=None, force_rerun=False): """BLAST this sequence to the PDB""" if not outdir: outdir = self.sequence_dir if not outdir: raise ValueError('Output directory must be s...
[ "def", "blast_pdb", "(", "self", ",", "seq_ident_cutoff", "=", "0", ",", "evalue", "=", "0.0001", ",", "display_link", "=", "False", ",", "outdir", "=", "None", ",", "force_rerun", "=", "False", ")", ":", "if", "not", "outdir", ":", "outdir", "=", "sel...
47.846154
27.692308
def cli(conf): """The fedora-messaging command line interface.""" if conf: if not os.path.isfile(conf): raise click.exceptions.BadParameter("{} is not a file".format(conf)) try: config.conf.load_config(config_path=conf) except exceptions.ConfigurationException as ...
[ "def", "cli", "(", "conf", ")", ":", "if", "conf", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "conf", ")", ":", "raise", "click", ".", "exceptions", ".", "BadParameter", "(", "\"{} is not a file\"", ".", "format", "(", "conf", ")", ")",...
41.166667
17.833333
def confirm_build(build_url, keeper_token): """Confirm a build upload is complete. Wraps ``PATCH /builds/{build}``. Parameters ---------- build_url : `str` URL of the build resource. Given a build resource, this URL is available from the ``self_url`` field. keeper_token : `str`...
[ "def", "confirm_build", "(", "build_url", ",", "keeper_token", ")", ":", "data", "=", "{", "'uploaded'", ":", "True", "}", "r", "=", "requests", ".", "patch", "(", "build_url", ",", "auth", "=", "(", "keeper_token", ",", "''", ")", ",", "json", "=", ...
24.714286
20.75
def plot_attention(attention_matrix: np.ndarray, source_tokens: List[str], target_tokens: List[str], filename: str): """ Uses matplotlib for creating a visualization of the attention matrix. :param attention_matrix: The attention matrix. :param source_tokens: A list of source tokens. :param target_...
[ "def", "plot_attention", "(", "attention_matrix", ":", "np", ".", "ndarray", ",", "source_tokens", ":", "List", "[", "str", "]", ",", "target_tokens", ":", "List", "[", "str", "]", ",", "filename", ":", "str", ")", ":", "try", ":", "import", "matplotlib"...
42.703704
22.111111
def visit_functiondef(self, node): """check method arguments, overriding""" # ignore actual functions if not node.is_method(): return self._check_useless_super_delegation(node) klass = node.parent.frame() self._meth_could_be_func = True # check first...
[ "def", "visit_functiondef", "(", "self", ",", "node", ")", ":", "# ignore actual functions", "if", "not", "node", ".", "is_method", "(", ")", ":", "return", "self", ".", "_check_useless_super_delegation", "(", "node", ")", "klass", "=", "node", ".", "parent", ...
42.7375
19.9875
def _exists(fs, path): """ Check that the given path exists on the filesystem. Note that unlike `os.path.exists`, we *do* propagate file system errors other than a non-existent path or non-existent directory component. E.g., should EPERM or ELOOP be raised, an exception will bubble up. """ ...
[ "def", "_exists", "(", "fs", ",", "path", ")", ":", "try", ":", "fs", ".", "stat", "(", "path", ")", "except", "(", "exceptions", ".", "FileNotFound", ",", "exceptions", ".", "NotADirectory", ")", ":", "return", "False", "return", "True" ]
31.071429
23.5
def cifar10_patches(data_set='cifar-10'): """The Candian Institute for Advanced Research 10 image data set. Code for loading in this data is taken from this Boris Babenko's blog post, original code available here: http://bbabenko.tumblr.com/post/86756017649/learning-low-level-vision-feautres-in-10-lines-of-code""" ...
[ "def", "cifar10_patches", "(", "data_set", "=", "'cifar-10'", ")", ":", "dir_path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "data_set", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "'cifar-10-python.tar.gz...
60
23.173913
def get_or_add_tx_rich(self): """ Return the `c:tx[c:rich]` subtree, newly created if not present. """ tx = self.get_or_add_tx() tx._remove_strRef() tx.get_or_add_rich() return tx
[ "def", "get_or_add_tx_rich", "(", "self", ")", ":", "tx", "=", "self", ".", "get_or_add_tx", "(", ")", "tx", ".", "_remove_strRef", "(", ")", "tx", ".", "get_or_add_rich", "(", ")", "return", "tx" ]
28.5
12.25
def parse_arguments(): """Parse arguments.""" parser = create_parser() args = parser.parse_args() if not args.role_requirements_old_commit: args.role_requirements_old_commit = args.role_requirements if not args.rpc_product_old_commit: args.rpc_product_old_commit = args.rpc_product ...
[ "def", "parse_arguments", "(", ")", ":", "parser", "=", "create_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "not", "args", ".", "role_requirements_old_commit", ":", "args", ".", "role_requirements_old_commit", "=", "args", ".",...
36.111111
12.333333
def load_validation_plugin(name=None): """Find and load the chosen validation plugin. Args: name (string): the name of the entry_point, as advertised in the setup.py of the providing package. Returns: an uninstantiated subclass of ``bigchaindb.validation.AbstractValidationRules...
[ "def", "load_validation_plugin", "(", "name", "=", "None", ")", ":", "if", "not", "name", ":", "return", "BaseValidationRules", "# TODO: This will return the first plugin with group `bigchaindb.validation`", "# and name `name` in the active WorkingSet.", "# We should prob...
37.676471
24.117647
def class_name_str(obj, skip_parent=False): """ return's object's class name as string """ rt = str(type(obj)).split(" ")[1][1:-2] if skip_parent: rt = rt.split(".")[-1] return rt
[ "def", "class_name_str", "(", "obj", ",", "skip_parent", "=", "False", ")", ":", "rt", "=", "str", "(", "type", "(", "obj", ")", ")", ".", "split", "(", "\" \"", ")", "[", "1", "]", "[", "1", ":", "-", "2", "]", "if", "skip_parent", ":", "rt", ...
25.5
8.25
def get_by_name(self, name): """ Retrieve a template by it's name Args: name (str): Name of the template to retrieve Raises: LagoMissingTemplateError: if no template is found """ try: spec = self._dom.get('templates', {})[name] ...
[ "def", "get_by_name", "(", "self", ",", "name", ")", ":", "try", ":", "spec", "=", "self", ".", "_dom", ".", "get", "(", "'templates'", ",", "{", "}", ")", "[", "name", "]", "except", "KeyError", ":", "raise", "LagoMissingTemplateError", "(", "name", ...
30.703704
19.518519
def _space_before_copyright(relative_path, contents, linter_options): """Check for a space between the last line and description. like such # Description # # Last Line """ del relative_path del linter_options last_line = _find_last_line_index(contents) if not _match_space_at_li...
[ "def", "_space_before_copyright", "(", "relative_path", ",", "contents", ",", "linter_options", ")", ":", "del", "relative_path", "del", "linter_options", "last_line", "=", "_find_last_line_index", "(", "contents", ")", "if", "not", "_match_space_at_line", "(", "conte...
35.176471
20.529412
def _read_points(self, vlrs): """ private function to handle reading of the points record parts of the las file. the header is needed for the point format and number of points the vlrs are need to get the potential laszip vlr as well as the extra bytes vlr """ try: ...
[ "def", "_read_points", "(", "self", ",", "vlrs", ")", ":", "try", ":", "extra_dims", "=", "vlrs", ".", "get", "(", "\"ExtraBytesVlr\"", ")", "[", "0", "]", ".", "type_of_extra_dims", "(", ")", "except", "IndexError", ":", "extra_dims", "=", "None", "poin...
41.714286
23.714286
def Matches(self, file_entry): """Compares the file entry against the filter. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches the filter, False if not or None if the filter does not apply. """ if not self._date_time_ran...
[ "def", "Matches", "(", "self", ",", "file_entry", ")", ":", "if", "not", "self", ".", "_date_time_ranges", ":", "return", "None", "for", "date_time_range", "in", "self", ".", "_date_time_ranges", ":", "time_attribute", "=", "self", ".", "_TIME_VALUE_MAPPINGS", ...
28.0625
21.03125
def _new_sensor_reading(self, sensor_value): """ Call this method to signal a new sensor reading. This method handles DB storage and triggers different events. :param value: New value to be stored in the system. """ if not self._active and not self._enabled: ...
[ "def", "_new_sensor_reading", "(", "self", ",", "sensor_value", ")", ":", "if", "not", "self", ".", "_active", "and", "not", "self", ".", "_enabled", ":", "return", "if", "self", ".", "_dimensions", ">", "1", ":", "for", "dimension", "in", "range", "(", ...
35.235294
17
def set_s3_profile(profile_name): """Load the credentials for an s3 profile into environmental variables""" import os session = boto3.Session(profile_name=profile_name) os.environ['AWS_ACCESS_KEY_ID'] = session.get_credentials().access_key os.environ['AWS_SECRET_ACCESS_KEY'] = session.get_credenti...
[ "def", "set_s3_profile", "(", "profile_name", ")", ":", "import", "os", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "profile_name", ")", "os", ".", "environ", "[", "'AWS_ACCESS_KEY_ID'", "]", "=", "session", ".", "get_credentials", "(", ...
41.125
25
def _pfp__is_non_consecutive_duplicate(self, name, child): """Return True/False if the child is a non-consecutive duplicately named field. Consecutive duplicately-named fields are stored in an implicit array, non-consecutive duplicately named fields have a numeric suffix appended to their name""...
[ "def", "_pfp__is_non_consecutive_duplicate", "(", "self", ",", "name", ",", "child", ")", ":", "if", "len", "(", "self", ".", "_pfp__children", ")", "==", "0", ":", "return", "False", "# it should be an implicit array", "if", "self", ".", "_pfp__children", "[", ...
41.95
22.55
def compile_pattern_list(self, patterns): """This compiles a pattern-string or a list of pattern-strings. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those. Patterns may also be None which results in an empty list (you might do this if waiting for an EOF or TI...
[ "def", "compile_pattern_list", "(", "self", ",", "patterns", ")", ":", "if", "patterns", "is", "None", ":", "return", "[", "]", "if", "not", "isinstance", "(", "patterns", ",", "list", ")", ":", "patterns", "=", "[", "patterns", "]", "compile_flags", "="...
39.530612
20.55102
def command_init(prog_name, prof_mgr, prof_name, prog_args): """ Initialize a profile. """ # Retrieve arguments parser = argparse.ArgumentParser( prog=prog_name ) parser.add_argument( "type", metavar="type", type=str, nargs=1, help="profile type" ) args = parser.parse_args(prog_args) # Profil...
[ "def", "command_init", "(", "prog_name", ",", "prof_mgr", ",", "prof_name", ",", "prog_args", ")", ":", "# Retrieve arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "prog_name", ")", "parser", ".", "add_argument", "(", "\"type\"", ...
16.818182
21.727273
def get_setting_from_keyring(self, setting_identifier, keyring_backend=None): """ Retrieves a protected setting from keyring :param setting_identifier: must be in the format package.module.Class.setting """ # If a custom keyring backend has been defined, use it. if keyrin...
[ "def", "get_setting_from_keyring", "(", "self", ",", "setting_identifier", ",", "keyring_backend", "=", "None", ")", ":", "# If a custom keyring backend has been defined, use it.", "if", "keyring_backend", ":", "return", "keyring_backend", ".", "get_password", "(", "setting...
39.375
22.875
def empirical(X): """Compute empirical covariance as baseline estimator. """ print("Empirical") cov = np.dot(X.T, X) / n_samples return cov, np.linalg.inv(cov)
[ "def", "empirical", "(", "X", ")", ":", "print", "(", "\"Empirical\"", ")", "cov", "=", "np", ".", "dot", "(", "X", ".", "T", ",", "X", ")", "/", "n_samples", "return", "cov", ",", "np", ".", "linalg", ".", "inv", "(", "cov", ")" ]
29
8.5
async def read_registers(self, address, count): """Read modbus registers. The Modbus protocol doesn't allow responses longer than 250 bytes (ie. 125 registers, 62 DF addresses), which this function manages by chunking larger requests. """ registers = [] while cou...
[ "async", "def", "read_registers", "(", "self", ",", "address", ",", "count", ")", ":", "registers", "=", "[", "]", "while", "count", ">", "124", ":", "r", "=", "await", "self", ".", "_request", "(", "'read_holding_registers'", ",", "address", ",", "124",...
41.066667
17.733333
def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must...
[ "def", "connection_from_url", "(", "url", ",", "*", "*", "kw", ")", ":", "scheme", ",", "host", ",", "port", "=", "get_host", "(", "url", ")", "if", "scheme", "==", "'https'", ":", "return", "HTTPSConnectionPool", "(", "host", ",", "port", "=", "port",...
34.08
23.04
def to_tsv(self, include_readonly=True): ''' Returns the instance's column values as a tab-separated line. A newline is not included. - `include_readonly`: if false, returns only fields that can be inserted into database. ''' data = self.__dict__ fields = self.fields(wri...
[ "def", "to_tsv", "(", "self", ",", "include_readonly", "=", "True", ")", ":", "data", "=", "self", ".", "__dict__", "fields", "=", "self", ".", "fields", "(", "writable", "=", "not", "include_readonly", ")", "return", "'\\t'", ".", "join", "(", "field", ...
49.555556
34
def unsubscribe(self, event): """Unsubscribe from an object's future changes""" # TODO: Automatic Unsubscription uuids = event.data if not isinstance(uuids, list): uuids = [uuids] result = [] for uuid in uuids: if uuid in self.subscriptions: ...
[ "def", "unsubscribe", "(", "self", ",", "event", ")", ":", "# TODO: Automatic Unsubscription", "uuids", "=", "event", ".", "data", "if", "not", "isinstance", "(", "uuids", ",", "list", ")", ":", "uuids", "=", "[", "uuids", "]", "result", "=", "[", "]", ...
26.642857
19.035714
def conditions_list(self, conkey): """ Return a (possibly empty) list of conditions based on conkey. The conditions are returned raw, not parsed. conkey: str for cond<n>, startcond<n> or stopcond<n>, specify only the prefix. The list will be filled with all condi...
[ "def", "conditions_list", "(", "self", ",", "conkey", ")", ":", "L", "=", "[", "]", "keys", "=", "[", "k", "for", "k", "in", "self", ".", "conditions", "if", "k", ".", "startswith", "(", "conkey", ")", "]", "# sloppy", "if", "not", "keys", ":", "...
32
18.5
def get_processor_name(): """Get the processor name. Returns ------- name : str the name of processor(host) """ mxlen = 256 length = ctypes.c_ulong() buf = ctypes.create_string_buffer(mxlen) _LIB.RabitGetProcessorName(buf, ctypes.byref(length), mxlen) return buf.value
[ "def", "get_processor_name", "(", ")", ":", "mxlen", "=", "256", "length", "=", "ctypes", ".", "c_ulong", "(", ")", "buf", "=", "ctypes", ".", "create_string_buffer", "(", "mxlen", ")", "_LIB", ".", "RabitGetProcessorName", "(", "buf", ",", "ctypes", ".", ...
23.461538
17.538462