text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def astype(self, out_dtype): """Return a copy of this space with new ``out_dtype``. Parameters ---------- out_dtype : Output data type of the returned space. Can be given in any way `numpy.dtype` understands, e.g. as string (``'complex64'``) or built-...
[ "def", "astype", "(", "self", ",", "out_dtype", ")", ":", "out_dtype", "=", "np", ".", "dtype", "(", "out_dtype", ")", "if", "out_dtype", "==", "self", ".", "out_dtype", ":", "return", "self", "# Try to use caching for real and complex versions (exact dtype", "# m...
37.972973
16.918919
def get_dates(self): """ Returns a list of acquisition times from tile info data :return: List of acquisition times in the order returned by WFS service. :rtype: list(datetime.datetime) """ return [datetime.datetime.strptime('{}T{}'.format(tile_info['properties']['date'], ...
[ "def", "get_dates", "(", "self", ")", ":", "return", "[", "datetime", ".", "datetime", ".", "strptime", "(", "'{}T{}'", ".", "format", "(", "tile_info", "[", "'properties'", "]", "[", "'date'", "]", ",", "tile_info", "[", "'properties'", "]", "[", "'time...
55.333333
29.111111
def dummynum(character, name): """Count how many nodes there already are in the character whose name starts the same. """ num = 0 for nodename in character.node: nodename = str(nodename) if not nodename.startswith(name): continue try: nodenum = int(no...
[ "def", "dummynum", "(", "character", ",", "name", ")", ":", "num", "=", "0", "for", "nodename", "in", "character", ".", "node", ":", "nodename", "=", "str", "(", "nodename", ")", "if", "not", "nodename", ".", "startswith", "(", "name", ")", ":", "con...
26.375
14.75
def to_dict(self): """Get an equivalent dict representation.""" d = {} for k, v in self.__dict__["data"].iteritems(): if isinstance(v, RecursiveAttribute): d[k] = v.to_dict() else: d[k] = v return d
[ "def", "to_dict", "(", "self", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "__dict__", "[", "\"data\"", "]", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "RecursiveAttribute", ")", ":", "d", "[", ...
30.888889
15.555556
def gauss_distribution(function_variable, standard_deviation, mean=0): r""" Gauss distribution. The Gauss distribution is used in the function :py:func:`~.power_curves.smooth_power_curve` for power curve smoothing. Parameters ---------- function_variable : float Variable of the gau...
[ "def", "gauss_distribution", "(", "function_variable", ",", "standard_deviation", ",", "mean", "=", "0", ")", ":", "return", "(", "1", "/", "(", "standard_deviation", "*", "np", ".", "sqrt", "(", "2", "*", "np", ".", "pi", ")", ")", "*", "np", ".", "...
29.463415
23.439024
def setup(self, bitdepth=16): """Set the client format parameters, specifying the desired PCM audio data format to be read from the file. Must be called before reading from the file. """ fmt = self.get_file_format() newfmt = copy.copy(fmt) newfmt.mFormatID = AUDI...
[ "def", "setup", "(", "self", ",", "bitdepth", "=", "16", ")", ":", "fmt", "=", "self", ".", "get_file_format", "(", ")", "newfmt", "=", "copy", ".", "copy", "(", "fmt", ")", "newfmt", ".", "mFormatID", "=", "AUDIO_ID_PCM", "newfmt", ".", "mFormatFlags"...
39
9.470588
def sign_direct(self, request, authheaders, secret): """Signs a request directly with an appropriate signature. The request's Authorization header will change. Keyword arguments: request -- A request object which can be consumed by this API. authheaders -- A string-indexable object whic...
[ "def", "sign_direct", "(", "self", ",", "request", ",", "authheaders", ",", "secret", ")", ":", "sig", "=", "self", ".", "sign", "(", "request", ",", "authheaders", ",", "secret", ")", "return", "request", ".", "with_header", "(", "\"Authorization\"", ",",...
61.6
27.9
def renderInTable(self, relpath=""): """renderInTable() is called to render a data product in a table relpath is as for renderLink() above. Return value should be empty, or a valid HTML string (usually delimited by <TR></TR> tags). Default implementation renders thumbnail,comment and lin...
[ "def", "renderInTable", "(", "self", ",", "relpath", "=", "\"\"", ")", ":", "thumb", "=", "self", ".", "renderThumbnail", "(", "relpath", ")", "or", "\"\"", "comment", "=", "self", ".", "renderLinkComment", "(", "relpath", ")", "or", "\"\"", "if", "thumb...
48.333333
14.266667
def _signed_mul_overflow(state, a, b): """ Sign extend the value to 512 bits and check the result can be represented in 256. Following there is a 32 bit excerpt of this condition: a * b +00000000000000000 +00000000000000001 +0000000003fffffff +0000000007fffffff +00000000080...
[ "def", "_signed_mul_overflow", "(", "state", ",", "a", ",", "b", ")", ":", "mul", "=", "Operators", ".", "SEXTEND", "(", "a", ",", "256", ",", "512", ")", "*", "Operators", ".", "SEXTEND", "(", "b", ",", "256", ",", "512", ")", "cond", "=", "Oper...
90.944444
65.611111
def unpack_ip(fourbytes): """Converts an ip address given in a four byte string in network byte order to a string in dotted notation. >>> unpack_ip(b"dead") '100.101.97.100' >>> unpack_ip(b"alive") Traceback (most recent call last): ... ValueError: given buffer is not exactly four bytes long @type fourbytes:...
[ "def", "unpack_ip", "(", "fourbytes", ")", ":", "if", "not", "isinstance", "(", "fourbytes", ",", "bytes", ")", ":", "raise", "ValueError", "(", "\"given buffer is not a string\"", ")", "if", "len", "(", "fourbytes", ")", "!=", "4", ":", "raise", "ValueError...
30.2
16.95
def box(df, s=None, title_from=None, subplots=False, figsize=(18,6), groups=None, fcol=None, ecol=None, hatch=None, ylabel="", xlabel=""): """ Generate a box plot from pandas DataFrame with sample grouping. Plot group mean, median and deviations for specific values (proteins) in the dataset. Plotting is co...
[ "def", "box", "(", "df", ",", "s", "=", "None", ",", "title_from", "=", "None", ",", "subplots", "=", "False", ",", "figsize", "=", "(", "18", ",", "6", ")", ",", "groups", "=", "None", ",", "fcol", "=", "None", ",", "ecol", "=", "None", ",", ...
37.290076
26.114504
def build_spia_matrices(nodes: Set[str]) -> Dict[str, pd.DataFrame]: """Build an adjacency matrix for each KEGG relationship and return in a dictionary. :param nodes: A set of HGNC gene symbols :return: Dictionary of adjacency matrix for each relationship """ nodes = list(sorted(nodes)) # Crea...
[ "def", "build_spia_matrices", "(", "nodes", ":", "Set", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "pd", ".", "DataFrame", "]", ":", "nodes", "=", "list", "(", "sorted", "(", "nodes", ")", ")", "# Create sheets of the excel in the given order", "...
36.214286
19.071429
def fail(self): """Fail a vector.""" if self.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(self)) else: self.failed = True self.time_of_death = timenow() for t in self.transmissions(): t.fail...
[ "def", "fail", "(", "self", ")", ":", "if", "self", ".", "failed", "is", "True", ":", "raise", "AttributeError", "(", "\"Cannot fail {} - it has already failed.\"", ".", "format", "(", "self", ")", ")", "else", ":", "self", ".", "failed", "=", "True", "sel...
31.3
17.9
def read_data_ext(self, model: str, field: str, idx=None, astype=None): """ Return a field of a model or group at the given indices :param str model: name of the group or model to retrieve :param str field: name of the field :param list, int, float str idx: idx of elements to ac...
[ "def", "read_data_ext", "(", "self", ",", "model", ":", "str", ",", "field", ":", "str", ",", "idx", "=", "None", ",", "astype", "=", "None", ")", ":", "ret", "=", "list", "(", ")", "if", "model", "in", "self", ".", "system", ".", "devman", ".", ...
38.05
22.8
def _spelling_pipeline(self, sources, options, personal_dict): """Check spelling pipeline.""" for source in self._pipeline_step(sources, options, personal_dict): # Don't waste time on empty strings if source._has_error(): yield Results([], source.context, source....
[ "def", "_spelling_pipeline", "(", "self", ",", "sources", ",", "options", ",", "personal_dict", ")", ":", "for", "source", "in", "self", ".", "_pipeline_step", "(", "sources", ",", "options", ",", "personal_dict", ")", ":", "# Don't waste time on empty strings", ...
46.764706
19.176471
def irf(self, ts_length=100, shock=None): """ Create Impulse Response Functions Parameters ---------- ts_length : scalar(int) Number of periods to calculate IRF Shock : array_like(float) Vector of shocks to calculate IRF to. Default is first ele...
[ "def", "irf", "(", "self", ",", "ts_length", "=", "100", ",", "shock", "=", "None", ")", ":", "if", "type", "(", "shock", ")", "!=", "np", ".", "ndarray", ":", "# Default is to select first element of w", "shock", "=", "np", ".", "vstack", "(", "(", "n...
40.489362
19.382979
def approvecommittee(self, committees, account=None, **kwargs): """ Approve a committee :param list committees: list of committee member name or id :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not ...
[ "def", "approvecommittee", "(", "self", ",", "committees", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "account", "=", "self", ".", "config", ...
37.918919
19
def _run_forever(self): """ Run configured jobs until termination request. """ while True: try: tick = time.time() asyncore.loop(timeout=self.POLL_TIMEOUT, use_poll=True) # Sleep for remaining poll cycle time tick += s...
[ "def", "_run_forever", "(", "self", ")", ":", "while", "True", ":", "try", ":", "tick", "=", "time", ".", "time", "(", ")", "asyncore", ".", "loop", "(", "timeout", "=", "self", ".", "POLL_TIMEOUT", ",", "use_poll", "=", "True", ")", "# Sleep for remai...
44.111111
23.185185
def record(self, *args, **kwargs): """Track and record values each day. Parameters ---------- **kwargs The names and values to record. Notes ----- These values will appear in the performance packets and the performance dataframe passed to ``a...
[ "def", "record", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Make 2 objects both referencing the same iterator", "args", "=", "[", "iter", "(", "args", ")", "]", "*", "2", "# Zip generates list entries by calling `next` on each iterator it", ...
38.166667
21.375
def repository_has_cookiecutter_json(repo_directory): """Determine if `repo_directory` contains a `cookiecutter.json` file. :param repo_directory: The candidate repository directory. :return: True if the `repo_directory` is valid, else False. """ repo_directory_exists = os.path.isdir(repo_directory...
[ "def", "repository_has_cookiecutter_json", "(", "repo_directory", ")", ":", "repo_directory_exists", "=", "os", ".", "path", ".", "isdir", "(", "repo_directory", ")", "repo_config_exists", "=", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "jo...
39.333333
18.5
def user_present(name, password, email, tenant=None, enabled=True, roles=None, profile=None, password_reset=True, project=None, **connection_args): ''' Ensure ...
[ "def", "user_present", "(", "name", ",", "password", ",", "email", ",", "tenant", "=", "None", ",", "enabled", "=", "True", ",", "roles", "=", "None", ",", "profile", "=", "None", ",", "password_reset", "=", "True", ",", "project", "=", "None", ",", ...
40.691542
22.761194
def query_saved_guest_screen_info(self, screen_id): """Returns the guest dimensions from the saved state. in screen_id of type int Saved guest screen to query info from. out origin_x of type int The X position of the guest monitor top left corner. out origin_y ...
[ "def", "query_saved_guest_screen_info", "(", "self", ",", "screen_id", ")", ":", "if", "not", "isinstance", "(", "screen_id", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"screen_id can only be an instance of type baseinteger\"", ")", "(", "origin_x", ",...
37.037037
22.148148
def on_change(self, attr, *callbacks): ''' Add a callback on this object to trigger when ``attr`` changes. Args: attr (str) : an attribute name on this object callback (callable) : a callback function to register Returns: None ''' if len(cal...
[ "def", "on_change", "(", "self", ",", "attr", ",", "*", "callbacks", ")", ":", "if", "len", "(", "callbacks", ")", "==", "0", ":", "raise", "ValueError", "(", "\"on_change takes an attribute name and one or more callbacks, got only one parameter\"", ")", "_callbacks",...
30
26.521739
def save_hdf_metadata(filename, metadata, groupname="data", mode="a"): """"Save a dictionary of metadata to a group's attrs.""" with _h5py.File(filename, mode) as f: for key, val in metadata.items(): f[groupname].attrs[key] = val
[ "def", "save_hdf_metadata", "(", "filename", ",", "metadata", ",", "groupname", "=", "\"data\"", ",", "mode", "=", "\"a\"", ")", ":", "with", "_h5py", ".", "File", "(", "filename", ",", "mode", ")", "as", "f", ":", "for", "key", ",", "val", "in", "me...
50.6
6.6
def list_from_env(key, default=""): """ Splits a string in the format "a,b,c,d,e,f" into ['a', 'b', 'c', 'd', 'e', 'f', ] """ try: val = os.environ.get(key, default) return val.split(',') except (KeyError, ValueError): return []
[ "def", "list_from_env", "(", "key", ",", "default", "=", "\"\"", ")", ":", "try", ":", "val", "=", "os", ".", "environ", ".", "get", "(", "key", ",", "default", ")", "return", "val", ".", "split", "(", "','", ")", "except", "(", "KeyError", ",", ...
26.7
9.5
def Group(self): """Return group object for group containing this server. >>> clc.v2.Server("CA3BTDICNTRLM01").Group() <clc.APIv2.group.Group object at 0x10b07b7d0> >>> print _ Ansible Managed Servers """ return(clc.v2.Group(id=self.groupId,alias=self.alias,session=self.session))
[ "def", "Group", "(", "self", ")", ":", "return", "(", "clc", ".", "v2", ".", "Group", "(", "id", "=", "self", ".", "groupId", ",", "alias", "=", "self", ".", "alias", ",", "session", "=", "self", ".", "session", ")", ")" ]
26.090909
21.454545
def from_xdr(cls, xdr): """Create a new :class:`TransactionEnvelope` from an XDR string. :param xdr: The XDR string that represents a transaction envelope. :type xdr: bytes, str """ xdr_decoded = base64.b64decode(xdr) te = Xdr.StellarXDRUnpacker(xdr_decoded)...
[ "def", "from_xdr", "(", "cls", ",", "xdr", ")", ":", "xdr_decoded", "=", "base64", ".", "b64decode", "(", "xdr", ")", "te", "=", "Xdr", ".", "StellarXDRUnpacker", "(", "xdr_decoded", ")", "te_xdr_object", "=", "te", ".", "unpack_TransactionEnvelope", "(", ...
38.111111
15.166667
def apply(self, fn): """ Apply an arbitrary function to ANTsImage. Args ---- fn : python function or lambda function to apply to ENTIRE image at once Returns ------- ANTsImage image with function applied to it """ ...
[ "def", "apply", "(", "self", ",", "fn", ")", ":", "this_array", "=", "self", ".", "numpy", "(", ")", "new_array", "=", "fn", "(", "this_array", ")", "return", "self", ".", "new_image_like", "(", "new_array", ")" ]
24.117647
16.235294
def release(self): """Release a lock.""" self.__lock.release() with self.__condition: self.__condition.notify()
[ "def", "release", "(", "self", ")", ":", "self", ".", "__lock", ".", "release", "(", ")", "with", "self", ".", "__condition", ":", "self", ".", "__condition", ".", "notify", "(", ")" ]
28.6
9.2
def launch(title, items, selected=None): """ Launches a new menu. Wraps curses nicely so exceptions won't screw with the terminal too much. """ resp = {"code": -1, "done": False} curses.wrapper(Menu, title, items, selected, resp) return resp
[ "def", "launch", "(", "title", ",", "items", ",", "selected", "=", "None", ")", ":", "resp", "=", "{", "\"code\"", ":", "-", "1", ",", "\"done\"", ":", "False", "}", "curses", ".", "wrapper", "(", "Menu", ",", "title", ",", "items", ",", "selected"...
36.25
11.25
def evaluate_classifier_fraction_sparse(input_, labels, per_example_weights=None, topk=1, name=PROVIDED, phase=Phase.tra...
[ "def", "evaluate_classifier_fraction_sparse", "(", "input_", ",", "labels", ",", "per_example_weights", "=", "None", ",", "topk", "=", "1", ",", "name", "=", "PROVIDED", ",", "phase", "=", "Phase", ".", "train", ")", ":", "_", "=", "name", "# Suppress lint",...
46.948718
20.948718
def mailto(to, cc=None, bcc=None, subject=None, body=None): """ Generate and run mailto. :type to: string :param to: The recipient email address. :type cc: string :param cc: The recipient to copy to. :type bcc: string :param bcc: The recipient to blind copy to. :type subject: str...
[ "def", "mailto", "(", "to", ",", "cc", "=", "None", ",", "bcc", "=", "None", ",", "subject", "=", "None", ",", "body", "=", "None", ")", ":", "mailurl", "=", "'mailto:'", "+", "str", "(", "to", ")", "if", "cc", "is", "None", "and", "bcc", "is",...
24.613636
16.840909
def json_encode(obj: Instance, **kwargs) -> str: """ Encodes an object to JSON using our custom encoder. The ``**kwargs`` can be used to pass things like ``'indent'``, for formatting. """ return json.dumps(obj, cls=JsonClassEncoder, **kwargs)
[ "def", "json_encode", "(", "obj", ":", "Instance", ",", "*", "*", "kwargs", ")", "->", "str", ":", "return", "json", ".", "dumps", "(", "obj", ",", "cls", "=", "JsonClassEncoder", ",", "*", "*", "kwargs", ")" ]
32.5
17
def show_env(): ''' Show Environment used by Oracle Client CLI Example: .. code-block:: bash salt '*' oracle.show_env .. note:: at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8' ''' envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result = {} for ...
[ "def", "show_env", "(", ")", ":", "envs", "=", "[", "'PATH'", ",", "'ORACLE_HOME'", ",", "'TNS_ADMIN'", ",", "'NLS_LANG'", "]", "result", "=", "{", "}", "for", "env", "in", "envs", ":", "if", "env", "in", "os", ".", "environ", ":", "result", "[", "...
21.263158
23.894737
def find_transaction_objects(adapter, **kwargs): # type: (BaseAdapter, **Iterable) -> List[Transaction] """ Finds transactions matching the specified criteria, fetches the corresponding trytes and converts them into Transaction objects. """ ft_response = FindTransactionsCommand(adapter)(**kwargs...
[ "def", "find_transaction_objects", "(", "adapter", ",", "*", "*", "kwargs", ")", ":", "# type: (BaseAdapter, **Iterable) -> List[Transaction]", "ft_response", "=", "FindTransactionsCommand", "(", "adapter", ")", "(", "*", "*", "kwargs", ")", "hashes", "=", "ft_respons...
30.789474
19.315789
def close(self): """Persist a checksum and close the file.""" fname = os.path.basename(self._path) checksum_persister = _get_checksum_persister(self._path) with contextlib.closing(checksum_persister): checksum_persister[fname] = self._hasher.hexdigest() self._close()
[ "def", "close", "(", "self", ")", ":", "fname", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "_path", ")", "checksum_persister", "=", "_get_checksum_persister", "(", "self", ".", "_path", ")", "with", "contextlib", ".", "closing", "(", "che...
39.125
18.375
def string(html, start_on=None, ignore=(), use_short=True, **queries): '''Returns a blox template from an html string''' if use_short: html = grow_short(html) return _to_template(fromstring(html), start_on=start_on, ignore=ignore, **queries)
[ "def", "string", "(", "html", ",", "start_on", "=", "None", ",", "ignore", "=", "(", ")", ",", "use_short", "=", "True", ",", "*", "*", "queries", ")", ":", "if", "use_short", ":", "html", "=", "grow_short", "(", "html", ")", "return", "_to_template"...
46.666667
17.333333
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']): """place a leaf node""" if part.startswith(':'): if self.param and self.param != part: err = """Cannot place param '{}' as '{self.param_name}' exist on node already!""" raise ParamAlreadyExist(e...
[ "def", "place", "(", "self", ",", "part", ":", "str", ",", "val", ":", "Union", "[", "'ApiNode'", ",", "'ApiEndpoint'", "]", ")", ":", "if", "part", ".", "startswith", "(", "':'", ")", ":", "if", "self", ".", "param", "and", "self", ".", "param", ...
43.090909
12.545455
def get_inj_param(injfile, param, ifo, args=None): """ Translates some popular injection parameters into functions that calculate them from an hdf found injection file Parameters ---------- injfile: hdf5 File object Injection file of format known to ANitz (DOCUMENTME) param: string ...
[ "def", "get_inj_param", "(", "injfile", ",", "param", ",", "ifo", ",", "args", "=", "None", ")", ":", "det", "=", "pycbc", ".", "detector", ".", "Detector", "(", "ifo", ")", "inj", "=", "injfile", "[", "\"injections\"", "]", "if", "param", "in", "inj...
35.4
19.342857
def getServiceLevel(self): """Returns the service level""" command = '$GE' settings = self.sendCommand(command) flags = int(settings[2], 16) return (flags & 0x0001) + 1
[ "def", "getServiceLevel", "(", "self", ")", ":", "command", "=", "'$GE'", "settings", "=", "self", ".", "sendCommand", "(", "command", ")", "flags", "=", "int", "(", "settings", "[", "2", "]", ",", "16", ")", "return", "(", "flags", "&", "0x0001", ")...
30.5
8.666667
def handoverComplete(MobileTimeDifference_presence=0): """HANDOVER COMPLETE Section 9.1.16""" a = TpPd(pd=0x6) b = MessageType(mesType=0x2c) # 00101100 c = RrCause() packet = a / b / c if MobileTimeDifference_presence is 1: d = MobileTimeDifferenceHdr(ieiMTD=0x77, eightBitMTD=0x0) ...
[ "def", "handoverComplete", "(", "MobileTimeDifference_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x6", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x2c", ")", "# 00101100", "c", "=", "RrCause", "(", ")", "packet", "=", "a...
35.1
14.3
def _get_struct_rect(self): """Get the RECT structure.""" bc = BitConsumer(self._src) nbits = bc.u_get(5) if self._read_twips: return tuple(bc.s_get(nbits) for _ in range(4)) else: return tuple(bc.s_get(nbits) / 20.0 for _ in range(4))
[ "def", "_get_struct_rect", "(", "self", ")", ":", "bc", "=", "BitConsumer", "(", "self", ".", "_src", ")", "nbits", "=", "bc", ".", "u_get", "(", "5", ")", "if", "self", ".", "_read_twips", ":", "return", "tuple", "(", "bc", ".", "s_get", "(", "nbi...
36.5
14.375
def set(self, section, key, value): """ Set a config value. It's not dumped on the disk. If the section doesn't exists the section is created """ conf = self.get_section_config(section) if isinstance(value, bool): conf[key] = str(value) else:...
[ "def", "set", "(", "self", ",", "section", ",", "key", ",", "value", ")", ":", "conf", "=", "self", ".", "get_section_config", "(", "section", ")", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "conf", "[", "key", "]", "=", "str", "(", ...
27.428571
13.142857
def migrate(self, mapping, index, doc_type): """ Migrate a ES mapping :param mapping: new mapping :param index: index of old mapping :param doc_type: type of old mapping :return: The diff mapping """ old_mapping = self.get_doctype(index, doc_type) ...
[ "def", "migrate", "(", "self", ",", "mapping", ",", "index", ",", "doc_type", ")", ":", "old_mapping", "=", "self", ".", "get_doctype", "(", "index", ",", "doc_type", ")", "#case missing", "if", "not", "old_mapping", ":", "self", ".", "connection", ".", ...
32.291667
14.791667
def get_single_int_pk_colname(table_: Table) -> Optional[str]: """ If a table has a single-field (non-composite) integer PK, this will return its database column name; otherwise, None. Note that it is legitimate for a database table to have both a composite primary key and a separate ``IDENTITY`` (...
[ "def", "get_single_int_pk_colname", "(", "table_", ":", "Table", ")", "->", "Optional", "[", "str", "]", ":", "n_pks", "=", "0", "int_pk_names", "=", "[", "]", "for", "col", "in", "table_", ".", "columns", ":", "if", "col", ".", "primary_key", ":", "n_...
36.263158
16.789474
def get_rule_by_pk(self, id_rule): """ Get a rule by its identifier :param id_rule: Rule identifier. :return: Seguinte estrutura :: { 'rule': {'id': < id >, 'environment': < Environment Object >, 'content': < content >, 'n...
[ "def", "get_rule_by_pk", "(", "self", ",", "id_rule", ")", ":", "url", "=", "'rule/get_by_id/'", "+", "str", "(", "id_rule", ")", "code", ",", "xml", "=", "self", ".", "submit", "(", "None", ",", "'GET'", ",", "url", ")", "return", "self", ".", "resp...
34.08
17.6
def _set_all_axis_color(self, axis, color): """Set axis ticks, title, labels to given color""" for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks', 'title', 'labels']: prop_set = getattr(axis.properties, prop) if color and prop in ['title', 'labels']: ...
[ "def", "_set_all_axis_color", "(", "self", ",", "axis", ",", "color", ")", ":", "for", "prop", "in", "[", "'ticks'", ",", "'axis'", ",", "'major_ticks'", ",", "'minor_ticks'", ",", "'title'", ",", "'labels'", "]", ":", "prop_set", "=", "getattr", "(", "a...
54
14
def create_language_dataset_from_url(self, file_url, token=None, url=API_CREATE_LANGUAGE_DATASET): """ Creates a dataset from a publicly accessible file stored in the cloud. :param file_url: string, in the form of a URL to a file accessible on the cloud. Popular options include Dropbox,...
[ "def", "create_language_dataset_from_url", "(", "self", ",", "file_url", ",", "token", "=", "None", ",", "url", "=", "API_CREATE_LANGUAGE_DATASET", ")", ":", "auth", "=", "'Bearer '", "+", "self", ".", "check_for_token", "(", "token", ")", "dummy_files", "=", ...
60.6875
30.625
def expand_templates(pars, context, return_left=False, client=False, getenv=True, getshell=True): """ Render variables in context into the set of parameters with jinja2. For variables that are not strings, nothing happens. Parameters ---------- pars: dict values ar...
[ "def", "expand_templates", "(", "pars", ",", "context", ",", "return_left", "=", "False", ",", "client", "=", "False", ",", "getenv", "=", "True", ",", "getshell", "=", "True", ")", ":", "all_vars", "=", "set", "(", "context", ")", "out", "=", "_expand...
30.925926
21.666667
def receive_message(self, message, data): """ Called when a media message is received. """ if data[MESSAGE_TYPE] == TYPE_MEDIA_STATUS: self._process_media_status(data) return True return False
[ "def", "receive_message", "(", "self", ",", "message", ",", "data", ")", ":", "if", "data", "[", "MESSAGE_TYPE", "]", "==", "TYPE_MEDIA_STATUS", ":", "self", ".", "_process_media_status", "(", "data", ")", "return", "True", "return", "False" ]
29.375
16.625
def start_receive(self, stream): """ Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as ready for reading. Safe to call from any thread. When the associated file descriptor becomes ready for reading, :meth:`BasicStream.on_receive` will be called. """ ...
[ "def", "start_receive", "(", "self", ",", "stream", ")", ":", "_vv", "and", "IOLOG", ".", "debug", "(", "'%r.start_receive(%r)'", ",", "self", ",", "stream", ")", "side", "=", "stream", ".", "receive_side", "assert", "side", "and", "side", ".", "fd", "is...
45.75
12.916667
def transform_list_to_dict(list): """ Transforms a list into a dictionary, putting values as keys Args: id: Returns: dict: dictionary built """ ret = {} for value in list: if isinstance(value, dict): ret.update(value) else: ret[st...
[ "def", "transform_list_to_dict", "(", "list", ")", ":", "ret", "=", "{", "}", "for", "value", "in", "list", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "ret", ".", "update", "(", "value", ")", "else", ":", "ret", "[", "str", "(", ...
18.611111
20.722222
def mesh(self, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1.), fname=None, meshdata=None): """Show a 3D mesh Parameters ---------- vertices : array Vertices. faces : array | None Face defini...
[ "def", "mesh", "(", "self", ",", "vertices", "=", "None", ",", "faces", "=", "None", ",", "vertex_colors", "=", "None", ",", "face_colors", "=", "None", ",", "color", "=", "(", "0.5", ",", "0.5", ",", "1.", ")", ",", "fname", "=", "None", ",", "m...
36.425532
17.787234
def _extract_packages(self): """ Extract a package in a new temporary directory. """ self.path_unpacked = mkdtemp(prefix="scoap3_package_", dir=CFG_TMPSHAREDDIR) for path in self.retrieved_packages_unpacked: scoap3utils_extract_pac...
[ "def", "_extract_packages", "(", "self", ")", ":", "self", ".", "path_unpacked", "=", "mkdtemp", "(", "prefix", "=", "\"scoap3_package_\"", ",", "dir", "=", "CFG_TMPSHAREDDIR", ")", "for", "path", "in", "self", ".", "retrieved_packages_unpacked", ":", "scoap3uti...
38.9
16.5
def make_logger(self, level="INFO"): """ Convenience function which creates a logger for the module. INPUTS: level (default="INFO"): Minimum log level for logged/streamed messages. OUTPUTS: logger Logger for the function. NOTE: Must be bound to ...
[ "def", "make_logger", "(", "self", ",", "level", "=", "\"INFO\"", ")", ":", "level", "=", "getattr", "(", "logging", ",", "level", ".", "upper", "(", ")", ")", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "setLevel",...
30.517241
24.241379
def save_config(self, volume, channel, theme, netease): """ 存储历史记录和登陆信息 """ self.login_data['cookies'] = self.cookies self.login_data['volume'] = volume self.login_data['channel'] = channel self.login_data['theme_id'] = theme self.login_data['netease'] = n...
[ "def", "save_config", "(", "self", ",", "volume", ",", "channel", ",", "theme", ",", "netease", ")", ":", "self", ".", "login_data", "[", "'cookies'", "]", "=", "self", ".", "cookies", "self", ".", "login_data", "[", "'volume'", "]", "=", "volume", "se...
41.4375
7.6875
def safe_str(obj): """ return the byte string representation of obj """ try: return str(obj) except UnicodeEncodeError: # obj is unicode try: return unicode(obj).encode('unicode_escape') # noqa for undefined-variable except NameError: # This is Python...
[ "def", "safe_str", "(", "obj", ")", ":", "try", ":", "return", "str", "(", "obj", ")", "except", "UnicodeEncodeError", ":", "# obj is unicode", "try", ":", "return", "unicode", "(", "obj", ")", ".", "encode", "(", "'unicode_escape'", ")", "# noqa for undefin...
34.545455
21.818182
def _build_kernel_call(self, name='kernel'): """Generate and return kernel call ast.""" return c_ast.FuncCall(name=c_ast.ID(name=name), args=c_ast.ExprList(exprs=[ c_ast.ID(name=d.name) for d in ( self._build_array_declarations()[0] + self._build_scala...
[ "def", "_build_kernel_call", "(", "self", ",", "name", "=", "'kernel'", ")", ":", "return", "c_ast", ".", "FuncCall", "(", "name", "=", "c_ast", ".", "ID", "(", "name", "=", "name", ")", ",", "args", "=", "c_ast", ".", "ExprList", "(", "exprs", "=", ...
55.428571
14
def _send(self): """ BFD packet sender. """ # If the switch was not connected to controller, exit. if self.datapath is None: return # BFD Flags Setup flags = 0 if self._pending_final: flags |= bfd.BFD_FLAG_FINAL self._...
[ "def", "_send", "(", "self", ")", ":", "# If the switch was not connected to controller, exit.", "if", "self", ".", "datapath", "is", "None", ":", "return", "# BFD Flags Setup", "flags", "=", "0", "if", "self", ".", "_pending_final", ":", "flags", "|=", "bfd", "...
37.990196
17.872549
def getQuotes(self, symbol, start, end): """ Get historical prices for the given ticker symbol. Date format is 'YYYY-MM-DD' Returns a nested list. """ try: start = str(start).replace('-', '') end = str(end).replace('-', '') ...
[ "def", "getQuotes", "(", "self", ",", "symbol", ",", "start", ",", "end", ")", ":", "try", ":", "start", "=", "str", "(", "start", ")", ".", "replace", "(", "'-'", ",", "''", ")", "end", "=", "str", "(", "end", ")", ".", "replace", "(", "'-'", ...
45.057143
22.428571
def connect(self, slot): """ Connects the signal to any callable object """ if not callable(slot): raise ValueError("Connection to non-callable '%s' object failed" % slot.__class__.__name__) if (isinstance(slot, partial) or '<' in slot.__name__): # If it'...
[ "def", "connect", "(", "self", ",", "slot", ")", ":", "if", "not", "callable", "(", "slot", ")", ":", "raise", "ValueError", "(", "\"Connection to non-callable '%s' object failed\"", "%", "slot", ".", "__class__", ".", "__name__", ")", "if", "(", "isinstance",...
45.217391
16.608696
def augment_resource_ids(self, resource_ids): """ Given a list of resource IDs, returns a list of dicts containing detailed information about the specified resources and their children. This function recurses to a maximum of two levels when fetching children from the specified resources. ...
[ "def", "augment_resource_ids", "(", "self", ",", "resource_ids", ")", ":", "resources_augmented", "=", "[", "]", "for", "id", "in", "resource_ids", ":", "# resource_data = self.get_resource_component_and_children(id, recurse_max_level=2)", "# resources_augmented.append(resource_d...
48.45
30.45
def _load_from_config(self, config_file): """Load zabbix server IP address and port from zabbix agent config file. If ServerActive variable is not found in the file, it will use the default: 127.0.0.1:10051 :type config_file: str :param use_config: Path to zabbix_agentd...
[ "def", "_load_from_config", "(", "self", ",", "config_file", ")", ":", "if", "config_file", "and", "isinstance", "(", "config_file", ",", "bool", ")", ":", "config_file", "=", "'/etc/zabbix/zabbix_agentd.conf'", "logger", ".", "debug", "(", "\"Used config: %s\"", ...
35.859649
19.385965
def load_nddata(self, ndd, naxispath=None): """Load from an astropy.nddata.NDData object. """ self.clear_metadata() # Make a header based on any NDData metadata ahdr = self.get_header() ahdr.update(ndd.meta) self.setup_data(ndd.data, naxispath=naxispath) ...
[ "def", "load_nddata", "(", "self", ",", "ndd", ",", "naxispath", "=", "None", ")", ":", "self", ".", "clear_metadata", "(", ")", "# Make a header based on any NDData metadata", "ahdr", "=", "self", ".", "get_header", "(", ")", "ahdr", ".", "update", "(", "nd...
36.761905
16.095238
def get_redis_connection(): """ Get the redis connection if not using mock """ if config.MOCK_REDIS: # pragma: no cover import mockredis return mockredis.mock_strict_redis_client() # pragma: no cover elif config.DEFENDER_REDIS_NAME: # pragma: no cover try: cache = cach...
[ "def", "get_redis_connection", "(", ")", ":", "if", "config", ".", "MOCK_REDIS", ":", "# pragma: no cover", "import", "mockredis", "return", "mockredis", ".", "mock_strict_redis_client", "(", ")", "# pragma: no cover", "elif", "config", ".", "DEFENDER_REDIS_NAME", ":"...
45.269231
13.576923
def cmd_tracker_param(self, args): '''Parameter commands''' if not self.connection: print("tracker not connected") return self.pstate.handle_command(self.connection, self.mpstate, args)
[ "def", "cmd_tracker_param", "(", "self", ",", "args", ")", ":", "if", "not", "self", ".", "connection", ":", "print", "(", "\"tracker not connected\"", ")", "return", "self", ".", "pstate", ".", "handle_command", "(", "self", ".", "connection", ",", "self", ...
38
13
def update_available_item_relationships(app): """ Update directive option_spec with custom relationships defined in configuration file ``traceability_relationships`` variable. Both keys (relationships) and values (reverse relationships) are added. This handler should be called upon builder initial...
[ "def", "update_available_item_relationships", "(", "app", ")", ":", "env", "=", "app", ".", "builder", ".", "env", "env", ".", "relationships", "=", "{", "}", "for", "rel", "in", "list", "(", "app", ".", "config", ".", "traceability_relationships", ".", "k...
38.913043
25.347826
def _notify(self, data): """Notify this channel of inbound data""" payload = tlv.decode( payload=data.get('payload'), content_type=data.get('ct'), decode_b64=True ) super(CurrentResourceValue, self)._notify(payload) # after one response, close ...
[ "def", "_notify", "(", "self", ",", "data", ")", ":", "payload", "=", "tlv", ".", "decode", "(", "payload", "=", "data", ".", "get", "(", "'payload'", ")", ",", "content_type", "=", "data", ".", "get", "(", "'ct'", ")", ",", "decode_b64", "=", "Tru...
35.2
10.7
def _make_type_verifier(dataType, nullable=True, name=None): """ Make a verifier that checks the type of obj against dataType and raises a TypeError if they do not match. This verifier also checks the value of obj against datatype and raises a ValueError if it's not within the allowed range, e.g. u...
[ "def", "_make_type_verifier", "(", "dataType", ",", "nullable", "=", "True", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "new_msg", "=", "lambda", "msg", ":", "msg", "new_name", "=", "lambda", "n", ":", "\"field %s\"", "%", "n"...
37.4
20.336842
def print_values(values, width=70): """Print the given values in multiple lines with a certain maximum width. By default, each line contains at most 70 characters: >>> from hydpy import print_values >>> print_values(range(21)) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
[ "def", "print_values", "(", "values", ",", "width", "=", "70", ")", ":", "for", "line", "in", "textwrap", ".", "wrap", "(", "repr_values", "(", "values", ")", ",", "width", "=", "width", ")", ":", "print", "(", "line", ")" ]
31.1
19.3
def add_isohybrid(self, part_entry=1, mbr_id=None, part_offset=0, geometry_sectors=32, geometry_heads=64, part_type=0x17, mac=False): # type: (int, Optional[int], int, int, int, int, bool) -> None ''' Make an ISO a 'hybrid', which means that it can be ...
[ "def", "add_isohybrid", "(", "self", ",", "part_entry", "=", "1", ",", "mbr_id", "=", "None", ",", "part_offset", "=", "0", ",", "geometry_sectors", "=", "32", ",", "geometry_heads", "=", "64", ",", "part_type", "=", "0x17", ",", "mac", "=", "False", "...
56.844444
34.311111
def from_array(name, array, dim_names = None): """ Construct a LIGO Light Weight XML Array document subtree from a numpy array object. Example: >>> import numpy, sys >>> a = numpy.arange(12, dtype = "double") >>> a.shape = (4, 3) >>> from_array(u"test", a).write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE <...
[ "def", "from_array", "(", "name", ",", "array", ",", "dim_names", "=", "None", ")", ":", "# Type must be set for .__init__(); easier to set Name afterwards", "# to take advantage of encoding handled by attribute proxy", "doc", "=", "Array", "(", "Attributes", "(", "{", "u\...
29.542857
22.057143
def create_or_update_issue_remote_links(self, issue_key, link_url, title, global_id=None, relationship=None): """ Add Remote Link to Issue, update url if global_id is passed :param issue_key: str :param link_url: str :param title: str :param global_id: str, OPTIONAL: ...
[ "def", "create_or_update_issue_remote_links", "(", "self", ",", "issue_key", ",", "link_url", ",", "title", ",", "global_id", "=", "None", ",", "relationship", "=", "None", ")", ":", "url", "=", "'rest/api/2/issue/{issue_key}/remotelink'", ".", "format", "(", "iss...
44.8125
17.5625
def list_datastores_via_proxy(datastore_names=None, backing_disk_ids=None, backing_disk_scsi_addresses=None, service_instance=None): ''' Returns a list of dict representations of the datastores visible to the proxy object. The list of datastores ca...
[ "def", "list_datastores_via_proxy", "(", "datastore_names", "=", "None", ",", "backing_disk_ids", "=", "None", ",", "backing_disk_scsi_addresses", "=", "None", ",", "service_instance", "=", "None", ")", ":", "target", "=", "_get_proxy_target", "(", "service_instance",...
42.475
21.625
def update_option_by_id(cls, option_id, option, **kwargs): """Update Option Update attributes of Option This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_option_by_id(option_id, option, a...
[ "def", "update_option_by_id", "(", "cls", ",", "option_id", ",", "option", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_updat...
42.818182
20.954545
def load_febrl1(return_links=False): """Load the FEBRL 1 dataset. The Freely Extensible Biomedical Record Linkage (Febrl) package is distributed with a dataset generator and four datasets generated with the generator. This function returns the first Febrl dataset as a :class:`pandas.DataFrame`. ...
[ "def", "load_febrl1", "(", "return_links", "=", "False", ")", ":", "df", "=", "_febrl_load_data", "(", "'dataset1.csv'", ")", "if", "return_links", ":", "links", "=", "_febrl_links", "(", "df", ")", "return", "df", ",", "links", "else", ":", "return", "df"...
29.117647
23.676471
def r_passage(self, objectId, subreference, lang=None): """ Retrieve the text of the passage :param objectId: Collection identifier :type objectId: str :param lang: Lang in which to express main data :type lang: str :param subreference: Reference identifier :type...
[ "def", "r_passage", "(", "self", ",", "objectId", ",", "subreference", ",", "lang", "=", "None", ")", ":", "collection", "=", "self", ".", "get_collection", "(", "objectId", ")", "if", "isinstance", "(", "collection", ",", "CtsWorkMetadata", ")", ":", "edi...
46.302326
19.162791
def barcode(iban, reference, amount, due=None): """Calculates virtual barcode for IBAN account number and ISO reference Arguments: iban {string} -- IBAN formed account number reference {string} -- ISO 11649 creditor reference amount {decimal.Decimal} -- Amount in euros, 0.01 - 999999.99...
[ "def", "barcode", "(", "iban", ",", "reference", ",", "amount", ",", "due", "=", "None", ")", ":", "iban", "=", "iban", ".", "replace", "(", "' '", ",", "''", ")", "reference", "=", "reference", ".", "replace", "(", "' '", ",", "''", ")", "if", "...
31.795455
23.931818
def write_array(self, outfile, pixels): """ Write an array in flat row flat pixel format as a PNG file on the output file. See also :meth:`write` method. """ if self.interlace: self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: ...
[ "def", "write_array", "(", "self", ",", "outfile", ",", "pixels", ")", ":", "if", "self", ".", "interlace", ":", "self", ".", "write_passes", "(", "outfile", ",", "self", ".", "array_scanlines_interlace", "(", "pixels", ")", ")", "else", ":", "self", "."...
37.1
19.3
def output_diagnostics(env, result, verbose=0, **kwargs): """Output diagnostic information.""" if verbose > 0: diagnostic_table = formatting.Table(['name', 'value']) diagnostic_table.add_row(['execution_time', '%fs' % (time.time() - START_TIME)]) api_call_value = [] for call in...
[ "def", "output_diagnostics", "(", "env", ",", "result", ",", "verbose", "=", "0", ",", "*", "*", "kwargs", ")", ":", "if", "verbose", ">", "0", ":", "diagnostic_table", "=", "formatting", ".", "Table", "(", "[", "'name'", ",", "'value'", "]", ")", "d...
43.114286
24.6
def _upload_file(self, authdata, attachment, reg_key): """ Step 2: auth successful, and file not on server zotero.org/support/dev/server_api/file_upload#a_full_upload reg_key isn't used, but we need to pass it through to Step 3 """ upload_dict = authdata[ "pa...
[ "def", "_upload_file", "(", "self", ",", "authdata", ",", "attachment", ",", "reg_key", ")", ":", "upload_dict", "=", "authdata", "[", "\"params\"", "]", "# using params now since prefix/suffix concat was giving ConnectionError", "# must pass tuple of tuples not dict to ensure ...
39.540541
16.027027
def read(cls, proto): """ :param proto: capnp TwoGramModelProto message reader """ instance = object.__new__(cls) super(TwoGramModel, instance).__init__(proto=proto.modelBase) instance._logger = opf_utils.initLogger(instance) instance._reset = proto.reset instance._hashToValueDict = {x...
[ "def", "read", "(", "cls", ",", "proto", ")", ":", "instance", "=", "object", ".", "__new__", "(", "cls", ")", "super", "(", "TwoGramModel", ",", "instance", ")", ".", "__init__", "(", "proto", "=", "proto", ".", "modelBase", ")", "instance", ".", "_...
41.08
19.08
def from_string(cls, fstring, fname=None, readers=None): """Create a Document from a byte string containing the contents of a file. Usage:: contents = open('paper.html', 'rb').read() doc = Document.from_string(contents) .. note:: This method expects a byte...
[ "def", "from_string", "(", "cls", ",", "fstring", ",", "fname", "=", "None", ",", "readers", "=", "None", ")", ":", "if", "readers", "is", "None", ":", "from", ".", ".", "reader", "import", "DEFAULT_READERS", "readers", "=", "DEFAULT_READERS", "if", "isi...
39.941176
25.382353
def modifyReject(LowLayerCompatibility_presence=0, HighLayerCompatibility_presence=0): """MODIFY REJECT Section 9.3.15""" a = TpPd(pd=0x3) b = MessageType(mesType=0x13) # 00010011 c = BearerCapability() d = Cause() packet = a / b / c / d if LowLayerCompatibility_presence is...
[ "def", "modifyReject", "(", "LowLayerCompatibility_presence", "=", "0", ",", "HighLayerCompatibility_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x13", ")", "# 00010011", "c", ...
37.533333
13.933333
def pstdev(data): """Calculates the population standard deviation.""" n = len(data) if n < 2: return 0 # raise ValueError('variance requires at least two data points') ss = TableExtraction._ss(data) pvar = ss/n # the population variance return pvar...
[ "def", "pstdev", "(", "data", ")", ":", "n", "=", "len", "(", "data", ")", "if", "n", "<", "2", ":", "return", "0", "# raise ValueError('variance requires at least two data points')", "ss", "=", "TableExtraction", ".", "_ss", "(", "data", ")", "pvar", "=", ...
35.222222
16
def random(cls, mu=1.0, alphabet='nuc'): """ Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap') """ alphabet=alph...
[ "def", "random", "(", "cls", ",", "mu", "=", "1.0", ",", "alphabet", "=", "'nuc'", ")", ":", "alphabet", "=", "alphabets", "[", "alphabet", "]", "gtr", "=", "cls", "(", "alphabet", ")", "n", "=", "gtr", ".", "alphabet", ".", "shape", "[", "0", "]...
23.041667
20.875
def fl2norm2(xf, axis=(0, 1)): r""" Compute the squared :math:`\ell_2` norm in the DFT domain, taking into account the unnormalised DFT scaling, i.e. given the DFT of a multi-dimensional array computed via :func:`fftn`, return the squared :math:`\ell_2` norm of the original array. Parameters ...
[ "def", "fl2norm2", "(", "xf", ",", "axis", "=", "(", "0", ",", "1", ")", ")", ":", "xfs", "=", "xf", ".", "shape", "return", "(", "np", ".", "linalg", ".", "norm", "(", "xf", ")", "**", "2", ")", "/", "np", ".", "prod", "(", "np", ".", "a...
32.416667
23.708333
def valueFromString(self, value, context=None): """ Converts the inputted string text to a value that matches the type from this column type. :param value | <str> """ if value == 'now': return datetime.datetime.now().time() elif dateutil_parser: ...
[ "def", "valueFromString", "(", "self", ",", "value", ",", "context", "=", "None", ")", ":", "if", "value", "==", "'now'", ":", "return", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "time", "(", ")", "elif", "dateutil_parser", ":", "return",...
37.625
15.5
def on_person_new(self, people): """ Add new people All people supported need to be added simultaneously, since on every call a unjoin() followed by a join() is issued :param people: People to add :type people: list[paps.people.People] :rtype: None :rais...
[ "def", "on_person_new", "(", "self", ",", "people", ")", ":", "try", ":", "self", ".", "on_person_leave", "(", "[", "]", ")", "except", ":", "# Already caught and logged", "pass", "try", ":", "self", ".", "sensor_client", ".", "join", "(", "people", ")", ...
28.956522
18
def run_inference_on_image(image): """Runs inference on an image. Args: image: Image file name. Returns: Nothing """ if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() # Creates graph from saved GraphDef. cr...
[ "def", "run_inference_on_image", "(", "image", ")", ":", "if", "not", "tf", ".", "gfile", ".", "Exists", "(", "image", ")", ":", "tf", ".", "logging", ".", "fatal", "(", "'File does not exist %s'", ",", "image", ")", "image_data", "=", "tf", ".", "gfile"...
33.842105
19.868421
def area_frac_vs_chempot_plot(self, ref_delu, chempot_range, delu_dict=None, delu_default=0, increments=10, no_clean=False, no_doped=False): """ 1D plot. Plots the change in the area contribution of each facet as a function of chemical potential. Args: ...
[ "def", "area_frac_vs_chempot_plot", "(", "self", ",", "ref_delu", ",", "chempot_range", ",", "delu_dict", "=", "None", ",", "delu_default", "=", "0", ",", "increments", "=", "10", ",", "no_clean", "=", "False", ",", "no_doped", "=", "False", ")", ":", "del...
46.322581
25.548387
def _broadcast_shape(*args): """Return the shape that would result from broadcasting the inputs""" #TODO: currently incorrect result if a Sequence is provided as an input shapes = [a.shape if hasattr(type(a), '__array_interface__') else () for a in args] ndim = max(len(sh) for sh in shapes...
[ "def", "_broadcast_shape", "(", "*", "args", ")", ":", "#TODO: currently incorrect result if a Sequence is provided as an input", "shapes", "=", "[", "a", ".", "shape", "if", "hasattr", "(", "type", "(", "a", ")", ",", "'__array_interface__'", ")", "else", "(", ")...
53.2
16.9
def get_without_ethernet(self, id_or_uri): """ Gets the logical downlink with the specified ID without ethernet. Args: id_or_uri: Can be either the logical downlink id or the logical downlink uri. Returns: dict """ uri = self._client.build_uri(id...
[ "def", "get_without_ethernet", "(", "self", ",", "id_or_uri", ")", ":", "uri", "=", "self", ".", "_client", ".", "build_uri", "(", "id_or_uri", ")", "+", "\"/withoutEthernet\"", "return", "self", ".", "_client", ".", "get", "(", "uri", ")" ]
31.25
22.583333
def _wait_for_travis_build(url, commit, committed_at): """ Waits for a Travis build to appear with the given commit SHA """ print('Waiting for a Travis build to appear ' 'for `%s` after `%s`...' % (commit, committed_at)) import requests slug = _slug_from_url(url) start_time = time.time() ...
[ "def", "_wait_for_travis_build", "(", "url", ",", "commit", ",", "committed_at", ")", ":", "print", "(", "'Waiting for a Travis build to appear '", "'for `%s` after `%s`...'", "%", "(", "commit", ",", "committed_at", ")", ")", "import", "requests", "slug", "=", "_sl...
41.851064
22.021277
def _get_dir_list(load): ''' Get a list of all directories on the master ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') if 'saltenv' not in load or load['saltenv'] not in envs(): return [] ret = set() for repo in init(): repo['...
[ "def", "_get_dir_list", "(", "load", ")", ":", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "if", "'saltenv'", "not", "in", "load", "or", "load", "[", "'saltenv'", "]", "not", "in", ...
35.096774
16.709677
def no_type_check_decorator(decorator): """Decorator to give another decorator the @no_type_check effect. This wraps the decorator with something that wraps the decorated function in @no_type_check. """ @functools.wraps(decorator) def wrapped_decorator(*args, **kwds): func = decorator(...
[ "def", "no_type_check_decorator", "(", "decorator", ")", ":", "@", "functools", ".", "wraps", "(", "decorator", ")", "def", "wrapped_decorator", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "func", "=", "decorator", "(", "*", "args", ",", "*", "*...
29
14.857143
def set_aad_cache(token, cache): """Set AAD token cache.""" set_config_value('aad_token', jsonpickle.encode(token)) set_config_value('aad_cache', jsonpickle.encode(cache))
[ "def", "set_aad_cache", "(", "token", ",", "cache", ")", ":", "set_config_value", "(", "'aad_token'", ",", "jsonpickle", ".", "encode", "(", "token", ")", ")", "set_config_value", "(", "'aad_cache'", ",", "jsonpickle", ".", "encode", "(", "cache", ")", ")" ]
45
11.5
def destination_absent(name, server=None): ''' Ensures that the JMS Destination doesn't exists name Name of the JMS Destination ''' ret = {'name': name, 'result': None, 'comment': None, 'changes': {}} jms_ret = _do_element_absent(name, 'admin_object_resource', {}, server) if not jms...
[ "def", "destination_absent", "(", "name", ",", "server", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ":", "None", ",", "'changes'", ":", "{", "}", "}", "jms_ret", "=", "_do_element_abse...
34.454545
19.454545
def get_func_params(method, called_params): """ :type method: function :type called_params: dict :return: """ insp = inspect.getfullargspec(method) if not isinstance(called_params, dict): raise UserWarning() _called_params = called_params.copy() params = {} arg_count = le...
[ "def", "get_func_params", "(", "method", ",", "called_params", ")", ":", "insp", "=", "inspect", ".", "getfullargspec", "(", "method", ")", "if", "not", "isinstance", "(", "called_params", ",", "dict", ")", ":", "raise", "UserWarning", "(", ")", "_called_par...
36.837838
13.432432
def setup_components_and_tf_funcs(self, custom_getter=None): """ Allows child models to create model's component objects, such as optimizer(s), memory(s), etc.. Creates all tensorflow functions via tf.make_template calls on all the class' "tf_"-methods. Args: custom_getter: ...
[ "def", "setup_components_and_tf_funcs", "(", "self", ",", "custom_getter", "=", "None", ")", ":", "if", "custom_getter", "is", "None", ":", "def", "custom_getter", "(", "getter", ",", "name", ",", "registered", "=", "False", ",", "*", "*", "kwargs", ")", "...
42.015152
18.560606