text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _cache_get_last_in_slice(url_dict, start_int, total_int, authn_subj_list): """Return None if cache entry does not exist.""" key_str = _gen_cache_key_for_slice(url_dict, start_int, total_int, authn_subj_list) # TODO: Django docs state that cache.get() should return None on unknown key. try: l...
[ "def", "_cache_get_last_in_slice", "(", "url_dict", ",", "start_int", ",", "total_int", ",", "authn_subj_list", ")", ":", "key_str", "=", "_gen_cache_key_for_slice", "(", "url_dict", ",", "start_int", ",", "total_int", ",", "authn_subj_list", ")", "# TODO: Django docs...
51.9
0.007576
def authenticate_token( self, token ): ''' authenticate_token checks the passed token and returns the user_id it is associated with. it is assumed that this method won't be directly exposed to the oauth client, but some kind of framework or wrapper. this allows the framework to h...
[ "def", "authenticate_token", "(", "self", ",", "token", ")", ":", "token_data", "=", "self", ".", "data_store", ".", "fetch", "(", "'tokens'", ",", "token", "=", "token", ")", "if", "not", "token_data", ":", "raise", "Proauth2Error", "(", "'access_denied'", ...
52.583333
0.017134
def data(path, hours, offset=0): """ Does the metric at ``path`` have any whisper data newer than ``hours``? If ``offset`` is not None, view the ``hours`` prior to ``offset`` hours ago, instead of from right now. """ now = time.time() end = now - _to_sec(offset) # Will default to now s...
[ "def", "data", "(", "path", ",", "hours", ",", "offset", "=", "0", ")", ":", "now", "=", "time", ".", "time", "(", ")", "end", "=", "now", "-", "_to_sec", "(", "offset", ")", "# Will default to now", "start", "=", "end", "-", "_to_sec", "(", "hours...
35.416667
0.002294
def get_tileset_from_gid(self, gid): """ Return tileset that owns the gid Note: this is a slow operation, so if you are expecting to do this often, it would be worthwhile to cache the results of this. :param gid: gid of tile image :rtype: TiledTileset if found, otherwise ...
[ "def", "get_tileset_from_gid", "(", "self", ",", "gid", ")", ":", "try", ":", "tiled_gid", "=", "self", ".", "tiledgidmap", "[", "gid", "]", "except", "KeyError", ":", "raise", "ValueError", "for", "tileset", "in", "sorted", "(", "self", ".", "tilesets", ...
32.9
0.002954
def set_range(self, minimum, maximum): """ Set a range. The range is passed unchanged to the rangeChanged member function. :param minimum: minimum value of the range (None if no percentage is required) :param maximum: maximum value of the range (None if no percentage is required)...
[ "def", "set_range", "(", "self", ",", "minimum", ",", "maximum", ")", ":", "self", ".", "_min", "=", "minimum", "self", ".", "_max", "=", "maximum", "self", ".", "on_rangeChange", "(", "minimum", ",", "maximum", ")" ]
42.5
0.009217
def _auth(profile=None, api_version=1, **connection_args): ''' Set up heat credentials, returns `heatclient.client.Client`. Optional parameter "api_version" defaults to 1. Only intended to be used within heat-enabled modules ''' if profile: prefix = profile + ':keystone.' else:...
[ "def", "_auth", "(", "profile", "=", "None", ",", "api_version", "=", "1", ",", "*", "*", "connection_args", ")", ":", "if", "profile", ":", "prefix", "=", "profile", "+", "':keystone.'", "else", ":", "prefix", "=", "'keystone.'", "def", "get", "(", "k...
38.2
0.001823
def queue_exists(self, name): """ Returns True or False, depending on the existence of the named queue. """ try: queue = self._manager.head(name) return True except exc.NotFound: return False
[ "def", "queue_exists", "(", "self", ",", "name", ")", ":", "try", ":", "queue", "=", "self", ".", "_manager", ".", "head", "(", "name", ")", "return", "True", "except", "exc", ".", "NotFound", ":", "return", "False" ]
28.777778
0.007491
def uptime(self): """dict: device uptime """ namespace = 'urn:brocade.com:mgmt:brocade-system' get_system_uptime = ET.Element('get-system-uptime', xmlns=namespace) results = self._callback(get_system_uptime, handler='get') system_uptime = dict(days=results.find('.//{%s}da...
[ "def", "uptime", "(", "self", ")", ":", "namespace", "=", "'urn:brocade.com:mgmt:brocade-system'", "get_system_uptime", "=", "ET", ".", "Element", "(", "'get-system-uptime'", ",", "xmlns", "=", "namespace", ")", "results", "=", "self", ".", "_callback", "(", "ge...
54.285714
0.002587
def find_repo_by_path(i): """ Input: { path - path to repo } Output: { return - return code = 0, if successful 16, if repo not found (may be warning) > 0, if error ...
[ "def", "find_repo_by_path", "(", "i", ")", ":", "p", "=", "i", "[", "'path'", "]", "if", "p", "!=", "''", ":", "p", "=", "os", ".", "path", ".", "normpath", "(", "p", ")", "found", "=", "False", "if", "p", "==", "work", "[", "'dir_default_repo'",...
27.12
0.037722
def length(self): """ Return length(meter) of the line :return: length(meter) of the line :rtype: float """ return math.sqrt( (self.endpoint_a.northing - self.endpoint_b.northing) ** 2 + (self.endpoint_a.easting - self.endpoint_b.easting) ** 2 ...
[ "def", "length", "(", "self", ")", ":", "return", "math", ".", "sqrt", "(", "(", "self", ".", "endpoint_a", ".", "northing", "-", "self", ".", "endpoint_b", ".", "northing", ")", "**", "2", "+", "(", "self", ".", "endpoint_a", ".", "easting", "-", ...
28.727273
0.006135
def empty_directory(self): """Remove all contents of a directory Including any sub-directories and their contents""" for child in self.walkfiles(): child.remove() for child in reversed([d for d in self.walkdirs()]): if child == self or not child.isdir(): ...
[ "def", "empty_directory", "(", "self", ")", ":", "for", "child", "in", "self", ".", "walkfiles", "(", ")", ":", "child", ".", "remove", "(", ")", "for", "child", "in", "reversed", "(", "[", "d", "for", "d", "in", "self", ".", "walkdirs", "(", ")", ...
35.3
0.005525
def content_disposition_header(disptype: str, quote_fields: bool=True, **params: str) -> str: """Sets ``Content-Disposition`` header. disptype is a disposition type: inline, attachment, form-data. Should be valid extension token (see RFC 2183) ...
[ "def", "content_disposition_header", "(", "disptype", ":", "str", ",", "quote_fields", ":", "bool", "=", "True", ",", "*", "*", "params", ":", "str", ")", "->", "str", ":", "if", "not", "disptype", "or", "not", "(", "TOKEN", ">", "set", "(", "disptype"...
39.892857
0.002622
def get_connection(self, internal=False): """Get a live connection to this instance. :param bool internal: Whether or not to use a DC internal network connection. :rtype: :py:class:`redis.client.StrictRedis` """ # Determine the connection string to use. connect_string =...
[ "def", "get_connection", "(", "self", ",", "internal", "=", "False", ")", ":", "# Determine the connection string to use.", "connect_string", "=", "self", ".", "connect_string", "if", "internal", ":", "connect_string", "=", "self", ".", "internal_connect_string", "# S...
38.555556
0.004219
def ToRequest(self): """Converts to gitkit api request parameter dict. Returns: Dict, containing non-empty user attributes. """ param = {} if self.email: param['email'] = self.email if self.user_id: param['localId'] = self.user_id if self.name: param['displayName'] =...
[ "def", "ToRequest", "(", "self", ")", ":", "param", "=", "{", "}", "if", "self", ".", "email", ":", "param", "[", "'email'", "]", "=", "self", ".", "email", "if", "self", ".", "user_id", ":", "param", "[", "'localId'", "]", "=", "self", ".", "use...
30.708333
0.011842
def recursive_setattr(obj: Any, attr: str, val: Any) -> Any: """ Recusrive ``setattr``. This can be used as a drop in for the standard ``setattr(...)``. Credit to: https://stackoverflow.com/a/31174427 Args: obj: Object to retrieve the attribute from. attr: Name of the attribute, with e...
[ "def", "recursive_setattr", "(", "obj", ":", "Any", ",", "attr", ":", "str", ",", "val", ":", "Any", ")", "->", "Any", ":", "pre", ",", "_", ",", "post", "=", "attr", ".", "rpartition", "(", "'.'", ")", "return", "setattr", "(", "recursive_getattr", ...
41.470588
0.004161
def clear(self): """Clear current state.""" self.exposures = [] self.exposure_labels = [] self.exposure_combo_boxes = [] self.exposure_edit_buttons = [] self.mode = CHOOSE_MODE self.layer_purpose = None self.layer_mode = None self.special_case_ind...
[ "def", "clear", "(", "self", ")", ":", "self", ".", "exposures", "=", "[", "]", "self", ".", "exposure_labels", "=", "[", "]", "self", ".", "exposure_combo_boxes", "=", "[", "]", "self", ".", "exposure_edit_buttons", "=", "[", "]", "self", ".", "mode",...
26.666667
0.003017
def stop(self): """ "Uninitialize" logger. Makes :attr:`wasp_launcher.apps.WAppsGlobals.log` logger unavailable :return: None """ if WAppsGlobals.log is not None and WLogApp.__log_handler__ is not None: WAppsGlobals.log.removeHandler(WLogApp.__log_handler__) WLogApp.__log_handler__ = None WAppsGlobals....
[ "def", "stop", "(", "self", ")", ":", "if", "WAppsGlobals", ".", "log", "is", "not", "None", "and", "WLogApp", ".", "__log_handler__", "is", "not", "None", ":", "WAppsGlobals", ".", "log", ".", "removeHandler", "(", "WLogApp", ".", "__log_handler__", ")", ...
32.1
0.030303
def create_event(self, **kwargs): # noqa: E501 """Create a specific event # noqa: E501 The following fields are readonly and will be ignored when passed in the request: <code>id</code>, <code>isEphemeral</code>, <code>isUserEvent</code>, <code>runningState</code>, <code>canDelete</code>, <code>canClo...
[ "def", "create_event", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "create_event_with_http_info", ...
73.380952
0.001281
def arcball_constrain_to_axis(point, axis): """Return sphere point perpendicular to axis.""" v = np.array(point, dtype=np.float64, copy=True) a = np.array(axis, dtype=np.float64, copy=True) v -= a * np.dot(a, v) # on plane n = vector_norm(v) if n > _EPS: if v[2] < 0.0: np.ne...
[ "def", "arcball_constrain_to_axis", "(", "point", ",", "axis", ")", ":", "v", "=", "np", ".", "array", "(", "point", ",", "dtype", "=", "np", ".", "float64", ",", "copy", "=", "True", ")", "a", "=", "np", ".", "array", "(", "axis", ",", "dtype", ...
32.5
0.002137
def save_config(self, cmd="write mem", confirm=False, confirm_response=""): """Saves Config Using Copy Run Start""" return super(CiscoIosBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
[ "def", "save_config", "(", "self", ",", "cmd", "=", "\"write mem\"", ",", "confirm", "=", "False", ",", "confirm_response", "=", "\"\"", ")", ":", "return", "super", "(", "CiscoIosBase", ",", "self", ")", ".", "save_config", "(", "cmd", "=", "cmd", ",", ...
51
0.007722
def _Open(self, path_spec=None, mode='rb'): """Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like...
[ "def", "_Open", "(", "self", ",", "path_spec", "=", "None", ",", "mode", "=", "'rb'", ")", ":", "if", "not", "path_spec", ":", "raise", "ValueError", "(", "'Missing path specfication.'", ")", "volume_index", "=", "lvm", ".", "LVMPathSpecGetVolumeIndex", "(", ...
38.382353
0.003737
def CheckDataStoreAccess(self, token, subjects, requested_access="r"): """Allow all access if token and requested access are valid.""" if any(not x for x in subjects): raise ValueError("Subjects list can't contain empty URNs.") subjects = list(map(rdfvalue.RDFURN, subjects)) return (ValidateAcces...
[ "def", "CheckDataStoreAccess", "(", "self", ",", "token", ",", "subjects", ",", "requested_access", "=", "\"r\"", ")", ":", "if", "any", "(", "not", "x", "for", "x", "in", "subjects", ")", ":", "raise", "ValueError", "(", "\"Subjects list can't contain empty U...
51.4
0.003824
def _read_hdr_dir(self): """Read the header for basic information. Returns ------- hdr : dict - 'erd': header of .erd file - 'stc': general part of .stc file - 'stamps' : time stamp for each file Also, it adds the attribute _basename : Path...
[ "def", "_read_hdr_dir", "(", "self", ")", ":", "foldername", "=", "Path", "(", "self", ".", "filename", ")", "stc_file", "=", "foldername", "/", "(", "foldername", ".", "stem", "+", "'.stc'", ")", "if", "stc_file", ".", "exists", "(", ")", ":", "self",...
34.469388
0.001151
def get_attribute_type(o_attr): ''' Get the base data type (S_DT) associated with a BridgePoint attribute. ''' ref_o_attr = one(o_attr).O_RATTR[106].O_BATTR[113].O_ATTR[106]() if ref_o_attr: return get_attribute_type(ref_o_attr) else: return one(o_attr).S_DT[114]()
[ "def", "get_attribute_type", "(", "o_attr", ")", ":", "ref_o_attr", "=", "one", "(", "o_attr", ")", ".", "O_RATTR", "[", "106", "]", ".", "O_BATTR", "[", "113", "]", ".", "O_ATTR", "[", "106", "]", "(", ")", "if", "ref_o_attr", ":", "return", "get_at...
33
0.003279
def is_labial(c,lang): """ Is the character a labial """ o=get_offset(c,lang) return (o>=LABIAL_RANGE[0] and o<=LABIAL_RANGE[1])
[ "def", "is_labial", "(", "c", ",", "lang", ")", ":", "o", "=", "get_offset", "(", "c", ",", "lang", ")", "return", "(", "o", ">=", "LABIAL_RANGE", "[", "0", "]", "and", "o", "<=", "LABIAL_RANGE", "[", "1", "]", ")" ]
24
0.04698
def collect(self): """ Collect and publish disk temperatures """ instances = {} # Support disks such as /dev/(sd.*) for device in os.listdir('/dev/'): instances.update(self.match_device(device, '/dev/')) # Support disk by id such as /dev/disk/by-id/w...
[ "def", "collect", "(", "self", ")", ":", "instances", "=", "{", "}", "# Support disks such as /dev/(sd.*)", "for", "device", "in", "os", ".", "listdir", "(", "'/dev/'", ")", ":", "instances", ".", "update", "(", "self", ".", "match_device", "(", "device", ...
32.88
0.003546
def admin_penalty(self, column=None, value=None, **kwargs): """ An enforcement action that results in levying the permit holder with a penalty or fine. It is used to track judicial hearing dates, penalty amounts, and type of administrative penalty order. >>> PCS().admin_penalty(...
[ "def", "admin_penalty", "(", "self", ",", "column", "=", "None", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_resolve_call", "(", "'PCS_ADMIN_PENALTY_ORDER'", ",", "column", ",", "value", ",", "*", "*", "kwargs",...
47.6
0.004124
def api_request(request, *args, **kwargs): """ Create an API request. `request_type` is the request type (string). This is used to look up a plugin, whose request class is instantiated and passed the remaining arguments passed to this function. """ plugin = pm.api_plugin_for_request(request...
[ "def", "api_request", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "plugin", "=", "pm", ".", "api_plugin_for_request", "(", "request", ")", "if", "plugin", "and", "plugin", ".", "request_class", ":", "req", "=", "plugin", ".", "...
33.785714
0.002058
def strip(self, text): '''Return string with markup tags removed.''' tags, results = [], [] return self.re_tag.sub(lambda m: self.clear_tag(m, tags, results), text)
[ "def", "strip", "(", "self", ",", "text", ")", ":", "tags", ",", "results", "=", "[", "]", ",", "[", "]", "return", "self", ".", "re_tag", ".", "sub", "(", "lambda", "m", ":", "self", ".", "clear_tag", "(", "m", ",", "tags", ",", "results", ")"...
46.25
0.015957
def env_float(name: str, required: bool=False, default: Union[Type[empty], float]=empty) -> float: """Pulls an environment variable out of the environment and casts it to an float. If the name is not present in the environment and no default is specified then a ``ValueError`` will be raised. Similarly, if t...
[ "def", "env_float", "(", "name", ":", "str", ",", "required", ":", "bool", "=", "False", ",", "default", ":", "Union", "[", "Type", "[", "empty", "]", ",", "float", "]", "=", "empty", ")", "->", "float", ":", "value", "=", "get_env_value", "(", "na...
43.961538
0.006849
def set(cls, var_name: str, value: Any) -> 'Configuration': """ Set the variable :param var_name: Variable name :param value: Value of variable :return: :class:`~haps.config.Configuration` instance for easy\ chaining """ with cls._lock: ...
[ "def", "set", "(", "cls", ",", "var_name", ":", "str", ",", "value", ":", "Any", ")", "->", "'Configuration'", ":", "with", "cls", ".", "_lock", ":", "if", "var_name", "not", "in", "cls", "(", ")", ".", "cache", ":", "cls", "(", ")", ".", "cache"...
32.75
0.003711
def _in_deferred_types(self, cls): """ Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type registry for future ...
[ "def", "_in_deferred_types", "(", "self", ",", "cls", ")", ":", "mod", "=", "getattr", "(", "cls", ",", "'__module__'", ",", "None", ")", "name", "=", "getattr", "(", "cls", ",", "'__name__'", ",", "None", ")", "key", "=", "(", "mod", ",", "name", ...
40.470588
0.002841
def _parse(self, fp): """ linux-pam-1.3.1/modules/pam_env/pam_env.c#L207 """ for line in fp: # ' #export foo=some var ' -> ['#export', 'foo=some var '] bits = shlex_split(line, comments=True) if (not bits) or bits[0].startswith('#'): ...
[ "def", "_parse", "(", "self", ",", "fp", ")", ":", "for", "line", "in", "fp", ":", "# ' #export foo=some var ' -> ['#export', 'foo=some var ']", "bits", "=", "shlex_split", "(", "line", ",", "comments", "=", "True", ")", "if", "(", "not", "bits", ")", "o...
31.875
0.00381
def _estimate_free(self): """ Estimate completion time for a free task. :returns: deferred that when fired returns a datetime object for the estimated, or the actual datetime, or None if we could not estimate a time for this task method. """ #...
[ "def", "_estimate_free", "(", "self", ")", ":", "# Query the information we need for this task's channel and package.", "capacity_deferred", "=", "self", ".", "channel", ".", "total_capacity", "(", ")", "open_tasks_deferred", "=", "self", ".", "channel", ".", "tasks", "...
49.90625
0.001229
def bind_path_fallback(self, name, folder): """Adds a fallback for a given folder relative to `base_path`.""" if not len(name) or name[0] != '/' or name[-1] != '/': raise ValueError( "name must start and end with '/': {0}".format(name)) self._folder_masks.append((name...
[ "def", "bind_path_fallback", "(", "self", ",", "name", ",", "folder", ")", ":", "if", "not", "len", "(", "name", ")", "or", "name", "[", "0", "]", "!=", "'/'", "or", "name", "[", "-", "1", "]", "!=", "'/'", ":", "raise", "ValueError", "(", "\"nam...
54.166667
0.006061
def get_params(mail, failobj=None, header='content-type', unquote=True): '''Get Content-Type parameters as dict. RFC 2045 specifies that parameter names are case-insensitive, so we normalize them here. :param mail: :class:`email.message.Message` :param failobj: object to return if no such header i...
[ "def", "get_params", "(", "mail", ",", "failobj", "=", "None", ",", "header", "=", "'content-type'", ",", "unquote", "=", "True", ")", ":", "failobj", "=", "failobj", "or", "[", "]", "return", "{", "k", ".", "lower", "(", ")", ":", "v", "for", "k",...
41.571429
0.001681
def get_relationship_form_for_update(self, relationship_id=None): """Gets the relationship form for updating an existing relationship. A new relationship form should be requested for each update transaction. arg: relationship_id (osid.id.Id): the ``Id`` of the ``Rela...
[ "def", "get_relationship_form_for_update", "(", "self", ",", "relationship_id", "=", "None", ")", ":", "if", "relationship_id", "is", "None", ":", "raise", "NullArgument", "(", ")", "try", ":", "url_path", "=", "(", "'/handcar/services/relationship/families/'", "+",...
45.178571
0.002322
def netdevs(): ''' RX and TX bytes for each of the network devices ''' with open('/proc/net/dev') as f: net_dump = f.readlines() device_data={} data = namedtuple('data',['rx','tx']) for line in net_dump[2:]: line = line.split(':') if line[0].strip() != 'lo': ...
[ "def", "netdevs", "(", ")", ":", "with", "open", "(", "'/proc/net/dev'", ")", "as", "f", ":", "net_dump", "=", "f", ".", "readlines", "(", ")", "device_data", "=", "{", "}", "data", "=", "namedtuple", "(", "'data'", ",", "[", "'rx'", ",", "'tx'", "...
33.666667
0.017341
def to_result(self, iface_name, func_name, resp): """ Takes a JSON-RPC response and checks for an "error" slot. If it exists, a RpcException is raised. If no "error" slot exists, the "result" slot is returned. If validate_response==True on the Client constructor, the result is...
[ "def", "to_result", "(", "self", ",", "iface_name", ",", "func_name", ",", "resp", ")", ":", "if", "resp", ".", "has_key", "(", "\"error\"", ")", ":", "e", "=", "resp", "[", "\"error\"", "]", "data", "=", "None", "if", "e", ".", "has_key", "(", "\"...
34.9
0.009294
def PluRunOff_cowinners(self, profile): """ Returns a list that associates all the winners of a profile under Plurality with Runoff rule. :ivar Profile profile: A Profile object that represents an election profile. """ # Currently, we expect the profile to contain complete orde...
[ "def", "PluRunOff_cowinners", "(", "self", ",", "profile", ")", ":", "# Currently, we expect the profile to contain complete ordering over candidates. Ties are", "# allowed however.", "elecType", "=", "profile", ".", "getElecType", "(", ")", "if", "elecType", "!=", "\"soc\"",...
42.88
0.003648
def get_child_account(self, account_name): """ Retrieves a child account. This could be a descendant nested at any level. :param account_name: The name of the account to retrieve. :returns: The child account, if found, else None. """ if r'/' in account_name: ...
[ "def", "get_child_account", "(", "self", ",", "account_name", ")", ":", "if", "r'/'", "in", "account_name", ":", "accs_in_path", "=", "account_name", ".", "split", "(", "r'/'", ",", "1", ")", "curr_acc", "=", "self", "[", "accs_in_path", "[", "0", "]", "...
29.6
0.003273
def log_parameter_and_gradient_statistics(self, # pylint: disable=invalid-name model: Model, batch_grad_norm: float) -> None: """ Send the mean and std of all parameters and gradients to tensorboard, as well ...
[ "def", "log_parameter_and_gradient_statistics", "(", "self", ",", "# pylint: disable=invalid-name", "model", ":", "Model", ",", "batch_grad_norm", ":", "float", ")", "->", "None", ":", "if", "self", ".", "_should_log_parameter_statistics", ":", "# Log parameter values to ...
56.068966
0.00786
def get_previous_price(self, currency, date_obj): """ Get Price for one bit coin on given date """ start = date_obj.strftime('%Y-%m-%d') end = date_obj.strftime('%Y-%m-%d') url = ( 'https://api.coindesk.com/v1/bpi/historical/close.json' '?start={}&...
[ "def", "get_previous_price", "(", "self", ",", "currency", ",", "date_obj", ")", ":", "start", "=", "date_obj", ".", "strftime", "(", "'%Y-%m-%d'", ")", "end", "=", "date_obj", ".", "strftime", "(", "'%Y-%m-%d'", ")", "url", "=", "(", "'https://api.coindesk....
37.45
0.003906
def digicam_configure_send(self, target_system, target_component, mode, shutter_speed, aperture, iso, exposure_type, command_id, engine_cut_off, extra_param, extra_value, force_mavlink1=False): ''' Configure on-board Camera Control System. target_system : Sys...
[ "def", "digicam_configure_send", "(", "self", ",", "target_system", ",", "target_component", ",", "mode", ",", "shutter_speed", ",", "aperture", ",", "iso", ",", "exposure_type", ",", "command_id", ",", "engine_cut_off", ",", "extra_param", ",", "extra_value", ","...
95.111111
0.007519
def memoize(fn): '''Cache the results of a function that only takes positional arguments.''' cache = {} @wraps(fn) def wrapped_function(*args): if args in cache: return cache[args] else: result = fn(*args) cache[args] = result return res...
[ "def", "memoize", "(", "fn", ")", ":", "cache", "=", "{", "}", "@", "wraps", "(", "fn", ")", "def", "wrapped_function", "(", "*", "args", ")", ":", "if", "args", "in", "cache", ":", "return", "cache", "[", "args", "]", "else", ":", "result", "=",...
21.0625
0.002841
def yield_pair_gradients(self, index1, index2): """Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))""" strength = self.strengths[index1, index2] distance = self.distances[index1, index2] yield -6*strength*distance**(-7), np.zeros(3)
[ "def", "yield_pair_gradients", "(", "self", ",", "index1", ",", "index2", ")", ":", "strength", "=", "self", ".", "strengths", "[", "index1", ",", "index2", "]", "distance", "=", "self", ".", "distances", "[", "index1", ",", "index2", "]", "yield", "-", ...
51.4
0.007663
def deep_copy(data, xid): """ Create a deep clone of the frame ``data``. :param data: an H2OFrame to be cloned :param xid: (internal) id to be assigned to the new frame. :returns: new :class:`H2OFrame` which is the clone of the passed frame. """ assert_is_type(data, H2OFrame) assert_is_...
[ "def", "deep_copy", "(", "data", ",", "xid", ")", ":", "assert_is_type", "(", "data", ",", "H2OFrame", ")", "assert_is_type", "(", "xid", ",", "str", ")", "assert_satisfies", "(", "xid", ",", "xid", "!=", "data", ".", "frame_id", ")", "check_frame_id", "...
35.058824
0.001634
def samples(*sets): """Generate samples from the given sets using their ``examples`` method. Parameters ---------- set1, ..., setN : `Set` instance Set(s) from which to generate the samples. Returns ------- samples : `generator` Generator that yields tuples of examples from...
[ "def", "samples", "(", "*", "sets", ")", ":", "if", "len", "(", "sets", ")", "==", "1", ":", "for", "example", "in", "sets", "[", "0", "]", ".", "examples", ":", "yield", "example", "else", ":", "generators", "=", "[", "set_", ".", "examples", "f...
27.96
0.001383
def save_formset(self, request, form, formset, change): """ For each photo set it's author to currently authenticated user. """ instances = formset.save(commit=False) for instance in instances: if isinstance(instance, Photo): instance.author = request....
[ "def", "save_formset", "(", "self", ",", "request", ",", "form", ",", "formset", ",", "change", ")", ":", "instances", "=", "formset", ".", "save", "(", "commit", "=", "False", ")", "for", "instance", "in", "instances", ":", "if", "isinstance", "(", "i...
38.222222
0.005682
def parse_factor_line(line): """ function to parse a factor file line. Used by fac2real() Parameters ---------- line : (str) a factor line from a factor file Returns ------- inode : int the inode of the grid node itrans : int flag for transformation of the grid...
[ "def", "parse_factor_line", "(", "line", ")", ":", "raw", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "inode", ",", "itrans", ",", "nfac", "=", "[", "int", "(", "i", ")", "for", "i", "in", "raw", "[", ":", "3", "]", "]", "fac...
27.321429
0.011364
def convert_zero_consonant(pinyin): """零声母转换,还原原始的韵母 i行的韵母,前面没有声母的时候,写成yi(衣),ya(呀),ye(耶),yao(腰), you(忧),yan(烟),yin(因),yang(央),ying(英),yong(雍)。 u行的韵母,前面没有声母的时候,写成wu(乌),wa(蛙),wo(窝),wai(歪), wei(威),wan(弯),wen(温),wang(汪),weng(翁)。 ü行的韵母,前面没有声母的时候,写成yu(迂),yue(约),yuan(冤), yun(晕);ü上两点省略。 """ ...
[ "def", "convert_zero_consonant", "(", "pinyin", ")", ":", "# y: yu -> v, yi -> i, y -> i", "if", "pinyin", ".", "startswith", "(", "'y'", ")", ":", "# 去除 y 后的拼音", "no_y_py", "=", "pinyin", "[", "1", ":", "]", "first_char", "=", "no_y_py", "[", "0", "]", "if"...
25.909091
0.000845
def validate_arguments_type_of_function(param_type=None): """ Decorator to validate the <type> of arguments in the calling function are of the `param_type` class. if `param_type` is None, uses `param_type` as the class where it is used. Note: Use this decorator on the functions of the class. "...
[ "def", "validate_arguments_type_of_function", "(", "param_type", "=", "None", ")", ":", "def", "inner", "(", "function", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "type_", "=", "param_type", "or", "type...
31.625
0.000959
def check(source): """Return messages from pyflakes.""" if sys.version_info[0] == 2 and isinstance(source, unicode): # Convert back to original byte string encoding, otherwise pyflakes # call to compile() will complain. See PEP 263. This only affects # Python 2. try: ...
[ "def", "check", "(", "source", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", "and", "isinstance", "(", "source", ",", "unicode", ")", ":", "# Convert back to original byte string encoding, otherwise pyflakes", "# call to compile() will complain...
36.941176
0.001553
def publishCombinedWebMap(self, maps_info, webmaps): """Publishes a combination of web maps. Args: maps_info (list): A list of JSON configuration combined web maps to publish. Returns: list: A list of results from :py:meth:`arcrest.manageorg._content.Use...
[ "def", "publishCombinedWebMap", "(", "self", ",", "maps_info", ",", "webmaps", ")", ":", "if", "self", ".", "securityhandler", "is", "None", ":", "print", "(", "\"Security handler required\"", ")", "return", "admin", "=", "None", "map_results", "=", "None", "m...
32.266055
0.006897
def create_and_update_from_json_data(d, user): """ Create or update page based on python dict d loaded from JSON data. This applies all data except for redirect_to, which is done in a second pass after all pages have been imported, user is the User instance that will be used if the author can't ...
[ "def", "create_and_update_from_json_data", "(", "d", ",", "user", ")", ":", "page", "=", "None", "parent", "=", "None", "parent_required", "=", "True", "created", "=", "False", "messages", "=", "[", "]", "page_languages", "=", "set", "(", "lang", "[", "0",...
34.178571
0.002031
def _validate_date_like_dtype(dtype): """ Check whether the dtype is a date-like dtype. Raises an error if invalid. Parameters ---------- dtype : dtype, type The dtype to check. Raises ------ TypeError : The dtype could not be casted to a date-like dtype. ValueError : The d...
[ "def", "_validate_date_like_dtype", "(", "dtype", ")", ":", "try", ":", "typ", "=", "np", ".", "datetime_data", "(", "dtype", ")", "[", "0", "]", "except", "ValueError", "as", "e", ":", "raise", "TypeError", "(", "'{error}'", ".", "format", "(", "error",...
32
0.001319
def ExtractEventsFromSources(self): """Processes the sources and extracts events. Raises: BadConfigOption: if the storage file path is invalid or the storage format not supported or an invalid filter was specified. SourceScannerError: if the source scanner could not find a supported ...
[ "def", "ExtractEventsFromSources", "(", "self", ")", ":", "self", ".", "_CheckStorageFile", "(", "self", ".", "_storage_file_path", ",", "warn_about_existing", "=", "True", ")", "scan_context", "=", "self", ".", "ScanSource", "(", "self", ".", "_source_path", ")...
40.631579
0.003288
def wait(self): '''This waits until the child exits. This is a blocking call. This will not read any data from the child, so this will block forever if the child has unread output and has terminated. In other words, the child may have printed output then called exit(), but, the child is ...
[ "def", "wait", "(", "self", ")", ":", "ptyproc", "=", "self", ".", "ptyproc", "with", "_wrap_ptyprocess_err", "(", ")", ":", "# exception may occur if \"Is some other process attempting", "# \"job control with our child pid?\"", "exitstatus", "=", "ptyproc", ".", "wait", ...
43.521739
0.001955
def _simplify(self, pattern): # type: (str) -> str r""" Clean up urlpattern regexes into something readable by humans: From: > "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$" To: > "{sport_slug}/athletes/{athlete_slug}/" """ # remove opti...
[ "def", "_simplify", "(", "self", ",", "pattern", ")", ":", "# type: (str) -> str", "# remove optional params", "# TODO(dcramer): it'd be nice to change these into [%s] but it currently", "# conflicts with the other rules because we're doing regexp matches", "# rather than parsing tokens", ...
32.888889
0.004922
def getResources(self,ep,noResp=False,cacheOnly=False): """ Get list of resources on an endpoint. :param str ep: Endpoint to get the resources of :param bool noResp: Optional - specify no response necessary from endpoint :param bool cacheOnly: Optional - get results from cache on connector, do not wake up ...
[ "def", "getResources", "(", "self", ",", "ep", ",", "noResp", "=", "False", ",", "cacheOnly", "=", "False", ")", ":", "# load query params if set to other than defaults", "q", "=", "{", "}", "result", "=", "asyncResult", "(", ")", "result", ".", "endpoint", ...
38.1
0.040956
def parse_feature(obj): """ Given a python object attemp to a GeoJSON-like Feature from it """ # object implementing geo_interface if hasattr(obj, '__geo_interface__'): gi = obj.__geo_interface__ if gi['type'] in geom_types: return wrap_geom(gi) elif gi['type'] =...
[ "def", "parse_feature", "(", "obj", ")", ":", "# object implementing geo_interface", "if", "hasattr", "(", "obj", ",", "'__geo_interface__'", ")", ":", "gi", "=", "obj", ".", "__geo_interface__", "if", "gi", "[", "'type'", "]", "in", "geom_types", ":", "return...
25.486486
0.001021
def dump_header(iterable, allow_token=True): """Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_heade...
[ "def", "dump_header", "(", "iterable", ",", "allow_token", "=", "True", ")", ":", "if", "isinstance", "(", "iterable", ",", "dict", ")", ":", "items", "=", "[", "]", "for", "key", ",", "value", "in", "iteritems", "(", "iterable", ")", ":", "if", "val...
39.074074
0.002775
def get_rlbot_directory() -> str: """Gets the path of the rlbot package directory""" return os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
[ "def", "get_rlbot_directory", "(", ")", "->", "str", ":", "return", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ")" ]
52.666667
0.00625
def write_to_file(self): """ Writes the weeks with associated commits to file. """ with open('../github_stats_output/last_year_commits.csv', 'w+') as output: output.write('date,organization,repos,members,teams,' + 'unique_contributors,total_contributors,forks,...
[ "def", "write_to_file", "(", "self", ")", ":", "with", "open", "(", "'../github_stats_output/last_year_commits.csv'", ",", "'w+'", ")", "as", "output", ":", "output", ".", "write", "(", "'date,organization,repos,members,teams,'", "+", "'unique_contributors,total_contribut...
51.9
0.012299
def fcoe_get_interface_input_fcoe_intf_include_stats(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface input = ET.SubElement(fcoe_get_interface, "input") fcoe...
[ "def", "fcoe_get_interface_input_fcoe_intf_include_stats", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fcoe_get_interface", "=", "ET", ".", "Element", "(", "\"fcoe_get_interface\"", ")", "config", ...
45.5
0.005386
def _get_mean(self, imt, mag, hypo_depth, rrup, d): """ Return mean value as defined in equation 3.5.1-1 page 148 """ # clip magnitude at 8.3 as per note at page 3-36 in table Table 3.3.2-6 # in "Technical Reports on National Seismic Hazard Maps for Japan" mag = min(mag, ...
[ "def", "_get_mean", "(", "self", ",", "imt", ",", "mag", ",", "hypo_depth", ",", "rrup", ",", "d", ")", ":", "# clip magnitude at 8.3 as per note at page 3-36 in table Table 3.3.2-6", "# in \"Technical Reports on National Seismic Hazard Maps for Japan\"", "mag", "=", "min", ...
31.5
0.0022
def _get_fault_type_hanging_wall(self, rake): """ Return fault type (F) and hanging wall (HW) flags depending on rake angle. The method assumes 'reverse' (F = 1) if 45 <= rake <= 135, 'other' (F = 0) if otherwise. Hanging-wall flag is set to 1 if 'reverse', and 0 if 'oth...
[ "def", "_get_fault_type_hanging_wall", "(", "self", ",", "rake", ")", ":", "F", ",", "HW", "=", "0", ",", "0", "if", "45", "<=", "rake", "<=", "135", ":", "F", ",", "HW", "=", "1", ",", "1", "return", "F", ",", "HW" ]
28.066667
0.004598
def get_fields(self, serializer_fields): """ Get fields metadata skipping empty fields """ fields = OrderedDict() for field_name, field in serializer_fields.items(): # Skip tags field in action because it is needed only for resource creation # See also: WA...
[ "def", "get_fields", "(", "self", ",", "serializer_fields", ")", ":", "fields", "=", "OrderedDict", "(", ")", "for", "field_name", ",", "field", "in", "serializer_fields", ".", "items", "(", ")", ":", "# Skip tags field in action because it is needed only for resource...
37
0.00565
def is_hash256(s): """ Returns True if the considered string is a valid SHA256 hash. """ if not s or not isinstance(s, str): return False return re.match('^[0-9A-F]{64}$', s.strip(), re.IGNORECASE)
[ "def", "is_hash256", "(", "s", ")", ":", "if", "not", "s", "or", "not", "isinstance", "(", "s", ",", "str", ")", ":", "return", "False", "return", "re", ".", "match", "(", "'^[0-9A-F]{64}$'", ",", "s", ".", "strip", "(", ")", ",", "re", ".", "IGN...
42.6
0.004608
def arrow_from_wid(self, wid): """Make a real portal and its arrow from a dummy arrow. This doesn't handle touch events. It takes a widget as its argument: the one the user has been dragging to indicate where they want the arrow to go. Said widget ought to be invisible. It check...
[ "def", "arrow_from_wid", "(", "self", ",", "wid", ")", ":", "for", "spot", "in", "self", ".", "board", ".", "spotlayout", ".", "children", ":", "if", "spot", ".", "collide_widget", "(", "wid", ")", ":", "whereto", "=", "spot", "break", "else", ":", "...
35.72
0.002181
def _colorize(self, msg, color=None, encode=False): """ Colorize a string. """ # Valid colors colors = { 'red': '31', 'green': '32', 'yellow': '33' } # No color specified or unsupported color if not...
[ "def", "_colorize", "(", "self", ",", "msg", ",", "color", "=", "None", ",", "encode", "=", "False", ")", ":", "# Valid colors", "colors", "=", "{", "'red'", ":", "'31'", ",", "'green'", ":", "'32'", ",", "'yellow'", ":", "'33'", "}", "# No color speci...
27.3
0.010619
async def make_response(*args: Any) -> Response: """Create a response, a simple wrapper function. This is most useful when you want to alter a Response before returning it, for example .. code-block:: python response = make_response(render_template('index.html')) response.headers['X-H...
[ "async", "def", "make_response", "(", "*", "args", ":", "Any", ")", "->", "Response", ":", "if", "not", "args", ":", "return", "current_app", ".", "response_class", "(", ")", "if", "len", "(", "args", ")", "==", "1", ":", "args", "=", "args", "[", ...
27.222222
0.001972
def _inter_manager_operations(self, other, how_to_join, func): """Inter-data operations (e.g. add, sub). Args: other: The other Manager for the operation. how_to_join: The type of join to join to make (e.g. right, outer). Returns: New DataManager with new da...
[ "def", "_inter_manager_operations", "(", "self", ",", "other", ",", "how_to_join", ",", "func", ")", ":", "reindexed_self", ",", "reindexed_other_list", ",", "joined_index", "=", "self", ".", "copartition", "(", "0", ",", "other", ",", "how_to_join", ",", "Fal...
43.725
0.001678
def LogLikelihood(self, data): """Computes the log likelihood of the data. Selects a random vector of probabilities from this distribution. Returns: float log probability """ m = len(data) if self.n < m: return float('-inf') x = self.Random() ...
[ "def", "LogLikelihood", "(", "self", ",", "data", ")", ":", "m", "=", "len", "(", "data", ")", "if", "self", ".", "n", "<", "m", ":", "return", "float", "(", "'-inf'", ")", "x", "=", "self", ".", "Random", "(", ")", "y", "=", "numpy", ".", "l...
25.642857
0.005376
def plot_simseries(self, **kwargs: Any) -> None: """Plot the |IOSequence.series| of the |Sim| sequence object. See method |Node.plot_allseries| for further information. """ self.__plot_series([self.sequences.sim], kwargs)
[ "def", "plot_simseries", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "__plot_series", "(", "[", "self", ".", "sequences", ".", "sim", "]", ",", "kwargs", ")" ]
41.5
0.007874
def get_urls(self): """ Add the entries view to urls. """ urls = super(FormAdmin, self).get_urls() extra_urls = [ re_path("^(?P<form_id>\d+)/entries/$", self.admin_site.admin_view(self.entries_view), name="form_entries"), re...
[ "def", "get_urls", "(", "self", ")", ":", "urls", "=", "super", "(", "FormAdmin", ",", "self", ")", ".", "get_urls", "(", ")", "extra_urls", "=", "[", "re_path", "(", "\"^(?P<form_id>\\d+)/entries/$\"", ",", "self", ".", "admin_site", ".", "admin_view", "(...
42.05
0.016279
def checkUserAccess(worksheet, request, redirect=True): """ Checks if the current user has granted access to the worksheet. If the user is an analyst without LabManager, LabClerk and RegulatoryInspector roles and the option 'Allow analysts only to access to the Worksheets on which they are a...
[ "def", "checkUserAccess", "(", "worksheet", ",", "request", ",", "redirect", "=", "True", ")", ":", "# Deny access to foreign analysts", "allowed", "=", "worksheet", ".", "checkUserAccess", "(", ")", "if", "allowed", "==", "False", "and", "redirect", "==", "True...
50.227273
0.003552
def _server_connect(self, s): """ Sets up a TCP connection to the server. """ self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.setblocking(0) self._socket.settimeout(1.0) if self.options["tcp_nodelay"]: self._socket.setsoc...
[ "def", "_server_connect", "(", "self", ",", "s", ")", ":", "self", ".", "_socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "_socket", ".", "setblocking", "(", "0", ")", "self", ...
39.478261
0.005376
def _real_set(self, obj, old, value, hint=None, setter=None): ''' Internal implementation helper to set property values. This function handles bookkeeping around noting whether values have been explicitly set, etc. Args: obj (HasProps) The object the propert...
[ "def", "_real_set", "(", "self", ",", "obj", ",", "old", ",", "value", ",", "hint", "=", "None", ",", "setter", "=", "None", ")", ":", "# Normally we want a \"no-op\" if the new value and old value are identical", "# but some hinted events are in-place. This check will allo...
40.691176
0.001411
def _set(self, schema): """Set a schema from another schema""" if isinstance(schema, CommonSchema): self._spl_type = False self._schema = schema.schema() self._style = self._default_style() else: self._spl_type = schema._spl_type self._...
[ "def", "_set", "(", "self", ",", "schema", ")", ":", "if", "isinstance", "(", "schema", ",", "CommonSchema", ")", ":", "self", ".", "_spl_type", "=", "False", "self", ".", "_schema", "=", "schema", ".", "schema", "(", ")", "self", ".", "_style", "=",...
37.4
0.005222
def predict(self, X, raw_score=False, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs): """Docstring is inherited from the LGBMModel.""" result = self.predict_proba(X, raw_score, num_iteration, pred_leaf, pred_contrib, **kwargs) ...
[ "def", "predict", "(", "self", ",", "X", ",", "raw_score", "=", "False", ",", "num_iteration", "=", "None", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "predict_proba...
50.7
0.005814
def list_listeners(self, retrieve_all=True, **_params): """Fetches a list of all lbaas_listeners for a project.""" return self.list('listeners', self.lbaas_listeners_path, retrieve_all, **_params)
[ "def", "list_listeners", "(", "self", ",", "retrieve_all", "=", "True", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "list", "(", "'listeners'", ",", "self", ".", "lbaas_listeners_path", ",", "retrieve_all", ",", "*", "*", "_params", ")" ]
58.5
0.008439
def delete_project(self, project): """ Called when project is deleted. """ pid = project.pid # project deleted ds_project = self.get_project(pid) if ds_project is not None: self._delete_project(pid) return
[ "def", "delete_project", "(", "self", ",", "project", ")", ":", "pid", "=", "project", ".", "pid", "# project deleted", "ds_project", "=", "self", ".", "get_project", "(", "pid", ")", "if", "ds_project", "is", "not", "None", ":", "self", ".", "_delete_proj...
23.454545
0.007463
def setup_signals(self, ): """Connect the signals with the slots to make the ui functional :returns: None :rtype: None :raises: None """ self.duplicate_tb.clicked.connect(self.duplicate) self.delete_tb.clicked.connect(self.delete) self.load_tb.clicked.con...
[ "def", "setup_signals", "(", "self", ",", ")", ":", "self", ".", "duplicate_tb", ".", "clicked", ".", "connect", "(", "self", ".", "duplicate", ")", "self", ".", "delete_tb", ".", "clicked", ".", "connect", "(", "self", ".", "delete", ")", "self", ".",...
46.647059
0.004944
def allowed_image(self, module_id): """Given a module id, determine whether the image is allowed to be built. """ shutit_global.shutit_global_object.yield_to_draw() self.log("In allowed_image: " + module_id,level=logging.DEBUG) cfg = self.cfg if self.build['ignoreimage']: self.log("ignoreimage == true, r...
[ "def", "allowed_image", "(", "self", ",", "module_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "log", "(", "\"In allowed_image: \"", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")",...
47.055556
0.030093
def _get_ordering(son): """Helper function to extract formatted ordering from dict. """ def fmt(field, direction): return '{0}{1}'.format({-1: '-', 1: '+'}[direction], field) if '$orderby' in son: return ', '.join(fmt(f, d) for f, d in son['$orderby'].items())
[ "def", "_get_ordering", "(", "son", ")", ":", "def", "fmt", "(", "field", ",", "direction", ")", ":", "return", "'{0}{1}'", ".", "format", "(", "{", "-", "1", ":", "'-'", ",", "1", ":", "'+'", "}", "[", "direction", "]", ",", "field", ")", "if", ...
35.75
0.003413
def relaxNGValidatePushElement(self, ctxt, elem): """Push a new element start on the RelaxNG validation stack. """ if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlRelaxNGValidatePushElemen...
[ "def", "relaxNGValidatePushElement", "(", "self", ",", "ctxt", ",", "elem", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "if", "elem", "is", "None", ":", "elem__o", "=", "None", "e...
45
0.019074
def nonlinear_odr(x, y, dx, dy, func, params_init, **kwargs): """Perform a non-linear orthogonal distance regression, return the results as ErrorValue() instances. Inputs: x: one-dimensional numpy array of the independent variable y: one-dimensional numpy array of the dependent variable ...
[ "def", "nonlinear_odr", "(", "x", ",", "y", ",", "dx", ",", "dy", ",", "func", ",", "params_init", ",", "*", "*", "kwargs", ")", ":", "odrmodel", "=", "odr", ".", "Model", "(", "lambda", "pars", ",", "x", ":", "func", "(", "x", ",", "*", "pars"...
47.15625
0.008439
async def call(self, methname, *args, **kwargs): ''' Call a remote method by name. Args: methname (str): The name of the remote method. *args: Arguments to the method call. **kwargs: Keyword arguments to the method call. Most use cases will likely us...
[ "async", "def", "call", "(", "self", ",", "methname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "todo", "=", "(", "methname", ",", "args", ",", "kwargs", ")", "return", "await", "self", ".", "task", "(", "todo", ")" ]
31.388889
0.003436
def bank_chisq_from_filters(tmplt_snr, tmplt_norm, bank_snrs, bank_norms, tmplt_bank_matches, indices=None): """ This function calculates and returns a TimeSeries object containing the bank veto calculated over a segment. Parameters ---------- tmplt_snr: TimeSeries The SNR time seri...
[ "def", "bank_chisq_from_filters", "(", "tmplt_snr", ",", "tmplt_norm", ",", "bank_snrs", ",", "bank_norms", ",", "tmplt_bank_matches", ",", "indices", "=", "None", ")", ":", "if", "indices", "is", "not", "None", ":", "tmplt_snr", "=", "Array", "(", "tmplt_snr"...
39.030769
0.001153
def receivetime_delay(self, tid, days, session): '''taobao.trade.receivetime.delay 延长交易收货时间 延长交易收货时间''' request = TOPRequest('taobao.trade.receivetime.delay') request['tid'] = tid request['days'] = days self.create(self.execute(request, session)['trade']) ...
[ "def", "receivetime_delay", "(", "self", ",", "tid", ",", "days", ",", "session", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.trade.receivetime.delay'", ")", "request", "[", "'tid'", "]", "=", "tid", "request", "[", "'days'", "]", "=", "days", "s...
36
0.009036
def process(self, event): """ event.event_type 'modified' | 'created' | 'moved' | 'deleted' event.is_directory True | False event.src_path path/to/observed/file """ uid = str(uuid.uuid4()) hostname = os.environ.get('VENT_HOST') ...
[ "def", "process", "(", "self", ",", "event", ")", ":", "uid", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "hostname", "=", "os", ".", "environ", ".", "get", "(", "'VENT_HOST'", ")", "if", "not", "hostname", ":", "hostname", "=", "''", "...
44.316327
0.000676
def _input_as_paths(self, data): """ Return data as a space delimited string with each path quoted data: paths or filenames, most likely as a list of strings """ return self._command_delimiter.join( map(str, map(self._input_as_path, data)))
[ "def", "_input_as_paths", "(", "self", ",", "data", ")", ":", "return", "self", ".", "_command_delimiter", ".", "join", "(", "map", "(", "str", ",", "map", "(", "self", ".", "_input_as_path", ",", "data", ")", ")", ")" ]
32.777778
0.006601
def _detect_delimiter(self): """ Detects the field delimiter in the sample data. """ candidate_value = ',' candidate_count = 0 for delimiter in UniversalCsvReader.delimiters: count = self._sample.count(delimiter) if count > candidate_count: ...
[ "def", "_detect_delimiter", "(", "self", ")", ":", "candidate_value", "=", "','", "candidate_count", "=", "0", "for", "delimiter", "in", "UniversalCsvReader", ".", "delimiters", ":", "count", "=", "self", ".", "_sample", ".", "count", "(", "delimiter", ")", ...
34.769231
0.00431
def new_log_files(self, name, redirect_output=True): """Generate partially randomized filenames for log files. Args: name (str): descriptive string for this log file. redirect_output (bool): True if files should be generated for logging stdout and stderr and fals...
[ "def", "new_log_files", "(", "self", ",", "name", ",", "redirect_output", "=", "True", ")", ":", "if", "redirect_output", "is", "None", ":", "redirect_output", "=", "self", ".", "_ray_params", ".", "redirect_output", "if", "not", "redirect_output", ":", "retur...
45.633333
0.001431
def from_clause(cls, clause): """ Factory method """ [_, field, operator, val] = clause return cls(field, operator, resolve(val))
[ "def", "from_clause", "(", "cls", ",", "clause", ")", ":", "[", "_", ",", "field", ",", "operator", ",", "val", "]", "=", "clause", "return", "cls", "(", "field", ",", "operator", ",", "resolve", "(", "val", ")", ")" ]
37.5
0.013072
def roll50(msg): """Roll angle, BDS 5,0 message Args: msg (String): 28 bytes hexadecimal message (BDS50) string Returns: float: angle in degrees, negative->left wing down, positive->right wing down """ d = hex2bin(data(msg)) if d[0] == '0': return None ...
[ "def", "roll50", "(", "msg", ")", ":", "d", "=", "hex2bin", "(", "data", "(", "msg", ")", ")", "if", "d", "[", "0", "]", "==", "'0'", ":", "return", "None", "sign", "=", "int", "(", "d", "[", "1", "]", ")", "# 1 -> left wing down", "value", "="...
21.173913
0.001965
def _save(self, data): """ Take the data from a dict and commit them to appropriate attributes. """ self.state = data.get('state') self.created = dt_time(data.get('created')) self.updated = dt_time(data.get('updated'))
[ "def", "_save", "(", "self", ",", "data", ")", ":", "self", ".", "state", "=", "data", ".", "get", "(", "'state'", ")", "self", ".", "created", "=", "dt_time", "(", "data", ".", "get", "(", "'created'", ")", ")", "self", ".", "updated", "=", "dt_...
37.142857
0.007519
def cli(env, sortby, columns, datacenter, username, storage_type): """List block storage.""" block_manager = SoftLayer.BlockStorageManager(env.client) block_volumes = block_manager.list_block_volumes(datacenter=datacenter, username=username, ...
[ "def", "cli", "(", "env", ",", "sortby", ",", "columns", ",", "datacenter", ",", "username", ",", "storage_type", ")", ":", "block_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "block_volumes", "=", "block_manager", ...
43.375
0.00141
def directory_copy(self, source, destination, flags): """Recursively copies a directory from one guest location to another. in source of type str The path to the directory to copy (in the guest). Guest path style. in destination of type str The path to the target direc...
[ "def", "directory_copy", "(", "self", ",", "source", ",", "destination", ",", "flags", ")", ":", "if", "not", "isinstance", "(", "source", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"source can only be an instance of type basestring\"", ")", "if", ...
43.971429
0.005086