text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def initialize(self, author=""): ''' Initialize the database. This is dangerous since it removes any existing content.''' self.cur.execute("CREATE TABLE version(major, minor);") self.cur.execute("INSERT INTO version(major, minor) VALUES (?,?);", (self.appversion[0], self...
[ "def", "initialize", "(", "self", ",", "author", "=", "\"\"", ")", ":", "self", ".", "cur", ".", "execute", "(", "\"CREATE TABLE version(major, minor);\"", ")", "self", ".", "cur", ".", "execute", "(", "\"INSERT INTO version(major, minor) VALUES (?,?);\"", ",", "(...
89.375
0.008304
def display(self): """Display the recordings.""" if self.data is None: return if self.scene is not None: self.y_scrollbar_value = self.verticalScrollBar().value() self.scene.clear() self.create_chan_labels() self.create_time_labels() ...
[ "def", "display", "(", "self", ")", ":", "if", "self", ".", "data", "is", "None", ":", "return", "if", "self", ".", "scene", "is", "not", "None", ":", "self", ".", "y_scrollbar_value", "=", "self", ".", "verticalScrollBar", "(", ")", ".", "value", "(...
33.414634
0.001418
def compute_regressor(exp_condition, hrf_model, frame_times, con_id='cond', oversampling=50, fir_delays=None, min_onset=-24): """ This is the main function to convolve regressors with hrf model Parameters ---------- exp_condition : array-like of shape (3, n_events) yields ...
[ "def", "compute_regressor", "(", "exp_condition", ",", "hrf_model", ",", "frame_times", ",", "con_id", "=", "'cond'", ",", "oversampling", "=", "50", ",", "fir_delays", "=", "None", ",", "min_onset", "=", "-", "24", ")", ":", "# this is the average tr in this se...
39.195122
0.000303
def mode(data): """Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: If there is not exactly one most common value, ``mode`` will raise StatisticsErr...
[ "def", "mode", "(", "data", ")", ":", "# Generate a table of sorted (value, frequency) pairs.", "table", "=", "counts", "(", "data", ")", "if", "len", "(", "table", ")", "==", "1", ":", "return", "table", "[", "0", "]", "[", "0", "]", "elif", "table", ":...
33.947368
0.001508
def cli(env, sortby, datacenter): """List number of block storage volumes per datacenter.""" block_manager = SoftLayer.BlockStorageManager(env.client) mask = "mask[serviceResource[datacenter[name]],"\ "replicationPartners[serviceResource[datacenter[name]]]]" block_volumes = block_manager.list...
[ "def", "cli", "(", "env", ",", "sortby", ",", "datacenter", ")", ":", "block_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "mask", "=", "\"mask[serviceResource[datacenter[name]],\"", "\"replicationPartners[serviceResource[datace...
45.083333
0.000905
def debug(victim=None, ignore_exceptions=(), catch_exception=None, depth=0): """A decorator function to catch exceptions and enter debug mode. Args: victim (typing.Union(type, function)): either a class or function to wrap and debug. ignore_exceptions (list): list of classes of exce...
[ "def", "debug", "(", "victim", "=", "None", ",", "ignore_exceptions", "=", "(", ")", ",", "catch_exception", "=", "None", ",", "depth", "=", "0", ")", ":", "if", "victim", "is", "None", ":", "# Debug is used as a decorator so we need to return wrap function to", ...
38.884892
0.000361
def get_users(session, query): """ Get one or more users """ # GET /api/users/0.1/users response = make_get_request(session, 'users', params_data=query) json_data = response.json() if response.status_code == 200: return json_data['result'] else: raise UsersNotFoundExcepti...
[ "def", "get_users", "(", "session", ",", "query", ")", ":", "# GET /api/users/0.1/users", "response", "=", "make_get_request", "(", "session", ",", "'users'", ",", "params_data", "=", "query", ")", "json_data", "=", "response", ".", "json", "(", ")", "if", "...
32
0.002169
def set_meta(self, meta, name=None, index=None): """Add metadata columns as pd.Series, list or value (int/float/str) Parameters ---------- meta: pd.Series, list, int, float or str column to be added to metadata (by `['model', 'scenario']` index if possible) ...
[ "def", "set_meta", "(", "self", ",", "meta", ",", "name", "=", "None", ",", "index", "=", "None", ")", ":", "# check that name is valid and doesn't conflict with data columns", "if", "(", "name", "or", "(", "hasattr", "(", "meta", ",", "'name'", ")", "and", ...
42.68254
0.000727
def generate_example_rst(app): """ Generate the list of examples, as well as the contents of examples. """ root_dir = os.path.join(app.builder.srcdir, 'auto_examples') example_dir = os.path.abspath(app.builder.srcdir + '/../' + 'examples') try: plot_gallery = eval(app.builder.config....
[ "def", "generate_example_rst", "(", "app", ")", ":", "root_dir", "=", "os", ".", "path", ".", "join", "(", "app", ".", "builder", ".", "srcdir", ",", "'auto_examples'", ")", "example_dir", "=", "os", ".", "path", ".", "abspath", "(", "app", ".", "build...
26.098361
0.001211
def SETZ(cpu, dest): """ Sets byte if zero. :param cpu: current CPU. :param dest: destination operand. """ dest.write(Operators.ITEBV(dest.size, cpu.ZF, 1, 0))
[ "def", "SETZ", "(", "cpu", ",", "dest", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "ZF", ",", "1", ",", "0", ")", ")" ]
25.125
0.009615
def read_dir(path, folder): """ Returns a list of relative file paths to `path` for all files within `folder` """ full_path = os.path.join(path, folder) fnames = glob(f"{full_path}/*.*") directories = glob(f"{full_path}/*/") if any(fnames): return [os.path.relpath(f,path) for f in fnames] ...
[ "def", "read_dir", "(", "path", ",", "folder", ")", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "folder", ")", "fnames", "=", "glob", "(", "f\"{full_path}/*.*\"", ")", "directories", "=", "glob", "(", "f\"{full_path}/*/\"", "...
51.909091
0.008606
def update_subtask_positions_obj(self, positions_obj_id, revision, values): ''' Updates the ordering of subtasks in the positions object with the given ID to the ordering in the given values. See https://developer.wunderlist.com/documentation/endpoints/positions for more info Return: ...
[ "def", "update_subtask_positions_obj", "(", "self", ",", "positions_obj_id", ",", "revision", ",", "values", ")", ":", "return", "positions_endpoints", ".", "update_subtask_positions_obj", "(", "self", ",", "positions_obj_id", ",", "revision", ",", "values", ")" ]
51.5
0.01145
def _optimize_with_progs(format_module, filename, image_format): """ Use the correct optimizing functions in sequence. And report back statistics. """ filesize_in = os.stat(filename).st_size report_stats = None for func in format_module.PROGRAMS: if not getattr(Settings, func.__nam...
[ "def", "_optimize_with_progs", "(", "format_module", ",", "filename", ",", "image_format", ")", ":", "filesize_in", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_size", "report_stats", "=", "None", "for", "func", "in", "format_module", ".", "PROGRAMS"...
29.541667
0.001366
def tuple_as_vec(xyz): """ Generates a Vector3 from a tuple or list. """ vec = Vector3() vec[0] = xyz[0] vec[1] = xyz[1] vec[2] = xyz[2] return vec
[ "def", "tuple_as_vec", "(", "xyz", ")", ":", "vec", "=", "Vector3", "(", ")", "vec", "[", "0", "]", "=", "xyz", "[", "0", "]", "vec", "[", "1", "]", "=", "xyz", "[", "1", "]", "vec", "[", "2", "]", "=", "xyz", "[", "2", "]", "return", "ve...
22.555556
0.009479
def load(obj, env=None, silent=True, key=None, filename=None): """ Reads and loads in to "obj" a single key or all keys from source :param obj: the settings instance :param env: settings current env (upper case) default='DEVELOPMENT' :param silent: if errors should raise :param key: if defined l...
[ "def", "load", "(", "obj", ",", "env", "=", "None", ",", "silent", "=", "True", ",", "key", "=", "None", ",", "filename", "=", "None", ")", ":", "# Load data from your custom data source (file, database, memory etc)", "# use `obj.set(key, value)` or `obj.update(dict)` t...
37.108696
0.000571
def sdk_version(self): '''sdk version of connected device.''' if self.__sdk == 0: try: self.__sdk = int(self.adb.cmd("shell", "getprop", "ro.build.version.sdk").communicate()[0].decode("utf-8").strip()) except: pass return self.__sdk
[ "def", "sdk_version", "(", "self", ")", ":", "if", "self", ".", "__sdk", "==", "0", ":", "try", ":", "self", ".", "__sdk", "=", "int", "(", "self", ".", "adb", ".", "cmd", "(", "\"shell\"", ",", "\"getprop\"", ",", "\"ro.build.version.sdk\"", ")", "....
38.25
0.01278
def is_dir_exists(dirpath): # type: (AnyStr) -> bool """Check the existence of folder path.""" if dirpath is None or not os.path.exists(dirpath) or not os.path.isdir(dirpath): return False else: return True
[ "def", "is_dir_exists", "(", "dirpath", ")", ":", "# type: (AnyStr) -> bool", "if", "dirpath", "is", "None", "or", "not", "os", ".", "path", ".", "exists", "(", "dirpath", ")", "or", "not", "os", ".", "path", ".", "isdir", "(", "dirpath", ")", ":", "re...
36.571429
0.015267
def get(self, key, default=None, cast=True): """ Return the field data given by field name *key*. Args: key: the field name of the data to return default: the value to return if *key* is not in the row """ tablename, _, key = key.rpartition(':') i...
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ",", "cast", "=", "True", ")", ":", "tablename", ",", "_", ",", "key", "=", "key", ".", "rpartition", "(", "':'", ")", "if", "tablename", "and", "tablename", "not", "in", "self", ...
36.636364
0.002418
def enough_input(layer, post_processor_input): """Check if the input from impact_fields in enough. :param layer: The vector layer to use for post processing. :type layer: QgsVectorLayer :param post_processor_input: Collection of post processor input requirements. :type post_processor_input...
[ "def", "enough_input", "(", "layer", ",", "post_processor_input", ")", ":", "impact_fields", "=", "list", "(", "layer", ".", "keywords", "[", "'inasafe_fields'", "]", ".", "keys", "(", ")", ")", "for", "input_key", ",", "input_values", "in", "list", "(", "...
42.988506
0.000261
def listen_ttf(self, target, timeout): """Listen as Type F Target is supported for either 212 or 424 kbps.""" if target.brty not in ('212F', '424F'): info = "unsupported target bitrate: %r" % target.brty raise nfc.clf.UnsupportedTargetError(info) if target.sensf_res is N...
[ "def", "listen_ttf", "(", "self", ",", "target", ",", "timeout", ")", ":", "if", "target", ".", "brty", "not", "in", "(", "'212F'", ",", "'424F'", ")", ":", "info", "=", "\"unsupported target bitrate: %r\"", "%", "target", ".", "brty", "raise", "nfc", "....
47.303571
0.00074
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw): '''elt -- the current DOMWrapper element sw -- soapWriter object pyobj -- python object to serialize ''' if pyobj is not None and type(pyobj) not in _seqtypes: raise EvaluateException, 'expecting ...
[ "def", "serialize", "(", "self", ",", "elt", ",", "sw", ",", "pyobj", ",", "name", "=", "None", ",", "orig", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "pyobj", "is", "not", "None", "and", "type", "(", "pyobj", ")", "not", "in", "_seqtyp...
35.181818
0.008805
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'duration') and self.duration is not None: _dict['duration'] = self.duration if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name ...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'duration'", ")", "and", "self", ".", "duration", "is", "not", "None", ":", "_dict", "[", "'duration'", "]", "=", "self", ".", "duration", "if", "...
50.125
0.002448
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AuthorizedConnectAppContext for this AuthorizedConnectAppInstance :rtype: twilio.rest.api.v2010.a...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "AuthorizedConnectAppContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]...
44.4
0.008824
def detectAndroidPhone(self): """Return detection of an Android phone Detects if the current device is a (small-ish) Android OS-based device used for calling and/or multi-media (like a Samsung Galaxy Player). Google says these devices will have 'Android' AND 'mobile' in user agent. ...
[ "def", "detectAndroidPhone", "(", "self", ")", ":", "#First, let's make sure we're on an Android device.", "if", "not", "self", ".", "detectAndroid", "(", ")", ":", "return", "False", "#If it's Android and has 'mobile' in it, Google says it's a phone.", "if", "UAgentInfo", "....
38.238095
0.008505
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at (R,z, phi) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: pote...
[ "def", "_evaluate", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "r", "=", "numpy", ".", "sqrt", "(", "R", "**", "2.", "+", "z", "**", "2.", ")", "out", "=", "self", ".", "_scf", "(", "R", ",", ...
29.190476
0.025276
def _write_openjpeg(self, img_array, verbose=False): """ Write JPEG 2000 file using OpenJPEG 1.5 interface. """ if img_array.ndim == 2: # Force the image to be 3D. Just makes things easier later on. img_array = img_array.reshape(img_array.shape[0], ...
[ "def", "_write_openjpeg", "(", "self", ",", "img_array", ",", "verbose", "=", "False", ")", ":", "if", "img_array", ".", "ndim", "==", "2", ":", "# Force the image to be 3D. Just makes things easier later on.", "img_array", "=", "img_array", ".", "reshape", "(", ...
41.287879
0.000717
def has_next_page(self): """Whether there is a next page or not :getter: Return true if there is a next page """ return self.current_page < math.ceil(self.total_count / self.per_page)
[ "def", "has_next_page", "(", "self", ")", ":", "return", "self", ".", "current_page", "<", "math", ".", "ceil", "(", "self", ".", "total_count", "/", "self", ".", "per_page", ")" ]
35.166667
0.009259
def _low_dim_sim(self, v, w, normalize=False, Y=None, idx=0): """Similarity measurement based on (Student) t-Distribution""" sim = (1 + np.linalg.norm(v - w) ** 2) ** -1 if normalize: return sim / sum(map(lambda x: x[1], self._knn(idx, Y, high_dim=False))) else: ...
[ "def", "_low_dim_sim", "(", "self", ",", "v", ",", "w", ",", "normalize", "=", "False", ",", "Y", "=", "None", ",", "idx", "=", "0", ")", ":", "sim", "=", "(", "1", "+", "np", ".", "linalg", ".", "norm", "(", "v", "-", "w", ")", "**", "2", ...
35.888889
0.009063
def atlasdb_sync_zonefiles( db, start_block, zonefile_dir, atlas_state, validate=True, end_block=None, path=None, con=None ): """ Synchronize atlas DB with name db NOT THREAD SAFE """ ret = None with AtlasDBOpen(con=con, path=path) as dbcon: ret = atlasdb_queue_zonefiles( dbcon, db, sta...
[ "def", "atlasdb_sync_zonefiles", "(", "db", ",", "start_block", ",", "zonefile_dir", ",", "atlas_state", ",", "validate", "=", "True", ",", "end_block", "=", "None", ",", "path", "=", "None", ",", "con", "=", "None", ")", ":", "ret", "=", "None", "with",...
48.095238
0.012621
def config_sources(app, environment, cluster, configs_dirs, app_dir, local=False, build=False): """Return the config files for an environment & cluster specific app.""" sources = [ # Machine-specific (configs_dirs, 'hostname'), (configs_dirs, 'hostname-local'), ...
[ "def", "config_sources", "(", "app", ",", "environment", ",", "cluster", ",", "configs_dirs", ",", "app_dir", ",", "local", "=", "False", ",", "build", "=", "False", ")", ":", "sources", "=", "[", "# Machine-specific", "(", "configs_dirs", ",", "'hostname'",...
39.904762
0.000582
def load_cell(fname="HL60_field.zip"): "Load zip file and return complex field" here = op.dirname(op.abspath(__file__)) data = op.join(here, "data") arc = zipfile.ZipFile(op.join(data, fname)) for f in arc.filelist: with arc.open(f) as fd: if f.filename.count("imag"): ...
[ "def", "load_cell", "(", "fname", "=", "\"HL60_field.zip\"", ")", ":", "here", "=", "op", ".", "dirname", "(", "op", ".", "abspath", "(", "__file__", ")", ")", "data", "=", "op", ".", "join", "(", "here", ",", "\"data\"", ")", "arc", "=", "zipfile", ...
30.733333
0.002105
def get_structure_seqrecords(model): """Get a dictionary of a PDB file's sequences. Special cases include: - Insertion codes. In the case of residue numbers like "15A", "15B", both residues are written out. Example: 9LPR - HETATMs. Currently written as an "X", or unknown amino acid. Args: ...
[ "def", "get_structure_seqrecords", "(", "model", ")", ":", "structure_seq_records", "=", "[", "]", "# Loop over each chain of the PDB", "for", "chain", "in", "model", ":", "tracker", "=", "0", "chain_seq", "=", "''", "chain_resnums", "=", "[", "]", "# Loop over th...
35.258065
0.002225
def expand_node_neighborhood(universe, graph, node: BaseEntity) -> None: """Expand around the neighborhoods of the given node in the result graph. :param pybel.BELGraph universe: The graph containing the stuff to add :param pybel.BELGraph graph: The graph to add stuff to :param node: A BEL node """...
[ "def", "expand_node_neighborhood", "(", "universe", ",", "graph", ",", "node", ":", "BaseEntity", ")", "->", "None", ":", "expand_node_predecessors", "(", "universe", ",", "graph", ",", "node", ")", "expand_node_successors", "(", "universe", ",", "graph", ",", ...
46
0.00237
def verify(password_hash, password): """ Takes a modular crypt encoded stored password hash derived using one of the algorithms supported by `libsodium` and checks if the user provided password will hash to the same string when using the parameters saved in the stored hash """ if password_ha...
[ "def", "verify", "(", "password_hash", ",", "password", ")", ":", "if", "password_hash", ".", "startswith", "(", "argon2id", ".", "STRPREFIX", ")", ":", "return", "argon2id", ".", "verify", "(", "password_hash", ",", "password", ")", "elif", "password_hash", ...
43.611111
0.001247
def _populate_basic_data(mfg_event, record): """Copies data from the OpenHTF TestRecord to the MfgEvent proto.""" # TODO: # * Missing in proto: set run name from metadata. # * `part_tags` field on proto is unused # * `timings` field on proto is unused. # * Handle arbitrary units as uom_code/uom_suff...
[ "def", "_populate_basic_data", "(", "mfg_event", ",", "record", ")", ":", "# TODO:", "# * Missing in proto: set run name from metadata.", "# * `part_tags` field on proto is unused", "# * `timings` field on proto is unused.", "# * Handle arbitrary units as uom_code/uom_suffix.", "# ...
43.127273
0.012366
def stop_listener_thread(self): """ Stop listener thread running in the background """ if self.sync_thread: self.should_listen = False self.sync_thread.join() self.sync_thread = None
[ "def", "stop_listener_thread", "(", "self", ")", ":", "if", "self", ".", "sync_thread", ":", "self", ".", "should_listen", "=", "False", "self", ".", "sync_thread", ".", "join", "(", ")", "self", ".", "sync_thread", "=", "None" ]
33.714286
0.008264
def connect_by_uri(uri): """General URI syntax: mysql://user:passwd@host:port/db?opt1=val1&opt2=val2&... where opt_n is in the list of options supported by MySQLdb: host,user,passwd,db,compress,connect_timeout,read_default_file, read_default_group,unix_socket,port NOTE: the authority...
[ "def", "connect_by_uri", "(", "uri", ")", ":", "puri", "=", "urisup", ".", "uri_help_split", "(", "uri", ")", "params", "=", "__dict_from_query", "(", "puri", "[", "QUERY", "]", ")", "if", "puri", "[", "AUTHORITY", "]", ":", "user", ",", "passwd", ",",...
40.917647
0.000842
def dict_stack(dict_list, key_prefix=''): r""" stacks values from two dicts into a new dict where the values are list of the input values. the keys are the same. DEPRICATE in favor of dict_stack2 Args: dict_list (list): list of dicts with similar keys Returns: dict dict_stacke...
[ "def", "dict_stack", "(", "dict_list", ",", "key_prefix", "=", "''", ")", ":", "dict_stacked_", "=", "defaultdict", "(", "list", ")", "for", "dict_", "in", "dict_list", ":", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "dict_", ")", ":...
34.104167
0.000594
def _make_association(self, subject_id, object_id, rel_id, pubmed_ids): """ Make a reified association given an array of pubmed identifiers. Args: :param subject_id id of the subject of the association (gene/chem) :param object_id id of the object of the association (d...
[ "def", "_make_association", "(", "self", ",", "subject_id", ",", "object_id", ",", "rel_id", ",", "pubmed_ids", ")", ":", "# TODO pass in the relevant Assoc class rather than relying on G2P", "assoc", "=", "G2PAssoc", "(", "self", ".", "graph", ",", "self", ".", "na...
39.538462
0.001899
def grid(fitness_function, no_dimensions, step_size): """ Grid search using a fitness function over a given number of dimensions and a given step size between inclusive limits of 0 and 1. Parameters ---------- fitness_function: function A function that takes a tuple of floats as an argu...
[ "def", "grid", "(", "fitness_function", ",", "no_dimensions", ",", "step_size", ")", ":", "best_fitness", "=", "float", "(", "\"-inf\"", ")", "best_arguments", "=", "None", "for", "arguments", "in", "make_lists", "(", "no_dimensions", ",", "step_size", ")", ":...
30.172414
0.002215
def copy(self, repodir): """Copies the static files and folders specified in these settings into the locally-cloned repository directory. :arg repodir: the full path to the directory with the locally-cloned version of the pull request being unit tested. """ #Instead of...
[ "def", "copy", "(", "self", ",", "repodir", ")", ":", "#Instead of using the built-in shell copy, we make shell calls to rsync.", "#This allows us to copy only changes across between runs of pull-requests.", "from", "os", "import", "system", ",", "path", "vms", "(", "\"Running st...
52.869565
0.008078
def validate_none_of(values): """ Validate that a field is not in one of the given values. :param values: Iterable of invalid values. :raises: ``ValidationError('none_of')`` """ def none_of_validator(field, data): options = values if callable(options): options = opti...
[ "def", "validate_none_of", "(", "values", ")", ":", "def", "none_of_validator", "(", "field", ",", "data", ")", ":", "options", "=", "values", "if", "callable", "(", "options", ")", ":", "options", "=", "options", "(", ")", "if", "field", ".", "value", ...
32.428571
0.002141
def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None, distance=Distance(au=0.1)): """Generate an Apparent position from an altitude and azimuth. The altitude and azimuth can each be provided as an `Angle` object, or else as a number of degrees provided as...
[ "def", "from_altaz", "(", "self", ",", "alt", "=", "None", ",", "az", "=", "None", ",", "alt_degrees", "=", "None", ",", "az_degrees", "=", "None", ",", "distance", "=", "Distance", "(", "au", "=", "0.1", ")", ")", ":", "# TODO: should this method live o...
46.178571
0.002273
def uri_tree_precode_check(uri_tree, type_host = HOST_REG_NAME): """ Call this function to validate a raw URI tree before trying to encode it. """ scheme, authority, path, query, fragment = uri_tree # pylint: disable-msg=W0612 if scheme: if not valid_scheme(scheme): raise Inv...
[ "def", "uri_tree_precode_check", "(", "uri_tree", ",", "type_host", "=", "HOST_REG_NAME", ")", ":", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", "=", "uri_tree", "# pylint: disable-msg=W0612", "if", "scheme", ":", "if", "not", "valid_s...
47.695652
0.011618
def _configDevRequests(self, namestr, titlestr, devlist): """Generate configuration for I/O Request stats. @param namestr: Field name component indicating device type. @param titlestr: Title component indicating device type. @param devlist: List of devices. ""...
[ "def", "_configDevRequests", "(", "self", ",", "namestr", ",", "titlestr", ",", "devlist", ")", ":", "name", "=", "'diskio_%s_requests'", "%", "namestr", "if", "self", ".", "graphEnabled", "(", "name", ")", ":", "graph", "=", "MuninGraph", "(", "'Disk I/O - ...
53.655172
0.017045
def raw_file(client, src, dest, opt): """Write the contents of a vault path/key to a file. Is smart enough to attempt and handle binary files that are base64 encoded.""" path, key = path_pieces(src) resp = client.read(path) if not resp: client.revoke_self_token() raise aomi.excep...
[ "def", "raw_file", "(", "client", ",", "src", ",", "dest", ",", "opt", ")", ":", "path", ",", "key", "=", "path_pieces", "(", "src", ")", "resp", "=", "client", ".", "read", "(", "path", ")", "if", "not", "resp", ":", "client", ".", "revoke_self_to...
37.25
0.001091
def create_bioset_lookup(lookupdb, spectrafns, set_names): """Fills lookup database with biological set names""" unique_setnames = set(set_names) lookupdb.store_biosets(((x,) for x in unique_setnames)) set_id_map = lookupdb.get_setnames() mzmlfiles = ((os.path.basename(fn), set_id_map[setname]) ...
[ "def", "create_bioset_lookup", "(", "lookupdb", ",", "spectrafns", ",", "set_names", ")", ":", "unique_setnames", "=", "set", "(", "set_names", ")", "lookupdb", ".", "store_biosets", "(", "(", "(", "x", ",", ")", "for", "x", "in", "unique_setnames", ")", "...
48.888889
0.002232
def locate(self, requirement, prereleases=False): """ Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``Tr...
[ "def", "locate", "(", "self", ",", "requirement", ",", "prereleases", "=", "False", ")", ":", "result", "=", "None", "r", "=", "parse_requirement", "(", "requirement", ")", "if", "r", "is", "None", ":", "raise", "DistlibException", "(", "'Not a valid require...
43.241379
0.00117
def predict_sequence(self, labels, steps, streams=1, rng=None): '''Draw a sequential sample of class labels from this network. Parameters ---------- labels : list of int A list of integer class labels to get the classifier started. steps : int The number ...
[ "def", "predict_sequence", "(", "self", ",", "labels", ",", "steps", ",", "streams", "=", "1", ",", "rng", "=", "None", ")", ":", "if", "rng", "is", "None", "or", "isinstance", "(", "rng", ",", "int", ")", ":", "rng", "=", "np", ".", "random", "....
44.880952
0.002077
def main(argv=sys.argv): """Populate database with 30 users.""" if len(argv) < 2: usage(argv) config_uri = argv[1] setup_logging(config_uri) settings = get_appsettings(config_uri) engine = engine_from_config(settings, "sqlalchemy.") DBSession.configure(bind=engine) Base.met...
[ "def", "main", "(", "argv", "=", "sys", ".", "argv", ")", ":", "if", "len", "(", "argv", ")", "<", "2", ":", "usage", "(", "argv", ")", "config_uri", "=", "argv", "[", "1", "]", "setup_logging", "(", "config_uri", ")", "settings", "=", "get_appsett...
23.533333
0.001361
def portgroups_configured(name, dvs, portgroups): ''' Configures portgroups on a DVS. Creates/updates/removes portgroups in a provided DVS dvs Name of the DVS portgroups Portgroup dict representations (see module sysdocs) ''' datacenter = _get_datacenter_name() log.inf...
[ "def", "portgroups_configured", "(", "name", ",", "dvs", ",", "portgroups", ")", ":", "datacenter", "=", "_get_datacenter_name", "(", ")", "log", ".", "info", "(", "'Running state %s on DVS \\'%s\\', datacenter \\'%s\\''", ",", "name", ",", "dvs", ",", "datacenter",...
45.462687
0.000482
def patch(self, *args, **kwargs): """Update an object""" json_data = request.get_json() or {} qs = QSManager(request.args, self.schema) schema_kwargs = getattr(self, 'patch_schema_kwargs', dict()) schema_kwargs.update({'partial': True}) self.before_marshmallow(args, kwa...
[ "def", "patch", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "json_data", "=", "request", ".", "get_json", "(", ")", "or", "{", "}", "qs", "=", "QSManager", "(", "request", ".", "args", ",", "self", ".", "schema", ")", "schem...
34.846154
0.002147
def _get_value_and_line_offset(self, key, values): """Returns the index of the location of key, value pair in lines. :type key: str :param key: key, in config file. :type values: str :param values: values for key, in config file. This is plural, because you can have...
[ "def", "_get_value_and_line_offset", "(", "self", ",", "key", ",", "values", ")", ":", "values_list", "=", "self", ".", "_construct_values_list", "(", "values", ")", "if", "not", "values_list", ":", "return", "[", "]", "current_value_list_index", "=", "0", "ou...
32.472222
0.00083
def create_parser(subparsers): """ create parser """ metrics_parser = subparsers.add_parser( 'metrics', help='Display info of a topology\'s metrics', usage="%(prog)s cluster/[role]/[env] topology-name [options]", add_help=False) args.add_cluster_role_env(metrics_parser) args.add_topology...
[ "def", "create_parser", "(", "subparsers", ")", ":", "metrics_parser", "=", "subparsers", ".", "add_parser", "(", "'metrics'", ",", "help", "=", "'Display info of a topology\\'s metrics'", ",", "usage", "=", "\"%(prog)s cluster/[role]/[env] topology-name [options]\"", ",", ...
36.724138
0.017383
def _parse_action(self, action, current_time): """Parse a player action. TODO: handle cancels """ if action.action_type == 'research': name = mgz.const.TECHNOLOGIES[action.data.technology_type] self._research[action.data.player_id].append({ 'techn...
[ "def", "_parse_action", "(", "self", ",", "action", ",", "current_time", ")", ":", "if", "action", ".", "action_type", "==", "'research'", ":", "name", "=", "mgz", ".", "const", ".", "TECHNOLOGIES", "[", "action", ".", "data", ".", "technology_type", "]", ...
43.652174
0.001949
def compute_similarity_scores(self): """ Produce a list of similarity scores for each contiguous pair in a response. Calls compute_similarity_score method for every adjacent pair of words. The results are not used in clustering; this is merely to provide a visual representation to print...
[ "def", "compute_similarity_scores", "(", "self", ")", ":", "for", "i", ",", "unit", "in", "enumerate", "(", "self", ".", "parsed_response", ")", ":", "if", "i", "<", "len", "(", "self", ".", "parsed_response", ")", "-", "1", ":", "next_unit", "=", "sel...
51
0.008821
def _prepare_transition(self, is_on=None, brightness=None, color=None): """ Perform pre-transition tasks and construct the destination state. :param is_on: The on-off state to transition to. :param brightness: The brightness to transition to (0.0-1.0). :param color: The color to...
[ "def", "_prepare_transition", "(", "self", ",", "is_on", "=", "None", ",", "brightness", "=", "None", ",", "color", "=", "None", ")", ":", "dest_state", "=", "super", "(", ")", ".", "_prepare_transition", "(", "is_on", ",", "brightness", "=", "brightness",...
43.722222
0.002488
def _get_asym_alpha(self,a,b): """ Find alpha diffusion ratios from cryo oven with alpha detectors. a: list of alpha detector histograms (each helicity) b: list of beta detector histograms (each helicity) """ # just use AL0 try: ...
[ "def", "_get_asym_alpha", "(", "self", ",", "a", ",", "b", ")", ":", "# just use AL0", "try", ":", "a", "=", "a", "[", "2", ":", "4", "]", "except", "IndexError", ":", "a", "=", "a", "[", ":", "2", "]", "# sum counts in alpha detectors", "asum", "="...
26.433333
0.019465
def convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if isinstance(argument, str): if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) i...
[ "def", "convert", "(", "self", ",", "argument", ")", ":", "if", "isinstance", "(", "argument", ",", "str", ")", ":", "if", "argument", ".", "lower", "(", ")", "in", "[", "'true'", ",", "'t'", ",", "'1'", "]", ":", "return", "True", "elif", "argumen...
38.933333
0.010033
def loopless_solution(model, fluxes=None): """Convert an existing solution to a loopless one. Removes as many loops as possible (see Notes). Uses the method from CycleFreeFlux [1]_ and is much faster than `add_loopless` and should therefore be the preferred option to get loopless flux distributions...
[ "def", "loopless_solution", "(", "model", ",", "fluxes", "=", "None", ")", ":", "# Need to reoptimize otherwise spurious solution artifacts can cause", "# all kinds of havoc", "# TODO: check solution status", "if", "fluxes", "is", "None", ":", "sol", "=", "model", ".", "o...
37.761905
0.00041
def search_course(self, xqdm, kcdm=None, kcmc=None): """ 课程查询 @structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}] :param xqdm: 学期代码 :param kcdm: 课程代码 :param kcmc: 课程名称 """ return self.query(SearchCourse(xqdm, kcdm, kcmc))
[ "def", "search_course", "(", "self", ",", "xqdm", ",", "kcdm", "=", "None", ",", "kcmc", "=", "None", ")", ":", "return", "self", ".", "query", "(", "SearchCourse", "(", "xqdm", ",", "kcdm", ",", "kcmc", ")", ")" ]
27.636364
0.009554
def _Rforce(self,R,z,phi=0.,t=0.): """ NAME: _Rforce PURPOSE: evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
[ "def", "_Rforce", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "r2", "=", "R", "**", "2.", "+", "z", "**", "2.", "r", "=", "nu", ".", "sqrt", "(", "r2", ")", "return", "-", "(", "1.", "/", "r", ...
26.684211
0.015238
def remove_alias(type_): """ Returns `type_t` without typedef Args: type_ (type_t | declaration_t): type or declaration Returns: type_t: the type associated to the inputted declaration """ if isinstance(type_, cpptypes.type_t): type_ref = type_ elif isinstance(type_...
[ "def", "remove_alias", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "type_t", ")", ":", "type_ref", "=", "type_", "elif", "isinstance", "(", "type_", ",", "typedef", ".", "typedef_t", ")", ":", "type_ref", "=", "type_",...
28.181818
0.00156
def monthrange(cls, year, month): """Returns the number of days in a month""" functions.check_valid_bs_range(NepDate(year, month, 1)) return values.NEPALI_MONTH_DAY_DATA[year][month - 1]
[ "def", "monthrange", "(", "cls", ",", "year", ",", "month", ")", ":", "functions", ".", "check_valid_bs_range", "(", "NepDate", "(", "year", ",", "month", ",", "1", ")", ")", "return", "values", ".", "NEPALI_MONTH_DAY_DATA", "[", "year", "]", "[", "month...
51.75
0.009524
def export_dqdv(cell_data, savedir, sep, last_cycle=None): """Exports dQ/dV data from a CellpyData instance. Args: cell_data: CellpyData instance savedir: path to the folder where the files should be saved sep: separator for the .csv-files. last_cycle: only export up to this cyc...
[ "def", "export_dqdv", "(", "cell_data", ",", "savedir", ",", "sep", ",", "last_cycle", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"exporting dqdv\"", ")", "filename", "=", "cell_data", ".", "dataset", ".", "loaded_from", "no_merged_sets", "=", "\"...
37.272727
0.000594
def postSolve(self): ''' This method adds consumption at m=0 to the list of stable arm points, then constructs the consumption function as a cubic interpolation over those points. Should be run after the backshooting routine is complete. Parameters ---------- no...
[ "def", "postSolve", "(", "self", ")", ":", "# Add bottom point to the stable arm points", "self", ".", "solution", "[", "0", "]", ".", "mNrm_list", ".", "insert", "(", "0", ",", "0.0", ")", "self", ".", "solution", "[", "0", "]", ".", "cNrm_list", ".", "...
39.909091
0.014461
def pprint(sequence_file, annotation=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print sequence(s) from a file. """ annotations = [] if annotation: annotations.append([(first - 1, last) for first, last in annotation]) try: # Peek to se...
[ "def", "pprint", "(", "sequence_file", ",", "annotation", "=", "None", ",", "annotation_file", "=", "None", ",", "block_length", "=", "10", ",", "blocks_per_line", "=", "6", ")", ":", "annotations", "=", "[", "]", "if", "annotation", ":", "annotations", "....
37.307692
0.001005
def vcf2cytosure(institute_id, case_name, individual_id): """Download vcf2cytosure file for individual.""" (display_name, vcf2cytosure) = controllers.vcf2cytosure(store, institute_id, case_name, individual_id) outdir = os.path.abspath(os.path.dirname(vcf2cytosure)) filename = os.path.basename(...
[ "def", "vcf2cytosure", "(", "institute_id", ",", "case_name", ",", "individual_id", ")", ":", "(", "display_name", ",", "vcf2cytosure", ")", "=", "controllers", ".", "vcf2cytosure", "(", "store", ",", "institute_id", ",", "case_name", ",", "individual_id", ")", ...
36.9375
0.008251
def _assignrepr_bracketed2(assignrepr_bracketed1, values, prefix, width=None): """Return a prefixed, wrapped and properly aligned bracketed string representation of the given 2-dimensional value matrix using function |repr|.""" brackets = getattr(assignrepr_bracketed1, '_brackets') prefix += bracket...
[ "def", "_assignrepr_bracketed2", "(", "assignrepr_bracketed1", ",", "values", ",", "prefix", ",", "width", "=", "None", ")", ":", "brackets", "=", "getattr", "(", "assignrepr_bracketed1", ",", "'_brackets'", ")", "prefix", "+=", "brackets", "[", "0", "]", "lin...
41.444444
0.001311
def publish(tgt, fun, arg=None, tgt_type='glob', returner='', timeout=5, via_master=None): ''' Publish a command from the minion out to other minions. Publications need to be enabled on the Salt master and the minion needs to have ...
[ "def", "publish", "(", "tgt", ",", "fun", ",", "arg", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "returner", "=", "''", ",", "timeout", "=", "5", ",", "via_master", "=", "None", ")", ":", "return", "_publish", "(", "tgt", ",", "fun", ",", ...
31.04878
0.002284
def renyi(alphas, Ks, dim, required, min_val=np.spacing(1), clamp=True, to_self=False): r''' Estimate the Renyi-alpha divergence between distributions, based on kNN distances: 1/(\alpha-1) \log \int p^alpha q^(1-\alpha) If the inner integral is less than min_val (default ``np.spacing(1)``), ...
[ "def", "renyi", "(", "alphas", ",", "Ks", ",", "dim", ",", "required", ",", "min_val", "=", "np", ".", "spacing", "(", "1", ")", ",", "clamp", "=", "True", ",", "to_self", "=", "False", ")", ":", "alphas", "=", "np", ".", "reshape", "(", "alphas"...
32.913043
0.001284
def get_uploadflags(self, location): """Return uploadflags for the given server. """ uploadflags = [] server = self.defaults.servers[location] if self.sign: uploadflags.append('--sign') elif server.sign is not None: if server.sign: ...
[ "def", "get_uploadflags", "(", "self", ",", "location", ")", ":", "uploadflags", "=", "[", "]", "server", "=", "self", ".", "defaults", ".", "servers", "[", "location", "]", "if", "self", ".", "sign", ":", "uploadflags", ".", "append", "(", "'--sign'", ...
35.461538
0.002112
def _validate_plan_base( new_plan, base_plan, is_partition_subset=True, allow_rf_change=False, ): """Validate if given plan is valid comparing with given base-plan. Validate following assertions: - Partition-check: New partition-set should be subset of base-partition set - Replica-count...
[ "def", "_validate_plan_base", "(", "new_plan", ",", "base_plan", ",", "is_partition_subset", "=", "True", ",", "allow_rf_change", "=", "False", ",", ")", ":", "# Verify that partitions in plan are subset of base plan.", "new_partitions", "=", "set", "(", "[", "(", "p_...
35.308824
0.000405
def legacy_decrypt(jwe, jwk, adata='', validate_claims=True, expiry_seconds=None): """ Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.J...
[ "def", "legacy_decrypt", "(", "jwe", ",", "jwk", ",", "adata", "=", "''", ",", "validate_claims", "=", "True", ",", "expiry_seconds", "=", "None", ")", ":", "protected_header", ",", "encrypted_key", ",", "iv", ",", "ciphertext", ",", "authentication_tag", "=...
38.757576
0.001144
def register_commands(self): """ Load entry points for custom commands. """ for command in self._entry_points[self.COMMANDS_ENTRY_POINT].values(): command.load()
[ "def", "register_commands", "(", "self", ")", ":", "for", "command", "in", "self", ".", "_entry_points", "[", "self", ".", "COMMANDS_ENTRY_POINT", "]", ".", "values", "(", ")", ":", "command", ".", "load", "(", ")" ]
33.333333
0.009756
def dict_to_row(cls, observation_data): """ Takes a dictionary of observation data and converts it to a list of fields according to AAVSO visual format specification. :param cls: current class :param observation_data: a single observation as a dictionary """ row ...
[ "def", "dict_to_row", "(", "cls", ",", "observation_data", ")", ":", "row", "=", "[", "]", "row", ".", "append", "(", "observation_data", "[", "'name'", "]", ")", "row", ".", "append", "(", "observation_data", "[", "'date'", "]", ")", "row", ".", "appe...
33.666667
0.00175
def _get_matrix(self): """ Build a matrix of scenarios with sequence to include and returns a dict. { scenario_1: { 'subcommand': [ 'action-1', 'action-2', ], }, scenario_2: { ...
[ "def", "_get_matrix", "(", "self", ")", ":", "return", "dict", "(", "{", "scenario", ".", "name", ":", "{", "'check'", ":", "scenario", ".", "check_sequence", ",", "'cleanup'", ":", "scenario", ".", "cleanup_sequence", ",", "'converge'", ":", "scenario", "...
31.769231
0.001566
def process_url(url, server_name="", document_root=None, check_security=True): """ Goes through the url and returns a dictionary of fields. For example: img/photos/2008/05/12/WIZARDS_0034_05022035_r329x151.jpg?e315d4515574cec417b1845392ba687dd98c17ce actions: [('r', '329x151')] parent_d...
[ "def", "process_url", "(", "url", ",", "server_name", "=", "\"\"", ",", "document_root", "=", "None", ",", "check_security", "=", "True", ")", ":", "from", ".", "network", "import", "Http404", "from", "settings", "import", "(", "BASE_PATH", ",", "ORIG_BASE_P...
38.145631
0.002233
def get_point(grade_str): """ 根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float """ try: grade = float(grade_str) assert 0 <= grade <= 100 if 95 <= grade <= 100: return 4.3 elif 90 <= grade < 95: return 4.0 ...
[ "def", "get_point", "(", "grade_str", ")", ":", "try", ":", "grade", "=", "float", "(", "grade_str", ")", "assert", "0", "<=", "grade", "<=", "100", "if", "95", "<=", "grade", "<=", "100", ":", "return", "4.3", "elif", "90", "<=", "grade", "<", "95...
24.583333
0.000815
def dirty(self): """True if the cache needs to be updated, False otherwise""" return not os.path.exists(self.cachename) or \ (os.path.getmtime(self.filename) > os.path.getmtime(self.cachename))
[ "def", "dirty", "(", "self", ")", ":", "return", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "cachename", ")", "or", "(", "os", ".", "path", ".", "getmtime", "(", "self", ".", "filename", ")", ">", "os", ".", "path", ".", "getmtime...
45.2
0.021739
def interact_gridsearch_result_images(show_result_func, cfgdict_list, cfglbl_list, cfgresult_list, score_list=None, fnum=None, figtitle='', unpack=False, max_plots=25, verbose=True, ...
[ "def", "interact_gridsearch_result_images", "(", "show_result_func", ",", "cfgdict_list", ",", "cfglbl_list", ",", "cfgresult_list", ",", "score_list", "=", "None", ",", "fnum", "=", "None", ",", "figtitle", "=", "''", ",", "unpack", "=", "False", ",", "max_plot...
44.2
0.002083
def list_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501 """list_namespaced_stateful_set # noqa: E501 list or watch objects of kind StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asy...
[ "def", "list_namespaced_stateful_set", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ...
163.033333
0.000407
def parse_tags(self): """Parses tags in tag group""" tags = [] try: for tag in self._tag_group_dict["tags"]: tags.append(Tag(tag)) except: return tags return tags
[ "def", "parse_tags", "(", "self", ")", ":", "tags", "=", "[", "]", "try", ":", "for", "tag", "in", "self", ".", "_tag_group_dict", "[", "\"tags\"", "]", ":", "tags", ".", "append", "(", "Tag", "(", "tag", ")", ")", "except", ":", "return", "tags", ...
26
0.012397
def _to_spherical(flds, header): """Convert vector field to spherical.""" cth = np.cos(header['t_mesh'][:, :, :-1]) sth = np.sin(header['t_mesh'][:, :, :-1]) cph = np.cos(header['p_mesh'][:, :, :-1]) sph = np.sin(header['p_mesh'][:, :, :-1]) fout = np.copy(flds) fout[0] = cth * cph * flds[0]...
[ "def", "_to_spherical", "(", "flds", ",", "header", ")", ":", "cth", "=", "np", ".", "cos", "(", "header", "[", "'t_mesh'", "]", "[", ":", ",", ":", ",", ":", "-", "1", "]", ")", "sth", "=", "np", ".", "sin", "(", "header", "[", "'t_mesh'", "...
46.727273
0.001908
def create(self, archive, interval=None, **import_args): """ Creating a table means uploading a file or setting up a sync table :param archive: URL to the file (both remote URLs or local paths are supported) or StringIO object :param interval: Interval in seconds. ...
[ "def", "create", "(", "self", ",", "archive", ",", "interval", "=", "None", ",", "*", "*", "import_args", ")", ":", "archive", "=", "archive", ".", "lower", "(", ")", "if", "hasattr", "(", "archive", ",", "\"lower\"", ")", "else", "archive", "if", "s...
42.906667
0.000911
def register_scale(key=None): """Returns a decorator to register a scale type in the scale type registry. If no key is provided, the class name is used as a key. A key is provided for each core bqplot scale type so that the frontend can use this key regardless of the kernal language. """ de...
[ "def", "register_scale", "(", "key", "=", "None", ")", ":", "def", "wrap", "(", "scale", ")", ":", "label", "=", "key", "if", "key", "is", "not", "None", "else", "scale", ".", "__module__", "+", "scale", ".", "__name__", "Scale", ".", "scale_types", ...
36.769231
0.002041
def pawns_at(self, x, y): """Iterate over pawns that collide the given point.""" for pawn in self.pawn.values(): if pawn.collide_point(x, y): yield pawn
[ "def", "pawns_at", "(", "self", ",", "x", ",", "y", ")", ":", "for", "pawn", "in", "self", ".", "pawn", ".", "values", "(", ")", ":", "if", "pawn", ".", "collide_point", "(", "x", ",", "y", ")", ":", "yield", "pawn" ]
38.4
0.010204
def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]: """Parse all dependencies out of the requirements.txt file.""" essential_packages: PackagesType = {} other_packages: PackagesType = {} duplicates: Set[str] = set() with open("requirements.txt", "r") as req_file: section...
[ "def", "parse_requirements", "(", ")", "->", "Tuple", "[", "PackagesType", ",", "PackagesType", ",", "Set", "[", "str", "]", "]", ":", "essential_packages", ":", "PackagesType", "=", "{", "}", "other_packages", ":", "PackagesType", "=", "{", "}", "duplicates...
36.068966
0.000931
def isOpen(self): """ Return true if this range has any room in it. """ if self.leftedge and self.rightedge and self.leftedge > self.rightedge: return False if self.leftedge == self.rightedge: if self.leftop is gt or self.rightop is lt: return...
[ "def", "isOpen", "(", "self", ")", ":", "if", "self", ".", "leftedge", "and", "self", ".", "rightedge", "and", "self", ".", "leftedge", ">", "self", ".", "rightedge", ":", "return", "False", "if", "self", ".", "leftedge", "==", "self", ".", "rightedge"...
30.636364
0.008646
def render_fields(dictionary, *fields, **opts): ''' This function works similarly to :mod:`render_field <salt.modules.napalm_formula.render_field>` but for a list of fields from the same dictionary, rendering, indenting and distributing them on separate lines. ...
[ "def", "render_fields", "(", "dictionary", ",", "*", "fields", ",", "*", "*", "opts", ")", ":", "results", "=", "[", "]", "for", "field", "in", "fields", ":", "res", "=", "render_field", "(", "dictionary", ",", "field", ",", "*", "*", "opts", ")", ...
28.196078
0.002016
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from ....
[ "def", "get_page_meta", "(", "page", ",", "language", ")", ":", "from", "django", ".", "core", ".", "cache", "import", "cache", "from", "meta", ".", "views", "import", "Meta", "from", ".", "models", "import", "PageMeta", ",", "TitleMeta", "try", ":", "me...
43.934426
0.001277
def setup(self, *args): """Do preparations before printing the first row Args: *args: first row cells """ self.setup_formatters(*args) if self.columns: self.print_header() elif self.border and not self.csv: self.print_line(sel...
[ "def", "setup", "(", "self", ",", "*", "args", ")", ":", "self", ".", "setup_formatters", "(", "*", "args", ")", "if", "self", ".", "columns", ":", "self", ".", "print_header", "(", ")", "elif", "self", ".", "border", "and", "not", "self", ".", "cs...
30.636364
0.011527
def S_isothermal_pipe_eccentric_to_isothermal_pipe(D1, D2, Z, L=1.): r'''Returns the Shape factor `S` of a pipe of constant outer temperature and of outer diameter `D1` which is `Z` distance from the center of another pipe of outer diameter`D2`. Length `L` must be provided, but can be set to 1 to obtain...
[ "def", "S_isothermal_pipe_eccentric_to_isothermal_pipe", "(", "D1", ",", "D2", ",", "Z", ",", "L", "=", "1.", ")", ":", "return", "2.", "*", "pi", "*", "L", "/", "acosh", "(", "(", "D2", "**", "2", "+", "D1", "**", "2", "-", "4.", "*", "Z", "**",...
30.914894
0.000667
def parse_token(self, token): """ Obtain a user from a signed token. """ try: data = self.unsign(token) except signing.SignatureExpired: logger.debug("Expired token: %s", token) return except signing.BadSignature: logger.de...
[ "def", "parse_token", "(", "self", ",", "token", ")", ":", "try", ":", "data", "=", "self", ".", "unsign", "(", "token", ")", "except", "signing", ".", "SignatureExpired", ":", "logger", ".", "debug", "(", "\"Expired token: %s\"", ",", "token", ")", "ret...
32.735294
0.001745
def set_defaults(self, default_values, recursive = False): """ Set default values from specified Parameters and returns a new Parameters object. :param default_values: Parameters with default parameter values. :param recursive: (optional) true to perform deep copy, and false for shallo...
[ "def", "set_defaults", "(", "self", ",", "default_values", ",", "recursive", "=", "False", ")", ":", "result", "=", "Parameters", "(", ")", "if", "recursive", ":", "RecursiveObjectWriter", ".", "copy_properties", "(", "result", ",", "default_values", ")", "Rec...
36.2
0.008075
def node_transmissions(node_id): """Get all the transmissions of a node. The node id must be specified in the url. You can also pass direction (to/from/all) or status (all/pending/received) as arguments. """ exp = Experiment(session) # get the parameters direction = request_parameter(p...
[ "def", "node_transmissions", "(", "node_id", ")", ":", "exp", "=", "Experiment", "(", "session", ")", "# get the parameters", "direction", "=", "request_parameter", "(", "parameter", "=", "\"direction\"", ",", "default", "=", "\"incoming\"", ")", "status", "=", ...
33.15
0.002198
def delete(self, **kwargs): """ Performs a DELETE statement on the model's table in the master database. :param where: The WHERE clause. This can be a plain string, a dict or an array. :type where: string, dict, array """ kwargs['stack'] = self.stack_mark(inspect.stack()...
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'stack'", "]", "=", "self", ".", "stack_mark", "(", "inspect", ".", "stack", "(", ")", ")", "return", "self", ".", "db_adapter", "(", "role", "=", "'master'", ")", "."...
38.4
0.012723
def global_data_dir(): """Return the global Intake catalog dir for the current environment""" prefix = False if VIRTUALENV_VAR in os.environ: prefix = os.environ[VIRTUALENV_VAR] elif CONDA_VAR in os.environ: prefix = sys.prefix elif which('conda'): # conda exists but is not a...
[ "def", "global_data_dir", "(", ")", ":", "prefix", "=", "False", "if", "VIRTUALENV_VAR", "in", "os", ".", "environ", ":", "prefix", "=", "os", ".", "environ", "[", "VIRTUALENV_VAR", "]", "elif", "CONDA_VAR", "in", "os", ".", "environ", ":", "prefix", "="...
36.4375
0.001672
def _get_manifest_body(context, prefix, path2info, put_headers): """ Returns body for manifest file and modifies put_headers. path2info is a dict like {"path": (size, etag)} """ if context.static_segments: body = json.dumps([ {'path': '/' + p, 'size_bytes': s, 'etag': e} ...
[ "def", "_get_manifest_body", "(", "context", ",", "prefix", ",", "path2info", ",", "put_headers", ")", ":", "if", "context", ".", "static_segments", ":", "body", "=", "json", ".", "dumps", "(", "[", "{", "'path'", ":", "'/'", "+", "p", ",", "'size_bytes'...
32.263158
0.001585
def format_log(request, message_type, message): """ Formats a log message similar to gevent's pywsgi request logging. """ from django_socketio.settings import MESSAGE_LOG_FORMAT if MESSAGE_LOG_FORMAT is None: return None now = datetime.now().replace(microsecond=0) args = dict(request...
[ "def", "format_log", "(", "request", ",", "message_type", ",", "message", ")", ":", "from", "django_socketio", ".", "settings", "import", "MESSAGE_LOG_FORMAT", "if", "MESSAGE_LOG_FORMAT", "is", "None", ":", "return", "None", "now", "=", "datetime", ".", "now", ...
40.9
0.002392