text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def addPixmap(self, pixmap): """ Adds the pixmap to the list for this slider. :param pixmap | <QPixmap> || <str> """ scene = self.scene() scene.addItem(XImageItem(pixmap)) self.recalculate()
[ "def", "addPixmap", "(", "self", ",", "pixmap", ")", ":", "scene", "=", "self", ".", "scene", "(", ")", "scene", ".", "addItem", "(", "XImageItem", "(", "pixmap", ")", ")", "self", ".", "recalculate", "(", ")" ]
28.888889
10
async def _check_resolver_ans( self, dns_answer_list, record_name, record_data_list, record_ttl, record_type_code): """Check if resolver answer is equal to record data. Args: dns_answer_list (list): DNS answer list contains record objects. record_name (st...
[ "async", "def", "_check_resolver_ans", "(", "self", ",", "dns_answer_list", ",", "record_name", ",", "record_data_list", ",", "record_ttl", ",", "record_type_code", ")", ":", "type_filtered_list", "=", "[", "ans", "for", "ans", "in", "dns_answer_list", "if", "ans"...
37.055556
19.416667
def clean(self, value): """Clean Uses the valid method to check which type the value is, and then calls the correct version of clean on that node Arguments: value {mixed} -- The value to clean Returns: mixed """ # If the value is None and it's optional, return as is if value is None and self._...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "# If the value is None and it's optional, return as is", "if", "value", "is", "None", "and", "self", ".", "_optional", ":", "return", "None", "# Go through each of the nodes", "for", "i", "in", "range", "(", "l...
20.142857
21.178571
def _is_type_compatible(a, b): """helper for interval_range to check type compat of start/end/freq""" is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset)) is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset)) return ((is_number(a) and is_number(b)) or (is_ts_compat(a) an...
[ "def", "_is_type_compatible", "(", "a", ",", "b", ")", ":", "is_ts_compat", "=", "lambda", "x", ":", "isinstance", "(", "x", ",", "(", "Timestamp", ",", "DateOffset", ")", ")", "is_td_compat", "=", "lambda", "x", ":", "isinstance", "(", "x", ",", "(", ...
52.5
12.75
def list(self, date_created_before=values.unset, date_created=values.unset, date_created_after=values.unset, limit=None, page_size=None): """ Lists MediaInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memor...
[ "def", "list", "(", "self", ",", "date_created_before", "=", "values", ".", "unset", ",", "date_created", "=", "values", ".", "unset", ",", "date_created_after", "=", "values", ".", "unset", ",", "limit", "=", "None", ",", "page_size", "=", "None", ")", ...
56.37037
29.777778
def key_for_request(self, method, url, **kwargs): """ Return a cache key from a given set of request parameters. Default behavior is to return a complete URL for all GET requests, and None otherwise. Can be overriden if caching of non-get requests is desired. """ ...
[ "def", "key_for_request", "(", "self", ",", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "if", "method", "!=", "'get'", ":", "return", "None", "return", "requests", ".", "Request", "(", "url", "=", "url", ",", "params", "=", "kwargs", "."...
37.25
22.166667
def wbmax(self, value=None): """ Corresponds to IDD Field `wbmax` Extreme maximum wet-bulb temperature Args: value (float): value for IDD Field `wbmax` Unit: C if `value` is None it will not be checked against the specification and is...
[ "def", "wbmax", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '"...
33.190476
19.380952
def analyze_fa(fa): """ analyze fa (names, insertions) and convert fasta to prodigal/cmscan safe file - find insertions (masked sequence) - make upper case - assign names to id number """ if fa.name == '<stdin>': safe = 'temp.id' else: safe = '%s.id' % (fa.name) safe ...
[ "def", "analyze_fa", "(", "fa", ")", ":", "if", "fa", ".", "name", "==", "'<stdin>'", ":", "safe", "=", "'temp.id'", "else", ":", "safe", "=", "'%s.id'", "%", "(", "fa", ".", "name", ")", "safe", "=", "open", "(", "safe", ",", "'w'", ")", "sequen...
31.848485
15.30303
def remove_absolute_impute__r2(X, y, model_generator, method_name, num_fcounts=11): """ Remove Absolute (impute) xlabel = "Max fraction of features removed" ylabel = "1 - R^2" transform = "one_minus" sort_order = 9 """ return __run_measure(measures.remove_impute, X, y, model_generator, metho...
[ "def", "remove_absolute_impute__r2", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ",", "num_fcounts", "=", "11", ")", ":", "return", "__run_measure", "(", "measures", ".", "remove_impute", ",", "X", ",", "y", ",", "model_generator", ",", "...
45.25
23.625
def path_to_filename(pathfile): ''' Takes a path filename string and returns the split between the path and the filename if filename is not given, filename = '' if path is not given, path = './' ''' path = pathfile[:pathfile.rfind('/') + 1] if path == '': path = './' filename...
[ "def", "path_to_filename", "(", "pathfile", ")", ":", "path", "=", "pathfile", "[", ":", "pathfile", ".", "rfind", "(", "'/'", ")", "+", "1", "]", "if", "path", "==", "''", ":", "path", "=", "'./'", "filename", "=", "pathfile", "[", "pathfile", ".", ...
24.045455
24.590909
def write_case_data(self, file): """ Writes the header to file. """ case_sheet = self.book.add_sheet("Case") case_sheet.write(0, 0, "Name") case_sheet.write(0, 1, self.case.name) case_sheet.write(1, 0, "base_mva") case_sheet.write(1, 1, self.case.base_mva)
[ "def", "write_case_data", "(", "self", ",", "file", ")", ":", "case_sheet", "=", "self", ".", "book", ".", "add_sheet", "(", "\"Case\"", ")", "case_sheet", ".", "write", "(", "0", ",", "0", ",", "\"Name\"", ")", "case_sheet", ".", "write", "(", "0", ...
38.125
4.5
def my_psd(x,NFFT=2**10,Fs=1): """ A local version of NumPy's PSD function that returns the plot arrays. A mlab.psd wrapper function that returns two ndarrays; makes no attempt to auto plot anything. Parameters ---------- x : ndarray input signal NFFT : a power of two, e.g., 2**10 = 10...
[ "def", "my_psd", "(", "x", ",", "NFFT", "=", "2", "**", "10", ",", "Fs", "=", "1", ")", ":", "Px", ",", "f", "=", "pylab", ".", "mlab", ".", "psd", "(", "x", ",", "NFFT", ",", "Fs", ")", "return", "Px", ".", "flatten", "(", ")", ",", "f" ...
27.138889
18.416667
def get_session_data(ctx, username, password, salt, server_public, private, preset): """Print out client session data.""" session = SRPClientSession( SRPContext(username, password, prime=preset[0], generator=preset[1]), private=private) session.process(server_public, salt, base64=True) ...
[ "def", "get_session_data", "(", "ctx", ",", "username", ",", "password", ",", "salt", ",", "server_public", ",", "private", ",", "preset", ")", ":", "session", "=", "SRPClientSession", "(", "SRPContext", "(", "username", ",", "password", ",", "prime", "=", ...
46.727273
25.818182
def parse(self, file): ''' Method the programmer should call when ready to parse a file. :param file: exact file path of the file to be processed :return: PieceTree object representing the file in memory ''' parser = make_parser() self.clear() class Extra...
[ "def", "parse", "(", "self", ",", "file", ")", ":", "parser", "=", "make_parser", "(", ")", "self", ".", "clear", "(", ")", "class", "Extractor", "(", "xml", ".", "sax", ".", "ContentHandler", ")", ":", "def", "__init__", "(", "self", ",", "parent", ...
33.1875
17.1875
def global_defaults(): """ Default configuration values and behavior toggles. Fabric only extends this method in order to make minor adjustments and additions to Invoke's `~invoke.config.Config.global_defaults`; see its documentation for the base values, such as the config subtr...
[ "def", "global_defaults", "(", ")", ":", "# TODO: hrm should the run-related things actually be derived from the", "# runner_class? E.g. Local defines local stuff, Remote defines remote", "# stuff? Doesn't help with the final config tree tho...", "# TODO: as to that, this is a core problem, Fabric w...
46.954545
21.5
def get_nearest(self, lat, lng, skip_cache=False): """ Calls `postcodes.get_nearest` but checks correctness of `lat` and `long`, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache and make an exp...
[ "def", "get_nearest", "(", "self", ",", "lat", ",", "lng", ",", "skip_cache", "=", "False", ")", ":", "lat", ",", "lng", "=", "float", "(", "lat", ")", ",", "float", "(", "lng", ")", "self", ".", "_check_point", "(", "lat", ",", "lng", ")", "retu...
41.125
20.375
def run(self, default=None): """Parse the command line arguments. default: Name of default command to run if no arguments are passed. """ parent, *sys_args = sys.argv self.parent = Path(parent).stem cmd_name = default if sys_args: cmd_nam...
[ "def", "run", "(", "self", ",", "default", "=", "None", ")", ":", "parent", ",", "", "*", "sys_args", "=", "sys", ".", "argv", "self", ".", "parent", "=", "Path", "(", "parent", ")", ".", "stem", "cmd_name", "=", "default", "if", "sys_args", ":", ...
28.76
17.44
def _set_ospf1(self, v, load=False): """ Setter method for ospf1, mapped from YANG variable /routing_system/interface/ve/ip/interface_vlan_ospf_conf/ospf1 (container) If this variable is read-only (config: false) in the source YANG file, then _set_ospf1 is considered as a private method. Backends lo...
[ "def", "_set_ospf1", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
82.681818
39.636364
def get_catalogs_by_query(self, catalog_query): """Gets a list of ``Catalogs`` matching the given catalog query. arg: catalog_query (osid.cataloging.CatalogQuery): the catalog query return: (osid.cataloging.CatalogList) - the returned ``CatalogList`` r...
[ "def", "get_catalogs_by_query", "(", "self", ",", "catalog_query", ")", ":", "# Implemented from template for", "# osid.resource.BinQuerySession.get_bins_by_query_template", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_se...
48.88
20.04
def choose_locale(self, locale: Text) -> Text: """ Returns the best matching locale in what is available. :param locale: Locale to match :return: Locale to use """ if locale not in self._choice_cache: locales = self.list_locales() best_choice = ...
[ "def", "choose_locale", "(", "self", ",", "locale", ":", "Text", ")", "->", "Text", ":", "if", "locale", "not", "in", "self", ".", "_choice_cache", ":", "locales", "=", "self", ".", "list_locales", "(", ")", "best_choice", "=", "locales", "[", "0", "]"...
26.916667
16.083333
def get_JWT(url, address=None): """ Given a URL, fetch and decode the JWT it points to. If address is given, then authenticate the JWT with the address. Return None if we could not fetch it, or unable to authenticate it. NOTE: the URL must be usable by the requests library """ jwt_txt = No...
[ "def", "get_JWT", "(", "url", ",", "address", "=", "None", ")", ":", "jwt_txt", "=", "None", "jwt", "=", "None", "log", ".", "debug", "(", "\"Try {}\"", ".", "format", "(", "url", ")", ")", "# special case: handle file://", "urlinfo", "=", "urllib2", "."...
34.347368
24.221053
async def _dump_container(self, writer, container, container_type, params=None): """ Dumps container of elements to the writer. :param writer: :param container: :param container_type: :param params: :return: """ await self._dump_container_size(wri...
[ "async", "def", "_dump_container", "(", "self", ",", "writer", ",", "container", ",", "container_type", ",", "params", "=", "None", ")", ":", "await", "self", ".", "_dump_container_size", "(", "writer", ",", "len", "(", "container", ")", ",", "container_type...
34.391304
20.043478
def call_backward(self, proj_data, out=None): """Run an ASTRA back-projection on the given data using the GPU. Parameters ---------- proj_data : ``proj_space`` element Projection data to which the back-projector is applied. out : ``reco_space`` element, optional ...
[ "def", "call_backward", "(", "self", ",", "proj_data", ",", "out", "=", "None", ")", ":", "with", "self", ".", "_mutex", ":", "assert", "proj_data", "in", "self", ".", "proj_space", "if", "out", "is", "not", "None", ":", "assert", "out", "in", "self", ...
38.130435
18.847826
def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' ps...
[ "def", "avail_modules", "(", "desc", "=", "False", ")", ":", "cmd", "=", "'Find-Module'", "modules", "=", "_pshell", "(", "cmd", ")", "names", "=", "[", "]", "if", "desc", ":", "names", "=", "{", "}", "for", "module", "in", "modules", ":", "if", "d...
24.24
22.96
def parse_ports(ports_text): """Parse ports text e.g. ports_text = "12345,13000-15000,20000-30000" """ ports_set = set() for bit in ports_text.split(','): if '-' in bit: low, high = bit.split('-', 1) ports_set = ports_set.union(range(int(low), int(high) + 1)) ...
[ "def", "parse_ports", "(", "ports_text", ")", ":", "ports_set", "=", "set", "(", ")", "for", "bit", "in", "ports_text", ".", "split", "(", "','", ")", ":", "if", "'-'", "in", "bit", ":", "low", ",", "high", "=", "bit", ".", "split", "(", "'-'", "...
29.615385
13.461538
def helper_for_plot_data(self, X, plot_limits, visible_dims, fixed_inputs, resolution): """ Figure out the data, free_dims and create an Xgrid for the prediction. This is only implemented for two dimensions for now! """ #work out what the inputs are for plotting (1D or 2D) if fixed_inputs i...
[ "def", "helper_for_plot_data", "(", "self", ",", "X", ",", "plot_limits", ",", "visible_dims", ",", "fixed_inputs", ",", "resolution", ")", ":", "#work out what the inputs are for plotting (1D or 2D)", "if", "fixed_inputs", "is", "None", ":", "fixed_inputs", "=", "[",...
41.25
19.472222
def make_request(name, params=None, version="V001", key=None, api_type="web", fetcher=get_page, base=None, language="en_us"): """ Make an API request """ params = params or {} params["key"] = key or API_KEY params["language"] = language if not params["key"]: raise ...
[ "def", "make_request", "(", "name", ",", "params", "=", "None", ",", "version", "=", "\"V001\"", ",", "key", "=", "None", ",", "api_type", "=", "\"web\"", ",", "fetcher", "=", "get_page", ",", "base", "=", "None", ",", "language", "=", "\"en_us\"", ")"...
30.666667
21.333333
def ancestors(self): """A list of this browse node's ancestors in the browse node tree. :return: List of :class:`~.AmazonBrowseNode` objects. """ ancestors = [] node = self.ancestor while node is not None: ancestors.append(node) node =...
[ "def", "ancestors", "(", "self", ")", ":", "ancestors", "=", "[", "]", "node", "=", "self", ".", "ancestor", "while", "node", "is", "not", "None", ":", "ancestors", ".", "append", "(", "node", ")", "node", "=", "node", ".", "ancestor", "return", "anc...
29
14.083333
def batch_create_read_session_streams( self, session, requested_streams, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates additional streams for a ReadSession. This API can be...
[ "def", "batch_create_read_session_streams", "(", "self", ",", "session", ",", "requested_streams", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", "....
44.738636
26.329545
def exons(context, build): """Delete all exons in the database""" LOG.info("Running scout delete exons") adapter = context.obj['adapter'] adapter.drop_exons(build)
[ "def", "exons", "(", "context", ",", "build", ")", ":", "LOG", ".", "info", "(", "\"Running scout delete exons\"", ")", "adapter", "=", "context", ".", "obj", "[", "'adapter'", "]", "adapter", ".", "drop_exons", "(", "build", ")" ]
29.166667
11.833333
def _setPath(cls): """ Sets the path of the custom configuration file """ cls._path = os.path.join(os.environ['NTA_DYNAMIC_CONF_DIR'], cls.customFileName)
[ "def", "_setPath", "(", "cls", ")", ":", "cls", ".", "_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'NTA_DYNAMIC_CONF_DIR'", "]", ",", "cls", ".", "customFileName", ")" ]
38.2
10.8
def attach(cls, training_job_name, sagemaker_session=None, model_channel_name='model'): """Attach to an existing training job. Create an Estimator bound to an existing training job, each subclass is responsible to implement ``_prepare_init_params_from_job_description()`` as this method delegate...
[ "def", "attach", "(", "cls", ",", "training_job_name", ",", "sagemaker_session", "=", "None", ",", "model_channel_name", "=", "'model'", ")", ":", "estimator", "=", "super", "(", "Framework", ",", "cls", ")", ".", "attach", "(", "training_job_name", ",", "sa...
60.444444
40.472222
def MaxPooling( inputs, pool_size, strides=None, padding='valid', data_format='channels_last'): """ Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size. """ if strides is None: strides = pool_size layer = tf.layers.MaxPooling2D(pool...
[ "def", "MaxPooling", "(", "inputs", ",", "pool_size", ",", "strides", "=", "None", ",", "padding", "=", "'valid'", ",", "data_format", "=", "'channels_last'", ")", ":", "if", "strides", "is", "None", ":", "strides", "=", "pool_size", "layer", "=", "tf", ...
33.428571
18.142857
def ReadPreprocessingInformation(self, knowledge_base): """Reads preprocessing information. The preprocessing information contains the system configuration which contains information about various system specific configuration data, for example the user accounts. Args: knowledge_base (Knowle...
[ "def", "ReadPreprocessingInformation", "(", "self", ",", "knowledge_base", ")", ":", "self", ".", "_RaiseIfNotWritable", "(", ")", "if", "self", ".", "_storage_type", "!=", "definitions", ".", "STORAGE_TYPE_SESSION", ":", "raise", "IOError", "(", "'Preprocessing inf...
39.571429
25.380952
def bifurcate_base(cls, newick): """ Rewrites a newick string so that the base is a bifurcation (rooted tree) """ t = cls(newick) t._tree.resolve_polytomies() return t.newick
[ "def", "bifurcate_base", "(", "cls", ",", "newick", ")", ":", "t", "=", "cls", "(", "newick", ")", "t", ".", "_tree", ".", "resolve_polytomies", "(", ")", "return", "t", ".", "newick" ]
34.833333
7.666667
def to_utf8(x): """ Tries to utf-8 encode x when possible If x is a string returns it encoded, otherwise tries to iter x and encode utf-8 all strings it contains, returning a list. """ if isinstance(x, basestring): return x.encode('utf-8') if isinstance(x, unicode) else x try: ...
[ "def", "to_utf8", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "basestring", ")", ":", "return", "x", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "x", ",", "unicode", ")", "else", "x", "try", ":", "l", "=", "iter", "(",...
28.428571
17.857143
def _input_as_parameters(self, data): """ Set the input path (a fasta filepath) """ # The list of values which can be passed on a per-run basis allowed_values = ['--input', '--uc', '--fastapairs', '--uc2clstr', '--output', '--mergesort'] unsupported_par...
[ "def", "_input_as_parameters", "(", "self", ",", "data", ")", ":", "# The list of values which can be passed on a per-run basis", "allowed_values", "=", "[", "'--input'", ",", "'--uc'", ",", "'--fastapairs'", ",", "'--uc2clstr'", ",", "'--output'", ",", "'--mergesort'", ...
40.909091
18.545455
def update_group(self, ID, data): """Update a Group.""" # http://teampasswordmanager.com/docs/api-groups/#update_group log.info('Update group %s with %s' % (ID, data)) self.put('groups/%s.json' % ID, data)
[ "def", "update_group", "(", "self", ",", "ID", ",", "data", ")", ":", "# http://teampasswordmanager.com/docs/api-groups/#update_group", "log", ".", "info", "(", "'Update group %s with %s'", "%", "(", "ID", ",", "data", ")", ")", "self", ".", "put", "(", "'groups...
46.6
11.6
def aes_cbc_pkcs7_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector ...
[ "def", "aes_cbc_pkcs7_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "not", "in", "[", "16", ",", "24", ",", "32", "]", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be either 16, ...
27.65
23.95
def circ_corrcc(x, y, tail='two-sided'): """Correlation coefficient between two circular variables. Parameters ---------- x : np.array First circular variable (expressed in radians) y : np.array Second circular variable (expressed in radians) tail : string Specify whethe...
[ "def", "circ_corrcc", "(", "x", ",", "y", ",", "tail", "=", "'two-sided'", ")", ":", "from", "scipy", ".", "stats", "import", "norm", "x", "=", "np", ".", "asarray", "(", "x", ")", "y", "=", "np", ".", "asarray", "(", "y", ")", "# Check size", "i...
27.546875
20.96875
def alter(self, id_filter, name, description): """Change Filter by the identifier. :param id_filter: Identifier of the Filter. Integer value and greater than zero. :param name: Name. String with a maximum of 50 characters and respect [a-zA-Z\_-] :param description: Description. String w...
[ "def", "alter", "(", "self", ",", "id_filter", ",", "name", ",", "description", ")", ":", "if", "not", "is_valid_int_param", "(", "id_filter", ")", ":", "raise", "InvalidParameterError", "(", "u'The identifier of Filter is invalid or was not informed.'", ")", "filter_...
40.689655
26.413793
def tag_labels(self): """Tag named entity labels in the ``words`` layer.""" if not self.is_tagged(ANALYSIS): self.tag_analysis() if self.__ner_tagger is None: self.__ner_tagger = load_default_ner_tagger() self.__ner_tagger.tag_document(self) return self
[ "def", "tag_labels", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "ANALYSIS", ")", ":", "self", ".", "tag_analysis", "(", ")", "if", "self", ".", "__ner_tagger", "is", "None", ":", "self", ".", "__ner_tagger", "=", "load_default_ner...
38.75
9.125
def filterAcceptsRow(self, row, parentindex): """Return True, if the filter accepts the given row of the parent :param row: the row to filter :type row: :class:`int` :param parentindex: the parent index :type parentindex: :class:`QtCore.QModelIndex` :returns: True, if th...
[ "def", "filterAcceptsRow", "(", "self", ",", "row", ",", "parentindex", ")", ":", "if", "not", "super", "(", "ReftrackSortFilterModel", ",", "self", ")", ".", "filterAcceptsRow", "(", "row", ",", "parentindex", ")", ":", "return", "False", "if", "parentindex...
34.5
14.583333
def get_base_level(text, upper_is_rtl=False): """Get the paragraph base embedding level. Returns 0 for LTR, 1 for RTL. `text` a unicode object. Set `upper_is_rtl` to True to treat upper case chars as strong 'R' for debugging (default: False). """ base_level = None prev_surrogate = F...
[ "def", "get_base_level", "(", "text", ",", "upper_is_rtl", "=", "False", ")", ":", "base_level", "=", "None", "prev_surrogate", "=", "False", "# P2", "for", "_ch", "in", "text", ":", "# surrogate in case of ucs2", "if", "_IS_UCS2", "and", "(", "_SURROGATE_MIN", ...
22.25
20.659091
def usnjrnl_timeline(self): """Iterates over the changes occurred within the filesystem. Yields UsnJrnlEvent namedtuples containing: file_reference_number: known in Unix FS as inode. path: full path of the file. size: size of the file in bytes if recoverable. ...
[ "def", "usnjrnl_timeline", "(", "self", ")", ":", "filesystem_content", "=", "defaultdict", "(", "list", ")", "self", ".", "logger", ".", "debug", "(", "\"Extracting Update Sequence Number journal.\"", ")", "journal", "=", "self", ".", "_read_journal", "(", ")", ...
36.56
20.2
def differing_blocks(self): """ :returns: A list of block matches which appear to differ """ differing_blocks = [] for (block_a, block_b) in self._block_matches: if not self.blocks_probably_identical(block_a, block_b): differing_blocks.append((block_a,...
[ "def", "differing_blocks", "(", "self", ")", ":", "differing_blocks", "=", "[", "]", "for", "(", "block_a", ",", "block_b", ")", "in", "self", ".", "_block_matches", ":", "if", "not", "self", ".", "blocks_probably_identical", "(", "block_a", ",", "block_b", ...
39.333333
13.111111
def competition_submit_cli(self, file_name, message, competition, competition_opt=None, quiet=False): """ submit a competition using the client. Arguments ar...
[ "def", "competition_submit_cli", "(", "self", ",", "file_name", ",", "message", ",", "competition", ",", "competition_opt", "=", "None", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competition", "or", "competition_opt", "try", ":", "submit_result"...
44.6
16.56
def proper_kwargs(self, section, kwargs): """Returns kwargs updated with proper meta variables (like __assistant__). If this method is run repeatedly with the same section and the same kwargs, it always modifies kwargs in the same way. """ kwargs['__section__'] = section ...
[ "def", "proper_kwargs", "(", "self", ",", "section", ",", "kwargs", ")", ":", "kwargs", "[", "'__section__'", "]", "=", "section", "kwargs", "[", "'__assistant__'", "]", "=", "self", "kwargs", "[", "'__env__'", "]", "=", "copy", ".", "deepcopy", "(", "os...
46.333333
12.722222
def parse_compounds(compound_info, case_id, variant_type): """Get a list with compounds objects for this variant. Arguments: compound_info(str): A Variant dictionary case_id (str): unique family id variant_type(str): 'research' or 'clinical' Returns: ...
[ "def", "parse_compounds", "(", "compound_info", ",", "case_id", ",", "variant_type", ")", ":", "# We need the case to construct the correct id", "compounds", "=", "[", "]", "if", "compound_info", ":", "for", "family_info", "in", "compound_info", ".", "split", "(", "...
38.888889
19.916667
def on_press(self, event): 'on but-ton press we will see if the mouse is over us and store data' if event.inaxes != self.ax: return # contains, attrd = self.rect.contains(event) # if not contains: return # print('event contains', self.rect.xy) # x0, y0 ...
[ "def", "on_press", "(", "self", ",", "event", ")", ":", "if", "event", ".", "inaxes", "!=", "self", ".", "ax", ":", "return", "# contains, attrd = self.rect.contains(event)\r", "# if not contains: return\r", "# print('event contains', self.rect.xy)\r", "# x0, y0 = self.rect...
43.444444
15
def _getTimeStamps(self, table): ''' get time stamps ''' timeStamps = [] for th in table.thead.tr.contents: if '\n' != th: timeStamps.append(th.getText()) return timeStamps[1:]
[ "def", "_getTimeStamps", "(", "self", ",", "table", ")", ":", "timeStamps", "=", "[", "]", "for", "th", "in", "table", ".", "thead", ".", "tr", ".", "contents", ":", "if", "'\\n'", "!=", "th", ":", "timeStamps", ".", "append", "(", "th", ".", "getT...
29.625
13.125
def drop_zombies(feed: "Feed") -> "Feed": """ In the given "Feed", drop stops with no stop times, trips with no stop times, shapes with no trips, routes with no trips, and services with no trips, in that order. Return the resulting "Feed". """ feed = feed.copy() # Drop stops of location...
[ "def", "drop_zombies", "(", "feed", ":", "\"Feed\"", ")", "->", "\"Feed\"", ":", "feed", "=", "feed", ".", "copy", "(", ")", "# Drop stops of location type 0 that lack stop times", "ids", "=", "feed", ".", "stop_times", "[", "\"stop_id\"", "]", ".", "unique", ...
30.348837
14.162791
def add(self, it: Signature) -> bool: """ Add it to the Set """ if isinstance(it, Scope): it.state = StateScope.EMBEDDED txt = it.internal_name() it.set_parent(self) if self.is_namespace: txt = it.internal_name() if txt == "": txt = '_'...
[ "def", "add", "(", "self", ",", "it", ":", "Signature", ")", "->", "bool", ":", "if", "isinstance", "(", "it", ",", "Scope", ")", ":", "it", ".", "state", "=", "StateScope", ".", "EMBEDDED", "txt", "=", "it", ".", "internal_name", "(", ")", "it", ...
32.8
9.266667
def patch_module(module, name, replacement, original=UNSPECIFIED, aliases=True, location=None, **_bogus_options): """ Low-level attribute patcher. :param module module: Object to patch. :param str name: Attribute to patch :param replacement: The replacement value. :param original: The original ...
[ "def", "patch_module", "(", "module", ",", "name", ",", "replacement", ",", "original", "=", "UNSPECIFIED", ",", "aliases", "=", "True", ",", "location", "=", "None", ",", "*", "*", "_bogus_options", ")", ":", "rollback", "=", "Rollback", "(", ")", "seen...
46.74
23.78
def _related_field_data(field, obj): """Returns relation ``field`` as a dict. Dict contains related pk info and some meta information for reconstructing objects. """ data = _basic_field_data(field, obj) relation_info = { Field.REL_DB_TABLE: field.rel.to._meta.db_table, Field.REL...
[ "def", "_related_field_data", "(", "field", ",", "obj", ")", ":", "data", "=", "_basic_field_data", "(", "field", ",", "obj", ")", "relation_info", "=", "{", "Field", ".", "REL_DB_TABLE", ":", "field", ".", "rel", ".", "to", ".", "_meta", ".", "db_table"...
32.2
12.933333
def _discover(**kwargs): """Yields info about station servers announcing themselves via multicast.""" query = station_server.MULTICAST_QUERY for host, response in multicast.send(query, **kwargs): try: result = json.loads(response) except ValueError: _LOG.warn('Received bad JSON over multicast ...
[ "def", "_discover", "(", "*", "*", "kwargs", ")", ":", "query", "=", "station_server", ".", "MULTICAST_QUERY", "for", "host", ",", "response", "in", "multicast", ".", "send", "(", "query", ",", "*", "*", "kwargs", ")", ":", "try", ":", "result", "=", ...
44.555556
19.333333
def precision(self, label=None): """ Returns precision or precision for a given label (category) if specified. """ if label is None: return self.call("precision") else: return self.call("precision", float(label))
[ "def", "precision", "(", "self", ",", "label", "=", "None", ")", ":", "if", "label", "is", "None", ":", "return", "self", ".", "call", "(", "\"precision\"", ")", "else", ":", "return", "self", ".", "call", "(", "\"precision\"", ",", "float", "(", "la...
33.625
13.375
def convert_coord_object(coord): """Convert ModestMaps.Core.Coordinate -> raw_tiles.tile.Tile""" assert isinstance(coord, Coordinate) coord = coord.container() return Tile(int(coord.zoom), int(coord.column), int(coord.row))
[ "def", "convert_coord_object", "(", "coord", ")", ":", "assert", "isinstance", "(", "coord", ",", "Coordinate", ")", "coord", "=", "coord", ".", "container", "(", ")", "return", "Tile", "(", "int", "(", "coord", ".", "zoom", ")", ",", "int", "(", "coor...
47
9.2
def dump_molecule(self, filepath=None, include_coms=False, **kwargs): """ Dump a :class:`Molecule` to a file (PDB or XYZ). Kwargs are passed to :func:`pywindow.io_tools.Output.dump2file()`. For validation purposes an overlay of window centres and COMs can also be dumped as: ...
[ "def", "dump_molecule", "(", "self", ",", "filepath", "=", "None", ",", "include_coms", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# If no filepath is provided we create one.", "if", "filepath", "is", "None", ":", "filepath", "=", "\"_\"", ".", "join", ...
40.402174
18.880435
def get(self, terser): """ Get a value in the HL7 dictionary. The terser can be fully qualified or not. Fully qualified : OBR[1]-10-01 Simpliest form : OBR-10-1 (in this case, 1 uniq segment OBR is present in the HL7 message) :return : the value or a list of val...
[ "def", "get", "(", "self", ",", "terser", ")", ":", "key", "=", "terser", "# if the expression in not found n the qualified names", "# find the alias", "if", "terser", "not", "in", "self", ".", "data", "and", "terser", "in", "self", ".", "aliasKeys", ":", "key",...
38.384615
23.384615
def runner(opts, utils=None, context=None, whitelist=None): ''' Directly call a function inside a loader directory ''' if utils is None: utils = {} if context is None: context = {} ret = LazyLoader( _module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'), ...
[ "def", "runner", "(", "opts", ",", "utils", "=", "None", ",", "context", "=", "None", ",", "whitelist", "=", "None", ")", ":", "if", "utils", "is", "None", ":", "utils", "=", "{", "}", "if", "context", "is", "None", ":", "context", "=", "{", "}",...
31
23.333333
def _custom_rdd_reduce(self, reduce_func): """Provides a custom RDD reduce which preserves ordering if the RDD has been sorted. This is useful for us because we need this functionality as many pandas operations support sorting the results. The standard reduce in PySpark does not have thi...
[ "def", "_custom_rdd_reduce", "(", "self", ",", "reduce_func", ")", ":", "def", "accumulating_iter", "(", "iterator", ")", ":", "acc", "=", "None", "for", "obj", "in", "iterator", ":", "if", "acc", "is", "None", ":", "acc", "=", "obj", "else", ":", "acc...
46.666667
15.388889
def get_details(var): """ Given a variable inside the context, obtain the attributes/callables, their values where possible, and the module name and class name if possible """ var_data = {} # Obtain module and class details if available and add them in module = getattr(var, '__module__', '')...
[ "def", "get_details", "(", "var", ")", ":", "var_data", "=", "{", "}", "# Obtain module and class details if available and add them in", "module", "=", "getattr", "(", "var", ",", "'__module__'", ",", "''", ")", "kls", "=", "getattr", "(", "getattr", "(", "var",...
36.111111
15.222222
def vcirc(self,R,phi=None): """ NAME: vcirc PURPOSE: calculate the circular velocity at R in potential Pot INPUT: Pot - Potential instance or list of such instances R - Galactocentric r...
[ "def", "vcirc", "(", "self", ",", "R", ",", "phi", "=", "None", ")", ":", "return", "nu", ".", "sqrt", "(", "R", "*", "-", "self", ".", "Rforce", "(", "R", ",", "phi", "=", "phi", ",", "use_physical", "=", "False", ")", ")" ]
23.193548
26.096774
def oauth_client_create(self, name, redirect_uri, **kwargs): """ Make a new OAuth Client and return it """ params = { "label": name, "redirect_uri": redirect_uri, } params.update(kwargs) result = self.client.post('/account/oauth-clients', ...
[ "def", "oauth_client_create", "(", "self", ",", "name", ",", "redirect_uri", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "\"label\"", ":", "name", ",", "\"redirect_uri\"", ":", "redirect_uri", ",", "}", "params", ".", "update", "(", "kwargs", ...
30.555556
20.444444
def _call_handler(self, key, insert_text): """ Callback to handler. """ if isinstance(key, tuple): for k in key: self._call_handler(k, insert_text) else: if key == Keys.BracketedPaste: self._in_bracketed_paste = True ...
[ "def", "_call_handler", "(", "self", ",", "key", ",", "insert_text", ")", ":", "if", "isinstance", "(", "key", ",", "tuple", ")", ":", "for", "k", "in", "key", ":", "self", ".", "_call_handler", "(", "k", ",", "insert_text", ")", "else", ":", "if", ...
32.692308
10.076923
def _fullname(o): """Return the fully-qualified name of a function.""" return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__
[ "def", "_fullname", "(", "o", ")", ":", "return", "o", ".", "__module__", "+", "\".\"", "+", "o", ".", "__name__", "if", "o", ".", "__module__", "else", "o", ".", "__name__" ]
49
19
def validate(self, signed_value, max_age=None): """Just validates the given signed value. Returns `True` if the signature exists and is valid, `False` otherwise.""" try: self.unsign(signed_value, max_age=max_age) return True except BadSignature: retur...
[ "def", "validate", "(", "self", ",", "signed_value", ",", "max_age", "=", "None", ")", ":", "try", ":", "self", ".", "unsign", "(", "signed_value", ",", "max_age", "=", "max_age", ")", "return", "True", "except", "BadSignature", ":", "return", "False" ]
40
11.75
def set_zones_device_assignment(self, internal_devices, external_devices) -> dict: """ sets the devices for the security zones Args: internal_devices(List[Device]): the devices which should be used for the internal zone external_devices(List[Device]): the devices which shoul...
[ "def", "set_zones_device_assignment", "(", "self", ",", "internal_devices", ",", "external_devices", ")", "->", "dict", ":", "internal", "=", "[", "x", ".", "id", "for", "x", "in", "internal_devices", "]", "external", "=", "[", "x", ".", "id", "for", "x", ...
49
26.6
def deliver_tx(self, raw_transaction): """Validate the transaction before mutating the state. Args: raw_tx: a raw string (in bytes) transaction. """ self.abort_if_abci_chain_is_not_synced() logger.debug('deliver_tx: %s', raw_transaction) transaction = self....
[ "def", "deliver_tx", "(", "self", ",", "raw_transaction", ")", ":", "self", ".", "abort_if_abci_chain_is_not_synced", "(", ")", "logger", ".", "debug", "(", "'deliver_tx: %s'", ",", "raw_transaction", ")", "transaction", "=", "self", ".", "bigchaindb", ".", "is_...
36.047619
18.380952
def init_random(X, n_clusters, random_state): """K-means initialization using randomly chosen points""" logger.info("Initializing randomly") idx = sorted(draw_seed(random_state, 0, len(X), size=n_clusters)) centers = X[idx].compute() return centers
[ "def", "init_random", "(", "X", ",", "n_clusters", ",", "random_state", ")", ":", "logger", ".", "info", "(", "\"Initializing randomly\"", ")", "idx", "=", "sorted", "(", "draw_seed", "(", "random_state", ",", "0", ",", "len", "(", "X", ")", ",", "size",...
43.833333
11
def _meanOmega_num_approx(self,dangle,tdisrupt,higherorder=False): """Compute the numerator going into meanOmega using the direct integration of the spline representation""" # First construct the breakpoints for this dangle Oparb= (dangle-self._kick_interpdOpar_poly.x)/self._timpact # Fi...
[ "def", "_meanOmega_num_approx", "(", "self", ",", "dangle", ",", "tdisrupt", ",", "higherorder", "=", "False", ")", ":", "# First construct the breakpoints for this dangle", "Oparb", "=", "(", "dangle", "-", "self", ".", "_kick_interpdOpar_poly", ".", "x", ")", "/...
62.324324
23.297297
def end(self, *args, **kwargs): """ Writes the passed chunk, flushes it to the client, and terminates the connection. """ self.send(*args, **kwargs) self.close()
[ "def", "end", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "send", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "close", "(", ")" ]
29
7.857143
def put_httpsconf(self, name, certid, forceHttps): """ 修改证书,文档 https://developer.qiniu.com/fusion/api/4246/the-domain-name#11 Args: domains: 域名name CertID: 证书id,从上传或者获取证书列表里拿到证书id ForceHttps: 是否强制https跳转 Returns: {} """ ...
[ "def", "put_httpsconf", "(", "self", ",", "name", ",", "certid", ",", "forceHttps", ")", ":", "req", "=", "{", "}", "req", ".", "update", "(", "{", "\"certid\"", ":", "certid", "}", ")", "req", ".", "update", "(", "{", "\"forceHttps\"", ":", "forceHt...
28.210526
17.894737
def _get_request_token(self): """ Obtain a temporary request token to authorize an access token and to sign the request to obtain the access token """ if self.request_token is None: get_params = {} if self.parameters: get_params.update(self...
[ "def", "_get_request_token", "(", "self", ")", ":", "if", "self", ".", "request_token", "is", "None", ":", "get_params", "=", "{", "}", "if", "self", ".", "parameters", ":", "get_params", ".", "update", "(", "self", ".", "parameters", ")", "get_params", ...
48.791667
15.291667
def parse_nargs(self, nargs): """ Nargs is essentially a multi-type encoding. We have to parse it to understand how many values this action may consume. """ self.max_args = self.min_args = 0 if nargs is None: self.max_args = self.min_args = 1 elif nargs == argparse.O...
[ "def", "parse_nargs", "(", "self", ",", "nargs", ")", ":", "self", ".", "max_args", "=", "self", ".", "min_args", "=", "0", "if", "nargs", "is", "None", ":", "self", ".", "max_args", "=", "self", ".", "min_args", "=", "1", "elif", "nargs", "==", "a...
42.666667
7.333333
def initialize_base(self, es): """set parameters and state variable based on dimension, mueff and possibly further options. """ ## meta_parameters.cs_exponent == 1.0 b = 1.0 ## meta_parameters.cs_multiplier == 1.0 self.cs = 1.0 * (es.sp.mueff + 2)**b / (es.N**b +...
[ "def", "initialize_base", "(", "self", ",", "es", ")", ":", "## meta_parameters.cs_exponent == 1.0", "b", "=", "1.0", "## meta_parameters.cs_multiplier == 1.0", "self", ".", "cs", "=", "1.0", "*", "(", "es", ".", "sp", ".", "mueff", "+", "2", ")", "**", "b",...
35.333333
13.25
def get_hooks(self): """ :calls: `GET /orgs/:owner/hooks <http://developer.github.com/v3/orgs/hooks>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Hook.Hook` """ return github.PaginatedList.PaginatedList( github.Hook.Hook, self._r...
[ "def", "get_hooks", "(", "self", ")", ":", "return", "github", ".", "PaginatedList", ".", "PaginatedList", "(", "github", ".", "Hook", ".", "Hook", ",", "self", ".", "_requester", ",", "self", ".", "url", "+", "\"/hooks\"", ",", "None", ")" ]
34.454545
19
def _set_internal_value(self, new_internal_value): """ This is supposed to be only used by fitting engines :param new_internal_value: new value in internal representation :return: none """ if new_internal_value != self._internal_value: self._internal_value ...
[ "def", "_set_internal_value", "(", "self", ",", "new_internal_value", ")", ":", "if", "new_internal_value", "!=", "self", ".", "_internal_value", ":", "self", ".", "_internal_value", "=", "new_internal_value", "# Call callbacks if any", "for", "callback", "in", "self"...
25.823529
21.470588
def process_delta(delta): """ This is the part of the code where you would process the information from the webhook notification. Each delta is one change that happened, and might require fetching message IDs, updating your database, and so on. However, because this is just an example project, ...
[ "def", "process_delta", "(", "delta", ")", ":", "kwargs", "=", "{", "\"type\"", ":", "delta", "[", "\"type\"", "]", ",", "\"date\"", ":", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "delta", "[", "\"date\"", "]", ")", ",", "\"object_id\"", ...
38.882353
21.823529
def labeled_intervals(intervals, labels, label_set=None, base=None, height=None, extend_labels=True, ax=None, tick=True, **kwargs): '''Plot labeled intervals with each label on its own row. Parameters ---------- intervals : np.ndarray, shape=(n, 2) se...
[ "def", "labeled_intervals", "(", "intervals", ",", "labels", ",", "label_set", "=", "None", ",", "base", "=", "None", ",", "height", "=", "None", ",", "extend_labels", "=", "True", ",", "ax", "=", "None", ",", "tick", "=", "True", ",", "*", "*", "kwa...
32.409091
21.424242
def make_html_items( self, items ): """ convert a field's content into some valid HTML """ lines = [] for item in items: if item.lines: lines.append( self.make_html_code( item.lines ) ) else: lines.append( self.make_html_para( item.words )...
[ "def", "make_html_items", "(", "self", ",", "items", ")", ":", "lines", "=", "[", "]", "for", "item", "in", "items", ":", "if", "item", ".", "lines", ":", "lines", ".", "append", "(", "self", ".", "make_html_code", "(", "item", ".", "lines", ")", "...
35.6
16.8
def get_context(self): """ Create a dict with the context data context is not required, but if it is defined it should be a tuple """ if not self.context: return else: assert isinstance(self.context, tuple), 'Expected a Tuple not {0}'.forma...
[ "def", "get_context", "(", "self", ")", ":", "if", "not", "self", ".", "context", ":", "return", "else", ":", "assert", "isinstance", "(", "self", ".", "context", ",", "tuple", ")", ",", "'Expected a Tuple not {0}'", ".", "format", "(", "type", "(", "sel...
38.857143
15.285714
def user_segment(self): """ | Comment: The id of the user segment to which this section belongs """ if self.api and self.user_segment_id: return self.api._get_user_segment(self.user_segment_id)
[ "def", "user_segment", "(", "self", ")", ":", "if", "self", ".", "api", "and", "self", ".", "user_segment_id", ":", "return", "self", ".", "api", ".", "_get_user_segment", "(", "self", ".", "user_segment_id", ")" ]
38.833333
14.166667
def read(author, kind): """ Attempts to read the cache to fetch missing arguments. This method will attempt to find a '.license' file in the 'CACHE_DIRECTORY', to read any arguments that were not passed to the license utility. Arguments: author (str): The author passed, if any. k...
[ "def", "read", "(", "author", ",", "kind", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "CACHE_PATH", ")", ":", "raise", "LicenseError", "(", "'No cache found. You must '", "'supply at least -a and -k.'", ")", "cache", "=", "read_cache", "(", ...
26.357143
21.5
def do_groupby(environment, value, attribute): """Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the ...
[ "def", "do_groupby", "(", "environment", ",", "value", ",", "attribute", ")", ":", "expr", "=", "make_attrgetter", "(", "environment", ",", "attribute", ")", "return", "[", "_GroupTuple", "(", "key", ",", "list", "(", "values", ")", ")", "for", "key", ",...
32.829268
23.560976
def list(self, query_criteria=None, order_criteria=None): ''' a generator method to list records in table which match query criteria :param query_criteria: dictionary with schema dot-path field names and query qualifiers :param order_criteria: list of single key...
[ "def", "list", "(", "self", ",", "query_criteria", "=", "None", ",", "order_criteria", "=", "None", ")", ":", "title", "=", "'%s.list'", "%", "self", ".", "__class__", ".", "__name__", "from", "sqlalchemy", "import", "desc", "as", "order_desc", "# validate i...
45.69375
24.25625
def translate(ra, dec, r, theta): """ Translate a given point a distance r in the (initial) direction theta, along a great circle. Parameters ---------- ra, dec : float The initial point of interest (degrees). r, theta : float The distance and initial direction to translate (d...
[ "def", "translate", "(", "ra", ",", "dec", ",", "r", ",", "theta", ")", ":", "factor", "=", "np", ".", "sin", "(", "np", ".", "radians", "(", "dec", ")", ")", "*", "np", ".", "cos", "(", "np", ".", "radians", "(", "r", ")", ")", "factor", "...
33.6
24.48
def setRpms(self, package, build, build_ts, rpms): """Add/Update package rpm """ self._builds[package] = {"build": build, "build_ts": build_ts, "rpms": rpms}
[ "def", "setRpms", "(", "self", ",", "package", ",", "build", ",", "build_ts", ",", "rpms", ")", ":", "self", ".", "_builds", "[", "package", "]", "=", "{", "\"build\"", ":", "build", ",", "\"build_ts\"", ":", "build_ts", ",", "\"rpms\"", ":", "rpms", ...
40
12
def create_address(self, account_id, **params): """https://developers.coinbase.com/api/v2#create-address""" response = self._post('v2', 'accounts', account_id, 'addresses', data=params) return self._make_api_object(response, Address)
[ "def", "create_address", "(", "self", ",", "account_id", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "_post", "(", "'v2'", ",", "'accounts'", ",", "account_id", ",", "'addresses'", ",", "data", "=", "params", ")", "return", "self", ...
63.5
16.75
def _validate_nbf(claims, leeway=0): """Validates that the 'nbf' claim is valid. The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the "nbf" claim requires that the current date/time MUST be after or equal to the not-before...
[ "def", "_validate_nbf", "(", "claims", ",", "leeway", "=", "0", ")", ":", "if", "'nbf'", "not", "in", "claims", ":", "return", "try", ":", "nbf", "=", "int", "(", "claims", "[", "'nbf'", "]", ")", "except", "ValueError", ":", "raise", "JWTClaimsError",...
36.571429
24.928571
def asum(data, axis=None, mapper=None, blen=None, storage=None, create='array', **kwargs): """Compute the sum.""" return reduce_axis(data, axis=axis, reducer=np.sum, block_reducer=np.add, mapper=mapper, blen=blen, storage=storage, create=create, **kwargs)
[ "def", "asum", "(", "data", ",", "axis", "=", "None", ",", "mapper", "=", "None", ",", "blen", "=", "None", ",", "storage", "=", "None", ",", "create", "=", "'array'", ",", "*", "*", "kwargs", ")", ":", "return", "reduce_axis", "(", "data", ",", ...
52.166667
16.166667
def _fix_deps_repos(self, dependencies): """Fix store deps include in repository """ requires = [] for dep in dependencies: if dep in self.repo_pkg_names: requires.append(dep) return requires
[ "def", "_fix_deps_repos", "(", "self", ",", "dependencies", ")", ":", "requires", "=", "[", "]", "for", "dep", "in", "dependencies", ":", "if", "dep", "in", "self", ".", "repo_pkg_names", ":", "requires", ".", "append", "(", "dep", ")", "return", "requir...
31.5
6.25
async def status_by_state(self, state: str) -> dict: """Return the CDC status for the specified state.""" data = await self.raw_cdc_data() try: info = next((v for k, v in data.items() if state in k)) except StopIteration: return {} return adjust_status(i...
[ "async", "def", "status_by_state", "(", "self", ",", "state", ":", "str", ")", "->", "dict", ":", "data", "=", "await", "self", ".", "raw_cdc_data", "(", ")", "try", ":", "info", "=", "next", "(", "(", "v", "for", "k", ",", "v", "in", "data", "."...
31.5
18.3
def parse(self, lint_target): # type: (AbstractLintTarget) -> Dict[str, Any] """ Parse vim script file and return the AST. """ decoder = Decoder(default_decoding_strategy) decoded = decoder.decode(lint_target.read()) decoded_and_lf_normalized = decoded.replace('\r\n', '\n') ret...
[ "def", "parse", "(", "self", ",", "lint_target", ")", ":", "# type: (AbstractLintTarget) -> Dict[str, Any]", "decoder", "=", "Decoder", "(", "default_decoding_strategy", ")", "decoded", "=", "decoder", ".", "decode", "(", "lint_target", ".", "read", "(", ")", ")",...
51.714286
20.714286
def maximum_independent_set(G, sampler=None, lagrange=2.0, **sampler_args): """Returns an approximate maximum independent set. Defines a QUBO with ground states corresponding to a maximum independent set and uses the sampler to sample from it. An independent set is a set of nodes such that the sub...
[ "def", "maximum_independent_set", "(", "G", ",", "sampler", "=", "None", ",", "lagrange", "=", "2.0", ",", "*", "*", "sampler_args", ")", ":", "return", "maximum_weighted_independent_set", "(", "G", ",", "None", ",", "sampler", ",", "lagrange", ",", "*", "...
35.724638
26.927536
def debug(self, command): """ Posts a debug message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but thei...
[ "def", "debug", "(", "self", ",", "command", ")", ":", "if", "self", ".", "console_level", "==", "logging", ".", "DEBUG", ":", "message", "=", "self", ".", "get_format", "(", ")", "message", "=", "message", ".", "replace", "(", "'{L}'", ",", "'DEBUG'",...
47.909091
30.090909
def find_val(self, eq, val): """Return the name of the equation having the given value""" if eq not in ('f', 'g', 'q'): return elif eq in ('f', 'q'): key = 'unamex' elif eq == 'g': key = 'unamey' idx = 0 for m, n in zip(self.system.varn...
[ "def", "find_val", "(", "self", ",", "eq", ",", "val", ")", ":", "if", "eq", "not", "in", "(", "'f'", ",", "'g'", ",", "'q'", ")", ":", "return", "elif", "eq", "in", "(", "'f'", ",", "'q'", ")", ":", "key", "=", "'unamex'", "elif", "eq", "=="...
31.142857
16.285714
def master(cls, cluster_id_label): """ Show the details of the master of the cluster with id/label `cluster_id_label`. """ cluster_status = cls.status(cluster_id_label) if cluster_status.get("state") == 'UP': return list(filter(lambda x: x["role"] == "master", cluster...
[ "def", "master", "(", "cls", ",", "cluster_id_label", ")", ":", "cluster_status", "=", "cls", ".", "status", "(", "cluster_id_label", ")", "if", "cluster_status", ".", "get", "(", "\"state\"", ")", "==", "'UP'", ":", "return", "list", "(", "filter", "(", ...
42.777778
18.111111
def _add_group_columns(data, gdf): """ Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x...
[ "def", "_add_group_columns", "(", "data", ",", "gdf", ")", ":", "n", "=", "len", "(", "data", ")", "if", "isinstance", "(", "gdf", ",", "GroupedDataFrame", ")", ":", "for", "i", ",", "col", "in", "enumerate", "(", "gdf", ".", "plydata_groups", ")", "...
33.410256
14.025641