text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def subgraph(self, nodeids): """ Return an Xmrs object with only the specified *nodeids*. Necessary variables and arguments are also included in order to connect any nodes that are connected in the original Xmrs. Args: nodeids: the nodeids of the nodes/EPs to includ...
[ "def", "subgraph", "(", "self", ",", "nodeids", ")", ":", "_eps", ",", "_vars", "=", "self", ".", "_eps", ",", "self", ".", "_vars", "_hcons", ",", "_icons", "=", "self", ".", "_hcons", ",", "self", ".", "_icons", "top", "=", "index", "=", "xarg", ...
36.962963
0.000976
def doArc8(arcs, domains, assignments): """ Perform the ARC-8 arc checking algorithm and prune domains @attention: Currently unused. """ check = dict.fromkeys(domains, True) while check: variable, _ = check.popitem() if variable not in arcs or variable in assignments: ...
[ "def", "doArc8", "(", "arcs", ",", "domains", ",", "assignments", ")", ":", "check", "=", "dict", ".", "fromkeys", "(", "domains", ",", "True", ")", "while", "check", ":", "variable", ",", "_", "=", "check", ".", "popitem", "(", ")", "if", "variable"...
40.355556
0.000538
def fit(self, X, y=None, **kwargs): """ The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not. Parameters ---------- X : ndarray or DataFrame of shape n x m ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "DataVisualizer", ",", "self", ")", ".", "fit", "(", "X", ",", "y", ",", "*", "*", "kwargs", ")", "# Store the classes for the legend if they...
30.558824
0.001866
def _paste(self, sources, destination, copy): """ Copies the files listed in ``sources`` to destination. Source are removed if copy is set to False. """ for src in sources: debug('%s <%s> to <%s>' % ( 'copying' if copy else 'cutting', src, destination)...
[ "def", "_paste", "(", "self", ",", "sources", ",", "destination", ",", "copy", ")", ":", "for", "src", "in", "sources", ":", "debug", "(", "'%s <%s> to <%s>'", "%", "(", "'copying'", "if", "copy", "else", "'cutting'", ",", "src", ",", "destination", ")",...
45.163265
0.001769
def _update_advertised(self, advertised): """Called when advertisement data is received.""" # Advertisement data was received, pull out advertised service UUIDs and # name from advertisement data. if 'kCBAdvDataServiceUUIDs' in advertised: self._advertised = self._advertised ...
[ "def", "_update_advertised", "(", "self", ",", "advertised", ")", ":", "# Advertisement data was received, pull out advertised service UUIDs and", "# name from advertisement data.", "if", "'kCBAdvDataServiceUUIDs'", "in", "advertised", ":", "self", ".", "_advertised", "=", "sel...
62.333333
0.010554
def create(context, name, component_types, active, product_id, data): """create(context, name, component_types, active, product_id, data) Create a topic. >>> dcictl topic-create [OPTIONS] :param string name: Name of the topic [required] :param string component_types: list of component types separ...
[ "def", "create", "(", "context", ",", "name", ",", "component_types", ",", "active", ",", "product_id", ",", "data", ")", ":", "if", "component_types", ":", "component_types", "=", "component_types", ".", "split", "(", "','", ")", "state", "=", "utils", "....
40.8
0.001198
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environment_id') and self.environment_id is not None: _dict['environment_id'] = self.environment_id if hasattr(self, 'session_token') and self.session_token is not None: ...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'environment_id'", ")", "and", "self", ".", "environment_id", "is", "not", "None", ":", "_dict", "[", "'environment_id'", "]", "=", "self", ".", "envi...
54.1
0.001817
def _topological_sort(self): """ Kahn's algorithm for Topological Sorting - Finds cycles in graph - Computes dependency weight """ sorted_graph = [] node_map = self._graph.get_nodes() nodes = [NodeVisitor(node_map[node]) for node in node_map] def...
[ "def", "_topological_sort", "(", "self", ")", ":", "sorted_graph", "=", "[", "]", "node_map", "=", "self", ".", "_graph", ".", "get_nodes", "(", ")", "nodes", "=", "[", "NodeVisitor", "(", "node_map", "[", "node", "]", ")", "for", "node", "in", "node_m...
33
0.001402
def aspectMalefics(self): """ Returns a list with the bad aspects the object makes to the malefics. """ malefics = [const.MARS, const.SATURN] return self.__aspectLists(malefics, aspList=[0, 90, 180])
[ "def", "aspectMalefics", "(", "self", ")", ":", "malefics", "=", "[", "const", ".", "MARS", ",", "const", ".", "SATURN", "]", "return", "self", ".", "__aspectLists", "(", "malefics", ",", "aspList", "=", "[", "0", ",", "90", ",", "180", "]", ")" ]
34.571429
0.012097
def gmst(utc_time): """Greenwich mean sidereal utc_time, in radians. As defined in the AIAA 2006 implementation: http://www.celestrak.com/publications/AIAA/2006-6753/ """ ut1 = jdays2000(utc_time) / 36525.0 theta = 67310.54841 + ut1 * (876600 * 3600 + 8640184.812866 + ut1 * ...
[ "def", "gmst", "(", "utc_time", ")", ":", "ut1", "=", "jdays2000", "(", "utc_time", ")", "/", "36525.0", "theta", "=", "67310.54841", "+", "ut1", "*", "(", "876600", "*", "3600", "+", "8640184.812866", "+", "ut1", "*", "(", "0.093104", "-", "ut1", "*...
40.6
0.00241
def extractBinaries(binaryDataArrayList, arrayLength): """ #TODO: docstring :param binaryDataArrayList: #TODO: docstring :param arrayLength: #TODO: docstring :returns: #TODO: docstring """ extractedArrays = dict() arrayInfo = dict() for binaryData in binaryDataArrayList: if fin...
[ "def", "extractBinaries", "(", "binaryDataArrayList", ",", "arrayLength", ")", ":", "extractedArrays", "=", "dict", "(", ")", "arrayInfo", "=", "dict", "(", ")", "for", "binaryData", "in", "binaryDataArrayList", ":", "if", "findParam", "(", "binaryData", "[", ...
40.657895
0.000632
def list_repo_pkgs(*args, **kwargs): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2014.7.0 All available versions of each package are now returned. This required a slight modification to the structure of the return dict. The return data shown below reflects the updated return d...
[ "def", "list_repo_pkgs", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "byrepo", "=", "kwargs", ".", "pop", "(", "'byrepo'", ",", "False", ")", "cacheonly", "=", "kwargs", ".", "pop", "(", "'cacheonly'", ",", "False", ")", "fromrepo", "=", "kw...
38.704918
0.000516
def add_measurement(measurement): """Add measurement data to the submission buffer for eventual writing to InfluxDB. Example: .. code:: python import sprockets_influxdb as influxdb measurement = influxdb.Measurement('example', 'measurement-name') measurement.set_tag('foo', 'b...
[ "def", "add_measurement", "(", "measurement", ")", ":", "global", "_buffer_size", "if", "not", "_enabled", ":", "LOGGER", ".", "debug", "(", "'Discarding measurement for %s while not enabled'", ",", "measurement", ".", "database", ")", "return", "if", "_stopping", "...
29.740741
0.000603
def couchdb(user, passwd, **kwargs): """ Provides a context manager to create a CouchDB session and provide access to databases, docs etc. :param str user: Username used to connect to CouchDB. :param str passwd: Passcode used to connect to CouchDB. :param str url: URL for CouchDB server. :p...
[ "def", "couchdb", "(", "user", ",", "passwd", ",", "*", "*", "kwargs", ")", ":", "couchdb_session", "=", "CouchDB", "(", "user", ",", "passwd", ",", "*", "*", "kwargs", ")", "couchdb_session", ".", "connect", "(", ")", "yield", "couchdb_session", "couchd...
33.785714
0.001028
def show_results(self, ds_type=DatasetType.Valid, rows:int=5, max_len:int=20): from IPython.display import display, HTML "Show `rows` result of predictions on `ds_type` dataset." ds = self.dl(ds_type).dataset x,y = self.data.one_batch(ds_type, detach=False, denorm=False) preds = ...
[ "def", "show_results", "(", "self", ",", "ds_type", "=", "DatasetType", ".", "Valid", ",", "rows", ":", "int", "=", "5", ",", "max_len", ":", "int", "=", "20", ")", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", "ds", "=", ...
56.952381
0.01727
def fit(self, X, y, recycle=True, **grow_params): """Build a linear mixed forest of trees from the training set (X, y). Parameters ---------- X : array-like of shape = [n_samples, n_features] The training input samples. y : array-like, shape = [n_samples] or [n_sam...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "recycle", "=", "True", ",", "*", "*", "grow_params", ")", ":", "if", "isinstance", "(", "self", ".", "kernel", ",", "str", ")", "and", "self", ".", "kernel", "==", "'data'", ":", "self", ".", ...
39.75
0.000491
def setup_logging(args): """ This sets up the logging. Needs the args to get the log level supplied :param args: The command line arguments """ handler = logging.StreamHandler() handler.setLevel(args.log_level) formatter = logging.Formatter(('%(asctime)s - ' ...
[ "def", "setup_logging", "(", "args", ")", ":", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setLevel", "(", "args", ".", "log_level", ")", "formatter", "=", "logging", ".", "Formatter", "(", "(", "'%(asctime)s - '", "'%(name)s ...
33.2
0.001953
def init( name, cpu, mem, image, hypervisor='kvm', host=None, seed=True, nic='default', install=True, start=True, disk='default', saltenv='base', enable_vnc=False, seed_cmd='seed.apply', enable_qcow=F...
[ "def", "init", "(", "name", ",", "cpu", ",", "mem", ",", "image", ",", "hypervisor", "=", "'kvm'", ",", "host", "=", "None", ",", "seed", "=", "True", ",", "nic", "=", "'default'", ",", "install", "=", "True", ",", "start", "=", "True", ",", "dis...
30.512821
0.001221
def epd_magseries_extparams( times, mags, errs, externalparam_arrs, initial_coeff_guess, magsarefluxes=False, epdsmooth_sigclip=3.0, epdsmooth_windowsize=21, epdsmooth_func=smooth_magseries_savgol, epdsmooth_extraparams=None, object...
[ "def", "epd_magseries_extparams", "(", "times", ",", "mags", ",", "errs", ",", "externalparam_arrs", ",", "initial_coeff_guess", ",", "magsarefluxes", "=", "False", ",", "epdsmooth_sigclip", "=", "3.0", ",", "epdsmooth_windowsize", "=", "21", ",", "epdsmooth_func", ...
38.775
0.00176
def pelt(cost, length, pen=None): """ PELT algorithm to compute changepoints in time series Ported from: https://github.com/STOR-i/Changepoints.jl https://github.com/rkillick/changepoint/ Reference: Killick R, Fearnhead P, Eckley IA (2012) Optimal detection of changepoin...
[ "def", "pelt", "(", "cost", ",", "length", ",", "pen", "=", "None", ")", ":", "if", "pen", "is", "None", ":", "pen", "=", "np", ".", "log", "(", "length", ")", "F", "=", "np", ".", "zeros", "(", "length", "+", "1", ")", "R", "=", "np", ".",...
31.576923
0.000591
def set_dag_run_state_to_running(dag, execution_date, commit=False, session=None): """ Set the dag run for a specific execution date to running. :param dag: the DAG of which to alter state :param execution_date: the execution date from which to start looking :param commit: commit DAG and tasks to be...
[ "def", "set_dag_run_state_to_running", "(", "dag", ",", "execution_date", ",", "commit", "=", "False", ",", "session", "=", "None", ")", ":", "res", "=", "[", "]", "if", "not", "dag", "or", "not", "execution_date", ":", "return", "res", "# Mark the dag run t...
39.45
0.002475
def get_list_of_concatenated_objects(obj, dot_separated_name, lst=None): """ get a list of the objects consisting of - obj - obj+"."+dot_separated_name - (obj+"."+dot_separated_name)+"."+dot_separated_name (called recursively) Note: lists are expanded Ar...
[ "def", "get_list_of_concatenated_objects", "(", "obj", ",", "dot_separated_name", ",", "lst", "=", "None", ")", ":", "from", "textx", ".", "scoping", "import", "Postponed", "if", "lst", "is", "None", ":", "lst", "=", "[", "]", "if", "not", "obj", ":", "r...
30.485714
0.000908
def timespan(t1, dt, keyword = 'days'): """ This function will set the time range for all time series plots. This is a wrapper for the function "xlim" to better handle time axes. Parameters: t1 : flt/str The time to start all time series plots. Can be given in seconds since ...
[ "def", "timespan", "(", "t1", ",", "dt", ",", "keyword", "=", "'days'", ")", ":", "if", "keyword", "is", "'days'", ":", "dt", "*=", "86400", "elif", "keyword", "is", "'hours'", ":", "dt", "*=", "3600", "elif", "keyword", "is", "'minutes'", ":", "dt",...
30.909091
0.012117
def fill_subparser(subparser): """Sets up a subparser to convert YouTube audio files. Adds the compulsory `--youtube-id` flag as well as the optional `sample` and `channels` flags. Parameters ---------- subparser : :class:`argparse.ArgumentParser` Subparser handling the `youtube_audio`...
[ "def", "fill_subparser", "(", "subparser", ")", ":", "subparser", ".", "add_argument", "(", "'--youtube-id'", ",", "type", "=", "str", ",", "required", "=", "True", ",", "help", "=", "(", "\"The YouTube ID of the video from which to extract audio, \"", "\"usually an 1...
35.517241
0.000945
async def postback_analytics(msg: BaseMessage, platform: Platform) -> Response: """ Makes a call to an analytics function. """ try: pb = msg.get_layers()[0] assert isinstance(pb, Postback) user = msg.get_user() user_lang = await user.get_locale() user_id = user....
[ "async", "def", "postback_analytics", "(", "msg", ":", "BaseMessage", ",", "platform", ":", "Platform", ")", "->", "Response", ":", "try", ":", "pb", "=", "msg", ".", "get_layers", "(", ")", "[", "0", "]", "assert", "isinstance", "(", "pb", ",", "Postb...
28.297297
0.000923
def Stat(self, urns): """Returns metadata about all urns. Currently the metadata include type, and last update time. Args: urns: The urns of the objects to open. Yields: A dict of metadata. Raises: ValueError: A string was passed instead of an iterable. """ if isinstanc...
[ "def", "Stat", "(", "self", ",", "urns", ")", ":", "if", "isinstance", "(", "urns", ",", "string_types", ")", ":", "raise", "ValueError", "(", "\"Expected an iterable, not string.\"", ")", "for", "subject", ",", "values", "in", "data_store", ".", "DB", ".", ...
28.76
0.010767
def get_data( dataset, query=None, crs="epsg:4326", bounds=None, sortby=None, pagesize=10000, max_workers=5, ): """Get GeoJSON featurecollection from DataBC WFS """ param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize) with ThreadPoolExecutor(max_worker...
[ "def", "get_data", "(", "dataset", ",", "query", "=", "None", ",", "crs", "=", "\"epsg:4326\"", ",", "bounds", "=", "None", ",", "sortby", "=", "None", ",", "pagesize", "=", "10000", ",", "max_workers", "=", "5", ",", ")", ":", "param_dicts", "=", "d...
26.45
0.001825
def train_model(extractor, data_dir, output_dir=None): """ Train an extractor model, then write train/test block-level classification performance as well as the model itself to disk in ``output_dir``. Args: extractor (:class:`Extractor`): Instance of the ``Extractor`` class to be tr...
[ "def", "train_model", "(", "extractor", ",", "data_dir", ",", "output_dir", "=", "None", ")", ":", "# set up directories and file naming", "output_dir", ",", "fname_prefix", "=", "_set_up_output_dir_and_fname_prefix", "(", "output_dir", ",", "extractor", ")", "# prepare...
43.208333
0.001886
def make_bigint_autoincrement_column(column_name: str, dialect: Dialect) -> Column: """ Returns an instance of :class:`Column` representing a :class:`BigInteger` ``AUTOINCREMENT`` column in the specified :class:`Dialect`. """ # noinspection PyUnresolvedReferences...
[ "def", "make_bigint_autoincrement_column", "(", "column_name", ":", "str", ",", "dialect", ":", "Dialect", ")", "->", "Column", ":", "# noinspection PyUnresolvedReferences", "if", "dialect", ".", "name", "==", "SqlaDialectName", ".", "MSSQL", ":", "return", "Column"...
47
0.001304
def replace_namespaced_replication_controller(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_replication_controller # noqa: E501 replace the specified ReplicationController # noqa: E501 This method makes a synchronous HTTP request by default. To make an as...
[ "def", "replace_namespaced_replication_controller", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asyn...
65.16
0.00121
def ancestor(self, index): """ Return the ``index``-th ancestor. The 0-th ancestor is the node itself, the 1-th ancestor is its parent node, etc. :param int index: the number of levels to go up :rtype: :class:`~aeneas.tree.Tree` :raises: TypeError if ``i...
[ "def", "ancestor", "(", "self", ",", "index", ")", ":", "if", "not", "isinstance", "(", "index", ",", "int", ")", ":", "self", ".", "log_exc", "(", "u\"index is not an integer\"", ",", "None", ",", "True", ",", "TypeError", ")", "if", "index", "<", "0"...
34.173913
0.002475
def get_newsnr(trigs): """ Calculate newsnr ('reweighted SNR') for a trigs object Parameters ---------- trigs: dict of numpy.ndarrays, h5py group (or similar dict-like object) Dictionary-like object holding single detector trigger information. 'chisq_dof', 'snr', and 'chisq' are req...
[ "def", "get_newsnr", "(", "trigs", ")", ":", "dof", "=", "2.", "*", "trigs", "[", "'chisq_dof'", "]", "[", ":", "]", "-", "2.", "nsnr", "=", "newsnr", "(", "trigs", "[", "'snr'", "]", "[", ":", "]", ",", "trigs", "[", "'chisq'", "]", "[", ":", ...
30.888889
0.001745
def estimate_bitstring_probs(results): """ Given an array of single shot results estimate the probability distribution over all bitstrings. :param np.array results: A 2d array where the outer axis iterates over shots and the inner axis over bits. :return: An array with as many axes as there are...
[ "def", "estimate_bitstring_probs", "(", "results", ")", ":", "nshots", ",", "nq", "=", "np", ".", "shape", "(", "results", ")", "outcomes", "=", "np", ".", "array", "(", "[", "int", "(", "\"\"", ".", "join", "(", "map", "(", "str", ",", "r", ")", ...
50.285714
0.008368
def create_all_tables(self): """Create database tables for all known database data-models.""" for klass in self.__get_classes(): if not klass.exists(): klass.create_table(read_capacity_units=1, write_capacity_units=1, wait=True)
[ "def", "create_all_tables", "(", "self", ")", ":", "for", "klass", "in", "self", ".", "__get_classes", "(", ")", ":", "if", "not", "klass", ".", "exists", "(", ")", ":", "klass", ".", "create_table", "(", "read_capacity_units", "=", "1", ",", "write_capa...
53.6
0.011029
def diff(self, obj=None): """Determine if something has changed or not""" if self.no_resource: return NOOP if not self.present: if self.existing: return DEL return NOOP if not obj: obj = self.obj() is_diff = NOOP...
[ "def", "diff", "(", "self", ",", "obj", "=", "None", ")", ":", "if", "self", ".", "no_resource", ":", "return", "NOOP", "if", "not", "self", ".", "present", ":", "if", "self", ".", "existing", ":", "return", "DEL", "return", "NOOP", "if", "not", "o...
26.935484
0.002312
def reward_wall(self): """ Add a wall collision reward """ if not 'wall' in self.mode: return mode = self.mode['wall'] if mode and mode and self.__test_cond(mode): self.logger.debug("Wall {x}/{y}'".format(x=self.bumped_x, y=self.bumped_y)) ...
[ "def", "reward_wall", "(", "self", ")", ":", "if", "not", "'wall'", "in", "self", ".", "mode", ":", "return", "mode", "=", "self", ".", "mode", "[", "'wall'", "]", "if", "mode", "and", "mode", "and", "self", ".", "__test_cond", "(", "mode", ")", ":...
36.416667
0.008929
def get_user_trades(self, limit=0, offset=0, sort='desc'): """Return user's trade history. :param limit: Maximum number of trades to return. If set to 0 or lower, all trades are returned (default: 0). :type limit: int :param offset: Number of trades to skip. :type of...
[ "def", "get_user_trades", "(", "self", ",", "limit", "=", "0", ",", "offset", "=", "0", ",", "sort", "=", "'desc'", ")", ":", "self", ".", "_log", "(", "'get user trades'", ")", "res", "=", "self", ".", "_rest_client", ".", "post", "(", "endpoint", "...
38.074074
0.001898
def operator(self, lhs, min_precedence): """Climb operator precedence as long as there are operators. This function implements a basic precedence climbing parser to deal with binary operators in a sane fashion. The outer loop will keep spinning as long as the next token is an operator w...
[ "def", "operator", "(", "self", ",", "lhs", ",", "min_precedence", ")", ":", "# Spin as long as the next token is an operator of higher", "# precedence. (This may not do anything, which is fine.)", "while", "self", ".", "accept_operator", "(", "precedence", "=", "min_precedence...
45.72549
0.001679
def channels_running(self): """Are any of the channels created and running?""" return (self.shell_channel.is_alive() or self.sub_channel.is_alive() or self.stdin_channel.is_alive() or self.hb_channel.is_alive())
[ "def", "channels_running", "(", "self", ")", ":", "return", "(", "self", ".", "shell_channel", ".", "is_alive", "(", ")", "or", "self", ".", "sub_channel", ".", "is_alive", "(", ")", "or", "self", ".", "stdin_channel", ".", "is_alive", "(", ")", "or", ...
60
0.00823
def sparql(self, stringa): """ wrapper around a sparql query """ qres = self.rdfgraph.query(stringa) return list(qres)
[ "def", "sparql", "(", "self", ",", "stringa", ")", ":", "qres", "=", "self", ".", "rdfgraph", ".", "query", "(", "stringa", ")", "return", "list", "(", "qres", ")" ]
34.75
0.014085
def _read_tRNA_scan(summary_file): """ Parse output from tRNA_Scan """ score = 0 if os.path.getsize(summary_file) == 0: return 0 with open(summary_file) as in_handle: # header = in_handle.next().strip().split() for line in in_handle: if not line.startswith("--...
[ "def", "_read_tRNA_scan", "(", "summary_file", ")", ":", "score", "=", "0", "if", "os", ".", "path", ".", "getsize", "(", "summary_file", ")", "==", "0", ":", "return", "0", "with", "open", "(", "summary_file", ")", "as", "in_handle", ":", "# header = in...
28.714286
0.00241
def rm(filename, serial=None): """ Removes a referenced file on the micro:bit. If no serial object is supplied, microfs will attempt to detect the connection itself. Returns True for success or raises an IOError if there's a problem. """ commands = [ "import os", "os.remove...
[ "def", "rm", "(", "filename", ",", "serial", "=", "None", ")", ":", "commands", "=", "[", "\"import os\"", ",", "\"os.remove('{}')\"", ".", "format", "(", "filename", ")", ",", "]", "out", ",", "err", "=", "execute", "(", "commands", ",", "serial", ")"...
26.117647
0.002174
def cipher(self): """Applies the Caesar shift cipher. Based on the attributes of the object, applies the Caesar shift cipher to the message attribute. Accepts positive and negative integers as offsets. Required attributes: message offset Returns...
[ "def", "cipher", "(", "self", ")", ":", "# If no offset is selected, pick random one with sufficient distance", "# from original.", "if", "self", ".", "offset", "is", "False", ":", "self", ".", "offset", "=", "randrange", "(", "5", ",", "25", ")", "logging", ".", ...
40.022727
0.001109
def conference_play(self, call_params): """REST Conference Play helper """ path = '/' + self.api_version + '/ConferencePlay/' method = 'POST' return self.request(path, method, call_params)
[ "def", "conference_play", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/ConferencePlay/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ...
37.166667
0.008772
def _fit_orbit(orb,vxvv,vxvv_err,pot,radec=False,lb=False, customsky=False,lb_to_customsky=None, pmllpmbb_to_customsky=None, tintJ=100,ntintJ=1000,integrate_method='dopr54_c', ro=None,vo=None,obs=None,disp=False): """Fit an orbit to data in a given potenti...
[ "def", "_fit_orbit", "(", "orb", ",", "vxvv", ",", "vxvv_err", ",", "pot", ",", "radec", "=", "False", ",", "lb", "=", "False", ",", "customsky", "=", "False", ",", "lb_to_customsky", "=", "None", ",", "pmllpmbb_to_customsky", "=", "None", ",", "tintJ", ...
52.189189
0.026945
def get_stock_data(self, stock_list, **kwargs): """获取并格式化股票信息""" res = self._fetch_stock_data(stock_list) return self.format_response_data(res, **kwargs)
[ "def", "get_stock_data", "(", "self", ",", "stock_list", ",", "*", "*", "kwargs", ")", ":", "res", "=", "self", ".", "_fetch_stock_data", "(", "stock_list", ")", "return", "self", ".", "format_response_data", "(", "res", ",", "*", "*", "kwargs", ")" ]
43.5
0.011299
def absent(name, region=None, key=None, keyid=None, profile=None): ''' Ensure cloud formation stack is absent. name (string) – The name of the stack to delete. region (string) - Region to connect to. key (string) - Secret key to be used. keyid (string) - Access key to be used. profile (...
[ "def", "absent", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''"...
37.085714
0.002252
def extract_relevant_tb(tb, exctype, is_test_failure): """Return extracted traceback frame 4-tuples that aren't unittest ones. This used to be _exc_info_to_string(). """ # Skip test runner traceback levels: while tb and _is_unittest_frame(tb): tb = tb.tb_next if is_test_failure: ...
[ "def", "extract_relevant_tb", "(", "tb", ",", "exctype", ",", "is_test_failure", ")", ":", "# Skip test runner traceback levels:", "while", "tb", "and", "_is_unittest_frame", "(", "tb", ")", ":", "tb", "=", "tb", ".", "tb_next", "if", "is_test_failure", ":", "# ...
32.428571
0.002141
def dump(node, annotate_fields=True, include_attributes=False, indent=" "): """ Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation...
[ "def", "dump", "(", "node", ",", "annotate_fields", "=", "True", ",", "include_attributes", "=", "False", ",", "indent", "=", "\" \"", ")", ":", "def", "_format", "(", "node", ",", "level", "=", "0", ")", ":", "if", "isinstance", "(", "node", ",", "...
37.18
0.000524
def geometric_series(q, n): """ Compute finite geometric series. \frac{1-q^{n+1}}{1-q} q \neq 1 \sum_{k=0}^{n} q^{k}= n+1 q = 1 Parameters ---------- q : array-like The common ratio of the geome...
[ "def", "geometric_series", "(", "q", ",", "n", ")", ":", "q", "=", "np", ".", "asarray", "(", "q", ")", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "'Finite geometric series is only defined for n>=0.'", ")", "else", ":", "\"\"\"q is scalar\"\"\"", ...
27.906977
0.00161
def setVisible(self, state): """ Sets the visible state for this line edit. :param state | <bool> """ super(XLineEdit, self).setVisible(state) self.adjustStyleSheet() self.adjustTextMargins()
[ "def", "setVisible", "(", "self", ",", "state", ")", ":", "super", "(", "XLineEdit", ",", "self", ")", ".", "setVisible", "(", "state", ")", "self", ".", "adjustStyleSheet", "(", ")", "self", ".", "adjustTextMargins", "(", ")" ]
27
0.014337
def moveto(self, new_abspath=None, new_dirpath=None, new_dirname=None, new_basename=None, new_fname=None, new_ext=None, overwrite=False, makedirs=False): """ An advanced :meth:`pathlib...
[ "def", "moveto", "(", "self", ",", "new_abspath", "=", "None", ",", "new_dirpath", "=", "None", ",", "new_dirname", "=", "None", ",", "new_basename", "=", "None", ",", "new_fname", "=", "None", ",", "new_ext", "=", "None", ",", "overwrite", "=", "False",...
30.421053
0.00922
def _is_port_name(name): ''' Check that name is IANA service: An alphanumeric (a-z, and 0-9) string, with a maximum length of 15 characters, with the '-' character allowed anywhere except the first or the last character or adjacent to another '-' character, it must contain at least a (a-z) character '''...
[ "def", "_is_port_name", "(", "name", ")", ":", "port_name", "=", "re", ".", "compile", "(", "\"\"\"^[a-z0-9]{1,15}$\"\"\"", ")", "if", "port_name", ".", "match", "(", "name", ")", ":", "return", "True", "else", ":", "return", "False" ]
40.272727
0.002208
def width(self): """Return number of qubits plus clbits in circuit. Returns: int: Width of circuit. """ return sum(reg.size for reg in self.qregs+self.cregs)
[ "def", "width", "(", "self", ")", ":", "return", "sum", "(", "reg", ".", "size", "for", "reg", "in", "self", ".", "qregs", "+", "self", ".", "cregs", ")" ]
24.5
0.009852
def create_box(width=1, height=1, depth=1, width_segments=1, height_segments=1, depth_segments=1, planes=None): """ Generate vertices & indices for a filled and outlined box. Parameters ---------- width : float Box width. height : float Box height. depth : float ...
[ "def", "create_box", "(", "width", "=", "1", ",", "height", "=", "1", ",", "depth", "=", "1", ",", "width_segments", "=", "1", ",", "height_segments", "=", "1", ",", "depth_segments", "=", "1", ",", "planes", "=", "None", ")", ":", "planes", "=", "...
35.597938
0.000282
def create_edisp(event_class, event_type, erec, egy, cth): """Create an array of energy response values versus energy and inclination angle. Parameters ---------- egy : `~numpy.ndarray` Energy in MeV. cth : `~numpy.ndarray` Cosine of the incidence angle. """ irf = crea...
[ "def", "create_edisp", "(", "event_class", ",", "event_type", ",", "erec", ",", "egy", ",", "cth", ")", ":", "irf", "=", "create_irf", "(", "event_class", ",", "event_type", ")", "theta", "=", "np", ".", "degrees", "(", "np", ".", "arccos", "(", "cth",...
34.818182
0.016088
def build_backend(tasks, default_host=('127.0.0.1', DEFAULT_PORT), *args, **kw): """ Most of these args are passed directly to BackEnd(). However, default_host is used a bit differently. It should be a (host, port) pair, and may be overridden with cmdline args: file.py localho...
[ "def", "build_backend", "(", "tasks", ",", "default_host", "=", "(", "'127.0.0.1'", ",", "DEFAULT_PORT", ")", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "host", ",", "port", "=", "default_host", "if", "len", "(", "sys", ".", "argv", ")", ">", ...
33.5625
0.009058
def appendImport(self, statement): '''append additional import statement(s). import_stament -- tuple or list or str ''' if type(statement) in (list,tuple): self.extras += statement else: self.extras.append(statement)
[ "def", "appendImport", "(", "self", ",", "statement", ")", ":", "if", "type", "(", "statement", ")", "in", "(", "list", ",", "tuple", ")", ":", "self", ".", "extras", "+=", "statement", "else", ":", "self", ".", "extras", ".", "append", "(", "stateme...
34.25
0.014235
def _operators_replace(self, string: str) -> str: """ Searches for first unary or binary operator (via self.op_regex that has only one group that contain operator) then replaces it (or escapes it if brackets do not match). Everything until: * space ' ' * begin...
[ "def", "_operators_replace", "(", "self", ",", "string", ":", "str", ")", "->", "str", ":", "# noinspection PyShadowingNames", "def", "replace", "(", "string", ":", "str", ",", "start", ":", "int", ",", "end", ":", "int", ",", "substring", ":", "str", ")...
43.2
0.001906
def read_json(self, xblock): """ Retrieve the serialized value for this field from the specified xblock """ self._warn_deprecated_outside_JSONField() return self.to_json(self.read_from(xblock))
[ "def", "read_json", "(", "self", ",", "xblock", ")", ":", "self", ".", "_warn_deprecated_outside_JSONField", "(", ")", "return", "self", ".", "to_json", "(", "self", ".", "read_from", "(", "xblock", ")", ")" ]
38
0.008584
def _register_update(self, replot=False, fmt={}, force=False, todefault=False): """ Register new formatoptions for updating Parameters ---------- replot: bool Boolean that determines whether the data specific formatoptions shall b...
[ "def", "_register_update", "(", "self", ",", "replot", "=", "False", ",", "fmt", "=", "{", "}", ",", "force", "=", "False", ",", "todefault", "=", "False", ")", ":", "self", ".", "replot", "=", "self", ".", "replot", "or", "replot", "if", "self", "...
43.46875
0.00211
def delete(repo, args=[]): """ Delete files Parameters ---------- repo: Repository object args: Arguments to git command """ # Remove the files result = generic_repo_cmd(repo, 'delete', args) if result['status'] != 'success': return status with cd(repo.rootdir)...
[ "def", "delete", "(", "repo", ",", "args", "=", "[", "]", ")", ":", "# Remove the files ", "result", "=", "generic_repo_cmd", "(", "repo", ",", "'delete'", ",", "args", ")", "if", "result", "[", "'status'", "]", "!=", "'success'", ":", "return", "status"...
25.880952
0.019504
def tableexists(tablename): """Test if a table exists.""" result = True try: t = table(tablename, ack=False) except: result = False return result
[ "def", "tableexists", "(", "tablename", ")", ":", "result", "=", "True", "try", ":", "t", "=", "table", "(", "tablename", ",", "ack", "=", "False", ")", "except", ":", "result", "=", "False", "return", "result" ]
21.75
0.01105
def begin_call(self, method, *args): """Perform an asynchronous remote call where the return value is not known yet. This returns immediately with a Deferred object. The Deferred object may then be used to attach a callback, force waiting for the call, or check for exceptions. """ ...
[ "def", "begin_call", "(", "self", ",", "method", ",", "*", "args", ")", ":", "d", "=", "Deferred", "(", "self", ".", "loop", ")", "d", ".", "request", "=", "self", ".", "request_num", "self", ".", "requests", "[", "self", ".", "request_num", "]", "...
40.230769
0.009346
def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|arg...
[ "def", "AddArguments", "(", "cls", ",", "argument_group", ")", ":", "argument_group", ".", "add_argument", "(", "'--virustotal-api-key'", ",", "'--virustotal_api_key'", ",", "dest", "=", "'virustotal_api_key'", ",", "type", "=", "str", ",", "action", "=", "'store'...
45.466667
0.000718
def peer_store_and_set(relation_id=None, peer_relation_name='cluster', peer_store_fatal=False, relation_settings=None, delimiter='_', **kwargs): """Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and p...
[ "def", "peer_store_and_set", "(", "relation_id", "=", "None", ",", "peer_relation_name", "=", "'cluster'", ",", "peer_store_fatal", "=", "False", ",", "relation_settings", "=", "None", ",", "delimiter", "=", "'_'", ",", "*", "*", "kwargs", ")", ":", "relation_...
49.321429
0.00071
def write(self, s, flush=True): """Write bytes to the pseudoterminal. Returns the number of bytes written. """ return self._writeb(s, flush=flush)
[ "def", "write", "(", "self", ",", "s", ",", "flush", "=", "True", ")", ":", "return", "self", ".", "_writeb", "(", "s", ",", "flush", "=", "flush", ")" ]
30.333333
0.016043
def define_symbol(name, open_brace, comma, i, j, close_brace, variables, **kwds): r"""Define a nice symbol with matrix indices. >>> name = "rho" >>> from sympy import symbols >>> t, x, y, z = symbols("t, x, y, z", positive=True) >>> variables = [t, x, y, z] >>> open_brace = ""...
[ "def", "define_symbol", "(", "name", ",", "open_brace", ",", "comma", ",", "i", ",", "j", ",", "close_brace", ",", "variables", ",", "*", "*", "kwds", ")", ":", "if", "variables", "is", "None", ":", "return", "Symbol", "(", "name", "+", "open_brace", ...
32.12
0.001209
def start_span(self, name='span'): """Start a span. :type name: str :param name: The name of the span. :rtype: :class:`~opencensus.trace.span.Span` :returns: The Span object. """ parent_span = self.current_span() # If a span has remote parent span, then...
[ "def", "start_span", "(", "self", ",", "name", "=", "'span'", ")", ":", "parent_span", "=", "self", ".", "current_span", "(", ")", "# If a span has remote parent span, then the parent_span.span_id", "# should be the span_id from the request header.", "if", "parent_span", "i...
31.555556
0.002278
def open(self, url, mode='rb', reload=False, filename=None): """Open a file, downloading it first if it does not yet exist. Unlike when you call a loader directly like ``my_loader()``, this ``my_loader.open()`` method does not attempt to parse or interpret the file; it simply returns an...
[ "def", "open", "(", "self", ",", "url", ",", "mode", "=", "'rb'", ",", "reload", "=", "False", ",", "filename", "=", "None", ")", ":", "if", "'://'", "not", "in", "url", ":", "path_that_might_be_relative", "=", "url", "path", "=", "os", ".", "path", ...
43.741935
0.001443
def supported_tasks(self, lang=None): """Languages that are covered by a specific task. Args: lang (string): Language code name. """ if lang: collection = self.get_collection(lang=lang) return [x.id.split('.')[0] for x in collection.packages] else: return [x.name.split()[0] ...
[ "def", "supported_tasks", "(", "self", ",", "lang", "=", "None", ")", ":", "if", "lang", ":", "collection", "=", "self", ".", "get_collection", "(", "lang", "=", "lang", ")", "return", "[", "x", ".", "id", ".", "split", "(", "'.'", ")", "[", "0", ...
33.818182
0.013089
def pull_isotime(voevent, index=0): """ Deprecated alias of :func:`.get_event_time_as_utc` """ import warnings warnings.warn( """ The function `pull_isotime` has been renamed to `get_event_time_as_utc`. This alias is preserved for backwards compatibility, and may be r...
[ "def", "pull_isotime", "(", "voevent", ",", "index", "=", "0", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"\"\"\n The function `pull_isotime` has been renamed to\n `get_event_time_as_utc`. This alias is preserved for backwards\n compatibility...
32.307692
0.002315
def _checkretry(self, mydelay, condition, tries_remaining, data): """Check if input parameters allow to retries function execution. :param float mydelay: waiting delay between two execution. :param int condition: condition to check with this condition. :param int tries_remaining: tries ...
[ "def", "_checkretry", "(", "self", ",", "mydelay", ",", "condition", ",", "tries_remaining", ",", "data", ")", ":", "result", "=", "mydelay", "if", "self", ".", "condition", "&", "condition", "and", "tries_remaining", ">", "0", ":", "# hook data with tries_rem...
36.037037
0.002002
def cli(): """ Command line interface """ ch = logging.StreamHandler() ch.setFormatter(logging.Formatter( '%(asctime)s.%(msecs)03d %(levelname)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S" )) logger.addHandler(ch) import argparse parser = argparse.ArgumentParser(description="...
[ "def", "cli", "(", ")", ":", "ch", "=", "logging", ".", "StreamHandler", "(", ")", "ch", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "'%(asctime)s.%(msecs)03d %(levelname)s: %(message)s'", ",", "datefmt", "=", "\"%Y-%m-%d %H:%M:%S\"", ")", ")", "...
43.72
0.009848
def _has_converged(centroids, old_centroids): """ Stop if centroids stop to update Parameters ----------- centroids: array-like, shape=(K, n_samples) old_centroids: array-like, shape=(K, n_samples) ------------ returns True: bool """ return (set([tuple(a) for a ...
[ "def", "_has_converged", "(", "centroids", ",", "old_centroids", ")", ":", "return", "(", "set", "(", "[", "tuple", "(", "a", ")", "for", "a", "in", "centroids", "]", ")", "==", "set", "(", "[", "tuple", "(", "a", ")", "for", "a", "in", "old_centro...
28.076923
0.013263
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. ''' if text is None: return None m = self.lex_pattern.match(text) if not m: raise EvaluateException('Bad Gregorian: %s' %text, ps.Backtrace(elt)) try: ...
[ "def", "text_to_data", "(", "self", ",", "text", ",", "elt", ",", "ps", ")", ":", "if", "text", "is", "None", ":", "return", "None", "m", "=", "self", ".", "lex_pattern", ".", "match", "(", "text", ")", "if", "not", "m", ":", "raise", "EvaluateExce...
30.555556
0.012346
def convert_to_11(self): """ converts the iocs in self.iocs from openioc 1.0 to openioc 1.1 format. the converted iocs are stored in the dictionary self.iocs_11 """ if len(self) < 1: log.error('No iocs available to modify.') return False log.info('...
[ "def", "convert_to_11", "(", "self", ")", ":", "if", "len", "(", "self", ")", "<", "1", ":", "log", ".", "error", "(", "'No iocs available to modify.'", ")", "return", "False", "log", ".", "info", "(", "'Converting IOCs from 1.0 to 1.1'", ")", "errors", "=",...
44.551724
0.001893
def is_empty(self): """Returns True if the root node contains no child elements, no text, and no attributes other than **type**. Returns False if any are present.""" non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type'] return len(self.node) == 0 and len(non_...
[ "def", "is_empty", "(", "self", ")", ":", "non_type_attributes", "=", "[", "attr", "for", "attr", "in", "self", ".", "node", ".", "attrib", ".", "keys", "(", ")", "if", "attr", "!=", "'type'", "]", "return", "len", "(", "self", ".", "node", ")", "=...
66
0.009975
def build_reduce(function: Callable[[Any, Any], Any] = None, *, init: Any = NONE): """ Decorator to wrap a function to return a Reduce operator. :param function: function to be wrapped :param init: optional initialization for state """ _init = init def _build_reduce(function: ...
[ "def", "build_reduce", "(", "function", ":", "Callable", "[", "[", "Any", ",", "Any", "]", ",", "Any", "]", "=", "None", ",", "*", ",", "init", ":", "Any", "=", "NONE", ")", ":", "_init", "=", "init", "def", "_build_reduce", "(", "function", ":", ...
31.590909
0.001397
def connect(self): """ Connects and logins to the server. """ self._ftp.connect() self._ftp.login(user=self._username, passwd=self._passwd)
[ "def", "connect", "(", "self", ")", ":", "self", ".", "_ftp", ".", "connect", "(", ")", "self", ".", "_ftp", ".", "login", "(", "user", "=", "self", ".", "_username", ",", "passwd", "=", "self", ".", "_passwd", ")" ]
40
0.01227
def case_stmt_handle(self, loc, tokens): """Process case blocks.""" if len(tokens) == 2: item, cases = tokens default = None elif len(tokens) == 3: item, cases, default = tokens else: raise CoconutInternalException("invalid case tokens", to...
[ "def", "case_stmt_handle", "(", "self", ",", "loc", ",", "tokens", ")", ":", "if", "len", "(", "tokens", ")", "==", "2", ":", "item", ",", "cases", "=", "tokens", "default", "=", "None", "elif", "len", "(", "tokens", ")", "==", "3", ":", "item", ...
37
0.002291
def delete_role_policy(role_name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete a role policy. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role_policy myirole mypolicy ''' conn = _get_conn(region=region, key=key, k...
[ "def", "delete_role_policy", "(", "role_name", ",", "policy_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key"...
32.230769
0.002317
def GetUcsMethodMeta(classId, key): """ Methods returns the method meta of the ExternalMethod. """ if classId in _MethodFactoryMeta: if key in _MethodFactoryMeta[classId]: return _MethodFactoryMeta[classId][key] return None
[ "def", "GetUcsMethodMeta", "(", "classId", ",", "key", ")", ":", "if", "classId", "in", "_MethodFactoryMeta", ":", "if", "key", "in", "_MethodFactoryMeta", "[", "classId", "]", ":", "return", "_MethodFactoryMeta", "[", "classId", "]", "[", "key", "]", "retur...
38.5
0.029661
def functions_factory(cls, coef, degree, knots, ext, **kwargs): """ Given some coefficients, return a B-spline. """ return cls._basis_spline_factory(coef, degree, knots, 0, ext)
[ "def", "functions_factory", "(", "cls", ",", "coef", ",", "degree", ",", "knots", ",", "ext", ",", "*", "*", "kwargs", ")", ":", "return", "cls", ".", "_basis_spline_factory", "(", "coef", ",", "degree", ",", "knots", ",", "0", ",", "ext", ")" ]
34.166667
0.009524
def print_network(self): # pragma: no cover """ Generate a graphviz compatible graph. """ edges = set() def gen_edges(node): nonlocal edges name = str(id(node)) yield '{name} [label="{cls_name}"];'.format( name=name, ...
[ "def", "print_network", "(", "self", ")", ":", "# pragma: no cover", "edges", "=", "set", "(", ")", "def", "gen_edges", "(", "node", ")", ":", "nonlocal", "edges", "name", "=", "str", "(", "id", "(", "node", ")", ")", "yield", "'{name} [label=\"{cls_name}\...
32.407407
0.00222
def is_number(obj): """Check if obj is number.""" return isinstance(obj, (int, float, np.int_, np.float_))
[ "def", "is_number", "(", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "(", "int", ",", "float", ",", "np", ".", "int_", ",", "np", ".", "float_", ")", ")" ]
37.333333
0.008772
def user_absent(name, channel=14, **kwargs): ''' Remove user Delete all user (uid) records having the matching name. name string name of user to delete channel channel to remove user access from defaults to 14 for auto. kwargs - api_host=localhost - api_user=ad...
[ "def", "user_absent", "(", "name", ",", "channel", "=", "14", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "user_id_list...
26.394737
0.000962
def send_data(self, stream_id, data, *, end_stream=False): """ Send request or response body on the given stream. This will block until either whole data is sent, or the stream gets closed. Meanwhile, a paused underlying transport or a closed flow control window will also help w...
[ "def", "send_data", "(", "self", ",", "stream_id", ",", "data", ",", "*", ",", "end_stream", "=", "False", ")", ":", "try", ":", "with", "(", "yield", "from", "self", ".", "_get_stream", "(", "stream_id", ")", ".", "wlock", ")", ":", "while", "True",...
49.8125
0.000615
def is_response(cls, response): '''Return whether the document is likely to be a Sitemap.''' if response.body: if cls.is_file(response.body): return True
[ "def", "is_response", "(", "cls", ",", "response", ")", ":", "if", "response", ".", "body", ":", "if", "cls", ".", "is_file", "(", "response", ".", "body", ")", ":", "return", "True" ]
38.6
0.010152
def configure_nodes(self): """Ensure that the LB's nodes matches the stack""" # Since load balancing runs after server provisioning, # the servers should already be created regardless of # whether this was a preexisting load balancer or not. # We also have the existing nodes, bec...
[ "def", "configure_nodes", "(", "self", ")", ":", "# Since load balancing runs after server provisioning,", "# the servers should already be created regardless of", "# whether this was a preexisting load balancer or not.", "# We also have the existing nodes, because add_to_inventory", "# has been...
38.652174
0.002195
def shutdown(name): ''' Shut down Traffic Server on the local node. .. code-block:: yaml shutdown_ats: trafficserver.shutdown ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __opts__['test']: ret['comment'] =...
[ "def", "shutdown", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "__opts__", "[", "'test'", "]", ":", "ret", "[", "'comment'", ...
20.434783
0.002033
def azimintpix(data, dataerr, bcx, bcy, mask=None, Ntheta=100, pixmin=0, pixmax=np.inf, returnmask=False, errorpropagation=2): """Azimuthal integration (averaging) on the detector plane Inputs: data: scattering pattern matrix (np.ndarray, dtype: np.double) dataerr: error matrix (...
[ "def", "azimintpix", "(", "data", ",", "dataerr", ",", "bcx", ",", "bcy", ",", "mask", "=", "None", ",", "Ntheta", "=", "100", ",", "pixmin", "=", "0", ",", "pixmax", "=", "np", ".", "inf", ",", "returnmask", "=", "False", ",", "errorpropagation", ...
44.448276
0.000759
def check(predicate): r"""A decorator that adds a check to the :class:`.Command` or its subclasses. These checks could be accessed via :attr:`.Command.checks`. These checks should be predicates that take in a single parameter taking a :class:`.Context`. If the check returns a ``False``\-like value then...
[ "def", "check", "(", "predicate", ")", ":", "def", "decorator", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "Command", ")", ":", "func", ".", "checks", ".", "append", "(", "predicate", ")", "else", ":", "if", "not", "hasattr", "(", ...
29.96875
0.000505
def create(dataset, num_topics=10, initial_topics=None, alpha=None, beta=.1, num_iterations=10, num_burnin=5, associations=None, verbose=False, print_interval=10, validation_set=None, method='auto'):...
[ "def", "create", "(", "dataset", ",", "num_topics", "=", "10", ",", "initial_topics", "=", "None", ",", "alpha", "=", "None", ",", "beta", "=", ".1", ",", "num_iterations", "=", "10", ",", "num_burnin", "=", "5", ",", "associations", "=", "None", ",", ...
40.957806
0.001106
def load_json(task: Task, file: str) -> Result: """ Loads a json file. Arguments: file: path to the file containing the json file to load Examples: Simple example with ``ordered_dict``:: > nr.run(task=load_json, file="mydata.json") file: path...
[ "def", "load_json", "(", "task", ":", "Task", ",", "file", ":", "str", ")", "->", "Result", ":", "kwargs", ":", "Dict", "[", "str", ",", "Type", "[", "MutableMapping", "[", "str", ",", "Any", "]", "]", "]", "=", "{", "}", "with", "open", "(", "...
27.04
0.001429
def printMe(self, selfTag, selfValue): '''Parse the single and its value and return the parsed str. Args: selfTag (str): The tag. Normally just ``self.tag`` selfValue (list): a list of value elements(single, subclasses, str, int). Normally just ``self.value`` Returns: ...
[ "def", "printMe", "(", "self", ",", "selfTag", ",", "selfValue", ")", ":", "if", "len", "(", "selfValue", ")", "==", "0", ":", "return", "''", "# if value have only one element and it is not another single", "# print differently", "elif", "len", "(", "selfValue", ...
43.162162
0.001837
def grant_bonus(self, assignment_id, amount, reason): """Grant a bonus to the MTurk Worker. Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or re...
[ "def", "grant_bonus", "(", "self", ",", "assignment_id", ",", "amount", ",", "reason", ")", ":", "assignment", "=", "self", ".", "get_assignment", "(", "assignment_id", ")", "worker_id", "=", "assignment", "[", "\"worker_id\"", "]", "amount_str", "=", "\"{:.2f...
42.62963
0.001699
def get_relation_count_query(self, query, parent): """ Add the constraints for a relationship count query. :type query: eloquent.orm.Builder :type parent: eloquent.orm.Builder :rtype: Builder """ query.select(QueryExpression('COUNT(*)')) other_key = sel...
[ "def", "get_relation_count_query", "(", "self", ",", "query", ",", "parent", ")", ":", "query", ".", "select", "(", "QueryExpression", "(", "'COUNT(*)'", ")", ")", "other_key", "=", "self", ".", "wrap", "(", "'%s.%s'", "%", "(", "query", ".", "get_model", ...
33.428571
0.008316
def get(self, pk): ''' Fetches an entity from the session based on primary key. ''' self._init() return self.known.get(pk) or self.wknown.get(pk)
[ "def", "get", "(", "self", ",", "pk", ")", ":", "self", ".", "_init", "(", ")", "return", "self", ".", "known", ".", "get", "(", "pk", ")", "or", "self", ".", "wknown", ".", "get", "(", "pk", ")" ]
30
0.010811
def run(self): """ run the plugin """ self.log.info("Resolving module compose") compose_info = self._resolve_compose() set_compose_info(self.workflow, compose_info) override_build_kwarg(self.workflow, 'compose_ids', [compose_info.compose_id])
[ "def", "run", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Resolving module compose\"", ")", "compose_info", "=", "self", ".", "_resolve_compose", "(", ")", "set_compose_info", "(", "self", ".", "workflow", ",", "compose_info", ")", "overr...
29.1
0.01