docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Get the retweeted Tweet OR the quoted Tweet and return it as a dictionary Args: tweet (Tweet): A Tweet object (not simply a dict) Returns: dict (or None, if the Tweet is neither a quote tweet or a Retweet): a dictionary representing the quote Tweet or the Retweet
def get_embedded_tweet(tweet): if tweet.retweeted_tweet is not None: return tweet.retweeted_tweet elif tweet.quoted_tweet is not None: return tweet.quoted_tweet else: return None
546,741
Simple checker to flag the format of a tweet. Args: tweet (Tweet): tweet in qustion Returns: Bool Example: >>> import tweet_parser.tweet_checking as tc >>> tweet = {"created_at": 124125125125, ... "text": "just setting up my twttr", ... "n...
def is_original_format(tweet): # deleted due to excess checking; it's a key lookup and does not need any # operational optimization if "created_at" in tweet: original_format = True elif "postedTime" in tweet: original_format = False else: raise NotATweetError("This dict ...
546,747
Validates the keys present in a Tweet. Args: tweet_keys_list (list): the keys present in a tweet superset_keys (set): the set of all possible keys for a tweet minset_keys (set): the set of minimal keys expected in a tweet. Returns: 0 if no errors Raises: Unexpected...
def key_validation_check(tweet_keys_list, superset_keys, minset_keys): # check for keys that must be present tweet_keys = set(tweet_keys_list) minset_overlap = tweet_keys & minset_keys if minset_overlap != minset_keys: raise UnexpectedFormatError("keys ({}) missing from Tweet (Public API da...
546,749
Ensures a tweet is valid and determines the type of format for the tweet. Args: tweet (dict/Tweet): the tweet payload validation_checking (bool): check for valid key structure in a tweet.
def check_tweet(tweet, validation_checking=False): if "id" not in tweet: raise NotATweetError("This text has no 'id' key") original_format = is_original_format(tweet) if original_format: _check_original_format_tweet(tweet, validation_checking=validation_checking) else: _c...
546,752
Get all of the text of the tweet. This includes @ mentions, long links, quote-tweet contents (separated by a newline), RT contents & poll options Args: tweet (Tweet): A Tweet object (must be a Tweet object) Returns: str: text from tweet.user_entered_text, tweet.quote_or_rt_text and ...
def get_all_text(tweet): if is_original_format(tweet): return "\n".join(filter(None, [tweet.user_entered_text, tweet.quote_or_rt_text, "\n".join(tweet.poll_options)])) else: return "\n".join(filter(None, [tweet.us...
546,757
Helper function to remove the links from the input text Args: text (str): A string Returns: str: the same text, but with any substring that matches the regex for a link removed and replaced with a space Example: >>> from tweet_parser.getter_methods.tweet_text import remove...
def remove_links(text): tco_link_regex = re.compile("https?://t.co/[A-z0-9].*") generic_link_regex = re.compile("(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*") remove_tco = re.sub(tco_link_regex, " ", text) remove_generic = re.sub(generic_link_regex, " ", remove_tco) return remove_generic
546,758
Retrieves the matching rules for a tweet with a gnip field enrichment. Args: tweet (Tweet): the tweet Returns: list: potential ``[{"tag": "user_tag", "value": "rule_value"}]`` pairs from standard rulesets or None if no rules or no matching_rules field is found. \n More...
def get_matching_rules(tweet): if is_original_format(tweet): rules = tweet.get("matching_rules") else: gnip = tweet.get("gnip") rules = gnip.get("matching_rules") if gnip else None return rules
546,759
For each url included in the Tweet "urls", get the most unrolled version available. Only return 1 url string per url in tweet.tweet_links In order of preference for "most unrolled" (keys from the dict at tweet.tweet_links): \n 1. `unwound`/`url` \n 2. `expanded_url` \n 3. `url` Args: ...
def get_most_unrolled_urls(tweet): unrolled_urls = [] for url in get_tweet_links(tweet): if url.get("unwound", {"url": None}).get("url", None) is not None: unrolled_urls.append(url["unwound"]["url"]) elif url.get("expanded_url", None) is not None: unrolled_urls.appen...
546,763
Decorator that makes a property lazy-evaluated whilst preserving docstrings. Args: fn (function): the property in question Returns: evaluated version of the property.
def lazy_property(fn): attr_name = '_lazy_' + fn.__name__ @property @wraps(fn) def _lazy_property(self): if not hasattr(self, attr_name): setattr(self, attr_name, fn(self)) return getattr(self, attr_name) return _lazy_property
546,766
Configures this extension with the given app. This registers an ``teardown_appcontext`` call, and attaches this ``LDAP3LoginManager`` to it as ``app.ldap3_login_manager``. Args: app (flask.Flask): The flask app to initialise with
def init_app(self, app): app.ldap3_login_manager = self servers = list(self._server_pool) for s in servers: self._server_pool.remove(s) self.init_config(app.config) if hasattr(app, 'teardown_appcontext'): app.teardown_appcontext(self.teardown)...
546,780
Configures this extension with a given configuration dictionary. This allows use of this extension without a flask app. Args: config (dict): A dictionary with configuration keys
def init_config(self, config): self.config.update(config) self.config.setdefault('LDAP_PORT', 389) self.config.setdefault('LDAP_HOST', None) self.config.setdefault('LDAP_USE_SSL', False) self.config.setdefault('LDAP_READONLY', True) self.config.setdefault('LDAP...
546,781
Add an additional server to the server pool and return the freshly created server. Args: hostname (str): Hostname of the server port (int): Port of the server use_ssl (bool): True if SSL is to be used when connecting. tls_ctx (ldap3.Tls): An optional TLS ...
def add_server(self, hostname, port, use_ssl, tls_ctx=None): if not use_ssl and tls_ctx: raise ValueError("Cannot specify a TLS context and not use SSL!") server = ldap3.Server( hostname, port=port, use_ssl=use_ssl, tls=tls_ctx ...
546,782
Add a connection to the appcontext so it can be freed/unbound at a later time if an exception occured and it was not freed. Args: connection (ldap3.Connection): Connection to add to the appcontext
def _contextualise_connection(self, connection): ctx = stack.top if ctx is not None: if not hasattr(ctx, 'ldap3_manager_connections'): ctx.ldap3_manager_connections = [connection] else: ctx.ldap3_manager_connections.append(connection)
546,783
Remove a connection from the appcontext. Args: connection (ldap3.Connection): connection to remove from the appcontext
def _decontextualise_connection(self, connection): ctx = stack.top if ctx is not None and connection in ctx.ldap3_manager_connections: ctx.ldap3_manager_connections.remove(connection)
546,784
An abstracted authentication method. Decides whether to perform a direct bind or a search bind based upon the login attribute configured in the config. Args: username (str): Username of the user to bind password (str): User's password to bind with. Returns: ...
def authenticate(self, username, password): if self.config.get('LDAP_BIND_DIRECT_CREDENTIALS'): result = self.authenticate_direct_credentials(username, password) elif not self.config.get('LDAP_ALWAYS_SEARCH_BIND') and \ self.config.get('LDAP_USER_RDN_ATTR') == \ ...
546,786
Performs a direct bind. We can do this since the RDN is the same as the login attribute. Hence we just string together a dn to find this user with. Args: username (str): Username of the user to bind (the field specified as LDAP_BIND_RDN_ATTR) password (st...
def authenticate_direct_bind(self, username, password): bind_user = '{rdn}={username},{user_search_dn}'.format( rdn=self.config.get('LDAP_USER_RDN_ATTR'), username=username, user_search_dn=self.full_user_search_dn, ) connection = self._make_connecti...
546,788
Gets info about a user specified at dn. Args: dn (str): The dn of the user to find _connection (ldap3.Connection): A connection object to use when searching. If not given, a temporary connection will be created, and destroyed after use. Returns: ...
def get_user_info(self, dn, _connection=None): return self.get_object( dn=dn, filter=self.config.get('LDAP_USER_OBJECT_FILTER'), attributes=self.config.get("LDAP_GET_USER_ATTRIBUTES"), _connection=_connection, )
546,791
Destroys a connection. Removes the connection from the appcontext, and unbinds it. Args: connection (ldap3.Connection): The connnection to destroy
def destroy_connection(self, connection): log.debug("Destroying connection at <{0}>".format(hex(id(connection)))) self._decontextualise_connection(connection) connection.unbind()
546,797
Returns: str: A DN with the DN Base appended to the end. Args: prepend (str): The dn to prepend to the base.
def compiled_sub_dn(self, prepend): prepend = prepend.strip() if prepend == '': return self.config.get('LDAP_BASE_DN') return '{prepend},{base}'.format( prepend=prepend, base=self.config.get('LDAP_BASE_DN') )
546,798
_write_to_zip: Write file to zip Args: path: (str) where in zip to write file contents: (str) contents of file to write Returns: None
def _write_to_zip(self, path, contents): if isinstance(path, list): path = os.path.sep.join(path) self.zf.writestr(path, contents)
547,844
add_channel: Creates channel metadata Args: source_id: (str) channel's unique id domain: (str) who is providing the content (e.g. learningequality.org) title: (str): name of channel language: (str): language code for channel (e.g. 'en') ...
def add_channel(self, title, source_id, domain, language, description=None, thumbnail=None): string_buffer = StringIO() writer = csv.writer(string_buffer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerow(['Title', 'Description', 'Domain', 'Source ID', 'Language',...
547,848
add_folder: Creates folder in csv Args: path: (str) where in zip to write folder title: (str) content's title source_id: (str) content's original id (optional) description: (str) description of content (optional) language (str):...
def add_folder(self, path, title, description=None, language=None, thumbnail=None, source_id=None, **node_data): self._parse_path(path) path = path if path.endswith(title) else "{}/{}".format(path, title) self._commit(path, title, description=description, language=language, thumbnail=th...
547,849
get_restore_path: returns path to directory for restoration points Args: filename (str): Name of file to store Returns: string path to file
def get_restore_path(filename): path = os.path.join(RESTORE_DIRECTORY, FILE_STORE_LOCATION) if not os.path.exists(path): os.makedirs(path) return os.path.join(path, filename + '.pickle')
547,894
open_channel_url: returns url to uploaded channel Args: channel (str): channel id of uploaded channel Returns: string url to open channel
def open_channel_url(channel, staging=False): return OPEN_CHANNEL_URL.format(domain=DOMAIN, channel_id=channel, access='staging' if staging or STAGE else 'edit')
547,895
Create a zip file with predictable sort order and metadata so that MD5 will stay consistent if zipping the same content twice. Args: path (str): absolute path either to a directory to zip up, or an existing zip file to convert. Returns: path (str) to the output zip file
def create_predictable_zip(path): # if path is a directory, recursively enumerate all the files under the directory if os.path.isdir(path): paths = [] for root, directories, filenames in os.walk(path): paths += [os.path.join(root, filename)[len(path)+1:] for filename in filenam...
547,899
Write the string `content` to `filename` in the open ZipFile `zfile`. Args: zfile (ZipFile): open ZipFile to write the content into filename (str): the file path within the zip file to write into content (str): the content to write into the zip Returns: None
def write_file_to_zip_with_neutral_metadata(zfile, filename, content): info = zipfile.ZipInfo(filename, date_time=(2015, 10, 21, 7, 28, 0)) info.compress_type = zipfile.ZIP_DEFLATED info.comment = "".encode() info.create_system = 0 zfile.writestr(info, content)
547,900
guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class
def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): if youtube_id: return FileTypes.YOUTUBE_VIDEO_FILE elif web_url: return FileTypes.WEB_VIDEO_FILE elif encoding: return FileTypes.BASE64_FILE else: ext = os.path.splitext(filepath)...
547,902
guess_content_kind: determines what kind the content is Args: files (str or list): files associated with content Returns: string indicating node's kind
def guess_content_kind(path=None, web_video_data=None, questions=None): # If there are any questions, return exercise if questions and len(questions) > 0: return content_kinds.EXERCISE # See if any files match a content kind if path: ext = os.path.splitext(path)[1][1:].lower() ...
547,903
set_images: Replace image strings with downloaded image checksums Args: text (str): text to parse for image strings Returns:string with checksums in place of image strings and list of files that were downloaded from string
def set_images(self, text, parse_html=True): # Set up return values and regex file_list = [] if parse_html: processed_string = self.parse_html(text) else: processed_string = text reg = re.compile(MARKDOWN_IMAGE_REGEX, flags=re.IGNORECASE) ...
547,913
parse_html: Properly formats any img tags that might be in content Args: text (str): text to parse Returns: string with properly formatted images
def parse_html(self, text): bs = BeautifulSoup(text, "html5lib") file_reg = re.compile(MARKDOWN_IMAGE_REGEX, flags=re.IGNORECASE) tags = bs.findAll('img') for tag in tags: # Look for src attribute, remove formatting if added to image src_text = tag.get("...
547,914
Save image resource at `text` (path or url) to storage, then return the replacement string and the necessary exercicse image file object. Args: - text (str): path or url to parse as an exercise image resource Returns: (new_text, files) - `new_text` (str): replacement string f...
def set_image(self, text): # Make sure `text` hasn't already been processed if exercises.CONTENT_STORAGE_PLACEHOLDER in text: return text, [] # Strip `text` of whitespace stripped_text = text.strip().replace('\\n', '') # If `stripped_text` is a web+graphie: p...
547,915
This function calls uploadchannel which performs all the run steps: - Create ChannelNode - Pupulate Tree with TopicNodes, ContentNodes, and associated File objects - . - .. - ... Args: args (dict): ricecooker command line arguments optio...
def run(self, args, options): self.pre_run(args, options) args_and_options = args.copy() args_and_options.update(options) uploadchannel(self, **args_and_options)
547,943
Call chef script's get_channel method in compatibility mode ...or... Create a `ChannelNode` from the Chef's `channel_info` class attribute. Args: kwargs (dict): additional keyword arguments that `uploadchannel` received Returns: channel created from get_channel method or Non...
def get_channel(self, **kwargs): if self.compatibility_mode: # For pre-sushibar scritps that do not implement `get_channel`, # we must check it this function exists before calling it... if hasattr(self.chef_module, 'get_channel'): config.LOGGER.info("...
547,944
Calls chef script's construct_channel method. Used only in compatibility mode. Args: kwargs (dict): additional keyword arguments that `uploadchannel` received Returns: channel populated from construct_channel method
def construct_channel(self, **kwargs): if self.compatibility_mode: # Constuct channel (using function from imported chef script) config.LOGGER.info("Populating channel... ") channel = self.chef_module.construct_channel(**kwargs) return channel els...
547,945
Open a ControlWebSocket to SushiBar server and listend for remote commands. Args: args (dict): chef command line arguments options (dict): additional compatibility mode options given on command line
def daemon_mode(self, args, options): cws = ControlWebSocket(self, args, options) cws.start() if 'cmdsock' in args and args['cmdsock']: lcs = LocalControlSocket(self, args, options) lcs.start() lcs.join() cws.join()
547,948
This function calls uploadchannel which performs all the run steps: Args: args (dict): chef command line arguments options (dict): additional compatibility mode options given on command line
def run(self, args, options): config.LOGGER.info('In SushiChef.run method. args=' + str(args) + 'options=' + str(options)) self.pre_run(args, options) uploadchannel_wrapper(self, args, options)
547,949
upload_files: uploads files to server Args: file_list (str): list of files to upload Returns: None
def upload_files(self, file_list): counter = 0 files_to_upload = list(set(file_list) - set(self.uploaded_files)) # In case restoring from previous session try: for f in files_to_upload: with open(config.get_storage_path(f), 'rb') as file_obj: ...
547,973
add_nodes: adds processed nodes to tree Args: root_id (str): id of parent node on Kolibri Studio current_node (Node): node to publish children indent (int): level of indentation for printing Returns: link to uploadedchannel
def add_nodes(self, root_id, current_node, indent=1): # if the current node has no children, no need to continue if not current_node.children: return config.LOGGER.info("({count} of {total} uploaded) {indent}Processing {title} ({kind})".format( count=self.node_c...
547,982
commit_channel: commits channel to Kolibri Studio Args: channel_id (str): channel's id on Kolibri Studio Returns: channel id and link to uploadedchannel
def commit_channel(self, channel_id): payload = { "channel_id":channel_id, "stage": config.STAGE, } response = config.SESSION.post(config.finish_channel_url(), data=json.dumps(payload)) if response.status_code != 200: config.LOGGER.error("\n\n...
547,983
publish: publishes tree to Kolibri Args: channel_id (str): channel's id on Kolibri Studio Returns: None
def publish(self, channel_id): payload = { "channel_id":channel_id, } response = config.SESSION.post(config.publish_channel_url(), data=json.dumps(payload)) response.raise_for_status()
547,984
check_for_session: see if session is in progress Args: status (str): step to check if last session reached (optional) Returns: boolean indicating if session exists
def check_for_session(self, status=None): status = Status.LAST if status is None else status return os.path.isfile(self.get_restore_path(status)) and os.path.getsize(self.get_restore_path(status)) > 0
547,988
get_restore_path: get path to restoration file Args: status (str): step to get restore file (optional) Returns: string path to restoration file
def get_restore_path(self, status=None): status = self.get_status() if status is None else status return config.get_restore_path(status.name.lower())
547,989
set_files: records progress from downloading files Args: files_downloaded ([str]): list of files that have been downloaded files_failed ([str]): list of files that failed to download Returns: None
def set_files(self, files_downloaded, files_failed): self.files_downloaded = files_downloaded self.files_failed = files_failed self.__record_progress(Status.GET_FILE_DIFF)
547,995
set_channel_created: records progress after creating channel on Kolibri Studio Args: channel_link (str): link to uploaded channel channel_id (str): id of channel that has been uploaded Returns: None
def set_channel_created(self, channel_link, channel_id): self.channel_link = channel_link self.channel_id = channel_id self.__record_progress(Status.PUBLISH_CHANNEL if config.PUBLISH else Status.DONE)
547,999
generate_key: generate key used for caching Args: action (str): how video is being processed (e.g. COMPRESSED or DOWNLOADED) path_or_id (str): path to video or youtube_id settings (dict): settings for compression or downloading passed in by user default (str): if ...
def generate_key(action, path_or_id, settings=None, default=" (default)"): settings = " {}".format(str(sorted(settings.items()))) if settings else default return "{}: {}{}".format(action.upper(), path_or_id, settings)
548,002
write_contents: Write contents to filename in zip Args: contents: (str) contents of file filename: (str) name of file in zip directory: (str) directory in zipfile to write file to (optional) Returns: path to file in zip
def write_contents(self, filename, contents, directory=None): filepath = "{}/{}".format(directory.rstrip("/"), filename) if directory else filename self._write_to_zipfile(filepath, contents) return filepath
548,144
write_file: Write local file to zip Args: filepath: (str) location to local file directory: (str) directory in zipfile to write file to (optional) Returns: path to file in zip Note: filepath must be a relative path
def write_file(self, filepath, filename=None, directory=None): arcname = None if filename or directory: directory = directory.rstrip("/") + "/" if directory else "" filename = filename or os.path.basename(filepath) arcname = "{}{}".format(directory, filename)...
548,145
write_url: Write contents from url to filename in zip Args: url: (str) url to file to download filename: (str) name of file in zip directory: (str) directory in zipfile to write file to (optional) Returns: path to file in zip
def write_url(self, url, filename, directory=None): return self.write_contents(filename, read(url), directory=directory)
548,146
create_initial_tree: Create initial tree structure Args: channel (Channel): channel to construct Returns: tree manager to run rest of steps
def create_initial_tree(channel): # Create channel manager with channel data config.LOGGER.info(" Setting up initial channel structure... ") tree = ChannelManager(channel) # Make sure channel structure is valid config.LOGGER.info(" Validating channel structure...") channel.print_tree()...
548,152
process_tree_files: Download files from nodes Args: tree (ChannelManager): manager to handle communication to Kolibri Studio Returns: None
def process_tree_files(tree): # Fill in values necessary for next steps config.LOGGER.info("Processing content...") files_to_diff = tree.process_tree(tree.channel) config.SUSHI_BAR_CLIENT.report_statistics(files_to_diff, topic_count=tree.channel.get_topic_count()) tree.check_for_files_failed() ...
548,153
get_file_diff: Download files from nodes Args: tree (ChannelManager): manager to handle communication to Kolibri Studio Returns: list of files that are not on Kolibri Studio
def get_file_diff(tree, files_to_diff): # Determine which files have not yet been uploaded to the CC server config.LOGGER.info("\nChecking if files exist on Kolibri Studio...") file_diff = tree.get_file_diff(files_to_diff) return file_diff
548,154
upload_files: Upload files to Kolibri Studio Args: tree (ChannelManager): manager to handle communication to Kolibri Studio file_diff ([str]): list of files to upload Returns: None
def upload_files(tree, file_diff): # Upload new files to CC config.LOGGER.info("\nUploading {0} new file(s) to Kolibri Studio...".format(len(file_diff))) tree.upload_files(file_diff) tree.reattempt_upload_fails() return file_diff
548,155
create_tree: Upload tree to Kolibri Studio Args: tree (ChannelManager): manager to handle communication to Kolibri Studio Returns: channel id of created channel and link to channel
def create_tree(tree): # Create tree config.LOGGER.info("\nCreating tree on Kolibri Studio...") channel_id, channel_link = tree.upload_tree() # channel_id, channel_link = tree.upload_channel_structure() return channel_link, channel_id
548,156
See: https://www.biostars.org/p/1816/ https://www.biostars.org/p/269579/ Args: resnum (int): angstroms (float): chain_id (str): model (Model): use_ca (bool): If the alpha-carbon atom should be used for the search, otherwise use the last atom of the residue custom_coo...
def within(resnum, angstroms, chain_id, model, use_ca=False, custom_coord=None): # XTODO: documentation # TODO: should have separate method for within a normal residue (can use "resnum" with a int) or a custom coord, # where you don't need to specify resnum atom_list = Selection.unfold_entities(mod...
548,160
Get a dictionary of a PDB file's sequences. Special cases include: - Insertion codes. In the case of residue numbers like "15A", "15B", both residues are written out. Example: 9LPR - HETATMs. Currently written as an "X", or unknown amino acid. Args: model: Biopython Model object of a S...
def get_structure_seqrecords(model): structure_seq_records = [] # Loop over each chain of the PDB for chain in model: tracker = 0 chain_seq = '' chain_resnums = [] # Loop over the residues for res in chain.get_residues(): # NOTE: you can get the re...
548,161
Get a dictionary of a PDB file's sequences. Special cases include: - Insertion codes. In the case of residue numbers like "15A", "15B", both residues are written out. Example: 9LPR - HETATMs. Currently written as an "X", or unknown amino acid. Args: pdb_file: Path to PDB file Retu...
def get_structure_seqs(pdb_file, file_type): # TODO: Please check out capitalization of chain IDs in mmcif files. example: 5afi - chain "l" is present but # it seems like biopython capitalizes it to chain L # Get the first model my_structure = StructureIO(pdb_file) model = my_structure.first_...
548,162
Retrieve and download PFAM results from the HMMER search tool. Args: seq: outpath: searchtype: force_rerun: Returns: Todo: * Document and test!
def manual_get_pfam_annotations(seq, outpath, searchtype='phmmer', force_rerun=False): if op.exists(outpath): with open(outpath, 'r') as f: json_results = json.loads(json.load(f)) else: fseq = '>Seq\n' + seq if searchtype == 'phmmer': parameters = {'seqdb': ...
548,190
Clean a pandas dataframe by: 1. Filling empty values with Nan 2. Dropping columns with all empty values Args: df: Pandas DataFrame fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN drop_empty_columns (bool): If columns whose values are all...
def clean_df(df, fill_nan=True, drop_empty_columns=True): if fill_nan: df = df.fillna(value=np.nan) if drop_empty_columns: df = df.dropna(axis=1, how='all') return df.sort_index()
548,192
Check if a parameter to be used is None, if it is, then check the specified backup attribute and throw an error if it is also None. Args: object: The original object setter: Any input object backup_attribute (str): Attribute in <object> to be double checked custom_error_text (st...
def double_check_attribute(object, setter, backup_attribute, custom_error_text=None): if not setter: next_checker = getattr(object, backup_attribute) if not next_checker: if custom_error_text: raise ValueError(custom_error_text) else: rais...
548,194
Split a file path into its folder, filename, and extension Args: path (str): Path to a file Returns: tuple: of (folder, filename (without extension), extension)
def split_folder_and_path(filepath): dirname = op.dirname(filepath) filename = op.basename(filepath) splitext = op.splitext(filename) filename_without_extension = splitext[0] extension = splitext[1] return dirname, filename_without_extension, extension
548,195
Decompress a gzip file and optionally set output values. Args: infile: Path to .gz file outfile: Name of output file outdir: Path to output directory delete_original: If original .gz file should be deleted force_rerun_flag: If file should be decompressed if outfile already e...
def gunzip_file(infile, outfile=None, outdir=None, delete_original=False, force_rerun_flag=False): if not outfile: outfile = infile.replace('.gz', '') if not outdir: outdir = '' else: outdir = op.dirname(infile) outfile = op.join(outdir, op.basename(outfile)) if force_...
548,198
Download a file given a URL if the outfile does not exist already. Args: link (str): Link to download file. outfile (str): Path to output file, will make a new file if it does not exist. Will not download if it does exist, unless force_rerun_flag is True. force_rerun_flag (bool)...
def request_file(link, outfile, force_rerun_flag=False): if force_rerun(flag=force_rerun_flag, outfile=outfile): req = requests.get(link) if req.status_code == 200: with open(outfile, 'w') as f: f.write(req.text) log.debug('Loaded and saved {} to {}'.form...
548,199
Download a file in JSON format from a web request Args: link: Link to web request outfile: Name of output file outdir: Directory of output file force_rerun_flag: If true, redownload the file Returns: dict: contents of the JSON request
def request_json(link, outfile, force_rerun_flag, outdir=None): if not outdir: outdir = '' outfile = op.join(outdir, outfile) if force_rerun(flag=force_rerun_flag, outfile=outfile): text_raw = requests.get(link) my_dict = text_raw.json() with open(outfile, 'w') as f: ...
548,200
Return the head of a dictionary. It will be random! Default is to return the first 5 key/value pairs in a dictionary. Args: d: Dictionary to get head. N: Number of elements to display. Returns: dict: the first N items of the dictionary.
def dict_head(d, N=5): return {k: d[k] for k in list(d.keys())[:N]}
548,204
Search a directory for files that match a pattern. Return an ordered list of these files by filename. Args: pattern: The glob pattern to search for. dir: Path to directory where the files will be searched for. descending: Default True, will sort alphabetically by descending order. Retu...
def rank_dated_files(pattern, dir, descending=True): files = glob.glob(op.join(dir, pattern)) return sorted(files, reverse=descending)
548,205
Return indices of a list which have elements that match an object or list of objects Args: lst: list of values a: object(s) to check equality case_sensitive: if the search should be case sensitive Returns: list: list of indicies of lst which equal a
def find(lst, a, case_sensitive=True): a = force_list(a) if not case_sensitive: lst = [x.lower() for x in lst] a = [y.lower() for y in a] return [i for i, x in enumerate(lst) if x in a]
548,206
Return a modified list removing items specified. Args: lst: Original list of values takeout: Object or objects to remove from lst case_sensitive: if the search should be case sensitive Returns: list: Filtered list of values
def filter_list(lst, takeout, case_sensitive=True): takeout = force_list(takeout) if not case_sensitive: lst = [x.lower() for x in lst] takeout = [y.lower() for y in takeout] return [x for x in lst if x not in takeout]
548,207
Return a modified list containing only the indices indicated. Args: lst: Original list of values indices: List of indices to keep from the original list Returns: list: Filtered list of values
def filter_list_by_indices(lst, indices): return [x for i, x in enumerate(lst) if i in indices]
548,208
Force a string representation of an object Args: val: object to parse into a string Returns: str: String representation
def force_string(val=None): if val is None: return '' if isinstance(val, list): newval = [str(x) for x in val] return ';'.join(newval) if isinstance(val, str): return val else: return str(val)
548,209
Force a list representation of an object Args: val: object to parse into a list Returns:
def force_list(val=None): if val is None: return [] if isinstance(val, pd.Series): return val.tolist() return val if isinstance(val, list) else [val]
548,210
Split a list into lists of size n. Args: l: List of stuff. n: Size of new lists. Returns: list: List of lists each of size n derived from l.
def split_list_by_n(l, n): n = max(1, n) return list(l[i:i+n] for i in range(0, len(l), n))
548,211
Always return a list of files with varying input. >>> input_list_parser(['/path/to/folder/']) ['/path/to/folder/file1.txt', '/path/to/folder/file2.txt', '/path/to/folder/file3.txt'] >>> input_list_parser(['/path/to/file.txt']) ['/path/to/file.txt'] >>> input_list_parser(['file1.txt']) ['file1...
def input_list_parser(infile_list): final_list_of_files = [] for x in infile_list: # If the input is a folder if op.isdir(x): os.chdir(x) final_list_of_files.extend(glob.glob('*')) # If the input is a file if op.isfile(x): final_list_o...
548,212
Make a single list out of a list of lists, and drop all duplicates. Args: list_of_lists: List of lists. Returns: list: List of single objects.
def flatlist_dropdup(list_of_lists): return list(set([str(item) for sublist in list_of_lists for item in sublist]))
548,213
Calculate combinations >>> list(combinations('ABCD',2)) [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'C'], ['B', 'D'], ['C', 'D']] >>> list(combinations(range(4), 3)) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]] Args: iterable: Any iterable object. r: Size of combination. Yield...
def combinations(iterable, r): pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield list(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: ...
548,214
Try to convert an arbitrary string to a float. Specify what will be replaced with "Inf". Args: indata (str): String which contains a float inf_str (str): If string contains something other than a float, and you want to replace it with float("Inf"), specify that string here. Re...
def conv_to_float(indata, inf_str=''): if indata.strip() == inf_str: outdata = float('Inf') else: try: outdata = float(indata) except: raise ValueError('Unable to convert {} to float'.format(indata)) return outdata
548,215
Input a list of labeled tuples and return a dictionary of sequentially labeled regions. Args: inlist (list): A list of tuples with the first number representing the index and the second the index label. Returns: dict: Dictionary of labeled regions. Examples: >>> label_sequential_...
def label_sequential_regions(inlist): import more_itertools as mit df = pd.DataFrame(inlist).set_index(0) labeled = {} for label in df[1].unique(): iterable = df[df[1] == label].index.tolist() labeled.update({'{}{}'.format(label, i + 1): items for i, items in ...
548,218
Provide pointers to the paths of the FASTA file Args: fasta_path: Path to FASTA file
def sequence_path(self, fasta_path): if not fasta_path: self.sequence_dir = None self.sequence_file = None else: if not op.exists(fasta_path): raise OSError('{}: file does not exist'.format(fasta_path)) if not op.dirname(fasta_pa...
548,229
Provide pointers to the paths of the metadata file Args: m_path: Path to metadata file
def metadata_path(self, m_path): if not m_path: self.metadata_dir = None self.metadata_file = None else: if not op.exists(m_path): raise OSError('{}: file does not exist!'.format(m_path)) if not op.dirname(m_path): ...
548,232
Load a GFF file with information on a single sequence and store features in the ``features`` attribute Args: gff_path: Path to GFF file.
def feature_path(self, gff_path): if not gff_path: self.feature_dir = None self.feature_file = None else: if not op.exists(gff_path): raise OSError('{}: file does not exist!'.format(gff_path)) if not op.dirname(gff_path): ...
548,235
Test if the sequence is equal to another SeqProp's sequence Args: seq_prop: SeqProp object Returns: bool: If the sequences are the same
def equal_to(self, seq_prop): if not self.seq or not seq_prop or not seq_prop.seq: return False return self.seq == seq_prop.seq
548,241
Write a FASTA file for the protein sequence, ``seq`` will now load directly from this file. Args: outfile (str): Path to new FASTA file to be written to force_rerun (bool): If an existing file should be overwritten
def write_fasta_file(self, outfile, force_rerun=False): if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile): SeqIO.write(self, outfile, "fasta") # The Seq as it will now be dynamically loaded from the file self.sequence_path = outfile
548,242
Write a GFF file for the protein features, ``features`` will now load directly from this file. Args: outfile (str): Path to new FASTA file to be written to force_rerun (bool): If an existing file should be overwritten
def write_gff_file(self, outfile, force_rerun=False): if ssbio.utils.force_rerun(outfile=outfile, flag=force_rerun): with open(outfile, "w") as out_handle: GFF.write([self], out_handle) self.feature_path = outfile
548,243
Add a feature to the features list describing a single residue. Args: resnum (int): Protein sequence residue number feat_type (str, optional): Optional description of the feature type (ie. 'catalytic residue') feat_id (str, optional): Optional ID of the feature type (ie. 'TM...
def add_point_feature(self, resnum, feat_type=None, feat_id=None, qualifiers=None): if self.feature_file: raise ValueError('Feature file associated with sequence, please remove file association to append ' 'additional features.') if not feat_type: ...
548,244
Add a feature to the features list describing a region of the protein sequence. Args: start_resnum (int): Start residue number of the protein sequence feature end_resnum (int): End residue number of the protein sequence feature feat_type (str, optional): Optional description...
def add_region_feature(self, start_resnum, end_resnum, feat_type=None, feat_id=None, qualifiers=None): if self.feature_file: raise ValueError('Feature file associated with sequence, please remove file association to append ' 'additional features.') if n...
548,245
Retrieve letter annotations for a residue or a range of residues Args: start_resnum (int): Residue number end_resnum (int): Optional residue number, specify if a range is desired Returns: dict: Letter annotations for this residue or residues
def get_residue_annotations(self, start_resnum, end_resnum=None): if not end_resnum: end_resnum = start_resnum # Create a new SeqFeature f = SeqFeature(FeatureLocation(start_resnum - 1, end_resnum)) # Get sequence properties return f.extract(self).letter_an...
548,252
Read the accpro20 output (.acc20) and return the parsed FASTA records. Keeps the spaces between the accessibility numbers. Args: infile: Path to .acc20 file Returns: dict: Dictionary of accessibilities with keys as the ID
def read_accpro20(infile): with open(infile) as f: records = f.read().splitlines() accpro20_dict = {} for i, r in enumerate(records): if i % 2 == 0: # TODO: Double check how to parse FASTA IDs (can they have a space because that is what i split by) # Key was ori...
548,258
Run SCRATCH on the sequence_file that was loaded into the class. Args: path_to_scratch: Path to the SCRATCH executable, run_SCRATCH-1D_predictors.sh outname: Prefix to name the output files outdir: Directory to store the output files force_rerun: Flag to force re...
def run_scratch(self, path_to_scratch, num_cores=1, outname=None, outdir=None, force_rerun=False): if not outname: outname = self.project_name if not outdir: outdir = '' outname = op.join(outdir, outname) self.out_sspro = '{}.ss'.format(outname) ...
548,260
Consolidated function to load a GEM using COBRApy. Specify the file type being loaded. Args: gem_file_path (str): Path to model file gem_file_type (str): GEM model type - ``sbml`` (or ``xml``), ``mat``, or ``json`` format Returns: COBRApy Model object.
def model_loader(gem_file_path, gem_file_type): if gem_file_type.lower() == 'xml' or gem_file_type.lower() == 'sbml': model = read_sbml_model(gem_file_path) elif gem_file_type.lower() == 'mat': model = load_matlab_model(gem_file_path) elif gem_file_type.lower() == 'json': model...
548,267
Input a COBRApy Gene object and check if the ID matches a spontaneous ID regex. Args: gene (Gene): COBRApy Gene custom_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: bool: If gene ID matches spontaneous ID
def is_spontaneous(gene, custom_id=None): spont = re.compile("[Ss](_|)0001") if spont.match(gene.id): return True elif gene.id == custom_id: return True else: return False
548,268
Return the DictList of genes that are not spontaneous in a model. Args: genes (DictList): Genes DictList custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: DictList: genes excluding ones that are spontaneous
def filter_out_spontaneous_genes(genes, custom_spont_id=None): new_genes = DictList() for gene in genes: if not is_spontaneous(gene, custom_id=custom_spont_id): new_genes.append(gene) return new_genes
548,269
Return the number of genes in a model ignoring spontaneously labeled genes. Args: model (Model): custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: int: Number of genes excluding spontaneous genes
def true_num_genes(model, custom_spont_id=None): true_num = 0 for gene in model.genes: if not is_spontaneous(gene, custom_id=custom_spont_id): true_num += 1 return true_num
548,270
Return the number of reactions associated with a gene. Args: model (Model): custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001`` Returns: int: Number of reactions associated with a gene
def true_num_reactions(model, custom_spont_id=None): true_num = 0 for rxn in model.reactions: if len(rxn.genes) == 0: continue if len(rxn.genes) == 1 and is_spontaneous(list(rxn.genes)[0], custom_id=custom_spont_id): continue else: true_num += 1 ...
548,271
Parse a FATCAT XML result file. Args: fatcat_xml (str): Path to FATCAT XML result file Returns: dict: Parsed information from the output Todo: - Only returning TM-score at the moment
def parse_fatcat(fatcat_xml): fatcat_results = {} # Parse output xml file with open(fatcat_xml, 'r') as f: soup = BeautifulSoup(f, 'lxml') # Find the tmScore of the alignment if soup.find('block'): fatcat_results['tm_score'] = float(soup.find('afpchain')['tmscore']) retur...
548,282
Attempt to get a rank-ordered list of available PDB structures for a BiGG Model and its gene. Args: bigg_model: BiGG Model ID bigg_gene: BiGG Gene ID Returns: list: rank-ordered list of tuples of (pdb_id, chain_id)
def get_pdbs_for_gene(bigg_model, bigg_gene, cache_dir=tempfile.gettempdir(), force_rerun=False): my_structures = [] # Download gene info gene = ssbio.utils.request_json(link='http://bigg.ucsd.edu/api/v2/models/{}/genes/{}'.format(bigg_model, bigg_gene), outfile='{}...
548,289
Summarize the secondary structure content of the DSSP dataframe for each chain. Args: dssp_df: Pandas DataFrame of parsed DSSP results Returns: dict: Chain to secondary structure summary dictionary
def secondary_structure_summary(dssp_df): chains = dssp_df.chain.unique() infodict = {} for chain in chains: expoinfo = defaultdict(int) chain_df = dssp_df[dssp_df.chain == chain] counts = chain_df.ss.value_counts() total = float(len(chain_df)) for ss, count in...
548,292
Define the secondary structure class of a PDB file at the specific chain Args: pdb_file: dssp_file: chain: Returns:
def get_ss_class(pdb_file, dssp_file, chain): prag = pr.parsePDB(pdb_file) pr.parseDSSP(dssp_file, prag) alpha, threeTen, beta = get_dssp_ss_content_multiplechains(prag, chain) if alpha == 0 and beta > 0: classification = 'all-beta' elif beta == 0 and alpha > 0: classification ...
548,296
Check if a string is a valid UniProt ID. See regex from: http://www.uniprot.org/help/accession_numbers Args: instring: any string identifier Returns: True if the string is a valid UniProt ID
def is_valid_uniprot_id(instring): valid_id = re.compile("[OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2}") if valid_id.match(str(instring)): return True else: return False
548,298
Check if a single UniProt ID is reviewed or not. Args: uniprot_id: Returns: bool: If the entry is reviewed
def uniprot_reviewed_checker(uniprot_id): query_string = 'id:' + uniprot_id uni_rev_raw = StringIO(bsup.search(query_string, columns='id,reviewed', frmt='tab')) uni_rev_df = pd.read_table(uni_rev_raw, sep='\t', index_col=0) uni_rev_df = uni_rev_df.fillna(False) uni_rev_df = uni_rev_df[pd.notn...
548,299
Batch check if uniprot IDs are reviewed or not Args: uniprot_ids: UniProt ID or list of UniProt IDs Returns: A dictionary of {UniProtID: Boolean}
def uniprot_reviewed_checker_batch(uniprot_ids): uniprot_ids = ssbio.utils.force_list(uniprot_ids) invalid_ids = [i for i in uniprot_ids if not is_valid_uniprot_id(i)] uniprot_ids = [i for i in uniprot_ids if is_valid_uniprot_id(i)] if invalid_ids: warnings.warn("Invalid UniProt IDs {} wi...
548,300
Retrieve the EC number annotation for a UniProt ID. Args: uniprot_id: Valid UniProt ID Returns:
def uniprot_ec(uniprot_id): r = requests.post('http://www.uniprot.org/uniprot/?query=%s&columns=ec&format=tab' % uniprot_id) ec = r.content.decode('utf-8').splitlines()[1] if len(ec) == 0: ec = None return ec
548,301