text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def trim_dense(M, n_std=3, s_min=None, s_max=None): """By default, return a matrix stripped of component vectors whose sparsity (i.e. total contact count on a single column or row) deviates more than specified number of standard deviations from the mean. Boolean variables s_min and s_max act as abso...
[ "def", "trim_dense", "(", "M", ",", "n_std", "=", "3", ",", "s_min", "=", "None", ",", "s_max", "=", "None", ")", ":", "M", "=", "np", ".", "array", "(", "M", ")", "sparsity", "=", "M", ".", "sum", "(", "axis", "=", "1", ")", "mean", "=", "...
32.818182
15.318182
def stem(self, text): """Stem a text string to its common stem form.""" normalizedText = TextNormalizer.normalize_text(text) words = normalizedText.split(' ') stems = [] for word in words: stems.append(self.stem_word(word)) return ' '.join(stems)
[ "def", "stem", "(", "self", ",", "text", ")", ":", "normalizedText", "=", "TextNormalizer", ".", "normalize_text", "(", "text", ")", "words", "=", "normalizedText", ".", "split", "(", "' '", ")", "stems", "=", "[", "]", "for", "word", "in", "words", ":...
27.181818
19.272727
def split(y, top_db=60, ref=np.max, frame_length=2048, hop_length=512): '''Split an audio signal into non-silent intervals. Parameters ---------- y : np.ndarray, shape=(n,) or (2, n) An audio signal top_db : number > 0 The threshold (in decibels) below reference to consider as ...
[ "def", "split", "(", "y", ",", "top_db", "=", "60", ",", "ref", "=", "np", ".", "max", ",", "frame_length", "=", "2048", ",", "hop_length", "=", "512", ")", ":", "non_silent", "=", "_signal_to_frame_nonsilent", "(", "y", ",", "frame_length", "=", "fram...
31.180328
22.065574
def candidate_priority(candidate_component, candidate_type, local_pref=65535): """ See RFC 5245 - 4.1.2.1. Recommended Formula """ if candidate_type == 'host': type_pref = 126 elif candidate_type == 'prflx': type_pref = 110 elif candidate_type == 'srflx': type_pref = 100 ...
[ "def", "candidate_priority", "(", "candidate_component", ",", "candidate_type", ",", "local_pref", "=", "65535", ")", ":", "if", "candidate_type", "==", "'host'", ":", "type_pref", "=", "126", "elif", "candidate_type", "==", "'prflx'", ":", "type_pref", "=", "11...
28.125
13.375
def _find_boundary_vars(self, ds, refresh=False): ''' Returns dictionary of boundary variables mapping the variable instance to the name of the variable acting as a boundary variable. :param netCDF4.Dataset ds: An open netCDF dataset :param bool refresh: if refresh is set to Tru...
[ "def", "_find_boundary_vars", "(", "self", ",", "ds", ",", "refresh", "=", "False", ")", ":", "if", "self", ".", "_boundary_vars", ".", "get", "(", "ds", ",", "None", ")", "and", "refresh", "is", "False", ":", "return", "self", ".", "_boundary_vars", "...
40.647059
24.176471
def detect_django_settings(): """ Automatically try to discover Django settings files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*settings.py'): full = os.path.join...
[ "def", "detect_django_settings", "(", ")", ":", "matches", "=", "[", "]", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "os", ".", "getcwd", "(", ")", ")", ":", "for", "filename", "in", "fnmatch", ".", "filter", "(",...
36.166667
16.944444
def write(self, out): """Used in constructing an outgoing packet""" out.write_string(self.cpu, len(self.cpu)) out.write_string(self.os, len(self.os))
[ "def", "write", "(", "self", ",", "out", ")", ":", "out", ".", "write_string", "(", "self", ".", "cpu", ",", "len", "(", "self", ".", "cpu", ")", ")", "out", ".", "write_string", "(", "self", ".", "os", ",", "len", "(", "self", ".", "os", ")", ...
42.5
8.75
def get_node_type(self, node, parent=None): """If node is a document, the type is page. If node is a binder with no parent, the type is book. If node is a translucent binder, the type is either chapters (only contain pages) or unit (contains at least one translucent binder). """ ...
[ "def", "get_node_type", "(", "self", ",", "node", ",", "parent", "=", "None", ")", ":", "if", "isinstance", "(", "node", ",", "CompositeDocument", ")", ":", "return", "'composite-page'", "elif", "isinstance", "(", "node", ",", "(", "Document", ",", "Docume...
43.3125
13.9375
def _verify_method(self): """Verify that a method may be doubled. Verifies that the target object has a method matching the name the user is attempting to double. :raise: ``VerifyingDoubleError`` if no matching method is found. """ class_level = self._target.is_class_o...
[ "def", "_verify_method", "(", "self", ")", ":", "class_level", "=", "self", ".", "_target", ".", "is_class_or_module", "(", ")", "verify_method", "(", "self", ".", "_target", ",", "self", ".", "_method_name", ",", "class_level", "=", "class_level", ")" ]
33.333333
28.5
def enclosing_box(boxes): """ Finds a new box that exactly encloses all the given boxes. :param boxes: Array of Box objects :return: Box object that encloses all boxes """ x = max(0, min([box.x for box in boxes])) y = max(0, min([box.y for box in boxes])) ...
[ "def", "enclosing_box", "(", "boxes", ")", ":", "x", "=", "max", "(", "0", ",", "min", "(", "[", "box", ".", "x", "for", "box", "in", "boxes", "]", ")", ")", "y", "=", "max", "(", "0", ",", "min", "(", "[", "box", ".", "y", "for", "box", ...
38.333333
12.333333
def dataframe_from_excel(path, sheetname=0, header=0, skiprows=None): # , parse_dates=False): """Thin wrapper for pandas.io.excel.read_excel() that accepts a file path and sheet index/name Arguments: path (str): file or folder to retrieve CSV files and `pandas.DataFrame`s from ext (str): file name...
[ "def", "dataframe_from_excel", "(", "path", ",", "sheetname", "=", "0", ",", "header", "=", "0", ",", "skiprows", "=", "None", ")", ":", "# , parse_dates=False):", "sheetname", "=", "sheetname", "or", "0", "if", "isinstance", "(", "sheetname", ",", "(", "b...
47.36
23.64
def extract_blocks(ubi): """Get a list of UBI block objects from file Arguments:. Obj:ubi -- UBI object. Returns: Dict -- Of block objects keyed by PEB number. """ blocks = {} ubi.file.seek(ubi.file.start_offset) peb_count = 0 cur_offset = 0 bad_blocks = [] # r...
[ "def", "extract_blocks", "(", "ubi", ")", ":", "blocks", "=", "{", "}", "ubi", ".", "file", ".", "seek", "(", "ubi", ".", "file", ".", "start_offset", ")", "peb_count", "=", "0", "cur_offset", "=", "0", "bad_blocks", "=", "[", "]", "# range instead of ...
34.431034
22.586207
def get_median_area(self, mag, rake): """ The values are a function of magnitude. """ # strike slip length = 10.0 ** (-2.57 + 0.62 * mag) seis_wid = 20.0 # estimate area based on length if length < seis_wid: return length ** 2. else: ...
[ "def", "get_median_area", "(", "self", ",", "mag", ",", "rake", ")", ":", "# strike slip", "length", "=", "10.0", "**", "(", "-", "2.57", "+", "0.62", "*", "mag", ")", "seis_wid", "=", "20.0", "# estimate area based on length", "if", "length", "<", "seis_w...
26.384615
11
def comment_marker(self, value): """ Setter for **self.__comment_marker** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( ...
[ "def", "comment_marker", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "unicode", ",", "\"'{0}' attribute: '{1}' type is not 'unicode'!\"", ".", "format", "(", "\"comment_marker\"", ",", ...
31.583333
15.75
def _check_params(self): """Check validity of parameters and raise ValueError if not valid. """ self.n_estimators = int(self.n_estimators) if self.n_estimators <= 0: raise ValueError("n_estimators must be greater than 0 but " "was %r" % self.n_estimators)...
[ "def", "_check_params", "(", "self", ")", ":", "self", ".", "n_estimators", "=", "int", "(", "self", ".", "n_estimators", ")", "if", "self", ".", "n_estimators", "<=", "0", ":", "raise", "ValueError", "(", "\"n_estimators must be greater than 0 but \"", "\"was %...
42.416667
20.861111
def list_extensions(): ''' List up available extensions. Note: It may not work on some platforms/environments since it depends on the directory structure of the namespace packages. Returns: list of str Names of available extensions. ''' import nnabla_ext.cpu from o...
[ "def", "list_extensions", "(", ")", ":", "import", "nnabla_ext", ".", "cpu", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "realpath", "from", "os", "import", "listdir", "ext_dir", "=", "realpath", "(", "(", "join", "(", "dirname", "(...
27.470588
23
def _sync(self): """ Synchronize the cached data with the underlyind database. Uses an internal transaction counter and compares to the checkpoint_operations and checkpoint_timeout paramters to determine whether to persist the memory store. In this implementation, this method w...
[ "def", "_sync", "(", "self", ")", ":", "if", "(", "self", ".", "_opcount", ">", "self", ".", "checkpoint_operations", "or", "datetime", ".", "now", "(", ")", ">", "self", ".", "_last_sync", "+", "self", ".", "checkpoint_timeout", ")", ":", "self", ".",...
43.470588
23.823529
def id_to_name(config, short_name): """ Returns the provider :doc:`config` key based on it's ``id`` value. :param dict config: :doc:`config`. :param id: Value of the id parameter in the :ref:`config` to search for. """ for k, v in list(config.items()): if v.get('id') =...
[ "def", "id_to_name", "(", "config", ",", "short_name", ")", ":", "for", "k", ",", "v", "in", "list", "(", "config", ".", "items", "(", ")", ")", ":", "if", "v", ".", "get", "(", "'id'", ")", "==", "short_name", ":", "return", "k", "raise", "Excep...
25.588235
21.470588
def add( self, years=0, months=0, weeks=0, days=0, hours=0, minutes=0, seconds=0, microseconds=0, ): # type: (int, int, int, int, int, int, int) -> DateTime """ Add a duration to the instance. If we're adding units of ...
[ "def", "add", "(", "self", ",", "years", "=", "0", ",", "months", "=", "0", ",", "weeks", "=", "0", ",", "days", "=", "0", ",", "hours", "=", "0", ",", "minutes", "=", "0", ",", "seconds", "=", "0", ",", "microseconds", "=", "0", ",", ")", ...
23.951807
18.337349
def dcc_event(regexp, callback=None, iotype='in', venusian_category='irc3.dcc'): """Work like :class:`~irc3.dec.event` but occurs during DCC CHATs""" return event(regexp, callback=callback, iotype='dcc_' + iotype, venusian_category=venusian_category)
[ "def", "dcc_event", "(", "regexp", ",", "callback", "=", "None", ",", "iotype", "=", "'in'", ",", "venusian_category", "=", "'irc3.dcc'", ")", ":", "return", "event", "(", "regexp", ",", "callback", "=", "callback", ",", "iotype", "=", "'dcc_'", "+", "io...
57
10.6
def _prepare(self): """ Setup initial requirements for daemon run. """ super(TaskRunner, self)._prepare() self._setup_root_plugins() # set the default x-window display for non-mac systems if not sys.platform.lower().startswith('darwin'): if not 'DISPLAY'...
[ "def", "_prepare", "(", "self", ")", ":", "super", "(", "TaskRunner", ",", "self", ")", ".", "_prepare", "(", ")", "self", ".", "_setup_root_plugins", "(", ")", "# set the default x-window display for non-mac systems", "if", "not", "sys", ".", "platform", ".", ...
33.818182
14.272727
def confirm_project_avatar(self, project, cropping_properties): """Confirm the temporary avatar image previously uploaded with the specified cropping. After a successful registry with :py:meth:`create_temp_project_avatar`, use this method to confirm the avatar for use. The final avatar can be a...
[ "def", "confirm_project_avatar", "(", "self", ",", "project", ",", "cropping_properties", ")", ":", "data", "=", "cropping_properties", "url", "=", "self", ".", "_get_url", "(", "'project/'", "+", "project", "+", "'/avatar'", ")", "r", "=", "self", ".", "_se...
52.470588
31.117647
def mason_morrow(target, throat_perimeter='throat.perimeter', throat_area='throat.area'): r""" Mason and Morrow relate the capillary pressure to the shaped factor in a similar way to Mortensen but for triangles. References ---------- Mason, G. and Morrow, N.R.. Capillary behavi...
[ "def", "mason_morrow", "(", "target", ",", "throat_perimeter", "=", "'throat.perimeter'", ",", "throat_area", "=", "'throat.area'", ")", ":", "# Only apply to throats with an area", "ts", "=", "target", ".", "throats", "(", ")", "[", "target", "[", "throat_area", ...
35.315789
16.631579
def build_arg_parser(): """ Build an argument parser using argparse. Use it when python version is 2.7 or later. """ parser = argparse.ArgumentParser(description="Smatch calculator -- arguments") parser.add_argument('-f', nargs=2, required=True, type=argparse.FileType('r'), ...
[ "def", "build_arg_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Smatch calculator -- arguments\"", ")", "parser", ".", "add_argument", "(", "'-f'", ",", "nargs", "=", "2", ",", "required", "=", "True", ",...
66.32
38.56
def _error_handler(data, unique_id): """Called when data first received :param data: Received data :param unique_id: Unique id :return: True if error present """ if data.get('statusCode') == 'FAILURE': logger.error('[Subscription: %s] %s: %s' % (unique_id, da...
[ "def", "_error_handler", "(", "data", ",", "unique_id", ")", ":", "if", "data", ".", "get", "(", "'statusCode'", ")", "==", "'FAILURE'", ":", "logger", ".", "error", "(", "'[Subscription: %s] %s: %s'", "%", "(", "unique_id", ",", "data", ".", "get", "(", ...
46.933333
19.4
def from_data( name, coors, ngroups, conns, mat_ids, descs, igs = None ): """ Create a mesh from mesh data. """ if igs is None: igs = range( len( conns ) ) mesh = Mesh(name) mesh._set_data(coors = coors, ngroups = ngroups, ...
[ "def", "from_data", "(", "name", ",", "coors", ",", "ngroups", ",", "conns", ",", "mat_ids", ",", "descs", ",", "igs", "=", "None", ")", ":", "if", "igs", "is", "None", ":", "igs", "=", "range", "(", "len", "(", "conns", ")", ")", "mesh", "=", ...
37.214286
11.357143
def _flush(self): """ Flush the write buffers of the stream if applicable. In write mode, send the buffer content to the cloud object. """ # Flush buffer to specified range buffer = self._get_buffer() start = self._buffer_size * (self._seek - 1) end = sta...
[ "def", "_flush", "(", "self", ")", ":", "# Flush buffer to specified range", "buffer", "=", "self", ".", "_get_buffer", "(", ")", "start", "=", "self", ".", "_buffer_size", "*", "(", "self", ".", "_seek", "-", "1", ")", "end", "=", "start", "+", "len", ...
35.933333
15.4
def _write(self, session, openFile, replaceParamFile): """ Precipitation File Write to File Method """ # Retrieve the events associated with this PrecipFile events = self.precipEvents # Write each event to file for event in events: openFile.write('EVE...
[ "def", "_write", "(", "self", ",", "session", ",", "openFile", ",", "replaceParamFile", ")", ":", "# Retrieve the events associated with this PrecipFile", "events", "=", "self", ".", "precipEvents", "# Write each event to file", "for", "event", "in", "events", ":", "o...
43.666667
22.619048
def selectByIdx(self, rowIdxs): 'Select given row indexes, without progress bar.' self.select((self.rows[i] for i in rowIdxs), progress=False)
[ "def", "selectByIdx", "(", "self", ",", "rowIdxs", ")", ":", "self", ".", "select", "(", "(", "self", ".", "rows", "[", "i", "]", "for", "i", "in", "rowIdxs", ")", ",", "progress", "=", "False", ")" ]
52
18
def send_raw(self, string): """Send raw string to the server. The string will be padded with appropriate CR LF. If too many messages are sent, this will call :func:`time.sleep` until it is allowed to send messages again. :param string: the raw string to send :type strin...
[ "def", "send_raw", "(", "self", ",", "string", ")", ":", "waittime", "=", "self", ".", "get_waittime", "(", ")", "if", "waittime", ":", "log", ".", "debug", "(", "'Sent too many messages. Waiting %s seconds'", ",", "waittime", ")", "time", ".", "sleep", "(",...
38.85
15.85
def _convert_angle_to_pypot(angle, joint, **kwargs): """Converts an angle to a PyPot-compatible format""" angle_deg = (angle * 180 / np.pi) if joint["orientation-convention"] == "indirect": angle_deg = -1 * angle_deg # UGLY if joint["name"].startswith("l_shoulder_x"): angle_deg = -...
[ "def", "_convert_angle_to_pypot", "(", "angle", ",", "joint", ",", "*", "*", "kwargs", ")", ":", "angle_deg", "=", "(", "angle", "*", "180", "/", "np", ".", "pi", ")", "if", "joint", "[", "\"orientation-convention\"", "]", "==", "\"indirect\"", ":", "ang...
27.928571
18.642857
def build_blueprint(self, url_prefix=''): """Build a blueprint that contains the endpoints for callback URLs of the current subscriber. Only call this once per instance. Arguments: - url_prefix; this allows you to prefix the callback URLs in your app. """ self.blueprint_name, s...
[ "def", "build_blueprint", "(", "self", ",", "url_prefix", "=", "''", ")", ":", "self", ".", "blueprint_name", ",", "self", ".", "blueprint", "=", "build_blueprint", "(", "self", ",", "url_prefix", ")", "return", "self", ".", "blueprint" ]
43.444444
22.777778
def increment_frame(self): """Increment a frame of the animation.""" if self.current_frame < len(self.images): self.current_frame += 1 if self.current_frame >= len(self.images): # Wrap back to the beginning of the animation if should_repeat is true. ...
[ "def", "increment_frame", "(", "self", ")", ":", "if", "self", ".", "current_frame", "<", "len", "(", "self", ".", "images", ")", ":", "self", ".", "current_frame", "+=", "1", "if", "self", ".", "current_frame", ">=", "len", "(", "self", ".", "images",...
45.176471
18.764706
def close(self): """ Close outputs of process. """ self.process.stdout.close() self.process.stderr.close() self.running = False
[ "def", "close", "(", "self", ")", ":", "self", ".", "process", ".", "stdout", ".", "close", "(", ")", "self", ".", "process", ".", "stderr", ".", "close", "(", ")", "self", ".", "running", "=", "False" ]
24.142857
7.571429
def _str_sid(self): 'Return a nicely formatted representation string' sub_auths = "-".join([str(sub) for sub in self.sub_authorities]) return f'S-{self.revision_number}-{self.authority}-{sub_auths}'
[ "def", "_str_sid", "(", "self", ")", ":", "sub_auths", "=", "\"-\"", ".", "join", "(", "[", "str", "(", "sub", ")", "for", "sub", "in", "self", ".", "sub_authorities", "]", ")", "return", "f'S-{self.revision_number}-{self.authority}-{sub_auths}'" ]
51.75
22.25
def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key)
[ "def", "set_key_state", "(", "self", ",", "key", ",", "state", ")", ":", "key", ".", "state", "=", "state", "self", ".", "renderer", ".", "draw_key", "(", "self", ".", "surface", ",", "key", ")" ]
30.75
9.5
def _calculate_gap(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, n_clusters: int) -> Tuple[float, int]: """ Calculate the gap value of the given data, n_refs, and number of clusters. Return the resutling gap value and n_clusters """ # Holder for reference dispersion resu...
[ "def", "_calculate_gap", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "n_clusters", ":", "int", ")", "->", "Tuple", "[", "float", ",", "int", "]", ":", "# Holder f...
51.833333
30.833333
def define_server( self, basename, server_tpl, server_tpl_rev, instance_type, ssh_key_name, tags=None, availability_zone=None, security_groups=None, **provider_extras ): """ Creates a new server instance. This call blocks until the server is creat...
[ "def", "define_server", "(", "self", ",", "basename", ",", "server_tpl", ",", "server_tpl_rev", ",", "instance_type", ",", "ssh_key_name", ",", "tags", "=", "None", ",", "availability_zone", "=", "None", ",", "security_groups", "=", "None", ",", "*", "*", "p...
37.592593
22.244444
def _funm_svd(a, func): """Apply real scalar function to singular values of a matrix. Args: a (array_like): (N, N) Matrix at which to evaluate the function. func (callable): Callable object that evaluates a scalar function f. Returns: ndarray: funm (N, N) Value of the matrix functi...
[ "def", "_funm_svd", "(", "a", ",", "func", ")", ":", "U", ",", "s", ",", "Vh", "=", "la", ".", "svd", "(", "a", ",", "lapack_driver", "=", "'gesvd'", ")", "S", "=", "np", ".", "diag", "(", "func", "(", "s", ")", ")", "return", "U", ".", "do...
33
22.142857
def create(cls, event): """Create a new Release model.""" # Check if the release has already been received release_id = event.payload['release']['id'] existing_release = Release.query.filter_by( release_id=release_id, ).first() if existing_release: ...
[ "def", "create", "(", "cls", ",", "event", ")", ":", "# Check if the release has already been received", "release_id", "=", "event", ".", "payload", "[", "'release'", "]", "[", "'id'", "]", "existing_release", "=", "Release", ".", "query", ".", "filter_by", "(",...
37.228571
14.4
def reassign_ids(elem): """ Recurses over all Table elements below elem whose next_id attributes are not None, and uses the .get_next_id() method of each of those Tables to generate and assign new IDs to their rows. The modifications are recorded, and finally all ID attributes in all rows of all tables are updat...
[ "def", "reassign_ids", "(", "elem", ")", ":", "mapping", "=", "{", "}", "for", "tbl", "in", "elem", ".", "getElementsByTagName", "(", "ligolw", ".", "Table", ".", "tagName", ")", ":", "if", "tbl", ".", "next_id", "is", "not", "None", ":", "tbl", ".",...
37.9375
23
def catalog(self): """Create MOC from catalog of coordinates. This command requires that the Healpy and Astropy libraries be available. It attempts to load the given catalog, and merges it with the running MOC. The name of an ASCII catalog file should be given. The file ...
[ "def", "catalog", "(", "self", ")", ":", "from", ".", "catalog", "import", "catalog_to_moc", ",", "read_ascii_catalog", "filename", "=", "self", ".", "params", ".", "pop", "(", ")", "order", "=", "12", "radius", "=", "3600", "unit", "=", "None", "format_...
33.028169
18.816901
def action_create(self, courseid, taskid, path): """ Delete a file or a directory """ # the path is given by the user. Let's normalize it path = path.strip() if not path.startswith("/"): path = "/" + path want_directory = path.endswith("/") wanted_path = sel...
[ "def", "action_create", "(", "self", ",", "courseid", ",", "taskid", ",", "path", ")", ":", "# the path is given by the user. Let's normalize it", "path", "=", "path", ".", "strip", "(", ")", "if", "not", "path", ".", "startswith", "(", "\"/\"", ")", ":", "p...
38
18.631579
def getNeighbouringDevices(self): """gets the neighboring devices' extended address to compute the DUT extended address automatically Returns: A list including extended address of neighboring routers, parent as well as children """ print '%s call getNe...
[ "def", "getNeighbouringDevices", "(", "self", ")", ":", "print", "'%s call getNeighbouringDevices'", "%", "self", ".", "port", "neighbourList", "=", "[", "]", "# get parent info", "parentAddr", "=", "self", ".", "getParentAddress", "(", ")", "if", "parentAddr", "!...
34.6
15.366667
def setup(self, name_filters=['*.py', '*.pyw'], show_all=False, single_click_to_open=False): """Setup tree widget""" self.setup_view() self.set_name_filters(name_filters) self.show_all = show_all self.single_click_to_open = single_click_to_open ...
[ "def", "setup", "(", "self", ",", "name_filters", "=", "[", "'*.py'", ",", "'*.pyw'", "]", ",", "show_all", "=", "False", ",", "single_click_to_open", "=", "False", ")", ":", "self", ".", "setup_view", "(", ")", "self", ".", "set_name_filters", "(", "nam...
35.583333
14.583333
def order(self): """Produce a flatten list of the partition, ordered by classes """ return [x.val for theclass in self.classes for x in theclass.items]
[ "def", "order", "(", "self", ")", ":", "return", "[", "x", ".", "val", "for", "theclass", "in", "self", ".", "classes", "for", "x", "in", "theclass", ".", "items", "]" ]
43
14.75
def _max_recursion_depth(obj): ''' Estimate recursion depth, which is defined as the number of nodes in a tree ''' neurites = obj.neurites if hasattr(obj, 'neurites') else [obj] return max(sum(1 for _ in neu.iter_sections()) for neu in neurites)
[ "def", "_max_recursion_depth", "(", "obj", ")", ":", "neurites", "=", "obj", ".", "neurites", "if", "hasattr", "(", "obj", ",", "'neurites'", ")", "else", "[", "obj", "]", "return", "max", "(", "sum", "(", "1", "for", "_", "in", "neu", ".", "iter_sec...
42.833333
30.5
def print_task_output(batch_client, job_id, task_ids, encoding=None): """Prints the stdout and stderr for each task specified. Originally in azure-batch-samples.Python.Batch.common.helpers :param batch_client: The batch client to use. :type batch_client: `batchserviceclient.BatchServiceClient` :par...
[ "def", "print_task_output", "(", "batch_client", ",", "job_id", ",", "task_ids", ",", "encoding", "=", "None", ")", ":", "for", "task_id", "in", "task_ids", ":", "file_text", "=", "read_task_file_as_string", "(", "batch_client", ",", "job_id", ",", "task_id", ...
34.939394
15.818182
def acquaint_and_shift(parts: Tuple[List[ops.Qid], List[ops.Qid]], layers: Layers, acquaintance_size: Optional[int], swap_gate: ops.Gate, mapping: Dict[ops.Qid, int]): """Acquaints and shifts a pair of lists of qubits. The f...
[ "def", "acquaint_and_shift", "(", "parts", ":", "Tuple", "[", "List", "[", "ops", ".", "Qid", "]", ",", "List", "[", "ops", ".", "Qid", "]", "]", ",", "layers", ":", "Layers", ",", "acquaintance_size", ":", "Optional", "[", "int", "]", ",", "swap_gat...
41.121212
15.151515
def encode_images_as_png(images): """Yield images encoded as pngs.""" if tf.executing_eagerly(): for image in images: yield tf.image.encode_png(image).numpy() else: (height, width, channels) = images[0].shape with tf.Graph().as_default(): image_t = tf.placeholder(dtype=tf.uint8, shape=(hei...
[ "def", "encode_images_as_png", "(", "images", ")", ":", "if", "tf", ".", "executing_eagerly", "(", ")", ":", "for", "image", "in", "images", ":", "yield", "tf", ".", "image", ".", "encode_png", "(", "image", ")", ".", "numpy", "(", ")", "else", ":", ...
39.142857
14.928571
def demote(self, move: chess.Move) -> None: """Moves a variation one down in the list of variations.""" variation = self[move] i = self.variations.index(variation) if i < len(self.variations) - 1: self.variations[i + 1], self.variations[i] = self.variations[i], self.variation...
[ "def", "demote", "(", "self", ",", "move", ":", "chess", ".", "Move", ")", "->", "None", ":", "variation", "=", "self", "[", "move", "]", "i", "=", "self", ".", "variations", ".", "index", "(", "variation", ")", "if", "i", "<", "len", "(", "self"...
53.833333
12.666667
def write(self, stream, message): '''write will write a message to a stream, first checking the encoding ''' if isinstance(message, bytes): message = message.decode('utf-8') stream.write(message)
[ "def", "write", "(", "self", ",", "stream", ",", "message", ")", ":", "if", "isinstance", "(", "message", ",", "bytes", ")", ":", "message", "=", "message", ".", "decode", "(", "'utf-8'", ")", "stream", ".", "write", "(", "message", ")" ]
34.428571
9.857143
def find(self, location): """ Find the specified location in the store. @param location: The I{location} part of a URL. @type location: str @return: An input stream to the document. @rtype: StringIO """ try: content = self.store[location] ...
[ "def", "find", "(", "self", ",", "location", ")", ":", "try", ":", "content", "=", "self", ".", "store", "[", "location", "]", "return", "StringIO", "(", "content", ")", "except", ":", "reason", "=", "'location \"%s\" not in document store'", "%", "location"...
32.857143
12.142857
def _get_response_message(self, request, result, input_chat): """ Extracts the response message known a request and Update result. The request may also be the ID of the message to match. If ``request is None`` this method returns ``{id: message}``. If ``request.random_id`` is a...
[ "def", "_get_response_message", "(", "self", ",", "request", ",", "result", ",", "input_chat", ")", ":", "if", "isinstance", "(", "result", ",", "types", ".", "UpdateShort", ")", ":", "updates", "=", "[", "result", ".", "update", "]", "entities", "=", "{...
43.483871
21.193548
def _create_user(self, username, password, mail, method, uuid): """Create a new user and all initial data""" try: if method == 'Invited': config_role = self.config.group_accept_invited else: config_role = self.config.group_accept_enrolled ...
[ "def", "_create_user", "(", "self", ",", "username", ",", "password", ",", "mail", ",", "method", ",", "uuid", ")", ":", "try", ":", "if", "method", "==", "'Invited'", ":", "config_role", "=", "self", ".", "config", ".", "group_accept_invited", "else", "...
30.836364
17.563636
def _find_scalac_plugins(self, scalac_plugins, classpath): """Returns a map from plugin name to list of plugin classpath entries. The first entry in each list is the classpath entry containing the plugin metadata. The rest are the internal transitive deps of the plugin. This allows us to have in-repo ...
[ "def", "_find_scalac_plugins", "(", "self", ",", "scalac_plugins", ",", "classpath", ")", ":", "# Allow multiple flags and also comma-separated values in a single flag.", "plugin_names", "=", "{", "p", "for", "val", "in", "scalac_plugins", "for", "p", "in", "val", ".", ...
56.3
29.68
def create(self, group_type, config_file, group_name=None, region=None, profile_name=None): """ Create a Greengrass group in the given region. :param group_type: the type of group to create. Must match a `key` in the `group_types` dict :param config_file: conf...
[ "def", "create", "(", "self", ",", "group_type", ",", "config_file", ",", "group_name", "=", "None", ",", "region", "=", "None", ",", "profile_name", "=", "None", ")", ":", "logging", ".", "info", "(", "\"[begin] create command using group_types:{0}\"", ".", "...
36.444444
20.074074
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.storage.v2015_06_15.models>` * 2016-01-01: :mod:`v2016_01_01.models<azure.mgmt.storage.v2016_01_01.models>` * 2016-12-01: :mod:`v2016_12_01....
[ "def", "models", "(", "cls", ",", "api_version", "=", "DEFAULT_API_VERSION", ")", ":", "if", "api_version", "==", "'2015-06-15'", ":", "from", ".", "v2015_06_15", "import", "models", "return", "models", "elif", "api_version", "==", "'2016-01-01'", ":", "from", ...
49.027027
18.378378
def userinfo_claims(self, access_token, scope_request, claims_request): """ Return the claims for the requested parameters. """ id_token = oidc.userinfo(access_token, scope_request, claims_request) return id_token.claims
[ "def", "userinfo_claims", "(", "self", ",", "access_token", ",", "scope_request", ",", "claims_request", ")", ":", "id_token", "=", "oidc", ".", "userinfo", "(", "access_token", ",", "scope_request", ",", "claims_request", ")", "return", "id_token", ".", "claims...
60.25
19.5
def setup_configuration(config_path): """Loads the core configuration from the specified path and uses its content for further setup :param config_path: Path to the core config file """ if config_path is not None: config_path, config_file = filesystem.separate_folder_path_and_file_name(config_p...
[ "def", "setup_configuration", "(", "config_path", ")", ":", "if", "config_path", "is", "not", "None", ":", "config_path", ",", "config_file", "=", "filesystem", ".", "separate_folder_path_and_file_name", "(", "config_path", ")", "global_config", ".", "load", "(", ...
39.538462
18.692308
def _delete_record(self, identifier=None, rtype=None, name=None, content=None): """ Delete one or more DNS entries in the domain zone that match the given criteria. Args: [identifier] (str): An ID to match against DNS entry easyname IDs. [rtype] (str): A DNS rtype (e...
[ "def", "_delete_record", "(", "self", ",", "identifier", "=", "None", ",", "rtype", "=", "None", ",", "name", "=", "None", ",", "content", "=", "None", ")", ":", "success_url", "=", "self", ".", "URLS", "[", "'dns'", "]", ".", "format", "(", "self", ...
43.333333
25.066667
def assertTimeZoneEqual(self, dt, tz, msg=None): '''Fail unless ``dt``'s ``tzinfo`` attribute equals ``tz`` as determined by the '==' operator. Parameters ---------- dt : datetime tz : timezone msg : str If not provided, the :mod:`marbles.mixins` or ...
[ "def", "assertTimeZoneEqual", "(", "self", ",", "dt", ",", "tz", ",", "msg", "=", "None", ")", ":", "if", "not", "isinstance", "(", "dt", ",", "datetime", ")", ":", "raise", "TypeError", "(", "'First argument is not a datetime object'", ")", "if", "not", "...
32.12
20.28
def from_string(value): """ Parses colon-separated list of descriptor fields and returns them as a Descriptor. :param value: colon-separated descriptor fields to initialize Descriptor. :return: a newly created Descriptor. """ if value == None or len(value) == 0: ...
[ "def", "from_string", "(", "value", ")", ":", "if", "value", "==", "None", "or", "len", "(", "value", ")", "==", "0", ":", "return", "None", "tokens", "=", "value", ".", "split", "(", "\":\"", ")", "if", "len", "(", "tokens", ")", "!=", "5", ":",...
39.277778
23.722222
def parse_corant(blob): """Creates new blob entries for the given blob keys""" if 'track_seamuon' in blob.keys(): muon = blob['track_seamuon'] blob['Muon'] = Table({ 'id': np.array(muon)[:, 0].astype(int), 'pos_x': np.array(muon)[:, 1], 'pos_y': np.array(mu...
[ "def", "parse_corant", "(", "blob", ")", ":", "if", "'track_seamuon'", "in", "blob", ".", "keys", "(", ")", ":", "muon", "=", "blob", "[", "'track_seamuon'", "]", "blob", "[", "'Muon'", "]", "=", "Table", "(", "{", "'id'", ":", "np", ".", "array", ...
37.197674
15.22093
def append_text_column(self, text: str, index: int): """ Add value to the output row, width based on index """ width = self.columns[index]["width"] return f"{text:<{width}}"
[ "def", "append_text_column", "(", "self", ",", "text", ":", "str", ",", "index", ":", "int", ")", ":", "width", "=", "self", ".", "columns", "[", "index", "]", "[", "\"width\"", "]", "return", "f\"{text:<{width}}\"" ]
48.5
5.75
def combine_samples(self, md5_list, filename, type_tag): """Combine samples together. This may have various use cases the most significant involving a bunch of sample 'chunks' got uploaded and now we combine them together Args: md5_list: The list of md5s to combine, orde...
[ "def", "combine_samples", "(", "self", ",", "md5_list", ",", "filename", ",", "type_tag", ")", ":", "total_bytes", "=", "\"\"", "for", "md5", "in", "md5_list", ":", "total_bytes", "+=", "self", ".", "get_sample", "(", "md5", ")", "[", "'sample'", "]", "[...
44.611111
23.222222
def atPage(self, page, pseudopage, declarations): """ This is overriden by xhtml2pdf.context.pisaCSSBuilder """ return self.ruleset([self.selector('*')], declarations)
[ "def", "atPage", "(", "self", ",", "page", ",", "pseudopage", ",", "declarations", ")", ":", "return", "self", ".", "ruleset", "(", "[", "self", ".", "selector", "(", "'*'", ")", "]", ",", "declarations", ")" ]
39
10.6
def act(self, world_state, agent_host, current_r ): """take 1 action in response to the current world state""" obs_text = world_state.observations[-1].text obs = json.loads(obs_text) # most recent observation self.logger.debug(obs) if not u'XPos' in obs or not u'ZPos' in...
[ "def", "act", "(", "self", ",", "world_state", ",", "agent_host", ",", "current_r", ")", ":", "obs_text", "=", "world_state", ".", "observations", "[", "-", "1", "]", ".", "text", "obs", "=", "json", ".", "loads", "(", "obs_text", ")", "# most recent obs...
41.391304
22.086957
def sext(self, n): ''' Sign-extend the variable to n bits. n bits must be stricly larger than the actual number of bits, or a ValueError is thrown ''' if n <= self.nbits: raise ValueError("n must be > %d bits" % self.nbits) mba_ret = self.__new_mba(...
[ "def", "sext", "(", "self", ",", "n", ")", ":", "if", "n", "<=", "self", ".", "nbits", ":", "raise", "ValueError", "(", "\"n must be > %d bits\"", "%", "self", ".", "nbits", ")", "mba_ret", "=", "self", ".", "__new_mba", "(", "n", ")", "ret", "=", ...
31.277778
16.055556
def list_role_secrets(self, role_name, mount_point='approle'): """LIST /auth/<mount_point>/role/<role name>/secret-id :param role_name: Name of the AppRole. :type role_name: str|unicode :param mount_point: The "path" the AppRole auth backend was mounted on. Vault currently defaults to "...
[ "def", "list_role_secrets", "(", "self", ",", "role_name", ",", "mount_point", "=", "'approle'", ")", ":", "url", "=", "'/v1/auth/{mount_point}/role/{name}/secret-id'", ".", "format", "(", "mount_point", "=", "mount_point", ",", "name", "=", "role_name", ")", "ret...
41.8
17.6
def muscle_chunker(data, sample): """ Splits the muscle alignment into chunks. Each chunk is run on a separate computing core. Because the largest clusters are at the beginning of the clusters file, assigning equal clusters to each file would put all of the large cluster, that take longer to align...
[ "def", "muscle_chunker", "(", "data", ",", "sample", ")", ":", "## log our location for debugging", "LOGGER", ".", "info", "(", "\"inside muscle_chunker\"", ")", "## only chunk up denovo data, refdata has its own chunking method which ", "## makes equal size chunks, instead of uneven...
45.132075
19.283019
def get_atom_map(structure): """ Returns a dict that maps each atomic symbol to a unique integer starting from 1. Args: structure (Structure) Returns: dict """ syms = [site.specie.symbol for site in structure] unique_pot_atoms = [] [unique_pot_atoms.append(i) for i ...
[ "def", "get_atom_map", "(", "structure", ")", ":", "syms", "=", "[", "site", ".", "specie", ".", "symbol", "for", "site", "in", "structure", "]", "unique_pot_atoms", "=", "[", "]", "[", "unique_pot_atoms", ".", "append", "(", "i", ")", "for", "i", "in"...
25.611111
21.277778
def destroySingleton(cls): """ Destroys the singleton instance of this class, if one exists. """ singleton_key = '_{0}__singleton'.format(cls.__name__) singleton = getattr(cls, singleton_key, None) if singleton is not None: setattr(cls, singleton_key,...
[ "def", "destroySingleton", "(", "cls", ")", ":", "singleton_key", "=", "'_{0}__singleton'", ".", "format", "(", "cls", ".", "__name__", ")", "singleton", "=", "getattr", "(", "cls", ",", "singleton_key", ",", "None", ")", "if", "singleton", "is", "not", "N...
31.833333
14.833333
def scale_back_batch(self, bboxes_in, scores_in): """ Do scale and transform from xywh to ltrb suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox """ if bboxes_in.device == torch.device("cpu"): self.dboxes = self.dboxes.cpu() self.dboxes_xywh = self.d...
[ "def", "scale_back_batch", "(", "self", ",", "bboxes_in", ",", "scores_in", ")", ":", "if", "bboxes_in", ".", "device", "==", "torch", ".", "device", "(", "\"cpu\"", ")", ":", "self", ".", "dboxes", "=", "self", ".", "dboxes", ".", "cpu", "(", ")", "...
42.567568
21.054054
def within_radius_sphere(self, x, y, radius): """ Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius_sphere(1, 2, 50) """ return QueryExpression({ self : {'$within' : { '$centerSphere' : [[x, y], radius...
[ "def", "within_radius_sphere", "(", "self", ",", "x", ",", "y", ",", "radius", ")", ":", "return", "QueryExpression", "(", "{", "self", ":", "{", "'$within'", ":", "{", "'$centerSphere'", ":", "[", "[", "x", ",", "y", "]", ",", "radius", "]", ",", ...
31.454545
15.454545
def validate_results(self, results, checks=None): ''' Valdiate results from the Anisble Run. ''' results['status'] = 'PASS' failed_hosts = [] ################################################### # First validation is to make sure connectivity to # all the ...
[ "def", "validate_results", "(", "self", ",", "results", ",", "checks", "=", "None", ")", ":", "results", "[", "'status'", "]", "=", "'PASS'", "failed_hosts", "=", "[", "]", "###################################################", "# First validation is to make sure connec...
41.185185
15.62963
def base_show_parser(): """Creates a parser with arguments specific to formatting a single resource. Returns: {ArgumentParser}: Base parser with default show args """ base_parser = ArgumentParser(add_help=False) base_parser.add_argument( '-k', '--key', type=str, ...
[ "def", "base_show_parser", "(", ")", ":", "base_parser", "=", "ArgumentParser", "(", "add_help", "=", "False", ")", "base_parser", ".", "add_argument", "(", "'-k'", ",", "'--key'", ",", "type", "=", "str", ",", "help", "=", "'show a single property from the bloc...
27.380952
18.52381
def migrate_1to2(store): """Migrate array metadata in `store` from Zarr format version 1 to version 2. Parameters ---------- store : MutableMapping Store to be migrated. Notes ----- Version 1 did not support hierarchies, so this migration function will look for a single arr...
[ "def", "migrate_1to2", "(", "store", ")", ":", "# migrate metadata", "from", "zarr", "import", "meta_v1", "meta", "=", "meta_v1", ".", "decode_metadata", "(", "store", "[", "'meta'", "]", ")", "del", "store", "[", "'meta'", "]", "# add empty filters", "meta", ...
27.617021
19.340426
def adjust_aperture(self, image_region=15, ignore_bright=0): """ Develop a panel showing the current aperture and the light curve as judged from that aperture. Clicking on individual pixels on the aperture will toggle those pixels on or off into the aperture (which will be updated after ...
[ "def", "adjust_aperture", "(", "self", ",", "image_region", "=", "15", ",", "ignore_bright", "=", "0", ")", ":", "self", ".", "ignore_bright", "=", "ignore_bright", "self", ".", "calc_fluxes", "(", ")", "self", ".", "coordsx", "=", "[", "]", "self", ".",...
54.86
33.22
def generateStats(filename, maxSamples = None,): """ Collect statistics for each of the fields in the user input data file and return a stats dict object. Parameters: ------------------------------------------------------------------------------ filename: The path and name of the data file. m...
[ "def", "generateStats", "(", "filename", ",", "maxSamples", "=", "None", ",", ")", ":", "# Mapping from field type to stats collector object", "statsCollectorMapping", "=", "{", "'float'", ":", "FloatStatsCollector", ",", "'int'", ":", "IntStatsCollector", ",", "'string...
36.57971
20.666667
def DbGetDeviceAttributeProperty(self, argin): """ Get device attribute property(ies) value :param argin: Str[0] = Device name Str[1] = Attribute name Str[n] = Attribute name :type: tango.DevVarStringArray :return: Str[0] = Device name Str[1] = Attribute property...
[ "def", "DbGetDeviceAttributeProperty", "(", "self", ",", "argin", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"In DbGetDeviceAttributeProperty()\"", ")", "dev_name", "=", "argin", "[", "0", "]", "return", "self", ".", "db", ".", "get_device_attribute_pro...
41.235294
9.294118
def subtract(self, route): """ Remove the route entirely. """ for address in self.raw_maps.pop(route, NullHardwareMap()).iterkeys(): self.pop(address, NullHardwareNode())
[ "def", "subtract", "(", "self", ",", "route", ")", ":", "for", "address", "in", "self", ".", "raw_maps", ".", "pop", "(", "route", ",", "NullHardwareMap", "(", ")", ")", ".", "iterkeys", "(", ")", ":", "self", ".", "pop", "(", "address", ",", "Null...
35.5
10.5
def cancelMarketData(self, contracts=None): """ Cancel streaming market data for contract https://www.interactivebrokers.com/en/software/api/apiguide/java/cancelmktdata.htm """ if contracts == None: contracts = list(self.contracts.values()) elif not isinstance...
[ "def", "cancelMarketData", "(", "self", ",", "contracts", "=", "None", ")", ":", "if", "contracts", "==", "None", ":", "contracts", "=", "list", "(", "self", ".", "contracts", ".", "values", "(", ")", ")", "elif", "not", "isinstance", "(", "contracts", ...
41.428571
14.428571
def standard_cl_params(items): """Shared command line parameters for GATK programs. Handles no removal of duplicate reads for amplicon or non mark duplicate experiments. If we have pre-aligned inputs we ignore the value or mark duplicates (since they may already be marked in the input BAM). """...
[ "def", "standard_cl_params", "(", "items", ")", ":", "out", "=", "[", "]", "def", "_skip_duplicates", "(", "data", ")", ":", "return", "(", "dd", ".", "get_coverage_interval", "(", "data", ")", "==", "\"amplicon\"", "or", "(", "dd", ".", "get_aligner", "...
44.85
18.9
def update_bgp_speaker(self, bgp_speaker_id, body=None): """Update a BGP speaker.""" return self.put(self.bgp_speaker_path % bgp_speaker_id, body=body)
[ "def", "update_bgp_speaker", "(", "self", ",", "bgp_speaker_id", ",", "body", "=", "None", ")", ":", "return", "self", ".", "put", "(", "self", ".", "bgp_speaker_path", "%", "bgp_speaker_id", ",", "body", "=", "body", ")" ]
55
16.666667
def url_should_be(self, url): """Assert the absolute URL of the browser is as provided.""" if world.browser.current_url != url: raise AssertionError( "Browser URL expected to be {!r}, got {!r}.".format( url, world.browser.current_url))
[ "def", "url_should_be", "(", "self", ",", "url", ")", ":", "if", "world", ".", "browser", ".", "current_url", "!=", "url", ":", "raise", "AssertionError", "(", "\"Browser URL expected to be {!r}, got {!r}.\"", ".", "format", "(", "url", ",", "world", ".", "bro...
39.142857
13.428571
def send(self, metrics): """Send the metrics to zabbix server. :type metrics: list :param metrics: List of :class:`zabbix.sender.ZabbixMetric` to send to Zabbix :rtype: :class:`pyzabbix.sender.ZabbixResponse` :return: Parsed response from Zabbix Server """ ...
[ "def", "send", "(", "self", ",", "metrics", ")", ":", "result", "=", "ZabbixResponse", "(", ")", "for", "m", "in", "range", "(", "0", ",", "len", "(", "metrics", ")", ",", "self", ".", "chunk_size", ")", ":", "result", ".", "parse", "(", "self", ...
35.285714
19
def security_layer(tls_provider, sasl_providers): """ .. deprecated:: 0.6 Replaced by :class:`SecurityLayer`. Return a configured :class:`SecurityLayer`. `tls_provider` must be a :class:`STARTTLSProvider`. The return value can be passed to the constructor of :class:`~.node.Client`. ...
[ "def", "security_layer", "(", "tls_provider", ",", "sasl_providers", ")", ":", "sasl_providers", "=", "tuple", "(", "sasl_providers", ")", "if", "not", "sasl_providers", ":", "raise", "ValueError", "(", "\"At least one SASL provider must be given.\"", ")", "for", "sas...
27.4
20.866667
def from_analysis_period(cls, analysis_period, clearness=1, daylight_savings_indicator='No'): """"Initialize a OriginalClearSkyCondition from an analysis_period""" _check_analysis_period(analysis_period) return cls(analysis_period.st_month, analysis_period.st_day, cl...
[ "def", "from_analysis_period", "(", "cls", ",", "analysis_period", ",", "clearness", "=", "1", ",", "daylight_savings_indicator", "=", "'No'", ")", ":", "_check_analysis_period", "(", "analysis_period", ")", "return", "cls", "(", "analysis_period", ".", "st_month", ...
61.666667
15.5
def set_location(request): """ Redirect to a given url while setting the chosen location in the cookie. The url and the location_id need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If ...
[ "def", "set_location", "(", "request", ")", ":", "next", "=", "request", ".", "GET", ".", "get", "(", "'next'", ",", "None", ")", "or", "request", ".", "POST", ".", "get", "(", "'next'", ",", "None", ")", "if", "not", "next", ":", "next", "=", "r...
43.153846
24.153846
def publish(self, topic, payload, QoS): """ **Description** Publish a new message to the desired topic with QoS. **Syntax** .. code:: python # Publish a QoS0 message "myPayload" to topic "myTopic" myAWSIoTMQTTClient.publish("myTopic", "myPayload", 0) ...
[ "def", "publish", "(", "self", ",", "topic", ",", "payload", ",", "QoS", ")", ":", "return", "self", ".", "_mqtt_core", ".", "publish", "(", "topic", ",", "payload", ",", "QoS", ",", "False", ")" ]
27.793103
26.758621
def get_orientation(strategy, **kwargs): """ Determine a PV system's surface tilt and surface azimuth using a named strategy. Parameters ---------- strategy: str The orientation strategy. Allowed strategies include 'flat', 'south_at_latitude_tilt'. **kwargs: Strategy...
[ "def", "get_orientation", "(", "strategy", ",", "*", "*", "kwargs", ")", ":", "if", "strategy", "==", "'south_at_latitude_tilt'", ":", "surface_azimuth", "=", "180", "surface_tilt", "=", "kwargs", "[", "'latitude'", "]", "elif", "strategy", "==", "'flat'", ":"...
27.551724
19.344828
def remove_role_requests(cursor, uuid_, roles): """Given a ``uuid`` and list of dicts containing the ``uid`` (user identifiers) and ``role`` for removal of the identified users' role acceptance entries. """ if not isinstance(roles, (list, set, tuple,)): raise TypeError("``roles`` is an inval...
[ "def", "remove_role_requests", "(", "cursor", ",", "uuid_", ",", "roles", ")", ":", "if", "not", "isinstance", "(", "roles", ",", "(", "list", ",", "set", ",", "tuple", ",", ")", ")", ":", "raise", "TypeError", "(", "\"``roles`` is an invalid type: {}\"", ...
39.375
13.8125
def get_metabolite_compartments(self): """Return all metabolites' compartments.""" warn('use Model.compartments instead', DeprecationWarning) return {met.compartment for met in self.metabolites if met.compartment is not None}
[ "def", "get_metabolite_compartments", "(", "self", ")", ":", "warn", "(", "'use Model.compartments instead'", ",", "DeprecationWarning", ")", "return", "{", "met", ".", "compartment", "for", "met", "in", "self", ".", "metabolites", "if", "met", ".", "compartment",...
52.2
10.8
def random_polygon(segments=8, radius=1.0): """ Generate a random polygon with a maximum number of sides and approximate radius. Parameters --------- segments: int, the maximum number of sides the random polygon will have radius: float, the approximate radius of the polygon desired Retur...
[ "def", "random_polygon", "(", "segments", "=", "8", ",", "radius", "=", "1.0", ")", ":", "angles", "=", "np", ".", "sort", "(", "np", ".", "cumsum", "(", "np", ".", "random", ".", "random", "(", "segments", ")", "*", "np", ".", "pi", "*", "2", ...
35.304348
19.391304
def oauth_token_exchange_cli(client_id, client_secret, redirect_uri, base_url=OH_BASE_URL, code=None, refresh_token=None): """ Command line function for obtaining the refresh token/code. For more information visit :func:`oauth2_token_exchange<oha...
[ "def", "oauth_token_exchange_cli", "(", "client_id", ",", "client_secret", ",", "redirect_uri", ",", "base_url", "=", "OH_BASE_URL", ",", "code", "=", "None", ",", "refresh_token", "=", "None", ")", ":", "print", "(", "oauth2_token_exchange", "(", "client_id", "...
48.6
17.2
def get_gradebook_lookup_session(self, proxy): """Gets the OsidSession associated with the gradebook lookup service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.grading.GradebookLookupSession) - a ``GradebookLookupSession`` raise: NullArgument - ``proxy`` is...
[ "def", "get_gradebook_lookup_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_gradebook_lookup", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "Gradeboo...
46.294118
15.823529
def small_parts(script, ratio=0.2, non_closed_only=False): """ Select & delete the small disconnected parts (components) of a mesh. Args: script: the FilterScript object or script filename to write the filter to. ratio (float): This ratio (between 0 and 1) defines the meaning of ...
[ "def", "small_parts", "(", "script", ",", "ratio", "=", "0.2", ",", "non_closed_only", "=", "False", ")", ":", "select", ".", "small_parts", "(", "script", ",", "ratio", ",", "non_closed_only", ")", "selected", "(", "script", ")", "return", "None" ]
33.636364
23.954545
def save(self, entry, with_location=True, debug=False): """Saves a DayOneEntry as a plist""" entry_dict = {} if isinstance(entry, DayOneEntry): # Get a dict of the DayOneEntry entry_dict = entry.as_dict() else: entry_dict = entry # Set...
[ "def", "save", "(", "self", ",", "entry", ",", "with_location", "=", "True", ",", "debug", "=", "False", ")", ":", "entry_dict", "=", "{", "}", "if", "isinstance", "(", "entry", ",", "DayOneEntry", ")", ":", "# Get a dict of the DayOneEntry", "entry_dict", ...
34.206897
18.896552
def add_backup_operation(self, backup, mode=None): """Add a backup operation to the version. :param backup: To either add or skip the backup :type backup: Boolean :param mode: Name of the mode in which the operation is executed For now, backups are mode-independent ...
[ "def", "add_backup_operation", "(", "self", ",", "backup", ",", "mode", "=", "None", ")", ":", "try", ":", "if", "self", ".", "options", ".", "backup", ":", "self", ".", "options", ".", "backup", ".", "ignore_if_operation", "(", ")", ".", "execute", "(...
37.571429
15.571429