text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def collect(self): """Collect the elements in an DataFrame and concatenate the partition.""" local_df = self._schema_rdd.toPandas() correct_idx_df = _update_index_on_df(local_df, self._index_names) return correct_idx_df
[ "def", "collect", "(", "self", ")", ":", "local_df", "=", "self", ".", "_schema_rdd", ".", "toPandas", "(", ")", "correct_idx_df", "=", "_update_index_on_df", "(", "local_df", ",", "self", ".", "_index_names", ")", "return", "correct_idx_df" ]
42.333333
0.007722
def clean_old_backups(self, encrypted=None, compressed=None, content_type=None, database=None, servername=None, keep_number=None): """ Delete olders backups and hold the number defined. :param encrypted: Filter by encrypted or not :typ...
[ "def", "clean_old_backups", "(", "self", ",", "encrypted", "=", "None", ",", "compressed", "=", "None", ",", "content_type", "=", "None", ",", "database", "=", "None", ",", "servername", "=", "None", ",", "keep_number", "=", "None", ")", ":", "if", "keep...
41.897436
0.00299
def bilinear(px, py, band_array, gt): """Bilinear interpolated point at(px, py) on band_array """ #import malib #band_array = malib.checkma(band_array) ndv = band_array.fill_value ny, nx = band_array.shape # Half raster cell widths hx = gt[1]/2.0 hy = gt[5]/2.0 # Calculate raster...
[ "def", "bilinear", "(", "px", ",", "py", ",", "band_array", ",", "gt", ")", ":", "#import malib", "#band_array = malib.checkma(band_array)", "ndv", "=", "band_array", ".", "fill_value", "ny", ",", "nx", "=", "band_array", ".", "shape", "# Half raster cell widths",...
34.702703
0.015909
def psource(self,obj,oname=''): """Print the source code for an object.""" # Flush the source cache because inspect can return out-of-date source linecache.checkcache() try: src = getsource(obj) except: self.noinfo('source',oname) else: ...
[ "def", "psource", "(", "self", ",", "obj", ",", "oname", "=", "''", ")", ":", "# Flush the source cache because inspect can return out-of-date source", "linecache", ".", "checkcache", "(", ")", "try", ":", "src", "=", "getsource", "(", "obj", ")", "except", ":",...
33.181818
0.016
def url_for(self, action='view', **kwargs): """ Return public URL to this instance for a given action (default 'view') """ app = current_app._get_current_object() if current_app else None if app is not None and action in self.url_for_endpoints.get(app, {}): endpoint, ...
[ "def", "url_for", "(", "self", ",", "action", "=", "'view'", ",", "*", "*", "kwargs", ")", ":", "app", "=", "current_app", ".", "_get_current_object", "(", ")", "if", "current_app", "else", "None", "if", "app", "is", "not", "None", "and", "action", "in...
41.722222
0.002602
def p_file_contributor(self, f_term, predicate): """ Parse all file contributors and adds them to the model. """ for _, _, contributor in self.graph.triples((f_term, predicate, None)): self.builder.add_file_contribution(self.doc, six.text_type(contributor))
[ "def", "p_file_contributor", "(", "self", ",", "f_term", ",", "predicate", ")", ":", "for", "_", ",", "_", ",", "contributor", "in", "self", ".", "graph", ".", "triples", "(", "(", "f_term", ",", "predicate", ",", "None", ")", ")", ":", "self", ".", ...
49.333333
0.009967
def sort_by_length_usearch61(seq_path, output_dir=".", minlen=64, remove_usearch_logs=False, HALT_EXEC=False, output_fna_filepath=None, log_name="...
[ "def", "sort_by_length_usearch61", "(", "seq_path", ",", "output_dir", "=", "\".\"", ",", "minlen", "=", "64", ",", "remove_usearch_logs", "=", "False", ",", "HALT_EXEC", "=", "False", ",", "output_fna_filepath", "=", "None", ",", "log_name", "=", "\"length_sort...
37.285714
0.000747
def SetMaxPowerUpCurrent(self, i): """Set the max power up current. """ if i < 0 or i > 8: raise MonsoonError(("Target max current %sA, is out of acceptable " "range [0, 8].") % i) val = 1023 - int((i / 8) * 1023) self._SendStruct("BBB"...
[ "def", "SetMaxPowerUpCurrent", "(", "self", ",", "i", ")", ":", "if", "i", "<", "0", "or", "i", ">", "8", ":", "raise", "MonsoonError", "(", "(", "\"Target max current %sA, is out of acceptable \"", "\"range [0, 8].\"", ")", "%", "i", ")", "val", "=", "1023"...
43.444444
0.005013
def init_with_context(self, context): """ Initializes the icon list. """ super(CmsAppIconList, self).init_with_context(context) apps = self.children cms_apps = [a for a in apps if is_cms_app(a['name'])] non_cms_apps = [a for a in apps if a not in cms_apps] ...
[ "def", "init_with_context", "(", "self", ",", "context", ")", ":", "super", "(", "CmsAppIconList", ",", "self", ")", ".", "init_with_context", "(", "context", ")", "apps", "=", "self", ".", "children", "cms_apps", "=", "[", "a", "for", "a", "in", "apps",...
35.571429
0.003911
def generate_sha1(string, salt=None): """ Generates a sha1 hash for supplied string. Doesn't need to be very secure because it's not used for password checking. We got Django for that. :param string: The string that needs to be encrypted. :param salt: Optionally define your own sal...
[ "def", "generate_sha1", "(", "string", ",", "salt", "=", "None", ")", ":", "if", "not", "isinstance", "(", "string", ",", "(", "str", ",", "text_type", ")", ")", ":", "string", "=", "str", "(", "string", ")", "if", "not", "salt", ":", "salt", "=", ...
29.08
0.001332
def _decode_exp(self, access_token=None): """Extract exp field from access token. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: int: JWT expiration in epoch seconds. """ c = self.get_credentials() jwt = access_...
[ "def", "_decode_exp", "(", "self", ",", "access_token", "=", "None", ")", ":", "c", "=", "self", ".", "get_credentials", "(", ")", "jwt", "=", "access_token", "or", "c", ".", "access_token", "x", "=", "self", ".", "decode_jwt_payload", "(", "jwt", ")", ...
29.12
0.00266
def to_dict(self, save_data=True): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :param boolean save_data: if true, it adds the training data self.X and self.Y to the dictionary :return dict: json ...
[ "def", "to_dict", "(", "self", ",", "save_data", "=", "True", ")", ":", "input_dict", "=", "super", "(", "GP", ",", "self", ")", ".", "_save_to_input_dict", "(", ")", "input_dict", "[", "\"class\"", "]", "=", "\"GPy.core.GP\"", "if", "not", "save_data", ...
45.424242
0.005225
def add_access_key_permissions(self, access_key_id, permissions): """ Adds to the existing list of permissions on this key with the contents of this list. Will not remove any existing permissions or modify the remainder of the key. :param access_key_id: the 'key' value of the access key...
[ "def", "add_access_key_permissions", "(", "self", ",", "access_key_id", ",", "permissions", ")", ":", "# Get current state via HTTPS.", "current_access_key", "=", "self", ".", "get_access_key", "(", "access_key_id", ")", "# Copy and only change the single parameter.", "payloa...
48.090909
0.005561
def unlock_weixin_callback_example(url, req, resp, img, identify_image_callback): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : ...
[ "def", "unlock_weixin_callback_example", "(", "url", ",", "req", ",", "resp", ",", "img", ",", "identify_image_callback", ")", ":", "# no use resp", "unlock_url", "=", "'https://mp.weixin.qq.com/mp/verifycode'", "data", "=", "{", "'cert'", ":", "time", ".", "time", ...
26.465116
0.002542
def block_start(self, previous_block): """Returns an ordered list of batches to inject at the beginning of the block. Can also return None if no batches should be injected. Args: previous_block (Block): The previous block. Returns: A list of batches to inject. ...
[ "def", "block_start", "(", "self", ",", "previous_block", ")", ":", "previous_header_bytes", "=", "previous_block", ".", "header", "previous_header", "=", "BlockHeader", "(", ")", "previous_header", ".", "ParseFromString", "(", "previous_header_bytes", ")", "block_inf...
36
0.002353
def get_policies_by_id(profile_manager, policy_ids): ''' Returns a list of policies with the specified ids. profile_manager Reference to the profile manager. policy_ids List of policy ids to retrieve. ''' try: return profile_manager.RetrieveContent(policy_ids) excep...
[ "def", "get_policies_by_id", "(", "profile_manager", ",", "policy_ids", ")", ":", "try", ":", "return", "profile_manager", ".", "RetrieveContent", "(", "policy_ids", ")", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "except...
32
0.001379
def setCustomCompletions(self, wordSet): """Add a set of custom completions to the editors completions. This set is managed independently of the set of keywords and words from the current document, and can thus be changed at any time. """ if not isinstance(wordSet, set): ...
[ "def", "setCustomCompletions", "(", "self", ",", "wordSet", ")", ":", "if", "not", "isinstance", "(", "wordSet", ",", "set", ")", ":", "raise", "TypeError", "(", "'\"wordSet\" is not a set: %s'", "%", "type", "(", "wordSet", ")", ")", "self", ".", "_complete...
43.2
0.004535
def delete_user(self, user): """ Delete user and all data""" assert self.user == 'catroot' or self.user == 'postgres' assert not user == 'public' con = self.connection or self._connect() cur = con.cursor() cur.execute('DROP SCHEMA {user} CASCADE;'.format(user=user)) ...
[ "def", "delete_user", "(", "self", ",", "user", ")", ":", "assert", "self", ".", "user", "==", "'catroot'", "or", "self", ".", "user", "==", "'postgres'", "assert", "not", "user", "==", "'public'", "con", "=", "self", ".", "connection", "or", "self", "...
35.636364
0.002484
def siphash24(message, key=b'', encoder=nacl.encoding.HexEncoder): """ Computes a keyed MAC of ``message`` using the short-input-optimized siphash-2-4 construction. :param message: The message to hash. :type message: bytes :param key: the message authentication key for the siphash MAC construct...
[ "def", "siphash24", "(", "message", ",", "key", "=", "b''", ",", "encoder", "=", "nacl", ".", "encoding", ".", "HexEncoder", ")", ":", "digest", "=", "_sip_hash", "(", "message", ",", "key", ")", "return", "encoder", ".", "encode", "(", "digest", ")" ]
38.666667
0.001684
def get_activities_by_ids(self, activity_ids=None): """Gets an ActivityList corresponding to the given IdList. In plenary mode, the returned list contains all of the activities specified in the Id list, in the order of the list, including duplicates, or an error results if an Id in the ...
[ "def", "get_activities_by_ids", "(", "self", ",", "activity_ids", "=", "None", ")", ":", "if", "activity_ids", "is", "None", ":", "raise", "NullArgument", "(", ")", "activities", "=", "[", "]", "for", "i", "in", "activity_ids", ":", "activity", "=", "None"...
43.975
0.001112
def resetScale(self): """Resets the scale on this image. Correctly aligns time scale, undoes manual scaling""" self.img.scale(1./self.imgScale[0], 1./self.imgScale[1]) self.imgScale = (1.,1.)
[ "def", "resetScale", "(", "self", ")", ":", "self", ".", "img", ".", "scale", "(", "1.", "/", "self", ".", "imgScale", "[", "0", "]", ",", "1.", "/", "self", ".", "imgScale", "[", "1", "]", ")", "self", ".", "imgScale", "=", "(", "1.", ",", "...
53
0.018605
def configure_authentication(self, database): """ Configure the authentication """ options = {"plugins": [], "superadmins": []} self._display_info("We will now create the first user.") username = self._ask_with_default("Enter the login of the superadmin", "superadmin") realname...
[ "def", "configure_authentication", "(", "self", ",", "database", ")", ":", "options", "=", "{", "\"plugins\"", ":", "[", "]", ",", "\"superadmins\"", ":", "[", "]", "}", "self", ".", "_display_info", "(", "\"We will now create the first user.\"", ")", "username"...
48
0.006807
def _on_trigger(self, my_task): """ Enqueue a trigger, such that this tasks triggers multiple times later when _on_complete() is called. """ self.queued += 1 # All tasks that have already completed need to be put back to # READY. for thetask in my_task.wor...
[ "def", "_on_trigger", "(", "self", ",", "my_task", ")", ":", "self", ".", "queued", "+=", "1", "# All tasks that have already completed need to be put back to", "# READY.", "for", "thetask", "in", "my_task", ".", "workflow", ".", "task_tree", ":", "if", "thetask", ...
39.466667
0.0033
def tn_days_below(tasmin, thresh='-10.0 degC', freq='YS'): r"""Number of days with tmin below a threshold in Number of days where daily minimum temperature is below a threshold. Parameters ---------- tasmin : xarray.DataArray Minimum daily temperature [℃] or [K] thresh : str Thresh...
[ "def", "tn_days_below", "(", "tasmin", ",", "thresh", "=", "'-10.0 degC'", ",", "freq", "=", "'YS'", ")", ":", "thresh", "=", "utils", ".", "convert_units_to", "(", "thresh", ",", "tasmin", ")", "f1", "=", "utils", ".", "threshold_count", "(", "tasmin", ...
27.290323
0.003425
def realpath(path): """ Return ``path`` with symlinks resolved. Currently this function returns non-local paths unchanged. """ scheme, netloc, path_ = parse(path) if scheme == 'file' or hdfs_fs.default_is_local(): return unparse(scheme, netloc, os.path.realpath(path_)) return path
[ "def", "realpath", "(", "path", ")", ":", "scheme", ",", "netloc", ",", "path_", "=", "parse", "(", "path", ")", "if", "scheme", "==", "'file'", "or", "hdfs_fs", ".", "default_is_local", "(", ")", ":", "return", "unparse", "(", "scheme", ",", "netloc",...
30.9
0.003145
def do_show(self, args): """Show the current structure of __root (no args), or show the result of the expression (something that can be eval'd). """ args = args.strip() to_show = self._interp._root if args != "": try: to_show = self._interp.ev...
[ "def", "do_show", "(", "self", ",", "args", ")", ":", "args", "=", "args", ".", "strip", "(", ")", "to_show", "=", "self", ".", "_interp", ".", "_root", "if", "args", "!=", "\"\"", ":", "try", ":", "to_show", "=", "self", ".", "_interp", ".", "ev...
30.611111
0.003521
def run_locally(self): """A convenience method to run the same result as a SLURM job but locally in a non-blocking way. Useful for testing.""" self.thread = threading.Thread(target=self.execute_locally) self.thread.daemon = True # So that they die when we die self.thread.start()
[ "def", "run_locally", "(", "self", ")", ":", "self", ".", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "execute_locally", ")", "self", ".", "thread", ".", "daemon", "=", "True", "# So that they die when we die", "self", ".", ...
52.333333
0.009404
def convert(image, shape, gray=False, dtype='float64', normalize='max'): """Convert image to standardized format. Several properties of the input image may be changed including the shape, data type and maximal value of the image. In addition, this function may convert the image into an ODL object and/o...
[ "def", "convert", "(", "image", ",", "shape", ",", "gray", "=", "False", ",", "dtype", "=", "'float64'", ",", "normalize", "=", "'max'", ")", ":", "image", "=", "image", ".", "astype", "(", "dtype", ")", "if", "gray", ":", "image", "[", "...", ",",...
28.642857
0.001206
async def list_blocks(self, request): """Fetches list of blocks from validator, optionally filtered by id. Request: query: - head: The id of the block to use as the head of the chain - id: Comma separated list of block ids to include in results Respo...
[ "async", "def", "list_blocks", "(", "self", ",", "request", ")", ":", "paging_controls", "=", "self", ".", "_get_paging_controls", "(", "request", ")", "validator_query", "=", "client_block_pb2", ".", "ClientBlockListRequest", "(", "head_id", "=", "self", ".", "...
43.387097
0.001455
def setShowGridRows( self, state ): """ Sets whether or not the grid rows should be rendered when drawing the \ grid. :param state | <bool> """ delegate = self.itemDelegate() if ( isinstance(delegate, XTreeWidgetDelegate) ): dele...
[ "def", "setShowGridRows", "(", "self", ",", "state", ")", ":", "delegate", "=", "self", ".", "itemDelegate", "(", ")", "if", "(", "isinstance", "(", "delegate", ",", "XTreeWidgetDelegate", ")", ")", ":", "delegate", ".", "setShowGridRows", "(", "state", ")...
33.8
0.023055
def AIC(data, model, params=None, corrected=True): """ Akaike Information Criteria given data and a model Parameters ---------- {0} {1} params : int Number of parameters in the model. If None, calculated from model object. corrected : bool If True, calculates the...
[ "def", "AIC", "(", "data", ",", "model", ",", "params", "=", "None", ",", "corrected", "=", "True", ")", ":", "n", "=", "len", "(", "data", ")", "# Number of observations", "L", "=", "nll", "(", "data", ",", "model", ")", "if", "not", "params", ":"...
25.873418
0.000943
def cross(series, cross=0, direction='cross'): """ From http://stackoverflow.com/questions/10475488/calculating-crossing-intercept-points-of-a-series-or-dataframe Given a Series returns all the index values where the data values equal the 'cross' value. Direction can be 'rising' (for rising edge...
[ "def", "cross", "(", "series", ",", "cross", "=", "0", ",", "direction", "=", "'cross'", ")", ":", "# Find if values are above or bellow yvalue crossing:", "above", "=", "series", ".", "values", ">", "cross", "below", "=", "scipy", ".", "logical_not", "(", "ab...
36.941176
0.005431
def GetReportData(self, get_report_args, token): """Filter the last week of user actions.""" ret = rdf_report_plugins.ApiReportData( representation_type=RepresentationType.STACK_CHART) week_duration = rdfvalue.Duration("7d") num_weeks = math.ceil(get_report_args.duration.seconds / ...
[ "def", "GetReportData", "(", "self", ",", "get_report_args", ",", "token", ")", ":", "ret", "=", "rdf_report_plugins", ".", "ApiReportData", "(", "representation_type", "=", "RepresentationType", ".", "STACK_CHART", ")", "week_duration", "=", "rdfvalue", ".", "Dur...
38.828571
0.002872
def cache_call_refresh(self, method, *options): """ Call a remote method and update the local cache with the result if it already existed. :param str method: The name of the remote procedure to execute. :return: The return value from the remote function. """ options_hash = self.encode(options) if len(o...
[ "def", "cache_call_refresh", "(", "self", ",", "method", ",", "*", "options", ")", ":", "options_hash", "=", "self", ".", "encode", "(", "options", ")", "if", "len", "(", "options_hash", ")", ">", "20", ":", "options_hash", "=", "hashlib", ".", "new", ...
40.565217
0.025131
def jaccard(seq1, seq2): """Compute the Jaccard distance between the two sequences `seq1` and `seq2`. They should contain hashable items. The return value is a float between 0 and 1, where 0 means equal, and 1 totally different. """ set1, set2 = set(seq1), set(seq2) return 1 - len(set1 & set2) / float(len(set1 ...
[ "def", "jaccard", "(", "seq1", ",", "seq2", ")", ":", "set1", ",", "set2", "=", "set", "(", "seq1", ")", ",", "set", "(", "seq2", ")", "return", "1", "-", "len", "(", "set1", "&", "set2", ")", "/", "float", "(", "len", "(", "set1", "|", "set2...
40.125
0.030488
def set(self, key, value, **kwargs): """ Set the value of a Parameter in the ParameterSet. If :func:`get` would retrieve a Parameter, this will set the value of that parameter. Or you can provide 'value@...' or 'default_unit@...', etc to specify what attribute to set. ...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "*", "*", "kwargs", ")", ":", "twig", "=", "key", "method", "=", "None", "twigsplit", "=", "re", ".", "findall", "(", "r\"[\\w']+\"", ",", "twig", ")", "if", "twigsplit", "[", "0", "]", "=...
42.163265
0.002838
def isregex_expr(expr): """ Returns ``True`` is the given expression value is a regular expression like string with prefix ``re/`` and suffix ``/``, otherwise ``False``. Arguments: expr (mixed): expression value to test. Returns: bool """ if not isinstance(expr, str): ...
[ "def", "isregex_expr", "(", "expr", ")", ":", "if", "not", "isinstance", "(", "expr", ",", "str", ")", ":", "return", "False", "return", "all", "(", "[", "len", "(", "expr", ")", ">", "3", ",", "expr", ".", "startswith", "(", "'re/'", ")", ",", "...
22.315789
0.002262
def change_pass(self, new_pass): """ Change the client password for 'new_pass'. :param new_pass: New password of the client. :type new_pass: :class:`str` :param old_pass: Old password of the client. :type old_pass: :class:`str` """ i...
[ "def", "change_pass", "(", "self", ",", "new_pass", ")", ":", "iq", "=", "aioxmpp", ".", "IQ", "(", "to", "=", "self", ".", "client", ".", "local_jid", ".", "bare", "(", ")", ".", "replace", "(", "localpart", "=", "None", ")", ",", "type_", "=", ...
28.842105
0.0053
def handle(self, message): ''' Attempts to send a message to the specified destination in IRC Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. ''' logger.debug(message) if Utilities.isNotEmpty(message['metad...
[ "def", "handle", "(", "self", ",", "message", ")", ":", "logger", ".", "debug", "(", "message", ")", "if", "Utilities", ".", "isNotEmpty", "(", "message", "[", "'metadata'", "]", "[", "'opts'", "]", ")", ":", "target", "=", "message", "[", "'metadata'"...
37.555556
0.002886
def _validate_keys(key_file, fingerprint_hash_type): ''' Return a dict containing validated keys in the passed file ''' ret = {} linere = re.compile(r'^(.*?)\s?((?:ssh\-|ecds)[\w-]+\s.+)$') try: with salt.utils.files.fopen(key_file, 'r') as _fh: for line in _fh: ...
[ "def", "_validate_keys", "(", "key_file", ",", "fingerprint_hash_type", ")", ":", "ret", "=", "{", "}", "linere", "=", "re", ".", "compile", "(", "r'^(.*?)\\s?((?:ssh\\-|ecds)[\\w-]+\\s.+)$'", ")", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", ...
32.107143
0.001079
def master_etcd(info, meta, max_pod_cluster, label): """ Function used to create the response for all master node types """ nodes = meta.get(label, []) or [] info = info[info["machine_id"].isin(nodes)] if info.empty: return cpu_factor = max_pod_cluster / 1000.0 nocpu_expected = MASTER_M...
[ "def", "master_etcd", "(", "info", ",", "meta", ",", "max_pod_cluster", ",", "label", ")", ":", "nodes", "=", "meta", ".", "get", "(", "label", ",", "[", "]", ")", "or", "[", "]", "info", "=", "info", "[", "info", "[", "\"machine_id\"", "]", ".", ...
49.333333
0.002653
def from_file(cls, vert, frag, **kwargs): """ Reads the shader programs, given the vert and frag filenames Arguments: - vert (str): The filename of the vertex shader program (ex: 'vertshader.vert') - frag (str): The filename of the fragment shader program (ex: 'fragshade...
[ "def", "from_file", "(", "cls", ",", "vert", ",", "frag", ",", "*", "*", "kwargs", ")", ":", "vert_program", "=", "open", "(", "vert", ")", ".", "read", "(", ")", "frag_program", "=", "open", "(", "frag", ")", ".", "read", "(", ")", "return", "cl...
39.642857
0.007042
def _expand_target(self): ''' Figures out if the target is a reachable host without wildcards, expands if any. :return: ''' # TODO: Support -L target = self.opts['tgt'] if isinstance(target, list): return hostname = self.opts['tgt'].split('@')...
[ "def", "_expand_target", "(", "self", ")", ":", "# TODO: Support -L", "target", "=", "self", ".", "opts", "[", "'tgt'", "]", "if", "isinstance", "(", "target", ",", "list", ")", ":", "return", "hostname", "=", "self", ".", "opts", "[", "'tgt'", "]", "....
43.068966
0.003132
def update(self, key, value): """ :param key: a string :value: a string """ if not is_string(key): raise Exception("Key must be string") # if len(key) > 32: # raise Exception("Max key length is 32") if not is_string(value): ra...
[ "def", "update", "(", "self", ",", "key", ",", "value", ")", ":", "if", "not", "is_string", "(", "key", ")", ":", "raise", "Exception", "(", "\"Key must be string\"", ")", "# if len(key) > 32:", "# raise Exception(\"Max key length is 32\")", "if", "not", "is_s...
30.318182
0.002907
def darken(self, amount): ''' Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color ''' hsl = self.to_hsl() hsl.l = self.clamp(hsl.l - amount) ...
[ "def", "darken", "(", "self", ",", "amount", ")", ":", "hsl", "=", "self", ".", "to_hsl", "(", ")", "hsl", ".", "l", "=", "self", ".", "clamp", "(", "hsl", ".", "l", "-", "amount", ")", "return", "self", ".", "from_hsl", "(", "hsl", ")" ]
24.142857
0.008547
def _hm_form_message_crc( self, thermostat_id, protocol, source, function, start, payload ): """Forms a message payload, including CRC""" data = self._hm_form_message( thermostat_id, protocol, ...
[ "def", "_hm_form_message_crc", "(", "self", ",", "thermostat_id", ",", "protocol", ",", "source", ",", "function", ",", "start", ",", "payload", ")", ":", "data", "=", "self", ".", "_hm_form_message", "(", "thermostat_id", ",", "protocol", ",", "source", ","...
28
0.006912
def is_valid_mpls_label(label): """Validates `label` according to MPLS label rules RFC says: This 20-bit field. A value of 0 represents the "IPv4 Explicit NULL Label". A value of 1 represents the "Router Alert Label". A value of 2 represents the "IPv6 Explicit NULL Label". A value of 3 repr...
[ "def", "is_valid_mpls_label", "(", "label", ")", ":", "if", "(", "not", "isinstance", "(", "label", ",", "numbers", ".", "Integral", ")", "or", "(", "4", "<=", "label", "<=", "15", ")", "or", "(", "label", "<", "0", "or", "label", ">", "2", "**", ...
31.941176
0.001789
def pre_execute(self): """ Check if there is a previous calculation ID. If yes, read the inputs by retrieving the previous calculation; if not, read the inputs directly. """ oq = self.oqparam if 'gmfs' in oq.inputs or 'multi_peril' in oq.inputs: # read...
[ "def", "pre_execute", "(", "self", ")", ":", "oq", "=", "self", ".", "oqparam", "if", "'gmfs'", "in", "oq", ".", "inputs", "or", "'multi_peril'", "in", "oq", ".", "inputs", ":", "# read hazard from files", "assert", "not", "oq", ".", "hazard_calculation_id",...
47.306667
0.000552
def read_default_config(self): """Read the default config file. :raises DefaultConfigValidationError: There was a validation error with the *default* file. """ if self.validate: self.default_config = ConfigObj(configspec=self.def...
[ "def", "read_default_config", "(", "self", ")", ":", "if", "self", ".", "validate", ":", "self", ".", "default_config", "=", "ConfigObj", "(", "configspec", "=", "self", ".", "default_file", ",", "list_values", "=", "False", ",", "_inspec", "=", "True", ",...
48.12
0.00163
def time_limited(limit_seconds, iterable): """ Yield items from *iterable* until *limit_seconds* have passed. >>> from time import sleep >>> def generator(): ... yield 1 ... yield 2 ... sleep(0.2) ... yield 3 >>> iterable = generator() >>> list(time_limited(0.1, ...
[ "def", "time_limited", "(", "limit_seconds", ",", "iterable", ")", ":", "if", "limit_seconds", "<", "0", ":", "raise", "ValueError", "(", "'limit_seconds must be positive'", ")", "start_time", "=", "monotonic", "(", ")", "for", "item", "in", "iterable", ":", "...
30.892857
0.001121
def show_tree(self, cachelim=np.inf): """Cachelim is in Mb. For any cached jacobians above cachelim, they are also added to the graph. """ import tempfile import subprocess assert DEBUG, "Please use dr tree visualization functions in debug mode" def string_for(self, my_name): ...
[ "def", "show_tree", "(", "self", ",", "cachelim", "=", "np", ".", "inf", ")", ":", "import", "tempfile", "import", "subprocess", "assert", "DEBUG", ",", "\"Please use dr tree visualization functions in debug mode\"", "def", "string_for", "(", "self", ",", "my_name",...
48.865854
0.005382
def get_electricity_info(self, apart_id, meter_room): """get electricity info :param apart_id: 栋数 :param meter_room: 宿舍号 """ apart_id = str(apart_id) meter_room = str(meter_room) try: content = LifeService._get_electricity_info_html(apart_id, ...
[ "def", "get_electricity_info", "(", "self", ",", "apart_id", ",", "meter_room", ")", ":", "apart_id", "=", "str", "(", "apart_id", ")", "meter_room", "=", "str", "(", "meter_room", ")", "try", ":", "content", "=", "LifeService", ".", "_get_electricity_info_htm...
33.285714
0.003128
def debug_query_result(rows: Sequence[Any]) -> None: """Writes a query result to the log.""" log.info("Retrieved {} rows", len(rows)) for i in range(len(rows)): log.info("Row {}: {}", i, rows[i])
[ "def", "debug_query_result", "(", "rows", ":", "Sequence", "[", "Any", "]", ")", "->", "None", ":", "log", ".", "info", "(", "\"Retrieved {} rows\"", ",", "len", "(", "rows", ")", ")", "for", "i", "in", "range", "(", "len", "(", "rows", ")", ")", "...
42.2
0.004651
def json_update(self, json_str, exclude=[], ignore_non_defaults=True): """ Updates a database object based on a json object. The intent of this method is to allow passing json to an interface which then subsequently manipulates the object and then sends back an update. ...
[ "def", "json_update", "(", "self", ",", "json_str", ",", "exclude", "=", "[", "]", ",", "ignore_non_defaults", "=", "True", ")", ":", "update_dict", "=", "json", ".", "loads", "(", "json_str", ",", "cls", "=", "MongoliaJSONDecoder", ",", "encoding", "=", ...
52.333333
0.005291
def _update_cd_drives(drives_old_new, controllers=None, parent=None): ''' Returns a list of vim.vm.device.VirtualDeviceSpec specifying to edit a deployed cd drive configuration to the new given config drives_old_new Dictionary with old and new keys which contains the current and the nex...
[ "def", "_update_cd_drives", "(", "drives_old_new", ",", "controllers", "=", "None", ",", "parent", "=", "None", ")", ":", "cd_changes", "=", "[", "]", "if", "drives_old_new", ":", "devs", "=", "[", "drive", "[", "'old'", "]", "[", "'adapter'", "]", "for"...
43.02439
0.001663
def cnst_A0T(self, Y0): r"""Compute :math:`A_0^T \mathbf{y}_0` component of :math:`A^T \mathbf{y}` (see :meth:`.ADMMTwoBlockCnstrnt.cnst_AT`). """ # This calculation involves non-negligible computational cost. It # should be possible to disable relevant diagnostic information ...
[ "def", "cnst_A0T", "(", "self", ",", "Y0", ")", ":", "# This calculation involves non-negligible computational cost. It", "# should be possible to disable relevant diagnostic information", "# (dual residual) to avoid this cost.", "Y0f", "=", "sl", ".", "rfftn", "(", "Y0", ",", ...
45.833333
0.005348
def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): """Create a GridIn property.""" def getter(self): if closed_only and not self._closed: raise AttributeError("can only get %r on a closed file" % field_name...
[ "def", "_grid_in_property", "(", "field_name", ",", "docstring", ",", "read_only", "=", "False", ",", "closed_only", "=", "False", ")", ":", "def", "getter", "(", "self", ")", ":", "if", "closed_only", "and", "not", "self", ".", "_closed", ":", "raise", ...
40.678571
0.000858
def cli(env, abuse, address1, address2, city, company, country, firstname, lastname, postal, public, state): """Edit the RWhois data on the account.""" mgr = SoftLayer.NetworkManager(env.client) update = { 'abuse_email': abuse, 'address1': address1, 'address2': address2, ...
[ "def", "cli", "(", "env", ",", "abuse", ",", "address1", ",", "address2", ",", "city", ",", "company", ",", "country", ",", "firstname", ",", "lastname", ",", "postal", ",", "public", ",", "state", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManage...
29.133333
0.001107
def _exec_calcs(calcs, parallelize=False, client=None, **compute_kwargs): """Execute the given calculations. Parameters ---------- calcs : Sequence of ``aospy.Calc`` objects parallelize : bool, default False Whether to submit the calculations in parallel or not client : distributed.Clie...
[ "def", "_exec_calcs", "(", "calcs", ",", "parallelize", "=", "False", ",", "client", "=", "None", ",", "*", "*", "compute_kwargs", ")", ":", "if", "parallelize", ":", "def", "func", "(", "calc", ")", ":", "\"\"\"Wrap _compute_or_skip_on_error to require only the...
39.289474
0.000654
def plot_cbv(self, ax, flux, info, show_cbv=False): ''' Plots the final CBV-corrected light curve. ''' # Plot the light curve bnmask = np.array( list(set(np.concatenate([self.badmask, self.nanmask]))), dtype=int) def M(x): return np.delete(x, bnmask) ...
[ "def", "plot_cbv", "(", "self", ",", "ax", ",", "flux", ",", "info", ",", "show_cbv", "=", "False", ")", ":", "# Plot the light curve", "bnmask", "=", "np", ".", "array", "(", "list", "(", "set", "(", "np", ".", "concatenate", "(", "[", "self", ".", ...
39.382979
0.001054
def _translate_port(port): ''' Look into services and return the port value using the service name as lookup value. ''' services = _get_services_mapping() if port in services and services[port]['port']: return services[port]['port'][0] return port
[ "def", "_translate_port", "(", "port", ")", ":", "services", "=", "_get_services_mapping", "(", ")", "if", "port", "in", "services", "and", "services", "[", "port", "]", "[", "'port'", "]", ":", "return", "services", "[", "port", "]", "[", "'port'", "]",...
30.555556
0.003534
def clear(self, omit_item_evicted=False): """Empty the cache and optionally invoke item_evicted callback.""" if not omit_item_evicted: items = self._dict.items() for key, value in items: self._evict_item(key, value) self._dict.clear()
[ "def", "clear", "(", "self", ",", "omit_item_evicted", "=", "False", ")", ":", "if", "not", "omit_item_evicted", ":", "items", "=", "self", ".", "_dict", ".", "items", "(", ")", "for", "key", ",", "value", "in", "items", ":", "self", ".", "_evict_item"...
41.714286
0.006711
def get_epublication(self): """ Returns: EPublication: Structure when the object :meth:`is_valid`. Raises: MetaParsingException: When the object is not valid. """ if not self.is_valid(): bad_fields = filter(lambda x: not x.is_valid(), self.fie...
[ "def", "get_epublication", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", "(", ")", ":", "bad_fields", "=", "filter", "(", "lambda", "x", ":", "not", "x", ".", "is_valid", "(", ")", ",", "self", ".", "fields", ")", "bad_fields", "=", ...
33.833333
0.002394
def QA_indicator_ADTM(DataFrame, N=23, M=8): '动态买卖气指标' HIGH = DataFrame.high LOW = DataFrame.low OPEN = DataFrame.open DTM = IF(OPEN > REF(OPEN, 1), MAX((HIGH - OPEN), (OPEN - REF(OPEN, 1))), 0) DBM = IF(OPEN < REF(OPEN, 1), MAX((OPEN - LOW), (OPEN - REF(OPEN, 1))), 0) STM = SUM(DTM, N) ...
[ "def", "QA_indicator_ADTM", "(", "DataFrame", ",", "N", "=", "23", ",", "M", "=", "8", ")", ":", "HIGH", "=", "DataFrame", ".", "high", "LOW", "=", "DataFrame", ".", "low", "OPEN", "=", "DataFrame", ".", "open", "DTM", "=", "IF", "(", "OPEN", ">", ...
34.866667
0.001862
def fit(self, y): """Estimate censoring distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as ...
[ "def", "fit", "(", "self", ",", "y", ")", ":", "event", ",", "time", "=", "check_y_survival", "(", "y", ")", "if", "event", ".", "all", "(", ")", ":", "self", ".", "unique_time_", "=", "numpy", ".", "unique", "(", "time", ")", "self", ".", "prob_...
33.041667
0.003676
def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False): """Return dict of response received from Twitter's API :param endpoint: (required) Full url or Twitter API endpoint (e.g. search/tweets) :type endpoint: string :param meth...
[ "def", "request", "(", "self", ",", "endpoint", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "version", "=", "'1.1'", ",", "json_encoded", "=", "False", ")", ":", "if", "endpoint", ".", "startswith", "(", "'http://'", ")", ":", "raise"...
41.810811
0.003159
def get_prev_step(self, step=None): """ Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically. """ if step is None: step = se...
[ "def", "get_prev_step", "(", "self", ",", "step", "=", "None", ")", ":", "if", "step", "is", "None", ":", "step", "=", "self", ".", "steps", ".", "current", "form_list", "=", "self", ".", "get_form_list", "(", ")", "key", "=", "form_list", ".", "keyO...
38.307692
0.003922
def _load_multipoint(tokens, string): """ Has similar inputs and return value to to :func:`_load_point`, except is for handling MULTIPOINT geometry. :returns: A GeoJSON `dict` MultiPoint representation of the WKT ``string``. """ open_paren = next(tokens) if not open_paren == '(': ...
[ "def", "_load_multipoint", "(", "tokens", ",", "string", ")", ":", "open_paren", "=", "next", "(", "tokens", ")", "if", "not", "open_paren", "==", "'('", ":", "raise", "ValueError", "(", "INVALID_WKT_FMT", "%", "string", ")", "coords", "=", "[", "]", "pt...
26.95122
0.000873
def make_relative (self, other): """Return a new path that is the equivalent of this one relative to the path *other*. Unlike :meth:`relative_to`, this will not throw an error if *self* is not a sub-path of *other*; instead, it will use ``..`` to build a relative path. This can result in...
[ "def", "make_relative", "(", "self", ",", "other", ")", ":", "if", "self", ".", "is_absolute", "(", ")", ":", "return", "self", "from", "os", ".", "path", "import", "relpath", "other", "=", "self", ".", "__class__", "(", "other", ")", "return", "self",...
42.0625
0.017442
def _subtoken_to_tokens(self, subtokens): """ Converts a list of subtoken to a list of tokens. Args: subtokens: a list of integers in the range [0, vocab_size) Returns: a list of strings. """ concatenated = "".join(subtokens) split = concatenated.spl...
[ "def", "_subtoken_to_tokens", "(", "self", ",", "subtokens", ")", ":", "concatenated", "=", "\"\"", ".", "join", "(", "subtokens", ")", "split", "=", "concatenated", ".", "split", "(", "\"_\"", ")", "return", "[", "_unescape_token", "(", "t", "+", "\"_\"",...
31.5
0.005141
def read(cls, proto): """ Reads deserialized data from proto object :param proto: (DynamicStructBuilder) Proto object :return (SparseNet) SparseNet instance """ sparsenet = object.__new__(cls) sparsenet.filterDim = proto.filterDim sparsenet.outputDim = proto.outputDim ...
[ "def", "read", "(", "cls", ",", "proto", ")", ":", "sparsenet", "=", "object", ".", "__new__", "(", "cls", ")", "sparsenet", ".", "filterDim", "=", "proto", ".", "filterDim", "sparsenet", ".", "outputDim", "=", "proto", ".", "outputDim", "sparsenet", "."...
33.27907
0.003394
def find_button(browser, value): """ Find a button with the given value. Searches for the following different kinds of buttons: <input type="submit"> <input type="reset"> <input type="button"> <input type="image"> <button> <{a,p,div,span,...} role="button"> ...
[ "def", "find_button", "(", "browser", ",", "value", ")", ":", "field_types", "=", "(", "'submit'", ",", "'reset'", ",", "'button-element'", ",", "'button'", ",", "'image'", ",", "'button-role'", ",", ")", "return", "reduce", "(", "operator", ".", "add", ",...
21.827586
0.001513
def get_full_durable_object(arn, event_time, durable_model): """ Utility method to fetch items from the Durable table if they are too big for SNS/SQS. :param record: :param durable_model: :return: """ LOG.debug(f'[-->] Item with ARN: {arn} was too big for SNS -- fetching it from the Durable...
[ "def", "get_full_durable_object", "(", "arn", ",", "event_time", ",", "durable_model", ")", ":", "LOG", ".", "debug", "(", "f'[-->] Item with ARN: {arn} was too big for SNS -- fetching it from the Durable table...'", ")", "item", "=", "list", "(", "durable_model", ".", "q...
45.15
0.008677
def expand_gallery(generator, metadata): """ Expand a gallery tag to include all of the files in a specific directory under IMAGE_PATH :param pelican: The pelican instance :return: None """ if "gallery" not in metadata or metadata['gallery'] is None: return # If no gallery specified, we do...
[ "def", "expand_gallery", "(", "generator", ",", "metadata", ")", ":", "if", "\"gallery\"", "not", "in", "metadata", "or", "metadata", "[", "'gallery'", "]", "is", "None", ":", "return", "# If no gallery specified, we do nothing", "lines", "=", "[", "]", "base_pa...
49.966667
0.003927
def _get_import_name(importnode, modname): """Get a prepared module name from the given import node In the case of relative imports, this will return the absolute qualified module name, which might be useful for debugging. Otherwise, the initial module name is returned unchanged. """ if isi...
[ "def", "_get_import_name", "(", "importnode", ",", "modname", ")", ":", "if", "isinstance", "(", "importnode", ",", "astroid", ".", "ImportFrom", ")", ":", "if", "importnode", ".", "level", ":", "root", "=", "importnode", ".", "root", "(", ")", "if", "is...
37.9375
0.001608
def _GetConfigValue(self, config_parser, section_name, value_name): """Retrieves a value from the config parser. Args: config_parser (ConfigParser): configuration parser. section_name (str): name of the section that contains the value. value_name (str): name of the value. Returns: ...
[ "def", "_GetConfigValue", "(", "self", ",", "config_parser", ",", "section_name", ",", "value_name", ")", ":", "try", ":", "return", "config_parser", ".", "get", "(", "section_name", ",", "value_name", ")", "except", "configparser", ".", "NoOptionError", ":", ...
33.466667
0.005814
def get_weekly_chart_dates(self): """Returns a list of From and To tuples for the available charts.""" doc = self._request(self.ws_prefix + ".getWeeklyChartList", True) seq = [] for node in doc.getElementsByTagName("chart"): seq.append((node.getAttribute("from"), node.getAt...
[ "def", "get_weekly_chart_dates", "(", "self", ")", ":", "doc", "=", "self", ".", "_request", "(", "self", ".", "ws_prefix", "+", "\".getWeeklyChartList\"", ",", "True", ")", "seq", "=", "[", "]", "for", "node", "in", "doc", ".", "getElementsByTagName", "("...
34.6
0.005634
def remove(self, *terminals): # type: (Iterable[Any]) -> None """ Remove terminals from the set. Removes also rules using this terminal. :param terminals: Terminals to remove. :raise KeyError if the object is not in the set. """ for term in set(terminals):...
[ "def", "remove", "(", "self", ",", "*", "terminals", ")", ":", "# type: (Iterable[Any]) -> None", "for", "term", "in", "set", "(", "terminals", ")", ":", "if", "term", "not", "in", "self", ":", "raise", "KeyError", "(", "'Terminal '", "+", "str", "(", "t...
40.571429
0.006885
async def fetch_page(session, host): """ Perform the page fetch from an individual host. `session` - An aiohttp [client session](http://aiohttp.readthedocs.io/en/stable/client_reference.html#client-session) `host` - URL to fetch `return` tuple with the following: * The host parameter ...
[ "async", "def", "fetch_page", "(", "session", ",", "host", ")", ":", "await", "asyncio", ".", "sleep", "(", "random", ".", "randint", "(", "0", ",", "25", ")", "*", "0.1", ")", "start", "=", "time", ".", "time", "(", ")", "logger", ".", "info", "...
39.183673
0.002541
def save(self, file_path, note_df): ''' Save MIDI file. Args: file_path: File path of MIDI. note_df: `pd.DataFrame` of note data. ''' chord = pretty_midi.PrettyMIDI() for program in note_df.program.drop_duplicates().v...
[ "def", "save", "(", "self", ",", "file_path", ",", "note_df", ")", ":", "chord", "=", "pretty_midi", ".", "PrettyMIDI", "(", ")", "for", "program", "in", "note_df", ".", "program", ".", "drop_duplicates", "(", ")", ".", "values", ".", "tolist", "(", ")...
37.777778
0.00478
def read_numbers(numbers): """ Read the input data in the most optimal way """ if isiterable(numbers): for number in numbers: yield float(str(number).strip()) else: with open(numbers) as fh: for number in fh: yield float(number.strip())
[ "def", "read_numbers", "(", "numbers", ")", ":", "if", "isiterable", "(", "numbers", ")", ":", "for", "number", "in", "numbers", ":", "yield", "float", "(", "str", "(", "number", ")", ".", "strip", "(", ")", ")", "else", ":", "with", "open", "(", "...
27.454545
0.003205
def scale(self, scalar, ignored_terms=None): """Multiply the polynomial by the given scalar. Args: scalar (number): Value to multiply the polynomial by. ignored_terms (iterable, optional): Biases associated with these terms are not scaled. ...
[ "def", "scale", "(", "self", ",", "scalar", ",", "ignored_terms", "=", "None", ")", ":", "if", "ignored_terms", "is", "None", ":", "ignored_terms", "=", "set", "(", ")", "else", ":", "ignored_terms", "=", "{", "asfrozenset", "(", "term", ")", "for", "t...
28.5
0.003396
def routes_collector(gatherer): """Decorator utility to collect flask routes in a dictionary. This function together with :func:`add_routes` provides an easy way to split flask routes declaration in multiple modules. :param gatherer: dict in which will be collected routes The decorator provided b...
[ "def", "routes_collector", "(", "gatherer", ")", ":", "def", "hatFunc", "(", "rule", ",", "*", "*", "options", ")", ":", "def", "decorator", "(", "f", ")", ":", "rule_dict", "=", "{", "'rule'", ":", "rule", ",", "'view_func'", ":", "f", "}", "rule_di...
33.413793
0.005015
def _results(self, connection, msgid): """ Returns the result of a previous asynchronous query. """ try: kind, results = connection.result(msgid) if kind != ldap.RES_SEARCH_RESULT: results = [] except ldap.LDAPError as e: result...
[ "def", "_results", "(", "self", ",", "connection", ",", "msgid", ")", ":", "try", ":", "kind", ",", "results", "=", "connection", ".", "result", "(", "msgid", ")", "if", "kind", "!=", "ldap", ".", "RES_SEARCH_RESULT", ":", "results", "=", "[", "]", "...
33.846154
0.004425
def _one_diagonal_capture_square(self, capture_square, position): """ Adds specified diagonal as a capture move if it is one """ if self.contains_opposite_color_piece(capture_square, position): if self.would_move_be_promotion(): for move in self.create_promot...
[ "def", "_one_diagonal_capture_square", "(", "self", ",", "capture_square", ",", "position", ")", ":", "if", "self", ".", "contains_opposite_color_piece", "(", "capture_square", ",", "position", ")", ":", "if", "self", ".", "would_move_be_promotion", "(", ")", ":",...
44.571429
0.006279
def bit_string_index(s): """Return the index of a string of 0s and 1s.""" n = len(s) k = s.count("1") if s.count("0") != n - k: raise VisualizationError("s must be a string of 0 and 1") ones = [pos for pos, char in enumerate(s) if char == "1"] return lex_index(n, k, ones)
[ "def", "bit_string_index", "(", "s", ")", ":", "n", "=", "len", "(", "s", ")", "k", "=", "s", ".", "count", "(", "\"1\"", ")", "if", "s", ".", "count", "(", "\"0\"", ")", "!=", "n", "-", "k", ":", "raise", "VisualizationError", "(", "\"s must be ...
37.125
0.003289
def lineage(expr, container=Stack): """Yield the path of the expression tree that comprises a column expression. Parameters ---------- expr : Expr An ibis expression. It must be an instance of :class:`ibis.expr.types.ColumnExpr`. container : Container, {Stack, Queue} Sta...
[ "def", "lineage", "(", "expr", ",", "container", "=", "Stack", ")", ":", "if", "not", "isinstance", "(", "expr", ",", "ir", ".", "ColumnExpr", ")", ":", "raise", "TypeError", "(", "'Input expression must be an instance of ColumnExpr'", ")", "c", "=", "containe...
30.093023
0.000749
def _backlog(self, data): """Find all the datagrepper messages between 'then' and 'now'. Put those on our work queue. Should be called in a thread so as not to block the hub at startup. """ try: data = json.loads(data) except ValueError as e: se...
[ "def", "_backlog", "(", "self", ",", "data", ")", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "data", ")", "except", "ValueError", "as", "e", ":", "self", ".", "log", ".", "info", "(", "\"Status contents are %r\"", "%", "data", ")", "sel...
36.378378
0.001447
def off(self, event): 'Remove an event handler' try: self._once_events.remove(event) except KeyError: pass self._callback_by_event.pop(event, None)
[ "def", "off", "(", "self", ",", "event", ")", ":", "try", ":", "self", ".", "_once_events", ".", "remove", "(", "event", ")", "except", "KeyError", ":", "pass", "self", ".", "_callback_by_event", ".", "pop", "(", "event", ",", "None", ")" ]
28.142857
0.009852
def scan_path(executable="mongod"): """Scan the path for a binary. """ for path in os.environ.get("PATH", "").split(":"): path = os.path.abspath(path) executable_path = os.path.join(path, executable) if os.path.exists(executable_path): return executable_path
[ "def", "scan_path", "(", "executable", "=", "\"mongod\"", ")", ":", "for", "path", "in", "os", ".", "environ", ".", "get", "(", "\"PATH\"", ",", "\"\"", ")", ".", "split", "(", "\":\"", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(",...
37.375
0.003268
def ReadCronJobRuns(self, job_id, cursor=None): """Reads all cron job runs for a given job id.""" query = """ SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs WHERE job_id = %s """ cursor.execute(query, [job_id]) runs = [self._CronJobRunFromRow(row) for row in cursor.fetchall...
[ "def", "ReadCronJobRuns", "(", "self", ",", "job_id", ",", "cursor", "=", "None", ")", ":", "query", "=", "\"\"\"\n SELECT run, UNIX_TIMESTAMP(write_time)\n FROM cron_job_runs\n WHERE job_id = %s\n \"\"\"", "cursor", ".", "execute", "(", "query", ",", "[", ...
38.4
0.002545
def notify_program_learners(cls, enterprise_customer, program_details, users): """ Notify learners about a program in which they've been enrolled. Args: enterprise_customer: The EnterpriseCustomer being linked to program_details: Details about the specific program the le...
[ "def", "notify_program_learners", "(", "cls", ",", "enterprise_customer", ",", "program_details", ",", "users", ")", ":", "program_name", "=", "program_details", ".", "get", "(", "'title'", ")", "program_branding", "=", "program_details", ".", "get", "(", "'type'"...
43.208333
0.002829
def export_fits(dataset, path, column_names=None, shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True): """ :param DatasetLocal dataset: dataset to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for all column...
[ "def", "export_fits", "(", "dataset", ",", "path", ",", "column_names", "=", "None", ",", "shuffle", "=", "False", ",", "selection", "=", "False", ",", "progress", "=", "None", ",", "virtual", "=", "True", ",", "sort", "=", "None", ",", "ascending", "=...
46.180328
0.003128
def index(self): """ Index all files/directories below the current BIDSNode. """ config_list = self.config layout = self.layout for (dirpath, dirnames, filenames) in os.walk(self.path): # If layout configuration file exists, delete it layout_file = self.layout....
[ "def", "index", "(", "self", ")", ":", "config_list", "=", "self", ".", "config", "layout", "=", "self", ".", "layout", "for", "(", "dirpath", ",", "dirnames", ",", "filenames", ")", "in", "os", ".", "walk", "(", "self", ".", "path", ")", ":", "# I...
39.797468
0.000621
def submit(self, command='sleep 1', blocksize=1, job_name="parsl.auto"): """Submit command to an Azure instance. Submit returns an ID that corresponds to the task that was just submitted. Parameters ---------- command : str Command to be invoked on the remote side. ...
[ "def", "submit", "(", "self", ",", "command", "=", "'sleep 1'", ",", "blocksize", "=", "1", ",", "job_name", "=", "\"parsl.auto\"", ")", ":", "job_name", "=", "\"parsl.auto.{0}\"", ".", "format", "(", "time", ".", "time", "(", ")", ")", "[", "instance", ...
33.8
0.00493
def get_redirect(self): """ Returns the previous url. """ index_url = self.appbuilder.get_url_for_index page_history = Stack(session.get("page_history", [])) if page_history.pop() is None: return index_url session["page_history"] = page_history.to...
[ "def", "get_redirect", "(", "self", ")", ":", "index_url", "=", "self", ".", "appbuilder", ".", "get_url_for_index", "page_history", "=", "Stack", "(", "session", ".", "get", "(", "\"page_history\"", ",", "[", "]", ")", ")", "if", "page_history", ".", "pop...
31.75
0.005102
def index_blockchain(self, block_start, block_end): """ Go through the sequence of zone files discovered in a block range, and reindex the names' subdomains. """ log.debug("Processing subdomain updates for zonefiles in blocks {}-{}".format(block_start, block_end)) res = ...
[ "def", "index_blockchain", "(", "self", ",", "block_start", ",", "block_end", ")", ":", "log", ".", "debug", "(", "\"Processing subdomain updates for zonefiles in blocks {}-{}\"", ".", "format", "(", "block_start", ",", "block_end", ")", ")", "res", "=", "self", "...
47.7
0.010288
def __score_method(X, y, fcounts, model_generator, score_function, method_name, nreps=10, test_size=100, cache_dir="/tmp"): """ Test an explanation method. """ old_seed = np.random.seed() np.random.seed(3293) # average the method scores over several train/test splits method_reps = [] data...
[ "def", "__score_method", "(", "X", ",", "y", ",", "fcounts", ",", "model_generator", ",", "score_function", ",", "method_name", ",", "nreps", "=", "10", ",", "test_size", "=", "100", ",", "cache_dir", "=", "\"/tmp\"", ")", ":", "old_seed", "=", "np", "."...
45.12
0.00564
def token_validate_with_login(self, **kwargs): """ Authenticate a user with a TMDb username and password. The user must have a verified email address and be registered on TMDb. Args: request_token: The token you generated for the user to approve. username: The u...
[ "def", "token_validate_with_login", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_path", "(", "'token_validate_with_login'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_at...
36
0.003008
def changes(self, target_version=None, nodes=None, labels=None): """Sync up (and down) all changes. Args: target_version (str): The local change version. nodes (List[dict]): A list of nodes to sync up to the server. labels (List[dict]): A list of labels to sync up to...
[ "def", "changes", "(", "self", ",", "target_version", "=", "None", ",", "nodes", "=", "None", ",", "labels", "=", "None", ")", ":", "if", "nodes", "is", "None", ":", "nodes", "=", "[", "]", "if", "labels", "is", "None", ":", "labels", "=", "[", "...
35.333333
0.005986