text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _validate_message(self, message): """Validate XML response from iLO. This function validates the XML response to see if the exit status is 0 or not in the response. If the status is non-zero it raises exception. """ if message.tag != 'RIBCL': # the true c...
[ "def", "_validate_message", "(", "self", ",", "message", ")", ":", "if", "message", ".", "tag", "!=", "'RIBCL'", ":", "# the true case shall be unreachable for response", "# XML from Ilo as all messages are tagged with RIBCL", "# but still raise an exception if any invalid", "# X...
49.45098
18.45098
def hello(): """"http://click.pocoo.org/5/ http://click.pocoo.org/5/api/ """ click.clear() click.secho('Hello World!', fg='green') click.secho('Some more text', bg='blue', fg='white') click.secho('ATTENTION', blink=True, bold=True) click.echo('Continue? [yn] ', nl=False) c = click.g...
[ "def", "hello", "(", ")", ":", "click", ".", "clear", "(", ")", "click", ".", "secho", "(", "'Hello World!'", ",", "fg", "=", "'green'", ")", "click", ".", "secho", "(", "'Some more text'", ",", "bg", "=", "'blue'", ",", "fg", "=", "'white'", ")", ...
29.1
14.6
def trunc(text, length): """ Truncates text to given length, taking into account wide characters. If truncated, the last char is replaced by an elipsis. """ if length < 1: raise ValueError("length should be 1 or larger") # Remove whitespace first so no unneccesary truncation is done. ...
[ "def", "trunc", "(", "text", ",", "length", ")", ":", "if", "length", "<", "1", ":", "raise", "ValueError", "(", "\"length should be 1 or larger\"", ")", "# Remove whitespace first so no unneccesary truncation is done.", "text", "=", "text", ".", "strip", "(", ")", ...
31.5
19.833333
def get_image_size(self, token, resolution=0): """ Return the size of the volume (3D). Convenient for when you want to download the entirety of a dataset. Arguments: token (str): The token for which to find the dataset image bounds resolution (int : 0): The resol...
[ "def", "get_image_size", "(", "self", ",", "token", ",", "resolution", "=", "0", ")", ":", "info", "=", "self", ".", "get_proj_info", "(", "token", ")", "res", "=", "str", "(", "resolution", ")", "if", "res", "not", "in", "info", "[", "'dataset'", "]...
42.304348
22.391304
def draw(molecule, TraversalType=SmilesTraversal): """(molecule)->canonical representation of a molecule Well, it's only canonical if the atom symorders are canonical, otherwise it's arbitrary. atoms must have a symorder attribute bonds must have a equiv_class attribute""" result = [] atoms...
[ "def", "draw", "(", "molecule", ",", "TraversalType", "=", "SmilesTraversal", ")", ":", "result", "=", "[", "]", "atoms", "=", "allAtoms", "=", "molecule", ".", "atoms", "visitedAtoms", "=", "{", "}", "#", "# Traverse all components of the graph to form", "# the...
29.952381
15.166667
def _read_mptcp_prio(self, bits, size): """Read Change Subflow Priority option. Positional arguments: * bits - str, 4-bit data * size - int, length of option Returns: * dict -- extracted Change Subflow Priority (MP_PRIO) option Structure of MP_PRIO ...
[ "def", "_read_mptcp_prio", "(", "self", ",", "bits", ",", "size", ")", ":", "temp", "=", "self", ".", "_read_unpack", "(", "1", ")", "if", "size", "else", "None", "data", "=", "dict", "(", "subtype", "=", "'MP_PRIO'", ",", "prio", "=", "dict", "(", ...
38.189189
23.972973
def get_file_encoding(self, file_path, preferred_encoding=None): """ Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding. ...
[ "def", "get_file_encoding", "(", "self", ",", "file_path", ",", "preferred_encoding", "=", "None", ")", ":", "_logger", "(", ")", ".", "debug", "(", "'getting encoding for %s'", ",", "file_path", ")", "try", ":", "map", "=", "json", ".", "loads", "(", "sel...
35.967742
17.322581
def send(self, event): # type(Event) -> bytes """Send an event to the remote. This will return the bytes to send based on the event or raise a LocalProtocolError if the event is not valid given the state. """ data = b"" if isinstance(event, Request): ...
[ "def", "send", "(", "self", ",", "event", ")", ":", "# type(Event) -> bytes", "data", "=", "b\"\"", "if", "isinstance", "(", "event", ",", "Request", ")", ":", "data", "+=", "self", ".", "_initiate_connection", "(", "event", ")", "elif", "isinstance", "(",...
34.086957
16.086957
def purcell(target, r_toroid, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', diameter='throat.diameter'): r""" Computes the throat capillary entry pressure assuming the throat is a toroid. Parameters ---------- target : OpenPNM Object ...
[ "def", "purcell", "(", "target", ",", "r_toroid", ",", "surface_tension", "=", "'pore.surface_tension'", ",", "contact_angle", "=", "'pore.contact_angle'", ",", "diameter", "=", "'throat.diameter'", ")", ":", "network", "=", "target", ".", "project", ".", "network...
40.348485
23.666667
def force_populate(self): """ Populates the parser with the entire contents of the word reference file. """ if not os.path.exists(self.ref): raise FileNotFoundError("The reference file path '{}' does not exists.".format(self.ref)) with open(self.ref, 'r') as f...
[ "def", "force_populate", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "ref", ")", ":", "raise", "FileNotFoundError", "(", "\"The reference file path '{}' does not exists.\"", ".", "format", "(", "self", ".", "ref", ...
36.75
11.916667
def part_specs(self, part): ''' returns the specifications of the given part. If multiple parts are matched, only the first one will be output. part: the productname or sku prints the results on stdout ''' result = self._e.parts_match( queries=[{'mpn...
[ "def", "part_specs", "(", "self", ",", "part", ")", ":", "result", "=", "self", ".", "_e", ".", "parts_match", "(", "queries", "=", "[", "{", "'mpn_or_sku'", ":", "part", "}", "]", ",", "exact_only", "=", "True", ",", "show_mpn", "=", "True", ",", ...
48.076923
19.102564
def vectorize(fn): """ Allows a method to accept one or more values, but internally deal only with a single item, and returning a list or a single item depending on what is desired. """ @functools.wraps(fn) def vectorized_method(self, values, *vargs, **kwargs): wrap = not isinst...
[ "def", "vectorize", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "vectorized_method", "(", "self", ",", "values", ",", "*", "vargs", ",", "*", "*", "kwargs", ")", ":", "wrap", "=", "not", "isinstance", "(", "values", ...
26.461538
19.538462
def gaussian(h, Xi, x): """ Gaussian Kernel for continuous variables Parameters ---------- h : 1-D ndarray, shape (K,) The bandwidths used to estimate the value of the kernel function. Xi : 1-D ndarray, shape (K,) The value of the training set. x : 1-D ndarray, shape (K,) ...
[ "def", "gaussian", "(", "h", ",", "Xi", ",", "x", ")", ":", "return", "(", "1.", "/", "np", ".", "sqrt", "(", "2", "*", "np", ".", "pi", ")", ")", "*", "np", ".", "exp", "(", "-", "(", "Xi", "-", "x", ")", "**", "2", "/", "(", "h", "*...
31.263158
19.473684
def xbm(self, scale=1, quiet_zone=4): """Returns a string representing an XBM image of the QR code. The XBM format is a black and white image format that looks like a C header file. Because displaying QR codes in Tkinter is the primary use case for this renderer, this m...
[ "def", "xbm", "(", "self", ",", "scale", "=", "1", ",", "quiet_zone", "=", "4", ")", ":", "return", "builder", ".", "_xbm", "(", "self", ".", "code", ",", "scale", ",", "quiet_zone", ")" ]
49.405405
23.351351
def _datetime_view( request, template, dt, timeslot_factory=None, items=None, params=None ): ''' Build a time slot grid representation for the given datetime ``dt``. See utils.create_timeslot_table documentation for items and params. Context parameters: ``day`` the ...
[ "def", "_datetime_view", "(", "request", ",", "template", ",", "dt", ",", "timeslot_factory", "=", "None", ",", "items", "=", "None", ",", "params", "=", "None", ")", ":", "timeslot_factory", "=", "timeslot_factory", "or", "utils", ".", "create_timeslot_table"...
21.75
25.25
def raise_exception(self, exception, tup=None): """Report an exception back to Storm via logging. :param exception: a Python exception. :param tup: a :class:`Tuple` object. """ if tup: message = ( "Python {exception_name} raised while processing Tuple...
[ "def", "raise_exception", "(", "self", ",", "exception", ",", "tup", "=", "None", ")", ":", "if", "tup", ":", "message", "=", "(", "\"Python {exception_name} raised while processing Tuple \"", "\"{tup!r}\\n{traceback}\"", ")", "else", ":", "message", "=", "\"Python ...
38.277778
18.5
def floatformat(fmt_string): """ Context manager to change the default format string for the function :func:`openquake.commonlib.writers.scientificformat`. :param fmt_string: the format to use; for instance '%13.9E' """ fmt_defaults = scientificformat.__defaults__ scientificformat.__default...
[ "def", "floatformat", "(", "fmt_string", ")", ":", "fmt_defaults", "=", "scientificformat", ".", "__defaults__", "scientificformat", ".", "__defaults__", "=", "(", "fmt_string", ",", ")", "+", "fmt_defaults", "[", "1", ":", "]", "try", ":", "yield", "finally",...
33.461538
19.923077
def parse_directory_index(directory_index): """ Retrieve a directory index and make a list of the RPMs listed. """ # Normalize our URL style if not directory_index.endswith('/'): directory_index = directory_index + '/' site_index = urllib2.urlopen(directory_index) parsed_site_index ...
[ "def", "parse_directory_index", "(", "directory_index", ")", ":", "# Normalize our URL style", "if", "not", "directory_index", ".", "endswith", "(", "'/'", ")", ":", "directory_index", "=", "directory_index", "+", "'/'", "site_index", "=", "urllib2", ".", "urlopen",...
37.157895
20.736842
def parse(self): """ Return the list of string of all the decorators found """ self._parse(self.method) return list(set([deco for deco in self.decos if deco]))
[ "def", "parse", "(", "self", ")", ":", "self", ".", "_parse", "(", "self", ".", "method", ")", "return", "list", "(", "set", "(", "[", "deco", "for", "deco", "in", "self", ".", "decos", "if", "deco", "]", ")", ")" ]
32.333333
12.666667
def find_bounds(model): """ Return the median upper and lower bound of the metabolic model. Bounds can vary from model to model. Cobrapy defaults to (-1000, 1000) but this may not be the case for merged or autogenerated models. In these cases, this function is used to iterate over all the bounds of...
[ "def", "find_bounds", "(", "model", ")", ":", "lower_bounds", "=", "np", ".", "asarray", "(", "[", "rxn", ".", "lower_bound", "for", "rxn", "in", "model", ".", "reactions", "]", ",", "dtype", "=", "float", ")", "upper_bounds", "=", "np", ".", "asarray"...
40.896552
20.827586
def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" url = '{}/userinfo'.format(self.BASE_URL) response = self.get_json( url, headers={'Authorization': 'Bearer ' + access_token}, ) self.check_correct_audience(response['aud...
[ "def", "user_data", "(", "self", ",", "access_token", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "url", "=", "'{}/userinfo'", ".", "format", "(", "self", ".", "BASE_URL", ")", "response", "=", "self", ".", "get_json", "(", "url", ",", "head...
34.454545
16.818182
def _fullClone(self, shallowClone=False): """Perform full clone and checkout to the revision if specified In the case of shallow clones if any of the step fail abort whole build step. """ res = yield self._clone(shallowClone) if res != RC_SUCCESS: return res ...
[ "def", "_fullClone", "(", "self", ",", "shallowClone", "=", "False", ")", ":", "res", "=", "yield", "self", ".", "_clone", "(", "shallowClone", ")", "if", "res", "!=", "RC_SUCCESS", ":", "return", "res", "# If revision specified checkout that revision", "if", ...
41.809524
18
def concat(attrs, inputs, proto_obj): """ Joins input arrays along a given axis. """ new_attrs = translation_utils._fix_attribute_names(attrs, {'axis': 'dim'}) return 'concat', new_attrs, inputs
[ "def", "concat", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'axis'", ":", "'dim'", "}", ")", "return", "'concat'", ",", "new_attrs", ",", "inputs" ]
50.75
10.75
def encrypt_message(self, reply, timestamp=None, nonce=None): """ 加密微信回复 :param reply: 加密前的回复 :type reply: WeChatReply 或 XML 文本 :return: 加密后的回复文本 """ if hasattr(reply, "render"): reply = reply.render() timestamp = timestamp or to_text(int(time...
[ "def", "encrypt_message", "(", "self", ",", "reply", ",", "timestamp", "=", "None", ",", "nonce", "=", "None", ")", ":", "if", "hasattr", "(", "reply", ",", "\"render\"", ")", ":", "reply", "=", "reply", ".", "render", "(", ")", "timestamp", "=", "ti...
32.954545
14.409091
def getRotatedSize(corners, angle): """ Determine the size of a rotated (meta)image.""" if angle: _rotm = fileutil.buildRotMatrix(angle) # Rotate about the center _corners = np.dot(corners, _rotm) else: # If there is no rotation, simply return original values _corners...
[ "def", "getRotatedSize", "(", "corners", ",", "angle", ")", ":", "if", "angle", ":", "_rotm", "=", "fileutil", ".", "buildRotMatrix", "(", "angle", ")", "# Rotate about the center", "_corners", "=", "np", ".", "dot", "(", "corners", ",", "_rotm", ")", "els...
32.272727
14.727273
def prt_goids(self, goids=None, prtfmt=None, sortby=True, prt=sys.stdout): """Given GO IDs, print decriptive info about each GO Term.""" if goids is None: goids = self.go_sources nts = self.get_nts(goids, sortby) if prtfmt is None: prtfmt = self.prt_attr['fmta'] ...
[ "def", "prt_goids", "(", "self", ",", "goids", "=", "None", ",", "prtfmt", "=", "None", ",", "sortby", "=", "True", ",", "prt", "=", "sys", ".", "stdout", ")", ":", "if", "goids", "is", "None", ":", "goids", "=", "self", ".", "go_sources", "nts", ...
41.545455
12.727273
def gmst(utc_time): """Greenwich mean sidereal utc_time, in radians. As defined in the AIAA 2006 implementation: http://www.celestrak.com/publications/AIAA/2006-6753/ """ ut1 = jdays2000(utc_time) / 36525.0 theta = 67310.54841 + ut1 * (876600 * 3600 + 8640184.812866 + ut1 * ...
[ "def", "gmst", "(", "utc_time", ")", ":", "ut1", "=", "jdays2000", "(", "utc_time", ")", "/", "36525.0", "theta", "=", "67310.54841", "+", "ut1", "*", "(", "876600", "*", "3600", "+", "8640184.812866", "+", "ut1", "*", "(", "0.093104", "-", "ut1", "*...
40.6
15.1
def instaprint(figure='gcf', arguments='', threaded=False, file_format='pdf'): """ Quick function that saves the specified figure as a postscript and then calls the command defined by spinmob.prefs['instaprint'] with this postscript file as the argument. figure='gcf' can be 'all', a number, or a...
[ "def", "instaprint", "(", "figure", "=", "'gcf'", ",", "arguments", "=", "''", ",", "threaded", "=", "False", ",", "file_format", "=", "'pdf'", ")", ":", "global", "_settings", "if", "'instaprint'", "not", "in", "_settings", ".", "keys", "(", ")", ":", ...
33.583333
24.125
def n_join(self, other, psi=-40.76, omega=-178.25, phi=-65.07, o_c_n_angle=None, c_n_ca_angle=None, c_n_length=None, relabel=True): """Joins other to self at the N-terminus via a peptide bond. Notes ----- This function directly modifies self. It does not return a new obje...
[ "def", "n_join", "(", "self", ",", "other", ",", "psi", "=", "-", "40.76", ",", "omega", "=", "-", "178.25", ",", "phi", "=", "-", "65.07", ",", "o_c_n_angle", "=", "None", ",", "c_n_ca_angle", "=", "None", ",", "c_n_length", "=", "None", ",", "rel...
46.94
19.45
def update_network(self, network, body=None): """Updates a network.""" return self.put(self.network_path % (network), body=body)
[ "def", "update_network", "(", "self", ",", "network", ",", "body", "=", "None", ")", ":", "return", "self", ".", "put", "(", "self", ".", "network_path", "%", "(", "network", ")", ",", "body", "=", "body", ")" ]
47.333333
10
def validate_string_list(lst): """Validate that the input is a list of strings. Raises ValueError if not.""" if not isinstance(lst, list): raise ValueError('input %r must be a list' % lst) for x in lst: if not isinstance(x, basestring): raise ValueError('element %r in list m...
[ "def", "validate_string_list", "(", "lst", ")", ":", "if", "not", "isinstance", "(", "lst", ",", "list", ")", ":", "raise", "ValueError", "(", "'input %r must be a list'", "%", "lst", ")", "for", "x", "in", "lst", ":", "if", "not", "isinstance", "(", "x"...
37
14.333333
def list( self, skiptoken=None, skip=None, top=None, select=None, search=None, filter=None, view=None, group_name=None, cache_control="no-cache", custom_headers=None, raw=False, **operation_config): """List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. ...
[ "def", "list", "(", "self", ",", "skiptoken", "=", "None", ",", "skip", "=", "None", ",", "top", "=", "None", ",", "select", "=", "None", ",", "search", "=", "None", ",", "filter", "=", "None", ",", "view", "=", "None", ",", "group_name", "=", "N...
54.047619
28.68254
def _put(self, *args, **kwargs): """ A wrapper for putting things. It will also json encode your 'data' parameter :returns: The response of your put :rtype: dict """ if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) response = requests....
[ "def", "_put", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "'data'", "in", "kwargs", ":", "kwargs", "[", "'data'", "]", "=", "json", ".", "dumps", "(", "kwargs", "[", "'data'", "]", ")", "response", "=", "requests", "....
33.272727
14
def _parse_bounding_box(bounding_box): ''' Parse response bounding box from the CapakeyRestGateway to (MinimumX, MinimumY, MaximumX, MaximumY) :param bounding_box: response bounding box from the CapakeyRestGateway :return: (MinimumX, MinimumY, MaximumX, MaximumY) ''' ...
[ "def", "_parse_bounding_box", "(", "bounding_box", ")", ":", "coordinates", "=", "json", ".", "loads", "(", "bounding_box", ")", "[", "\"coordinates\"", "]", "x_coords", "=", "[", "x", "for", "x", ",", "y", "in", "coordinates", "[", "0", "]", "]", "y_coo...
49.272727
26
def serialize(self): """ Serializes the Peer data as a simple JSON map string. """ return json.dumps({ "name": self.name, "ip": self.ip, "port": self.port }, sort_keys=True)
[ "def", "serialize", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "{", "\"name\"", ":", "self", ".", "name", ",", "\"ip\"", ":", "self", ".", "ip", ",", "\"port\"", ":", "self", ".", "port", "}", ",", "sort_keys", "=", "True", ")" ]
26.777778
11.444444
def context_include(zap_helper, name, pattern): """Include a pattern in a given context.""" console.info('Including regex {0} in context with name: {1}'.format(pattern, name)) with zap_error_handler(): result = zap_helper.zap.context.include_in_context(contextname=name, regex=pattern) if re...
[ "def", "context_include", "(", "zap_helper", ",", "name", ",", "pattern", ")", ":", "console", ".", "info", "(", "'Including regex {0} in context with name: {1}'", ".", "format", "(", "pattern", ",", "name", ")", ")", "with", "zap_error_handler", "(", ")", ":", ...
51.375
26.75
async def disable_user(self, username): """Disable a user. :param str username: Username """ user_facade = client.UserManagerFacade.from_connection( self.connection()) entity = client.Entity(tag.user(username)) return await user_facade.DisableUser([entity])
[ "async", "def", "disable_user", "(", "self", ",", "username", ")", ":", "user_facade", "=", "client", ".", "UserManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "entity", "=", "client", ".", "Entity", "(", "tag", ".", ...
31
14.1
def take_home_pay(gross_pay, employer_match, taxes_and_fees, numtype='float'): """ Calculate net take-home pay including employer retirement savings match using the formula laid out by Mr. Money Mustache: http://www.mrmoneymustache.com/2015/01/26/calculating-net-worth/ Args: gross_pay: floa...
[ "def", "take_home_pay", "(", "gross_pay", ",", "employer_match", ",", "taxes_and_fees", ",", "numtype", "=", "'float'", ")", ":", "if", "numtype", "==", "'decimal'", ":", "return", "(", "Decimal", "(", "gross_pay", ")", "+", "Decimal", "(", "employer_match", ...
35.625
27.291667
def check_accesspoints(sess): """ check the status of all connected access points """ ap_names = walk_data(sess, name_ap_oid, helper)[0] ap_operationals = walk_data(sess, operational_ap_oid, helper)[0] ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0] ...
[ "def", "check_accesspoints", "(", "sess", ")", ":", "ap_names", "=", "walk_data", "(", "sess", ",", "name_ap_oid", ",", "helper", ")", "[", "0", "]", "ap_operationals", "=", "walk_data", "(", "sess", ",", "operational_ap_oid", ",", "helper", ")", "[", "0",...
46.358974
27.025641
def status(self): """ check the status of the network and the peers :return: network_height, peer_status """ peer = random.choice(self.PEERS) formatted_peer = 'http://{}:4001'.format(peer) peerdata = requests.get(url=formatted_peer + '/api/peers/').json()['peers'...
[ "def", "status", "(", "self", ")", ":", "peer", "=", "random", ".", "choice", "(", "self", ".", "PEERS", ")", "formatted_peer", "=", "'http://{}:4001'", ".", "format", "(", "peer", ")", "peerdata", "=", "requests", ".", "get", "(", "url", "=", "formatt...
31.846154
16.307692
def get(self, sid): """ Constructs a CredentialListContext :param sid: The unique string that identifies the resource :returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListContext ...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "CredentialListContext", "(", "self", ".", "_version", ",", "trunk_sid", "=", "self", ".", "_solution", "[", "'trunk_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
41.8
27.8
def _new_stream(self, idx): '''Randomly select and create a new stream. Parameters ---------- idx : int, [0:n_streams - 1] The stream index to replace ''' # Choose the stream index from the candidate pool self.stream_idxs_[idx] = self.rng.choice( ...
[ "def", "_new_stream", "(", "self", ",", "idx", ")", ":", "# Choose the stream index from the candidate pool", "self", ".", "stream_idxs_", "[", "idx", "]", "=", "self", ".", "rng", ".", "choice", "(", "self", ".", "n_streams", ",", "p", "=", "self", ".", "...
33.111111
17.555556
def get_sub_doc(self, subpage): """Returns PyQuery object for a given subpage URL. :subpage: The subpage of the season, e.g. 'per_game'. :returns: PyQuery object. """ html = sportsref.utils.get_html(self._subpage_url(subpage)) return pq(html)
[ "def", "get_sub_doc", "(", "self", ",", "subpage", ")", ":", "html", "=", "sportsref", ".", "utils", ".", "get_html", "(", "self", ".", "_subpage_url", "(", "subpage", ")", ")", "return", "pq", "(", "html", ")" ]
40.571429
11.571429
def list_namespaced_pod_disruption_budget(self, namespace, **kwargs): # noqa: E501 """list_namespaced_pod_disruption_budget # noqa: E501 list or watch objects of kind PodDisruptionBudget # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTT...
[ "def", "list_namespaced_pod_disruption_budget", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "...
165.233333
135.266667
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with rotation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform ...
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# random draw in rotation range", "rotation_x", "=", "random", ".", "gauss", "(", "self", ".", "rotation_range", "[", "0", "]", ",", "self", ".", "rotation_range", ...
33.5
20.777778
def append_little_endian64(self, unsigned_value): """Appends an unsigned 64-bit integer to the internal buffer, in little-endian byte order. """ if not 0 <= unsigned_value <= wire_format.UINT64_MAX: raise errors.EncodeError( 'Unsigned 64-bit out of range: %d' ...
[ "def", "append_little_endian64", "(", "self", ",", "unsigned_value", ")", ":", "if", "not", "0", "<=", "unsigned_value", "<=", "wire_format", ".", "UINT64_MAX", ":", "raise", "errors", ".", "EncodeError", "(", "'Unsigned 64-bit out of range: %d'", "%", "unsigned_val...
49.111111
10.666667
def is_functional_group(self, atom, group): """Given a pybel atom, look up if it belongs to a function group""" n_atoms = [a_neighbor.GetAtomicNum() for a_neighbor in pybel.ob.OBAtomAtomIter(atom.OBAtom)] if group in ['quartamine', 'tertamine'] and atom.atomicnum == 7: # Nitrogen #...
[ "def", "is_functional_group", "(", "self", ",", "atom", ",", "group", ")", ":", "n_atoms", "=", "[", "a_neighbor", ".", "GetAtomicNum", "(", ")", "for", "a_neighbor", "in", "pybel", ".", "ob", ".", "OBAtomAtomIter", "(", "atom", ".", "OBAtom", ")", "]", ...
60.195122
34.414634
def _conf(cls, opts): """Setup logging via ini-file from logging_conf_file option.""" if not opts.logging_conf_file: return False if not os.path.exists(opts.logging_conf_file): # FileNotFoundError added only in Python 3.3 # https://docs.python.org/3/whatsnew/...
[ "def", "_conf", "(", "cls", ",", "opts", ")", ":", "if", "not", "opts", ".", "logging_conf_file", ":", "return", "False", "if", "not", "os", ".", "path", ".", "exists", "(", "opts", ".", "logging_conf_file", ")", ":", "# FileNotFoundError added only in Pytho...
47.666667
28.083333
def predict_proba(self, a, b, device=None): """Infer causal directions using the trained NCC pairwise model. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 device (str): Device to run the algorithm on (defaults to ``cdt.SETTINGS.default_device``) ...
[ "def", "predict_proba", "(", "self", ",", "a", ",", "b", ",", "device", "=", "None", ")", ":", "device", "=", "SETTINGS", ".", "get_default", "(", "device", "=", "device", ")", "if", "self", ".", "model", "is", "None", ":", "print", "(", "'Model has ...
35.444444
17.259259
def enable_contact_host_notifications(self, contact): """Enable host notifications for a contact Format of the line that triggers function call:: ENABLE_CONTACT_HOST_NOTIFICATIONS;<contact_name> :param contact: contact to enable :type contact: alignak.objects.contact.Contact ...
[ "def", "enable_contact_host_notifications", "(", "self", ",", "contact", ")", ":", "if", "not", "contact", ".", "host_notifications_enabled", ":", "contact", ".", "modified_attributes", "|=", "DICT_MODATTR", "[", "\"MODATTR_NOTIFICATIONS_ENABLED\"", "]", ".", "value", ...
41.466667
15.933333
def traverse_bfs(self): '''Perform a Breadth-First Search (BFS) starting at this ``Node`` object'. Yields (``Node``, distance) tuples Args: ``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False`` ''' if not isinstance(include_self,...
[ "def", "traverse_bfs", "(", "self", ")", ":", "if", "not", "isinstance", "(", "include_self", ",", "bool", ")", ":", "raise", "TypeError", "(", "\"include_self must be a bool\"", ")", "q", "=", "deque", "(", ")", "dist", "=", "dict", "(", ")", "dist", "[...
46.583333
22.083333
def make_comparison_png(self, outpath=None, include_legend=False): """ Creates a thematic map image with a three color beside it :param outpath: if specified, will save the image instead of showing it :param include_legend: if true will include the thamatic map label legend """ ...
[ "def", "make_comparison_png", "(", "self", ",", "outpath", "=", "None", ",", "include_legend", "=", "False", ")", ":", "from", "matplotlib", ".", "patches", "import", "Patch", "fig", ",", "axs", "=", "plt", ".", "subplots", "(", "ncols", "=", "2", ",", ...
38.875
18.125
def acquire_restore(lock, state): """Acquire a lock and restore its state.""" if hasattr(lock, '_acquire_restore'): lock._acquire_restore(state) elif hasattr(lock, 'acquire'): lock.acquire() else: raise TypeError('expecting Lock/RLock')
[ "def", "acquire_restore", "(", "lock", ",", "state", ")", ":", "if", "hasattr", "(", "lock", ",", "'_acquire_restore'", ")", ":", "lock", ".", "_acquire_restore", "(", "state", ")", "elif", "hasattr", "(", "lock", ",", "'acquire'", ")", ":", "lock", ".",...
33.625
9.25
def override_spec(cls, **kwargs): """OVerride 'spec' and '_default_spec' with given values""" cls._default_spec.set(**kwargs) cls.spec.set(**kwargs)
[ "def", "override_spec", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "cls", ".", "_default_spec", ".", "set", "(", "*", "*", "kwargs", ")", "cls", ".", "spec", ".", "set", "(", "*", "*", "kwargs", ")" ]
42.25
4.5
def reader_acquire(self): """Acquire the lock to read""" self._order_mutex.acquire() self._readers_mutex.acquire() if self._readers == 0: self._access_mutex.acquire() self._readers += 1 self._order_mutex.release() self._readers_mutex.release()
[ "def", "reader_acquire", "(", "self", ")", ":", "self", ".", "_order_mutex", ".", "acquire", "(", ")", "self", ".", "_readers_mutex", ".", "acquire", "(", ")", "if", "self", ".", "_readers", "==", "0", ":", "self", ".", "_access_mutex", ".", "acquire", ...
25.25
14.583333
def _parse_astorb_database_file( self, astorbgz): """* parse astorb database file* **Key Arguments:** - ``astorbgz`` -- path to the downloaded astorb database file **Return:** - ``astorbDictList`` -- the astorb database parsed as a list of dictio...
[ "def", "_parse_astorb_database_file", "(", "self", ",", "astorbgz", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_parse_astorb_database_file`` method'", ")", "print", "\"Parsing the astorb.dat orbital elements file\"", "with", "gzip", ".", "open", "(",...
39.771739
19.847826
def feed_appdata(self, data, offset=0): """Feed plaintext data into the pipe. Return an (ssldata, offset) tuple. The ssldata element is a list of buffers containing record level data that needs to be sent to the remote SSL instance. The offset is the number of plaintext bytes that ...
[ "def", "feed_appdata", "(", "self", ",", "data", ",", "offset", "=", "0", ")", ":", "if", "self", ".", "_state", "==", "self", ".", "S_UNWRAPPED", ":", "# pass through data in unwrapped mode", "return", "(", "[", "data", "[", "offset", ":", "]", "]", "if...
50.609756
21.243902
def generate_twofactor_code_for_time(shared_secret, timestamp): """Generate Steam 2FA code for timestamp :param shared_secret: authenticator shared secret :type shared_secret: bytes :param timestamp: timestamp to use, if left out uses current time :type timestamp: int :return: steam two factor ...
[ "def", "generate_twofactor_code_for_time", "(", "shared_secret", ",", "timestamp", ")", ":", "hmac", "=", "hmac_sha1", "(", "bytes", "(", "shared_secret", ")", ",", "struct", ".", "pack", "(", "'>Q'", ",", "int", "(", "timestamp", ")", "//", "30", ")", ")"...
31.25
21.375
def handle_error(self, error=None): """Trap for TCPServer errors, otherwise continue.""" if _debug: TCPServerActor._debug("handle_error %r", error) # pass along to the director if error is not None: self.director.actor_error(self, error) else: TCPServer.h...
[ "def", "handle_error", "(", "self", ",", "error", "=", "None", ")", ":", "if", "_debug", ":", "TCPServerActor", ".", "_debug", "(", "\"handle_error %r\"", ",", "error", ")", "# pass along to the director", "if", "error", "is", "not", "None", ":", "self", "."...
36.555556
13.666667
def reload(self): """ Rerun the query (lazily). The results will contain any values on the server side that have changed since the last run. :return: None """ self._results = [] self._next_item_index = 0 self._next_page_index = 0 self._last_page_se...
[ "def", "reload", "(", "self", ")", ":", "self", ".", "_results", "=", "[", "]", "self", ".", "_next_item_index", "=", "0", "self", ".", "_next_page_index", "=", "0", "self", ".", "_last_page_seen", "=", "False" ]
32.1
14.1
def _parse_shape_list(shape_list, crs): """ Checks if the given list of shapes is in correct format and parses geometry objects :param shape_list: The parameter `shape_list` from class initialization :type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.P...
[ "def", "_parse_shape_list", "(", "shape_list", ",", "crs", ")", ":", "if", "not", "isinstance", "(", "shape_list", ",", "list", ")", ":", "raise", "ValueError", "(", "'Splitter must be initialized with a list of shapes'", ")", "return", "[", "AreaSplitter", ".", "...
51.363636
26.090909
def manage_conflict(self, item, name): """ Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that s...
[ "def", "manage_conflict", "(", "self", ",", "item", ",", "name", ")", ":", "if", "item", ".", "is_tpl", "(", ")", ":", "existing", "=", "self", ".", "name_to_template", "[", "name", "]", "else", ":", "existing", "=", "self", ".", "name_to_item", "[", ...
38.907407
19.648148
def load_data(self): """ Loads image and label data from specified directory path. :return: Dataset object containing image and label data. """ images = list() labels = list() emotion_index_map = dict() label_directories = [dir for dir in os.listdir(self....
[ "def", "load_data", "(", "self", ")", ":", "images", "=", "list", "(", ")", "labels", "=", "list", "(", ")", "emotion_index_map", "=", "dict", "(", ")", "label_directories", "=", "[", "dir", "for", "dir", "in", "os", ".", "listdir", "(", "self", ".",...
52.08
31.44
def rebuild_indexes(self, chunk_size=1000, aggressive_clear=False, index_class=None): """Rebuild all indexes tied to this field Parameters ---------- chunk_size: int Default to 1000, it's the number of instances to load at once. aggressive_clear: bool Wil...
[ "def", "rebuild_indexes", "(", "self", ",", "chunk_size", "=", "1000", ",", "aggressive_clear", "=", "False", ",", "index_class", "=", "None", ")", ":", "assert", "self", ".", "indexable", ",", "\"Field not indexable\"", "assert", "self", ".", "attached_to_model...
39.5
28.111111
def read_csv(self, file: str, table: str = '_csv', libref: str = '', results: str = '', opts: dict = None) -> 'SASdata': """ :param file: either the OS filesystem path of the file, or HTTP://... for a url accessible file :param table: the name of the SAS Data Set to create ...
[ "def", "read_csv", "(", "self", ",", "file", ":", "str", ",", "table", ":", "str", "=", "'_csv'", ",", "libref", ":", "str", "=", "''", ",", "results", ":", "str", "=", "''", ",", "opts", ":", "dict", "=", "None", ")", "->", "'SASdata'", ":", "...
47.714286
29.238095
def parse_int_list(s): """ Parse a comma-separated list of strings. The list may additionally contain ranges such as "1-5", which will be expanded into "1,2,3,4,5". """ result = [] for item in s.split(','): item = item.strip().split('-') if len(item) == 1: result....
[ "def", "parse_int_list", "(", "s", ")", ":", "result", "=", "[", "]", "for", "item", "in", "s", ".", "split", "(", "','", ")", ":", "item", "=", "item", ".", "strip", "(", ")", ".", "split", "(", "'-'", ")", "if", "len", "(", "item", ")", "==...
31.470588
12.294118
def note_off(self, channel, note, velocity): """Return bytes for a 'note off' event.""" return self.midi_event(NOTE_OFF, channel, note, velocity)
[ "def", "note_off", "(", "self", ",", "channel", ",", "note", ",", "velocity", ")", ":", "return", "self", ".", "midi_event", "(", "NOTE_OFF", ",", "channel", ",", "note", ",", "velocity", ")" ]
53
9.666667
def get_frame(self, frame_idx, env_idx): """ Return frame from the buffer """ if frame_idx >= self.current_size: raise VelException("Requested frame beyond the size of the buffer") accumulator = [] last_frame = self.state_buffer[frame_idx, env_idx] accumulator.appe...
[ "def", "get_frame", "(", "self", ",", "frame_idx", ",", "env_idx", ")", ":", "if", "frame_idx", ">=", "self", ".", "current_size", ":", "raise", "VelException", "(", "\"Requested frame beyond the size of the buffer\"", ")", "accumulator", "=", "[", "]", "last_fram...
38.96
21.6
def scan(self, A1, X1): """ LML, fixed-effect sizes, and scale of the candidate set. Parameters ---------- A1 : (p, e) array_like Trait-by-environments design matrix. X1 : (n, m) array_like Variants set matrix. Returns ------- ...
[ "def", "scan", "(", "self", ",", "A1", ",", "X1", ")", ":", "from", "numpy", "import", "empty", "from", "numpy", ".", "linalg", "import", "multi_dot", "from", "numpy_sugar", "import", "epsilon", ",", "is_all_finite", "from", "scipy", ".", "linalg", "import...
33.787879
17.828283
def clear_duration(self): """Clears the duration. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.assessment.AssessmentOffe...
[ "def", "clear_duration", "(", "self", ")", ":", "# Implemented from template for osid.assessment.AssessmentOfferedForm.clear_duration_template", "if", "(", "self", ".", "get_duration_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", ".", "get_duration_metada...
42.538462
20.846154
def setup_prjs_signals(self, ): """Setup the signals for the projects page :returns: None :rtype: None :raises: None """ log.debug("Setting up projects page signals.") self.prjs_prj_view_pb.clicked.connect(self.prjs_view_prj) self.prjs_prj_create_pb.click...
[ "def", "setup_prjs_signals", "(", "self", ",", ")", ":", "log", ".", "debug", "(", "\"Setting up projects page signals.\"", ")", "self", ".", "prjs_prj_view_pb", ".", "clicked", ".", "connect", "(", "self", ".", "prjs_view_prj", ")", "self", ".", "prjs_prj_creat...
34.3
17.4
def insert(self, index, child, **kwargs): '''add a new script to the container. :param child: a ``string`` representing an absolute path to the script or relative path (does not start with ``http`` or ``/``), in which case the :attr:`Media.media_path` attribute is prepended. ...
[ "def", "insert", "(", "self", ",", "index", ",", "child", ",", "*", "*", "kwargs", ")", ":", "if", "child", ":", "script", "=", "self", ".", "script", "(", "child", ",", "*", "*", "kwargs", ")", "if", "script", "not", "in", "self", ".", "children...
42
18.857143
def publish(obj, event, event_state, **kwargs): """Publish an event from an object. This is a really basic pub-sub event system to allow for tracking progress on methods externally. It fires the events for the first match it finds in the object hierarchy, going most specific to least. If no match is ...
[ "def", "publish", "(", "obj", ",", "event", ",", "event_state", ",", "*", "*", "kwargs", ")", ":", "# short-circuit if nothing is listening", "if", "len", "(", "EVENT_HANDLERS", ")", "==", "0", ":", "return", "if", "inspect", ".", "isclass", "(", "obj", ")...
34.902439
21.341463
def readmarheader(filename): """Read a header from a MarResearch .image file.""" with open(filename, 'rb') as f: intheader = np.fromstring(f.read(10 * 4), np.int32) floatheader = np.fromstring(f.read(15 * 4), '<f4') strheader = f.read(24) f.read(4) otherstrings = [f.read(...
[ "def", "readmarheader", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "intheader", "=", "np", ".", "fromstring", "(", "f", ".", "read", "(", "10", "*", "4", ")", ",", "np", ".", "int32", ")", "float...
52.375
17.6875
def create(self, label, status=None, master=None): """ Create an Identity :param label: The label to give this new identity :param status: The status of this identity. Default: 'active' :param master: Represents whether this identity is a master. Default: Fal...
[ "def", "create", "(", "self", ",", "label", ",", "status", "=", "None", ",", "master", "=", "None", ")", ":", "params", "=", "{", "'label'", ":", "label", "}", "if", "status", ":", "params", "[", "'status'", "]", "=", "status", "if", "master", ":",...
36.428571
19.904762
def add_header_info(data_api, struct_inflator): """ Add ancilliary header information to the structure. :param data_api the interface to the decoded data :param struct_inflator the interface to put the data into the client object """ struct_inflator.set_header_info(data_api.r_free, ...
[ "def", "add_header_info", "(", "data_api", ",", "struct_inflator", ")", ":", "struct_inflator", ".", "set_header_info", "(", "data_api", ".", "r_free", ",", "data_api", ".", "r_work", ",", "data_api", ".", "resolution", ",", "data_api", ".", "title", ",", "dat...
52.916667
14.25
def create_ethereum_client(uri, timeout=60, *, loop=None): """Create client to ethereum node based on schema. :param uri: Host on ethereum node :type uri: str :param timeout: An optional total time of timeout call :type timeout: int :param loop: An optional *event loop* instance ...
[ "def", "create_ethereum_client", "(", "uri", ",", "timeout", "=", "60", ",", "*", ",", "loop", "=", "None", ")", ":", "if", "loop", "is", "None", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "presult", "=", "urlparse", "(", "uri", ")...
38.258065
19.580645
def search(self, **kwargs): """ Method to search neighbors based on extends search. :param search: Dict containing QuerySets to find neighbors. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. ...
[ "def", "search", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ApiV4Neighbor", ",", "self", ")", ".", "get", "(", "self", ".", "prepare_url", "(", "'api/v4/neighbor/'", ",", "kwargs", ")", ")" ]
44.642857
22.071429
def swapWH(self): """! \~english Swap width and height of rectangles \~chinese 交换矩形高宽边数据 """ width = self.width self.width = self.height self.height = width
[ "def", "swapWH", "(", "self", ")", ":", "width", "=", "self", ".", "width", "self", ".", "width", "=", "self", ".", "height", "self", ".", "height", "=", "width" ]
25.625
10.5
def _from_string(cls, serialized): """ Return a DefinitionLocator parsing the given serialized string :param serialized: matches the string to """ parse = cls.URL_RE.match(serialized) if not parse: raise InvalidKeyError(cls, serialized) parse = parse....
[ "def", "_from_string", "(", "cls", ",", "serialized", ")", ":", "parse", "=", "cls", ".", "URL_RE", ".", "match", "(", "serialized", ")", "if", "not", "parse", ":", "raise", "InvalidKeyError", "(", "cls", ",", "serialized", ")", "parse", "=", "parse", ...
35.857143
16.857143
def save_json(filename: str, config: Union[List, Dict]): """Save JSON data to a file. Returns True on success. """ try: data = json.dumps(config, sort_keys=True, indent=4) with open(filename, 'w', encoding='utf-8') as fdesc: fdesc.write(data) return True exce...
[ "def", "save_json", "(", "filename", ":", "str", ",", "config", ":", "Union", "[", "List", ",", "Dict", "]", ")", ":", "try", ":", "data", "=", "json", ".", "dumps", "(", "config", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", "wit...
34.222222
13.611111
def get_key_delivery_url(access_token, ck_id, key_type): '''Get Media Services Key Delivery URL. Args: access_token (str): A valid Azure authentication token. ck_id (str): A Media Service Content Key ID. key_type (str): A Media Service key Type. Returns: HTTP response. JSON...
[ "def", "get_key_delivery_url", "(", "access_token", ",", "ck_id", ",", "key_type", ")", ":", "path", "=", "'/ContentKeys'", "full_path", "=", "''", ".", "join", "(", "[", "path", ",", "\"('\"", ",", "ck_id", ",", "\"')\"", ",", "\"/GetKeyDeliveryUrl\"", "]",...
36.875
21.125
def _get_caller_supplement(caller, data): """Some callers like MuTect incorporate a second caller for indels. """ if caller == "mutect": icaller = tz.get_in(["config", "algorithm", "indelcaller"], data) if icaller: caller = "%s/%s" % (caller, icaller) return caller
[ "def", "_get_caller_supplement", "(", "caller", ",", "data", ")", ":", "if", "caller", "==", "\"mutect\"", ":", "icaller", "=", "tz", ".", "get_in", "(", "[", "\"config\"", ",", "\"algorithm\"", ",", "\"indelcaller\"", "]", ",", "data", ")", "if", "icaller...
37.75
12.5
def selectShapePoint(self, point): """Select the first shape created which contains this point.""" self.deSelectShape() if self.selectedVertex(): # A vertex is marked for selection. index, shape = self.hVertex, self.hShape shape.highlightVertex(index, shape.MOVE_VERTEX) ...
[ "def", "selectShapePoint", "(", "self", ",", "point", ")", ":", "self", ".", "deSelectShape", "(", ")", "if", "self", ".", "selectedVertex", "(", ")", ":", "# A vertex is marked for selection.", "index", ",", "shape", "=", "self", ".", "hVertex", ",", "self"...
45.384615
12.846154
def _indirect_jump_resolved(self, jump, jump_addr, resolved_by, targets): """ Called when an indirect jump is successfully resolved. :param IndirectJump jump: The resolved indirect jump, or None if an IndirectJump instance is ...
[ "def", "_indirect_jump_resolved", "(", "self", ",", "jump", ",", "jump_addr", ",", "resolved_by", ",", "targets", ")", ":", "addr", "=", "jump", ".", "addr", "if", "jump", "is", "not", "None", "else", "jump_addr", "l", ".", "debug", "(", "'The indirect jum...
57.882353
37.647059
def simulation(self, ts_length=90, random_state=None): """ Compute a simulated sample path assuming Gaussian shocks. Parameters ---------- ts_length : scalar(int), optional(default=90) Number of periods to simulate for random_state : int or np.random.RandomS...
[ "def", "simulation", "(", "self", ",", "ts_length", "=", "90", ",", "random_state", "=", "None", ")", ":", "from", "scipy", ".", "signal", "import", "dlsim", "random_state", "=", "check_random_state", "(", "random_state", ")", "sys", "=", "self", ".", "ma_...
32.724138
21.413793
def count(self): '''Estimate the cardinality count based on the technique described in `this paper <http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=365694>`_. Returns: int: The estimated cardinality of the set represented by this MinHash. ''' k = len(self) ...
[ "def", "count", "(", "self", ")", ":", "k", "=", "len", "(", "self", ")", "return", "np", ".", "float", "(", "k", ")", "/", "np", ".", "sum", "(", "self", ".", "hashvalues", "/", "np", ".", "float", "(", "_max_hash", ")", ")", "-", "1.0" ]
42.888889
33.111111
def find_entity_view(self, view_type, begin_entity=None, filter={}, properties=None): """Find a ManagedEntity of the requested type. Traverses the MOB looking for an entity matching the filter. :param view_type: The type of ManagedEntity to find. :type view_typ...
[ "def", "find_entity_view", "(", "self", ",", "view_type", ",", "begin_entity", "=", "None", ",", "filter", "=", "{", "}", ",", "properties", "=", "None", ")", ":", "if", "properties", "is", "None", ":", "properties", "=", "[", "]", "kls", "=", "classma...
40.602273
19.090909
def install_isochrones(self): """ Call to isochrone install command: http://stackoverflow.com/a/24353921/4075339 """ cmd_obj = self.distribution.get_command_obj('isochrones') cmd_obj.force = self.force if self.ugali_dir: cmd_obj.ugali_dir = self.ugali_dir ...
[ "def", "install_isochrones", "(", "self", ")", ":", "cmd_obj", "=", "self", ".", "distribution", ".", "get_command_obj", "(", "'isochrones'", ")", "cmd_obj", ".", "force", "=", "self", ".", "force", "if", "self", ".", "ugali_dir", ":", "cmd_obj", ".", "uga...
38
8.666667
def rebuild( self ): """ Rebuilds the parts widget with the latest text. """ navitem = self.currentItem() if ( navitem ): navitem.initialize() self.setUpdatesEnabled(False) self.scrollWidget().show() self._originalText = '' ...
[ "def", "rebuild", "(", "self", ")", ":", "navitem", "=", "self", ".", "currentItem", "(", ")", "if", "(", "navitem", ")", ":", "navitem", ".", "initialize", "(", ")", "self", ".", "setUpdatesEnabled", "(", "False", ")", "self", ".", "scrollWidget", "("...
35.771084
15.144578
def doRollover(self): """ Do a rollover, as described in __init__(). """ self._close() if self.backupCount <= 0: # Don't keep any backups, just overwrite the existing backup file # Locking doesn't much matter here; since we are overwriting it anyway ...
[ "def", "doRollover", "(", "self", ")", ":", "self", ".", "_close", "(", ")", "if", "self", ".", "backupCount", "<=", "0", ":", "# Don't keep any backups, just overwrite the existing backup file", "# Locking doesn't much matter here; since we are overwriting it anyway", "self"...
40.828571
19.485714
def load(self): """ Load the repo database from the remote source, and then parse it. :return: """ data = self.http_request(self.location()) self._parse(data) return self
[ "def", "load", "(", "self", ")", ":", "data", "=", "self", ".", "http_request", "(", "self", ".", "location", "(", ")", ")", "self", ".", "_parse", "(", "data", ")", "return", "self" ]
27.375
15.875
def crop(data, crinfo): """ Crop the data. crop(data, crinfo) :param crinfo: min and max for each axis - [[minX, maxX], [minY, maxY], [minZ, maxZ]] """ crinfo = fix_crinfo(crinfo) return data[ __int_or_none(crinfo[0][0]) : __int_or_none(crinfo[0][1]), __int_or_none(crinfo[...
[ "def", "crop", "(", "data", ",", "crinfo", ")", ":", "crinfo", "=", "fix_crinfo", "(", "crinfo", ")", "return", "data", "[", "__int_or_none", "(", "crinfo", "[", "0", "]", "[", "0", "]", ")", ":", "__int_or_none", "(", "crinfo", "[", "0", "]", "[",...
27.733333
24.8
def strframe(obj, extended=False): """ Return a string with a frame record pretty-formatted. The record is typically an item in a list generated by `inspect.stack() <https://docs.python.org/3/library/inspect.html#inspect.stack>`_). :param obj: Frame record :type obj: tuple :param extende...
[ "def", "strframe", "(", "obj", ",", "extended", "=", "False", ")", ":", "# Stack frame -> (frame object [0], filename [1], line number of current", "# line [2], function name [3], list of lines of context from source", "# code [4], index of current line within list [5])", "fname", "=", ...
46.051282
22.615385
def ui(root_url, path): """ Generate URL for a path in the Taskcluster ui. The purpose of the function is to switch on rootUrl: "The driver for having a ui method is so we can just call ui with a path and any root url, and the returned url should work for both our current deployment (with root URL =...
[ "def", "ui", "(", "root_url", ",", "path", ")", ":", "root_url", "=", "root_url", ".", "rstrip", "(", "'/'", ")", "path", "=", "path", ".", "lstrip", "(", "'/'", ")", "if", "root_url", "==", "OLD_ROOT_URL", ":", "return", "'https://tools.taskcluster.net/{}...
45.4375
20.5625
def callback_parent(attr, old, new): '''Update data directories drop down with new parent directory''' import os # Remove accidental white space if copy/pasted new = new.strip() parent_input.value = new # Verify new parent path exists and update `datadirs_select` widget if os.path.exists(n...
[ "def", "callback_parent", "(", "attr", ",", "old", ",", "new", ")", ":", "import", "os", "# Remove accidental white space if copy/pasted", "new", "=", "new", ".", "strip", "(", ")", "parent_input", ".", "value", "=", "new", "# Verify new parent path exists and updat...
35.071429
24
def reply(self, obj, result, command_exec_status='ok', info_messages=[], warning_messages=[], error_messages=[]): """Build a response from a previouslsy received command message, send it and return number of sent bytes. :param result: Used to send back the result of th...
[ "def", "reply", "(", "self", ",", "obj", ",", "result", ",", "command_exec_status", "=", "'ok'", ",", "info_messages", "=", "[", "]", ",", "warning_messages", "=", "[", "]", ",", "error_messages", "=", "[", "]", ")", ":", "with", "self", ".", "_connect...
43.92
14.44
def setXpanId(self, xPanId): """set extended PAN ID of Thread Network Args: xPanId: extended PAN ID in hex format Returns: True: successful to set the extended PAN ID False: fail to set the extended PAN ID """ xpanid = '' print '%s ca...
[ "def", "setXpanId", "(", "self", ",", "xPanId", ")", ":", "xpanid", "=", "''", "print", "'%s call setXpanId'", "%", "self", ".", "port", "print", "xPanId", "try", ":", "if", "not", "isinstance", "(", "xPanId", ",", "str", ")", ":", "xpanid", "=", "self...
39
21.212121
def touch(self, conn, key, exptime): """The command is used to update the expiration time of an existing item without fetching it. :param key: ``bytes``, is the key to update expiration time :param exptime: ``int``, is expiration time. This replaces the existing expiration time....
[ "def", "touch", "(", "self", ",", "conn", ",", "key", ",", "exptime", ")", ":", "assert", "self", ".", "_validate_key", "(", "key", ")", "_cmd", "=", "b' '", ".", "join", "(", "[", "b'touch'", ",", "key", ",", "str", "(", "exptime", ")", ".", "en...
43.235294
17.470588
def sensor_bias_encode(self, axBias, ayBias, azBias, gxBias, gyBias, gzBias): ''' Accelerometer and gyro biases. axBias : Accelerometer X bias (m/s) (float) ayBias : Accelerometer Y bias (m/s) (float) ...
[ "def", "sensor_bias_encode", "(", "self", ",", "axBias", ",", "ayBias", ",", "azBias", ",", "gxBias", ",", "gyBias", ",", "gzBias", ")", ":", "return", "MAVLink_sensor_bias_message", "(", "axBias", ",", "ayBias", ",", "azBias", ",", "gxBias", ",", "gyBias", ...
54.307692
33.076923