text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def to_esri_wkt(self): """ Returns the CS as a ESRI WKT formatted string. """ return 'GEOGCS["%s", %s, %s, %s, AXIS["Lon", %s], AXIS["Lat", %s]]' % (self.name, self.datum.to_esri_wkt(), self.prime_mer.to_esri_wkt(), self.angunit.to_esri_wkt(), self.twin_ax[0].esri_wkt, self.twin_ax[1].es...
[ "def", "to_esri_wkt", "(", "self", ")", ":", "return", "'GEOGCS[\"%s\", %s, %s, %s, AXIS[\"Lon\", %s], AXIS[\"Lat\", %s]]'", "%", "(", "self", ".", "name", ",", "self", ".", "datum", ".", "to_esri_wkt", "(", ")", ",", "self", ".", "prime_mer", ".", "to_esri_wkt", ...
64.8
0.012195
def runStretch(noiseLevel=None, profile=False): """ Stretch test that learns a lot of objects. Parameters: ---------------------------- @param noiseLevel (float) Noise level to add to the locations and features during inference @param profile (bool) If True, the network will ...
[ "def", "runStretch", "(", "noiseLevel", "=", "None", ",", "profile", "=", "False", ")", ":", "exp", "=", "L4L2Experiment", "(", "\"stretch_L10_F10_C2\"", ",", "numCorticalColumns", "=", "2", ",", ")", "objects", "=", "createObjectMachine", "(", "machineType", ...
27.207317
0.014706
def encode_df(df, data_types={}): """ Encode columns so their values are usable in vector operations. Making a few assumptions here, like that datetime should be an integer, and that it's acceptable to fill NaNs with 0. """ numbers = [] categories = [] datetimes = [] for ...
[ "def", "encode_df", "(", "df", ",", "data_types", "=", "{", "}", ")", ":", "numbers", "=", "[", "]", "categories", "=", "[", "]", "datetimes", "=", "[", "]", "for", "column", ",", "series", "in", "df", ".", "iteritems", "(", ")", ":", "if", "colu...
33.175
0.009517
def ndef(ctx, slot, prefix): """ Select slot configuration to use for NDEF. The default prefix will be used if no prefix is specified. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if not dev.config.nfc_supported: ctx.fail('NFC interface not available.') if not co...
[ "def", "ndef", "(", "ctx", ",", "slot", ",", "prefix", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "dev", ".", "config", ".", "nfc_supported", ":", "ctx", ...
28.428571
0.001621
def _sqrt(x): """ Return square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply a sqrt method. """ x = np.clip(x, a_min=0, a_max=None) try: return np.sqrt(x) except AttributeError: exponen...
[ "def", "_sqrt", "(", "x", ")", ":", "x", "=", "np", ".", "clip", "(", "x", ",", "a_min", "=", "0", ",", "a_max", "=", "None", ")", "try", ":", "return", "np", ".", "sqrt", "(", "x", ")", "except", "AttributeError", ":", "exponent", "=", "0.5", ...
21.761905
0.002096
def body(self): """get the contents of the script""" if not hasattr(self, '_body'): self._body = inspect.getsource(self.module) return self._body
[ "def", "body", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_body'", ")", ":", "self", ".", "_body", "=", "inspect", ".", "getsource", "(", "self", ".", "module", ")", "return", "self", ".", "_body" ]
35.4
0.01105
def _gcs_get_key_names(bucket, pattern): """ Get names of all Google Cloud Storage keys in a specified bucket that match a pattern. """ return [obj.metadata.name for obj in _gcs_get_keys(bucket, pattern)]
[ "def", "_gcs_get_key_names", "(", "bucket", ",", "pattern", ")", ":", "return", "[", "obj", ".", "metadata", ".", "name", "for", "obj", "in", "_gcs_get_keys", "(", "bucket", ",", "pattern", ")", "]" ]
68.666667
0.019231
def draw_screen(self, size): """Render curses screen """ self.tui.clear() canvas = self.top.render(size, focus=True) self.tui.draw_screen(size, canvas)
[ "def", "draw_screen", "(", "self", ",", "size", ")", ":", "self", ".", "tui", ".", "clear", "(", ")", "canvas", "=", "self", ".", "top", ".", "render", "(", "size", ",", "focus", "=", "True", ")", "self", ".", "tui", ".", "draw_screen", "(", "siz...
26.571429
0.010417
def merge_lists(dest, source, extend_lists=False): """Recursively merge two lists. :keyword extend_lists: if true, just extends lists instead of merging them. This applies merge_dictionary if any of the entries are dicts. Note: This updates dest and returns it. """ if not source: retur...
[ "def", "merge_lists", "(", "dest", ",", "source", ",", "extend_lists", "=", "False", ")", ":", "if", "not", "source", ":", "return", "if", "not", "extend_lists", ":", "# Make them the same size", "left", "=", "dest", "right", "=", "source", "[", ":", "]", ...
38.25
0.000797
def rescale_max(x, to=(0, 1), _from=None): """ Rescale numeric vector to have specified maximum. Parameters ---------- x : array_like | numeric 1D vector of values to manipulate. to : tuple output range (numeric vector of length two) _from : tuple input range (numeri...
[ "def", "rescale_max", "(", "x", ",", "to", "=", "(", "0", ",", "1", ")", ",", "_from", "=", "None", ")", ":", "array_like", "=", "True", "try", ":", "len", "(", "x", ")", "except", "TypeError", ":", "array_like", "=", "False", "x", "=", "[", "x...
23.098361
0.000681
def build_graph(layout_str, slanted): ''' builds an adjacency graph as a dictionary: {character: [adjacent_characters]}. adjacent characters occur in a clockwise order. for example: * on qwerty layout, 'g' maps to ['fF', 'tT', 'yY', 'hH', 'bB', 'vV'] * on keypad layout, '7' maps to [None, None, ...
[ "def", "build_graph", "(", "layout_str", ",", "slanted", ")", ":", "position_table", "=", "{", "}", "# maps from tuple (x,y) -> characters at that position.", "tokens", "=", "layout_str", ".", "split", "(", ")", "token_size", "=", "len", "(", "tokens", "[", "0", ...
58.8
0.008366
def _apply_units_to_numpy_data_readers(parameters, data): """ Apply units to data originally loaded by :class:`NumPyLoadTxtReader` or :class:`NumPyGenFromTxtReader`. :param parameters: Dictionary of data source parameters read from JSON file. :type parameters: dict :param data: Dictiona...
[ "def", "_apply_units_to_numpy_data_readers", "(", "parameters", ",", "data", ")", ":", "# apply header units", "header_param", "=", "parameters", ".", "get", "(", "'header'", ")", "# default is None", "# check for headers", "if", "header_param", ":", "fields", "=", "h...
38.464286
0.000906
def process(in_path, annot_beats=False, feature="pcp", framesync=False, boundaries_id=msaf.config.default_bound_id, labels_id=msaf.config.default_label_id, hier=False, sonify_bounds=False, plot=False, n_jobs=4, annotator_id=0, config=None, out_bounds="out_bounds.wav", out...
[ "def", "process", "(", "in_path", ",", "annot_beats", "=", "False", ",", "feature", "=", "\"pcp\"", ",", "framesync", "=", "False", ",", "boundaries_id", "=", "msaf", ".", "config", ".", "default_bound_id", ",", "labels_id", "=", "msaf", ".", "config", "."...
40.221154
0.000233
def WalkChildren(elem): """ Walk the XML tree of children below elem, returning each in order. """ for child in elem.childNodes: yield child for elem in WalkChildren(child): yield elem
[ "def", "WalkChildren", "(", "elem", ")", ":", "for", "child", "in", "elem", ".", "childNodes", ":", "yield", "child", "for", "elem", "in", "WalkChildren", "(", "child", ")", ":", "yield", "elem" ]
23.5
0.041026
def lock(self, lock_name, timeout=900): """ Attempt to use lock and unlock, which will work if the Cache is Redis, but fall back to a memcached-compliant add/delete approach. If the Jobtastic Cache isn't Redis or Memcache, or another product with a compatible lock or add/delete ...
[ "def", "lock", "(", "self", ",", "lock_name", ",", "timeout", "=", "900", ")", ":", "# Try Redis first", "try", ":", "try", ":", "lock", "=", "self", ".", "cache", ".", "lock", "except", "AttributeError", ":", "try", ":", "# Possibly using old Django-Redis",...
38.782609
0.001093
def coll_to_tuples(cls, coll): """``coll_to_tuples`` is capable of unpacking its own collection types (`list`), ``collections.Mapping`` objects, as well generators, sequences and iterators. Returns ``(*int*, Value)``. Does not coerce items. """ if isinstance(coll, bases...
[ "def", "coll_to_tuples", "(", "cls", ",", "coll", ")", ":", "if", "isinstance", "(", "coll", ",", "basestring", ")", ":", "raise", "exc", ".", "CollectionCoerceError", "(", "passed", "=", "coll", ",", "colltype", "=", "cls", ",", ")", "if", "isinstance",...
34.16129
0.001837
def cmdline(argv=sys.argv[1:]): """ Script for rebasing a text file """ parser = ArgumentParser( description='Rebase a text from his stop words') parser.add_argument('language', help='The language used to rebase') parser.add_argument('source', help='Text file to rebase') options = pa...
[ "def", "cmdline", "(", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "'Rebase a text from his stop words'", ")", "parser", ".", "add_argument", "(", "'language'", ",", "help", "=", ...
37.333333
0.001742
def _add(self, name, *args, **kwargs): '''Appends a command to the scrims list of commands. You should not need to use this.''' self.commands.append(Command(name, args, kwargs))
[ "def", "_add", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "commands", ".", "append", "(", "Command", "(", "name", ",", "args", ",", "kwargs", ")", ")" ]
39.6
0.009901
def set_sgr_code(self, params): """ Set attributes based on SGR (Select Graphic Rendition) codes. Parameters ---------- params : sequence of ints A list of SGR codes for one or more SGR commands. Usually this sequence will have one element per command, although c...
[ "def", "set_sgr_code", "(", "self", ",", "params", ")", ":", "# Always consume the first parameter.", "if", "not", "params", ":", "return", "code", "=", "params", ".", "pop", "(", "0", ")", "if", "code", "==", "0", ":", "self", ".", "reset_sgr", "(", ")"...
33.203704
0.001083
def final_spin_from_f0_tau(f0, tau, l=2, m=2): """Returns the final spin based on the given frequency and damping time. .. note:: Currently, only l = m = 2 is supported. Any other indices will raise a ``KeyError``. Parameters ---------- f0 : float or array Frequency of the ...
[ "def", "final_spin_from_f0_tau", "(", "f0", ",", "tau", ",", "l", "=", "2", ",", "m", "=", "2", ")", ":", "f0", ",", "tau", ",", "input_is_array", "=", "ensurearray", "(", "f0", ",", "tau", ")", "# from Berti et al. 2006", "a", ",", "b", ",", "c", ...
30.119048
0.002297
def _get_hourly_data(self, day_date, p_p_id): """Get Hourly Data.""" params = {"p_p_id": p_p_id, "p_p_lifecycle": 2, "p_p_state": "normal", "p_p_mode": "view", "p_p_resource_id": "resourceObtenirDonneesConsommationHoraires", ...
[ "def", "_get_hourly_data", "(", "self", ",", "day_date", ",", "p_p_id", ")", ":", "params", "=", "{", "\"p_p_id\"", ":", "p_p_id", ",", "\"p_p_lifecycle\"", ":", "2", ",", "\"p_p_state\"", ":", "\"normal\"", ",", "\"p_p_mode\"", ":", "\"view\"", ",", "\"p_p_...
48.454545
0.002452
def start_redis(self): """Start the Redis servers.""" assert self._redis_address is None redis_log_files = [self.new_log_files("redis")] for i in range(self._ray_params.num_redis_shards): redis_log_files.append(self.new_log_files("redis-shard_" + str(i))) (self._redi...
[ "def", "start_redis", "(", "self", ")", ":", "assert", "self", ".", "_redis_address", "is", "None", "redis_log_files", "=", "[", "self", ".", "new_log_files", "(", "\"redis\"", ")", "]", "for", "i", "in", "range", "(", "self", ".", "_ray_params", ".", "n...
47.826087
0.001783
def _deserialize(self, value, attr, data): """Deserialize string value.""" value = super(TrimmedString, self)._deserialize(value, attr, data) return value.strip()
[ "def", "_deserialize", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "value", "=", "super", "(", "TrimmedString", ",", "self", ")", ".", "_deserialize", "(", "value", ",", "attr", ",", "data", ")", "return", "value", ".", "strip", "(...
45.75
0.010753
def archive(cwd, output, rev='HEAD', prefix=None, git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Returns ``True`` if...
[ "def", "archive", "(", "cwd", ",", "output", ",", "rev", "=", "'HEAD'", ",", "prefix", "=", "None", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", ...
37.103896
0.00017
def listdir_iter(self, path=".", read_aheads=50): """ Generator version of `.listdir_attr`. See the API docs for `.listdir_attr` for overall details. This function adds one more kwarg on top of `.listdir_attr`: ``read_aheads``, an integer controlling how many ``SSH_FXP_...
[ "def", "listdir_iter", "(", "self", ",", "path", "=", "\".\"", ",", "read_aheads", "=", "50", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "\"listdir({!r})\"", ".", "format", "(", "path", ...
40.190476
0.000771
def make_middleware(cls, app, **options): """Creates the application WSGI middleware in charge of serving local files. A Depot middleware is required if your application wants to serve files from storages that don't directly provide and HTTP interface like :class:`depot.io.local.LocalFi...
[ "def", "make_middleware", "(", "cls", ",", "app", ",", "*", "*", "options", ")", ":", "from", "depot", ".", "middleware", "import", "DepotMiddleware", "mw", "=", "DepotMiddleware", "(", "app", ",", "*", "*", "options", ")", "cls", ".", "set_middleware", ...
43.5
0.009381
def _spectrum(self, photon_energy): """Compute differential IC spectrum for energies in ``photon_energy``. Compute IC spectrum using IC cross-section for isotropic interaction with a blackbody photon spectrum following Khangulyan, Aharonian, and Kelner 2014, ApJ 783, 100 (`arXiv:1310.79...
[ "def", "_spectrum", "(", "self", ",", "photon_energy", ")", ":", "outspecene", "=", "_validate_ene", "(", "photon_energy", ")", "self", ".", "specic", "=", "[", "]", "for", "seed", "in", "self", ".", "seed_photon_fields", ":", "# Call actual computation, detache...
36.166667
0.002245
def pagebreak(type='page', orient='portrait'): '''Insert a break, default 'page'. See http://openxmldeveloper.org/forums/thread/4075.aspx Return our page break element.''' # Need to enumerate different types of page breaks. validtypes = ['page', 'section'] if type not in validtypes: tmpl...
[ "def", "pagebreak", "(", "type", "=", "'page'", ",", "orient", "=", "'portrait'", ")", ":", "# Need to enumerate different types of page breaks.", "validtypes", "=", "[", "'page'", ",", "'section'", "]", "if", "type", "not", "in", "validtypes", ":", "tmpl", "=",...
41.259259
0.000877
def _rename_relation(self, old_key, new_relation): """Rename a relation named old_key to new_key, updating references. Return whether or not there was a key to rename. :param _ReferenceKey old_key: The existing key, to rename from. :param _CachedRelation new_key: The new relation, to re...
[ "def", "_rename_relation", "(", "self", ",", "old_key", ",", "new_relation", ")", ":", "# On the database level, a rename updates all values that were", "# previously referenced by old_name to be referenced by new_name.", "# basically, the name changes but some underlying ID moves. Kind of",...
44
0.001435
def set_Wp(self, Wp, Epmin=None, Epmax=None, amplitude_name=None): """ Normalize particle distribution so that the total energy in protons between Epmin and Epmax is Wp Parameters ---------- Wp : :class:`~astropy.units.Quantity` float Desired energy in protons. ...
[ "def", "set_Wp", "(", "self", ",", "Wp", ",", "Epmin", "=", "None", ",", "Epmax", "=", "None", ",", "amplitude_name", "=", "None", ")", ":", "Wp", "=", "validate_scalar", "(", "\"Wp\"", ",", "Wp", ",", "physical_type", "=", "\"energy\"", ")", "oldWp", ...
39
0.001191
def _FormatReturnOrExitToken(self, token_data): """Formats a return or exit token as a dictionary of values. Args: token_data (bsm_token_data_exit|bsm_token_data_return32| bsm_token_data_return64): AUT_EXIT, AUT_RETURN32 or AUT_RETURN64 token data. Returns: dict[str...
[ "def", "_FormatReturnOrExitToken", "(", "self", ",", "token_data", ")", ":", "error_string", "=", "bsmtoken", ".", "BSM_ERRORS", ".", "get", "(", "token_data", ".", "status", ",", "'UNKNOWN'", ")", "return", "{", "'error'", ":", "error_string", ",", "'token_st...
33.875
0.001795
def gwcalctyp(self): """Returns the value of the gwcalctyp input variable.""" dig0 = str(self._SIGMA_TYPES[self.type]) dig1 = str(self._SC_MODES[self.sc_mode]) return dig1.strip() + dig0.strip()
[ "def", "gwcalctyp", "(", "self", ")", ":", "dig0", "=", "str", "(", "self", ".", "_SIGMA_TYPES", "[", "self", ".", "type", "]", ")", "dig1", "=", "str", "(", "self", ".", "_SC_MODES", "[", "self", ".", "sc_mode", "]", ")", "return", "dig1", ".", ...
44.4
0.00885
def verify_tops(self, tops): ''' Verify the contents of the top file data ''' errors = [] if not isinstance(tops, dict): errors.append('Top data was not formed as a dict') # No further checks will work, bail out return errors for salten...
[ "def", "verify_tops", "(", "self", ",", "tops", ")", ":", "errors", "=", "[", "]", "if", "not", "isinstance", "(", "tops", ",", "dict", ")", ":", "errors", ".", "append", "(", "'Top data was not formed as a dict'", ")", "# No further checks will work, bail out",...
42.98
0.00091
def split_citations(citation_elements): """Split a citation line in multiple citations We handle the case where the author has put 2 citations in the same line but split with ; or some other method. """ splitted_citations = [] new_elements = [] current_recid = None current_doi = None ...
[ "def", "split_citations", "(", "citation_elements", ")", ":", "splitted_citations", "=", "[", "]", "new_elements", "=", "[", "]", "current_recid", "=", "None", "current_doi", "=", "None", "def", "check_ibid", "(", "current_elements", ",", "trigger_el", ")", ":",...
34.61039
0.000365
def demo_args(self): """ Additional method for replacing input arguments by demo ones. """ argv = random.choice(self.examples).replace("--demo", "") self._reparse_args['pos'] = shlex.split(argv)
[ "def", "demo_args", "(", "self", ")", ":", "argv", "=", "random", ".", "choice", "(", "self", ".", "examples", ")", ".", "replace", "(", "\"--demo\"", ",", "\"\"", ")", "self", ".", "_reparse_args", "[", "'pos'", "]", "=", "shlex", ".", "split", "(",...
38.166667
0.008547
def establishment_FPR(reference_patterns, estimated_patterns, similarity_metric="cardinality_score"): """Establishment F1 Score, Precision and Recall. Examples -------- >>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt") >>> est_patterns = mir_eval.io.load_patterns...
[ "def", "establishment_FPR", "(", "reference_patterns", ",", "estimated_patterns", ",", "similarity_metric", "=", "\"cardinality_score\"", ")", ":", "validate", "(", "reference_patterns", ",", "estimated_patterns", ")", "nP", "=", "len", "(", "reference_patterns", ")", ...
33
0.000475
def _on_scan(_loop, adapter, _adapter_id, info, expiration_time): """Callback when a new device is seen.""" info['validity_period'] = expiration_time adapter.notify_event_nowait(info.get('connection_string'), 'device_seen', info)
[ "def", "_on_scan", "(", "_loop", ",", "adapter", ",", "_adapter_id", ",", "info", ",", "expiration_time", ")", ":", "info", "[", "'validity_period'", "]", "=", "expiration_time", "adapter", ".", "notify_event_nowait", "(", "info", ".", "get", "(", "'connection...
47.6
0.008264
def hex_to_name(hex_value, spec=u'css3'): """ Convert a hexadecimal color value to its corresponding normalized color name, if any such name exists. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``...
[ "def", "hex_to_name", "(", "hex_value", ",", "spec", "=", "u'css3'", ")", ":", "if", "spec", "not", "in", "SUPPORTED_SPECIFICATIONS", ":", "raise", "ValueError", "(", "SPECIFICATION_ERROR_TEMPLATE", ".", "format", "(", "spec", "=", "spec", ")", ")", "normalize...
36.846154
0.001017
def zeroize_after_level(self, base_level): """ Set all levels after ``base_level`` to zero. """ index = _LEVELS.index(base_level) + 1 for level in _LEVELS[index:]: self.version_info[level] = 0
[ "def", "zeroize_after_level", "(", "self", ",", "base_level", ")", ":", "index", "=", "_LEVELS", ".", "index", "(", "base_level", ")", "+", "1", "for", "level", "in", "_LEVELS", "[", "index", ":", "]", ":", "self", ".", "version_info", "[", "level", "]...
44.8
0.008772
def pointsToVoronoiGridArray(lat, lon, extent=None): """ Converts points to grid array via voronoi """ voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent) # find nodes surrounding polygon centroid # sort nodes in counterclockwise order # create polygon perimeter through nodes ...
[ "def", "pointsToVoronoiGridArray", "(", "lat", ",", "lon", ",", "extent", "=", "None", ")", ":", "voronoi_centroids", "=", "_get_voronoi_centroid_array", "(", "lat", ",", "lon", ",", "extent", ")", "# find nodes surrounding polygon centroid", "# sort nodes in counterclo...
44.37037
0.000817
def get_elements(self, center='500@10', asteroid=False, comet=False): """Call JPL HORIZONS website to obtain orbital elements based on the provided targetname, epochs, and center code. For valid center codes, please refer to http://ssd.jpl.nasa.gov/horizons.cgi :param center: str; ...
[ "def", "get_elements", "(", "self", ",", "center", "=", "'500@10'", ",", "asteroid", "=", "False", ",", "comet", "=", "False", ")", ":", "# encode objectname for use in URL", "objectname", "=", "urllib", ".", "quote", "(", "self", ".", "targetname", ".", "en...
46.521073
0.000484
def get_hashhash(self, username): """ Generate a digest of the htpasswd hash """ return hashlib.sha256( self.users.get_hash(username) ).hexdigest()
[ "def", "get_hashhash", "(", "self", ",", "username", ")", ":", "return", "hashlib", ".", "sha256", "(", "self", ".", "users", ".", "get_hash", "(", "username", ")", ")", ".", "hexdigest", "(", ")" ]
27.571429
0.01005
def create_random_mutation_file(self, list_of_tuples, original_sequence, randomize_resnums=False, randomize_resids=False, skip_resnums=None): """Create the FoldX file 'individual_list.txt', but randomize the mutation numbers or residues tha...
[ "def", "create_random_mutation_file", "(", "self", ",", "list_of_tuples", ",", "original_sequence", ",", "randomize_resnums", "=", "False", ",", "randomize_resids", "=", "False", ",", "skip_resnums", "=", "None", ")", ":", "import", "random", "def", "find", "(", ...
53.928571
0.009109
def default_permission_factory(query_name, params): """Default permission factory. It enables by default the statistics if they don't have a dedicated permission factory. """ from invenio_stats import current_stats if current_stats.queries[query_name].permission_factory is None: return ...
[ "def", "default_permission_factory", "(", "query_name", ",", "params", ")", ":", "from", "invenio_stats", "import", "current_stats", "if", "current_stats", ".", "queries", "[", "query_name", "]", ".", "permission_factory", "is", "None", ":", "return", "AllowAllPermi...
34.307692
0.002183
def convert(sk_obj, input_features = None, output_feature_names = None): """ Convert scikit-learn pipeline, classifier, or regressor to Core ML format. Parameters ---------- sk_obj: model | [model] of scikit-learn format. Scikit learn model(s) to convert to a Core ML format. ...
[ "def", "convert", "(", "sk_obj", ",", "input_features", "=", "None", ",", "output_feature_names", "=", "None", ")", ":", "# This function is just a thin wrapper around the internal converter so", "# that sklearn isn't actually imported unless this function is called", "from", ".", ...
35.877698
0.001951
def poke_native(getstate): """ Serializer factory for types which state can be natively serialized. Arguments: getstate (callable): takes an object and returns the object's state to be passed to `pokeNative`. Returns: callable: serializer (`poke` routine). """ de...
[ "def", "poke_native", "(", "getstate", ")", ":", "def", "poke", "(", "service", ",", "objname", ",", "obj", ",", "container", ",", "visited", "=", "None", ",", "_stack", "=", "None", ")", ":", "service", ".", "pokeNative", "(", "objname", ",", "getstat...
26.470588
0.002146
def deploy(self, image_name, ip, flavor='m1.small'): """Create the node. This method should only be called by the BaremetalFactory. """ body_value = { "port": { "admin_state_up": True, "name": self.name + '_provision', "network...
[ "def", "deploy", "(", "self", ",", "image_name", ",", "ip", ",", "flavor", "=", "'m1.small'", ")", ":", "body_value", "=", "{", "\"port\"", ":", "{", "\"admin_state_up\"", ":", "True", ",", "\"name\"", ":", "self", ".", "name", "+", "'_provision'", ",", ...
41.190476
0.002259
def setCredentials(self, username, password): """ Sets authentication credentials for accessing the remote gateway. """ self.addHeader('Credentials', dict(userid=username.decode('utf-8'), password=password.decode('utf-8')), True)
[ "def", "setCredentials", "(", "self", ",", "username", ",", "password", ")", ":", "self", ".", "addHeader", "(", "'Credentials'", ",", "dict", "(", "userid", "=", "username", ".", "decode", "(", "'utf-8'", ")", ",", "password", "=", "password", ".", "dec...
44.666667
0.010989
def index(self, val, start=None, stop=None): """ Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice ind...
[ "def", "index", "(", "self", ",", "val", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "_len", "=", "self", ".", "_len", "if", "not", "_len", ":", "raise", "ValueError", "(", "'{0!r} is not in list'", ".", "format", "(", "val", ")", ...
29.688525
0.001603
def to_creator(self, subject, desc): """ Return a python-zimbra dict for CreateTaskRequest Example : <CreateTaskRequest> <m su="Task subject"> <inv> <comp name="Task subject"> <fr>Task comment</fr> <...
[ "def", "to_creator", "(", "self", ",", "subject", ",", "desc", ")", ":", "task", "=", "{", "'m'", ":", "{", "'su'", ":", "subject", ",", "'inv'", ":", "{", "'comp'", ":", "{", "'name'", ":", "subject", ",", "'fr'", ":", "{", "'_content'", ":", "d...
26.108108
0.001996
def bytes2zip(bytes): """ RETURN COMPRESSED BYTES """ if hasattr(bytes, "read"): buff = TemporaryFile() archive = gzip.GzipFile(fileobj=buff, mode='w') for b in bytes: archive.write(b) archive.close() buff.seek(0) from pyLibrary.env.big_data im...
[ "def", "bytes2zip", "(", "bytes", ")", ":", "if", "hasattr", "(", "bytes", ",", "\"read\"", ")", ":", "buff", "=", "TemporaryFile", "(", ")", "archive", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "buff", ",", "mode", "=", "'w'", ")", "for", ...
26.631579
0.001908
def is_email_enabled(email): """ Emails are activated by default. Returns false if an email has been disabled in settings.py """ s = get_settings(string="OVP_EMAILS") email_settings = s.get(email, {}) enabled = True if email_settings.get("disabled", False): enabled = False return enabled
[ "def", "is_email_enabled", "(", "email", ")", ":", "s", "=", "get_settings", "(", "string", "=", "\"OVP_EMAILS\"", ")", "email_settings", "=", "s", ".", "get", "(", "email", ",", "{", "}", ")", "enabled", "=", "True", "if", "email_settings", ".", "get", ...
25.25
0.022293
def process_request(self, request): """Adds data necessary for Horizon to function to the request.""" # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout try: timeout = ...
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "# Activate timezone handling", "tz", "=", "request", ".", "session", ".", "get", "(", "'django_timezone'", ")", "if", "tz", ":", "timezone", ".", "activate", "(", "tz", ")", "# Check for session...
45.253968
0.000687
def gate(self, tzero=1.0, tpad=0.5, whiten=True, threshold=50., cluster_window=0.5, **whiten_kwargs): """Removes high amplitude peaks from data using inverse Planck window. Points will be discovered automatically using a provided threshold and clustered within a provided time window...
[ "def", "gate", "(", "self", ",", "tzero", "=", "1.0", ",", "tpad", "=", "0.5", ",", "whiten", "=", "True", ",", "threshold", "=", "50.", ",", "cluster_window", "=", "0.5", ",", "*", "*", "whiten_kwargs", ")", ":", "try", ":", "from", "scipy", ".", ...
39.836957
0.000799
def make_ro(obj: Any, forgive_type=False): """ Make a json-serializable type recursively read-only :param obj: Any json-serializable type :param forgive_type: If you can forgive a type to be unknown (instead of raising an exception) """ if isinstance(obj, (str, bytes, ...
[ "def", "make_ro", "(", "obj", ":", "Any", ",", "forgive_type", "=", "False", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "str", ",", "bytes", ",", "int", ",", "float", ",", "bool", ",", "RoDict", ",", "RoList", ")", ")", "or", "obj", "is"...
34.333333
0.00135
def B(g,i): """recursively constructs B line for g; i = len(g)-1""" g1 = g&(2**i) if i: nA = Awidth(i) nB = Bwidth(i) i=i-1 Bn = B(g,i) if g1: return Bn << (nA+nB) | int('1'*nA,2) << nB | Bn else: return int('1'*nB,2) << (nA+...
[ "def", "B", "(", "g", ",", "i", ")", ":", "g1", "=", "g", "&", "(", "2", "**", "i", ")", "if", "i", ":", "nA", "=", "Awidth", "(", "i", ")", "nB", "=", "Bwidth", "(", "i", ")", "i", "=", "i", "-", "1", "Bn", "=", "B", "(", "g", ",",...
24.294118
0.02331
def edit( cls, record, parent = None, uifile = '', commit = True ): """ Prompts the user to edit the inputed record. :param record | <orb.Table> parent | <QWidget> :return <bool> | accepted """ # create the dialog ...
[ "def", "edit", "(", "cls", ",", "record", ",", "parent", "=", "None", ",", "uifile", "=", "''", ",", "commit", "=", "True", ")", ":", "# create the dialog\r", "dlg", "=", "QDialog", "(", "parent", ")", "dlg", ".", "setWindowTitle", "(", "'Edit %s'", "%...
32.137255
0.015986
def describe_function(FunctionName, region=None, key=None, keyid=None, profile=None): ''' Given a function name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_lambda.describe_function myf...
[ "def", "describe_function", "(", "FunctionName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "func", "=", "_find_function", "(", "FunctionName", ",", "region", "=", ...
33.592593
0.002144
def get_materialized_checkpoints(checkpoints, colnames, lower_dt, odo_kwargs): """ Computes a lower bound and a DataFrame checkpoints. Parameters ---------- checkpoints : Expr Bound blaze expression for a checkpoints table from which to get a computed lower bound. colnames : ite...
[ "def", "get_materialized_checkpoints", "(", "checkpoints", ",", "colnames", ",", "lower_dt", ",", "odo_kwargs", ")", ":", "if", "checkpoints", "is", "not", "None", ":", "ts", "=", "checkpoints", "[", "TS_FIELD_NAME", "]", "checkpoints_ts", "=", "odo", "(", "ts...
36.375
0.000669
def ip_address_subnet(self): """ IP Address/subnet """ return "{}/{}".format( self.interface.ip.compressed, self.interface.exploded.split("/")[-1] )
[ "def", "ip_address_subnet", "(", "self", ")", ":", "return", "\"{}/{}\"", ".", "format", "(", "self", ".", "interface", ".", "ip", ".", "compressed", ",", "self", ".", "interface", ".", "exploded", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", ...
27.714286
0.015
def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whit...
[ "def", "fill", "(", "text", ",", "width", "=", "70", ",", "*", "*", "kwargs", ")", ":", "w", "=", "TextWrapper", "(", "width", "=", "width", ",", "*", "*", "kwargs", ")", "return", "w", ".", "fill", "(", "text", ")" ]
46.272727
0.001927
def render_pulp_tag(self): """ Configure the pulp_tag plugin. """ if not self.dj.dock_json_has_plugin_conf('postbuild_plugins', 'pulp_tag'): return pulp_registry = self.spec.pulp_registry.value if pulp_registry...
[ "def", "render_pulp_tag", "(", "self", ")", ":", "if", "not", "self", ".", "dj", ".", "dock_json_has_plugin_conf", "(", "'postbuild_plugins'", ",", "'pulp_tag'", ")", ":", "return", "pulp_registry", "=", "self", ".", "spec", ".", "pulp_registry", ".", "value",...
46.461538
0.001622
def get_nuclearity_type(child_types): """Returns the nuclearity type of an RST relation (i.e. 'multinuc', 'nucsat' or 'multisat') or 'edu' if the node is below the relation level. """ if 'text' in child_types and len(child_types) == 1: return NucType.edu assert 'nucleus' in child_types,...
[ "def", "get_nuclearity_type", "(", "child_types", ")", ":", "if", "'text'", "in", "child_types", "and", "len", "(", "child_types", ")", "==", "1", ":", "return", "NucType", ".", "edu", "assert", "'nucleus'", "in", "child_types", ",", "\"This is not a relational ...
35
0.001264
def parsedata(self, packet): '''parse the data section of a packet, it can range from 0 to many bytes''' data = [] datalength = ord(packet[3]) position = 4 while position < datalength + 4: data.append(packet[position]) position += 1 return data
[ "def", "parsedata", "(", "self", ",", "packet", ")", ":", "data", "=", "[", "]", "datalength", "=", "ord", "(", "packet", "[", "3", "]", ")", "position", "=", "4", "while", "position", "<", "datalength", "+", "4", ":", "data", ".", "append", "(", ...
34.222222
0.009494
def render(self, template=None): """Render the plot using a template. Once the plot is complete, it needs to be rendered. Artist uses the Jinja2 templating engine. The default template results in a LaTeX file which can be included in your document. :param template: a user-sup...
[ "def", "render", "(", "self", ",", "template", "=", "None", ")", ":", "if", "not", "template", ":", "template", "=", "self", ".", "template", "self", ".", "_prepare_data", "(", ")", "response", "=", "template", ".", "render", "(", "axis_background", "=",...
33.073171
0.001433
def assign_job_record(self, tree_node): """ - looks for an existing job record in the DB, and if not found - creates a job record in STATE_EMBRYO and bind it to the given tree node """ try: job_record = self.job_dao.get_one(tree_node.process_name, tree_node.timeperiod) ex...
[ "def", "assign_job_record", "(", "self", ",", "tree_node", ")", ":", "try", ":", "job_record", "=", "self", ".", "job_dao", ".", "get_one", "(", "tree_node", ".", "process_name", ",", "tree_node", ".", "timeperiod", ")", "except", "LookupError", ":", "state_...
63.4
0.009331
def subontology(self, minimal=False): """ Generates a sub-ontology based on associations """ return self.ontology.subontology(self.objects, minimal=minimal)
[ "def", "subontology", "(", "self", ",", "minimal", "=", "False", ")", ":", "return", "self", ".", "ontology", ".", "subontology", "(", "self", ".", "objects", ",", "minimal", "=", "minimal", ")" ]
36.8
0.010638
def docify(self, df): """ Convert a Pandas DataFrame to SON. Parameters ---------- df: DataFrame The Pandas DataFrame to encode """ dtypes = {} masks = {} lengths = {} columns = [] data = Binary(b'') start = 0 ...
[ "def", "docify", "(", "self", ",", "df", ")", ":", "dtypes", "=", "{", "}", "masks", "=", "{", "}", "lengths", "=", "{", "}", "columns", "=", "[", "]", "data", "=", "Binary", "(", "b''", ")", "start", "=", "0", "arrays", "=", "[", "]", "for",...
28.956522
0.001452
def napalm_get( task: Task, getters: List[str], getters_options: GetterOptionsDict = None, **kwargs: Any ) -> Result: """ Gather information from network devices using napalm Arguments: getters: getters to use getters_options (dict of dicts): When passing multiple getters yo...
[ "def", "napalm_get", "(", "task", ":", "Task", ",", "getters", ":", "List", "[", "str", "]", ",", "getters_options", ":", "GetterOptionsDict", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Result", ":", "device", "=", "task", ".", "ho...
30.703704
0.000584
def connect_bitcoind_impl( bitcoind_opts ): """ Create a connection to bitcoind, using a dict of config options. """ if 'bitcoind_port' not in bitcoind_opts.keys() or bitcoind_opts['bitcoind_port'] is None: log.error("No port given") raise ValueError("No RPC port given (bitcoind_port)")...
[ "def", "connect_bitcoind_impl", "(", "bitcoind_opts", ")", ":", "if", "'bitcoind_port'", "not", "in", "bitcoind_opts", ".", "keys", "(", ")", "or", "bitcoind_opts", "[", "'bitcoind_port'", "]", "is", "None", ":", "log", ".", "error", "(", "\"No port given\"", ...
41.142857
0.012723
def make_wheelfile_inner(base_name, base_dir='.'): """Create a whl file from all the files under 'base_dir'. Places .dist-info at the end of the archive.""" zip_filename = base_name + ".whl" log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) # XXX support bz2, xz when availa...
[ "def", "make_wheelfile_inner", "(", "base_name", ",", "base_dir", "=", "'.'", ")", ":", "zip_filename", "=", "base_name", "+", "\".whl\"", "log", ".", "info", "(", "\"creating '%s' and adding '%s' to it\"", ",", "zip_filename", ",", "base_dir", ")", "# XXX support b...
28.621622
0.000913
def container_config_delete(name, config_key, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Delete a container config value name : Name of the container config_key : The config key to delete remote_addr : An URL to a remote Serve...
[ "def", "container_config_delete", "(", "name", ",", "config_key", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "verify_cert", "=", "True", ")", ":", "container", "=", "container_get", "(", "name", ",", "remote_ad...
24.511628
0.000912
def read_uic4tag(fh, byteorder, dtype, planecount, offsetsize): """Read MetaMorph STK UIC4Tag from file and return as dict.""" assert dtype == '1I' and byteorder == '<' result = {} while True: tagid = struct.unpack('<H', fh.read(2))[0] if tagid == 0: break name, value...
[ "def", "read_uic4tag", "(", "fh", ",", "byteorder", ",", "dtype", ",", "planecount", ",", "offsetsize", ")", ":", "assert", "dtype", "==", "'1I'", "and", "byteorder", "==", "'<'", "result", "=", "{", "}", "while", "True", ":", "tagid", "=", "struct", "...
37.181818
0.002387
def upload_directory( self, path, source=None, description=None, related_article=None, published_url=None, access='private', project=None, data=None, secure=False, force_ocr=False ): """ Uploads all the PDFs in the provided directory. Example usage: >> d...
[ "def", "upload_directory", "(", "self", ",", "path", ",", "source", "=", "None", ",", "description", "=", "None", ",", "related_article", "=", "None", ",", "published_url", "=", "None", ",", "access", "=", "'private'", ",", "project", "=", "None", ",", "...
35.944444
0.002257
def define_logging_options(options: Any = None) -> None: """Add logging-related flags to ``options``. These options are present automatically on the default options instance; this method is only necessary if you have created your own `.OptionParser`. .. versionadded:: 4.2 This function existed...
[ "def", "define_logging_options", "(", "options", ":", "Any", "=", "None", ")", "->", "None", ":", "if", "options", "is", "None", ":", "# late import to prevent cycle", "import", "tornado", ".", "options", "options", "=", "tornado", ".", "options", ".", "option...
28.860759
0.001272
def get_monoprice(port_url): """ Return synchronous version of Monoprice interface :param port_url: serial port, i.e. '/dev/ttyUSB0' :return: synchronous implementation of Monoprice interface """ lock = RLock() def synchronized(func): @wraps(func) def wrapper(*args, **kwarg...
[ "def", "get_monoprice", "(", "port_url", ")", ":", "lock", "=", "RLock", "(", ")", "def", "synchronized", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "lock", ...
37.05102
0.001341
def get_pre_auth_url_m(self, redirect_uri): """ 快速获取pre auth url,可以直接微信中发送该链接,直接授权 """ url = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=3&no_scan=1&" redirect_uri = quote(redirect_uri, safe='') return "{0}component_appid={1}&pre_auth_code=...
[ "def", "get_pre_auth_url_m", "(", "self", ",", "redirect_uri", ")", ":", "url", "=", "\"https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=3&no_scan=1&\"", "redirect_uri", "=", "quote", "(", "redirect_uri", ",", "safe", "=", "''", ")", "return", "\...
49.666667
0.010989
def find_data(self, subject_ids=None, visit_ids=None, **kwargs): """ Find all data within a repository, registering filesets, fields and provenance with the found_fileset, found_field and found_provenance methods, respectively Parameters ---------- subject_ids : ...
[ "def", "find_data", "(", "self", ",", "subject_ids", "=", "None", ",", "visit_ids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "all_filesets", "=", "[", "]", "all_fields", "=", "[", "]", "all_records", "=", "[", "]", "for", "session_path", ",", ...
44.227723
0.000438
def mechanism(self): """tuple[int]: The nodes of the mechanism in the partition.""" return tuple(sorted( chain.from_iterable(part.mechanism for part in self)))
[ "def", "mechanism", "(", "self", ")", ":", "return", "tuple", "(", "sorted", "(", "chain", ".", "from_iterable", "(", "part", ".", "mechanism", "for", "part", "in", "self", ")", ")", ")" ]
46
0.010695
def worker_recover(name, workers=None, profile='default'): ''' Recover all the workers in the modjk load balancer Example: .. code-block:: yaml loadbalancer: modjk.worker_recover: - workers: - app1 - app2 ''' if workers is None: ...
[ "def", "worker_recover", "(", "name", ",", "workers", "=", "None", ",", "profile", "=", "'default'", ")", ":", "if", "workers", "is", "None", ":", "workers", "=", "[", "]", "return", "_bulk_state", "(", "'modjk.bulk_recover'", ",", "name", ",", "workers", ...
21
0.002398
def pkcs7_pad(inp, block_size): """ Using the PKCS#7 padding scheme, pad <inp> to be a multiple of <block_size> bytes. Ruby's AES encryption pads with this scheme, but pycrypto doesn't support it. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/dia...
[ "def", "pkcs7_pad", "(", "inp", ",", "block_size", ")", ":", "val", "=", "block_size", "-", "len", "(", "inp", ")", "%", "block_size", "if", "val", "==", "0", ":", "return", "inp", "+", "(", "bytes", "(", "[", "block_size", "]", ")", "*", "block_si...
36.214286
0.001923
def cli(env, columns, sortby, volume_id): """List suitable replication datacenters for the given volume.""" file_storage_manager = SoftLayer.FileStorageManager(env.client) legal_centers = file_storage_manager.get_replication_locations( volume_id ) if not legal_centers: click.echo("...
[ "def", "cli", "(", "env", ",", "columns", ",", "sortby", ",", "volume_id", ")", ":", "file_storage_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "legal_centers", "=", "file_storage_manager", ".", "get_replication_locations"...
35.388889
0.001529
def extern_store_tuple(self, context_handle, vals_ptr, vals_len): """Given storage and an array of Handles, return a new Handle to represent the list.""" c = self._ffi.from_handle(context_handle) return c.to_value(tuple(c.from_value(val[0]) for val in self._ffi.unpack(vals_ptr, vals_len)))
[ "def", "extern_store_tuple", "(", "self", ",", "context_handle", ",", "vals_ptr", ",", "vals_len", ")", ":", "c", "=", "self", ".", "_ffi", ".", "from_handle", "(", "context_handle", ")", "return", "c", ".", "to_value", "(", "tuple", "(", "c", ".", "from...
74.75
0.009934
def get(self, key, **ctx_options): """Return a Model instance given the entity key. It will use the context cache if the cache policy for the given key is enabled. Args: key: Key instance. **ctx_options: Context options. Returns: A Model instance if the key exists in the datasto...
[ "def", "get", "(", "self", ",", "key", ",", "*", "*", "ctx_options", ")", ":", "options", "=", "_make_ctx_options", "(", "ctx_options", ")", "use_cache", "=", "self", ".", "_use_cache", "(", "key", ",", "options", ")", "if", "use_cache", ":", "self", "...
40.5
0.008787
def exec_command(self, cmd, in_data='', sudoable=True, mitogen_chdir=None): """ Implement exec_command() by calling the corresponding ansible_mitogen.target function in the target. :param str cmd: Shell command to execute. :param bytes in_data: Data to su...
[ "def", "exec_command", "(", "self", ",", "cmd", ",", "in_data", "=", "''", ",", "sudoable", "=", "True", ",", "mitogen_chdir", "=", "None", ")", ":", "emulate_tty", "=", "(", "not", "in_data", "and", "sudoable", ")", "rc", ",", "stdout", ",", "stderr",...
37.076923
0.002022
def separation(self,ra,dec): """Compute the separation between self and (ra,dec)""" import ephem return ephem.separation((self.ra,self.dec),(ra,dec))
[ "def", "separation", "(", "self", ",", "ra", ",", "dec", ")", ":", "import", "ephem", "return", "ephem", ".", "separation", "(", "(", "self", ".", "ra", ",", "self", ".", "dec", ")", ",", "(", "ra", ",", "dec", ")", ")" ]
34
0.04023
def _ecg_band_pass_filter(data, sample_rate): """ Bandpass filter with a bandpass setting of 5 to 15 Hz ---------- Parameters ---------- data : list List with the ECG signal samples. sample_rate : int Sampling rate at which the acquisition took place. Returns ------...
[ "def", "_ecg_band_pass_filter", "(", "data", ",", "sample_rate", ")", ":", "nyquist_sample_rate", "=", "sample_rate", "/", "2.", "normalized_cut_offs", "=", "[", "5", "/", "nyquist_sample_rate", ",", "15", "/", "nyquist_sample_rate", "]", "b_coeff", ",", "a_coeff"...
28.47619
0.001618
def plot_data(self, proj, ax): """ Creates and plots the contourplot of the original data. This is done by evaluating the density of projected datapoints on a grid. """ x, y = proj x_data = self.ig.independent_data[x] y_data = self.ig.dependent_data[y] pro...
[ "def", "plot_data", "(", "self", ",", "proj", ",", "ax", ")", ":", "x", ",", "y", "=", "proj", "x_data", "=", "self", ".", "ig", ".", "independent_data", "[", "x", "]", "y_data", "=", "self", ".", "ig", ".", "dependent_data", "[", "y", "]", "proj...
37.76
0.002066
def isin(self, column, compare_list): """ Returns a boolean list where each elements is whether that element in the column is in the compare_list. :param column: single column name, does not work for multiple columns :param compare_list: list of items to compare to :return: list...
[ "def", "isin", "(", "self", ",", "column", ",", "compare_list", ")", ":", "return", "[", "x", "in", "compare_list", "for", "x", "in", "self", ".", "_data", "[", "self", ".", "_columns", ".", "index", "(", "column", ")", "]", "]" ]
46.666667
0.009346
def epsilon_lexicase(self, F, sizes, num_selections=None, survival = False): """conducts epsilon lexicase selection for de-aggregated fitness vectors""" # pdb.set_trace() if num_selections is None: num_selections = F.shape[0] if self.c: # use c library # defi...
[ "def", "epsilon_lexicase", "(", "self", ",", "F", ",", "sizes", ",", "num_selections", "=", "None", ",", "survival", "=", "False", ")", ":", "# pdb.set_trace()", "if", "num_selections", "is", "None", ":", "num_selections", "=", "F", ".", "shape", "[", "0",...
47.44186
0.01537
def distutils_autosemver_case( metadata, with_release_notes=False, with_authors=True, with_changelog=True, bugtracker_url=None, ): """ :param metadata: distutils metadata object. :param with_release_notes: if true, will create the release notes. :type with_release_notes: bool :param with_aut...
[ "def", "distutils_autosemver_case", "(", "metadata", ",", "with_release_notes", "=", "False", ",", "with_authors", "=", "True", ",", "with_changelog", "=", "True", ",", "bugtracker_url", "=", "None", ",", ")", ":", "metadata", ".", "version", "=", "pkg_version",...
30.103448
0.00111
def reflection_matrix(point, normal): """Return matrix to mirror at plane defined by point and normal vector. >>> v0 = np.random.random(4) - 0.5 >>> v0[3] = 1. >>> v1 = np.random.random(3) - 0.5 >>> R = reflection_matrix(v0, v1) >>> np.allclose(2, np.trace(R)) True >>> np.allclose(v0, n...
[ "def", "reflection_matrix", "(", "point", ",", "normal", ")", ":", "normal", "=", "unit_vector", "(", "normal", "[", ":", "3", "]", ")", "M", "=", "np", ".", "identity", "(", "4", ")", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "2.0", "*", ...
26.791667
0.001502
def download(download_info): """Module method for downloading from S3 This public module method takes a key and the full path to the destination directory, assumes that the args have been validated by the public caller methods, and attempts to download the specified key to the dest_dir. :para...
[ "def", "download", "(", "download_info", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.download'", ")", "# Ensure the passed arg is a dict", "if", "not", "isinstance", "(", "download_info", ",", "dict", ")", ":", "msg", "=", "'d...
39.885714
0.002097
def set_implicitly_wait(self): """Read implicitly timeout from configuration properties and configure driver implicitly wait""" implicitly_wait = self.driver_wrapper.config.get_optional('Driver', 'implicitly_wait') if implicitly_wait: self.driver_wrapper.driver.implicitly_wait(implic...
[ "def", "set_implicitly_wait", "(", "self", ")", ":", "implicitly_wait", "=", "self", ".", "driver_wrapper", ".", "config", ".", "get_optional", "(", "'Driver'", ",", "'implicitly_wait'", ")", "if", "implicitly_wait", ":", "self", ".", "driver_wrapper", ".", "dri...
65.2
0.012121
def header(header_text: str, level: int = 1, expand_full: bool = False): """ Adds a text header to the display with the specified level. :param header_text: The text to display in the header. :param level: The level of the header, which corresponds to the html header levels, suc...
[ "def", "header", "(", "header_text", ":", "str", ",", "level", ":", "int", "=", "1", ",", "expand_full", ":", "bool", "=", "False", ")", ":", "r", "=", "_get_report", "(", ")", "r", ".", "append_body", "(", "render", ".", "header", "(", "header_text"...
35.8
0.001361
def get_dependent_items(self, item) -> typing.List: """Return the list of data items containing data that directly depends on data in this item.""" with self.__dependency_tree_lock: return copy.copy(self.__dependency_tree_source_to_target_map.get(weakref.ref(item), list()))
[ "def", "get_dependent_items", "(", "self", ",", "item", ")", "->", "typing", ".", "List", ":", "with", "self", ".", "__dependency_tree_lock", ":", "return", "copy", ".", "copy", "(", "self", ".", "__dependency_tree_source_to_target_map", ".", "get", "(", "weak...
74.75
0.013245
def decorate(self, pos, widget, is_first=True): """ builds a list element for given position in the tree. It consists of the original widget taken from the Tree and some decoration columns depending on the existence of parent and sibling positions. The result is a urwid.Columns w...
[ "def", "decorate", "(", "self", ",", "pos", ",", "widget", ",", "is_first", "=", "True", ")", ":", "line", "=", "None", "if", "pos", "is", "not", "None", ":", "original_widget", "=", "widget", "cols", "=", "self", ".", "_construct_spacer", "(", "pos", ...
48.159091
0.000925
def _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships o...
[ "def", "_get_relationships", "(", "model", ")", ":", "relationships", "=", "[", "]", "for", "name", ",", "relationship", "in", "inspect", "(", "model", ")", ".", "relationships", ".", "items", "(", ")", ":", "class_", "=", "relationship", ".", "mapper", ...
37.789474
0.001359
def reinterptet_harray_to_bits(typeFrom, sigOrVal, bitsT): """ Cast HArray signal or value to signal or value of type Bits """ size = int(typeFrom.size) widthOfElm = typeFrom.elmType.bit_length() w = bitsT.bit_length() if size * widthOfElm != w: raise TypeConversionErr( "...
[ "def", "reinterptet_harray_to_bits", "(", "typeFrom", ",", "sigOrVal", ",", "bitsT", ")", ":", "size", "=", "int", "(", "typeFrom", ".", "size", ")", "widthOfElm", "=", "typeFrom", ".", "elmType", ".", "bit_length", "(", ")", "w", "=", "bitsT", ".", "bit...
33.8
0.001919
def make_public(self, container, ttl=None): """ Enables CDN access for the specified container, and optionally sets the TTL for the container. """ return self._set_cdn_access(container, public=True, ttl=ttl)
[ "def", "make_public", "(", "self", ",", "container", ",", "ttl", "=", "None", ")", ":", "return", "self", ".", "_set_cdn_access", "(", "container", ",", "public", "=", "True", ",", "ttl", "=", "ttl", ")" ]
40.333333
0.008097