text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def clean(self): """ Validates the forum instance. """ super().clean() if self.parent and self.parent.is_link: raise ValidationError(_('A forum can not have a link forum as parent')) if self.is_category and self.parent and self.parent.is_category: raise Validati...
[ "def", "clean", "(", "self", ")", ":", "super", "(", ")", ".", "clean", "(", ")", "if", "self", ".", "parent", "and", "self", ".", "parent", ".", "is_link", ":", "raise", "ValidationError", "(", "_", "(", "'A forum can not have a link forum as parent'", ")...
42.166667
0.009671
def filename(self): """ Returns readable filename for a transcript """ client_id, __ = os.path.splitext(self.video.client_video_id) file_name = u'{name}-{language}.{format}'.format( name=client_id, language=self.language_code, format=self.file_...
[ "def", "filename", "(", "self", ")", ":", "client_id", ",", "__", "=", "os", ".", "path", ".", "splitext", "(", "self", ".", "video", ".", "client_video_id", ")", "file_name", "=", "u'{name}-{language}.{format}'", ".", "format", "(", "name", "=", "client_i...
31.5
0.007712
def debug(self, value): """ Sets the debug status. :param value: The debug status, True or False. :type: bool """ self.__debug = value if self.__debug: # if debug status is True, turn on debug logging for _, logger in iteritems(self.logger...
[ "def", "debug", "(", "self", ",", "value", ")", ":", "self", ".", "__debug", "=", "value", "if", "self", ".", "__debug", ":", "# if debug status is True, turn on debug logging", "for", "_", ",", "logger", "in", "iteritems", "(", "self", ".", "logger", ")", ...
36.333333
0.002554
def get_config(): """ Prepare and return alembic config These configurations used to live in alembic config initialiser, but that just tight coupling. Ideally we should move that to userspace and find a way to pass these into alembic commands. @todo: think about it """ from boiler.migra...
[ "def", "get_config", "(", ")", ":", "from", "boiler", ".", "migrations", ".", "config", "import", "MigrationsConfig", "# used for errors", "map", "=", "dict", "(", "path", "=", "'MIGRATIONS_PATH'", ",", "db_url", "=", "'SQLALCHEMY_DATABASE_URI'", ",", "metadata", ...
29.709677
0.001052
def accept(self): """ Call the :meth:`accept` method of the underlying socket and set up SSL on the returned socket, using the Context object supplied to this :class:`Connection` object at creation. :return: A *(conn, addr)* pair where *conn* is the new :class:`Conne...
[ "def", "accept", "(", "self", ")", ":", "client", ",", "addr", "=", "self", ".", "_socket", ".", "accept", "(", ")", "conn", "=", "Connection", "(", "self", ".", "_context", ",", "client", ")", "conn", ".", "set_accept_state", "(", ")", "return", "("...
40.571429
0.003442
def attempt_json_write( path: str, contents: dict, mode: str = 'w' ) -> typing.Union[None, Exception]: """ Attempts to write the specified JSON content to file. :param path: The path to the file where the JSON serialized content will be written. :param contents: ...
[ "def", "attempt_json_write", "(", "path", ":", "str", ",", "contents", ":", "dict", ",", "mode", ":", "str", "=", "'w'", ")", "->", "typing", ".", "Union", "[", "None", ",", "Exception", "]", ":", "try", ":", "with", "open", "(", "path", ",", "mode...
30.416667
0.007968
def install(packages, repos=None, yes=None, options=None): """ Install one or more RPM packages. Extra *repos* may be passed to ``yum`` to enable extra repositories at install time. Extra *yes* may be passed to ``yum`` to validate license if necessary. Extra *options* may be passed to ``yum`` if ...
[ "def", "install", "(", "packages", ",", "repos", "=", "None", ",", "yes", "=", "None", ",", "options", "=", "None", ")", ":", "manager", "=", "MANAGER", "if", "options", "is", "None", ":", "options", "=", "[", "]", "elif", "isinstance", "(", "options...
31.15
0.002335
def user_lookup(self, ids, id_type="user_id"): """ A generator that returns users for supplied user ids, screen_names, or an iterator of user_ids of either. Use the id_type to indicate which you are supplying (user_id or screen_name) """ if id_type not in ['user_id', 'sc...
[ "def", "user_lookup", "(", "self", ",", "ids", ",", "id_type", "=", "\"user_id\"", ")", ":", "if", "id_type", "not", "in", "[", "'user_id'", ",", "'screen_name'", "]", ":", "raise", "RuntimeError", "(", "\"id_type must be user_id or screen_name\"", ")", "if", ...
34.475
0.00141
def partof(self, ns1, id1, ns2, id2): """Return True if one entity is "partof" another. Parameters ---------- ns1 : str Namespace code for an entity. id1 : str URI for an entity. ns2 : str Namespace code for an entity. id2 : st...
[ "def", "partof", "(", "self", ",", "ns1", ",", "id1", ",", "ns2", ",", "id2", ")", ":", "rel_fun", "=", "lambda", "node", ",", "graph", ":", "self", ".", "partof_objects", "(", "node", ")", "return", "self", ".", "directly_or_indirectly_related", "(", ...
33.208333
0.003659
def show_qos_policy(self, qos_policy, **_params): """Fetches information of a certain qos policy.""" return self.get(self.qos_policy_path % qos_policy, params=_params)
[ "def", "show_qos_policy", "(", "self", ",", "qos_policy", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "qos_policy_path", "%", "qos_policy", ",", "params", "=", "_params", ")" ]
51
0.009662
def put_file_bytes(self, commit, path, value, delimiter=proto.NONE, target_file_datums=0, target_file_bytes=0, overwrite_index=None): """ Uploads a binary bytes array as file(s) in a certain path. Params: * commit: A tuple, string, or Commit object representing th...
[ "def", "put_file_bytes", "(", "self", ",", "commit", ",", "path", ",", "value", ",", "delimiter", "=", "proto", ".", "NONE", ",", "target_file_datums", "=", "0", ",", "target_file_bytes", "=", "0", ",", "overwrite_index", "=", "None", ")", ":", "overwrite_...
47.097222
0.002311
def set_log_channel(self, name): """ Set the channel for this transport's logging. The default is ``"paramiko.transport"`` but it can be set to anything you want. (See the `.logging` module for more info.) SSH Channels will log to a sub-channel of the one specified. :p...
[ "def", "set_log_channel", "(", "self", ",", "name", ")", ":", "self", ".", "log_name", "=", "name", "self", ".", "logger", "=", "util", ".", "get_logger", "(", "name", ")", "self", ".", "packetizer", ".", "set_log", "(", "self", ".", "logger", ")" ]
36.5
0.003817
def submit(self, form, url=None, **kwargs): """Prepares and sends a form request. NOTE: To submit a form with a :class:`StatefulBrowser` instance, it is recommended to use :func:`StatefulBrowser.submit_selected` instead of this method so that the browser state is correctly updated. ...
[ "def", "submit", "(", "self", ",", "form", ",", "url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "form", ",", "Form", ")", ":", "form", "=", "form", ".", "form", "response", "=", "self", ".", "_request", "(", "form"...
46.954545
0.001898
def _url(self, endpoint, path=None): """The complete URL we will end up querying. Depending on the endpoint we pass in this will result in different URL's with different prefixes. :param endpoint: The PuppetDB API endpoint we want to query. :type endpoint: :obj:`string` ...
[ "def", "_url", "(", "self", ",", "endpoint", ",", "path", "=", "None", ")", ":", "log", ".", "debug", "(", "'_url called with endpoint: {0} and path: {1}'", ".", "format", "(", "endpoint", ",", "path", ")", ")", "try", ":", "endpoint", "=", "ENDPOINTS", "[...
33.75
0.0016
def run(self): """Main service entrypoint. Called via Thread.start() via PantsDaemon.run().""" self._logger.info('starting pailgun server on port {}'.format(self.pailgun_port)) try: # Manually call handle_request() in a loop vs serve_forever() for interruptability. while not self._state.is_term...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "'starting pailgun server on port {}'", ".", "format", "(", "self", ".", "pailgun_port", ")", ")", "try", ":", "# Manually call handle_request() in a loop vs serve_forever() for interruptabil...
50.357143
0.016713
def sliding_tensor(mv_time_series, width, step, order='F'): ''' segments multivariate time series with sliding window Parameters ---------- mv_time_series : array like shape [n_samples, n_variables] multivariate time series or sequence width : int > 0 segment width in samples ...
[ "def", "sliding_tensor", "(", "mv_time_series", ",", "width", ",", "step", ",", "order", "=", "'F'", ")", ":", "D", "=", "mv_time_series", ".", "shape", "[", "1", "]", "data", "=", "[", "sliding_window", "(", "mv_time_series", "[", ":", ",", "j", "]", ...
31.047619
0.002976
def get(self, event): """Get a stored configuration""" try: comp = event.data['uuid'] except KeyError: comp = None if not comp: self.log('Invalid get request without schema or component', lvl=error) return se...
[ "def", "get", "(", "self", ",", "event", ")", ":", "try", ":", "comp", "=", "event", ".", "data", "[", "'uuid'", "]", "except", "KeyError", ":", "comp", "=", "None", "if", "not", "comp", ":", "self", ".", "log", "(", "'Invalid get request without schem...
27.68
0.002793
def load(cls, path, voxel_size=1, project=None): r""" Load data from a 3DMA-Rock extracted network. This format consists of two files: 'rockname.np2th' and 'rockname.th2pn'. They should be stored together in a folder which is referred to by the path argument. These files are bi...
[ "def", "load", "(", "cls", ",", "path", ",", "voxel_size", "=", "1", ",", "project", "=", "None", ")", ":", "net", "=", "{", "}", "path", "=", "Path", "(", "path", ")", "path", "=", "path", ".", "resolve", "(", ")", "for", "file", "in", "os", ...
46.382353
0.000414
def login_defs(): """Discover the minimum and maximum UID number.""" uid_min = None uid_max = None login_defs_path = '/etc/login.defs' if os.path.exists(login_defs_path): with io.open(text_type(login_defs_path), encoding=text_type('utf-8')) as log_defs_file: login_data = log_defs...
[ "def", "login_defs", "(", ")", ":", "uid_min", "=", "None", "uid_max", "=", "None", "login_defs_path", "=", "'/etc/login.defs'", "if", "os", ".", "path", ".", "exists", "(", "login_defs_path", ")", ":", "with", "io", ".", "open", "(", "text_type", "(", "...
40.863636
0.002174
def create_symlink(self, link, destination, **kwargs): """Create a symbolic link at ``link`` pointing to ``destination``. :param link: the path to be created that points to target :param destination: the target of the symbolic link :param createParent: If the parent directories do not e...
[ "def", "create_symlink", "(", "self", ",", "link", ",", "destination", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "_put", "(", "link", ",", "'CREATESYMLINK'", ",", "destination", "=", "destination", ",", "*", "*", "kwargs", ")", "...
52.333333
0.007825
def scale_rows(A, v, copy=True): """Scale the sparse rows of a matrix. Parameters ---------- A : sparse matrix Sparse matrix with M rows v : array_like Array of M scales copy : {True,False} - If copy=True, then the matrix is copied to a new and different return ...
[ "def", "scale_rows", "(", "A", ",", "v", ",", "copy", "=", "True", ")", ":", "v", "=", "np", ".", "ravel", "(", "v", ")", "M", ",", "N", "=", "A", ".", "shape", "if", "not", "isspmatrix", "(", "A", ")", ":", "raise", "ValueError", "(", "'scal...
27.197183
0.0005
def undeploy_api_gateway(self, lambda_name, domain_name=None, base_path=None): """ Delete a deployed REST API Gateway. """ print("Deleting API Gateway..") api_id = self.get_api_id(lambda_name) if domain_name: # XXX - Remove Route53 smartly here? ...
[ "def", "undeploy_api_gateway", "(", "self", ",", "lambda_name", ",", "domain_name", "=", "None", ",", "base_path", "=", "None", ")", ":", "print", "(", "\"Deleting API Gateway..\"", ")", "api_id", "=", "self", ".", "get_api_id", "(", "lambda_name", ")", "if", ...
33.2
0.001951
def clean_partitions(self): """Delete partition records and any built partition files. """ import shutil from ambry.orm import ColumnStat # FIXME. There is a problem with the cascades for ColumnStats that prevents them from # being deleted with the partitions. Probably, they ar...
[ "def", "clean_partitions", "(", "self", ")", ":", "import", "shutil", "from", "ambry", ".", "orm", "import", "ColumnStat", "# FIXME. There is a problem with the cascades for ColumnStats that prevents them from", "# being deleted with the partitions. Probably, they are seen to be owed ...
38.157895
0.006729
def __get_untitled_file_name(self): """ Returns an untitled file name. :return: Untitled file name. :rtype: unicode """ untitledNameId = Editor._Editor__untitled_name_id for file in self.list_files(): if not os.path.dirname(file) == self.__default_se...
[ "def", "__get_untitled_file_name", "(", "self", ")", ":", "untitledNameId", "=", "Editor", ".", "_Editor__untitled_name_id", "for", "file", "in", "self", ".", "list_files", "(", ")", ":", "if", "not", "os", ".", "path", ".", "dirname", "(", "file", ")", "=...
33.826087
0.00375
def p_file_comment(self, f_term, predicate): """Sets file comment text.""" try: for _, _, comment in self.graph.triples((f_term, predicate, None)): self.builder.set_file_comment(self.doc, six.text_type(comment)) except CardinalityError: self.more_than_one_...
[ "def", "p_file_comment", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "try", ":", "for", "_", ",", "_", ",", "comment", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "self",...
47.857143
0.005865
def equinox(date, eop_correction=True, terms=106, kinematic=True): """Equinox equation in degrees """ epsilon_bar, delta_psi, delta_eps = _nutation(date, eop_correction, terms) equin = delta_psi * 3600. * np.cos(np.deg2rad(epsilon_bar)) if date.d >= 50506 and kinematic: # Starting 1992-02-...
[ "def", "equinox", "(", "date", ",", "eop_correction", "=", "True", ",", "terms", "=", "106", ",", "kinematic", "=", "True", ")", ":", "epsilon_bar", ",", "delta_psi", ",", "delta_eps", "=", "_nutation", "(", "date", ",", "eop_correction", ",", "terms", "...
40.058824
0.002869
def get(self, now): """ Get a bucket key to compact. If none are available, returns None. This uses a configured lock to ensure that the bucket key is popped off the sorted set in an atomic fashion. :param now: The current time, as a float. Used to ensure the ...
[ "def", "get", "(", "self", ",", "now", ")", ":", "with", "self", ".", "lock", ":", "items", "=", "self", ".", "db", ".", "zrangebyscore", "(", "self", ".", "key", ",", "0", ",", "now", "-", "self", ".", "min_age", ",", "start", "=", "0", ",", ...
33.851852
0.002128
def distributions(self, _args): """Lists all distributions currently available (i.e. that have already been built).""" ctx = self.ctx dists = Distribution.get_distributions(ctx) if dists: print('{Style.BRIGHT}Distributions currently installed are:' ...
[ "def", "distributions", "(", "self", ",", "_args", ")", ":", "ctx", "=", "self", ".", "ctx", "dists", "=", "Distribution", ".", "get_distributions", "(", "ctx", ")", "if", "dists", ":", "print", "(", "'{Style.BRIGHT}Distributions currently installed are:'", "'{S...
42.846154
0.003515
def dx(mt, x): """ Returns the number of dying at begining of age x """ end_x_val = mt.lx.index(0) if x < end_x_val: return mt.lx[x] - mt.lx[x + 1] else: return 0.0
[ "def", "dx", "(", "mt", ",", "x", ")", ":", "end_x_val", "=", "mt", ".", "lx", ".", "index", "(", "0", ")", "if", "x", "<", "end_x_val", ":", "return", "mt", ".", "lx", "[", "x", "]", "-", "mt", ".", "lx", "[", "x", "+", "1", "]", "else",...
27.571429
0.015075
def format(self, record): """Formats a log record and serializes to json""" message_dict = {} if isinstance(record.msg, dict): message_dict = record.msg record.message = None else: record.message = record.getMessage() # only format time if need...
[ "def", "format", "(", "self", ",", "record", ")", ":", "message_dict", "=", "{", "}", "if", "isinstance", "(", "record", ".", "msg", ",", "dict", ")", ":", "message_dict", "=", "record", ".", "msg", "record", ".", "message", "=", "None", "else", ":",...
40.527778
0.002677
def _open_connection(self): """ Open a new connection socket to the CPS.""" if self._scheme == 'unix': self._connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0) self._connection.connect(self._path) elif self._scheme == 'tcp': self._connection = s...
[ "def", "_open_connection", "(", "self", ")", ":", "if", "self", ".", "_scheme", "==", "'unix'", ":", "self", ".", "_connection", "=", "socket", ".", "socket", "(", "socket", ".", "AF_UNIX", ",", "socket", ".", "SOCK_STREAM", ",", "0", ")", "self", ".",...
54.25
0.009063
def trigger(self, **event): """Trigger an event. Event parameters are passed as keyword arguments. Passing an `event` argument isn't required, but generally recommended. """ if not event: raise ValueError("tried to trigger nothing") for hook in self.hooks: ...
[ "def", "trigger", "(", "self", ",", "*", "*", "event", ")", ":", "if", "not", "event", ":", "raise", "ValueError", "(", "\"tried to trigger nothing\"", ")", "for", "hook", "in", "self", ".", "hooks", ":", "if", "hook", ".", "matches", "(", "event", ")"...
29.615385
0.005038
def generate_meta_features(path, base_learner_id): """Generates meta-features for specified base learner After generation of meta-features, the file is saved into the meta-features folder Args: path (str): Path to Xcessiv notebook base_learner_id (str): Base learner ID """ with fu...
[ "def", "generate_meta_features", "(", "path", ",", "base_learner_id", ")", ":", "with", "functions", ".", "DBContextManager", "(", "path", ")", "as", "session", ":", "base_learner", "=", "session", ".", "query", "(", "models", ".", "BaseLearner", ")", ".", "...
41.671233
0.001927
def get(self): """List all accounts""" _, accounts = BaseAccount.search() if ROLE_ADMIN not in session['user'].roles: accounts = list(filter(lambda acct: acct.account_id in session['accounts'], accounts)) if accounts: return self.make_response({ ...
[ "def", "get", "(", "self", ")", ":", "_", ",", "accounts", "=", "BaseAccount", ".", "search", "(", ")", "if", "ROLE_ADMIN", "not", "in", "session", "[", "'user'", "]", ".", "roles", ":", "accounts", "=", "list", "(", "filter", "(", "lambda", "acct", ...
36.705882
0.00625
def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica: """ Create a new replica with the specified parameters. """ return self._replica_class(self._node, instance_id, self._config, is_master, bls_bft, self._metrics)
[ "def", "_new_replica", "(", "self", ",", "instance_id", ":", "int", ",", "is_master", ":", "bool", ",", "bls_bft", ":", "BlsBft", ")", "->", "Replica", ":", "return", "self", ".", "_replica_class", "(", "self", ".", "_node", ",", "instance_id", ",", "sel...
55
0.014337
def generate_plates(seed, world_name, output_dir, width, height, num_plates=10): """ Eventually this method should be invoked when generation is called at asked to stop at step "plates", it should not be a different operation :param seed: :param world_name: :param output_dir:...
[ "def", "generate_plates", "(", "seed", ",", "world_name", ",", "output_dir", ",", "width", ",", "height", ",", "num_plates", "=", "10", ")", ":", "elevation", ",", "plates", "=", "generate_plates_simulation", "(", "seed", ",", "width", ",", "height", ",", ...
42.103448
0.001601
def notification_selected_sm_changed(self, model, prop_name, info): """If a new state machine is selected, make sure the tab is open""" selected_state_machine_id = self.model.selected_state_machine_id if selected_state_machine_id is None: return page_id = self.get_page_num(s...
[ "def", "notification_selected_sm_changed", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "selected_state_machine_id", "=", "self", ".", "model", ".", "selected_state_machine_id", "if", "selected_state_machine_id", "is", "None", ":", "return", "...
46.555556
0.003897
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'store_generic_responses' ) and self.store_generic_responses is not None: _dict['store_generic_responses'] = self.store_generic_responses return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'store_generic_responses'", ")", "and", "self", ".", "store_generic_responses", "is", "not", "None", ":", "_dict", "[", "'store_generic_responses'", "]", "=...
44.285714
0.009494
def _filter_attribute(mcs, attribute_name, attribute_value): """ decides whether the given attribute should be excluded from tracing or not """ if attribute_name == '__module__': return True elif hasattr(attribute_value, '_trace_disable'): return True ...
[ "def", "_filter_attribute", "(", "mcs", ",", "attribute_name", ",", "attribute_value", ")", ":", "if", "attribute_name", "==", "'__module__'", ":", "return", "True", "elif", "hasattr", "(", "attribute_value", ",", "'_trace_disable'", ")", ":", "return", "True", ...
36.444444
0.008929
def deauthorize_application(request): """ When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's "deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding users as unauthorized. """ if request.facebook: ...
[ "def", "deauthorize_application", "(", "request", ")", ":", "if", "request", ".", "facebook", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "facebook_id", "=", "request", ".", "facebook", ".", "signed_request", ".", "user", ".", "id", ")", "...
31.823529
0.008977
def explainParam(self, param): """ Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string. """ param = self._resolveParam(param) values = [] if self.isDefined(param): if param in self._defaultP...
[ "def", "explainParam", "(", "self", ",", "param", ")", ":", "param", "=", "self", ".", "_resolveParam", "(", "param", ")", "values", "=", "[", "]", "if", "self", ".", "isDefined", "(", "param", ")", ":", "if", "param", "in", "self", ".", "_defaultPar...
41.4375
0.00295
def prefix_to_url(self, id): '''prefix_to_url High-level api: Convert an identifier from `prefix:tagname` notation to `{namespace}tagname` notation. If the identifier does not have a prefix, it is assumed that the whole identifier is a tag name. Parameters ---------- ...
[ "def", "prefix_to_url", "(", "self", ",", "id", ")", ":", "parts", "=", "id", ".", "split", "(", "':'", ")", "if", "len", "(", "parts", ")", ">", "1", ":", "return", "'{'", "+", "self", ".", "prefixes", "[", "parts", "[", "0", "]", "]", "+", ...
26.56
0.002907
def gid(self, value): """Group ID setter.""" self.bytearray[self._get_slicers(2)] = bytearray(c_int32(value or 0))
[ "def", "gid", "(", "self", ",", "value", ")", ":", "self", ".", "bytearray", "[", "self", ".", "_get_slicers", "(", "2", ")", "]", "=", "bytearray", "(", "c_int32", "(", "value", "or", "0", ")", ")" ]
42.666667
0.015385
def log_event(name: str, request: Request=None, data=None, ip=None): """ Logs consistent event for easy parsing/analysis. :param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals. :param request: Django REST framework Request (optional) :param data: Even data (optional) :...
[ "def", "log_event", "(", "name", ":", "str", ",", "request", ":", "Request", "=", "None", ",", "data", "=", "None", ",", "ip", "=", "None", ")", ":", "log_data", "=", "{", "}", "if", "not", "ip", "and", "request", ":", "ip", "=", "get_real_ip", "...
32.888889
0.006568
def dot1x_enable(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") dot1x = ET.SubElement(config, "dot1x", xmlns="urn:brocade.com:mgmt:brocade-dot1x") enable = ET.SubElement(dot1x, "enable") callback = kwargs.pop('callback', self._callback) ...
[ "def", "dot1x_enable", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "dot1x", "=", "ET", ".", "SubElement", "(", "config", ",", "\"dot1x\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:brocade-d...
37.333333
0.008721
def _logged_in_successful(data): """ Test the login status from the returned communication of the server. :param data: bytes received from server during login :type data: list of bytes :return boolean, True when you are logged in. """ if re.match(r'^:(te...
[ "def", "_logged_in_successful", "(", "data", ")", ":", "if", "re", ".", "match", "(", "r'^:(testserver\\.local|tmi\\.twitch\\.tv)'", "r' NOTICE \\* :'", "r'(Login unsuccessful|Error logging in)*$'", ",", "data", ".", "strip", "(", ")", ")", ":", "return", "False", "el...
31.470588
0.00363
def near(cls, collection, latitude, longitude, index_id, distance=None, skip=None, limit=None): """ The default will find at most 100 documents near the given coordinate. The returned list is sorted according to the distance, with the nearest document being first in the list. ...
[ "def", "near", "(", "cls", ",", "collection", ",", "latitude", ",", "longitude", ",", "index_id", ",", "distance", "=", "None", ",", "skip", "=", "None", ",", "limit", "=", "None", ")", ":", "kwargs", "=", "{", "'geo'", ":", "index_id", ",", "'latitu...
47.567568
0.006125
def unlink(self): """ Overrides orm unlink method. @param self: The object pointer @return: True/False. """ sale_line_obj = self.env['sale.order.line'] fr_obj = self.env['folio.room.line'] for line in self: if line.order_line_id: ...
[ "def", "unlink", "(", "self", ")", ":", "sale_line_obj", "=", "self", ".", "env", "[", "'sale.order.line'", "]", "fr_obj", "=", "self", ".", "env", "[", "'folio.room.line'", "]", "for", "line", "in", "self", ":", "if", "line", ".", "order_line_id", ":", ...
46.24
0.001695
def DownloadFile(ID, season=None, mission='k2', cadence='lc', filename=None, clobber=False): ''' Download a given :py:mod:`everest` file from MAST. :param str mission: The mission name. Default `k2` :param str cadence: The light curve cadence. Default `lc` :param str filename: The ...
[ "def", "DownloadFile", "(", "ID", ",", "season", "=", "None", ",", "mission", "=", "'k2'", ",", "cadence", "=", "'lc'", ",", "filename", "=", "None", ",", "clobber", "=", "False", ")", ":", "# Get season", "if", "season", "is", "None", ":", "season", ...
33.891304
0.000312
def list_upgrades(refresh=False, root=None, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades on this system CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' upgrades = {} cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v'] ...
[ "def", "list_upgrades", "(", "refresh", "=", "False", ",", "root", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "upgrades", "=", "{", "}", "cmd", "=", "[", "'pacman'", ",", "'-S'", ",", "'-p'", ",", "'-u'", ",", "'--print-...
31.270833
0.000646
def find_tokens(sentence, pattern): """Find all tokens from parts of sentence fitted to pattern, being on the end of matched sub-tree(of sentence) :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which senten...
[ "def", "find_tokens", "(", "sentence", ",", "pattern", ")", ":", "if", "not", "verify_pattern", "(", "pattern", ")", ":", "raise", "PatternSyntaxException", "(", "pattern", ")", "def", "_match_node", "(", "t", ",", "p", ",", "tokens", ")", ":", "pat_node",...
39.666667
0.004474
def spharm(lmax, theta, phi, normalization='4pi', kind='real', csphase=1, packed=False, degrees=True): """ Compute all the spherical harmonic functions up to a maximum degree. Usage ----- ylm = spharm (lmax, theta, phi, [normalization, kind, csphase, packed, ...
[ "def", "spharm", "(", "lmax", ",", "theta", ",", "phi", ",", "normalization", "=", "'4pi'", ",", "kind", "=", "'real'", ",", "csphase", "=", "1", ",", "packed", "=", "False", ",", "degrees", "=", "True", ")", ":", "if", "lmax", "<", "0", ":", "ra...
42.25
0.000413
def check_npndarray(val, dtype=None, writeable=True, verbose=True): """Check if input object is a numpy array. Parameters ---------- val : np.ndarray Input object """ if not isinstance(val, np.ndarray): raise TypeError('Input is not a numpy array.') if ((not isinstance(dt...
[ "def", "check_npndarray", "(", "val", ",", "dtype", "=", "None", ",", "writeable", "=", "True", ",", "verbose", "=", "True", ")", ":", "if", "not", "isinstance", "(", "val", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "'Input is not...
28.454545
0.001546
def _row_heights2xls(self, worksheets): """Writes row_heights to xls file Format: <row>\t<tab>\t<value>\n """ xls_max_rows, xls_max_tabs = self.xls_max_rows, self.xls_max_tabs dict_grid = self.code_array.dict_grid for row, tab in dict_grid.row_heights: if...
[ "def", "_row_heights2xls", "(", "self", ",", "worksheets", ")", ":", "xls_max_rows", ",", "xls_max_tabs", "=", "self", ".", "xls_max_rows", ",", "self", ".", "xls_max_tabs", "dict_grid", "=", "self", ".", "code_array", ".", "dict_grid", "for", "row", ",", "t...
35.421053
0.002894
def shell(args): " A helper command to be used for shell integration " print print "# Makesite integration " print "# ==================== " print "export MAKESITE_HOME=%s" % args.path print "source %s" % op.join(settings.BASEDIR, 'shell.sh') print
[ "def", "shell", "(", "args", ")", ":", "print", "print", "\"# Makesite integration \"", "print", "\"# ==================== \"", "print", "\"export MAKESITE_HOME=%s\"", "%", "args", ".", "path", "print", "\"source %s\"", "%", "op", ".", "join", "(", "settings", ".", ...
33.625
0.003623
def is_json_file(abspath): """Parse file extension. - *.json: uncompressed, utf-8 encode json file - *.gz: compressed, utf-8 encode json file """ abspath = abspath.lower() fname, ext = os.path.splitext(abspath) if ext in [".json", ".js"]: is_json = True elif ext == ".gz": ...
[ "def", "is_json_file", "(", "abspath", ")", ":", "abspath", "=", "abspath", ".", "lower", "(", ")", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "abspath", ")", "if", "ext", "in", "[", "\".json\"", ",", "\".js\"", "]", ":", "i...
29.4
0.001647
def spaced_items(list_, n, **kwargs): """ Returns n evenly spaced items """ indexes = spaced_indexes(len(list_), n, **kwargs) items = list_[indexes] return items
[ "def", "spaced_items", "(", "list_", ",", "n", ",", "*", "*", "kwargs", ")", ":", "indexes", "=", "spaced_indexes", "(", "len", "(", "list_", ")", ",", "n", ",", "*", "*", "kwargs", ")", "items", "=", "list_", "[", "indexes", "]", "return", "items"...
34.6
0.00565
def get_gosubdagplot(self, goids=None, **kws_usr): """Plot GO IDs.""" if goids is None: goids = self.grprobj.usrgos kws_plt, kws_dag = self._get_kws_plt(goids, **kws_usr) gosubdag = GoSubDag( goids, self.grprobj.gosubdag.get_go2obj(goids), ...
[ "def", "get_gosubdagplot", "(", "self", ",", "goids", "=", "None", ",", "*", "*", "kws_usr", ")", ":", "if", "goids", "is", "None", ":", "goids", "=", "self", ".", "grprobj", ".", "usrgos", "kws_plt", ",", "kws_dag", "=", "self", ".", "_get_kws_plt", ...
39.538462
0.003802
def get_version(): """Returns the Postgres version in tuple form, e.g: (9, 1)""" cmd = [PostgresFinder.find_root() / 'pg_ctl', '--version'] results = subprocess.check_output(cmd).decode('utf-8') match = re.search(r'(\d+\.\d+(\.\d+)?)', results) if match: ver_string = ...
[ "def", "get_version", "(", ")", ":", "cmd", "=", "[", "PostgresFinder", ".", "find_root", "(", ")", "/", "'pg_ctl'", ",", "'--version'", "]", "results", "=", "subprocess", ".", "check_output", "(", "cmd", ")", ".", "decode", "(", "'utf-8'", ")", "match",...
48.875
0.005025
def stringify(self) : "a pretty str version of getChain()" l = [] h = self.head while h : l.append(str(h._key)) h = h.nextDoc return "<->".join(l)
[ "def", "stringify", "(", "self", ")", ":", "l", "=", "[", "]", "h", "=", "self", ".", "head", "while", "h", ":", "l", ".", "append", "(", "str", "(", "h", ".", "_key", ")", ")", "h", "=", "h", ".", "nextDoc", "return", "\"<->\"", ".", "join",...
25.375
0.02381
def get_vector( self, lr_motor: float, rr_motor: float, lf_motor: float, rf_motor: float ) -> typing.Tuple[float, float]: """ :param lr_motor: Left rear motor value (-1 to 1); -1 is forward :param rr_motor: Right rear motor value (-1 to 1); 1 is forward :param...
[ "def", "get_vector", "(", "self", ",", "lr_motor", ":", "float", ",", "rr_motor", ":", "float", ",", "lf_motor", ":", "float", ",", "rf_motor", ":", "float", ")", "->", "typing", ".", "Tuple", "[", "float", ",", "float", "]", ":", "if", "self", ".", ...
37.285714
0.006536
def get_single_instance(sql, class_type, *args, **kwargs): """Returns an instance of class_type populated with attributes from the DB record; throws an error if no records are found @param sql: Sql statement to execute @param class_type: The type of class to instantiate and populate wit...
[ "def", "get_single_instance", "(", "sql", ",", "class_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "record", "=", "CoyoteDb", ".", "get_single_record", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "instance", ...
50.222222
0.006515
def interpret_obj( self, obj, v_level_indexes, h_level_indexes, v_level_visibility, h_level_visibility, v_level_sort_keys, h_level_sort_keys, v_level_titles, h_level_titles, ): """Interpret the given Python object as a table. ...
[ "def", "interpret_obj", "(", "self", ",", "obj", ",", "v_level_indexes", ",", "h_level_indexes", ",", "v_level_visibility", ",", "h_level_visibility", ",", "v_level_sort_keys", ",", "h_level_sort_keys", ",", "v_level_titles", ",", "h_level_titles", ",", ")", ":", "i...
30.775
0.00315
def obfuscate(self): """Disguise ciphertext by multiplying by r ** n with random r. This operation must be performed for every `EncryptedNumber` that is sent to an untrusted party, otherwise eavesdroppers might deduce relationships between this and an antecedent `EncryptedNumber...
[ "def", "obfuscate", "(", "self", ")", ":", "r", "=", "self", ".", "public_key", ".", "get_random_lt_n", "(", ")", "r_pow_n", "=", "powmod", "(", "r", ",", "self", ".", "public_key", ".", "n", ",", "self", ".", "public_key", ".", "nsquare", ")", "self...
42.818182
0.004154
def Start(self): """This uploads the rules to the foreman and, thus, starts the hunt.""" # We are already running. if self.hunt_obj.Get(self.hunt_obj.Schema.STATE) == "STARTED": return # Determine when this hunt will expire. self.context.duration = self.runner_args.expiry_time # When the...
[ "def", "Start", "(", "self", ")", ":", "# We are already running.", "if", "self", ".", "hunt_obj", ".", "Get", "(", "self", ".", "hunt_obj", ".", "Schema", ".", "STATE", ")", "==", "\"STARTED\"", ":", "return", "# Determine when this hunt will expire.", "self", ...
33.238095
0.004178
def get_user_model(): """ Returns the user model to use at runtime. :return: User or custom user """ if DJANGO_VERSION >= (1, 5): from django.contrib.auth import get_user_model return get_user_model() # NOQA else: from django.contrib.auth.models import User # NOQA ...
[ "def", "get_user_model", "(", ")", ":", "if", "DJANGO_VERSION", ">=", "(", "1", ",", "5", ")", ":", "from", "django", ".", "contrib", ".", "auth", "import", "get_user_model", "return", "get_user_model", "(", ")", "# NOQA", "else", ":", "from", "django", ...
27
0.002985
def read_map(fname): """ reads a saved text file to list """ lst = [] with open(fname, "r") as f: for line in f: lst.append(line) return lst
[ "def", "read_map", "(", "fname", ")", ":", "lst", "=", "[", "]", "with", "open", "(", "fname", ",", "\"r\"", ")", "as", "f", ":", "for", "line", "in", "f", ":", "lst", ".", "append", "(", "line", ")", "return", "lst" ]
19.555556
0.005435
def trim_common_prefixes(strs, min_len=0): """trim common prefixes""" trimmed = 0 if len(strs) > 1: s1 = min(strs) s2 = max(strs) for i in range(len(s1) - min_len): if s1[i] != s2[i]: break trimmed = i + 1 if trimmed > 0: strs =...
[ "def", "trim_common_prefixes", "(", "strs", ",", "min_len", "=", "0", ")", ":", "trimmed", "=", "0", "if", "len", "(", "strs", ")", ">", "1", ":", "s1", "=", "min", "(", "strs", ")", "s2", "=", "max", "(", "strs", ")", "for", "i", "in", "range"...
19.833333
0.002674
def update_free_item_coupon_by_id(cls, free_item_coupon_id, free_item_coupon, **kwargs): """Update FreeItemCoupon Update attributes of FreeItemCoupon This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread ...
[ "def", "update_free_item_coupon_by_id", "(", "cls", ",", "free_item_coupon_id", ",", "free_item_coupon", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "retu...
51.363636
0.00695
def throttle_login(request): """Throttles a client by keeping track of the number of failed login attempts. If the user succeeds at a login before the max attempts has been reached, the attempts are reset. """ email = request.POST['email'] password = request.POST['password'] # if the form i...
[ "def", "throttle_login", "(", "request", ")", ":", "email", "=", "request", ".", "POST", "[", "'email'", "]", "password", "=", "request", ".", "POST", "[", "'password'", "]", "# if the form is not filled out completely, pass along", "if", "not", "(", "email", "a...
33.169014
0.000412
def ruleName(self): ''' overrides from parent class ''' return _('%s at %s' % (self.room.name, self.room.location.name))
[ "def", "ruleName", "(", "self", ")", ":", "return", "_", "(", "'%s at %s'", "%", "(", "self", ".", "room", ".", "name", ",", "self", ".", "room", ".", "location", ".", "name", ")", ")" ]
44.666667
0.014706
def is_modified(self): """ Determines whether this record set has been modified since the last retrieval or save. :rtype: bool :returns: ``True` if the record set has been modified, and ``False`` if not. """ for key, val in self._initial_vals.items()...
[ "def", "is_modified", "(", "self", ")", ":", "for", "key", ",", "val", "in", "self", ".", "_initial_vals", ".", "items", "(", ")", ":", "if", "getattr", "(", "self", ",", "key", ")", "!=", "val", ":", "# One of the initial values doesn't match, we know", "...
30.117647
0.003788
def clone(self, options=None, attribute_options=None): """ Returns a clone of this mapping that is configured with the given option and attribute option dictionaries. :param dict options: Maps representer options to their values. :param dict attribute_options: Maps attribute nam...
[ "def", "clone", "(", "self", ",", "options", "=", "None", ",", "attribute_options", "=", "None", ")", ":", "copied_cfg", "=", "self", ".", "__configurations", "[", "-", "1", "]", ".", "copy", "(", ")", "upd_cfg", "=", "type", "(", "copied_cfg", ")", ...
48.2
0.002714
def read_from_list_with_ids(self, lines): """ Read text fragments from a given list of tuples:: [(id_1, text_1), (id_2, text_2), ..., (id_n, text_n)]. :param list lines: the list of ``[id, text]`` fragments (see above) """ self.log(u"Reading text fragments from list...
[ "def", "read_from_list_with_ids", "(", "self", ",", "lines", ")", ":", "self", ".", "log", "(", "u\"Reading text fragments from list with ids\"", ")", "self", ".", "_create_text_fragments", "(", "[", "(", "line", "[", "0", "]", ",", "[", "line", "[", "1", "]...
40
0.00489
def p_define(p): """ define : DEFINE ID params defs """ if ENABLED: if p[4]: if SPACES.match(p[4][0]): p[4][0] = p[4][0][1:] else: warning(p.lineno(1), "missing whitespace after the macro name") ID_TABLE.define(p[2], args=p[3], value=p...
[ "def", "p_define", "(", "p", ")", ":", "if", "ENABLED", ":", "if", "p", "[", "4", "]", ":", "if", "SPACES", ".", "match", "(", "p", "[", "4", "]", "[", "0", "]", ")", ":", "p", "[", "4", "]", "[", "0", "]", "=", "p", "[", "4", "]", "[...
30.307692
0.002463
def set( cls, key, value, execution_date, task_id, dag_id, session=None): """ Store an XCom value. TODO: "pickling" has been deprecated and JSON is preferred. "pickling" will be removed in Airflow 2.0. ...
[ "def", "set", "(", "cls", ",", "key", ",", "value", ",", "execution_date", ",", "task_id", ",", "dag_id", ",", "session", "=", "None", ")", ":", "session", ".", "expunge_all", "(", ")", "enable_pickling", "=", "configuration", ".", "getboolean", "(", "'c...
29.285714
0.002023
def get_merkle_root(merkle_tree: MerkleTree) -> bytes: """ Returns the root element of the merkle tree. """ assert merkle_tree.layers, 'the merkle tree layers are empty' assert merkle_tree.layers[-1], 'the root layer is empty' return merkle_tree.layers[-1][0]
[ "def", "get_merkle_root", "(", "merkle_tree", ":", "MerkleTree", ")", "->", "bytes", ":", "assert", "merkle_tree", ".", "layers", ",", "'the merkle tree layers are empty'", "assert", "merkle_tree", ".", "layers", "[", "-", "1", "]", ",", "'the root layer is empty'",...
45.166667
0.003623
def _request_post(self, path, data=None, params=None, url=BASE_URL): """Perform a HTTP POST request..""" url = urljoin(url, path) headers = self._get_request_headers() response = requests.post( url, json=data, params=params, headers=headers, timeout=DEFAULT_TIME...
[ "def", "_request_post", "(", "self", ",", "path", ",", "data", "=", "None", ",", "params", "=", "None", ",", "url", "=", "BASE_URL", ")", ":", "url", "=", "urljoin", "(", "url", ",", "path", ")", "headers", "=", "self", ".", "_get_request_headers", "...
35.333333
0.004598
def getExtensionList(self,extensions): """ This is an internal method that transforms the comma-separated extensions string into a list of extensions, e.g., "ext1,ext2,ext3" gets turned into ['.ext1','.ext2','.ext3']. If MapConstants.placeholderNoExtensionFilter is part of the string, th...
[ "def", "getExtensionList", "(", "self", ",", "extensions", ")", ":", "basicList", "=", "extensions", ".", "split", "(", "','", ")", "extensionList", "=", "[", "]", "for", "ext", "in", "basicList", ":", "if", "ext", "==", "MapConstants", ".", "placeholderNo...
52.055556
0.006289
def get_config_input_source_config_source_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_config = ET.Element("get_config") config = get_config input = ET.SubElement(get_config, "input") source = ET.SubElement(inpu...
[ "def", "get_config_input_source_config_source_candidate_candidate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_config", "=", "ET", ".", "Element", "(", "\"get_config\"", ")", "config", "=", ...
42.357143
0.0033
def get_header(request, header_service): """Return request's 'X_POLYAXON_...:' header, as a bytestring. Hide some test client ickyness where the header can be unicode. """ service = request.META.get('HTTP_{}'.format(header_service), b'') if isinstance(service, str): # Work around django tes...
[ "def", "get_header", "(", "request", ",", "header_service", ")", ":", "service", "=", "request", ".", "META", ".", "get", "(", "'HTTP_{}'", ".", "format", "(", "header_service", ")", ",", "b''", ")", "if", "isinstance", "(", "service", ",", "str", ")", ...
40.1
0.002439
def create_config_backend_options(module_opts, env_name, env_vars): """Return backend options defined in module options.""" backend_opts = {} if module_opts.get('terraform_backend_config'): backend_opts['config'] = merge_nested_environment_dicts( module_opts.get('terraform_backend_confi...
[ "def", "create_config_backend_options", "(", "module_opts", ",", "env_name", ",", "env_vars", ")", ":", "backend_opts", "=", "{", "}", "if", "module_opts", ".", "get", "(", "'terraform_backend_config'", ")", ":", "backend_opts", "[", "'config'", "]", "=", "merge...
41.967742
0.000751
def coal(return_X_y=True): """coal-mining accidents dataset Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) OR Pandas DataFrame ...
[ "def", "coal", "(", "return_X_y", "=", "True", ")", ":", "# y is counts", "# recommend PoissonGAM", "coal", "=", "pd", ".", "read_csv", "(", "PATH", "+", "'/coal.csv'", ",", "index_col", "=", "0", ")", "if", "return_X_y", ":", "y", ",", "x", "=", "np", ...
26.685714
0.003099
def get_vpc(vpc_id, flags=FLAGS.ALL, **conn): """ Orchestrates all the calls required to fully fetch details about a VPC: { "Arn": ..., "Region": ..., "Name": ..., "Id": ..., "Tags: ..., "VpcPeeringConnections": ..., "ClassicLink": ..., "DhcpO...
[ "def", "get_vpc", "(", "vpc_id", ",", "flags", "=", "FLAGS", ".", "ALL", ",", "*", "*", "conn", ")", ":", "# Is the account number that's passed in the same as in the connection dictionary?", "if", "not", "conn", ".", "get", "(", "\"account_number\"", ")", ":", "r...
33.903846
0.00441
def start_user_session(self, username, domain, resource, **kwargs): """Method to add a user session for debugging. Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`. """ kwargs.setdefault('uptime', pytz.utc.localize(datetime.utcnow())...
[ "def", "start_user_session", "(", "self", ",", "username", ",", "domain", ",", "resource", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'uptime'", ",", "pytz", ".", "utc", ".", "localize", "(", "datetime", ".", "utcnow", "(", "...
42.315789
0.001824
async def clear_topic_channel(self, channel): """Set the topic channel for this server""" try: if self.topicchannel: await client.edit_channel(self.topicchannel, topic="") except Exception as e: logger.exception(e) self.topicchannel = None ...
[ "async", "def", "clear_topic_channel", "(", "self", ",", "channel", ")", ":", "try", ":", "if", "self", ".", "topicchannel", ":", "await", "client", ".", "edit_channel", "(", "self", ".", "topicchannel", ",", "topic", "=", "\"\"", ")", "except", "Exception...
35.333333
0.004594
def _get_run_info_dict(self, run_id): """Get the RunInfo for a run, as a dict.""" run_info_path = os.path.join(self._settings.info_dir, run_id, 'info') if os.path.exists(run_info_path): # We copy the RunInfo as a dict, so we can add stuff to it to pass to the template. return RunInfo(run_info_pa...
[ "def", "_get_run_info_dict", "(", "self", ",", "run_id", ")", ":", "run_info_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_settings", ".", "info_dir", ",", "run_id", ",", "'info'", ")", "if", "os", ".", "path", ".", "exists", "(", "...
44.75
0.013699
def get_formset(self, request, obj=None, **kwargs): """ Load Synchronizer schema to display specific fields in admin """ if obj is not None: try: # this is enough to load the new schema obj.external except LayerExternal.DoesNotExist...
[ "def", "get_formset", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "obj", "is", "not", "None", ":", "try", ":", "# this is enough to load the new schema", "obj", ".", "external", "except", "LayerExternal", ...
38.272727
0.006961
def add_tab_stop(self, position, alignment=WD_TAB_ALIGNMENT.LEFT, leader=WD_TAB_LEADER.SPACES): """ Add a new tab stop at *position*, a |Length| object specifying the location of the tab stop relative to the paragraph edge. A negative *position* value is valid and ap...
[ "def", "add_tab_stop", "(", "self", ",", "position", ",", "alignment", "=", "WD_TAB_ALIGNMENT", ".", "LEFT", ",", "leader", "=", "WD_TAB_LEADER", ".", "SPACES", ")", ":", "tabs", "=", "self", ".", "_pPr", ".", "get_or_add_tabs", "(", ")", "tab", "=", "ta...
54.714286
0.003851
def get_staff_url(self): """ Return the Admin URL for the current view. By default, it uses the :func:`get_staff_object` function to base the URL on. """ object = self.get_staff_object() if object is not None: # View is likely using SingleObjectMixin ...
[ "def", "get_staff_url", "(", "self", ")", ":", "object", "=", "self", ".", "get_staff_object", "(", ")", "if", "object", "is", "not", "None", ":", "# View is likely using SingleObjectMixin", "return", "reverse", "(", "admin_urlname", "(", "object", ".", "_meta",...
38.1875
0.00639
def glance_process(body, message): """ This function deal with the glance notification. First, find process from customer_process that not include wildcard. if not find from customer_process, then find process from customer_process_wildcard. if not find from customer_process_wildcard, then use tern...
[ "def", "glance_process", "(", "body", ",", "message", ")", ":", "event_type", "=", "body", "[", "'event_type'", "]", "process", "=", "glance_customer_process", ".", "get", "(", "event_type", ")", "if", "process", "is", "not", "None", ":", "process", "(", "...
36.285714
0.003835
def _isna_old(obj): """Detect missing values. Treat None, NaN, INF, -INF as null. Parameters ---------- arr: ndarray or object value Returns ------- boolean ndarray or boolean """ if is_scalar(obj): return libmissing.checknull_old(obj) # hack (for now) because MI regist...
[ "def", "_isna_old", "(", "obj", ")", ":", "if", "is_scalar", "(", "obj", ")", ":", "return", "libmissing", ".", "checknull_old", "(", "obj", ")", "# hack (for now) because MI registers as ndarray", "elif", "isinstance", "(", "obj", ",", "ABCMultiIndex", ")", ":"...
33.038462
0.001131
def loadDefaultStopWords(language): """ Loads the default stop words for the given language. Supported languages: danish, dutch, english, finnish, french, german, hungarian, italian, norwegian, portuguese, russian, spanish, swedish, turkish """ stopWordsObj = _jvm().org.a...
[ "def", "loadDefaultStopWords", "(", "language", ")", ":", "stopWordsObj", "=", "_jvm", "(", ")", ".", "org", ".", "apache", ".", "spark", ".", "ml", ".", "feature", ".", "StopWordsRemover", "return", "list", "(", "stopWordsObj", ".", "loadDefaultStopWords", ...
52.125
0.007075
def start_auth(self, context, internal_request, get_state=stateID): """ See super class method satosa.backends.base#start_auth :param get_state: Generates a state to be used in the authentication call. :type get_state: Callable[[str, bytes], str] :type context: satosa.context.Co...
[ "def", "start_auth", "(", "self", ",", "context", ",", "internal_request", ",", "get_state", "=", "stateID", ")", ":", "oauth_state", "=", "get_state", "(", "self", ".", "config", "[", "\"base_url\"", "]", ",", "rndstr", "(", ")", ".", "encode", "(", ")"...
46.222222
0.005889
def template_class_from_name(name): """ Return the template class object from agiven name. """ # import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' ...
[ "def", "template_class_from_name", "(", "name", ")", ":", "# import the right template module", "term", "=", "TerminalView", "(", ")", "template_name", "=", "name", "+", "'Template'", "try", ":", "__import__", "(", "'projy.templates.'", "+", "template_name", ")", "t...
38.764706
0.002963
def _request_pre_prepare_for_prepare(self, three_pc_key) -> bool: """ Check if has an acceptable PRE_PREPARE already stashed, if not then check count of PREPAREs, make sure >f consistent PREPAREs are found, store the acceptable PREPARE state (digest, roots) for verification of th...
[ "def", "_request_pre_prepare_for_prepare", "(", "self", ",", "three_pc_key", ")", "->", "bool", ":", "if", "three_pc_key", "in", "self", ".", "prePreparesPendingPrevPP", ":", "self", ".", "logger", ".", "debug", "(", "'{} not requesting a PRE-PREPARE since already found...
46.263158
0.003343
def get_web_proxy(self, backend): """获取一次性代理地址 对内网地址获取一个一次性的外部可访问的代理地址 Args: - backend: 后端地址,如:"10.128.0.1:8080" Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回代理地址信息,失败返回{"error": "<errMsg string>"} - Response...
[ "def", "get_web_proxy", "(", "self", ",", "backend", ")", ":", "url", "=", "'{0}/v3/webproxy'", ".", "format", "(", "self", ".", "host", ")", "return", "self", ".", "__post", "(", "url", ",", "{", "'backend'", ":", "backend", "}", ")" ]
29.533333
0.004376
def path(self): """URL path for change set APIs. :rtype: str :returns: the path based on project, zone, and change set names. """ return "/projects/%s/managedZones/%s/changes/%s" % ( self.zone.project, self.zone.name, self.name, )
[ "def", "path", "(", "self", ")", ":", "return", "\"/projects/%s/managedZones/%s/changes/%s\"", "%", "(", "self", ".", "zone", ".", "project", ",", "self", ".", "zone", ".", "name", ",", "self", ".", "name", ",", ")" ]
27.727273
0.006349
def call_filter(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None): """Invokes a filter on a value the same way the compiler does it. Note that on Python 3 this might return a coroutine in case the filter is running from an environment in async mode and ...
[ "def", "call_filter", "(", "self", ",", "name", ",", "value", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "context", "=", "None", ",", "eval_ctx", "=", "None", ")", ":", "func", "=", "self", ".", "filters", ".", "get", "(", "name", ...
42.933333
0.002278
def get_translocation(self): """Extract INDRA Translocation Statements.""" qstr = "$.events.frames[@.type is 'translocation']" res = self.tree.execute(qstr) if res is None: return for r in res: epistemics = self._get_epistemics(r) if epistemics...
[ "def", "get_translocation", "(", "self", ")", ":", "qstr", "=", "\"$.events.frames[@.type is 'translocation']\"", "res", "=", "self", ".", "tree", ".", "execute", "(", "qstr", ")", "if", "res", "is", "None", ":", "return", "for", "r", "in", "res", ":", "ep...
46.064516
0.001372