text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def recvServerInit(self, data): """ Read server init packet @param data: Stream that contains well formed packet """ data.readType(self._serverInit) self.expectWithHeader(4, self.recvServerName)
[ "def", "recvServerInit", "(", "self", ",", "data", ")", ":", "data", ".", "readType", "(", "self", ".", "_serverInit", ")", "self", ".", "expectWithHeader", "(", "4", ",", "self", ".", "recvServerName", ")" ]
33.714286
7.428571
def reset_ilo_credential(self, password): """Resets the iLO password. :param password: The password to be set. :raises: IloError, if account not found or on an error from iLO. """ dic = {'USER_LOGIN': self.login} root = self._create_dynamic_xml( 'MOD_USER', ...
[ "def", "reset_ilo_credential", "(", "self", ",", "password", ")", ":", "dic", "=", "{", "'USER_LOGIN'", ":", "self", ".", "login", "}", "root", "=", "self", ".", "_create_dynamic_xml", "(", "'MOD_USER'", ",", "'USER_INFO'", ",", "'write'", ",", "dic", ")",...
34.466667
14.866667
async def read(self, *_id): """Read data from database table. Accepts ids of entries. Returns list of results if success or string with error code and explanation. read(*id) => [(result), (result)] (if success) read(*id) => [] (if missed) read() => {"error":400, "reason":"Missed required fields"} """ ...
[ "async", "def", "read", "(", "self", ",", "*", "_id", ")", ":", "if", "not", "_id", ":", "return", "{", "\"error\"", ":", "400", ",", "\"reason\"", ":", "\"Missed required fields\"", "}", "result", "=", "[", "]", "for", "i", "in", "_id", ":", "docume...
25.608696
17.608696
def getInputOrder(ast, input_order=None): """Derive the input order of the variables in an expression. """ variables = {} for a in ast.allOf('variable'): variables[a.value] = a variable_names = set(variables.keys()) if input_order: if variable_names != set(input_order): ...
[ "def", "getInputOrder", "(", "ast", ",", "input_order", "=", "None", ")", ":", "variables", "=", "{", "}", "for", "a", "in", "ast", ".", "allOf", "(", "'variable'", ")", ":", "variables", "[", "a", ".", "value", "]", "=", "a", "variable_names", "=", ...
33.05
14.4
def _set_axis(self, axis, labels, fastpath=False): """ Override generic, we want to set the _typ here. """ if not fastpath: labels = ensure_index(labels) is_all_dates = labels.is_all_dates if is_all_dates: if not isinstance(labels, ...
[ "def", "_set_axis", "(", "self", ",", "axis", ",", "labels", ",", "fastpath", "=", "False", ")", ":", "if", "not", "fastpath", ":", "labels", "=", "ensure_index", "(", "labels", ")", "is_all_dates", "=", "labels", ".", "is_all_dates", "if", "is_all_dates",...
35.037037
16.222222
def build_metamodel(self, id_generator=None): ''' Build and return a *xtuml.MetaModel* containing previously loaded input. ''' m = xtuml.MetaModel(id_generator) self.populate(m) return m
[ "def", "build_metamodel", "(", "self", ",", "id_generator", "=", "None", ")", ":", "m", "=", "xtuml", ".", "MetaModel", "(", "id_generator", ")", "self", ".", "populate", "(", "m", ")", "return", "m" ]
27.111111
23.111111
def extendleft(self, other): """ Extend the left side of the the collection by appending values from the iterable *other*. Note that the appends will reverse the order of the given values. """ def extendleft_trans(pipe): values = list(other.__iter__(pipe)) if ...
[ "def", "extendleft", "(", "self", ",", "other", ")", ":", "def", "extendleft_trans", "(", "pipe", ")", ":", "values", "=", "list", "(", "other", ".", "__iter__", "(", "pipe", ")", ")", "if", "use_redis", "else", "other", "for", "v", "in", "values", "...
37.411765
16.235294
def child_widgets(self): """ Get the child toolkit widgets for this object. Returns ------- result : iterable of QObject The child widgets defined for this object. """ for child in self.children(): w = child.widget if w is not None: ...
[ "def", "child_widgets", "(", "self", ")", ":", "for", "child", "in", "self", ".", "children", "(", ")", ":", "w", "=", "child", ".", "widget", "if", "w", "is", "not", "None", ":", "yield", "w" ]
25.384615
15.923077
def checkform (form, env): """Check form data. throw exception on error Be sure to NOT print out any user-given data as HTML code, so use only plain strings as exception text.""" # check lang support if "language" in form: lang = formvalue(form, 'language') if lang in _supported_lang...
[ "def", "checkform", "(", "form", ",", "env", ")", ":", "# check lang support", "if", "\"language\"", "in", "form", ":", "lang", "=", "formvalue", "(", "form", ",", "'language'", ")", "if", "lang", "in", "_supported_langs", ":", "localestr", "=", "lang_locale...
40.648649
14.864865
def get_inert_ratio_raw(cont): """Compute the inertia ratio of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that hold...
[ "def", "get_inert_ratio_raw", "(", "cont", ")", ":", "if", "isinstance", "(", "cont", ",", "np", ".", "ndarray", ")", ":", "# If cont is an array, it is not a list of contours,", "# because contours can have different lengths.", "cont", "=", "[", "cont", "]", "ret_list"...
30.175439
22.631579
def send_report(report, config): """ Sends the report to IOpipe's collector. :param report: The report to be sent. :param config: The IOpipe agent configuration. """ headers = {"Authorization": "Bearer {}".format(config["token"])} url = "https://{host}{path}".format(**config) try: ...
[ "def", "send_report", "(", "report", ",", "config", ")", ":", "headers", "=", "{", "\"Authorization\"", ":", "\"Bearer {}\"", ".", "format", "(", "config", "[", "\"token\"", "]", ")", "}", "url", "=", "\"https://{host}{path}\"", ".", "format", "(", "*", "*...
32.421053
17.894737
def to_polycollection(self, *args, **kwargs): """ Returns the mesh as matplotlib polygon collection. (tested only for 2D meshes) """ from matplotlib import collections nodes, elements = self.nodes, self.elements.reset_index() verts = [] index = [] for etype, gro...
[ "def", "to_polycollection", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "matplotlib", "import", "collections", "nodes", ",", "elements", "=", "self", ".", "nodes", ",", "self", ".", "elements", ".", "reset_index", "(", ")", ...
42.222222
15.333333
def delete_folder(self, project, path): """DeleteFolder. [Preview API] Deletes a definition folder. Definitions and their corresponding builds will also be deleted. :param str project: Project ID or project name :param str path: The full path to the folder. """ route_valu...
[ "def", "delete_folder", "(", "self", ",", "project", ",", "path", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'project'", "...
49.133333
17.066667
def analyses(): """Display analyses.""" per_page = int(request.args.get('per_page', 50)) page = int(request.args.get('page', 1)) query = store.analyses(status=request.args.get('status'), query=request.args.get('query'), is_visible=request.args.get('i...
[ "def", "analyses", "(", ")", ":", "per_page", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'per_page'", ",", "50", ")", ")", "page", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'page'", ",", "1", ")", ")", "query", ...
44.411765
22.235294
def __nn_filter_helper(R_data, R_indices, R_ptr, S, aggregate): '''Nearest-neighbor filter helper function. This is an internal function, not for use outside of the decompose module. It applies the nearest-neighbor filter to S, assuming that the first index corresponds to observations. Parameters...
[ "def", "__nn_filter_helper", "(", "R_data", ",", "R_indices", ",", "R_ptr", ",", "S", ",", "aggregate", ")", ":", "s_out", "=", "np", ".", "empty_like", "(", "S", ")", "for", "i", "in", "range", "(", "len", "(", "R_ptr", ")", "-", "1", ")", ":", ...
25.688889
23.866667
def _transform(self, crash_id): """this default transform function only transfers raw data from the source to the destination without changing the data. While this may be good enough for the raw crashmover, the processor would override this method to create and save processed crashes"""...
[ "def", "_transform", "(", "self", ",", "crash_id", ")", ":", "try", ":", "raw_crash", "=", "self", ".", "source", ".", "get_raw_crash", "(", "crash_id", ")", "except", "Exception", "as", "x", ":", "self", ".", "config", ".", "logger", ".", "error", "("...
34.463415
14.658537
def auto_zip_open(filepath, mode): """Convenience function for opening potentially-compressed files.""" if filepath.endswith('.gz'): outfile = gzip.open(filepath, mode) elif filepath.endswith('.bz2'): outfile = bz2.BZ2File(filepath, mode) else: outfile = open(filepath, mode) ...
[ "def", "auto_zip_open", "(", "filepath", ",", "mode", ")", ":", "if", "filepath", ".", "endswith", "(", "'.gz'", ")", ":", "outfile", "=", "gzip", ".", "open", "(", "filepath", ",", "mode", ")", "elif", "filepath", ".", "endswith", "(", "'.bz2'", ")", ...
36.222222
9.111111
def parse_scale(x): """Splits a "%s:%d" string and returns the string and number. :return: A ``(string, int)`` pair extracted from ``x``. :raise ValueError: the string ``x`` does not respect the input format. """ match = re.match(r'^(.+?):(\d+)$', x) if not match: raise ValueError('Inv...
[ "def", "parse_scale", "(", "x", ")", ":", "match", "=", "re", ".", "match", "(", "r'^(.+?):(\\d+)$'", ",", "x", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "'Invalid scale \"%s\".'", "%", "x", ")", "return", "match", ".", "group", "(", ...
34.454545
17.727273
def _set_rules(self, group, rules): """Implementation detail""" group.clear() for rule in rules: self._add_rule(group, *rule) self.invalidate()
[ "def", "_set_rules", "(", "self", ",", "group", ",", "rules", ")", ":", "group", ".", "clear", "(", ")", "for", "rule", "in", "rules", ":", "self", ".", "_add_rule", "(", "group", ",", "*", "rule", ")", "self", ".", "invalidate", "(", ")" ]
22.75
16.625
def get(self, sid): """ Constructs a UserContext :param sid: The unique string that identifies the resource :returns: twilio.rest.chat.v2.service.user.UserContext :rtype: twilio.rest.chat.v2.service.user.UserContext """ return UserContext(self._version, service_...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "UserContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
35.6
23.2
def __unionfs_set_up(ro_dir, rw_dir, mount_dir): """ Setup a unionfs via unionfs-fuse. Args: ro_base: base_directory of the project rw_image: virtual image of actual file system mountpoint: location where ro_base and rw_image merge """ mount_dir.mkdir() rw_dir.mkdir() ...
[ "def", "__unionfs_set_up", "(", "ro_dir", ",", "rw_dir", ",", "mount_dir", ")", ":", "mount_dir", ".", "mkdir", "(", ")", "rw_dir", ".", "mkdir", "(", ")", "if", "not", "ro_dir", ".", "exists", "(", ")", ":", "LOG", ".", "error", "(", "\"Base dir does ...
36.85
18.85
def flush(self, indices=None, refresh=None): """ Flushes one or more indices (clear memory) If a bulk is full, it sends it. (See :ref:`es-guide-reference-api-admin-indices-flush`) :keyword indices: an index or a list of indices :keyword refresh: set the refresh paramet...
[ "def", "flush", "(", "self", ",", "indices", "=", "None", ",", "refresh", "=", "None", ")", ":", "self", ".", "conn", ".", "force_bulk", "(", ")", "path", "=", "self", ".", "conn", ".", "_make_path", "(", "indices", ",", "'_flush'", ")", "args", "=...
31
17.111111
def _finish_pending_requests(self) -> None: """Process any requests that were completed by the last call to multi.socket_action. """ while True: num_q, ok_list, err_list = self._multi.info_read() for curl in ok_list: self._finish(curl) ...
[ "def", "_finish_pending_requests", "(", "self", ")", "->", "None", ":", "while", "True", ":", "num_q", ",", "ok_list", ",", "err_list", "=", "self", ".", "_multi", ".", "info_read", "(", ")", "for", "curl", "in", "ok_list", ":", "self", ".", "_finish", ...
36.538462
9.769231
def to_linear(self, index=None): """ Transforms the StepColormap into a LinearColormap. Parameters ---------- index : list of floats, default None The values corresponding to each color in the output colormap. It has to be sorted. ...
[ "def", "to_linear", "(", "self", ",", "index", "=", "None", ")", ":", "if", "index", "is", "None", ":", "n", "=", "len", "(", "self", ".", "index", ")", "-", "1", "index", "=", "[", "self", ".", "index", "[", "i", "]", "*", "(", "1.", "-", ...
36.15
19.35
def run_ahead(self, time, framerate): """Run the particle system for the specified time frame at the specified framerate to move time forward as quickly as possible. Useful for "warming up" the particle system to reach a steady-state before anything is drawn or to simply "skip ahead" in ...
[ "def", "run_ahead", "(", "self", ",", "time", ",", "framerate", ")", ":", "if", "time", ":", "td", "=", "1.0", "/", "framerate", "update", "=", "self", ".", "update", "for", "i", "in", "range", "(", "int", "(", "time", "/", "td", ")", ")", ":", ...
42
18.058824
def write_calculations_to_csv(funcs, states, columns, path, headers, out_name, metaids=[], extension=".xls"): """Writes each output of the given functions on the given states and data columns to a new column in the specified output file. Note: Column 0 is time. The first data ...
[ "def", "write_calculations_to_csv", "(", "funcs", ",", "states", ",", "columns", ",", "path", ",", "headers", ",", "out_name", ",", "metaids", "=", "[", "]", ",", "extension", "=", "\".xls\"", ")", ":", "if", "not", "isinstance", "(", "funcs", ",", "list...
53.918367
33.265306
def compile_bundle_entry(self, spec, entry): """ Handler for each entry for the bundle method of the compile process. This copies the source file or directory into the build directory. """ modname, source, target, modpath = entry bundled_modpath = {modname: modp...
[ "def", "compile_bundle_entry", "(", "self", ",", "spec", ",", "entry", ")", ":", "modname", ",", "source", ",", "target", ",", "modpath", "=", "entry", "bundled_modpath", "=", "{", "modname", ":", "modpath", "}", "bundled_target", "=", "{", "modname", ":",...
38.681818
13.318182
def calcTemperature(self): """ Calculates the temperature using which uses equations.MeanPlanetTemp, albedo assumption and potentially equations.starTemperature. issues - you cant get the albedo assumption without temp but you need it to calculate the temp. """ try: ...
[ "def", "calcTemperature", "(", "self", ")", ":", "try", ":", "return", "eq", ".", "MeanPlanetTemp", "(", "self", ".", "albedo", ",", "self", ".", "star", ".", "T", ",", "self", ".", "star", ".", "R", ",", "self", ".", "a", ")", ".", "T_p", "excep...
45.727273
25
def get_all_customer_gateways(self, customer_gateway_ids=None, filters=None): """ Retrieve information about your CustomerGateways. You can filter results to return information only about those CustomerGateways that match your search parameters. Otherwise, all CustomerGateways associat...
[ "def", "get_all_customer_gateways", "(", "self", ",", "customer_gateway_ids", "=", "None", ",", "filters", "=", "None", ")", ":", "params", "=", "{", "}", "if", "customer_gateway_ids", ":", "self", ".", "build_list_params", "(", "params", ",", "customer_gateway_...
47.029412
26.323529
def play(self): """ Sends a "play" command to the player. """ msg = cr.Message() msg.type = cr.PLAY self.send_message(msg)
[ "def", "play", "(", "self", ")", ":", "msg", "=", "cr", ".", "Message", "(", ")", "msg", ".", "type", "=", "cr", ".", "PLAY", "self", ".", "send_message", "(", "msg", ")" ]
23.428571
9.714286
def format(self, rec): """ :type rec: logging.LogRecord """ t = self.formatTime(rec, self.datefmt) func = '' if rec.funcName == '<module>' else ' %s()' % rec.funcName left_header_data = (t, rec.msecs, rec.name, func, rec.lineno) left_header = '%s.%03d %s%s @ %d' %...
[ "def", "format", "(", "self", ",", "rec", ")", ":", "t", "=", "self", ".", "formatTime", "(", "rec", ",", "self", ".", "datefmt", ")", "func", "=", "''", "if", "rec", ".", "funcName", "==", "'<module>'", "else", "' %s()'", "%", "rec", ".", "funcNam...
47
19.583333
def build_boolCoeff(self): ''' Compute coefficients for tuple space. ''' # coefficients for hill functions from boolean update rules self.boolCoeff = collections.OrderedDict([(s,[]) for s in self.varNames.keys()]) # parents self.pas = collections.OrderedDict([(s,[]) for s...
[ "def", "build_boolCoeff", "(", "self", ")", ":", "# coefficients for hill functions from boolean update rules", "self", ".", "boolCoeff", "=", "collections", ".", "OrderedDict", "(", "[", "(", "s", ",", "[", "]", ")", "for", "s", "in", "self", ".", "varNames", ...
50.096774
21.451613
def _make_default_privileges_list_query(name, object_type, prepend): ''' Generate the SQL required for specific object type ''' if object_type == 'table': query = (' '.join([ 'SELECT defacl.defaclacl AS name', 'FROM pg_default_acl defacl', 'JOIN pg_authid aid'...
[ "def", "_make_default_privileges_list_query", "(", "name", ",", "object_type", ",", "prepend", ")", ":", "if", "object_type", "==", "'table'", ":", "query", "=", "(", "' '", ".", "join", "(", "[", "'SELECT defacl.defaclacl AS name'", ",", "'FROM pg_default_acl defac...
35.229508
8.901639
def save_into_qrcode(text, out_filepath, color='', box_size=10, pixel_size=1850): """ Save `text` in a qrcode svg image file. Parameters ---------- text: str The string to be codified in the QR image. out_filepath: str Path to the output file color: str A RGB color exp...
[ "def", "save_into_qrcode", "(", "text", ",", "out_filepath", ",", "color", "=", "''", ",", "box_size", "=", "10", ",", "pixel_size", "=", "1850", ")", ":", "try", ":", "qr", "=", "qrcode", ".", "QRCode", "(", "version", "=", "1", ",", "error_correction...
30.71875
24.71875
def release(self, conn): """Revert back connection to pool.""" if conn.in_transaction: raise InvalidRequestError( "Cannot release a connection with " "not finished transaction" ) raw = conn.connection res = yield from self._pool.rel...
[ "def", "release", "(", "self", ",", "conn", ")", ":", "if", "conn", ".", "in_transaction", ":", "raise", "InvalidRequestError", "(", "\"Cannot release a connection with \"", "\"not finished transaction\"", ")", "raw", "=", "conn", ".", "connection", "res", "=", "y...
33.9
10.8
def save(self, new=None, timeout=2): """write ALL_VERS_DATA to disk in 'pretty' format""" if new: self.update(new) # allow two operations (update + save) with a single command if not self._updated: return # nothing to do thisPkg = os.path.dirname(__file__) filename = os.path.join...
[ "def", "save", "(", "self", ",", "new", "=", "None", ",", "timeout", "=", "2", ")", ":", "if", "new", ":", "self", ".", "update", "(", "new", ")", "# allow two operations (update + save) with a single command", "if", "not", "self", ".", "_updated", ":", "r...
61.807692
27.807692
def send(self, *args, **kwargs): """Sends the envelope using a freshly created SMTP connection. *args* and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP` constructor. Returns a tuple of SMTP object and whatever its send method returns.""" conn = SMTP(*args, **kw...
[ "def", "send", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "SMTP", "(", "*", "args", ",", "*", "*", "kwargs", ")", "send_result", "=", "conn", ".", "send", "(", "self", ")", "return", "conn", ",", "send_result" ...
43.111111
13.111111
def set_mesh(self, mesh, shift=None, is_time_reversal=True, is_mesh_symmetry=True, is_eigenvectors=False, is_gamma_center=False, run_immediately=True): """Phonon calculations on sampling mesh g...
[ "def", "set_mesh", "(", "self", ",", "mesh", ",", "shift", "=", "None", ",", "is_time_reversal", "=", "True", ",", "is_mesh_symmetry", "=", "True", ",", "is_eigenvectors", "=", "False", ",", "is_gamma_center", "=", "False", ",", "run_immediately", "=", "True...
42.290323
16.967742
def _decode_relation(self, s): '''(INTERNAL) Decodes a relation line. The relation declaration is a line with the format ``@RELATION <relation-name>``, where ``relation-name`` is a string. The string must start with alphabetic character and must be quoted if the name includes sp...
[ "def", "_decode_relation", "(", "self", ",", "s", ")", ":", "_", ",", "v", "=", "s", ".", "split", "(", "' '", ",", "1", ")", "v", "=", "v", ".", "strip", "(", ")", "if", "not", "_RE_RELATION", ".", "match", "(", "v", ")", ":", "raise", "BadR...
36.181818
23.545455
def StatResultFromStatEntry( stat_entry): """Returns a `os.stat_result` with most information from `StatEntry`. This is a lossy conversion, only the 10 first stat_result fields are populated, because the os.stat_result constructor is inflexible. Args: stat_entry: An instance of rdf_client_fs.StatEntry...
[ "def", "StatResultFromStatEntry", "(", "stat_entry", ")", ":", "values", "=", "[", "]", "for", "attr", "in", "_STAT_ATTRS", "[", ":", "10", "]", ":", "values", ".", "append", "(", "stat_entry", ".", "Get", "(", "attr", ")", ")", "return", "os", ".", ...
29.764706
21.176471
def follower_num(self): """获取追随者数量,就是关注此人的人数. :return: 追随者数量 :rtype: int """ if self.url is None: return 0 else: number = int(self.soup.find( 'div', class_='zm-profile-side-following zg-clear').find_all( 'a')[1].str...
[ "def", "follower_num", "(", "self", ")", ":", "if", "self", ".", "url", "is", "None", ":", "return", "0", "else", ":", "number", "=", "int", "(", "self", ".", "soup", ".", "find", "(", "'div'", ",", "class_", "=", "'zm-profile-side-following zg-clear'", ...
26.384615
16.230769
def register(coordinator): """Registers this module as a worker with the given coordinator.""" fetch_queue = Queue.Queue() coordinator.register(FetchItem, fetch_queue) for i in xrange(FLAGS.fetch_threads): coordinator.worker_threads.append( FetchThread(fetch_queue, coordinator.input_...
[ "def", "register", "(", "coordinator", ")", ":", "fetch_queue", "=", "Queue", ".", "Queue", "(", ")", "coordinator", ".", "register", "(", "FetchItem", ",", "fetch_queue", ")", "for", "i", "in", "xrange", "(", "FLAGS", ".", "fetch_threads", ")", ":", "co...
45.857143
8
def json(self, attribs=None, recurse=True, ignorelist=False): """Serialises the FoLiA element and all its contents to a Python dictionary suitable for serialisation to JSON. Example:: import json json.dumps(word.json()) Returns: dict """ jso...
[ "def", "json", "(", "self", ",", "attribs", "=", "None", ",", "recurse", "=", "True", ",", "ignorelist", "=", "False", ")", ":", "jsonnode", "=", "{", "}", "jsonnode", "[", "'type'", "]", "=", "self", ".", "XMLTAG", "if", "self", ".", "id", ":", ...
34.901639
15.065574
def _nodeGetNonDefaultsDict(self): """ Retrieves this nodes` values as a dictionary to be used for persistence. Non-recursive auxiliary function for getNonDefaultsDict """ dct = {} if self.data != self.defaultData: dct['data'] = self.data.name() return dct
[ "def", "_nodeGetNonDefaultsDict", "(", "self", ")", ":", "dct", "=", "{", "}", "if", "self", ".", "data", "!=", "self", ".", "defaultData", ":", "dct", "[", "'data'", "]", "=", "self", ".", "data", ".", "name", "(", ")", "return", "dct" ]
39.125
10.25
def swo_set_host_buffer_size(self, buf_size): """Sets the size of the buffer used by the host to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the host buffer Returns: ``None`` Raises: JLinkExceptio...
[ "def", "swo_set_host_buffer_size", "(", "self", ",", "buf_size", ")", ":", "buf", "=", "ctypes", ".", "c_uint32", "(", "buf_size", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "SET_BUFFERSIZE_HO...
30.15
20.5
def _from_binary_idx_e(cls, binary_stream, content_type=None): """See base class.""" #TODO don't save this here and overload later? #TODO confirm if this is really generic or is always a file reference ''' Undefined - 8 Length of entry - 2 Length of content - 2 Flags - 4 ...
[ "def", "_from_binary_idx_e", "(", "cls", ",", "binary_stream", ",", "content_type", "=", "None", ")", ":", "#TODO don't save this here and overload later?", "#TODO confirm if this is really generic or is always a file reference", "''' Undefined - 8\n Length of entry - 2\n L...
46.451613
29.451613
def toLinear(self): """ NAME: toLinear PURPOSE: convert a 3D orbit into a 1D orbit (z) INPUT: (none) OUTPUT: linear Orbit HISTORY: 2010-11-30 - Written - Bovy (NYU) """ orbSetupKwargs= {'ro':...
[ "def", "toLinear", "(", "self", ")", ":", "orbSetupKwargs", "=", "{", "'ro'", ":", "None", ",", "'vo'", ":", "None", ",", "'zo'", ":", "self", ".", "_orb", ".", "_zo", ",", "'solarmotion'", ":", "self", ".", "_orb", ".", "_solarmotion", "}", "if", ...
24.083333
22.861111
def get_classname(class_, local=False): r""" Args: class_ (type): local (bool): (default = False) Returns: str: classname CommandLine: python -m utool.util_class --exec-get_classname --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_class im...
[ "def", "get_classname", "(", "class_", ",", "local", "=", "False", ")", ":", "if", "not", "local", ":", "classname", "=", "class_", ".", "__module__", "+", "'.'", "+", "class_", ".", "__name__", "else", ":", "classname", "=", "class_", ".", "__name__", ...
27.961538
20.076923
def filter(self, table, idps, filter_string): """Naive case-insensitive search.""" q = filter_string.lower() return [idp for idp in idps if q in idp.ud.lower()]
[ "def", "filter", "(", "self", ",", "table", ",", "idps", ",", "filter_string", ")", ":", "q", "=", "filter_string", ".", "lower", "(", ")", "return", "[", "idp", "for", "idp", "in", "idps", "if", "q", "in", "idp", ".", "ud", ".", "lower", "(", ")...
39.2
3.6
async def seek(self, pos, *, device: Optional[SomeDevice] = None): """Seeks to the given position in the user’s currently playing track. Parameters ---------- pos : int The position in milliseconds to seek to. Must be a positive number. Passing in a p...
[ "async", "def", "seek", "(", "self", ",", "pos", ",", "*", ",", "device", ":", "Optional", "[", "SomeDevice", "]", "=", "None", ")", ":", "await", "self", ".", "_user", ".", "http", ".", "seek_playback", "(", "pos", ",", "device_id", "=", "str", "(...
49.857143
24.857143
def add_audio(self, tag, audio, sample_rate=44100, global_step=None): """Add audio data to the event file. Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs. Since `asnumpy()` is a blocking function call, this function would block the main thread till it return...
[ "def", "add_audio", "(", "self", ",", "tag", ",", "audio", ",", "sample_rate", "=", "44100", ",", "global_step", "=", "None", ")", ":", "self", ".", "_file_writer", ".", "add_summary", "(", "audio_summary", "(", "tag", ",", "audio", ",", "sample_rate", "...
43.727273
23.045455
def load_item_for_objective(self): """if this is the first time for this magic part, find an LO linked item""" mgr = self.my_osid_object._get_provider_manager('ASSESSMENT', local=True) if self.my_osid_object._my_map['itemBankId']: item_query_session = mgr.get_item_query_session_for_b...
[ "def", "load_item_for_objective", "(", "self", ")", ":", "mgr", "=", "self", ".", "my_osid_object", ".", "_get_provider_manager", "(", "'ASSESSMENT'", ",", "local", "=", "True", ")", "if", "self", ".", "my_osid_object", ".", "_my_map", "[", "'itemBankId'", "]"...
60.392157
26.568627
def __run_post_all(self): """Execute the post-all.py and post-all.sql files if they exist""" # if the list of delta dirs is [delta1, delta2] the post scripts of delta1 are # executed before the post scripts of delta2 for d in self.dirs: post_all_py_path = os.path.join(d, 'p...
[ "def", "__run_post_all", "(", "self", ")", ":", "# if the list of delta dirs is [delta1, delta2] the post scripts of delta1 are", "# executed before the post scripts of delta2", "for", "d", "in", "self", ".", "dirs", ":", "post_all_py_path", "=", "os", ".", "path", ".", "jo...
43.444444
20.888889
def create(self, resource_id=None, attributes=None): """ Creates a resource with a given ID (optional) and attributes for the current content type. """ return self.proxy.create(resource_id=resource_id, attributes=attributes)
[ "def", "create", "(", "self", ",", "resource_id", "=", "None", ",", "attributes", "=", "None", ")", ":", "return", "self", ".", "proxy", ".", "create", "(", "resource_id", "=", "resource_id", ",", "attributes", "=", "attributes", ")" ]
42
25
def P(self): """Diffusion operator (cached) Return or calculate the diffusion operator Returns ------- P : array-like, shape=[n_samples, n_samples] diffusion operator defined as a row-stochastic form of the kernel matrix """ try: ...
[ "def", "P", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_diff_op", "except", "AttributeError", ":", "self", ".", "_diff_op", "=", "normalize", "(", "self", ".", "kernel", ",", "'l1'", ",", "axis", "=", "1", ")", "return", "self", ".", ...
26.941176
19.352941
def _convolution_integrand(t_val, f, g, inverse_time=None, return_log=False): ''' Evaluates int_tau f(t+tau)*g(tau) or int_tau f(t-tau)g(tau) if inverse time is TRUE Parameters ----------- t_val : double Time point f : Interpolation object First mu...
[ "def", "_convolution_integrand", "(", "t_val", ",", "f", ",", "g", ",", "inverse_time", "=", "None", ",", "return_log", "=", "False", ")", ":", "if", "inverse_time", "is", "None", ":", "raise", "Exception", "(", "\"Inverse time argument must be set!\"", ")", "...
29.697368
23.328947
def get_object(cls, api_token, firewall_id): """ Class method that will return a Firewall object by ID. """ firewall = cls(token=api_token, id=firewall_id) firewall.load() return firewall
[ "def", "get_object", "(", "cls", ",", "api_token", ",", "firewall_id", ")", ":", "firewall", "=", "cls", "(", "token", "=", "api_token", ",", "id", "=", "firewall_id", ")", "firewall", ".", "load", "(", ")", "return", "firewall" ]
33.285714
11.285714
def shorten_comment(line, max_line_length, last_comment=False): """Return trimmed or split long comment line. If there are no comments immediately following it, do a text wrap. Doing this wrapping on all comments in general would lead to jagged comment text. """ assert len(line) > max_line_len...
[ "def", "shorten_comment", "(", "line", ",", "max_line_length", ",", "last_comment", "=", "False", ")", ":", "assert", "len", "(", "line", ")", ">", "max_line_length", "line", "=", "line", ".", "rstrip", "(", ")", "# PEP 8 recommends 72 characters for comment text....
38.272727
20.030303
def parse_log(log_file): """Retrieves some statistics from a single Trimmomatic log file. This function parses Trimmomatic's log file and stores some trimming statistics in an :py:class:`OrderedDict` object. This object contains the following keys: - ``clean_len``: Total length after trimming....
[ "def", "parse_log", "(", "log_file", ")", ":", "template", "=", "OrderedDict", "(", "[", "# Total length after trimming", "(", "\"clean_len\"", ",", "0", ")", ",", "# Total trimmed base pairs", "(", "\"total_trim\"", ",", "0", ")", ",", "# Total trimmed base pairs i...
30.014925
18.955224
def RetrievePluginAsset(self, plugin_name, asset_name): """Return the contents of a given plugin asset. Args: plugin_name: The string name of a plugin. asset_name: The string name of an asset. Returns: The string contents of the plugin asset. Raises: KeyError: If the asset is ...
[ "def", "RetrievePluginAsset", "(", "self", ",", "plugin_name", ",", "asset_name", ")", ":", "return", "plugin_asset_util", ".", "RetrieveAsset", "(", "self", ".", "path", ",", "plugin_name", ",", "asset_name", ")" ]
29.142857
20.428571
def setting(self, name_hyphen): """ Retrieves the setting value whose name is indicated by name_hyphen. Values starting with $ are assumed to reference environment variables, and the value stored in environment variables is retrieved. It's an error if thes corresponding environm...
[ "def", "setting", "(", "self", ",", "name_hyphen", ")", ":", "if", "name_hyphen", "in", "self", ".", "_instance_settings", ":", "value", "=", "self", ".", "_instance_settings", "[", "name_hyphen", "]", "[", "1", "]", "else", ":", "msg", "=", "\"No setting ...
37.851852
20.148148
def get_category(self): """Get the category of the item. :return: the category of the item. :returntype: `unicode`""" var = self.xmlnode.prop("category") if not var: var = "?" return var.decode("utf-8")
[ "def", "get_category", "(", "self", ")", ":", "var", "=", "self", ".", "xmlnode", ".", "prop", "(", "\"category\"", ")", "if", "not", "var", ":", "var", "=", "\"?\"", "return", "var", ".", "decode", "(", "\"utf-8\"", ")" ]
28.333333
12
def change_option(self, option_name, new_value): """ Change a config option. This function is called if sig_option_changed is received. If the option changed is the dataframe format, then the leading '%' character is stripped (because it can't be stored in the user config)...
[ "def", "change_option", "(", "self", ",", "option_name", ",", "new_value", ")", ":", "if", "option_name", "==", "'dataframe_format'", ":", "assert", "new_value", ".", "startswith", "(", "'%'", ")", "new_value", "=", "new_value", "[", "1", ":", "]", "self", ...
44.214286
17.928571
def set_attributes(d, elm): """Set attributes from dictionary of values.""" for key in d: elm.setAttribute(key, d[key])
[ "def", "set_attributes", "(", "d", ",", "elm", ")", ":", "for", "key", "in", "d", ":", "elm", ".", "setAttribute", "(", "key", ",", "d", "[", "key", "]", ")" ]
33
9.75
def hungarian(A, B): """ Hungarian reordering. Assume A and B are coordinates for atoms of SAME type only """ # should be kabasch here i think distances = cdist(A, B, 'euclidean') # Perform Hungarian analysis on distance matrix between atoms of 1st # structure and trial structure ...
[ "def", "hungarian", "(", "A", ",", "B", ")", ":", "# should be kabasch here i think", "distances", "=", "cdist", "(", "A", ",", "B", ",", "'euclidean'", ")", "# Perform Hungarian analysis on distance matrix between atoms of 1st", "# structure and trial structure", "indices_...
25.533333
19.8
def absent(name, auth=None): ''' Ensure domain does not exist name Name of the domain ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} __salt__['keystoneng.setup_clouds'](auth) domain = __salt__['keystoneng.domain_get'](name=n...
[ "def", "absent", "(", "name", ",", "auth", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "__salt__", "[", "'keystoneng.setup_clouds'", "...
24.25
20.964286
def parse_args(arglist=None): """Parse cmd line arguments. Update :attr:`stagpy.conf` accordingly. Args: arglist (list of str): the list of cmd line arguments. If set to None, the arguments are taken from :attr:`sys.argv`. Returns: function: the function implementing the s...
[ "def", "parse_args", "(", "arglist", "=", "None", ")", ":", "climan", "=", "CLIManager", "(", "conf", ",", "*", "*", "SUB_CMDS", ")", "create_complete_files", "(", "climan", ",", "CONFIG_DIR", ",", "'stagpy'", ",", "'stagpy-git'", ",", "zsh_sourceable", "=",...
24.615385
22.384615
def init_registry(mongo, model_defs, clear_collection=False): """Initialize a model registry with a list of model definitions in Json format. Parameters ---------- mongo : scodata.MongoDBFactory Connector for MongoDB model_defs : list() List of model definitions in Json-like for...
[ "def", "init_registry", "(", "mongo", ",", "model_defs", ",", "clear_collection", "=", "False", ")", ":", "# Create model registry", "registry", "=", "SCOEngine", "(", "mongo", ")", ".", "registry", "# Drop collection if clear flag is set to True", "if", "clear_collecti...
31.925926
14.222222
def stencils(self): """List of stencils.""" if not self._stencils: self._stencils = self.manifest['stencils'] return self._stencils
[ "def", "stencils", "(", "self", ")", ":", "if", "not", "self", ".", "_stencils", ":", "self", ".", "_stencils", "=", "self", ".", "manifest", "[", "'stencils'", "]", "return", "self", ".", "_stencils" ]
32.6
11.2
def dist(self, src, tar, probs=None): """Return the NCD between two strings using arithmetic coding. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison probs : dict A dictionary trained ...
[ "def", "dist", "(", "self", ",", "src", ",", "tar", ",", "probs", "=", "None", ")", ":", "if", "src", "==", "tar", ":", "return", "0.0", "if", "probs", "is", "None", ":", "# lacking a reasonable dictionary, train on the strings themselves", "self", ".", "_co...
27.404255
18.276596
def get_type_string(item): """Return type string of an object.""" if isinstance(item, DataFrame): return "DataFrame" if isinstance(item, Index): return type(item).__name__ if isinstance(item, Series): return "Series" found = re.findall(r"<(?:type|class) '(\S*)'>", ...
[ "def", "get_type_string", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "DataFrame", ")", ":", "return", "\"DataFrame\"", "if", "isinstance", "(", "item", ",", "Index", ")", ":", "return", "type", "(", "item", ")", ".", "__name__", "if", ...
32.166667
11.5
def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) ...
[ "def", "get_zones", "(", "self", ")", ":", "home_data", "=", "self", ".", "get_home", "(", ")", "if", "not", "home_data", "[", "'isSuccess'", "]", ":", "return", "[", "]", "zones", "=", "[", "]", "for", "receiver", "in", "home_data", "[", "'data'", "...
21.733333
16.666667
def jsonGraph(fdefs,calls,outfile='nout.json'): '''For reference, each node has: node.name (string) node.source (string) node.weight (int) node.pclass (class node object) Each call contains a node in call.source and call.target ''' outpath = os.path.join('data',outfile) ...
[ "def", "jsonGraph", "(", "fdefs", ",", "calls", ",", "outfile", "=", "'nout.json'", ")", ":", "outpath", "=", "os", ".", "path", ".", "join", "(", "'data'", ",", "outfile", ")", "data", "=", "dict", "(", ")", "ids", "=", "dict", "(", ")", "nodelist...
29.634146
14.609756
def _handleMessage(self, src_socket, msg): ''' :returns: :data:`python:True` if the connect has been disconnected and :data:`python:False` if the connection is still alive and everything was processed normally ''' self._logger.debug('Message received: ...
[ "def", "_handleMessage", "(", "self", ",", "src_socket", ",", "msg", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Message received: {!r}'", ".", "format", "(", "msg", ")", ")", "# Check where the message came from and determine where it's going", "if", "sr...
38.833333
20.291667
def shutdown(self): """shutdown connection""" if self.verbose: print(self.socket.getsockname(), 'xx', self.peername) try: self.socket.shutdown(socket.SHUT_RDWR) except IOError as err: assert err.errno is _ENOTCONN, "unexpected IOError: %s" % err ...
[ "def", "shutdown", "(", "self", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "self", ".", "socket", ".", "getsockname", "(", ")", ",", "'xx'", ",", "self", ".", "peername", ")", "try", ":", "self", ".", "socket", ".", "shutdown", "(",...
32.461538
20.538462
def isdigit(cls, value): """ ditit check for stats :param value: stats value :return: True or False """ if str(value).replace('.','').replace('-','').isdigit(): return True return False
[ "def", "isdigit", "(", "cls", ",", "value", ")", ":", "if", "str", "(", "value", ")", ".", "replace", "(", "'.'", ",", "''", ")", ".", "replace", "(", "'-'", ",", "''", ")", ".", "isdigit", "(", ")", ":", "return", "True", "return", "False" ]
27.222222
11.666667
def tokens(self): """ Access the tokens :returns: twilio.rest.api.v2010.account.token.TokenList :rtype: twilio.rest.api.v2010.account.token.TokenList """ if self._tokens is None: self._tokens = TokenList(self._version, account_sid=self._solution['sid'], ) ...
[ "def", "tokens", "(", "self", ")", ":", "if", "self", ".", "_tokens", "is", "None", ":", "self", ".", "_tokens", "=", "TokenList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "return",...
33.5
19.1
def get_predicate(self, cmd=False, pred=None): """Get the current default `Plugin` or command predicate. If the `cmd` argument is `True`, the current command predicate is returned if set, otherwise the default `Plugin` predicate will be returned (which may be `None`). ...
[ "def", "get_predicate", "(", "self", ",", "cmd", "=", "False", ",", "pred", "=", "None", ")", ":", "if", "pred", "is", "not", "None", ":", "return", "pred", "if", "cmd", "and", "self", ".", "cmd_predicate", "is", "not", "None", ":", "return", "self",...
42.071429
14.857143
def is_erroneous(self, field, sources): """Check if attribute has been marked as being erroneous.""" if self._KEYS.ERRORS in self: my_errors = self[self._KEYS.ERRORS] for alias in sources.split(','): source = self.get_source_by_alias(alias) bib_err...
[ "def", "is_erroneous", "(", "self", ",", "field", ",", "sources", ")", ":", "if", "self", ".", "_KEYS", ".", "ERRORS", "in", "self", ":", "my_errors", "=", "self", "[", "self", ".", "_KEYS", ".", "ERRORS", "]", "for", "alias", "in", "sources", ".", ...
40.8
15.2
def parse(self): """ Retreive and parse Event Summary report for the given :py:class:`nhlscrapi.games.game.GameKey` :returns: ``self`` on success, ``None`` otherwise """ try: return super(EventSummRep, self).parse() \ .parse_away_shots() \ ...
[ "def", "parse", "(", "self", ")", ":", "try", ":", "return", "super", "(", "EventSummRep", ",", "self", ")", ".", "parse", "(", ")", ".", "parse_away_shots", "(", ")", ".", "parse_home_shots", "(", ")", ".", "parse_away_fo", "(", ")", ".", "parse_home_...
33.1875
14.9375
def convert_the_getters(getters): """ A function used to prepare the arguments of calculator and atoms getter methods """ return_list = [] for getter in getters: if isinstance(getter,basestring): out_args = "" method_name = getter else: ...
[ "def", "convert_the_getters", "(", "getters", ")", ":", "return_list", "=", "[", "]", "for", "getter", "in", "getters", ":", "if", "isinstance", "(", "getter", ",", "basestring", ")", ":", "out_args", "=", "\"\"", "method_name", "=", "getter", "else", ":",...
26.833333
16.055556
def get_redirect_url(self, **kwargs): """ Redirect to request parameter 'next' or to referrer if url is not defined. """ if self.request.REQUEST.has_key('next'): return self.request.REQUEST.get('next') url = RedirectView.get_redirect_url(self, **kwargs) if u...
[ "def", "get_redirect_url", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "request", ".", "REQUEST", ".", "has_key", "(", "'next'", ")", ":", "return", "self", ".", "request", ".", "REQUEST", ".", "get", "(", "'next'", ")", "url",...
39
14
def provideObjectToInfer(self, inferenceConfig): """ Returns the sensations in a canonical format to be sent to an experiment. The input inferenceConfig should be a dict with the following form: { "numSteps": 2 # number of sensations for each column "pairs": { 0: [(1, 2), (2, 2)] ...
[ "def", "provideObjectToInfer", "(", "self", ",", "inferenceConfig", ")", ":", "numSteps", "=", "inferenceConfig", ".", "get", "(", "\"numSteps\"", ",", "len", "(", "inferenceConfig", "[", "\"pairs\"", "]", "[", "0", "]", ")", ")", "# some checks", "if", "num...
39.952381
24.746032
def _set_ext_vni(self, v, load=False): """ Setter method for ext_vni, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/ext_vni (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_ext_vni is considered as a private method. Backends looki...
[ "def", "_set_ext_vni", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base",...
96.181818
46.272727
def import_module(self, name): """Import a module into the bridge.""" if name not in self._objects: module = _import_module(name) self._objects[name] = module self._object_references[id(module)] = name return self._objects[name]
[ "def", "import_module", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "_objects", ":", "module", "=", "_import_module", "(", "name", ")", "self", ".", "_objects", "[", "name", "]", "=", "module", "self", ".", "_object_refe...
40.285714
4.857143
def locate(connection, agent_id): ''' Return the hostname of the agency where given agent runs or None. ''' connection = IDatabaseClient(connection) log.log('locate', 'Locate called for agent_id: %r', agent_id) try: desc = yield connection.get_document(agent_id) log.log('locate',...
[ "def", "locate", "(", "connection", ",", "agent_id", ")", ":", "connection", "=", "IDatabaseClient", "(", "connection", ")", "log", ".", "log", "(", "'locate'", ",", "'Locate called for agent_id: %r'", ",", "agent_id", ")", "try", ":", "desc", "=", "yield", ...
42.347826
16.695652
def deactivate(name): """Deactivate plugin. Parameters ---------- name : str Plugin name. """ if name in plugins: plugins[name].deactivate() else: raise Exception("plugin {} not found".format(name))
[ "def", "deactivate", "(", "name", ")", ":", "if", "name", "in", "plugins", ":", "plugins", "[", "name", "]", ".", "deactivate", "(", ")", "else", ":", "raise", "Exception", "(", "\"plugin {} not found\"", ".", "format", "(", "name", ")", ")" ]
20
19.166667
def get_abs_template_path(template_name, directory, extension): """ Given a template name, a directory, and an extension, return the absolute path to the template. """ # Get the relative path relative_path = join(directory, template_name) file_with_ext = template_name if extension: # If...
[ "def", "get_abs_template_path", "(", "template_name", ",", "directory", ",", "extension", ")", ":", "# Get the relative path", "relative_path", "=", "join", "(", "directory", ",", "template_name", ")", "file_with_ext", "=", "template_name", "if", "extension", ":", "...
40.176471
15.705882
def disassemble(self, start=None, end=None, arch_mode=None): """Disassemble native instructions. Args: start (int): Start address. end (int): End address. arch_mode (int): Architecture mode. Returns: (int, Instruction, int): A tuple of the form (...
[ "def", "disassemble", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "arch_mode", "=", "None", ")", ":", "if", "arch_mode", "is", "None", ":", "arch_mode", "=", "self", ".", "binary", ".", "architecture_mode", "curr_addr", "=", "...
32.290323
21.709677
def bilinear_interpolation_weights(lon, lat, nside, order='ring'): """ Get the four neighbours for each (lon, lat) position and the weight associated with each one for bilinear interpolation. Parameters ---------- lon, lat : :class:`~astropy.units.Quantity` The longitude and latitude va...
[ "def", "bilinear_interpolation_weights", "(", "lon", ",", "lat", ",", "nside", ",", "order", "=", "'ring'", ")", ":", "lon", "=", "lon", ".", "to_value", "(", "u", ".", "rad", ")", "lat", "=", "lat", ".", "to_value", "(", "u", ".", "rad", ")", "_va...
30.125
21.525
def find_template_filename(self, template_name): """ Searches for a file matching the given template name. If found, this method returns the pathlib.Path object of the found template file. Args: template_name (str): Name of the template, with or without a file ...
[ "def", "find_template_filename", "(", "self", ",", "template_name", ")", ":", "def", "next_file", "(", ")", ":", "filename", "=", "self", ".", "path", "/", "template_name", "yield", "filename", "try", ":", "exts", "=", "self", ".", "default_file_extensions", ...
28.3
19.1
def present_active(self): """ Weak verbs I >>> verb = WeakOldNorseVerb() >>> verb.set_canonic_forms(["kalla", "kallaði", "kallaðinn"]) >>> verb.present_active() ['kalla', 'kallar', 'kallar', 'köllum', 'kallið', 'kalla'] II >>> verb = WeakOldNorseV...
[ "def", "present_active", "(", "self", ")", ":", "forms", "=", "[", "]", "stem_ending_by_j", "=", "self", ".", "sng", "[", "-", "1", "]", "==", "\"a\"", "and", "self", ".", "sng", "[", "-", "2", "]", "==", "\"j\"", "stem_ending_by_v", "=", "self", "...
36.859259
13.6
def _TypecheckDecorator(subject=None, **kwargs): """Dispatches type checks based on what the subject is. Functions or methods are annotated directly. If this method is called with keyword arguments only, return a decorator. """ if subject is None: return _TypecheckDecoratorFactory(kwargs) elif inspect....
[ "def", "_TypecheckDecorator", "(", "subject", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "subject", "is", "None", ":", "return", "_TypecheckDecoratorFactory", "(", "kwargs", ")", "elif", "inspect", ".", "isfunction", "(", "subject", ")", "or", "...
36.666667
16.666667
def searchlast(self,n=10): """Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.""" solutions = deque([], n) for solution in self: solutions.append(solution) return...
[ "def", "searchlast", "(", "self", ",", "n", "=", "10", ")", ":", "solutions", "=", "deque", "(", "[", "]", ",", "n", ")", "for", "solution", "in", "self", ":", "solutions", ".", "append", "(", "solution", ")", "return", "solutions" ]
54.166667
8.5
def create_add_on(self, add_on): """Make the given `AddOn` available to subscribers on this plan.""" url = urljoin(self._url, '/add_ons') return add_on.post(url)
[ "def", "create_add_on", "(", "self", ",", "add_on", ")", ":", "url", "=", "urljoin", "(", "self", ".", "_url", ",", "'/add_ons'", ")", "return", "add_on", ".", "post", "(", "url", ")" ]
45.5
5.25
def __densify_border(self): """ Densify the border of a polygon. The border is densified by a given factor (by default: 0.5). The complexity of the polygon's geometry is evaluated in order to densify the borders of its interior rings as well. Returns: list:...
[ "def", "__densify_border", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_input_geom", ",", "MultiPolygon", ")", ":", "polygons", "=", "[", "polygon", "for", "polygon", "in", "self", ".", "_input_geom", "]", "else", ":", "polygons", "=", ...
32.594595
22.216216
def get_image(self, source): """ Returns the backend image objects from a ImageFile instance """ with NamedTemporaryFile(mode='wb', delete=False) as fp: fp.write(source.read()) return {'source': fp.name, 'options': OrderedDict(), 'size': None}
[ "def", "get_image", "(", "self", ",", "source", ")", ":", "with", "NamedTemporaryFile", "(", "mode", "=", "'wb'", ",", "delete", "=", "False", ")", "as", "fp", ":", "fp", ".", "write", "(", "source", ".", "read", "(", ")", ")", "return", "{", "'sou...
41.285714
14.428571
def set_params(self, **params): """ Set the parameters of this estimator. Returns ------- self """ valid_params = self.get_params() for key, value in params.items(): if key not in valid_params: raise ValueError( ...
[ "def", "set_params", "(", "self", ",", "*", "*", "params", ")", ":", "valid_params", "=", "self", ".", "get_params", "(", ")", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "key", "not", "in", "valid_params", ":", "...
24.958333
19.208333
def verify_compact_verbose(self, jws=None, keys=None, allow_none=False, sigalg=None): """ Verify a JWT signature and return dict with validation results :param jws: A signed JSON Web Token :param keys: A list of keys that can possibly be used to verify the...
[ "def", "verify_compact_verbose", "(", "self", ",", "jws", "=", "None", ",", "keys", "=", "None", ",", "allow_none", "=", "False", ",", "sigalg", "=", "None", ")", ":", "if", "jws", ":", "jwt", "=", "JWSig", "(", ")", ".", "unpack", "(", "jws", ")",...
35.304348
18.130435
def update_context(cls, base_context, str_or_dict, template_path=None): """Helper method to structure initial message context data. NOTE: updates `base_context` inplace. :param dict base_context: context dict to update :param dict, str str_or_dict: text representing a message, or a dic...
[ "def", "update_context", "(", "cls", ",", "base_context", ",", "str_or_dict", ",", "template_path", "=", "None", ")", ":", "if", "isinstance", "(", "str_or_dict", ",", "dict", ")", ":", "base_context", ".", "update", "(", "str_or_dict", ")", "base_context", ...
40.526316
20.315789