text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def copy_and_verify(path, source_path, sha256): """ Copy a file to a given path from a given path, if it does not exist. After copying it, verify it integrity by checking the SHA-256 hash. Parameters ---------- path: str The (destination) path of the file on the local filesystem sou...
[ "def", "copy_and_verify", "(", "path", ",", "source_path", ",", "sha256", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "# Already exists?", "# Nothing to do, except print the SHA-256 if necessary", "if", "sha256", "is", "None", ":", "...
31.442308
18.596154
def create(self, request): """ Creates a new document based on the given data """ document = self.collection(request.json) document.created_at = datetime.utcnow() document.updated_at = document.created_at created = document.insert() return Response( ...
[ "def", "create", "(", "self", ",", "request", ")", ":", "document", "=", "self", ".", "collection", "(", "request", ".", "json", ")", "document", ".", "created_at", "=", "datetime", ".", "utcnow", "(", ")", "document", ".", "updated_at", "=", "document",...
30.473684
14.052632
def visible_to_user(self, user): """Get a list of visible events for a given user (usually request.user). These visible events will be those that either have no groups assigned to them (and are therefore public) or those in which the user is a member. """ return (Event...
[ "def", "visible_to_user", "(", "self", ",", "user", ")", ":", "return", "(", "Event", ".", "objects", ".", "filter", "(", "approved", "=", "True", ")", ".", "filter", "(", "Q", "(", "groups__in", "=", "user", ".", "groups", ".", "all", "(", ")", ")...
42.2
28.9
def makeSolution(self,cNrm,mNrm): ''' Construct an object representing the solution to this period's problem. Parameters ---------- cNrm : np.array Array of normalized consumption values for interpolation. Each row corresponds to a Markov state for this ...
[ "def", "makeSolution", "(", "self", ",", "cNrm", ",", "mNrm", ")", ":", "solution", "=", "ConsumerSolution", "(", ")", "# An empty solution to which we'll add state-conditional solutions", "# Calculate the MPC at each market resource gridpoint in each state (if desired)", "if", "...
51.342857
28.571429
def print_env_info(key, out=sys.stderr): """If given environment key is defined, print it out.""" value = os.getenv(key) if value is not None: print(key, "=", repr(value), file=out)
[ "def", "print_env_info", "(", "key", ",", "out", "=", "sys", ".", "stderr", ")", ":", "value", "=", "os", ".", "getenv", "(", "key", ")", "if", "value", "is", "not", "None", ":", "print", "(", "key", ",", "\"=\"", ",", "repr", "(", "value", ")", ...
39.4
7
def parse(s): """Parse a string representation back into the Vector. >>> Vectors.parse('[2,1,2 ]') DenseVector([2.0, 1.0, 2.0]) >>> Vectors.parse(' ( 100, [0], [2])') SparseVector(100, {0: 2.0}) """ if s.find('(') == -1 and s.find('[') != -1: return...
[ "def", "parse", "(", "s", ")", ":", "if", "s", ".", "find", "(", "'('", ")", "==", "-", "1", "and", "s", ".", "find", "(", "'['", ")", "!=", "-", "1", ":", "return", "DenseVector", ".", "parse", "(", "s", ")", "elif", "s", ".", "find", "(",...
34.4
11.8
def send_terrain_data(self): '''send some terrain data''' for bit in range(56): if self.current_request.mask & (1<<bit) and self.sent_mask & (1<<bit) == 0: self.send_terrain_data_bit(bit) return # no bits to send self.current_request = None ...
[ "def", "send_terrain_data", "(", "self", ")", ":", "for", "bit", "in", "range", "(", "56", ")", ":", "if", "self", ".", "current_request", ".", "mask", "&", "(", "1", "<<", "bit", ")", "and", "self", ".", "sent_mask", "&", "(", "1", "<<", "bit", ...
37.222222
14.777778
def html_document_fromstring(s): """Parse html tree from string. Return None if the string can't be parsed. """ if isinstance(s, six.text_type): s = s.encode('utf8') try: if html_too_big(s): return None return html5parser.document_fromstring(s, parser=_html5lib_parse...
[ "def", "html_document_fromstring", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "text_type", ")", ":", "s", "=", "s", ".", "encode", "(", "'utf8'", ")", "try", ":", "if", "html_too_big", "(", "s", ")", ":", "return", "None", "...
29
17.416667
def get_outputs(sym, params, in_shape, in_label): """ Infer output shapes and return dictionary of output name to shape :param :class:`~mxnet.symbol.Symbol` sym: symbol to perform infer shape on :param dic of (str, nd.NDArray) params: :param list of tuple(int, ...) in_shape: list of all...
[ "def", "get_outputs", "(", "sym", ",", "params", ",", "in_shape", ",", "in_label", ")", ":", "# remove any input listed in params from sym.list_inputs() and bind them to the input shapes provided", "# by user. Also remove in_label, which is the name of the label symbol that may have been u...
52.117647
24.352941
def get_files(self): """ Read and parse files from a directory, return a dictionary of path => post """ files = {} for filename in os.listdir(self.source): path = os.path.join(self.source, filename) files[filename] = frontmatter.load(path, ...
[ "def", "get_files", "(", "self", ")", ":", "files", "=", "{", "}", "for", "filename", "in", "os", ".", "listdir", "(", "self", ".", "source", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "source", ",", "filename", ")",...
31.538462
12.461538
def read(self, entity=None, attrs=None, ignore=None, params=None): """Ignore usergroup from read and alter auth_source_ldap with auth_source """ if entity is None: entity = type(self)( self._server_config, usergroup=self.usergroup, # pylint:disable=no...
[ "def", "read", "(", "self", ",", "entity", "=", "None", ",", "attrs", "=", "None", ",", "ignore", "=", "None", ",", "params", "=", "None", ")", ":", "if", "entity", "is", "None", ":", "entity", "=", "type", "(", "self", ")", "(", "self", ".", "...
41.266667
15
def modify_url_for_impersonation(cls, url, impersonate_user, username): """ Modify the SQL Alchemy URL object with the user to impersonate if applicable. :param url: SQLAlchemy URL object :param impersonate_user: Bool indicating if impersonation is enabled :param username: Effect...
[ "def", "modify_url_for_impersonation", "(", "cls", ",", "url", ",", "impersonate_user", ",", "username", ")", ":", "if", "impersonate_user", "is", "not", "None", "and", "username", "is", "not", "None", ":", "url", ".", "username", "=", "username" ]
48.666667
16.222222
def AddContract(self, contract): """ Add a contract to the wallet. Args: contract (Contract): a contract of type neo.SmartContract.Contract. Raises: Exception: Invalid operation - public key mismatch. """ if not contract.PublicKeyHash.ToBytes() i...
[ "def", "AddContract", "(", "self", ",", "contract", ")", ":", "if", "not", "contract", ".", "PublicKeyHash", ".", "ToBytes", "(", ")", "in", "self", ".", "_keys", ".", "keys", "(", ")", ":", "raise", "Exception", "(", "'Invalid operation - public key mismatc...
35.75
22.25
def slice_time(begin, end=None, duration=datetime.timedelta(days=2)): """ :param begin: datetime :param end: datetime :param duration: timedelta :return: a generator for a set of timeslices of the given duration """ duration_ms = int(duration.total_seconds() * 1000) previous = int(unix_t...
[ "def", "slice_time", "(", "begin", ",", "end", "=", "None", ",", "duration", "=", "datetime", ".", "timedelta", "(", "days", "=", "2", ")", ")", ":", "duration_ms", "=", "int", "(", "duration", ".", "total_seconds", "(", ")", "*", "1000", ")", "previ...
39.35
15.75
def value_for_arguments(self, arguments): """ Parameters ---------- arguments: {Prior: float} A dictionary of arguments Returns ------- tuple: (float,...) A tuple of float values """ def convert(tup): if hasatt...
[ "def", "value_for_arguments", "(", "self", ",", "arguments", ")", ":", "def", "convert", "(", "tup", ")", ":", "if", "hasattr", "(", "tup", ",", "\"prior\"", ")", ":", "return", "arguments", "[", "tup", ".", "prior", "]", "return", "tup", ".", "constan...
26.947368
17.789474
def traverse_frozen_data(data_structure): """Yields the leaves of the frozen data-structure pre-order. It will produce the same order as one would write the data-structure.""" parent_stack = [data_structure] while parent_stack: node = parent_stack.pop(0) # We don't iterate strings ...
[ "def", "traverse_frozen_data", "(", "data_structure", ")", ":", "parent_stack", "=", "[", "data_structure", "]", "while", "parent_stack", ":", "node", "=", "parent_stack", ".", "pop", "(", "0", ")", "# We don't iterate strings", "tlen", "=", "-", "1", "if", "n...
32.315789
13.684211
def get_device_info(self, bigip): '''Get device information about a specific BigIP device. :param bigip: bigip object --- device to inspect :returns: bigip object ''' coll = bigip.tm.cm.devices.get_collection() device = [device for device in coll if device.selfDevice ==...
[ "def", "get_device_info", "(", "self", ",", "bigip", ")", ":", "coll", "=", "bigip", ".", "tm", ".", "cm", ".", "devices", ".", "get_collection", "(", ")", "device", "=", "[", "device", "for", "device", "in", "coll", "if", "device", ".", "selfDevice", ...
34.090909
21.545455
def _get_user_data(self): """ Base method for retrieving user data from a viz. """ url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/settings/' r = requests.get(url) if r.status_code == 200: content = r.json...
[ "def", "_get_user_data", "(", "self", ")", ":", "url", "=", "self", ".", "session", ".", "host", "+", "'/sessions/'", "+", "str", "(", "self", ".", "session", ".", "id", ")", "+", "'/visualizations/'", "+", "str", "(", "self", ".", "id", ")", "+", ...
32.153846
22.615385
def remove_unreferenced_vertices(self): """ Remove all vertices in the current mesh which are not referenced by a face. """ referenced = np.zeros(len(self.vertices), dtype=np.bool) referenced[self.faces] = True inverse = np.zeros(len(self.vertices), dtype=np.int6...
[ "def", "remove_unreferenced_vertices", "(", "self", ")", ":", "referenced", "=", "np", ".", "zeros", "(", "len", "(", "self", ".", "vertices", ")", ",", "dtype", "=", "np", ".", "bool", ")", "referenced", "[", "self", ".", "faces", "]", "=", "True", ...
36.083333
16.75
def encrypt_file(self, path, output_path=None, overwrite=False, enable_verbose=True): """ Encrypt a file using rsa. RSA for big file encryption is very slow. For big file, I recommend to use symmetric en...
[ "def", "encrypt_file", "(", "self", ",", "path", ",", "output_path", "=", "None", ",", "overwrite", "=", "False", ",", "enable_verbose", "=", "True", ")", ":", "path", ",", "output_path", "=", "files", ".", "process_dst_overwrite_args", "(", "src", "=", "p...
38.111111
18.555556
def read_plain_text(fname, encoding="utf-8"): """Reads a file as a list of strings.""" with io.open(fname, encoding=encoding) as f: result = list(f) if result: if result[-1][-1:] == "\n": result.append("\n") else: result[-1] += "\n" return [line[:-1] f...
[ "def", "read_plain_text", "(", "fname", ",", "encoding", "=", "\"utf-8\"", ")", ":", "with", "io", ".", "open", "(", "fname", ",", "encoding", "=", "encoding", ")", "as", "f", ":", "result", "=", "list", "(", "f", ")", "if", "result", ":", "if", "r...
31.090909
12.545455
def trajectory_length(self, itraj, stride=1, skip=0): r"""Returns the length of trajectory of the requested index. Parameters ---------- itraj : int trajectory index stride : int return value is the number of frames in the trajectory when runn...
[ "def", "trajectory_length", "(", "self", ",", "itraj", ",", "stride", "=", "1", ",", "skip", "=", "0", ")", ":", "if", "itraj", ">=", "self", ".", "ntraj", ":", "raise", "IndexError", "(", "\"given index (%s) exceeds number of data sets (%s).\"", "\" Zero based ...
36.961538
21.307692
def _massageData(self, row): """ Convert a row into a tuple of Item instances, by slicing it according to the number of columns for each instance, and then proceeding as for ItemQuery._massageData. @param row: an n-tuple, where n is the total number of columns specified...
[ "def", "_massageData", "(", "self", ",", "row", ")", ":", "offset", "=", "0", "resultBits", "=", "[", "]", "for", "i", ",", "tableClass", "in", "enumerate", "(", "self", ".", "tableClass", ")", ":", "numAttrs", "=", "self", ".", "schemaLengths", "[", ...
35.259259
23.481481
def neighborhood_cortical_magnification(mesh, coordinates): ''' neighborhood_cortical_magnification(mesh, visual_coordinates) yields a list of neighborhood- based cortical magnification values for the vertices in the given mesh if their visual field coordinates are given by the visual_coordinates matrix...
[ "def", "neighborhood_cortical_magnification", "(", "mesh", ",", "coordinates", ")", ":", "idcs", "=", "_cmag_coord_idcs", "(", "coordinates", ")", "neis", "=", "mesh", ".", "tess", ".", "indexed_neighborhoods", "coords_vis", "=", "np", ".", "asarray", "(", "coor...
54.6
22.733333
def count_n_grams_py_polarity(self, data_set_reader, n_grams, filters): """ Returns a map of n-gram and the number of times it appeared in positive context and the number of times it appeared in negative context in dataset file. :param data_set_reader: Dataset containing tweets and thei...
[ "def", "count_n_grams_py_polarity", "(", "self", ",", "data_set_reader", ",", "n_grams", ",", "filters", ")", ":", "self", ".", "data_set_reader", "=", "data_set_reader", "token_trie", "=", "TokenTrie", "(", "n_grams", ")", "counter", "=", "{", "}", "# Todo: par...
42.969697
23.575758
def _update_raid_input_data(target_raid_config, raid_input): """Process raid input data. :param target_raid_config: node raid info :param raid_input: raid information for creating via eLCM :raises ELCMValueError: raise msg if wrong input :return: raid_input: raid input data which create raid config...
[ "def", "_update_raid_input_data", "(", "target_raid_config", ",", "raid_input", ")", ":", "logical_disk_list", "=", "target_raid_config", "[", "'logical_disks'", "]", "raid_input", "[", "'Server'", "]", "[", "'HWConfigurationIrmc'", "]", ".", "update", "(", "{", "'@...
35.164948
18.113402
def degree_circle(self,EdgeAttribute=None,network=None,NodeAttribute=None,\ nodeList=None,singlePartition=None,verbose=None): """ Execute the Degree Sorted Circle Layout on a network. :param EdgeAttribute (string, optional): The name of the edge column contai ning numeric values that will be used as weights...
[ "def", "degree_circle", "(", "self", ",", "EdgeAttribute", "=", "None", ",", "network", "=", "None", ",", "NodeAttribute", "=", "None", ",", "nodeList", "=", "None", ",", "singlePartition", "=", "None", ",", "verbose", "=", "None", ")", ":", "network", "...
57.433333
25.833333
def continuous(self): """ List of measures in <continuous> section Example: ["simulated EIR", "GVI coverage"] :rtype: list """ list_of_measures = [] if self.et.find("continuous") is None: return list_of_measures return self._get_measures(self.e...
[ "def", "continuous", "(", "self", ")", ":", "list_of_measures", "=", "[", "]", "if", "self", ".", "et", ".", "find", "(", "\"continuous\"", ")", "is", "None", ":", "return", "list_of_measures", "return", "self", ".", "_get_measures", "(", "self", ".", "e...
33.2
10
def get_init(dirname): """Get __init__ file path for module directory Parameters ---------- dirname : str Find the __init__ file in directory `dirname` Returns ------- init_path : str Path to __init__ file """ fbase = os.path.join(dirname, "__init__") for e...
[ "def", "get_init", "(", "dirname", ")", ":", "fbase", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "\"__init__\"", ")", "for", "ext", "in", "[", "\".py\"", ",", "\".pyw\"", "]", ":", "fname", "=", "fbase", "+", "ext", "if", "os", ".", ...
22.888889
17.944444
def set_state(self, state, brightness=None, color_kelvin=None, color_xy=None, color_hue_saturation=None): """ :param state: a boolean of true (on) or false ('off') :param brightness: a float from 0 to 1 to set the brightness of this bulb :pa...
[ "def", "set_state", "(", "self", ",", "state", ",", "brightness", "=", "None", ",", "color_kelvin", "=", "None", ",", "color_xy", "=", "None", ",", "color_hue_saturation", "=", "None", ")", ":", "desired_state", "=", "{", "\"powered\"", ":", "state", "}", ...
41.689655
18.724138
def get_request_feature(self, name): """Parses the request for a particular feature. Arguments: name: A feature name. Returns: A feature parsed from the URL if the feature is supported, or None. """ if '[]' in name: # array-type retur...
[ "def", "get_request_feature", "(", "self", ",", "name", ")", ":", "if", "'[]'", "in", "name", ":", "# array-type", "return", "self", ".", "request", ".", "query_params", ".", "getlist", "(", "name", ")", "if", "name", "in", "self", ".", "features", "else...
34.380952
16.666667
def presence_stanza_handler(stanza_type = None, payload_class = None, payload_key = None, usage_restriction = "post-auth"): """Method decorator generator for decorating <presence/> stanza handler methods in `XMPPFeatureHandler` subclasses. :Parameters: - `payload_class`: pay...
[ "def", "presence_stanza_handler", "(", "stanza_type", "=", "None", ",", "payload_class", "=", "None", ",", "payload_key", "=", "None", ",", "usage_restriction", "=", "\"post-auth\"", ")", ":", "return", "_stanza_handler", "(", "\"presence\"", ",", "stanza_type", "...
48.222222
22.055556
def get_event_questions(self, id, **data): """ GET /events/:id/questions/ Eventbrite allows event organizers to add custom questions that attendees fill out upon registration. This endpoint can be helpful for determining what custom information is collected and available per even...
[ "def", "get_event_questions", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/events/{0}/questions/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
46
19.4
def remove_nio(self, port_number): """ Removes the specified NIO as member of this Ethernet switch. :param port_number: allocated port number :returns: the NIO that was bound to the port """ if port_number not in self._nios: raise DynamipsError("Port {} is ...
[ "def", "remove_nio", "(", "self", ",", "port_number", ")", ":", "if", "port_number", "not", "in", "self", ".", "_nios", ":", "raise", "DynamipsError", "(", "\"Port {} is not allocated\"", ".", "format", "(", "port_number", ")", ")", "nio", "=", "self", ".", ...
43
28.857143
def filedict(self, kv): """Updates filedict with single file entry or deletes given key if the value is False. Shouldn't be used by the user.""" k, v = kv if v is not None: self.__files.update({k: v}) else: with suppress(KeyError): del sel...
[ "def", "filedict", "(", "self", ",", "kv", ")", ":", "k", ",", "v", "=", "kv", "if", "v", "is", "not", "None", ":", "self", ".", "__files", ".", "update", "(", "{", "k", ":", "v", "}", ")", "else", ":", "with", "suppress", "(", "KeyError", ")...
32.3
13.2
def list_namespaced_daemon_set(self, namespace, **kwargs): # noqa: E501 """list_namespaced_daemon_set # noqa: E501 list or watch objects of kind DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req...
[ "def", "list_namespaced_daemon_set", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", "....
162.733333
133.333333
def title(self, title): """Prints the title""" title = " What's it like out side {0}? ".format(title) click.secho("{:=^62}".format(title), fg=self.colors.WHITE) click.echo()
[ "def", "title", "(", "self", ",", "title", ")", ":", "title", "=", "\" What's it like out side {0}? \"", ".", "format", "(", "title", ")", "click", ".", "secho", "(", "\"{:=^62}\"", ".", "format", "(", "title", ")", ",", "fg", "=", "self", ".", "colors",...
40.2
17
def Dir(self, name, create=True): """Create a directory node named 'name' relative to the directory of this file.""" return self.dir.Dir(name, create=create)
[ "def", "Dir", "(", "self", ",", "name", ",", "create", "=", "True", ")", ":", "return", "self", ".", "dir", ".", "Dir", "(", "name", ",", "create", "=", "create", ")" ]
44.5
3.75
def rectangle_surface_intersection(rectangle, f_lower, f_upper, bounds_lower=None, bounds_upper=None, check=True, numpoints_check=500): """ Method to calculate the surface of the intersection of a rectangle (aligned with axes) and another sur...
[ "def", "rectangle_surface_intersection", "(", "rectangle", ",", "f_lower", ",", "f_upper", ",", "bounds_lower", "=", "None", ",", "bounds_upper", "=", "None", ",", "check", "=", "True", ",", "numpoints_check", "=", "500", ")", ":", "x1", "=", "np", ".", "m...
49.950617
27.382716
def typeOf(cls, expected_type): #pylint: disable=no-self-argument,invalid-name,no-self-use """ (*Type does NOT consider inherited class) Matcher.mtest(...) will return True if type(...) == expected_type Return: Matcher Raise: matcher_type_error """ if isinstance(e...
[ "def", "typeOf", "(", "cls", ",", "expected_type", ")", ":", "#pylint: disable=no-self-argument,invalid-name,no-self-use", "if", "isinstance", "(", "expected_type", ",", "type", ")", ":", "options", "=", "{", "}", "options", "[", "\"target_type\"", "]", "=", "expe...
42.333333
13.833333
def then_a_model_exists(context, model_name, key, value): """ :type model_name: str :type key: str :type value: str :type context: behave.runner.Context """ model = apps.get_model(model_name) args = { key: value } obj = model.objects.get(**args) assert obj...
[ "def", "then_a_model_exists", "(", "context", ",", "model_name", ",", "key", ",", "value", ")", ":", "model", "=", "apps", ".", "get_model", "(", "model_name", ")", "args", "=", "{", "key", ":", "value", "}", "obj", "=", "model", ".", "objects", ".", ...
24.615385
13.384615
def timeuntil(d, now=None): """ Like timesince, but returns a string measuring the time until the given time. """ if not now: if getattr(d, 'tzinfo', None): now = datetime.datetime.now(LocalTimezone(d)) else: now = datetime.datetime.now() return timesince(...
[ "def", "timeuntil", "(", "d", ",", "now", "=", "None", ")", ":", "if", "not", "now", ":", "if", "getattr", "(", "d", ",", "'tzinfo'", ",", "None", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", "LocalTimezone", "(", "d", ")",...
28.818182
13
def command(self, init=False): """Define CLI command.""" def wrapper(func): header = '\n'.join([s for s in (func.__doc__ or '').split('\n') if not s.strip().startswith(':')]) parser = self.parsers.add_parser(func.__name__, description=header) ...
[ "def", "command", "(", "self", ",", "init", "=", "False", ")", ":", "def", "wrapper", "(", "func", ")", ":", "header", "=", "'\\n'", ".", "join", "(", "[", "s", "for", "s", "in", "(", "func", ".", "__doc__", "or", "''", ")", ".", "split", "(", ...
38.172414
22.327586
def _rebuild_table(self, new_name, old_name, new_columns, old_columns): ''' a helper method for rebuilding table (by renaming & migrating) ''' # verbosity print('Rebuilding %s table in %s database' % (self.table_name, self.database_name), end='', flush=True) from sqla...
[ "def", "_rebuild_table", "(", "self", ",", "new_name", ",", "old_name", ",", "new_columns", ",", "old_columns", ")", ":", "# verbosity", "print", "(", "'Rebuilding %s table in %s database'", "%", "(", "self", ".", "table_name", ",", "self", ".", "database_name", ...
40.754386
22.122807
def acosh(wave): r""" Return the hyperbolic arc cosine of a waveform's dependent variable vector. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions docum...
[ "def", "acosh", "(", "wave", ")", ":", "pexdoc", ".", "exh", ".", "addex", "(", "ValueError", ",", "\"Math domain error\"", ",", "bool", "(", "min", "(", "wave", ".", "_dep_vector", ")", "<", "1", ")", ")", "return", "_operation", "(", "wave", ",", "...
28
22.045455
def dumped(text, level, indent=2): """Put curly brackets round an indented text""" return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n"
[ "def", "dumped", "(", "text", ",", "level", ",", "indent", "=", "2", ")", ":", "return", "indented", "(", "\"{\\n%s\\n}\"", "%", "indented", "(", "text", ",", "level", "+", "1", ",", "indent", ")", "or", "\"None\"", ",", "level", ",", "indent", ")", ...
61.333333
21.666667
def maybeDeferred(f, *args, **kw): """ Copied from twsited.internet.defer and add a check to detect fibers. """ try: result = f(*args, **kw) except Exception: return fail(failure.Failure()) if IFiber.providedBy(result): import traceback frames = traceback.extract...
[ "def", "maybeDeferred", "(", "f", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "try", ":", "result", "=", "f", "(", "*", "args", ",", "*", "*", "kw", ")", "except", "Exception", ":", "return", "fail", "(", "failure", ".", "Failure", "(", ")...
28.782609
15.130435
def wrap_get_user(cls, response): """Wrap the response from getting a user into an instance and return it :param response: The response from getting a user :type response: :class:`requests.Response` :returns: the new user instance :rtype: :class:`list` of :class:`User` ...
[ "def", "wrap_get_user", "(", "cls", ",", "response", ")", ":", "json", "=", "response", ".", "json", "(", ")", "u", "=", "cls", ".", "wrap_json", "(", "json", ")", "return", "u" ]
32.307692
12.461538
def return_item_count_on_page(self, page=1, total_items=1): """ Return the number of items on page. Args: * page = The Page to test for * total_items = the total item count Returns: * Integer - Which represents the calculated number of items on page. """ up_...
[ "def", "return_item_count_on_page", "(", "self", ",", "page", "=", "1", ",", "total_items", "=", "1", ")", ":", "up_to_page", "=", "(", "(", "page", "-", "1", ")", "*", "self", ".", "page_items", ")", "# Number of items up to the page in question", "if", "...
31.259259
18.148148
def _get_binary_from_ipv4(self, ip_addr): """Converts IPv4 address to binary form.""" return struct.unpack("!L", socket.inet_pton(socket.AF_INET, ip_addr))[0]
[ "def", "_get_binary_from_ipv4", "(", "self", ",", "ip_addr", ")", ":", "return", "struct", ".", "unpack", "(", "\"!L\"", ",", "socket", ".", "inet_pton", "(", "socket", ".", "AF_INET", ",", "ip_addr", ")", ")", "[", "0", "]" ]
44.6
18.4
def to_dict(self): """ Attribute values to dict """ return { "total": self.total, "subtotal": self.subtotal, "items": self.items, "extra_amount": self.extra_amount }
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "\"total\"", ":", "self", ".", "total", ",", "\"subtotal\"", ":", "self", ".", "subtotal", ",", "\"items\"", ":", "self", ".", "items", ",", "\"extra_amount\"", ":", "self", ".", "extra_amount", "}"...
25.555556
15.555556
def _setupHttp(self): """ Setup an HTTP session authorized by OAuth2. """ if self._http == None: http = httplib2.Http() self._http = self._credentials.authorize(http)
[ "def", "_setupHttp", "(", "self", ")", ":", "if", "self", ".", "_http", "==", "None", ":", "http", "=", "httplib2", ".", "Http", "(", ")", "self", ".", "_http", "=", "self", ".", "_credentials", ".", "authorize", "(", "http", ")" ]
30.857143
9.142857
def _eval_summary(self, context: MonitorContext, feed_dict: Optional[Dict]=None) -> None: """ Evaluates the summary tensor and writes the result to the event file. :param context: Monitor context :param feed_dict: Input values dictionary to be provided to the `session.run` when e...
[ "def", "_eval_summary", "(", "self", ",", "context", ":", "MonitorContext", ",", "feed_dict", ":", "Optional", "[", "Dict", "]", "=", "None", ")", "->", "None", ":", "if", "self", ".", "_summary", "is", "None", ":", "raise", "RuntimeError", "(", "'Tensor...
47.421053
26.684211
def _list_directories_and_files(self, share_name, directory_name=None, marker=None, max_results=None, timeout=None): ''' Returns a list of the directories and files under the specified share. :param str share_name: Name of existing share. ...
[ "def", "_list_directories_and_files", "(", "self", ",", "share_name", ",", "directory_name", "=", "None", ",", "marker", "=", "None", ",", "max_results", "=", "None", ",", "timeout", "=", "None", ")", ":", "_validate_not_none", "(", "'share_name'", ",", "share...
46.825
21.025
def sort_clusters(self, data, cs, sort_by): """ Sort clusters by the concentration of a particular analyte. Parameters ---------- data : dict A dataset containing sort_by as a key. cs : array-like An array of clusters, the same length as values of...
[ "def", "sort_clusters", "(", "self", ",", "data", ",", "cs", ",", "sort_by", ")", ":", "# label the clusters according to their contents", "sdat", "=", "data", "[", "sort_by", "]", "means", "=", "[", "]", "nclusts", "=", "np", ".", "arange", "(", "cs", "."...
27.4
19
def get_song_id(self, song_title): """ 根据歌名获取歌曲id """ song = self.search(song_title) if song.get('hMusic', None): return song['hMusic']['dfsId'], song['hMusic']['bitrate'] elif song.get('mMusic', None): return song['mMusic']['dfsId'], song['mMusic...
[ "def", "get_song_id", "(", "self", ",", "song_title", ")", ":", "song", "=", "self", ".", "search", "(", "song_title", ")", "if", "song", ".", "get", "(", "'hMusic'", ",", "None", ")", ":", "return", "song", "[", "'hMusic'", "]", "[", "'dfsId'", "]",...
34.615385
14.307692
def _make_writeable(filename): """ Make sure that the file is writeable. Useful if our source is read-only. """ import stat if sys.platform.startswith('java'): # On Jython there is no os.access() return if not os.access(filename, os.W_OK): st = os.stat(filename) ...
[ "def", "_make_writeable", "(", "filename", ")", ":", "import", "stat", "if", "sys", ".", "platform", ".", "startswith", "(", "'java'", ")", ":", "# On Jython there is no os.access()", "return", "if", "not", "os", ".", "access", "(", "filename", ",", "os", "....
31.692308
11.846154
def push(*resources): """ Push translation source English files to Transifex. Arguments name specific resources to push. Otherwise, push all the source files. """ cmd = 'tx push -s' if resources: for resource in resources: execute(cmd + ' -r {resource}'.format(resource=r...
[ "def", "push", "(", "*", "resources", ")", ":", "cmd", "=", "'tx push -s'", "if", "resources", ":", "for", "resource", "in", "resources", ":", "execute", "(", "cmd", "+", "' -r {resource}'", ".", "format", "(", "resource", "=", "resource", ")", ")", "els...
26.769231
20.615385
def get_system(self, identity): """Given the identity return a HPESystem object :param identity: The identity of the System resource :returns: The System object """ return system.HPESystem(self._conn, identity, redfish_version=self.redfish_version...
[ "def", "get_system", "(", "self", ",", "identity", ")", ":", "return", "system", ".", "HPESystem", "(", "self", ".", "_conn", ",", "identity", ",", "redfish_version", "=", "self", ".", "redfish_version", ")" ]
39.25
14.5
def stop(self): """Stops the pusherclient cleanly """ self.pusherthread_stop.set() self.pusher.disconnect() # wait until pusher is down while self.pusher.connection.state is "connected": sleep(0.1) logging.info("shutting down pusher connector thread")
[ "def", "stop", "(", "self", ")", ":", "self", ".", "pusherthread_stop", ".", "set", "(", ")", "self", ".", "pusher", ".", "disconnect", "(", ")", "# wait until pusher is down", "while", "self", ".", "pusher", ".", "connection", ".", "state", "is", "\"conne...
31.1
13.9
def parse(self, response, metadata_type): """ Parses RETS metadata using the COMPACT-DECODED format :param response: :param metadata_type: :return: """ xml = xmltodict.parse(response.text) self.analyze_reply_code(xml_response_dict=xml) base = xml.g...
[ "def", "parse", "(", "self", ",", "response", ",", "metadata_type", ")", ":", "xml", "=", "xmltodict", ".", "parse", "(", "response", ".", "text", ")", "self", ".", "analyze_reply_code", "(", "xml_response_dict", "=", "xml", ")", "base", "=", "xml", ".",...
37.883721
23.697674
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(Con...
[ "def", "fix_config", "(", "self", ",", "options", ")", ":", "options", "=", "super", "(", "ContainerValuePicker", ",", "self", ")", ".", "fix_config", "(", "options", ")", "opt", "=", "\"value\"", "if", "opt", "not", "in", "options", ":", "options", "[",...
36.44
23.4
def qteDisconnectHook(self, hookName: str, slot: (types.FunctionType, types.MethodType)): """ Disconnect ``slot`` from ``hookName``. If ``hookName`` does not exist, or ``slot`` is not connected to ``hookName`` then return **False**, otherwise disassociate ...
[ "def", "qteDisconnectHook", "(", "self", ",", "hookName", ":", "str", ",", "slot", ":", "(", "types", ".", "FunctionType", ",", "types", ".", "MethodType", ")", ")", ":", "# Shorthand.", "reg", "=", "self", ".", "_qteRegistryHooks", "# Return immediately if no...
33.608696
22
def _wrap_class(request_handler, validator): """Decorate each HTTP verb method to check if the request is authenticated :param request_handler: a tornado.web.RequestHandler instance """ METHODS = ['get', 'post', 'put', 'head', 'options', 'delete', 'patch'] for name in METHODS: method = geta...
[ "def", "_wrap_class", "(", "request_handler", ",", "validator", ")", ":", "METHODS", "=", "[", "'get'", ",", "'post'", ",", "'put'", ",", "'head'", ",", "'options'", ",", "'delete'", ",", "'patch'", "]", "for", "name", "in", "METHODS", ":", "method", "="...
39.818182
19.363636
def set_stage(self, stage: Stages): """ Convenience method to set the stage and lookup message """ assert stage in Stages LOG.info(f'Update session: stage {self._stage.name}->{stage.name}') self._stage = stage
[ "def", "set_stage", "(", "self", ",", "stage", ":", "Stages", ")", ":", "assert", "stage", "in", "Stages", "LOG", ".", "info", "(", "f'Update session: stage {self._stage.name}->{stage.name}'", ")", "self", ".", "_stage", "=", "stage" ]
47.4
12.6
def set_filter(self, text, status): """ text : string The string to be used for pattern matching. status : int TODO: add description """ self._filter_string = text.lower() self._filter_status = status self.invalidateFilter()
[ "def", "set_filter", "(", "self", ",", "text", ",", "status", ")", ":", "self", ".", "_filter_string", "=", "text", ".", "lower", "(", ")", "self", ".", "_filter_status", "=", "status", "self", ".", "invalidateFilter", "(", ")" ]
29.5
8.1
def delete_organization(self, organization_id): """ Deletes an organization for a given organization ID :param organization_id: :return: """ log.warning('Deleting organization...') url = 'rest/servicedeskapi/organization/{}'.format(organization_id) retur...
[ "def", "delete_organization", "(", "self", ",", "organization_id", ")", ":", "log", ".", "warning", "(", "'Deleting organization...'", ")", "url", "=", "'rest/servicedeskapi/organization/{}'", ".", "format", "(", "organization_id", ")", "return", "self", ".", "delet...
33
18.818182
def visit_BinOp(self, node: ast.BinOp) -> Any: """Recursively visit the left and right operand, respectively, and apply the operation on the results.""" # pylint: disable=too-many-branches left = self.visit(node=node.left) right = self.visit(node=node.right) if isinstance(node.o...
[ "def", "visit_BinOp", "(", "self", ",", "node", ":", "ast", ".", "BinOp", ")", "->", "Any", ":", "# pylint: disable=too-many-branches", "left", "=", "self", ".", "visit", "(", "node", "=", "node", ".", "left", ")", "right", "=", "self", ".", "visit", "...
39.162162
8.810811
def get_types(json_type: StrOrList) -> typing.Tuple[str, str]: """Returns the json and native python type based on the json_type input. If json_type is a list of types it will return the first non 'null' value. :param json_type: A json type or a list of json types. :returns: A tuple containing the jso...
[ "def", "get_types", "(", "json_type", ":", "StrOrList", ")", "->", "typing", ".", "Tuple", "[", "str", ",", "str", "]", ":", "# If the type is a list, use the first non 'null' value as the type.", "if", "isinstance", "(", "json_type", ",", "list", ")", ":", "for",...
42.133333
18.733333
def addprefix(subject, prefix): """ Adds the specified *prefix* to the last path element in *subject*. If *prefix* is a callable, it must accept exactly one argument, which is the last path element, and return a modified value. """ if not prefix: return subject dir_, base = split(subject) if callab...
[ "def", "addprefix", "(", "subject", ",", "prefix", ")", ":", "if", "not", "prefix", ":", "return", "subject", "dir_", ",", "base", "=", "split", "(", "subject", ")", "if", "callable", "(", "prefix", ")", ":", "base", "=", "prefix", "(", "base", ")", ...
26.666667
18.666667
def create_tags(self, entry): """Inspects an ``Entry`` instance, and builds associates ``Tag`` objects based on the values in the ``Entry``'s ``tag_string``.""" tag_list = [t.lower().strip() for t in entry.tag_string.split(',')] for t in tag_list: tag, created = self.get_or_c...
[ "def", "create_tags", "(", "self", ",", "entry", ")", ":", "tag_list", "=", "[", "t", ".", "lower", "(", ")", ".", "strip", "(", ")", "for", "t", "in", "entry", ".", "tag_string", ".", "split", "(", "','", ")", "]", "for", "t", "in", "tag_list", ...
51.285714
11.714286
def get_provisioning_configuration( self, provisioning_configuration_id, custom_headers=None, raw=False, **operation_config): """GetContinuousDeploymentOperation. :param provisioning_configuration_id: :type provisioning_configuration_id: str :param dict custom_headers: heade...
[ "def", "get_provisioning_configuration", "(", "self", ",", "provisioning_configuration_id", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "*", "*", "operation_config", ")", ":", "# Construct URL", "url", "=", "'/_apis/continuousdelivery/provisioning...
42.641509
23.867925
def table(self): """Build and cache a table from query results""" if self._table is None: self._table = list(self._iter_rows()) return self._table
[ "def", "table", "(", "self", ")", ":", "if", "self", ".", "_table", "is", "None", ":", "self", ".", "_table", "=", "list", "(", "self", ".", "_iter_rows", "(", ")", ")", "return", "self", ".", "_table" ]
29.666667
16
def create_static_finding(self, application_id, vulnerability_type, description, severity, parameter=None, file_path=None, native_id=None, column=None, line_text=None, line_number=None): """ Creates a static finding with given properties. :param application_id: Appl...
[ "def", "create_static_finding", "(", "self", ",", "application_id", ",", "vulnerability_type", ",", "description", ",", "severity", ",", "parameter", "=", "None", ",", "file_path", "=", "None", ",", "native_id", "=", "None", ",", "column", "=", "None", ",", ...
44.333333
23.277778
def memory_used(self): """To know the allocated memory at function termination. ..versionadded:: 4.1 This property might return None if the function is still running. This function should help to show memory leaks or ram greedy code. """ if self._end_memory: ...
[ "def", "memory_used", "(", "self", ")", ":", "if", "self", ".", "_end_memory", ":", "memory_used", "=", "self", ".", "_end_memory", "-", "self", ".", "_start_memory", "return", "memory_used", "else", ":", "return", "None" ]
30.642857
21.857143
def on_btn_orientation(self, event): """ Create and fill wxPython grid for entering orientation data. """ wait = wx.BusyInfo('Compiling required data, please wait...') wx.SafeYield() #dw, dh = wx.DisplaySize() size = wx.DisplaySize() size = (size[0...
[ "def", "on_btn_orientation", "(", "self", ",", "event", ")", ":", "wait", "=", "wx", ".", "BusyInfo", "(", "'Compiling required data, please wait...'", ")", "wx", ".", "SafeYield", "(", ")", "#dw, dh = wx.DisplaySize()", "size", "=", "wx", ".", "DisplaySize", "(...
41.619048
19.809524
def type(self, value): """The type property. Args: value (string). the property value. """ if value == self._defaults['type'] and 'type' in self._values: del self._values['type'] else: self._values['type'] = value
[ "def", "type", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'type'", "]", "and", "'type'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'type'", "]", "else", ":", "self", ".", ...
28.9
14.5
def create_cluster(self, cluster, project_id=None, retry=DEFAULT, timeout=DEFAULT): """ Creates a cluster, consisting of the specified number and type of Google Compute Engine instances. :param cluster: A Cluster protobuf or dict. If dict is provided, it must be of the same ...
[ "def", "create_cluster", "(", "self", ",", "cluster", ",", "project_id", "=", "None", ",", "retry", "=", "DEFAULT", ",", "timeout", "=", "DEFAULT", ")", ":", "if", "isinstance", "(", "cluster", ",", "dict", ")", ":", "cluster_proto", "=", "Cluster", "(",...
47.74
24.14
def _set_link_fault_signaling(self, v, load=False): """ Setter method for link_fault_signaling, mapped from YANG variable /interface/ethernet/link_fault_signaling (container) If this variable is read-only (config: false) in the source YANG file, then _set_link_fault_signaling is considered as a private ...
[ "def", "_set_link_fault_signaling", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", "...
92.318182
43.590909
def get_object_name(object): """ Returns given object name. :param object: Object to retrieve the name. :type object: object :return: Object name. :rtype: unicode """ if type(object) is property: return object.fget.__name__ elif hasattr(object, "__name__"): return o...
[ "def", "get_object_name", "(", "object", ")", ":", "if", "type", "(", "object", ")", "is", "property", ":", "return", "object", ".", "fget", ".", "__name__", "elif", "hasattr", "(", "object", ",", "\"__name__\"", ")", ":", "return", "object", ".", "__nam...
24.388889
12.722222
def get_assessment_offered_lookup_session_for_bank(self, bank_id): """Gets the ``OsidSession`` associated with the assessment offered lookup service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the bank return: (osid.assessment.AssessmentOfferedLookupSession) - an ...
[ "def", "get_assessment_offered_lookup_session_for_bank", "(", "self", ",", "bank_id", ")", ":", "if", "not", "self", ".", "supports_assessment_offered_lookup", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "##", "# Also include check to see if the ca...
51.086957
21.956522
def _climlab_to_rrtm(field): '''Prepare field with proper dimension order. RRTM code expects arrays with (ncol, nlay) and with pressure decreasing from surface at element 0 climlab grid dimensions are any of: - (num_lev,) --> (1, num_lev) - (num_lat, num_lev) --> (num_lat, num_lev) ...
[ "def", "_climlab_to_rrtm", "(", "field", ")", ":", "# Make this work just with 1D (KM,) arrays", "# (KM,) --> (1, nlay)", "try", ":", "# Flip along the last axis to reverse the pressure order", "field", "=", "field", "[", "...", ",", ":", ":", "-", "1", "]", "except",...
34.5
18.375
def resource_from_rdf(graph_or_distrib, dataset=None): ''' Map a Resource domain model to a DCAT/RDF graph ''' if isinstance(graph_or_distrib, RdfResource): distrib = graph_or_distrib else: node = graph_or_distrib.value(predicate=RDF.type, object...
[ "def", "resource_from_rdf", "(", "graph_or_distrib", ",", "dataset", "=", "None", ")", ":", "if", "isinstance", "(", "graph_or_distrib", ",", "RdfResource", ")", ":", "distrib", "=", "graph_or_distrib", "else", ":", "node", "=", "graph_or_distrib", ".", "value",...
37.816327
19.897959
def translate_config(self, profile, merge=None, replace=None): """ Translate the object to native configuration. In this context, merge and replace means the following: * **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the values in ``merge`...
[ "def", "translate_config", "(", "self", ",", "profile", ",", "merge", "=", "None", ",", "replace", "=", "None", ")", ":", "result", "=", "[", "]", "for", "k", ",", "v", "in", "self", ":", "other_merge", "=", "getattr", "(", "merge", ",", "k", ")", ...
42.290323
25.129032
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Create User Role.""" assert wait_for_completion is True # synchronous operation try: console = hmc.consoles.lookup_by_oid(None) except KeyError: raise Inv...
[ "def", "post", "(", "method", ",", "hmc", ",", "uri", ",", "uri_parms", ",", "body", ",", "logon_required", ",", "wait_for_completion", ")", ":", "assert", "wait_for_completion", "is", "True", "# synchronous operation", "try", ":", "console", "=", "hmc", ".", ...
45
12.222222
def to_sa_pair_form(self, sparse=True): """ Convert this instance of `DiscreteDP` to SA-pair form Parameters ---------- sparse : bool, optional(default=True) Should the `Q` matrix be stored as a sparse matrix? If true the CSR format is used Retur...
[ "def", "to_sa_pair_form", "(", "self", ",", "sparse", "=", "True", ")", ":", "if", "self", ".", "_sa_pair", ":", "return", "self", "else", ":", "s_ind", ",", "a_ind", "=", "np", ".", "where", "(", "self", ".", "R", ">", "-", "np", ".", "inf", ")"...
28.903226
19.548387
def get_default_config(self): """ Returns the default collector settings """ config = super(IODriveSNMPCollector, self).get_default_config() config.update({ 'path': 'iodrive', 'timeout': 15, }) return config
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "IODriveSNMPCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'iodrive'", ",", "'timeout'", ":", "15", ",",...
28.3
13.3
def get_rendered_toctree(builder, docname, prune=False, collapse=True): """Build the toctree relative to the named document, with the given parameters, and then return the rendered HTML fragment. """ fulltoc = build_full_toctree(builder, docname, ...
[ "def", "get_rendered_toctree", "(", "builder", ",", "docname", ",", "prune", "=", "False", ",", "collapse", "=", "True", ")", ":", "fulltoc", "=", "build_full_toctree", "(", "builder", ",", "docname", ",", "prune", "=", "prune", ",", "collapse", "=", "coll...
42.333333
11.25
def publish(self, cat, **kwargs): """ This method is used for creating objects in the facebook graph. The first paramter is "cat", the category of publish. In addition to "cat" "id" must also be passed and is catched by "kwargs" """ ...
[ "def", "publish", "(", "self", ",", "cat", ",", "*", "*", "kwargs", ")", ":", "res", "=", "request", ".", "publish_cat1", "(", "\"POST\"", ",", "self", ".", "con", ",", "self", ".", "token", ",", "cat", ",", "kwargs", ")", "return", "res" ]
52.75
23
def inference(self, kern, X, Z, likelihood, Y, indexD, output_dim, Y_metadata=None, Lm=None, dL_dKmm=None, Kuu_sigma=None): """ The first phase of inference: Compute: log-likelihood, dL_dKmm Cached intermediate results: Kmm, KmmInv, """ input_dim = Z.shape[0] u...
[ "def", "inference", "(", "self", ",", "kern", ",", "X", ",", "Z", ",", "likelihood", ",", "Y", ",", "indexD", ",", "output_dim", ",", "Y_metadata", "=", "None", ",", "Lm", "=", "None", ",", "dL_dKmm", "=", "None", ",", "Kuu_sigma", "=", "None", ")"...
38.178571
24.292857
def unixjoin(*args): """ Like os.path.join, but uses forward slashes on win32 """ isabs_list = list(map(isabs, args)) if any(isabs_list): poslist = [count for count, flag in enumerate(isabs_list) if flag] pos = poslist[-1] return '/'.join(args[pos:]) else: return ...
[ "def", "unixjoin", "(", "*", "args", ")", ":", "isabs_list", "=", "list", "(", "map", "(", "isabs", ",", "args", ")", ")", "if", "any", "(", "isabs_list", ")", ":", "poslist", "=", "[", "count", "for", "count", ",", "flag", "in", "enumerate", "(", ...
29.454545
13.636364
def reset(self): """ Reset target collection (rebuild index). """ self.connection.rebuild_index( self.index, coll_name=self.target_coll_name)
[ "def", "reset", "(", "self", ")", ":", "self", ".", "connection", ".", "rebuild_index", "(", "self", ".", "index", ",", "coll_name", "=", "self", ".", "target_coll_name", ")" ]
34.6
8.4
def receivetime_delay(self, tid, days, session): '''taobao.trade.receivetime.delay 延长交易收货时间 延长交易收货时间''' request = TOPRequest('taobao.trade.receivetime.delay') request['tid'] = tid request['days'] = days self.create(self.execute(request, session)['trade']) ...
[ "def", "receivetime_delay", "(", "self", ",", "tid", ",", "days", ",", "session", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.trade.receivetime.delay'", ")", "request", "[", "'tid'", "]", "=", "tid", "request", "[", "'days'", "]", "=", "days", "s...
36
17.333333
def get_elements(self, center='500@10', asteroid=False, comet=False): """Call JPL HORIZONS website to obtain orbital elements based on the provided targetname, epochs, and center code. For valid center codes, please refer to http://ssd.jpl.nasa.gov/horizons.cgi :param center: str; ...
[ "def", "get_elements", "(", "self", ",", "center", "=", "'500@10'", ",", "asteroid", "=", "False", ",", "comet", "=", "False", ")", ":", "# encode objectname for use in URL", "objectname", "=", "urllib", ".", "quote", "(", "self", ".", "targetname", ".", "en...
46.521073
18.233716
def yearly_plots( df, variable, renormalize = True, horizontal_axis_labels_days = False, horizontal_axis_labels_months = True, plot = True, scatter = False, linestyle = "-", linewidth ...
[ "def", "yearly_plots", "(", "df", ",", "variable", ",", "renormalize", "=", "True", ",", "horizontal_axis_labels_days", "=", "False", ",", "horizontal_axis_labels_months", "=", "True", ",", "plot", "=", "True", ",", "scatter", "=", "False", ",", "linestyle", "...
38.575
20.975
def restore_trash(cookie, tokens, fidlist): '''从回收站中还原文件/目录. fildlist - 要还原的文件/目录列表, fs_id. ''' url = ''.join([ const.PAN_API_URL, 'recycle/restore?channel=chunlei&clienttype=0&web=1', '&t=', util.timestamp(), '&bdstoken=', tokens['bdstoken'], ]) data = 'fidlist=...
[ "def", "restore_trash", "(", "cookie", ",", "tokens", ",", "fidlist", ")", ":", "url", "=", "''", ".", "join", "(", "[", "const", ".", "PAN_API_URL", ",", "'recycle/restore?channel=chunlei&clienttype=0&web=1'", ",", "'&t='", ",", "util", ".", "timestamp", "(",...
29.761905
16.904762
def decode_netloc(self): """Decodes the netloc part into a string.""" rv = _decode_idna(self.host or '') if ':' in rv: rv = '[%s]' % rv port = self.port if port is not None: rv = '%s:%d' % (rv, port) auth = ':'.join(filter(None, [ _url...
[ "def", "decode_netloc", "(", "self", ")", ":", "rv", "=", "_decode_idna", "(", "self", ".", "host", "or", "''", ")", "if", "':'", "in", "rv", ":", "rv", "=", "'[%s]'", "%", "rv", "port", "=", "self", ".", "port", "if", "port", "is", "not", "None"...
31.5625
15.6875
def deserialize_property(value: Any) -> Any: """ Deserializes a single protobuf value (either `Struct` or `ListValue`) into idiomatic Python values. """ if value == UNKNOWN: return None # ListValues are projected to lists if isinstance(value, struct_pb2.ListValue): return [d...
[ "def", "deserialize_property", "(", "value", ":", "Any", ")", "->", "Any", ":", "if", "value", "==", "UNKNOWN", ":", "return", "None", "# ListValues are projected to lists", "if", "isinstance", "(", "value", ",", "struct_pb2", ".", "ListValue", ")", ":", "retu...
29.944444
16.277778
def delitem_via_sibseqs(ol,*sibseqs): ''' from elist.elist import * y = ['a',['b',["bb"]],'c'] y[1][1] delitem_via_sibseqs(y,1,1) y ''' pathlist = list(sibseqs) this = ol for i in range(0,pathlist.__len__()-1): key = pathlist[i] this = this.__g...
[ "def", "delitem_via_sibseqs", "(", "ol", ",", "*", "sibseqs", ")", ":", "pathlist", "=", "list", "(", "sibseqs", ")", "this", "=", "ol", "for", "i", "in", "range", "(", "0", ",", "pathlist", ".", "__len__", "(", ")", "-", "1", ")", ":", "key", "=...
24.6
15.8
def _expand_libs_in_apps(specs): """ Expands specs.apps.depends.libs to include any indirectly required libs """ for app_name, app_spec in specs['apps'].iteritems(): if 'depends' in app_spec and 'libs' in app_spec['depends']: app_spec['depends']['libs'] = _get_dependent('libs', app_n...
[ "def", "_expand_libs_in_apps", "(", "specs", ")", ":", "for", "app_name", ",", "app_spec", "in", "specs", "[", "'apps'", "]", ".", "iteritems", "(", ")", ":", "if", "'depends'", "in", "app_spec", "and", "'libs'", "in", "app_spec", "[", "'depends'", "]", ...
47.571429
19.285714