text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def deactivateAaPdpContextAccept(): """DEACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.14""" a = TpPd(pd=0x8) b = MessageType(mesType=0x54) # 01010100 packet = a / b return packet
[ "def", "deactivateAaPdpContextAccept", "(", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x8", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x54", ")", "# 01010100", "packet", "=", "a", "/", "b", "return", "packet" ]
32
12.5
def transform_help_end(line): """Translate lines with ?/?? at the end""" m = _help_end_re.search(line) if m is None or has_comment(line): return line target = m.group(1) esc = m.group(3) lspace = _initial_space_re.match(line).group(0) # If we're mid-command, put it back on the n...
[ "def", "transform_help_end", "(", "line", ")", ":", "m", "=", "_help_end_re", ".", "search", "(", "line", ")", "if", "m", "is", "None", "or", "has_comment", "(", "line", ")", ":", "return", "line", "target", "=", "m", ".", "group", "(", "1", ")", "...
36.538462
18.538462
def union(self, other, *, ignore_strand=False): """ Union of two intervals :param GenomicInterval other: interval to union with :return: union of two intervals íf overlapping or touching :rtype: GenomicInterval """ if not ignore_strand: self._assert_sa...
[ "def", "union", "(", "self", ",", "other", ",", "*", ",", "ignore_strand", "=", "False", ")", ":", "if", "not", "ignore_strand", ":", "self", ".", "_assert_same_chromosome_and_strand", "(", "other", ")", "interval", "=", "deepcopy", "(", "self", ")", "inte...
36.25
10.75
def _discover_sensitivity_seq(self, signals: List[RtlSignalBase], seen: set, ctx: SensitivityCtx)\ -> None: """ Discover sensitivity for list of signals """ casualSensitivity = set() for s in signals...
[ "def", "_discover_sensitivity_seq", "(", "self", ",", "signals", ":", "List", "[", "RtlSignalBase", "]", ",", "seen", ":", "set", ",", "ctx", ":", "SensitivityCtx", ")", "->", "None", ":", "casualSensitivity", "=", "set", "(", ")", "for", "s", "in", "sig...
34.941176
15.529412
def tpeak(self, wavelengths=None): """Calculate :ref:`peak bandpass throughput <synphot-formula-tpeak>`. Parameters ---------- wavelengths : array-like, `~astropy.units.quantity.Quantity`, or `None` Wavelength values for sampling. If not a Quantity, assumed to be...
[ "def", "tpeak", "(", "self", ",", "wavelengths", "=", "None", ")", ":", "x", "=", "self", ".", "_validate_wavelengths", "(", "wavelengths", ")", ".", "value", "return", "self", "(", "x", ")", ".", "max", "(", ")" ]
32.611111
18.277778
def skydir(self): """Return a SkyCoord representation of the source position. Returns ------- skydir : `~astropy.coordinates.SkyCoord` """ return SkyCoord(self.radec[0] * u.deg, self.radec[1] * u.deg)
[ "def", "skydir", "(", "self", ")", ":", "return", "SkyCoord", "(", "self", ".", "radec", "[", "0", "]", "*", "u", ".", "deg", ",", "self", ".", "radec", "[", "1", "]", "*", "u", ".", "deg", ")" ]
30.375
18.875
def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]: """Get jobs from a queue.""" jobs_json_string = self._run_script( self._get_jobs_from_queue, self._to_namespaced(queue), self._to_namespaced(RUNNING_JOBS_KEY.format(self._id)), JobStatu...
[ "def", "get_jobs_from_queue", "(", "self", ",", "queue", ":", "str", ",", "max_jobs", ":", "int", ")", "->", "List", "[", "Job", "]", ":", "jobs_json_string", "=", "self", ".", "_run_script", "(", "self", ".", "_get_jobs_from_queue", ",", "self", ".", "_...
34.5
17.5
def _item_exists_in_bucket(self, bucket, key, checksums): """ Returns true if the key already exists in the current bucket and the clientside checksum matches the file's checksums, and false otherwise.""" try: obj = self.target_s3.meta.client.head_object(Bucket=bucket, Key=key) ...
[ "def", "_item_exists_in_bucket", "(", "self", ",", "bucket", ",", "key", ",", "checksums", ")", ":", "try", ":", "obj", "=", "self", ".", "target_s3", ".", "meta", ".", "client", ".", "head_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key",...
53.666667
18.25
def k(self): """ Driving force term: :math:`r'' = -k \\left( \\frac{1-e^{-r^2/2{\\sigma_r}^2}}{r} \\right)` """ try: return self._k except AttributeError: self._k = e**2 * self.N_e / ( (2*_np.pi)**(5/2) * e0 * self.m * c**2 * self.sig_xi) retur...
[ "def", "k", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_k", "except", "AttributeError", ":", "self", ".", "_k", "=", "e", "**", "2", "*", "self", ".", "N_e", "/", "(", "(", "2", "*", "_np", ".", "pi", ")", "**", "(", "5", "/...
35.666667
23
def delete(self, loc): """ Make new index with passed location deleted Returns ------- new_index : MultiIndex """ new_codes = [np.delete(level_codes, loc) for level_codes in self.codes] return MultiIndex(levels=self.levels, codes=new_codes, ...
[ "def", "delete", "(", "self", ",", "loc", ")", ":", "new_codes", "=", "[", "np", ".", "delete", "(", "level_codes", ",", "loc", ")", "for", "level_codes", "in", "self", ".", "codes", "]", "return", "MultiIndex", "(", "levels", "=", "self", ".", "leve...
33
19.727273
def _canvas_route(self, *args, **kwargs): """ Decorator for canvas route """ def outer(view_fn): @self.route(*args, **kwargs) def inner(*args, **kwargs): fn_args = getargspec(view_fn) try: idx = fn_args.args.index(_ARG_KEY) except ValueErr...
[ "def", "_canvas_route", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "outer", "(", "view_fn", ")", ":", "@", "self", ".", "route", "(", "*", "args", ",", "*", "*", "kwargs", ")", "def", "inner", "(", "*", "args", ","...
36.489362
18.659574
def setSenderKeyState(self, id, iteration, chainKey, signatureKey): """ :type id: int :type iteration: int :type chainKey: bytearray :type signatureKey: ECKeyPair """ del self.senderKeyStates[:] self.senderKeyStates.append(SenderKeyState(id, iteration, cha...
[ "def", "setSenderKeyState", "(", "self", ",", "id", ",", "iteration", ",", "chainKey", ",", "signatureKey", ")", ":", "del", "self", ".", "senderKeyStates", "[", ":", "]", "self", ".", "senderKeyStates", ".", "append", "(", "SenderKeyState", "(", "id", ","...
38.888889
15.555556
def _netinfo_freebsd_netbsd(): ''' Get process information for network connections using sockstat ''' ret = {} # NetBSD requires '-n' to disable port-to-service resolution out = __salt__['cmd.run']( 'sockstat -46 {0} | tail -n+2'.format( '-n' if __grains__['kernel'] == 'NetBS...
[ "def", "_netinfo_freebsd_netbsd", "(", ")", ":", "ret", "=", "{", "}", "# NetBSD requires '-n' to disable port-to-service resolution", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'sockstat -46 {0} | tail -n+2'", ".", "format", "(", "'-n'", "if", "__grains__", ...
38.363636
17.636364
def _instantiate_remote_sources(self, kwargs): """For RemoteSources target, convert "dest" field to its real target type.""" kwargs['dest'] = _DestWrapper((self._target_types[kwargs['dest']],)) return RemoteSources(build_graph=self, **kwargs)
[ "def", "_instantiate_remote_sources", "(", "self", ",", "kwargs", ")", ":", "kwargs", "[", "'dest'", "]", "=", "_DestWrapper", "(", "(", "self", ".", "_target_types", "[", "kwargs", "[", "'dest'", "]", "]", ",", ")", ")", "return", "RemoteSources", "(", ...
62.75
12.5
def rhochange(self): """Action to be taken when rho parameter is changed.""" self.Gamma = 1.0 / (1.0 + (self.lmbda/self.rho)*(self.Alpha**2))
[ "def", "rhochange", "(", "self", ")", ":", "self", ".", "Gamma", "=", "1.0", "/", "(", "1.0", "+", "(", "self", ".", "lmbda", "/", "self", ".", "rho", ")", "*", "(", "self", ".", "Alpha", "**", "2", ")", ")" ]
38.75
23
def accuracy(y_true: [list, np.ndarray], y_predicted: [list, np.ndarray]) -> float: """ Calculate accuracy in terms of absolute coincidence Args: y_true: array of true values y_predicted: array of predicted values Returns: portion of absolutely coincidental samples """ ...
[ "def", "accuracy", "(", "y_true", ":", "[", "list", ",", "np", ".", "ndarray", "]", ",", "y_predicted", ":", "[", "list", ",", "np", ".", "ndarray", "]", ")", "->", "float", ":", "examples_len", "=", "len", "(", "y_true", ")", "correct", "=", "sum"...
32.785714
19.357143
def is_distinct(self): """True if results are guaranteed to contain a unique set of property values. This happens when every property in the group_by is also in the projection. """ return bool(self.__group_by and set(self._to_property_names(self.__group_by)) <= set(s...
[ "def", "is_distinct", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "__group_by", "and", "set", "(", "self", ".", "_to_property_names", "(", "self", ".", "__group_by", ")", ")", "<=", "set", "(", "self", ".", "_to_property_names", "(", "self...
39.444444
19.888889
def _iterate_uniqueness_keys(self, field): """Iterates over the keys marked as "unique" in the specified field. Arguments: field: The field of which key's to iterate over. """ uniqueness = getattr(field, 'uniqueness', None) if...
[ "def", "_iterate_uniqueness_keys", "(", "self", ",", "field", ")", ":", "uniqueness", "=", "getattr", "(", "field", ",", "'uniqueness'", ",", "None", ")", "if", "not", "uniqueness", ":", "return", "for", "keys", "in", "uniqueness", ":", "composed_keys", "=",...
26.882353
15.882353
def _start_process(self, classpath): """Given a classpath prepared for running ENSIME, spawns a server process in a way that is otherwise agnostic to how the strategy installs ENSIME. Args: classpath (list of str): list of paths to jars or directories (Within this functi...
[ "def", "_start_process", "(", "self", ",", "classpath", ")", ":", "cache_dir", "=", "self", ".", "config", "[", "'cache-dir'", "]", "java_flags", "=", "self", ".", "config", "[", "'java-flags'", "]", "iswindows", "=", "os", ".", "name", "==", "'nt'", "Ut...
39.125
20.333333
def create_channel(cls, address="firestore.googleapis.com:443", credentials=None): """Create and return a gRPC channel object. Args: address (str): The host for the channel to use. credentials (~.Credentials): The authorization credentials to attach to requests. ...
[ "def", "create_channel", "(", "cls", ",", "address", "=", "\"firestore.googleapis.com:443\"", ",", "credentials", "=", "None", ")", ":", "return", "google", ".", "api_core", ".", "grpc_helpers", ".", "create_channel", "(", "address", ",", "credentials", "=", "cr...
42.882353
23
def channel_angle(im, chanapproxangle=None, *, isshiftdftedge=False, truesize=None): """Extract the channel angle from the rfft Parameters: ----------- im: 2d array The channel image chanapproxangle: number, optional If not None, an approximation of the result ...
[ "def", "channel_angle", "(", "im", ",", "chanapproxangle", "=", "None", ",", "*", ",", "isshiftdftedge", "=", "False", ",", "truesize", "=", "None", ")", ":", "im", "=", "np", ".", "asarray", "(", "im", ")", "# Compute edge", "if", "not", "isshiftdftedge...
28.833333
18.466667
def load_jam_audio(jam_in, audio_file, validate=True, strict=True, fmt='auto', **kwargs): '''Load a jam and pack it with audio. Parameters ---------- jam_in : str, file descriptor, or jams.JAMS JAMS filename, open file-...
[ "def", "load_jam_audio", "(", "jam_in", ",", "audio_file", ",", "validate", "=", "True", ",", "strict", "=", "True", ",", "fmt", "=", "'auto'", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "jam_in", ",", "jams", ".", "JAMS", ")", ":", ...
24.788462
23.557692
def _read_frame(self): """Read a frame from the XYZ file""" size = self.read_size() title = self._f.readline()[:-1] if self.symbols is None: symbols = [] coordinates = np.zeros((size, 3), float) for counter in range(size): line = self._f.readline(...
[ "def", "_read_frame", "(", "self", ")", ":", "size", "=", "self", ".", "read_size", "(", ")", "title", "=", "self", ".", "_f", ".", "readline", "(", ")", "[", ":", "-", "1", "]", "if", "self", ".", "symbols", "is", "None", ":", "symbols", "=", ...
34.740741
9.777778
def fcat(*fs): """Concatenate a sequence of farrays. The variadic *fs* input is a homogeneous sequence of functions or arrays. """ items = list() for f in fs: if isinstance(f, boolfunc.Function): items.append(f) elif isinstance(f, farray): items.extend(f.flat...
[ "def", "fcat", "(", "*", "fs", ")", ":", "items", "=", "list", "(", ")", "for", "f", "in", "fs", ":", "if", "isinstance", "(", "f", ",", "boolfunc", ".", "Function", ")", ":", "items", ".", "append", "(", "f", ")", "elif", "isinstance", "(", "f...
29
17.142857
def sentences(self): ''' Iterate over <s> XML-like tags and tokenize with nltk ''' for sentence_id, node in enumerate(self.ner_dom.childNodes): ## increment the char index with any text before the <s> ## tag. Crucial assumption here is that the LingPipe XML ...
[ "def", "sentences", "(", "self", ")", ":", "for", "sentence_id", ",", "node", "in", "enumerate", "(", "self", ".", "ner_dom", ".", "childNodes", ")", ":", "## increment the char index with any text before the <s>", "## tag. Crucial assumption here is that the LingPipe XML"...
46.409091
21.727273
def get_columns(model=None, fields=None, meta=None): """ Get model columns list """ if model: M = get_model(model) else: M = None if fields is not None: f = fields if M: if meta and hasattr(M, meta): m = getattr(model, meta) ...
[ "def", "get_columns", "(", "model", "=", "None", ",", "fields", "=", "None", ",", "meta", "=", "None", ")", ":", "if", "model", ":", "M", "=", "get_model", "(", "model", ")", "else", ":", "M", "=", "None", "if", "fields", "is", "not", "None", ":"...
26.95122
19.97561
def _validateParamsFor_validateChoice(choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, numbered=False, lettered=False, caseSensitive=False, excMsg=None): """Raises PySimpleValidateException if the arguments are invalid. This is called by the validateChoice() fun...
[ "def", "_validateParamsFor_validateChoice", "(", "choices", ",", "blank", "=", "False", ",", "strip", "=", "None", ",", "allowlistRegexes", "=", "None", ",", "blocklistRegexes", "=", "None", ",", "numbered", "=", "False", ",", "lettered", "=", "False", ",", ...
51.972222
33.194444
def local_response_norm(attrs, inputs, proto_obj): """Local Response Normalization.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'bias': 'knorm', 'size' : 'nsize'}) return 'LRN', n...
[ "def", "local_response_norm", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "new_attrs", "=", "translation_utils", ".", "_fix_attribute_names", "(", "attrs", ",", "{", "'bias'", ":", "'knorm'", ",", "'size'", ":", "'nsize'", "}", ")", "return", "'...
55.166667
17
async def remove(self, *instances, using_db=None) -> None: """ Removes one or more of ``instances`` from the relation. """ db = using_db if using_db else self.model._meta.db if not instances: raise OperationalError("remove() called on no instances") through_ta...
[ "async", "def", "remove", "(", "self", ",", "*", "instances", ",", "using_db", "=", "None", ")", "->", "None", ":", "db", "=", "using_db", "if", "using_db", "else", "self", ".", "model", ".", "_meta", ".", "db", "if", "not", "instances", ":", "raise"...
47.473684
25.789474
def cache(cache={}, maxmem=config.MAXIMUM_CACHE_MEMORY_PERCENTAGE, typed=False): """Memory-limited cache decorator. ``maxmem`` is a float between 0 and 100, inclusive, specifying the maximum percentage of physical memory that the cache can use. If ``typed`` is ``True``, arguments of differen...
[ "def", "cache", "(", "cache", "=", "{", "}", ",", "maxmem", "=", "config", ".", "MAXIMUM_CACHE_MEMORY_PERCENTAGE", ",", "typed", "=", "False", ")", ":", "# Constants shared by all lru cache instances:", "# Unique object used to signal cache misses.", "sentinel", "=", "o...
35.443038
17.265823
def insertBefore(self, child, beforeChild): ''' insertBefore - Inserts a child before #beforeChild @param child <AdvancedTag/str> - Child block to insert @param beforeChild <AdvancedTag/str> - Child block to insert before. if None, will be appended @r...
[ "def", "insertBefore", "(", "self", ",", "child", ",", "beforeChild", ")", ":", "# When the second arg is null/None, the node is appended. The argument is required per JS API, but null is acceptable..", "if", "beforeChild", "is", "None", ":", "return", "self", ".", "appendBlock...
40.3
30.45
def get_header(file,**kw): '''gets the header for the .p4 file, note that this Advanced the file position to the end of the header. Returns the size of the header, and the size of the header, if the header keyword is true. ''' if type(file) == str: #if called with a file...
[ "def", "get_header", "(", "file", ",", "*", "*", "kw", ")", ":", "if", "type", "(", "file", ")", "==", "str", ":", "#if called with a filename, recall with opened file.", "if", "test", "(", "kw", ",", "\"gzip\"", ")", "and", "kw", "[", "'gzip'", "]", "==...
37.25
15.477273
def getWorkingSeatedZeroPoseToRawTrackingPose(self): """Returns the preferred seated position from the working copy.""" fn = self.function_table.getWorkingSeatedZeroPoseToRawTrackingPose pmatSeatedZeroPoseToRawTrackingPose = HmdMatrix34_t() result = fn(byref(pmatSeatedZeroPoseToRawTrack...
[ "def", "getWorkingSeatedZeroPoseToRawTrackingPose", "(", "self", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getWorkingSeatedZeroPoseToRawTrackingPose", "pmatSeatedZeroPoseToRawTrackingPose", "=", "HmdMatrix34_t", "(", ")", "result", "=", "fn", "(", "byref",...
54.571429
21.142857
def action_checklist_report_extractor(impact_report, component_metadata): """Extracting action checklist of the impact layer to its own report. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.Imp...
[ "def", "action_checklist_report_extractor", "(", "impact_report", ",", "component_metadata", ")", ":", "context", "=", "{", "}", "extra_args", "=", "component_metadata", ".", "extra_args", "components_list", "=", "resolve_from_dictionary", "(", "extra_args", ",", "'comp...
34.53125
20.46875
async def widget(self): """|coro| Returns the widget of the guild. .. note:: The guild must have the widget enabled to get this information. Raises ------- Forbidden The widget for this guild is disabled. HTTPException Retri...
[ "async", "def", "widget", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "get_widget", "(", "self", ".", "id", ")", "return", "Widget", "(", "state", "=", "self", ".", "_state", ",", "data", "=", "data", ")" ]
22.25
21.75
def top_priority_effect_per_variant(self): """Highest priority effect for each unique variant""" return OrderedDict( (variant, top_priority_effect(variant_effects)) for (variant, variant_effects) in self.groupby_variant().items())
[ "def", "top_priority_effect_per_variant", "(", "self", ")", ":", "return", "OrderedDict", "(", "(", "variant", ",", "top_priority_effect", "(", "variant_effects", ")", ")", "for", "(", "variant", ",", "variant_effects", ")", "in", "self", ".", "groupby_variant", ...
46.166667
7
def aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth): """ Calculates the angle of incidence of the solar vector on a surface. This is the angle between the solar vector and the surface normal. Input all angles in degrees. Parameters ---------- surface_tilt : numeric ...
[ "def", "aoi", "(", "surface_tilt", ",", "surface_azimuth", ",", "solar_zenith", ",", "solar_azimuth", ")", ":", "projection", "=", "aoi_projection", "(", "surface_tilt", ",", "surface_azimuth", ",", "solar_zenith", ",", "solar_azimuth", ")", "aoi_value", "=", "np"...
25.235294
21.058824
def multi_index_to_frame(index): """ Replicates MultiIndex.to_frame, which was introduced in pandas 0.21, for the sake of backwards compatibility. """ return pandas.DataFrame(index.tolist(), index=index, columns=index.names)
[ "def", "multi_index_to_frame", "(", "index", ")", ":", "return", "pandas", ".", "DataFrame", "(", "index", ".", "tolist", "(", ")", ",", "index", "=", "index", ",", "columns", "=", "index", ".", "names", ")" ]
39.833333
13.5
def inside_brain(stat_dset,atlas=None,p=0.001): '''calculates the percentage of voxels above a statistical threshold inside a brain mask vs. outside it if ``atlas`` is ``None``, it will try to find ``TT_N27``''' atlas = find_atlas(atlas) if atlas==None: return None mask_dset = nl.suffix...
[ "def", "inside_brain", "(", "stat_dset", ",", "atlas", "=", "None", ",", "p", "=", "0.001", ")", ":", "atlas", "=", "find_atlas", "(", "atlas", ")", "if", "atlas", "==", "None", ":", "return", "None", "mask_dset", "=", "nl", ".", "suffix", "(", "stat...
61.818182
38
def load_cdx_for_dupe(self, url, timestamp, digest, cdx_loader): """ If a cdx_server is available, return response from server, otherwise empty list """ if not cdx_loader: return iter([]) filters = [] filters.append('!mime:warc/revisit') if ...
[ "def", "load_cdx_for_dupe", "(", "self", ",", "url", ",", "timestamp", ",", "digest", ",", "cdx_loader", ")", ":", "if", "not", "cdx_loader", ":", "return", "iter", "(", "[", "]", ")", "filters", "=", "[", "]", "filters", ".", "append", "(", "'!mime:wa...
25.95
17.15
def hash_algo(self): """ Returns the name of the family of hash algorithms used to generate a DSA key :raises: ValueError - when the key is not a DSA key :return: A unicode string of "sha1" or "sha2" or None if no parameters are present ...
[ "def", "hash_algo", "(", "self", ")", ":", "if", "self", ".", "algorithm", "!=", "'dsa'", ":", "raise", "ValueError", "(", "unwrap", "(", "'''\n Only DSA keys are generated using a hash algorithm, this key is\n %s\n '''", ",", "sel...
27.413793
22.103448
def fragment_fromstring(html, create_parent=False, guess_charset=False, parser=None): """Parses a single HTML element; it is an error if there is more than one element, or if anything but whitespace precedes or follows the element. If create_parent is true (or is a tag name) the...
[ "def", "fragment_fromstring", "(", "html", ",", "create_parent", "=", "False", ",", "guess_charset", "=", "False", ",", "parser", "=", "None", ")", ":", "if", "not", "isinstance", "(", "html", ",", "_strings", ")", ":", "raise", "TypeError", "(", "'string ...
36.102564
16.666667
def motif_from_consensus(cons, n=12): """Convert consensus sequence to motif. Converts a consensus sequences using the nucleotide IUPAC alphabet to a motif. Parameters ---------- cons : str Consensus sequence using the IUPAC alphabet. n : int , optional Count used to conv...
[ "def", "motif_from_consensus", "(", "cons", ",", "n", "=", "12", ")", ":", "width", "=", "len", "(", "cons", ")", "nucs", "=", "{", "\"A\"", ":", "0", ",", "\"C\"", ":", "1", ",", "\"G\"", ":", "2", ",", "\"T\"", ":", "3", "}", "pfm", "=", "[...
26.428571
19.571429
def is_processed(self, db_versions): """Check if version is already applied in the database. :param db_versions: """ return self.number in (v.number for v in db_versions if v.date_done)
[ "def", "is_processed", "(", "self", ",", "db_versions", ")", ":", "return", "self", ".", "number", "in", "(", "v", ".", "number", "for", "v", "in", "db_versions", "if", "v", ".", "date_done", ")" ]
35.5
15.5
def moments_of_masked_time_series(time_series_tensor, broadcast_mask): """Compute mean and variance, accounting for a mask. Args: time_series_tensor: float `Tensor` time series of shape `concat([batch_shape, [num_timesteps]])`. broadcast_mask: bool `Tensor` of the same shape as `time_series`. Retur...
[ "def", "moments_of_masked_time_series", "(", "time_series_tensor", ",", "broadcast_mask", ")", ":", "num_unmasked_entries", "=", "tf", ".", "cast", "(", "tf", ".", "reduce_sum", "(", "input_tensor", "=", "tf", ".", "cast", "(", "~", "broadcast_mask", ",", "tf", ...
39.653846
17.153846
def get_dir_relpath(base, relpath): """Returns the absolute path to the 'relpath' taken relative to the base directory. :arg base: the base directory to take the path relative to. :arg relpath: the path relative to 'base' in terms of '.' and '..'. """ from os import path xbase = path.abspat...
[ "def", "get_dir_relpath", "(", "base", ",", "relpath", ")", ":", "from", "os", "import", "path", "xbase", "=", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "base", ")", ")", "if", "not", "path", ".", "isdir", "(", "xbase", ")", ":", ...
30.666667
15.761905
def check_wlcalib_sp(sp, crpix1, crval1, cdelt1, wv_master, coeff_ini=None, naxis1_ini=None, min_nlines_to_refine=0, interactive=False, threshold=0, nwinwidth_initial=7, nwinwidth_refined=5, ...
[ "def", "check_wlcalib_sp", "(", "sp", ",", "crpix1", ",", "crval1", ",", "cdelt1", ",", "wv_master", ",", "coeff_ini", "=", "None", ",", "naxis1_ini", "=", "None", ",", "min_nlines_to_refine", "=", "0", ",", "interactive", "=", "False", ",", "threshold", "...
39.850622
15.883817
def deflate_and_encode(plantuml_text): """zlib compress the plantuml text and encode it for the plantuml server. """ zlibbed_str = zlib.compress(plantuml_text.encode('utf-8')) compressed_string = zlibbed_str[2:-4] return encode(compressed_string.decode('latin-1'))
[ "def", "deflate_and_encode", "(", "plantuml_text", ")", ":", "zlibbed_str", "=", "zlib", ".", "compress", "(", "plantuml_text", ".", "encode", "(", "'utf-8'", ")", ")", "compressed_string", "=", "zlibbed_str", "[", "2", ":", "-", "4", "]", "return", "encode"...
46.5
6.5
def fallback_to_default_project_id(func): """ Decorator that provides fallback for Google Cloud Platform project id. If the project is None it will be replaced with the project_id from the service account the Hook is authenticated with. Project id can be specified either via proj...
[ "def", "fallback_to_default_project_id", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "inner_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "0", ":", ...
50.038462
20.576923
def cmp_contents(filename1, filename2): """ Returns True if contents of the files are the same Parameters ---------- filename1 : str filename of first file to compare filename2 : str filename of second file to compare Returns ------- tf : bool True if binary con...
[ "def", "cmp_contents", "(", "filename1", ",", "filename2", ")", ":", "with", "open_readable", "(", "filename1", ",", "'rb'", ")", "as", "fobj", ":", "contents1", "=", "fobj", ".", "read", "(", ")", "with", "open_readable", "(", "filename2", ",", "'rb'", ...
28.190476
16.333333
def tracer(object): """ | Traces execution. | Any method / definition decorated will have it's execution traced. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) @functools.partial(validate_tracer, object) ...
[ "def", "tracer", "(", "object", ")", ":", "@", "functools", ".", "wraps", "(", "object", ")", "@", "functools", ".", "partial", "(", "validate_tracer", ",", "object", ")", "def", "tracer_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", ...
37.363636
21.136364
def get_revision(self, location): """ Return the maximum revision for all files under a given location """ # Note: taken from setuptools.command.egg_info revision = 0 for base, dirs, files in os.walk(location): if self.dirname not in dirs: dir...
[ "def", "get_revision", "(", "self", ",", "location", ")", ":", "# Note: taken from setuptools.command.egg_info", "revision", "=", "0", "for", "base", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "location", ")", ":", "if", "self", ".", "dirname",...
40.382979
16.808511
def submit(self, data, runtime_dir, argv): """Run process locally. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. """ logger.debug(__( "Connector '{}' running for Data with id {} ({}).", self.__class__.__mod...
[ "def", "submit", "(", "self", ",", "data", ",", "runtime_dir", ",", "argv", ")", ":", "logger", ".", "debug", "(", "__", "(", "\"Connector '{}' running for Data with id {} ({}).\"", ",", "self", ".", "__class__", ".", "__module__", ",", "data", ".", "id", ",...
28.941176
17.058824
def compounds(context, case_id): """ Update all compounds for a case """ adapter = context.obj['adapter'] LOG.info("Running scout update compounds") # Check if the case exists case_obj = adapter.case(case_id) if not case_obj: LOG.warning("Case %s could not be found", case_id...
[ "def", "compounds", "(", "context", ",", "case_id", ")", ":", "adapter", "=", "context", ".", "obj", "[", "'adapter'", "]", "LOG", ".", "info", "(", "\"Running scout update compounds\"", ")", "# Check if the case exists", "case_obj", "=", "adapter", ".", "case",...
26
13.777778
def ecp_pot_str(pot): '''Return a string representing the data for an ECP potential ''' am = pot['angular_momentum'] amchar = lut.amint_to_char(am) rexponents = pot['r_exponents'] gexponents = pot['gaussian_exponents'] coefficients = pot['coefficients'] point_places = [0, 10, 33] ...
[ "def", "ecp_pot_str", "(", "pot", ")", ":", "am", "=", "pot", "[", "'angular_momentum'", "]", "amchar", "=", "lut", ".", "amint_to_char", "(", "am", ")", "rexponents", "=", "pot", "[", "'r_exponents'", "]", "gexponents", "=", "pot", "[", "'gaussian_exponen...
30.4375
19.3125
def fallout(self): r"""Return fall-out. Fall-out is defined as :math:`\frac{fp}{fp + tn}` AKA false positive rate (FPR) Cf. https://en.wikipedia.org/wiki/Information_retrieval#Fall-out Returns ------- float The fall-out of the confusion table ...
[ "def", "fallout", "(", "self", ")", ":", "if", "self", ".", "_fp", "+", "self", ".", "_tn", "==", "0", ":", "return", "float", "(", "'NaN'", ")", "return", "self", ".", "_fp", "/", "(", "self", ".", "_fp", "+", "self", ".", "_tn", ")" ]
22.541667
21.666667
def get_extension_classes(): """ Hotdoc's setuptools entry point """ res = [SyntaxHighlightingExtension, SearchExtension, TagExtension, DevhelpExtension, LicenseExtension, GitUploadExtension, EditOnGitHubExtension] if sys.version_info[1] >= 5: res += [DBusExtension] ...
[ "def", "get_extension_classes", "(", ")", ":", "res", "=", "[", "SyntaxHighlightingExtension", ",", "SearchExtension", ",", "TagExtension", ",", "DevhelpExtension", ",", "LicenseExtension", ",", "GitUploadExtension", ",", "EditOnGitHubExtension", "]", "if", "sys", "."...
24.583333
21.25
def get(self, url): """Navigate to a specific url This specific implementation inject a javascript script to intercept the javascript error Configurable with the "proxy_driver:intercept_javascript_error" config Args: url (str): the url to navigate to R...
[ "def", "get", "(", "self", ",", "url", ")", ":", "self", ".", "_driver", ".", "get", "(", "url", ")", "if", "self", ".", "bot_diary", ":", "self", ".", "bot_diary", ".", "add_auto_entry", "(", "\"I went on\"", ",", "target", "=", "url", ",", "take_sc...
24.5
22.642857
def conv_layer(ni:int, nf:int, ks:int=3, stride:int=1, padding:int=None, bias:bool=None, is_1d:bool=False, norm_type:Optional[NormType]=NormType.Batch, use_activ:bool=True, leaky:float=None, transpose:bool=False, init:Callable=nn.init.kaiming_normal_, self_attention:bool=False): "Crea...
[ "def", "conv_layer", "(", "ni", ":", "int", ",", "nf", ":", "int", ",", "ks", ":", "int", "=", "3", ",", "stride", ":", "int", "=", "1", ",", "padding", ":", "int", "=", "None", ",", "bias", ":", "bool", "=", "None", ",", "is_1d", ":", "bool"...
71
35.25
def p_wait_statement(self, p): 'wait_statement : WAIT LPAREN cond RPAREN waitcontent_statement' p[0] = WaitStatement(p[3], p[5], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_wait_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "WaitStatement", "(", "p", "[", "3", "]", ",", "p", "[", "5", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", ...
49.5
16.5
def _reinit_daq_daemons(sender, instance, **kwargs): """ update the daq daemon configuration when changes be applied in the models """ if type(instance) is SMbusDevice: post_save.send_robust(sender=Device, instance=instance.smbus_device) elif type(instance) is SMbusVariable: post_sav...
[ "def", "_reinit_daq_daemons", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "instance", ")", "is", "SMbusDevice", ":", "post_save", ".", "send_robust", "(", "sender", "=", "Device", ",", "instance", "=", "instance", ...
54.583333
20.583333
def parse(type: Type): """ Register a parser for a attribute type. Parsers will be used to parse `str` type objects from either the commandline arguments or environment variables. Args: type: the type the decorated function will be responsible for pa...
[ "def", "parse", "(", "type", ":", "Type", ")", ":", "def", "decorator", "(", "parser", ")", ":", "EnvVar", ".", "parsers", "[", "type", "]", "=", "parser", "return", "parser", "return", "decorator" ]
27.882353
20.235294
def release(self, conn): """Returns used connection back into pool. When returned connection has db index that differs from one in pool the connection will be closed and dropped. When queue of free connections is full the connection will be dropped. """ assert conn in se...
[ "def", "release", "(", "self", ",", "conn", ")", ":", "assert", "conn", "in", "self", ".", "_used", ",", "(", "\"Invalid connection, maybe from other pool\"", ",", "conn", ")", "self", ".", "_used", ".", "remove", "(", "conn", ")", "if", "not", "conn", "...
41.272727
15.969697
def get_consensus_at(block_height, proxy=None, hostport=None): """ Get consensus at a block Returns the consensus hash on success Returns {'error': ...} on error """ assert proxy or hostport, 'Need either proxy or hostport' if proxy is None: proxy = connect_hostport(hostport) co...
[ "def", "get_consensus_at", "(", "block_height", ",", "proxy", "=", "None", ",", "hostport", "=", "None", ")", ":", "assert", "proxy", "or", "hostport", ",", "'Need either proxy or hostport'", "if", "proxy", "is", "None", ":", "proxy", "=", "connect_hostport", ...
31.205882
22.882353
def get_package_version(self, feed_id, package_id, package_version_id, project=None, include_urls=None, is_listed=None, is_deleted=None): """GetPackageVersion. [Preview API] Get details about a specific package version. :param str feed_id: Name or Id of the feed. :param str package_id: I...
[ "def", "get_package_version", "(", "self", ",", "feed_id", ",", "package_id", ",", "package_version_id", ",", "project", "=", "None", ",", "include_urls", "=", "None", ",", "is_listed", "=", "None", ",", "is_deleted", "=", "None", ")", ":", "route_values", "...
70.264706
35.382353
def lazy_value_map(f, m, *args, **kwargs): ''' lazy_value_map(f, mapping) yields a lazy map whose keys are the same as those of the given dict or mapping object and whose values, for each key k are f(mapping[k]). lazy_value_map(f, mapping, *args, **kw) additionally passes the given arguments to the fu...
[ "def", "lazy_value_map", "(", "f", ",", "m", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_map", "(", "m", ")", ":", "raise", "ValueError", "(", "'Non-mapping object passed to lazy_value_map'", ")", "if", "not", "is_lazy_map", "(", ...
61.857143
35.761905
def find_first_file_with_ext(base_paths, prefix, exts): """Runs through the given list of file extensions and returns the first file with the given base path and extension combination that actually exists. Args: base_paths: The base paths in which to search for files. prefix: The filename p...
[ "def", "find_first_file_with_ext", "(", "base_paths", ",", "prefix", ",", "exts", ")", ":", "for", "base_path", "in", "base_paths", ":", "for", "ext", "in", "exts", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "\"%s%s\"", ...
46.454545
25.681818
def farps(self) -> typing.Iterator['Static']: """ Returns: generator over all FARPs objects """ for coa in [self._blue_coa, self._red_coa]: if coa is not None: for farp in coa.farps: yield farp
[ "def", "farps", "(", "self", ")", "->", "typing", ".", "Iterator", "[", "'Static'", "]", ":", "for", "coa", "in", "[", "self", ".", "_blue_coa", ",", "self", ".", "_red_coa", "]", ":", "if", "coa", "is", "not", "None", ":", "for", "farp", "in", "...
33.25
5.75
def is_filtered(self, process): """Return True if the process item match the current filter The proces item is a dict. """ if self.filter is None: # No filter => Not filtered return False if self.filter_key is None: # Apply filter on command l...
[ "def", "is_filtered", "(", "self", ",", "process", ")", ":", "if", "self", ".", "filter", "is", "None", ":", "# No filter => Not filtered", "return", "False", "if", "self", ".", "filter_key", "is", "None", ":", "# Apply filter on command line and process name", "r...
37.8
13.666667
def exact(self, column, *values): """ Sets the main dataframe to rows that has the exact string value in a column """ df = self._exact(column, *values) if df is None: self.err("Can not select exact data") self.df = df
[ "def", "exact", "(", "self", ",", "column", ",", "*", "values", ")", ":", "df", "=", "self", ".", "_exact", "(", "column", ",", "*", "values", ")", "if", "df", "is", "None", ":", "self", ".", "err", "(", "\"Can not select exact data\"", ")", "self", ...
30.777778
10.555556
def next_datetime(min_year = None, max_year = None): """ Generates a random Date and time in the range ['minYear', 'maxYear']. This method generate dates without time (or time set to 00:00:00) :param min_year: (optional) minimum range value :param max_year: max range value ...
[ "def", "next_datetime", "(", "min_year", "=", "None", ",", "max_year", "=", "None", ")", ":", "date", "=", "RandomDateTime", ".", "next_date", "(", "min_year", ",", "max_year", ")", ".", "date", "(", ")", "time", "=", "RandomDateTime", ".", "next_time", ...
37.428571
18.714286
def _handle(self, request: Request, response: Response) -> TypeGenerator[Any, None, None]: """ request 解析后的回调,调用中间件,并处理 headers, body 发送。 """ # request.start_time = datetime.now().timestamp() # 创建一个新的会话上下文 ctx = self._context( cast(asyncio.AbstractEventLoop, s...
[ "def", "_handle", "(", "self", ",", "request", ":", "Request", ",", "response", ":", "Response", ")", "->", "TypeGenerator", "[", "Any", ",", "None", ",", "None", "]", ":", "# request.start_time = datetime.now().timestamp()", "# 创建一个新的会话上下文", "ctx", "=", "self",...
33.151515
16.181818
def get_service_endpoint_types(self, type=None, scheme=None): """GetServiceEndpointTypes. [Preview API] Get service endpoint types. :param str type: Type of service endpoint. :param str scheme: Scheme of service endpoint. :rtype: [ServiceEndpointType] """ query_pa...
[ "def", "get_service_endpoint_types", "(", "self", ",", "type", "=", "None", ",", "scheme", "=", "None", ")", ":", "query_parameters", "=", "{", "}", "if", "type", "is", "not", "None", ":", "query_parameters", "[", "'type'", "]", "=", "self", ".", "_seria...
52.411765
18.647059
def _persist(self): """ Run the command inside a thread so that we can catch output for each line as it comes in and display it. """ # run the block/command for command in self.commands: try: process = Popen( [command], ...
[ "def", "_persist", "(", "self", ")", ":", "# run the block/command", "for", "command", "in", "self", ".", "commands", ":", "try", ":", "process", "=", "Popen", "(", "[", "command", "]", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "univ...
41.514706
15.426471
def errors_to_json(errors): """Convert the errors to JSON.""" out = [] for e in errors: out.append({ "check": e[0], "message": e[1], "line": 1 + e[2], "column": 1 + e[3], "start": 1 + e[4], "end": 1 + e[5], "extent":...
[ "def", "errors_to_json", "(", "errors", ")", ":", "out", "=", "[", "]", "for", "e", "in", "errors", ":", "out", ".", "append", "(", "{", "\"check\"", ":", "e", "[", "0", "]", ",", "\"message\"", ":", "e", "[", "1", "]", ",", "\"line\"", ":", "1...
26.555556
16.5
def __create_dir_property(self, dir_name, docstring): """ Generate getter and setter for a directory property. """ property_name = "{}_dir".format(dir_name) private_name = "_" + property_name setattr(self, private_name, None) def fget(self): return g...
[ "def", "__create_dir_property", "(", "self", ",", "dir_name", ",", "docstring", ")", ":", "property_name", "=", "\"{}_dir\"", ".", "format", "(", "dir_name", ")", "private_name", "=", "\"_\"", "+", "property_name", "setattr", "(", "self", ",", "private_name", ...
30.777778
15.111111
def get(self, key, namespace=None): """Retrieve value for key.""" if not self.path: return NO_VALUE logger.debug('Searching %r for key: %s, namepsace: %s', self, key, namespace) full_key = generate_uppercase_key(key, namespace) return get_key_from_envs(self.cfg, full...
[ "def", "get", "(", "self", ",", "key", ",", "namespace", "=", "None", ")", ":", "if", "not", "self", ".", "path", ":", "return", "NO_VALUE", "logger", ".", "debug", "(", "'Searching %r for key: %s, namepsace: %s'", ",", "self", ",", "key", ",", "namespace"...
39.75
18.375
def _getSynIngestNodes(self, item): ''' Get a list of packed nodes from a ingest definition. ''' pnodes = [] seen = item.get('seen') # Track all the ndefs we make so we can make sources ndefs = [] # Make the form nodes tags = item.get('tags', {}) ...
[ "def", "_getSynIngestNodes", "(", "self", ",", "item", ")", ":", "pnodes", "=", "[", "]", "seen", "=", "item", ".", "get", "(", "'seen'", ")", "# Track all the ndefs we make so we can make sources", "ndefs", "=", "[", "]", "# Make the form nodes", "tags", "=", ...
34.305556
13.972222
def __set_identifier(self, value): ''' Sets the ID of the invoice. @param value:str ''' if not value or not len(value): raise ValueError("Invalid invoice ID") self.__identifier = value
[ "def", "__set_identifier", "(", "self", ",", "value", ")", ":", "if", "not", "value", "or", "not", "len", "(", "value", ")", ":", "raise", "ValueError", "(", "\"Invalid invoice ID\"", ")", "self", ".", "__identifier", "=", "value" ]
26.333333
15.888889
def dec2dms(dec): """ ADW: This should really be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. dec = float(dec) sign = np.copysign(1.0,dec) fdeg = np.abs(dec) deg = int(fdeg) fminute = (fdeg - deg)*MINUTE minute = int(fminute) ...
[ "def", "dec2dms", "(", "dec", ")", ":", "DEGREE", "=", "360.", "HOUR", "=", "24.", "MINUTE", "=", "60.", "SECOND", "=", "3600.", "dec", "=", "float", "(", "dec", ")", "sign", "=", "np", ".", "copysign", "(", "1.0", ",", "dec", ")", "fdeg", "=", ...
18.136364
19.772727
def parse_diff(self, diff: str) -> Dict[str, List[Tuple[int, str]]]: """ Given a diff, returns a dictionary with the added and deleted lines. The dictionary has 2 keys: "added" and "deleted", each containing the corresponding added or deleted lines. For both keys, the value is a ...
[ "def", "parse_diff", "(", "self", ",", "diff", ":", "str", ")", "->", "Dict", "[", "str", ",", "List", "[", "Tuple", "[", "int", ",", "str", "]", "]", "]", ":", "lines", "=", "diff", ".", "split", "(", "'\\n'", ")", "modified_lines", "=", "{", ...
33.74359
20.974359
def _parse_nested_interval(self, tokens): """ Parses a super range. SuperRange ::= Range | Join | Complement """ if tokens[0].isdigit(): return self._parse_interval(tokens) elif tokens[0] in ['join', 'order']: return self._parse_join(tokens) elif ...
[ "def", "_parse_nested_interval", "(", "self", ",", "tokens", ")", ":", "if", "tokens", "[", "0", "]", ".", "isdigit", "(", ")", ":", "return", "self", ".", "_parse_interval", "(", "tokens", ")", "elif", "tokens", "[", "0", "]", "in", "[", "'join'", "...
42.090909
7.181818
def index(self, sub, *args): ''' Returns index of sub in bytes. Raises ValueError if byte is not in bytes and TypeError if can't be converted bytes or its length is not 1. ''' if isinstance(sub, int): if len(args) == 0: start, end = 0, len(self...
[ "def", "index", "(", "self", ",", "sub", ",", "*", "args", ")", ":", "if", "isinstance", "(", "sub", ",", "int", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "start", ",", "end", "=", "0", ",", "len", "(", "self", ")", "elif", "...
36.6
13.64
def print_full_name(*args, **kwargs): '''Decorator, print the full name of the decorated function. May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``) or with named arguments ``color``, ``bold``, or ``prefix`` (eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``). '''...
[ "def", "print_full_name", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "color", "=", "kwargs", ".", "get", "(", "'color'", ",", "default_color", ")", "bold", "=", "kwargs", ".", "get", "(", "'bold'", ",", "False", ")", "prefix", "=", "kwargs"...
35.5625
16.9375
def _write_cols(self, sid, dts, cols, invalid_data_behavior): """ Internal method for `write_cols` and `write`. Parameters ---------- sid : int The asset identifier for the data being written. dts : datetime64 array The dts corresponding to values...
[ "def", "_write_cols", "(", "self", ",", "sid", ",", "dts", ",", "cols", ",", "invalid_data_behavior", ")", ":", "table", "=", "self", ".", "_ensure_ctable", "(", "sid", ")", "tds", "=", "self", ".", "_session_labels", "input_first_day", "=", "self", ".", ...
35.879518
21.385542
def _automatic_dims(cls, dims, size): """Check if input dimension corresponds to qubit subsystems.""" if dims is None: dims = size elif np.product(dims) != size: raise QiskitError("dimensions do not match size.") if isinstance(dims, (int, np.integer)): ...
[ "def", "_automatic_dims", "(", "cls", ",", "dims", ",", "size", ")", ":", "if", "dims", "is", "None", ":", "dims", "=", "size", "elif", "np", ".", "product", "(", "dims", ")", "!=", "size", ":", "raise", "QiskitError", "(", "\"dimensions do not match siz...
39.666667
8.25
def get_xgb_params(xgb_node): """ Retrieves parameters of a model. """ if hasattr(xgb_node, 'kwargs'): # XGBoost >= 0.7 params = xgb_node.get_xgb_params() else: # XGBoost < 0.7 params = xgb_node.__dict__ return params
[ "def", "get_xgb_params", "(", "xgb_node", ")", ":", "if", "hasattr", "(", "xgb_node", ",", "'kwargs'", ")", ":", "# XGBoost >= 0.7", "params", "=", "xgb_node", ".", "get_xgb_params", "(", ")", "else", ":", "# XGBoost < 0.7", "params", "=", "xgb_node", ".", "...
22.583333
12.25
def string2latlon(lat_str, lon_str, format_str): ''' Create a LatLon object from a pair of strings. Inputs: lat_str (str) - string representation of a latitude (e.g. '5 52 59.88 N') lon_str (str) - string representation of a longitude (e.g. '162 4 59.88 W') format_str (str) - format ...
[ "def", "string2latlon", "(", "lat_str", ",", "lon_str", ",", "format_str", ")", ":", "lat", "=", "string2geocoord", "(", "lat_str", ",", "Latitude", ",", "format_str", ")", "lon", "=", "string2geocoord", "(", "lon_str", ",", "Longitude", ",", "format_str", "...
49.75
27.5
def resname_in_proximity(resname, model, chains, resnums, threshold=5): """Search within the proximity of a defined list of residue numbers and their chains for any specifed residue name. Args: resname (str): Residue name to search for in proximity of specified chains + resnums model: Biopython...
[ "def", "resname_in_proximity", "(", "resname", ",", "model", ",", "chains", ",", "resnums", ",", "threshold", "=", "5", ")", ":", "residues", "=", "[", "r", "for", "r", "in", "model", ".", "get_residues", "(", ")", "if", "r", ".", "get_resname", "(", ...
39.344828
23.275862
def _processed_filepath(self, filepath): """ checks to see if the filepath has already been processed """ processed = False if filepath in self.processed_filepaths.values(): processed = True return processed
[ "def", "_processed_filepath", "(", "self", ",", "filepath", ")", ":", "processed", "=", "False", "if", "filepath", "in", "self", ".", "processed_filepaths", ".", "values", "(", ")", ":", "processed", "=", "True", "return", "processed" ]
28.888889
13.777778
def pressed_keys(self): """An array containing all detected keys that are pressed from the initalized list-of-lists passed in during creation""" # make a list of all the keys that are detected pressed = [] # set all pins pins to be inputs w/pullups for pin in self.row_pi...
[ "def", "pressed_keys", "(", "self", ")", ":", "# make a list of all the keys that are detected", "pressed", "=", "[", "]", "# set all pins pins to be inputs w/pullups", "for", "pin", "in", "self", ".", "row_pins", "+", "self", ".", "col_pins", ":", "pin", ".", "dire...
42.26087
12.565217
def get_version_from_dirname(name, parent): """Extracted sdist""" parent = parent.resolve() logger.info(f"dirname: Trying to get version of {name} from dirname {parent}") name_re = name.replace("_", "[_-]") re_dirname = re.compile(f"{name_re}-{RE_VERSION}$") if not re_dirname.match(parent.name)...
[ "def", "get_version_from_dirname", "(", "name", ",", "parent", ")", ":", "parent", "=", "parent", ".", "resolve", "(", ")", "logger", ".", "info", "(", "f\"dirname: Trying to get version of {name} from dirname {parent}\"", ")", "name_re", "=", "name", ".", "replace"...
38
17
def mark_in_progress(self, rr_id: str, rr_size: int) -> None: """ Prepare sentinel directory for revocation registry construction. :param rr_id: revocation registry identifier :rr_size: size of revocation registry to build """ try: makedirs(join(self._dir_tai...
[ "def", "mark_in_progress", "(", "self", ",", "rr_id", ":", "str", ",", "rr_size", ":", "int", ")", "->", "None", ":", "try", ":", "makedirs", "(", "join", "(", "self", ".", "_dir_tails_sentinel", ",", "rr_id", ")", ",", "exist_ok", "=", "False", ")", ...
43.307692
23.769231
def _category(self): """ Type of the image: LOLA or WAC Note: Specify the attribute ``grid``, ``img`` and ``lbl` """ if self.fname.split('_')[0] == 'WAC': self.grid = 'WAC' self.img = os.path.join(self.wacpath, self.fname + '.IMG') self.lbl = '' ...
[ "def", "_category", "(", "self", ")", ":", "if", "self", ".", "fname", ".", "split", "(", "'_'", ")", "[", "0", "]", "==", "'WAC'", ":", "self", ".", "grid", "=", "'WAC'", "self", ".", "img", "=", "os", ".", "path", ".", "join", "(", "self", ...
42.235294
23
def recursive_mtime(path, newest=True): """Gets the newest/oldest mtime for all files in a directory.""" if os.path.isfile(path): return mtime(path) current_extreme = None for dirname, _, filenames in os.walk(path, topdown=False): for filename in filenames: mt = mtime(os.path...
[ "def", "recursive_mtime", "(", "path", ",", "newest", "=", "True", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "return", "mtime", "(", "path", ")", "current_extreme", "=", "None", "for", "dirname", ",", "_", ",", "filenam...
41.571429
8.857143
def xmlrpc_provision(self, app_id, path_to_cert_or_cert, environment, timeout=15): """ Starts an APNSService for the this app_id and keeps it running Arguments: app_id the app_id to provision for APNS path_to_cert_or_cert absolute path to the APNS SSL cert or a ...
[ "def", "xmlrpc_provision", "(", "self", ",", "app_id", ",", "path_to_cert_or_cert", ",", "environment", ",", "timeout", "=", "15", ")", ":", "if", "environment", "not", "in", "(", "'sandbox'", ",", "'production'", ")", ":", "raise", "xmlrpc", ".", "Fault", ...
49.47619
24.285714
def protect_pip_from_modification_on_windows(modifying_pip): """Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... """ pip_names = [ "pip.exe", "pip{}.exe".format(sys.version_info[0]), "pip{}.{}....
[ "def", "protect_pip_from_modification_on_windows", "(", "modifying_pip", ")", ":", "pip_names", "=", "[", "\"pip.exe\"", ",", "\"pip{}.exe\"", ".", "format", "(", "sys", ".", "version_info", "[", "0", "]", ")", ",", "\"pip{}.{}.exe\"", ".", "format", "(", "*", ...
30.222222
18.666667
def _validate_features(self, data): """ Validate Booster and data's feature_names are identical. Set feature_names and feature_types from DMatrix """ if self.feature_names is None: self.feature_names = data.feature_names self.feature_types = data.feature_t...
[ "def", "_validate_features", "(", "self", ",", "data", ")", ":", "if", "self", ".", "feature_names", "is", "None", ":", "self", ".", "feature_names", "=", "data", ".", "feature_names", "self", ".", "feature_types", "=", "data", ".", "feature_types", "else", ...
43.538462
22.153846
def request_comment_show(self, request_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/requests#getting-comments" api_path = "/api/v2/requests/{request_id}/comments/{id}.json" api_path = api_path.format(request_id=request_id, id=id) return self.call(api_path, **kwarg...
[ "def", "request_comment_show", "(", "self", ",", "request_id", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/requests/{request_id}/comments/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "request_id", "=", "request_id", ...
63.6
23.6
def asobject(self): """ Return object Series which contains boxed values. .. deprecated :: 0.23.0 Use ``astype(object)`` instead. *this is an internal non-public method* """ warnings.warn("'asobject' is deprecated. Use 'astype(object)'" ...
[ "def", "asobject", "(", "self", ")", ":", "warnings", ".", "warn", "(", "\"'asobject' is deprecated. Use 'astype(object)'\"", "\" instead\"", ",", "FutureWarning", ",", "stacklevel", "=", "2", ")", "return", "self", ".", "astype", "(", "object", ")", ".", "value...
30.076923
17.615385