text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _Close(self): """Closes the file-like object.""" super(VHDIFile, self)._Close() for vhdi_file in self._parent_vhdi_files: vhdi_file.close() for file_object in self._sub_file_objects: file_object.close() self._parent_vhdi_files = [] self._sub_file_objects = []
[ "def", "_Close", "(", "self", ")", ":", "super", "(", "VHDIFile", ",", "self", ")", ".", "_Close", "(", ")", "for", "vhdi_file", "in", "self", ".", "_parent_vhdi_files", ":", "vhdi_file", ".", "close", "(", ")", "for", "file_object", "in", "self", ".",...
24.25
0.009934
def delete_bucket(): """ Delete S3 Bucket """ args = parser.parse_args s3_bucket(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name)().delete()
[ "def", "delete_bucket", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "s3_bucket", "(", "args", ".", "aws_access_key_id", ",", "args", ".", "aws_secret_access_key", ",", "args", ".", "bucket_name", ")", "(", ")", ".", "delete", "(", ")" ]
29.333333
0.01105
def handleMethodCallMessage(self, msg): """ Handles DBus MethodCall messages on behalf of the DBus Connection and dispatches them to the appropriate exported object """ if ( msg.interface == 'org.freedesktop.DBus.Peer' and msg.member == 'Ping' ): ...
[ "def", "handleMethodCallMessage", "(", "self", ",", "msg", ")", ":", "if", "(", "msg", ".", "interface", "==", "'org.freedesktop.DBus.Peer'", "and", "msg", ".", "member", "==", "'Ping'", ")", ":", "r", "=", "message", ".", "MethodReturnMessage", "(", "msg", ...
29.598726
0.000416
def _convert_punctuation( line ): ''' Converts given analysis line if it describes punctuation; Uses the set of predefined punctuation conversion rules from _punctConversions; _punctConversions should be a list of lists, where each outer list stands for a single conversion rule an...
[ "def", "_convert_punctuation", "(", "line", ")", ":", "for", "[", "pattern", ",", "replacement", "]", "in", "_punctConversions", ":", "lastline", "=", "line", "line", "=", "re", ".", "sub", "(", "pattern", ",", "replacement", ",", "line", ")", "if", "las...
42.888889
0.013942
def export_csv(self, table, output=None, columns="*", **kwargs): """ Export a table to a CSV file. If an output path is provided, write to file. Else, return a string. Wrapper around pandas.sql.to_csv(). See: http://pandas.pydata.org/pandas-docs/stable/io.html#io-store-...
[ "def", "export_csv", "(", "self", ",", "table", ",", "output", "=", "None", ",", "columns", "=", "\"*\"", ",", "*", "*", "kwargs", ")", ":", "import", "pandas", ".", "io", ".", "sql", "as", "panda", "# Determine if we're writing to a file or returning a string...
33.173913
0.001273
def ricker(f, length, dt): """ A Ricker wavelet. Args: f (float): frequency in Haz, e.g. 25 Hz. length (float): Length in s, e.g. 0.128. dt (float): sample interval in s, e.g. 0.001. Returns: tuple. time basis, amplitude values. """ t = np.linspace(-int(length/2...
[ "def", "ricker", "(", "f", ",", "length", ",", "dt", ")", ":", "t", "=", "np", ".", "linspace", "(", "-", "int", "(", "length", "/", "2", ")", ",", "int", "(", "(", "length", "-", "dt", ")", "/", "2", ")", ",", "int", "(", "length", "/", ...
29.133333
0.002217
def parse(self, p_todo): """ Returns fully parsed string from 'format_string' attribute with all placeholders properly substituted by content obtained from p_todo. It uses preprocessed form of 'format_string' (result of ListFormatParser._preprocess_format) stored in 'format_list...
[ "def", "parse", "(", "self", ",", "p_todo", ")", ":", "parsed_list", "=", "[", "]", "repl_trunc", "=", "None", "for", "substr", ",", "placeholder", ",", "getter", "in", "self", ".", "format_list", ":", "repl", "=", "getter", "(", "p_todo", ")", "if", ...
35.225
0.002072
def solve_status_str(hdrlbl, fmtmap=None, fwdth0=4, fwdthdlt=6, fprec=2): """Construct header and format details for status display of an iterative solver. Parameters ---------- hdrlbl : tuple of strings Tuple of field header strings fmtmap : dict or None, optional (d...
[ "def", "solve_status_str", "(", "hdrlbl", ",", "fmtmap", "=", "None", ",", "fwdth0", "=", "4", ",", "fwdthdlt", "=", "6", ",", "fprec", "=", "2", ")", ":", "if", "fmtmap", "is", "None", ":", "fmtmap", "=", "{", "}", "fwdthn", "=", "fprec", "+", "...
35.661538
0.00042
def cut(self, selection, smart_selection_adaption=False): """Cuts all selected items and copy them to the clipboard using smart selection adaptation by default :param selection: the current selection :param bool smart_selection_adaption: flag to enable smart selection adaptation mode :r...
[ "def", "cut", "(", "self", ",", "selection", ",", "smart_selection_adaption", "=", "False", ")", ":", "assert", "isinstance", "(", "selection", ",", "Selection", ")", "import", "rafcon", ".", "gui", ".", "helpers", ".", "state_machine", "as", "gui_helper_state...
62.741935
0.009114
def unflatten(flat_weights): """ Pivot weights from long DataFrame into weighting matrix. Parameters ---------- flat_weights: pandas.DataFrame A long DataFrame of weights, where columns are "date", "contract", "generic", "weight" and optionally "key". If "key" column is pres...
[ "def", "unflatten", "(", "flat_weights", ")", ":", "# NOQA", "if", "flat_weights", ".", "columns", ".", "contains", "(", "\"key\"", ")", ":", "weights", "=", "{", "}", "for", "key", "in", "flat_weights", ".", "loc", "[", ":", ",", "\"key\"", "]", ".", ...
40.903846
0.000459
def onKey(self, event): """ Copy selection if control down and 'c' """ if event.CmdDown() or event.ControlDown(): if event.GetKeyCode() == 67: self.onCopySelection(None)
[ "def", "onKey", "(", "self", ",", "event", ")", ":", "if", "event", ".", "CmdDown", "(", ")", "or", "event", ".", "ControlDown", "(", ")", ":", "if", "event", ".", "GetKeyCode", "(", ")", "==", "67", ":", "self", ".", "onCopySelection", "(", "None"...
31.857143
0.008734
def fso_mkdir(self, path, mode=None): 'overlays os.mkdir()' path = self.deref(path, to_parent=True) if self._lexists(path): raise OSError(17, 'File exists', path) self._addentry(OverlayEntry(self, path, stat.S_IFDIR))
[ "def", "fso_mkdir", "(", "self", ",", "path", ",", "mode", "=", "None", ")", ":", "path", "=", "self", ".", "deref", "(", "path", ",", "to_parent", "=", "True", ")", "if", "self", ".", "_lexists", "(", "path", ")", ":", "raise", "OSError", "(", "...
39
0.008368
def kron(*matrices: np.ndarray) -> np.ndarray: """Computes the kronecker product of a sequence of matrices. A *args version of lambda args: functools.reduce(np.kron, args). Args: *matrices: The matrices and controls to combine with the kronecker product. Returns: The resul...
[ "def", "kron", "(", "*", "matrices", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "product", "=", "np", ".", "eye", "(", "1", ")", "for", "m", "in", "matrices", ":", "product", "=", "np", ".", "kron", "(", "product", ",", "m...
27.4375
0.002203
def lookup(self, plain_src_ns): """Given a plain source namespace, return the corresponding Namespace object, or None if it is not included. """ # Ignore the namespace if it is excluded. if plain_src_ns in self._ex_namespace_set: return None # Include all name...
[ "def", "lookup", "(", "self", ",", "plain_src_ns", ")", ":", "# Ignore the namespace if it is excluded.", "if", "plain_src_ns", "in", "self", ".", "_ex_namespace_set", ":", "return", "None", "# Include all namespaces if there are no included namespaces.", "if", "not", "self...
44.111111
0.001848
def stats(self): """ Return statistics calculated overall samples of all utterances in the corpus. Returns: DataStats: A DataStats object containing statistics overall samples in the corpus. """ per_utt_stats = self.stats_per_utterance() return stats.DataSta...
[ "def", "stats", "(", "self", ")", ":", "per_utt_stats", "=", "self", ".", "stats_per_utterance", "(", ")", "return", "stats", ".", "DataStats", ".", "concatenate", "(", "per_utt_stats", ".", "values", "(", ")", ")" ]
34.9
0.011173
def get_x(self, var, coords=None): """ Get the x-coordinate of a variable This method searches for the x-coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'X', otherwise it looks whether there is an intersection ...
[ "def", "get_x", "(", "self", ",", "var", ",", "coords", "=", "None", ")", ":", "coords", "=", "coords", "or", "self", ".", "ds", ".", "coords", "coord", "=", "self", ".", "get_variable_by_axis", "(", "var", ",", "'x'", ",", "coords", ")", "if", "co...
39.111111
0.001848
def make_simple_step_size_update_policy(num_adaptation_steps, target_rate=0.75, decrement_multiplier=0.01, increment_multiplier=0.01, step_counter=None): """C...
[ "def", "make_simple_step_size_update_policy", "(", "num_adaptation_steps", ",", "target_rate", "=", "0.75", ",", "decrement_multiplier", "=", "0.01", ",", "increment_multiplier", "=", "0.01", ",", "step_counter", "=", "None", ")", ":", "if", "step_counter", "is", "N...
43.912621
0.002378
def to_dataset_files(self, local_path=None, remote_path=None): """ Save the GDataframe to a local or remote location :param local_path: a local path to the folder in which the data must be saved :param remote_path: a remote dataset name that wants to be used for these data :return: None...
[ "def", "to_dataset_files", "(", "self", ",", "local_path", "=", "None", ",", "remote_path", "=", "None", ")", ":", "return", "FrameToGMQL", ".", "to_dataset_files", "(", "self", ",", "path_local", "=", "local_path", ",", "path_remote", "=", "remote_path", ")" ...
52.875
0.011628
def load_zip_data(zipname, f_sino_real, f_sino_imag, f_angles=None, f_phantom=None, f_info=None): """Load example sinogram data from a .zip file""" ret = [] with zipfile.ZipFile(str(zipname)) as arc: sino_real = np.loadtxt(arc.open(f_sino_real)) sino_imag = np.loadtxt(arc.o...
[ "def", "load_zip_data", "(", "zipname", ",", "f_sino_real", ",", "f_sino_imag", ",", "f_angles", "=", "None", ",", "f_phantom", "=", "None", ",", "f_info", "=", "None", ")", ":", "ret", "=", "[", "]", "with", "zipfile", ".", "ZipFile", "(", "str", "(",...
38.28
0.001019
def _post_connect(self): """Initialize authentication when the connection is established and we are the initiator.""" if not self.initiator: if "plain" in self.auth_methods or "digest" in self.auth_methods: self.set_iq_get_handler("query","jabber:iq:auth", ...
[ "def", "_post_connect", "(", "self", ")", ":", "if", "not", "self", ".", "initiator", ":", "if", "\"plain\"", "in", "self", ".", "auth_methods", "or", "\"digest\"", "in", "self", ".", "auth_methods", ":", "self", ".", "set_iq_get_handler", "(", "\"query\"", ...
47.8125
0.011538
def mset(self, values): """Set the value of several keys at once. Args: values (dict): maps a key to its value. """ for key, value in values.items(): self.set(key, value)
[ "def", "mset", "(", "self", ",", "values", ")", ":", "for", "key", ",", "value", "in", "values", ".", "items", "(", ")", ":", "self", ".", "set", "(", "key", ",", "value", ")" ]
27.5
0.008811
def from_google(cls, google_x, google_y, zoom): """Creates a tile from Google format X Y and zoom""" max_tile = (2 ** zoom) - 1 assert 0 <= google_x <= max_tile, 'Google X needs to be a value between 0 and (2^zoom) -1.' assert 0 <= google_y <= max_tile, 'Google Y needs to be a value betw...
[ "def", "from_google", "(", "cls", ",", "google_x", ",", "google_y", ",", "zoom", ")", ":", "max_tile", "=", "(", "2", "**", "zoom", ")", "-", "1", "assert", "0", "<=", "google_x", "<=", "max_tile", ",", "'Google X needs to be a value between 0 and (2^zoom) -1....
69.666667
0.009456
def froze_it(cls): """ Decorator to prevent from creating attributes in the object ouside __init__(). This decorator must be applied to the final class (doesn't work if a decorated class is inherited). Yoann's answer at http://stackoverflow.com/questions/3603502 """ cls._frozen = ...
[ "def", "froze_it", "(", "cls", ")", ":", "cls", ".", "_frozen", "=", "False", "def", "frozensetattr", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "_frozen", "and", "not", "hasattr", "(", "self", ",", "key", ")", ":", "raise"...
30.724138
0.002176
def main(): from IPython import embed """ Python 3.6.6 ibttl 2.605194091796875 ttl 3.8316309452056885 diff lt - ttl -1.2264368534088135 librdfxml 31.267616748809814 rdfxml 58.25124502182007 diff lr - rl -26.983628273010254 simple time 17.405116319656372 """ """ Python 3.5.3 ...
[ "def", "main", "(", ")", ":", "from", "IPython", "import", "embed", "\"\"\" Python 3.5.3 (pypy3)\n libttl 2.387338638305664\n ttl 1.3430471420288086\n diff lt - ttl 1.0442914962768555\n librdfxml 24.70371127128601\n rdfxml 17.85916304588318\n diff lr - rl 6.844548225402832\n s...
29.611111
0.001816
def to_bed12(f, db, child_type='exon', name_field='ID'): """ Given a top-level feature (e.g., transcript), construct a BED12 entry Parameters ---------- f : Feature object or string This is the top-level feature represented by one BED12 line. For a canonical GFF or GTF, this will ge...
[ "def", "to_bed12", "(", "f", ",", "db", ",", "child_type", "=", "'exon'", ",", "name_field", "=", "'ID'", ")", ":", "if", "isinstance", "(", "f", ",", "six", ".", "string_types", ")", ":", "f", "=", "db", "[", "f", "]", "children", "=", "list", "...
34.162162
0.000769
def prepare_body(self, data, files): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None length = None is_stream = all([ h...
[ "def", "prepare_body", "(", "self", ",", "data", ",", "files", ")", ":", "# Check if file, fo, generator, iterator.", "# If not, run through normal process.", "# Nottin' on you.", "body", "=", "None", "content_type", "=", "None", "length", "=", "None", "is_stream", "=",...
32.04
0.002423
def redact_http_basic_auth(output): ''' Remove HTTP user and password ''' # We can't use re.compile because re.compile(someregex).sub() doesn't # support flags even in Python 2.7. url_re = '(https?)://.*@' redacted = r'\1://<redacted>@' if sys.version_info >= (2, 7): # re.sub() s...
[ "def", "redact_http_basic_auth", "(", "output", ")", ":", "# We can't use re.compile because re.compile(someregex).sub() doesn't", "# support flags even in Python 2.7.", "url_re", "=", "'(https?)://.*@'", "redacted", "=", "r'\\1://<redacted>@'", "if", "sys", ".", "version_info", ...
40.25
0.001214
def _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances using just nearest neighbors. This method is approximately equal to _joint_probabilities. The latter is O(N), but limiting the joint probability to nearest neighbors improv...
[ "def", "_joint_probabilities_nn", "(", "distances", ",", "neighbors", ",", "desired_perplexity", ",", "verbose", ")", ":", "t0", "=", "time", "(", ")", "# Compute conditional probabilities such that they approximately match", "# the desired perplexity", "n_samples", ",", "k...
35.203704
0.000512
def construct(self, sp_entity_id, attrconvs, policy, issuer, farg, authn_class=None, authn_auth=None, authn_decl=None, encrypt=None, sec_context=None, authn_decl_ref=None, authn_instant="", subject_locality="", authn_statem=None, name_id=None, sess...
[ "def", "construct", "(", "self", ",", "sp_entity_id", ",", "attrconvs", ",", "policy", ",", "issuer", ",", "farg", ",", "authn_class", "=", "None", ",", "authn_auth", "=", "None", ",", "authn_decl", "=", "None", ",", "encrypt", "=", "None", ",", "sec_con...
43.260274
0.002167
def format_scheme(scheme, slug): """Change $scheme so it can be applied to a template.""" scheme['scheme-name'] = scheme.pop('scheme') scheme['scheme-author'] = scheme.pop('author') scheme['scheme-slug'] = slug bases = ['base{:02X}'.format(x) for x in range(0, 16)] for base in bases: sch...
[ "def", "format_scheme", "(", "scheme", ",", "slug", ")", ":", "scheme", "[", "'scheme-name'", "]", "=", "scheme", ".", "pop", "(", "'scheme'", ")", "scheme", "[", "'scheme-author'", "]", "=", "scheme", ".", "pop", "(", "'author'", ")", "scheme", "[", "...
47.44
0.000826
def plot_ts(ax, agemin, agemax, timescale='gts12', ylabel="Age (Ma)"): """ Make a time scale plot between specified ages. Parameters: ------------ ax : figure object agemin : Minimum age for timescale agemax : Maximum age for timescale timescale : Time Scale [ default is Gradstein et al...
[ "def", "plot_ts", "(", "ax", ",", "agemin", ",", "agemax", ",", "timescale", "=", "'gts12'", ",", "ylabel", "=", "\"Age (Ma)\"", ")", ":", "ax", ".", "set_title", "(", "timescale", ".", "upper", "(", ")", ")", "ax", ".", "axis", "(", "[", "-", ".25...
35.061224
0.000566
def add_actor(self, uinput, reset_camera=False, name=None, loc=None, culling=False): """ Adds an actor to render window. Creates an actor if input is a mapper. Parameters ---------- uinput : vtk.vtkMapper or vtk.vtkActor vtk mapper or vtk a...
[ "def", "add_actor", "(", "self", ",", "uinput", ",", "reset_camera", "=", "False", ",", "name", "=", "None", ",", "loc", "=", "None", ",", "culling", "=", "False", ")", ":", "# Remove actor by that name if present", "rv", "=", "self", ".", "remove_actor", ...
28.060606
0.001565
def snapshot (self): """Take a snapshot of the experiment. Returns `self`.""" nextSnapshotNum = self.nextSnapshotNum nextSnapshotPath = self.getFullPathToSnapshot(nextSnapshotNum) if os.path.lexists(nextSnapshotPath): self.rmR(nextSnapshotPath) self.mkdirp(os.path.join(nextSnapshotPath...
[ "def", "snapshot", "(", "self", ")", ":", "nextSnapshotNum", "=", "self", ".", "nextSnapshotNum", "nextSnapshotPath", "=", "self", ".", "getFullPathToSnapshot", "(", "nextSnapshotNum", ")", "if", "os", ".", "path", ".", "lexists", "(", "nextSnapshotPath", ")", ...
35.818182
0.039604
def _get_serv(ret=None): ''' Return an influxdb client object ''' _options = _get_options(ret) host = _options.get('host') port = _options.get('port') database = _options.get('db') user = _options.get('user') password = _options.get('password') version = _get_version(host, port, ...
[ "def", "_get_serv", "(", "ret", "=", "None", ")", ":", "_options", "=", "_get_options", "(", "ret", ")", "host", "=", "_options", ".", "get", "(", "'host'", ")", "port", "=", "_options", ".", "get", "(", "'port'", ")", "database", "=", "_options", "....
32.307692
0.012717
def run_func(self, func, load): ''' Wrapper for running functions executed with AES encryption :param function func: The function to run :return: The result of the master function that was called ''' # Don't honor private functions if func.startswith('__'): ...
[ "def", "run_func", "(", "self", ",", "func", ",", "load", ")", ":", "# Don't honor private functions", "if", "func", ".", "startswith", "(", "'__'", ")", ":", "# TODO: return some error? Seems odd to return {}", "return", "{", "}", ",", "{", "'fun'", ":", "'send...
39.925
0.001834
def start(self, key=None, **params): """initialize process timing for the current stack""" self.params.update(**params) key = key or self.stack_key if key is not None: self.current_times[key] = time()
[ "def", "start", "(", "self", ",", "key", "=", "None", ",", "*", "*", "params", ")", ":", "self", ".", "params", ".", "update", "(", "*", "*", "params", ")", "key", "=", "key", "or", "self", ".", "stack_key", "if", "key", "is", "not", "None", ":...
34.333333
0.033175
def command(state, args): """Register watching regexp for an anime.""" args = parser.parse_args(args[1:]) aid = state.results.parse_aid(args.aid, default_key='db') if args.query: # Use regexp provided by user. regexp = '.*'.join(args.query) else: # Make default regexp. ...
[ "def", "command", "(", "state", ",", "args", ")", ":", "args", "=", "parser", ".", "parse_args", "(", "args", "[", "1", ":", "]", ")", "aid", "=", "state", ".", "results", ".", "parse_aid", "(", "args", ".", "aid", ",", "default_key", "=", "'db'", ...
40
0.001221
def _nac(self, q_direction): """nac_term = (A1 (x) A2) / B * coef. """ num_atom = self._pcell.get_number_of_atoms() nac_q = np.zeros((num_atom, num_atom, 3, 3), dtype='double') if (np.abs(q_direction) < 1e-5).all(): return nac_q rec_lat = np.linalg.inv(self._...
[ "def", "_nac", "(", "self", ",", "q_direction", ")", ":", "num_atom", "=", "self", ".", "_pcell", ".", "get_number_of_atoms", "(", ")", "nac_q", "=", "np", ".", "zeros", "(", "(", "num_atom", ",", "num_atom", ",", "3", ",", "3", ")", ",", "dtype", ...
34.56
0.002252
def throw(self, command): """ Posts an exception's stacktrace string as returned by 'traceback.format_exc()' in an 'except' block. :param command: The command object that holds all the necessary information from the remote process. """ exception_message = '[Process {}{}]:\n{}'.fo...
[ "def", "throw", "(", "self", ",", "command", ")", ":", "exception_message", "=", "'[Process {}{}]:\\n{}'", ".", "format", "(", "command", ".", "pid", ",", "' - {}'", ".", "format", "(", "command", ".", "process_title", ")", "if", "command", ".", "process_tit...
42.6
0.008037
def ConsultarTipoRetencion(self, sep="||"): "Consulta de tipos de Retenciones." ret = self.client.tipoRetencionConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['ti...
[ "def", "ConsultarTipoRetencion", "(", "self", ",", "sep", "=", "\"||\"", ")", ":", "ret", "=", "self", ".", "client", ".", "tipoRetencionConsultar", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self", ".", "Sign", "...
47.538462
0.009524
def _createGsshaPyObjects(self, cell): """ Create GSSHAPY GridPipeCell and GridPipeNode Objects Method """ # Initialize GSSHAPY GridPipeCell object gridCell = GridPipeCell(cellI=cell['i'], cellJ=cell['j'], numPipes=c...
[ "def", "_createGsshaPyObjects", "(", "self", ",", "cell", ")", ":", "# Initialize GSSHAPY GridPipeCell object", "gridCell", "=", "GridPipeCell", "(", "cellI", "=", "cell", "[", "'i'", "]", ",", "cellJ", "=", "cell", "[", "'j'", "]", ",", "numPipes", "=", "ce...
40.05
0.002439
def estimateHeritabilities(self, K, verbose=False): """ estimate variance components and fixed effects from a single trait model having only two terms """ # Fit single trait model varg = SP.zeros(self.P) varn = SP.zeros(self.P) fixed = SP.zeros(...
[ "def", "estimateHeritabilities", "(", "self", ",", "K", ",", "verbose", "=", "False", ")", ":", "# Fit single trait model", "varg", "=", "SP", ".", "zeros", "(", "self", ".", "P", ")", "varn", "=", "SP", ".", "zeros", "(", "self", ".", "P", ")", "fix...
28.514286
0.01938
def annotations_class(cls): """Works like annotations, but is only applicable to classes. """ assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use insp...
[ "def", "annotations_class", "(", "cls", ")", ":", "assert", "(", "isclass", "(", "cls", ")", ")", "# To play it safe we avoid to modify the dict while iterating over it,", "# so we previously cache keys.", "# For this we don't use keys() because of Python 3.", "# Todo: Better use ins...
35.375
0.001721
def evaluation_metrics(predicted, actual, bow=True): """ Input: predicted, actual = lists of the predicted and actual tokens bow: if true use bag of words assumption Returns: precision, recall, F1, Levenshtein distance """ if bow: p = set(predicted) a = set(ac...
[ "def", "evaluation_metrics", "(", "predicted", ",", "actual", ",", "bow", "=", "True", ")", ":", "if", "bow", ":", "p", "=", "set", "(", "predicted", ")", "a", "=", "set", "(", "actual", ")", "true_positive", "=", "0", "for", "token", "in", "p", ":...
27.632653
0.001427
def is_multi_target(target): """ Determine if pipeline manager's run target is multiple. :param None or str or Sequence of str target: 0, 1, or multiple targets :return bool: Whether there are multiple targets :raise TypeError: if the argument is neither None nor string nor Sequence """ if ...
[ "def", "is_multi_target", "(", "target", ")", ":", "if", "target", "is", "None", "or", "isinstance", "(", "target", ",", "str", ")", ":", "return", "False", "elif", "isinstance", "(", "target", ",", "Sequence", ")", ":", "return", "len", "(", "target", ...
38.666667
0.001684
def main(args=sys.argv[1:]): """ Run Grole static file server """ args = parse_args(args) if args.verbose: logging.basicConfig(level=logging.DEBUG) elif args.quiet: logging.basicConfig(level=logging.ERROR) else: logging.basicConfig(level=logging.INFO) app = Grole(...
[ "def", "main", "(", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "args", "=", "parse_args", "(", "args", ")", "if", "args", ".", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", ")", "el...
28.928571
0.002392
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data.get("properties", {}) load_balancing_rules = [] for raw_content in properties.get("loadBalancingRules", []): resource = Resource.from_raw_data(raw_content) ...
[ "def", "process_raw_data", "(", "cls", ",", "raw_data", ")", ":", "properties", "=", "raw_data", ".", "get", "(", "\"properties\"", ",", "{", "}", ")", "load_balancing_rules", "=", "[", "]", "for", "raw_content", "in", "properties", ".", "get", "(", "\"loa...
42.75
0.001634
def list_images(self): # type: () -> List[str] """ List images stored in the registry. Returns: list[str]: List of image names. """ r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth) return r.json()['repositories']
[ "def", "list_images", "(", "self", ")", ":", "# type: () -> List[str]", "r", "=", "self", ".", "get", "(", "self", ".", "registry_url", "+", "'/v2/_catalog'", ",", "auth", "=", "self", ".", "auth", ")", "return", "r", ".", "json", "(", ")", "[", "'repo...
31.222222
0.010381
def get_dstat_provider_args(provider, project): """A string with the arguments to point dstat to the same provider+project.""" provider_name = get_provider_name(provider) args = [] if provider_name == 'google': args.append('--project %s' % project) elif provider_name == 'google-v2': args.append('--pr...
[ "def", "get_dstat_provider_args", "(", "provider", ",", "project", ")", ":", "provider_name", "=", "get_provider_name", "(", "provider", ")", "args", "=", "[", "]", "if", "provider_name", "==", "'google'", ":", "args", ".", "append", "(", "'--project %s'", "%"...
33.842105
0.019667
def threatlist(self, ip: str): """Return threatlist information we have for the given IPv{4,6} address with history of changes """ url_path = "/api/threatlist/{ip}".format(ip=ip) return self._request(path=url_path)
[ "def", "threatlist", "(", "self", ",", "ip", ":", "str", ")", ":", "url_path", "=", "\"/api/threatlist/{ip}\"", ".", "format", "(", "ip", "=", "ip", ")", "return", "self", ".", "_request", "(", "path", "=", "url_path", ")" ]
48.4
0.012195
def candidates(self, word): """ Generate possible spelling corrections for the provided word up to an edit distance of two, if and only when needed Args: word (str): The word for which to calculate candidate spellings Returns: set: The set of ...
[ "def", "candidates", "(", "self", ",", "word", ")", ":", "if", "self", ".", "known", "(", "[", "word", "]", ")", ":", "# short-cut if word is correct already", "return", "{", "word", "}", "# get edit distance 1...", "res", "=", "[", "x", "for", "x", "in", ...
40.142857
0.002317
def last_location_of_maximum(x): """ Returns the relative last location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float ...
[ "def", "last_location_of_maximum", "(", "x", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "return", "1.0", "-", "np", ".", "argmax", "(", "x", "[", ":", ":", "-", "1", "]", ")", "/", "len", "(", "x", ")", "if", "len", "(", "x", ...
33.916667
0.002392
async def api_request(self, url, params): """Make api fetch request.""" request = None try: with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop): request = await self._api_session.get( url, params=params) if request.status...
[ "async", "def", "api_request", "(", "self", ",", "url", ",", "params", ")", ":", "request", "=", "None", "try", ":", "with", "async_timeout", ".", "timeout", "(", "DEFAULT_TIMEOUT", ",", "loop", "=", "self", ".", "_event_loop", ")", ":", "request", "=", ...
43.5
0.002045
def topics(self): """ Get the set of topics that can be extracted from this report. """ return set(node.tag for node in self.root.iter() if node.attrib)
[ "def", "topics", "(", "self", ")", ":", "return", "set", "(", "node", ".", "tag", "for", "node", "in", "self", ".", "root", ".", "iter", "(", ")", "if", "node", ".", "attrib", ")" ]
36
0.01087
def _recolumn(tmy3_dataframe): """ Rename the columns of the TMY3 DataFrame. Parameters ---------- tmy3_dataframe : DataFrame inplace : bool passed to DataFrame.rename() Returns ------- Recolumned DataFrame. """ # paste in the header as one long line raw_columns...
[ "def", "_recolumn", "(", "tmy3_dataframe", ")", ":", "# paste in the header as one long line", "raw_columns", "=", "'ETR (W/m^2),ETRN (W/m^2),GHI (W/m^2),GHI source,GHI uncert (%),DNI (W/m^2),DNI source,DNI uncert (%),DHI (W/m^2),DHI source,DHI uncert (%),GH illum (lx),GH illum source,Global illum...
67.875
0.000363
def colors(palette): """Example endpoint return a list of colors by palette This is using docstring for specifications --- tags: - colors parameters: - name: palette in: path type: string enum: ['all', 'rgb', 'cmyk'] required: true default: all ...
[ "def", "colors", "(", "palette", ")", ":", "all_colors", "=", "{", "'cmyk'", ":", "[", "'cian'", ",", "'magenta'", ",", "'yellow'", ",", "'black'", "]", ",", "'rgb'", ":", "[", "'red'", ",", "'green'", ",", "'blue'", "]", "}", "if", "palette", "==", ...
24.089286
0.000712
def get_index_in_row(self): """Index of the instruction in the instructions of the row or None. :return: index in the :attr:`row`'s instructions or None, if the instruction is not in the row :rtype: int .. seealso:: :attr:`row_instructions`, :attr:`index_in_row`, :m...
[ "def", "get_index_in_row", "(", "self", ")", ":", "expected_index", "=", "self", ".", "_cached_index_in_row", "instructions", "=", "self", ".", "_row", ".", "instructions", "if", "expected_index", "is", "not", "None", "and", "0", "<=", "expected_index", "<", "...
39.333333
0.002364
def doppler(self, rf='', v0=0.0, off=None): """Defines a doppler measure. It has to specify a reference code, doppler quantity value (see introduction for the action on a scalar quantity with either a vector or scalar value, and when a vector of quantities is given), and optionally it ca...
[ "def", "doppler", "(", "self", ",", "rf", "=", "''", ",", "v0", "=", "0.0", ",", "off", "=", "None", ")", ":", "if", "isinstance", "(", "v0", ",", "float", ")", ":", "v0", "=", "str", "(", "v0", ")", "loc", "=", "{", "'type'", ":", "\"doppler...
41.351351
0.001277
def _use_vxrentry(self, f, VXRoffset, recStart, recEnd, offset): ''' Adds a VVR pointer to a VXR ''' # Select the next unused entry in a VXR for a VVR/CVVR f.seek(VXRoffset+20) # num entries numEntries = int.from_bytes(f.read(4), 'big', signed=True) # used...
[ "def", "_use_vxrentry", "(", "self", ",", "f", ",", "VXRoffset", ",", "recStart", ",", "recEnd", ",", "offset", ")", ":", "# Select the next unused entry in a VXR for a VVR/CVVR", "f", ".", "seek", "(", "VXRoffset", "+", "20", ")", "# num entries", "numEntries", ...
41.590909
0.002137
def chop(seq, size): """Chop a sequence into chunks of the given size.""" chunk = lambda i: seq[i:i+size] return map(chunk,xrange(0,len(seq),size))
[ "def", "chop", "(", "seq", ",", "size", ")", ":", "chunk", "=", "lambda", "i", ":", "seq", "[", "i", ":", "i", "+", "size", "]", "return", "map", "(", "chunk", ",", "xrange", "(", "0", ",", "len", "(", "seq", ")", ",", "size", ")", ")" ]
39
0.031447
def scatter_kwargs(inputs, kwargs, target_gpus, dim=0): """Scatter with support for kwargs dictionary""" inputs = scatter(inputs, target_gpus, dim) if inputs else [] kwargs = scatter(kwargs, target_gpus, dim) if kwargs else [] if len(inputs) < len(kwargs): inputs.extend([() for _ in range(len(kw...
[ "def", "scatter_kwargs", "(", "inputs", ",", "kwargs", ",", "target_gpus", ",", "dim", "=", "0", ")", ":", "inputs", "=", "scatter", "(", "inputs", ",", "target_gpus", ",", "dim", ")", "if", "inputs", "else", "[", "]", "kwargs", "=", "scatter", "(", ...
47.090909
0.001894
def _run(name, **kwargs): ''' .. deprecated:: 2017.7.0 Function name stays the same, behaviour will change. Run a single module function ``name`` The module function to execute ``returner`` Specify the returner to send the return of the module execution to ``kwargs`` ...
[ "def", "_run", "(", "name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "None", "}", "if", "name", "not", "in", "__salt__", ":", ...
30.134228
0.000431
def stop(self): """Stop the DbServer and the zworkers if any""" if ZMQ: logging.warning(self.master.stop()) z.context.term() self.db.close()
[ "def", "stop", "(", "self", ")", ":", "if", "ZMQ", ":", "logging", ".", "warning", "(", "self", ".", "master", ".", "stop", "(", ")", ")", "z", ".", "context", ".", "term", "(", ")", "self", ".", "db", ".", "close", "(", ")" ]
30.5
0.010638
def modify(self, user=None, **params): """ modify user page """ self._check_auth(must_admin=True) is_admin = self._check_admin() if cherrypy.request.method.upper() == 'POST': params = self._parse_params(params) self._modify(params) self._add_notificat...
[ "def", "modify", "(", "self", ",", "user", "=", "None", ",", "*", "*", "params", ")", ":", "self", ".", "_check_auth", "(", "must_admin", "=", "True", ")", "is_admin", "=", "self", ".", "_check_admin", "(", ")", "if", "cherrypy", ".", "request", ".",...
34.873418
0.000706
def img2img_transformer2d_n31(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.num_encoder_layers = 6 hparams.num_decoder_layers = 12 hparams.num_heads = 8 hparams.query_shape = (16, 32) hparams.memory_flange = (16, 32) return hparams
[ "def", "img2img_transformer2d_n31", "(", ")", ":", "hparams", "=", "img2img_transformer2d_base", "(", ")", "hparams", ".", "batch_size", "=", "1", "hparams", ".", "num_encoder_layers", "=", "6", "hparams", ".", "num_decoder_layers", "=", "12", "hparams", ".", "n...
29.7
0.03268
def load_url(url, verbose = False, **kwargs): """ Parse the contents of file at the given URL and return the contents as a LIGO Light Weight document tree. Any source from which Python's urllib2 library can read data is acceptable. stdin is parsed if url is None. Helpful verbosity messages are printed to stder...
[ "def", "load_url", "(", "url", ",", "verbose", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "verbose", ":", "print", ">>", "sys", ".", "stderr", ",", "\"reading %s ...\"", "%", "(", "(", "\"'%s'\"", "%", "url", ")", "if", "url", "is", "no...
40.033333
0.026829
def email(prompt=None, empty=False, mode="simple"): """Prompt an email address. This check is based on a simple regular expression and does not verify whether an email actually exists. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional ...
[ "def", "email", "(", "prompt", "=", "None", ",", "empty", "=", "False", ",", "mode", "=", "\"simple\"", ")", ":", "if", "mode", "==", "\"simple\"", ":", "s", "=", "_prompt_input", "(", "prompt", ")", "if", "empty", "and", "not", "s", ":", "return", ...
27.470588
0.001034
def image_section(image, title): """Create detail section with one image. Args: title (str): Title to be displayed for detail section. image: marv image file. Returns One detail section. """ # pull first image img = yield marv.pull(image) if img is None: ret...
[ "def", "image_section", "(", "image", ",", "title", ")", ":", "# pull first image", "img", "=", "yield", "marv", ".", "pull", "(", "image", ")", "if", "img", "is", "None", ":", "return", "# create image widget and section containing it", "widget", "=", "{", "'...
26.631579
0.001908
def destroy(self): """ Unregister up from untwisted reactor. It is needed to call self.terminate() first to kill the process. """ core.gear.pool.remove(self) self.base.clear()
[ "def", "destroy", "(", "self", ")", ":", "core", ".", "gear", ".", "pool", ".", "remove", "(", "self", ")", "self", ".", "base", ".", "clear", "(", ")" ]
31.571429
0.013216
def init_megno(self, seed=None): """ This function initialises the chaos indicator MEGNO particles and enables their integration. MEGNO is short for Mean Exponential Growth of Nearby orbits. It can be used to test if a system is chaotic or not. In the backend, the integrator is integrat...
[ "def", "init_megno", "(", "self", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "None", ":", "clibrebound", ".", "reb_tools_megno_init", "(", "byref", "(", "self", ")", ")", "else", ":", "clibrebound", ".", "reb_tools_megno_init_seed", "(", "byre...
54.263158
0.011439
def extract_labels(filename): """Extract the labels into a 1D uint8 numpy array [index].""" with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (mag...
[ "def", "extract_labels", "(", "filename", ")", ":", "with", "gzip", ".", "open", "(", "filename", ")", "as", "bytestream", ":", "magic", "=", "_read32", "(", "bytestream", ")", "if", "magic", "!=", "2049", ":", "raise", "ValueError", "(", "'Invalid magic n...
40.333333
0.00202
def reader(fname, header=True, sep="\t", skip_while=None, quotechar='"'): r""" for each row in the file `fname` generate dicts If `header` is True or lists if `header` is False. The dict keys are drawn from the first line. If `header` is a list of names, those will be used as the dict keys. ...
[ "def", "reader", "(", "fname", ",", "header", "=", "True", ",", "sep", "=", "\"\\t\"", ",", "skip_while", "=", "None", ",", "quotechar", "=", "'\"'", ")", ":", "if", "isinstance", "(", "fname", ",", "int_types", ")", ":", "fname", "=", "sys", ".", ...
34.38835
0.002195
def _isCompatible(self, other, reporter): """ This is the environment implementation of :meth:`BaseContour.isCompatible`. Subclasses may override this method. """ contour1 = self contour2 = other # open/closed if contour1.open != contour2.open: ...
[ "def", "_isCompatible", "(", "self", ",", "other", ",", "reporter", ")", ":", "contour1", "=", "self", "contour2", "=", "other", "# open/closed", "if", "contour1", ".", "open", "!=", "contour2", ".", "open", ":", "reporter", ".", "openDifference", "=", "Tr...
38.533333
0.001688
def normalise_filled(self, meta, val): """Only care about valid image names""" available = list(meta.everything["images"].keys()) val = sb.formatted(sb.string_spec(), formatter=MergedOptionStringFormatter).normalise(meta, val) if val not in available: raise BadConfiguration("...
[ "def", "normalise_filled", "(", "self", ",", "meta", ",", "val", ")", ":", "available", "=", "list", "(", "meta", ".", "everything", "[", "\"images\"", "]", ".", "keys", "(", ")", ")", "val", "=", "sb", ".", "formatted", "(", "sb", ".", "string_spec"...
57.142857
0.009852
def count_cores_in_state(self, state, app_id): """Count the number of cores in a given state. .. warning:: In current implementations of SARK, signals (which are used to determine the state of cores) are highly likely to arrive but this is not guaranteed (especially ...
[ "def", "count_cores_in_state", "(", "self", ",", "state", ",", "app_id", ")", ":", "if", "(", "isinstance", "(", "state", ",", "collections", ".", "Iterable", ")", "and", "not", "isinstance", "(", "state", ",", "str", ")", ")", ":", "# If the state is iter...
43.947368
0.000781
def isin(arg, values): """ Check whether the value expression is contained within the indicated list of values. Parameters ---------- values : list, tuple, or array expression The values can be scalar or array-like. Each of them must be comparable with the calling expression, or Non...
[ "def", "isin", "(", "arg", ",", "values", ")", ":", "op", "=", "ops", ".", "Contains", "(", "arg", ",", "values", ")", "return", "op", ".", "to_expr", "(", ")" ]
28.48
0.001359
def move_to_top(self): """Move to root item.""" self.current_item = self.root for f in self._hooks["top"]: f(self) return self
[ "def", "move_to_top", "(", "self", ")", ":", "self", ".", "current_item", "=", "self", ".", "root", "for", "f", "in", "self", ".", "_hooks", "[", "\"top\"", "]", ":", "f", "(", "self", ")", "return", "self" ]
27.5
0.011765
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'custom_pronunciation' ) and self.custom_pronunciation is not None: _dict['custom_pronunciation'] = self.custom_pronunciation if hasattr(self, 'voice_tran...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'custom_pronunciation'", ")", "and", "self", ".", "custom_pronunciation", "is", "not", "None", ":", "_dict", "[", "'custom_pronunciation'", "]", "=", "sel...
47.6
0.008247
def init(track_log_handler): """ (Re)initialize track's file handler for track package logger. Adds a stdout-printing handler automatically. """ logger = logging.getLogger(__package__) # TODO (just document prominently) # assume only one trial can run at once right now # multi-concurr...
[ "def", "init", "(", "track_log_handler", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__package__", ")", "# TODO (just document prominently)", "# assume only one trial can run at once right now", "# multi-concurrent-trial support will require complex filter logic", "...
33.571429
0.001034
def getinputfile(self, outputfile, loadmetadata=True, client=None,requiremetadata=False): """Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles()""" if isinstance(ou...
[ "def", "getinputfile", "(", "self", ",", "outputfile", ",", "loadmetadata", "=", "True", ",", "client", "=", "None", ",", "requiremetadata", "=", "False", ")", ":", "if", "isinstance", "(", "outputfile", ",", "CLAMOutputFile", ")", ":", "outputfilename", "="...
67.583333
0.015815
def get_amplification_factors(self, imt, sctx, rctx, dists, stddev_types): """ Returns the amplification factors for the given rupture and site conditions. :param imt: Intensity measure type as an instance of the :class: `openquake.hazardlib.imt` :param s...
[ "def", "get_amplification_factors", "(", "self", ",", "imt", ",", "sctx", ",", "rctx", ",", "dists", ",", "stddev_types", ")", ":", "dist_level_table", "=", "self", ".", "get_mean_table", "(", "imt", ",", "rctx", ")", "sigma_tables", "=", "self", ".", "get...
44.133333
0.000985
def speziale_pth(v, temp, v0, gamma0, q0, q1, theta0, n, z, t_ref=300., three_r=3. * constants.R): """ calculate thermal pressure for the Speziale equation :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param gamma0:...
[ "def", "speziale_pth", "(", "v", ",", "temp", ",", "v0", ",", "gamma0", ",", "q0", ",", "q1", ",", "theta0", ",", "n", ",", "z", ",", "t_ref", "=", "300.", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ")", ":", "v_mol", "=", "vol_uc2m...
35.818182
0.000824
def get_context_data(self, **kwargs): """ Return a dictionary containing all of the values needed to render the menu instance to a template, including values that might be used by the 'sub_menu' tag to render any additional levels. """ ctx_vals = self._contextual_vals ...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "ctx_vals", "=", "self", ".", "_contextual_vals", "opt_vals", "=", "self", ".", "_option_vals", "data", "=", "self", ".", "create_dict_from_parent_context", "(", ")", "data", ".", "up...
47.214286
0.001483
def _handleResultTyping(self, result): ''' If any of the following calls return a single result, and self._strictResultTyping is true, return the single result, rather than [(SaveResult) {...}]: convertLead() create() delete() emptyRecycleBin() invalidateSessions() merge...
[ "def", "_handleResultTyping", "(", "self", ",", "result", ")", ":", "if", "self", ".", "_strictResultTyping", "==", "False", "and", "len", "(", "result", ")", "==", "1", ":", "return", "result", "[", "0", "]", "else", ":", "return", "result" ]
23.782609
0.008787
def get_time_eta(total_done, total, start_time): """Gets ETA :param total_done: items processed :param total: total # of items to process :param start_time: Time of start processing items :return: Time to go """ time_done = int(time()) - start_time speed = total_done / time_done if...
[ "def", "get_time_eta", "(", "total_done", ",", "total", ",", "start_time", ")", ":", "time_done", "=", "int", "(", "time", "(", ")", ")", "-", "start_time", "speed", "=", "total_done", "/", "time_done", "if", "time_done", ">", "0", "and", "speed", ">", ...
27.193548
0.001145
def kpl_set_on_mask(self, address, group, mask): """Get the status of a KPL button.""" addr = Address(address) device = self.plm.devices[addr.id] device.states[group].set_on_mask(mask)
[ "def", "kpl_set_on_mask", "(", "self", ",", "address", ",", "group", ",", "mask", ")", ":", "addr", "=", "Address", "(", "address", ")", "device", "=", "self", ".", "plm", ".", "devices", "[", "addr", ".", "id", "]", "device", ".", "states", "[", "...
42.4
0.009259
def analyze(self, using=None, **kwargs): """ Perform the analysis process on a text and return the tokens breakdown of the text. Any additional keyword arguments will be passed to ``Elasticsearch.indices.analyze`` unchanged. """ return self._get_connection(using)...
[ "def", "analyze", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "analyze", "(", "index", "=", "self", ".", "_name", ",", "*", "*", "kwarg...
39.555556
0.008242
def get_argument_topology(self): """ Helper function to get topology argument. Raises exception if argument is missing. Returns the topology argument. """ try: topology = self.get_argument(constants.PARAM_TOPOLOGY) return topology except tornado.web.MissingArgumentError as e: ...
[ "def", "get_argument_topology", "(", "self", ")", ":", "try", ":", "topology", "=", "self", ".", "get_argument", "(", "constants", ".", "PARAM_TOPOLOGY", ")", "return", "topology", "except", "tornado", ".", "web", ".", "MissingArgumentError", "as", "e", ":", ...
31.181818
0.011331
def _JRAxiIntegrand(r,E,L,pot): """The J_R integrand""" return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.)
[ "def", "_JRAxiIntegrand", "(", "r", ",", "E", ",", "L", ",", "pot", ")", ":", "return", "nu", ".", "sqrt", "(", "2.", "*", "(", "E", "-", "potentialAxi", "(", "r", ",", "pot", ")", ")", "-", "L", "**", "2.", "/", "r", "**", "2.", ")" ]
38.666667
0.042373
def open_zip(path_or_file, *args, **kwargs): """A with-context for zip files. Passes through *args and **kwargs to zipfile.ZipFile. :API: public :param path_or_file: Full path to zip file. :param args: Any extra args accepted by `zipfile.ZipFile`. :param kwargs: Any extra keyword args accepted by `zipfil...
[ "def", "open_zip", "(", "path_or_file", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "path_or_file", ":", "raise", "InvalidZipPath", "(", "'Invalid zip location: {}'", ".", "format", "(", "path_or_file", ")", ")", "allowZip64", "=", "kwa...
38.576923
0.0107
def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica: """ Create a new replica with the specified parameters. """ return self._replica_class(self._node, instance_id, self._config, is_master, bls_bft, self._metrics)
[ "def", "_new_replica", "(", "self", ",", "instance_id", ":", "int", ",", "is_master", ":", "bool", ",", "bls_bft", ":", "BlsBft", ")", "->", "Replica", ":", "return", "self", ".", "_replica_class", "(", "self", ".", "_node", ",", "instance_id", ",", "sel...
55
0.014337
def from_rest(model, props): """ Map the REST data onto the model Additionally, perform the following tasks: * set all blank strings to None where needed * purge all fields not allowed as incoming data * purge all unknown fields from the incoming data * lowercase certain fields...
[ "def", "from_rest", "(", "model", ",", "props", ")", ":", "req", "=", "goldman", ".", "sess", ".", "req", "_from_rest_blank", "(", "model", ",", "props", ")", "_from_rest_hide", "(", "model", ",", "props", ")", "_from_rest_ignore", "(", "model", ",", "pr...
28.612903
0.001091
def __register_types(self): """Iterates all entry points for resource types and registers a `resource_type_id` to class mapping Returns: `None` """ try: for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.types']['plugins']: cls = entry_poin...
[ "def", "__register_types", "(", "self", ")", ":", "try", ":", "for", "entry_point", "in", "CINQ_PLUGINS", "[", "'cloud_inquisitor.plugins.types'", "]", "[", "'plugins'", "]", ":", "cls", "=", "entry_point", ".", "load", "(", ")", "self", ".", "types", "[", ...
46.076923
0.00982
def fkg_allowing_type_hints( namespace: Optional[str], fn: Callable, to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]: """ Replacement for :func:`dogpile.cache.util.function_key_generator` that handles type-hinted functions like .. code-block:: python def te...
[ "def", "fkg_allowing_type_hints", "(", "namespace", ":", "Optional", "[", "str", "]", ",", "fn", ":", "Callable", ",", "to_str", ":", "Callable", "[", "[", "Any", "]", ",", "str", "]", "=", "repr", ")", "->", "Callable", "[", "[", "Any", "]", ",", ...
37.533333
0.000433
def solidity_resolve_address(hex_code, library_symbol, library_address): """ Change the bytecode to use the given library address. Args: hex_code (bin): The bytecode encoded in hexadecimal. library_name (str): The library that will be resolved. library_address (str): The address of the ...
[ "def", "solidity_resolve_address", "(", "hex_code", ",", "library_symbol", ",", "library_address", ")", ":", "if", "library_address", ".", "startswith", "(", "'0x'", ")", ":", "raise", "ValueError", "(", "'Address should not contain the 0x prefix'", ")", "try", ":", ...
35.76
0.002179
def remove_task_db(self, fid, force=False): '''将任务从数据库中删除''' self.remove_slice_db(fid) sql = 'DELETE FROM upload WHERE fid=?' self.cursor.execute(sql, [fid, ]) self.check_commit(force=force)
[ "def", "remove_task_db", "(", "self", ",", "fid", ",", "force", "=", "False", ")", ":", "self", ".", "remove_slice_db", "(", "fid", ")", "sql", "=", "'DELETE FROM upload WHERE fid=?'", "self", ".", "cursor", ".", "execute", "(", "sql", ",", "[", "fid", "...
37.5
0.008696
def std(self, bessel_correction=True): """Estimates std of underlying data, assuming each datapoint was exactly in the center of its bin.""" if bessel_correction: n = self.n bc = n / (n - 1) else: bc = 1 return np.sqrt(np.average((self.bin_centers - se...
[ "def", "std", "(", "self", ",", "bessel_correction", "=", "True", ")", ":", "if", "bessel_correction", ":", "n", "=", "self", ".", "n", "bc", "=", "n", "/", "(", "n", "-", "1", ")", "else", ":", "bc", "=", "1", "return", "np", ".", "sqrt", "(",...
44.625
0.010989
def parent_org_sdo_ids(self): '''The SDO IDs of the compositions this RTC belongs to.''' return [sdo.get_owner()._narrow(SDOPackage.SDO).get_sdo_id() \ for sdo in self._obj.get_organizations() if sdo]
[ "def", "parent_org_sdo_ids", "(", "self", ")", ":", "return", "[", "sdo", ".", "get_owner", "(", ")", ".", "_narrow", "(", "SDOPackage", ".", "SDO", ")", ".", "get_sdo_id", "(", ")", "for", "sdo", "in", "self", ".", "_obj", ".", "get_organizations", "(...
57.25
0.012931
def compute_checksum(stream, algo, message_digest, chunk_size=None, progress_callback=None): """Get helper method to compute checksum from a stream. :param stream: File-like object. :param algo: Identifier for checksum algorithm. :param messsage_digest: A message digest instance. ...
[ "def", "compute_checksum", "(", "stream", ",", "algo", ",", "message_digest", ",", "chunk_size", "=", "None", ",", "progress_callback", "=", "None", ")", ":", "chunk_size", "=", "chunk_size_or_default", "(", "chunk_size", ")", "bytes_read", "=", "0", "while", ...
37.153846
0.001009
def apply(self, method, *args, **kwargs): """Create a new image by applying a function to this image's data. Parameters ---------- method : :obj:`function` A function to call on the data. This takes in a ndarray as its first argument and optionally takes other ar...
[ "def", "apply", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "method", "(", "self", ".", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "type", "(", "self", ")", "(", "data", ...
34
0.002384