text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _parse_var(self, element): """ Parse a variable assignment :param element: The XML Element object :type element: etree._Element """ syntax = 'attribute' if element.get('name') else 'element' var_type = attribute(element, 'type', 'user') if syntax == ...
[ "def", "_parse_var", "(", "self", ",", "element", ")", ":", "syntax", "=", "'attribute'", "if", "element", ".", "get", "(", "'name'", ")", "else", "'element'", "var_type", "=", "attribute", "(", "element", ",", "'type'", ",", "'user'", ")", "if", "syntax...
43.55
0.008989
def raw_comment(self): """Returns the raw comment text associated with that Cursor""" r = conf.lib.clang_Cursor_getRawCommentText(self) if not r: return None return str(r)
[ "def", "raw_comment", "(", "self", ")", ":", "r", "=", "conf", ".", "lib", ".", "clang_Cursor_getRawCommentText", "(", "self", ")", "if", "not", "r", ":", "return", "None", "return", "str", "(", "r", ")" ]
35
0.009302
def pathIndex(self, path): '''Return index of item with *path*.''' sourceModel = self.sourceModel() if not sourceModel: return QModelIndex() return self.mapFromSource(sourceModel.pathIndex(path))
[ "def", "pathIndex", "(", "self", ",", "path", ")", ":", "sourceModel", "=", "self", ".", "sourceModel", "(", ")", "if", "not", "sourceModel", ":", "return", "QModelIndex", "(", ")", "return", "self", ".", "mapFromSource", "(", "sourceModel", ".", "pathInde...
33.428571
0.008333
def clear(self): """ Removes all text decoration from the editor. """ self._decorations[:] = [] try: self.editor.setExtraSelections(self._decorations) except RuntimeError: pass
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_decorations", "[", ":", "]", "=", "[", "]", "try", ":", "self", ".", "editor", ".", "setExtraSelections", "(", "self", ".", "_decorations", ")", "except", "RuntimeError", ":", "pass" ]
24
0.008032
def build_concordance(text_str: str) -> List[List[str]]: """ Inherit or mimic the logic of ConcordanceIndex() at: http://www.nltk.org/_modules/nltk/text.html and/or ConcordanceSearchView() & SearchCorpus() at: https://github.com/nltk/nltk/blob/develop/nltk/app/concordance_app.py :param text_st...
[ "def", "build_concordance", "(", "text_str", ":", "str", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "punkt_vars", "=", "PunktLanguageVars", "(", ")", "# type: PunktLanguageVars", "orig_tokens", "=", "punkt_vars", ".", "word_tokenize", "(", "tex...
48.95
0.002004
def Reset(self): ' Reset Axis and set default parameters for H-bridge ' spi.SPI_write_byte(self.CS, 0xC0) # reset # spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup # spi.SPI_write_byte(self.CS, 0xFF) # spi.SPI_write_byte(self.CS, 0x13) # Over Current Tresho...
[ "def", "Reset", "(", "self", ")", ":", "spi", ".", "SPI_write_byte", "(", "self", ".", "CS", ",", "0xC0", ")", "# reset", "# spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup", "# spi.SPI_write_byte(self.CS, 0xFF) ", "# spi.SPI_write_byte(self....
49.407407
0.008088
def get_rendition_key_set(key): """ Retrieve a validated and prepped Rendition Key Set from settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS """ try: rendition_key_set = IMAGE_SETS[key] except KeyError: raise ImproperlyConfigured( "No Rendition Key Set exists at " ...
[ "def", "get_rendition_key_set", "(", "key", ")", ":", "try", ":", "rendition_key_set", "=", "IMAGE_SETS", "[", "key", "]", "except", "KeyError", ":", "raise", "ImproperlyConfigured", "(", "\"No Rendition Key Set exists at \"", "\"settings.VERSATILEIMAGEFIELD_RENDITION_KEY_S...
34.142857
0.002037
def compile(self): """Compile this expression into a query string""" return "{lhs}{sep}{rhs}".format( lhs=self.lhs.compile(), sep=self.sep, rhs=self.rhs.compile(), )
[ "def", "compile", "(", "self", ")", ":", "return", "\"{lhs}{sep}{rhs}\"", ".", "format", "(", "lhs", "=", "self", ".", "lhs", ".", "compile", "(", ")", ",", "sep", "=", "self", ".", "sep", ",", "rhs", "=", "self", ".", "rhs", ".", "compile", "(", ...
31.285714
0.008889
def download(self): """Download the specified file.""" def total_seconds(td): # Keep backward compatibility with Python 2.6 which doesn't have # this method if hasattr(td, 'total_seconds'): return td.total_seconds() else: re...
[ "def", "download", "(", "self", ")", ":", "def", "total_seconds", "(", "td", ")", ":", "# Keep backward compatibility with Python 2.6 which doesn't have", "# this method", "if", "hasattr", "(", "td", ",", "'total_seconds'", ")", ":", "return", "td", ".", "total_seco...
38.776316
0.000662
def _check_action_feasibility(self): """ Check that for every state, reward is finite for some action, and for the case sa_pair is True, that for every state, there is some action available. """ # Check that for every state, reward is finite for some action R_max...
[ "def", "_check_action_feasibility", "(", "self", ")", ":", "# Check that for every state, reward is finite for some action", "R_max", "=", "self", ".", "s_wise_max", "(", "self", ".", "R", ")", "if", "(", "R_max", "==", "-", "np", ".", "inf", ")", ".", "any", ...
41.888889
0.001729
def purged(name, version=None, pkgs=None, normalize=True, ignore_epoch=False, **kwargs): ''' Verify that a package is not installed, calling ``pkg.purge`` if necessary to purge the package. All configuration files are also removed. name The...
[ "def", "purged", "(", "name", ",", "version", "=", "None", ",", "pkgs", "=", "None", ",", "normalize", "=", "True", ",", "ignore_epoch", "=", "False", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'saltenv'", "]", "=", "__env__", "try", ":", "...
39.115385
0.00024
def angvel(target, current, scale): '''Use sigmoid function to choose a delta that will help smoothly steer from current angle to target angle.''' delta = target - current while delta < -180: delta += 360; while delta > 180: delta -= 360; return (old_div(2.0, (1.0 + math.exp(old_div(...
[ "def", "angvel", "(", "target", ",", "current", ",", "scale", ")", ":", "delta", "=", "target", "-", "current", "while", "delta", "<", "-", "180", ":", "delta", "+=", "360", "while", "delta", ">", "180", ":", "delta", "-=", "360", "return", "(", "o...
42
0.014577
def issn(self, mask: str = '####-####') -> str: """Generate a random ISSN. :param mask: Mask of ISSN. :return: ISSN. """ return self.random.custom_code(mask=mask)
[ "def", "issn", "(", "self", ",", "mask", ":", "str", "=", "'####-####'", ")", "->", "str", ":", "return", "self", ".", "random", ".", "custom_code", "(", "mask", "=", "mask", ")" ]
28.142857
0.009852
def safe_print(text, file=sys.stdout, flush=False): """Prints a (unicode) string to the console, encoded depending on the stdout/file encoding (eg. cp437 on Windows). This is to avoid encoding errors in case of funky path names. Works with Python 2 and 3. """ if not isinstance(text, basestring):...
[ "def", "safe_print", "(", "text", ",", "file", "=", "sys", ".", "stdout", ",", "flush", "=", "False", ")", ":", "if", "not", "isinstance", "(", "text", ",", "basestring", ")", ":", "return", "print", "(", "text", ",", "file", "=", "file", ")", "try...
38
0.001427
def _modifies_cart(func): ''' Decorator that makes the wrapped function raise ValidationError if we're doing something that could modify the cart. It also wraps the execution of this function in a database transaction, and marks the boundaries of a cart operations batch. ''' @functools.wraps(f...
[ "def", "_modifies_cart", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "inner", "(", "self", ",", "*", "a", ",", "*", "*", "k", ")", ":", "self", ".", "_fail_if_cart_is_not_active", "(", ")", "with", "transaction", "...
39.611111
0.00137
def Boolean(v): """Convert human-readable boolean values to a bool. Accepted values are 1, true, yes, on, enable, and their negatives. Non-string values are cast to bool. >>> validate = Schema(Boolean()) >>> validate(True) True >>> validate("1") True >>> validate("0") False ...
[ "def", "Boolean", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "basestring", ")", ":", "v", "=", "v", ".", "lower", "(", ")", "if", "v", "in", "(", "'1'", ",", "'true'", ",", "'yes'", ",", "'on'", ",", "'enable'", ")", ":", "return", ...
27.571429
0.001252
def _sanitize_inputs(self): """Sanitizes input fields and returns a map <GlobalStreamId -> Grouping>""" ret = {} if self.inputs is None: return if isinstance(self.inputs, dict): # inputs are dictionary, must be either <HeronComponentSpec -> Grouping> or # <GlobalStreamId -> Grouping> ...
[ "def", "_sanitize_inputs", "(", "self", ")", ":", "ret", "=", "{", "}", "if", "self", ".", "inputs", "is", "None", ":", "return", "if", "isinstance", "(", "self", ".", "inputs", ",", "dict", ")", ":", "# inputs are dictionary, must be either <HeronComponentSpe...
46.837209
0.013132
def parse_args(argv): """ Use Argparse to parse command-line arguments. :param argv: list of arguments to parse (``sys.argv[1:]``) :type argv: ``list`` :return: parsed arguments :rtype: :py:class:`argparse.Namespace` """ p = argparse.ArgumentParser( description='pypi-download-st...
[ "def", "parse_args", "(", "argv", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'pypi-download-stats - Calculate detailed download stats '", "'and generate HTML and badges for PyPI packages - '", "'<%s>'", "%", "PROJECT_URL", ",", "prog", ...
54.490566
0.001701
def __push_frame(self, ancestry_item): """Push a new frame on top of the frame stack.""" frame = self.__frame_factory(ancestry_item) self.__stack.append(frame)
[ "def", "__push_frame", "(", "self", ",", "ancestry_item", ")", ":", "frame", "=", "self", ".", "__frame_factory", "(", "ancestry_item", ")", "self", ".", "__stack", ".", "append", "(", "frame", ")" ]
45
0.010929
def assignPlugin(self): """ Assigns an editor based on the current column for this schema. """ self.uiOperatorDDL.blockSignals(True) self.uiOperatorDDL.clear() plugin = self.currentPlugin() if plugin: flags = 0 if not sel...
[ "def", "assignPlugin", "(", "self", ")", ":", "self", ".", "uiOperatorDDL", ".", "blockSignals", "(", "True", ")", "self", ".", "uiOperatorDDL", ".", "clear", "(", ")", "plugin", "=", "self", ".", "currentPlugin", "(", ")", "if", "plugin", ":", "flags", ...
33.764706
0.008475
def get_XIJ(nat, i_now, dr_now, dr_old): """ Calculates the X_{ij} matrix """ # Do an element-wise outer product dr_dr = dr_now.reshape(-1,3,1)*dr_old.reshape(-1,1,3) xij = np.zeros([nat,3,3]) for i in range(3): for j in range(3): # For each atom, sum over all neighbors ...
[ "def", "get_XIJ", "(", "nat", ",", "i_now", ",", "dr_now", ",", "dr_old", ")", ":", "# Do an element-wise outer product", "dr_dr", "=", "dr_now", ".", "reshape", "(", "-", "1", ",", "3", ",", "1", ")", "*", "dr_old", ".", "reshape", "(", "-", "1", ",...
27.714286
0.027431
def getXML(self): """ Return a XML representation of the current element. This function can be used for debugging purposes. It is also used by getXML in SVG @return: the representation of the current element as an xml string """ xml='<'+self._elementName+' ' ...
[ "def", "getXML", "(", "self", ")", ":", "xml", "=", "'<'", "+", "self", ".", "_elementName", "+", "' '", "for", "key", ",", "value", "in", "list", "(", "self", ".", "_attributes", ".", "items", "(", ")", ")", ":", "if", "value", "!=", "None", ":"...
36.357143
0.020096
def boo(rest): "Boo someone" slapee = rest karma.Karma.store.change(slapee, -1) return "/me BOOO %s!!! BOOO!!!" % slapee
[ "def", "boo", "(", "rest", ")", ":", "slapee", "=", "rest", "karma", ".", "Karma", ".", "store", ".", "change", "(", "slapee", ",", "-", "1", ")", "return", "\"/me BOOO %s!!! BOOO!!!\"", "%", "slapee" ]
24
0.040323
def get_recurring_bill_by_subscription(self, subscription_id): """ Consulta de las facturas que están pagadas o pendientes por pagar. Se puede consultar por cliente, por suscripción o por rango de fechas. Args: subscription_id: Returns: """ params =...
[ "def", "get_recurring_bill_by_subscription", "(", "self", ",", "subscription_id", ")", ":", "params", "=", "{", "\"subscriptionId\"", ":", "subscription_id", ",", "}", "return", "self", ".", "client", ".", "_get", "(", "self", ".", "url", "+", "'recurringBill'",...
31.2
0.008299
def format_timedelta(t, timedelta_format=None): """Cast given object to a Timestamp and return a nicely formatted string""" timedelta_str = str(pd.Timedelta(t)) try: days_str, time_str = timedelta_str.split(' days ') except ValueError: # catch NaT and others that don't split nicely ...
[ "def", "format_timedelta", "(", "t", ",", "timedelta_format", "=", "None", ")", ":", "timedelta_str", "=", "str", "(", "pd", ".", "Timedelta", "(", "t", ")", ")", "try", ":", "days_str", ",", "time_str", "=", "timedelta_str", ".", "split", "(", "' days '...
35.466667
0.001832
def tags(self, value): """The tags property. Args: value (hash). the property value. """ if value == self._defaults['tags'] and 'tags' in self._values: del self._values['tags'] else: self._values['tags'] = value
[ "def", "tags", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'tags'", "]", "and", "'tags'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'tags'", "]", "else", ":", "self", ".", ...
28.7
0.010135
def process_text(self, kind, context): """Combine multiple lines of bare text and emit as a Python string literal.""" result = None while True: chunk = yield None if chunk is None: if result: yield result.clone(line=repr(result.line)) return if not result: result = chu...
[ "def", "process_text", "(", "self", ",", "kind", ",", "context", ")", ":", "result", "=", "None", "while", "True", ":", "chunk", "=", "yield", "None", "if", "chunk", "is", "None", ":", "if", "result", ":", "yield", "result", ".", "clone", "(", "line"...
18.421053
0.07337
def MDL(N, rho, k): r"""Minimum Description Length .. math:: MDL(k) = N log \rho_k + p \log N :validation: results """ from numpy import log #p = arange(1, len(rho)+1) mdl = N* log(rho) + k * log(N) return mdl
[ "def", "MDL", "(", "N", ",", "rho", ",", "k", ")", ":", "from", "numpy", "import", "log", "#p = arange(1, len(rho)+1)", "mdl", "=", "N", "*", "log", "(", "rho", ")", "+", "k", "*", "log", "(", "N", ")", "return", "mdl" ]
21.181818
0.012346
def clean_session_table(): """Automatically clean session table. To enable a periodically clean of the session table, you should configure the task as a celery periodic task. .. code-block:: python from datetime import timedelta CELERYBEAT_SCHEDULE = { 'session_cleaner': {...
[ "def", "clean_session_table", "(", ")", ":", "sessions", "=", "SessionActivity", ".", "query_by_expired", "(", ")", ".", "all", "(", ")", "for", "session", "in", "sessions", ":", "delete_session", "(", "sid_s", "=", "session", ".", "sid_s", ")", "db", ".",...
30.782609
0.00137
def fetch_json_by_href(href, params=None): """ Fetch json for element by using href. Params should be key/value pairs. For example {'filter': 'myfilter'} :method: GET :param str href: href of the element :params dict params: optional search query parameters :return: :py:class:`smc.api.web.S...
[ "def", "fetch_json_by_href", "(", "href", ",", "params", "=", "None", ")", ":", "result", "=", "SMCRequest", "(", "href", "=", "href", ",", "params", "=", "params", ")", ".", "read", "(", ")", "if", "result", ":", "result", ".", "href", "=", "href", ...
31.5
0.002203
def resource_definition(resource): """ Generate a `Swagger Definitions Object <http://swagger.io/specification/#definitionsObject>`_ from a resource. """ meta = getmeta(resource) definition = { 'type': "object", 'properties': {} } for field in meta.all_fields: ...
[ "def", "resource_definition", "(", "resource", ")", ":", "meta", "=", "getmeta", "(", "resource", ")", "definition", "=", "{", "'type'", ":", "\"object\"", ",", "'properties'", ":", "{", "}", "}", "for", "field", "in", "meta", ".", "all_fields", ":", "fi...
28.2
0.001959
def topdown(cls): """Get all topdown `Relationship` instances. Returns: :obj:`generator` Example: >>> from pronto import Relationship >>> for r in Relationship.topdown(): ... print(r) Relationship('can_be') Relationshi...
[ "def", "topdown", "(", "cls", ")", ":", "return", "tuple", "(", "unique_everseen", "(", "r", "for", "r", "in", "cls", ".", "_instances", ".", "values", "(", ")", "if", "r", ".", "direction", "==", "'topdown'", ")", ")" ]
26.9375
0.008969
def setShowRichText( self, state ): """ Sets whether or not the delegate should render rich text information \ as HTML when drawing the contents of the item. :param state | <bool> """ delegate = self.itemDelegate() if isinstance(delegate, XTr...
[ "def", "setShowRichText", "(", "self", ",", "state", ")", ":", "delegate", "=", "self", ".", "itemDelegate", "(", ")", "if", "isinstance", "(", "delegate", ",", "XTreeWidgetDelegate", ")", ":", "delegate", ".", "setShowRichText", "(", "state", ")" ]
37.4
0.015666
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist, not empty (issue #871) and plugin not disabled if not self.stats or (self.stats == {}) or self.is_disable():...
[ "def", "msg_curse", "(", "self", ",", "args", "=", "None", ",", "max_width", "=", "None", ")", ":", "# Init the return message", "ret", "=", "[", "]", "# Only process if stats exist, not empty (issue #871) and plugin not disabled", "if", "not", "self", ".", "stats", ...
37.52381
0.001855
def char_groups(self, t, i): """Handle character groups.""" current = [] pos = i.index - 1 found = 0 sub_first = None escaped = False first = None try: while True: if not escaped and t == "\\": escaped = Tr...
[ "def", "char_groups", "(", "self", ",", "t", ",", "i", ")", ":", "current", "=", "[", "]", "pos", "=", "i", ".", "index", "-", "1", "found", "=", "0", "sub_first", "=", "None", "escaped", "=", "False", "first", "=", "None", "try", ":", "while", ...
37.707692
0.002386
def GetMessageStrings(cls, formatter_mediator, event): """Retrieves the formatted message strings for a specific event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resource...
[ "def", "GetMessageStrings", "(", "cls", ",", "formatter_mediator", ",", "event", ")", ":", "formatter_object", "=", "cls", ".", "GetFormatterObject", "(", "event", ".", "data_type", ")", "return", "formatter_object", ".", "GetMessages", "(", "formatter_mediator", ...
40.214286
0.001736
def _variants(self, case_id, gemini_query): """Return variants found in the gemini database Args: case_id (str): The case for which we want to see information gemini_query (str): What variants should be chosen filters (dict): A dictionary with filters...
[ "def", "_variants", "(", "self", ",", "case_id", ",", "gemini_query", ")", ":", "individuals", "=", "[", "]", "# Get the individuals for the case", "case_obj", "=", "self", ".", "case", "(", "case_id", ")", "for", "individual", "in", "case_obj", ".", "individu...
31.191489
0.001323
def _check_data(self, X): ''' Checks that unique identifiers vaf_types are consistent between time series. Parameters ---------- X : array-like, shape [n_series, ...] Time series data and (optionally) contextual data ''' if len(X) > 1: sv...
[ "def", "_check_data", "(", "self", ",", "X", ")", ":", "if", "len", "(", "X", ")", ">", "1", ":", "sval", "=", "np", ".", "unique", "(", "X", "[", "0", "]", "[", ":", ",", "1", "]", ")", "if", "np", ".", "all", "(", "[", "np", ".", "all...
34.9375
0.008711
def seekable(fileobj): """Backwards compat function to determine if a fileobj is seekable :param fileobj: The file-like object to determine if seekable :returns: True, if seekable. False, otherwise. """ # If the fileobj has a seekable attr, try calling the seekable() # method on it. if has...
[ "def", "seekable", "(", "fileobj", ")", ":", "# If the fileobj has a seekable attr, try calling the seekable()", "# method on it.", "if", "hasattr", "(", "fileobj", ",", "'seekable'", ")", ":", "return", "fileobj", ".", "seekable", "(", ")", "# If there is no seekable att...
37.090909
0.001195
def store( self, collection, **kwargs ): ''' validate the passed values in kwargs based on the collection, store them in the mongodb collection ''' key = validate( collection, **kwargs ) if self.fetch( collection, **{ key : kwargs[key] } ): raise Proauth2Error...
[ "def", "store", "(", "self", ",", "collection", ",", "*", "*", "kwargs", ")", ":", "key", "=", "validate", "(", "collection", ",", "*", "*", "kwargs", ")", "if", "self", ".", "fetch", "(", "collection", ",", "*", "*", "{", "key", ":", "kwargs", "...
41.777778
0.039063
def _sigmaclip_withaxis(self, data, axis=None, masked=True, return_bounds=False, copy=True): """ Sigma clip the data when ``axis`` is specified. In this case, we replace clipped values with NaNs as placeholder values. """ # float array type i...
[ "def", "_sigmaclip_withaxis", "(", "self", ",", "data", ",", "axis", "=", "None", ",", "masked", "=", "True", ",", "return_bounds", "=", "False", ",", "copy", "=", "True", ")", ":", "# float array type is needed to insert nans into the array", "filtered_data", "="...
39.042254
0.001056
def ensure_columns_are_in_dataframe(columns, dataframe, col_title='', data_title='data'): """ Checks whether each column in `columns` is in `dataframe`. Raises ValueError if any of the columns are not...
[ "def", "ensure_columns_are_in_dataframe", "(", "columns", ",", "dataframe", ",", "col_title", "=", "''", ",", "data_title", "=", "'data'", ")", ":", "# Make sure columns is an iterable", "assert", "isinstance", "(", "columns", ",", "Iterable", ")", "# Make sure datafr...
36.090909
0.000613
def _do_identity_role_list(args): """Lists the current on-chain configuration values. """ rest_client = RestClient(args.url) state = rest_client.list_state(subtree=IDENTITY_NAMESPACE + _ROLE_PREFIX) head = state['head'] state_values = state['data'] printable_roles = [] for state_value i...
[ "def", "_do_identity_role_list", "(", "args", ")", ":", "rest_client", "=", "RestClient", "(", "args", ".", "url", ")", "state", "=", "rest_client", ".", "list_state", "(", "subtree", "=", "IDENTITY_NAMESPACE", "+", "_ROLE_PREFIX", ")", "head", "=", "state", ...
38.55102
0.000516
def apply_plan(text, plan): """ Apply a plan for fixing the encoding of text. The plan is a list of tuples of the form (operation, encoding, cost): - `operation` is 'encode' if it turns a string into bytes, 'decode' if it turns bytes into a string, and 'transcode' if it keeps the type the same. ...
[ "def", "apply_plan", "(", "text", ",", "plan", ")", ":", "obj", "=", "text", "for", "operation", ",", "encoding", ",", "_", "in", "plan", ":", "if", "operation", "==", "'encode'", ":", "obj", "=", "obj", ".", "encode", "(", "encoding", ")", "elif", ...
39.448276
0.000853
def add_linked_dataset(self, project_key, dataset_key): """Link project to an existing dataset This method links a dataset to project :param project_key: Project identifier, in the form of owner/id :type project_key: str :param dataset_key: Dataset identifier, in the form of ow...
[ "def", "add_linked_dataset", "(", "self", ",", "project_key", ",", "dataset_key", ")", ":", "try", ":", "project_owner_id", ",", "project_id", "=", "parse_dataset_key", "(", "project_key", ")", "dataset_owner_id", ",", "dataset_id", "=", "parse_dataset_key", "(", ...
42.285714
0.001652
def has_changes(self): """ Returns true if at least one tracker detects a change. """ lm = self.last_manifest for tracker in self.get_trackers(): last_thumbprint = lm['_tracker_%s' % tracker.get_natural_key_hash()] if tracker.is_changed(last_thumbprint): ...
[ "def", "has_changes", "(", "self", ")", ":", "lm", "=", "self", ".", "last_manifest", "for", "tracker", "in", "self", ".", "get_trackers", "(", ")", ":", "last_thumbprint", "=", "lm", "[", "'_tracker_%s'", "%", "tracker", ".", "get_natural_key_hash", "(", ...
35.8
0.008174
def setup_icons(self, ): """Setup the icons of the ui :returns: None :rtype: None :raises: None """ iconbtns = [("menu_border_24x24.png", self.menu_tb), ("duplicate_border_24x24.png", self.duplicate_tb), ("delete_border_24x24.png",...
[ "def", "setup_icons", "(", "self", ",", ")", ":", "iconbtns", "=", "[", "(", "\"menu_border_24x24.png\"", ",", "self", ".", "menu_tb", ")", ",", "(", "\"duplicate_border_24x24.png\"", ",", "self", ".", "duplicate_tb", ")", ",", "(", "\"delete_border_24x24.png\""...
44.571429
0.002092
def _values_tuple(self, i, valuemap_list, values_list, cimtype): """ Return a tuple for the value range or unclaimed marker at position i, with these items: * lo - low value of the range * hi - high value of the range (can be equal to lo) * values - value of `Values` qua...
[ "def", "_values_tuple", "(", "self", ",", "i", ",", "valuemap_list", ",", "values_list", ",", "cimtype", ")", ":", "values_str", "=", "values_list", "[", "i", "]", "valuemap_str", "=", "valuemap_list", "[", "i", "]", "m", "=", "re", ".", "match", "(", ...
31.87037
0.001127
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: IpAccessControlListContext for this IpAccessControlListInstance :rtype: twilio.rest.trunking.v1.t...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "IpAccessControlListContext", "(", "self", ".", "_version", ",", "trunk_sid", "=", "self", ".", "_solution", "[", "'trunk_sid'", "]", ...
42.266667
0.009259
def construct_kde(samples_array, use_kombine=False): """Constructs a KDE from the given samples. """ if use_kombine: try: import kombine except ImportError: raise ImportError("kombine is not installed.") # construct the kde if use_kombine: kde = kombin...
[ "def", "construct_kde", "(", "samples_array", ",", "use_kombine", "=", "False", ")", ":", "if", "use_kombine", ":", "try", ":", "import", "kombine", "except", "ImportError", ":", "raise", "ImportError", "(", "\"kombine is not installed.\"", ")", "# construct the kde...
30.142857
0.002299
def root(self): '''The root node of the tree this node is in.''' with self._mutex: if self._parent: return self._parent.root else: return self
[ "def", "root", "(", "self", ")", ":", "with", "self", ".", "_mutex", ":", "if", "self", ".", "_parent", ":", "return", "self", ".", "_parent", ".", "root", "else", ":", "return", "self" ]
29.714286
0.009346
def calc_nbes_inzp_v1(self): """Calculate stand precipitation and update the interception storage accordingly. Required control parameters: |NHRU| |Lnk| Required derived parameter: |KInz| Required flux sequence: |NKor| Calculated flux sequence: |NBes| Updat...
[ "def", "calc_nbes_inzp_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", "....
32.181034
0.00026
def t_intnumber(self, t): r'-?\d+' t.value = int(t.value) t.type = 'NUMBER' return t
[ "def", "t_intnumber", "(", "self", ",", "t", ")", ":", "t", ".", "value", "=", "int", "(", "t", ".", "value", ")", "t", ".", "type", "=", "'NUMBER'", "return", "t" ]
22.4
0.017241
def critical(self, msg): """ Log Critical Messages """ self._execActions('critical', msg) msg = self._execFilters('critical', msg) self._processMsg('critical', msg) self._sendMsg('critical', msg)
[ "def", "critical", "(", "self", ",", "msg", ")", ":", "self", ".", "_execActions", "(", "'critical'", ",", "msg", ")", "msg", "=", "self", ".", "_execFilters", "(", "'critical'", ",", "msg", ")", "self", ".", "_processMsg", "(", "'critical'", ",", "msg...
38.333333
0.008511
def assemble_hex(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str | iterator[Instruction] :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) ...
[ "def", "assemble_hex", "(", "asmcode", ",", "pc", "=", "0", ",", "fork", "=", "DEFAULT_FORK", ")", ":", "if", "isinstance", "(", "asmcode", ",", "list", ")", ":", "return", "'0x'", "+", "hexlify", "(", "b''", ".", "join", "(", "[", "x", ".", "bytes...
37.423077
0.002004
def make_request(self, method, *args, **kwargs): """Creates a request from a method function call.""" if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()} if use_signature: ...
[ "def", "make_request", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "not", "use_signature", ":", "raise", "NotImplementedError", "(", "\"Only keyword arguments allowed in Python2\"", ")", "new_kwargs", "="...
36.675676
0.000718
def obj_from_file(filename='annotation.yaml', filetype='auto'): ''' Read object from file ''' if filetype == 'auto': _, ext = os.path.splitext(filename) filetype = ext[1:] if filetype in ('yaml', 'yml'): from ruamel.yaml import YAML yaml = YAML(typ="unsafe") with op...
[ "def", "obj_from_file", "(", "filename", "=", "'annotation.yaml'", ",", "filetype", "=", "'auto'", ")", ":", "if", "filetype", "==", "'auto'", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "filetype", "=", "ext", ...
32.424242
0.000907
def validate_mixture(supports_mixture: SupportsMixture): """Validates that the mixture's tuple are valid probabilities.""" mixture_tuple = mixture(supports_mixture, None) if mixture_tuple is None: raise TypeError('{}_mixture did not have a _mixture_ method'.format( supports_mixture)) ...
[ "def", "validate_mixture", "(", "supports_mixture", ":", "SupportsMixture", ")", ":", "mixture_tuple", "=", "mixture", "(", "supports_mixture", ",", "None", ")", "if", "mixture_tuple", "is", "None", ":", "raise", "TypeError", "(", "'{}_mixture did not have a _mixture_...
40
0.001285
def width_tuple(value): """ test if value is a valid width indicator (for a sub-widget in a column). This can either be ('fit', min, max): use the length actually needed for the content, padded to use at least width min, and cut of at width max. Here, min an...
[ "def", "width_tuple", "(", "value", ")", ":", "if", "value", "is", "None", ":", "res", "=", "'fit'", ",", "0", ",", "0", "elif", "not", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "VdtTypeError", "(", "value"...
39.269231
0.000956
def get_by_symbol(self, symbol: str) -> Commodity: """ Loads currency by symbol """ assert isinstance(symbol, str) query = ( self.currencies_query .filter(Commodity.mnemonic == symbol) ) return query.one()
[ "def", "get_by_symbol", "(", "self", ",", "symbol", ":", "str", ")", "->", "Commodity", ":", "assert", "isinstance", "(", "symbol", ",", "str", ")", "query", "=", "(", "self", ".", "currencies_query", ".", "filter", "(", "Commodity", ".", "mnemonic", "==...
29.555556
0.010949
def gid_to_group(gid): ''' Convert the group id to the group name on this system Under Windows, because groups are just another ACL entity, this function behaves the same as uid_to_user. For maintaining Windows systems, this function is superfluous and only exists for API compatibility with Un...
[ "def", "gid_to_group", "(", "gid", ")", ":", "func_name", "=", "'{0}.gid_to_group'", ".", "format", "(", "__virtualname__", ")", "if", "__opts__", ".", "get", "(", "'fun'", ",", "''", ")", "==", "func_name", ":", "log", ".", "info", "(", "'The function %s ...
30.666667
0.001054
def command_stop(self): ''' Stop a server:: ./manage.py flup:stop ''' if self.pidfile: if not os.path.exists(self.pidfile): sys.exit("Pidfile {!r} doesn't exist".format(self.pidfile)) with open(self.pidfile) as pidfile: ...
[ "def", "command_stop", "(", "self", ")", ":", "if", "self", ".", "pidfile", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "pidfile", ")", ":", "sys", ".", "exit", "(", "\"Pidfile {!r} doesn't exist\"", ".", "format", "(", "self"...
38.75
0.002099
def set_tile(self, row, col, value): """ Set the tile at position row, col to have the given value. """ #print('set_tile: y=', row, 'x=', col) if col < 0: print("ERROR - x less than zero", col) col = 0 #return if col > s...
[ "def", "set_tile", "(", "self", ",", "row", ",", "col", ",", "value", ")", ":", "#print('set_tile: y=', row, 'x=', col)", "if", "col", "<", "0", ":", "print", "(", "\"ERROR - x less than zero\"", ",", "col", ")", "col", "=", "0", "#return", "if", "col", ">...
29.28
0.01455
def positionToIntensityUncertaintyForPxGroup(image, std, y0, y1, x0, x1): ''' like positionToIntensityUncertainty but calculated average uncertainty for an area [y0:y1,x0:x1] ''' fy, fx = y1 - y0, x1 - x0 if fy != fx: raise Exception('averaged area need to be square ATM') ima...
[ "def", "positionToIntensityUncertaintyForPxGroup", "(", "image", ",", "std", ",", "y0", ",", "y1", ",", "x0", ",", "x1", ")", ":", "fy", ",", "fx", "=", "y1", "-", "y0", ",", "x1", "-", "x0", "if", "fy", "!=", "fx", ":", "raise", "Exception", "(", ...
37.4
0.001739
def get_request_data(self, var_name, full_data=False): """ :param var_name: :param full_data: If you want `.to_array()` with this data, ready to be sent. :return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`). Files can be None, if...
[ "def", "get_request_data", "(", "self", ",", "var_name", ",", "full_data", "=", "False", ")", ":", "if", "full_data", ":", "data", "=", "self", ".", "to_array", "(", ")", "data", "[", "'media'", "]", ",", "file", "=", "self", ".", "get_inputfile_data", ...
55.4
0.009467
def load_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000): ''' Prepare the IPython notebook for displaying Bokeh plots. Args: resources (Resource, optional) : how and where to load BokehJS from (default: CDN) verbose (bool, optional) : wheth...
[ "def", "load_notebook", "(", "resources", "=", "None", ",", "verbose", "=", "False", ",", "hide_banner", "=", "False", ",", "load_timeout", "=", "5000", ")", ":", "global", "_NOTEBOOK_LOADED", "from", ".", ".", "import", "__version__", "from", ".", ".", "c...
30.986842
0.011111
def unmask(self, arr): """Use self.mask to reshape arr and self.img to get an affine and header to create a new self.img using the data in arr. If self.has_mask() is False, will return the same arr. """ self._check_for_mask() if 1 > arr.ndim > 2: raise ValueE...
[ "def", "unmask", "(", "self", ",", "arr", ")", ":", "self", ".", "_check_for_mask", "(", ")", "if", "1", ">", "arr", ".", "ndim", ">", "2", ":", "raise", "ValueError", "(", "'The given array has {} dimensions while my mask has {}. '", "'Masked data must be 1D or 2...
45.875
0.008011
def tasks(self, from_date=DEFAULT_DATETIME): """Retrieve tasks. :param from_date: retrieve tasks that where updated from that date; dates are converted epoch time. """ # Convert 'from_date' to epoch timestamp. # Zero value (1970-01-01 00:00:00) is not allowed for ...
[ "def", "tasks", "(", "self", ",", "from_date", "=", "DEFAULT_DATETIME", ")", ":", "# Convert 'from_date' to epoch timestamp.", "# Zero value (1970-01-01 00:00:00) is not allowed for", "# 'modifiedStart' so it will be set to 1, by default.", "ts", "=", "int", "(", "datetime_to_utc",...
29.242424
0.002006
def sendrequest(self, request): ''' Recieves a request xml as a string and posts it to the health service url specified in the settings.py ''' url = urlparse.urlparse(self.connection.healthserviceurl) conn = None if url.scheme == 'https': ...
[ "def", "sendrequest", "(", "self", ",", "request", ")", ":", "url", "=", "urlparse", ".", "urlparse", "(", "self", ".", "connection", ".", "healthserviceurl", ")", "conn", "=", "None", "if", "url", ".", "scheme", "==", "'https'", ":", "conn", "=", "htt...
35.458333
0.002288
def gen_retries(start, end, intervals, time=time): """Helper for retrying something, sleeping between attempts. Yields ``(elapsed, remaining, wait)`` tuples, giving times in seconds. The last item, `wait`, is the suggested amount of time to sleep before trying again. This function works in concert...
[ "def", "gen_retries", "(", "start", ",", "end", ",", "intervals", ",", "time", "=", "time", ")", ":", "for", "interval", "in", "intervals", ":", "now", "=", "time", "(", ")", "if", "now", "<", "end", ":", "wait", "=", "min", "(", "interval", ",", ...
43.571429
0.000802
async def create( cls, fabric: Union[Fabric, int], vid: int, *, name: str = None, description: str = None, mtu: int = None, relay_vlan: Union[Vlan, int] = None, dhcp_on: bool = False, primary_rack: Union[RackController, str] = None, secondary_rack: Union[RackC...
[ "async", "def", "create", "(", "cls", ",", "fabric", ":", "Union", "[", "Fabric", ",", "int", "]", ",", "vid", ":", "int", ",", "*", ",", "name", ":", "str", "=", "None", ",", "description", ":", "str", "=", "None", ",", "mtu", ":", "int", "=",...
43.125
0.000515
def format_fit(text, width=None, align='<', suffix="..."): """ Fits a piece of text to ``width`` characters by truncating too long text and padding too short text with spaces. Defaults to terminal width. Truncation is indicated by a customizable suffix. ``align`` specifies the alignment of the conte...
[ "def", "format_fit", "(", "text", ",", "width", "=", "None", ",", "align", "=", "'<'", ",", "suffix", "=", "\"...\"", ")", ":", "if", "width", "==", "None", ":", "width", "=", "get_terminal_size", "(", ")", ".", "columns", "if", "len", "(", "text", ...
33.363636
0.009272
def tsp(V,c): """tsp -- model for solving the traveling salesman problem with callbacks - start with assignment model - add cuts until there are no sub-cycles Parameters: - V: set/list of nodes in the graph - c[i,j]: cost for traversing edge (i,j) Returns the optimum objective ...
[ "def", "tsp", "(", "V", ",", "c", ")", ":", "model", "=", "Model", "(", "\"TSP_lazy\"", ")", "conshdlr", "=", "TSPconshdlr", "(", ")", "x", "=", "{", "}", "for", "i", "in", "V", ":", "for", "j", "in", "V", ":", "if", "j", ">", "i", ":", "x"...
32.615385
0.0126
def run_one(self, name, migrator, fake=True, downgrade=False, force=False): """Run/emulate a migration with given name.""" try: migrate, rollback = self.read(name) if fake: with mock.patch('peewee.Model.select'): with mock.patch('peewee.Query._...
[ "def", "run_one", "(", "self", ",", "name", ",", "migrator", ",", "fake", "=", "True", ",", "downgrade", "=", "False", ",", "force", "=", "False", ")", ":", "try", ":", "migrate", ",", "rollback", "=", "self", ".", "read", "(", "name", ")", "if", ...
39.514286
0.002117
def _connect(self): """ Connect to the influxdb server """ try: # Open Connection self.influx = InfluxDBClient(self.hostname, self.port, self.username, self.password, self.database,...
[ "def", "_connect", "(", "self", ")", ":", "try", ":", "# Open Connection", "self", ".", "influx", "=", "InfluxDBClient", "(", "self", ".", "hostname", ",", "self", ".", "port", ",", "self", ".", "username", ",", "self", ".", "password", ",", "self", "....
38.045455
0.002331
def end_protocol(self): """End protocol definition.""" protocol = self._get_message_template() self._protocols[protocol.name] = protocol self._protocol_in_progress = False
[ "def", "end_protocol", "(", "self", ")", ":", "protocol", "=", "self", ".", "_get_message_template", "(", ")", "self", ".", "_protocols", "[", "protocol", ".", "name", "]", "=", "protocol", "self", ".", "_protocol_in_progress", "=", "False" ]
39.8
0.009852
def cli(env, sortby, cpu, columns, datacenter, name, memory, disk, tag): """List dedicated host.""" mgr = SoftLayer.DedicatedHostManager(env.client) hosts = mgr.list_instances(cpus=cpu, datacenter=datacenter, hostname=name, ...
[ "def", "cli", "(", "env", ",", "sortby", ",", "cpu", ",", "columns", ",", "datacenter", ",", "name", ",", "memory", ",", "disk", ",", "tag", ")", ":", "mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "hosts", "=",...
36.052632
0.001422
def register_actions(self, shortcut_manager): """Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions. """ super(DescriptionEditorController...
[ "def", "register_actions", "(", "self", ",", "shortcut_manager", ")", ":", "super", "(", "DescriptionEditorController", ",", "self", ")", ".", "register_actions", "(", "shortcut_manager", ")", "shortcut_manager", ".", "add_callback_for_action", "(", "\"abort\"", ",", ...
53.25
0.009238
def rpush(self, key, *values): """ Insert all the specified values at the tail of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the tail of the list. :re...
[ "def", "rpush", "(", "self", ",", "key", ",", "*", "values", ")", ":", "return", "self", ".", "_execute", "(", "[", "b'RPUSH'", ",", "key", "]", "+", "list", "(", "values", ")", ")" ]
40.866667
0.001594
def has_ssd(self): """Return true if any of the drive is ssd""" for member in self._drives_list(): if member.media_type == constants.MEDIA_TYPE_SSD: return True return False
[ "def", "has_ssd", "(", "self", ")", ":", "for", "member", "in", "self", ".", "_drives_list", "(", ")", ":", "if", "member", ".", "media_type", "==", "constants", ".", "MEDIA_TYPE_SSD", ":", "return", "True", "return", "False" ]
36.666667
0.008889
def getdarkimg(self,chip): """ Return an array representing the dark image for the detector. Returns ------- dark: array Dark image array in the same shape as the input image with **units of cps** """ sci_chip = self._image[self.scienceExt,chip] ...
[ "def", "getdarkimg", "(", "self", ",", "chip", ")", ":", "sci_chip", "=", "self", ".", "_image", "[", "self", ".", "scienceExt", ",", "chip", "]", "# First attempt to get the dark image specified by the \"DARKFILE\"", "# keyword in the primary keyword of the science data.",...
39.464286
0.008834
async def field(self, elem=None, elem_type=None, params=None): """ Archive field :param elem: :param elem_type: :param params: :return: """ elem_type = elem_type if elem_type else elem.__class__ fvalue = None etype = self._get_type(elem_ty...
[ "async", "def", "field", "(", "self", ",", "elem", "=", "None", ",", "elem_type", "=", "None", ",", "params", "=", "None", ")", ":", "elem_type", "=", "elem_type", "if", "elem_type", "else", "elem", ".", "__class__", "fvalue", "=", "None", "etype", "="...
33.442308
0.001676
def read_key_value_lines(path, separator=' ', default_value=''): """ Reads lines of a text file with two columns as key/value dictionary. Parameters: path (str): Path to the file. separator (str): Separator that is used to split key and value. default_value (str): If no value is giv...
[ "def", "read_key_value_lines", "(", "path", ",", "separator", "=", "' '", ",", "default_value", "=", "''", ")", ":", "gen", "=", "read_separated_lines_generator", "(", "path", ",", "separator", ",", "2", ")", "dic", "=", "{", "}", "for", "record", "in", ...
29.130435
0.001445
def decimate_circmean(self, a, maxpoints, **kwargs): """Return data *a* circmean-decimated on *maxpoints*. Histograms each column into *maxpoints* bins and calculates the weighted circular mean in each bin as the decimated data, using :func:`numkit.timeseries.circmean_histogramm...
[ "def", "decimate_circmean", "(", "self", ",", "a", ",", "maxpoints", ",", "*", "*", "kwargs", ")", ":", "a_rad", "=", "numpy", ".", "vstack", "(", "(", "a", "[", "0", "]", ",", "numpy", ".", "deg2rad", "(", "a", "[", "1", ":", "]", ")", ")", ...
41.219512
0.002312
def write(self, features=None, outfile=None, format=0, is_leaf_fn=None, format_root_node=False, dist_formatter=None, support_formatter=None, name_formatter=None): """ Returns the newick representation of current node. Several ...
[ "def", "write", "(", "self", ",", "features", "=", "None", ",", "outfile", "=", "None", ",", "format", "=", "0", ",", "is_leaf_fn", "=", "None", ",", "format_root_node", "=", "False", ",", "dist_formatter", "=", "None", ",", "support_formatter", "=", "No...
33.173077
0.013514
def timeout(duration): """ A decorator to force a time limit on the execution of an external function. :param int duration: the timeout duration :raises: TypeError, if duration is anything other than integer :raises: ValueError, if duration is a negative integer :raises TimeoutError, if the ...
[ "def", "timeout", "(", "duration", ")", ":", "if", "not", "isinstance", "(", "duration", ",", "int", ")", ":", "raise", "TypeError", "(", "\"timeout duration should be a positive integer\"", ")", "if", "duration", "<=", "0", ":", "raise", "ValueError", "(", "\...
32.741935
0.001914
def register_gwf_api(library): """Register a full set of GWF I/O methods for the given library The given frame library must define the following methods - `read` : which receives one of more frame files which can be assumed to be contiguous, and should return a `TimeSeriesDict` - `write...
[ "def", "register_gwf_api", "(", "library", ")", ":", "# import library to get details (don't require library to importable)", "try", ":", "lib", "=", "import_gwf_library", "(", "library", ")", "except", "ImportError", ":", "pass", "# means any reads will fail at run-time", "e...
38.354067
0.000122
def add_user(self, attrs): """add a user""" ldap_client = self._bind() # encoding crap attrs_srt = self.attrs_pretreatment(attrs) attrs_srt[self._byte_p2('objectClass')] = self.objectclasses # construct is DN dn = \ self._byte_p2(self.dn_user_attr) + ...
[ "def", "add_user", "(", "self", ",", "attrs", ")", ":", "ldap_client", "=", "self", ".", "_bind", "(", ")", "# encoding crap", "attrs_srt", "=", "self", ".", "attrs_pretreatment", "(", "attrs", ")", "attrs_srt", "[", "self", ".", "_byte_p2", "(", "'objectC...
35.074074
0.002055
def browse_history(self, backward): """Browse history""" if self.is_cursor_before('eol') and self.hist_wholeline: self.hist_wholeline = False tocursor = self.get_current_line_to_cursor() text, self.histidx = self.find_in_history(tocursor, self.histidx, ...
[ "def", "browse_history", "(", "self", ",", "backward", ")", ":", "if", "self", ".", "is_cursor_before", "(", "'eol'", ")", "and", "self", ".", "hist_wholeline", ":", "self", ".", "hist_wholeline", "=", "False", "tocursor", "=", "self", ".", "get_current_line...
46.055556
0.002364
def panel_index(time, panels, names=None): """ Returns a multi-index suitable for a panel-like DataFrame. Parameters ---------- time : array-like Time index, does not have to repeat panels : array-like Panel index, does not have to repeat names : list, optional List ...
[ "def", "panel_index", "(", "time", ",", "panels", ",", "names", "=", "None", ")", ":", "if", "names", "is", "None", ":", "names", "=", "[", "'time'", ",", "'panel'", "]", "time", ",", "panels", "=", "_ensure_like_indices", "(", "time", ",", "panels", ...
31.452381
0.000734
def create_pool(self, name, method='ROUND_ROBIN'): ''' Create a pool on the F5 load balancer ''' lbmethods = self.bigIP.LocalLB.Pool.typefactory.create( 'LocalLB.LBMethod' ) supported_method = [i[0] for i in lbmethods if ( i[0].split('_', 2)[-1] =...
[ "def", "create_pool", "(", "self", ",", "name", ",", "method", "=", "'ROUND_ROBIN'", ")", ":", "lbmethods", "=", "self", ".", "bigIP", ".", "LocalLB", ".", "Pool", ".", "typefactory", ".", "create", "(", "'LocalLB.LBMethod'", ")", "supported_method", "=", ...
35.375
0.002294
def fetch_last_receipt_number(self, point_of_sales, receipt_type): """Returns the number for the last validated receipt.""" client = clients.get_client('wsfe', point_of_sales.owner.is_sandboxed) response_xml = client.service.FECompUltimoAutorizado( serializers.serialize_ticket( ...
[ "def", "fetch_last_receipt_number", "(", "self", ",", "point_of_sales", ",", "receipt_type", ")", ":", "client", "=", "clients", ".", "get_client", "(", "'wsfe'", ",", "point_of_sales", ".", "owner", ".", "is_sandboxed", ")", "response_xml", "=", "client", ".", ...
33.607143
0.002066
def version_cmp(ver_a, ver_b): """ Compares two version strings in the dotted-numeric-label format. Returns -1 if a < b, 0 if a == b, and +1 if a > b. Inputs may include a prefix string that matches '^\w+[_-]', but both strings must start with the same prefix. If present, it is ignored for pu...
[ "def", "version_cmp", "(", "ver_a", ",", "ver_b", ")", ":", "if", "ver_a", "is", "None", "and", "ver_b", "is", "None", ":", "return", "0", "if", "ver_a", "is", "None", ":", "return", "-", "1", "elif", "ver_b", "is", "None", ":", "return", "1", "try...
29.044776
0.012922
def update_node(self, node, diff=None): """Updates the node's attributes.""" lb = node.parent if not lb: raise exc.UnattachedNode("No parent Load Balancer for this node " "could be determined.") if diff is None: diff = node._diff() req_...
[ "def", "update_node", "(", "self", ",", "node", ",", "diff", "=", "None", ")", ":", "lb", "=", "node", ".", "parent", "if", "not", "lb", ":", "raise", "exc", ".", "UnattachedNode", "(", "\"No parent Load Balancer for this node \"", "\"could be determined.\"", ...
39.75
0.008197
def init_grad(obj, allow_lazy_initializer=False): """Initialize the gradient for an object. Args: obj: The object to initialize the gradient for, can be either a number, array, tuple, list, or dictionary. allow_lazy_initializer: Whether to allow using the ZeroGradient wrapper, for efficiency. ...
[ "def", "init_grad", "(", "obj", ",", "allow_lazy_initializer", "=", "False", ")", ":", "if", "obj", "is", "None", ":", "# TODO: fixes.py appears to pass None value and expect 0.0 back. Bug?", "return", "0.0", "initializer", ",", "supports_lazy_initializer", "=", "grad_ini...
33.516129
0.009355
def wash_html_id(dirty): """Strip non-alphabetic or newline characters from a given string. It can be used as a HTML element ID (also with jQuery and in all browsers). :param dirty: the string to wash :returns: the HTML ID ready string """ import re if not dirty[0].isalpha(): # we ...
[ "def", "wash_html_id", "(", "dirty", ")", ":", "import", "re", "if", "not", "dirty", "[", "0", "]", ".", "isalpha", "(", ")", ":", "# we make sure that the first character is a lowercase letter", "dirty", "=", "'i'", "+", "dirty", "non_word", "=", "re", ".", ...
33.071429
0.002101
def pbkdf2_iteration_calculator(hash_algorithm, key_length, target_ms=100, quiet=False): """ Runs pbkdf2() twice to determine the approximate number of iterations to use to hit a desired time per run. Use this on a production machine to dynamically adjust the number of iterations as high as you can. ...
[ "def", "pbkdf2_iteration_calculator", "(", "hash_algorithm", ",", "key_length", ",", "target_ms", "=", "100", ",", "quiet", "=", "False", ")", ":", "if", "hash_algorithm", "not", "in", "set", "(", "[", "'sha1'", ",", "'sha224'", ",", "'sha256'", ",", "'sha38...
30.356436
0.000948
def psd(t, data, window=None, n_band_average=1): """Compute one-sided power spectral density, subtracting mean automatically. Parameters ---------- t : Time array data : Time series data window : {None, "Hanning"} n_band_average : Number of samples over which to band average ...
[ "def", "psd", "(", "t", ",", "data", ",", "window", "=", "None", ",", "n_band_average", "=", "1", ")", ":", "dt", "=", "t", "[", "1", "]", "-", "t", "[", "0", "]", "N", "=", "len", "(", "data", ")", "data", "=", "data", "-", "np", ".", "m...
31.424242
0.001871
def transpose(self): """Return the transpose of the QuantumChannel.""" return SuperOp( np.transpose(self._data), input_dims=self.output_dims(), output_dims=self.input_dims())
[ "def", "transpose", "(", "self", ")", ":", "return", "SuperOp", "(", "np", ".", "transpose", "(", "self", ".", "_data", ")", ",", "input_dims", "=", "self", ".", "output_dims", "(", ")", ",", "output_dims", "=", "self", ".", "input_dims", "(", ")", "...
36.833333
0.00885
def getAcceptable(accept_header, have_types): """Parse the accept header and return a list of available types in preferred order. If a type is unacceptable, it will not be in the resulting list. This is a convenience wrapper around matchTypes and parseAcceptHeader. (str, [str]) -> [str] ""...
[ "def", "getAcceptable", "(", "accept_header", ",", "have_types", ")", ":", "accepted", "=", "parseAcceptHeader", "(", "accept_header", ")", "preferred", "=", "matchTypes", "(", "accepted", ",", "have_types", ")", "return", "[", "mtype", "for", "(", "mtype", ",...
34.846154
0.002151