text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cursor(self): """The position of the cursor in the text."""
if self._cursor < 0: self.cursor = 0 if self._cursor > len(self): self.cursor = len(self) return self._cursor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_one_letter(self, letter=RIGHT): """Delete one letter the right or the the left of the cursor."""
assert letter in (self.RIGHT, self.LEFT) if letter == self.LEFT: papy = self.cursor self.text = self.text[:self.cursor - 1] + self.text[self.cursor:] self.cursor = papy - 1 else: self.text = self.text[:self.cursor] + self.text[self.cursor + 1:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_one_word(self, word=RIGHT): """Delete one word the right or the the left of the cursor."""
assert word in (self.RIGHT, self.LEFT) if word == self.RIGHT: papy = self.text.find(' ', self.cursor) + 1 if not papy: papy = len(self.text) self.text = self.text[:self.cursor] + self.text[papy:] else: papy = self.text.rfind(' '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_letter(self, letter): """Add a letter at the cursor pos."""
assert isinstance(letter, str) assert len(letter) == 1 self.text = self.text[:self.cursor] + letter + self.text[self.cursor:] self.cursor += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, event_or_list): """Update the text and position of cursor according to the event passed."""
event_or_list = super().update(event_or_list) for e in event_or_list: if e.type == KEYDOWN: if e.key == K_RIGHT: if e.mod * KMOD_CTRL: self.move_cursor_one_word(self.RIGHT) else: self.m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shawn_text(self): """The text displayed instead of the real one."""
if len(self._shawn_text) == len(self): return self._shawn_text if self.style == self.DOTS: return chr(0x2022) * len(self) ranges = [ (902, 1366), (192, 683), (33, 122) ] s = '' while len(s) < len(self.text):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cursor_pos(self): """The cursor position in pixels."""
if len(self) == 0: return self.left + self.default_text.get_width() papy = self._surface.get_width() if papy > self.w: shift = papy - self.width else: shift = 0 return self.left + self.font.size(self.shawn_text[:self.cursor])[0] - shift
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def latex_to_img(tex): """Return a pygame image from a latex template."""
with tempfile.TemporaryDirectory() as tmpdirname: with open(tmpdirname + r'\tex.tex', 'w') as f: f.write(tex) os.system(r"latex {0}\tex.tex -halt-on-error -interaction=batchmode -disable-installer -aux-directory={0} " r"-output-directory={0}".forma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name2rgb(name): """Convert the name of a color into its RGB value"""
try: import colour except ImportError: raise ImportError('You need colour to be installed: pip install colour') c = colour.Color(name) color = int(c.red * 255), int(c.green * 255), int(c.blue * 255) return color
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_page(page): """Parse the command man page."""
colors = get_config()['colors'] with io.open(page, encoding='utf-8') as f: lines = f.readlines() output_lines = [] for line in lines[1:]: if is_headline(line): continue elif is_description(line): output_lines.append(click.style(line.replace('>', ' '), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure_logging(level=logging.DEBUG): """Configure the module logging engine."""
if level == logging.DEBUG: # For debugging purposes, log from everyone! logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s' ) return logging logger = logging.getLogger(__name__) logger.setLevel(level) form...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_username_password_hostname(remote_url): """ Parse a command line string and return username, password, remote hostname and remote path. :param remote_u...
assert remote_url assert ':' in remote_url if '@' in remote_url: username, hostname = remote_url.rsplit('@', 1) else: username, hostname = None, remote_url hostname, remote_path = hostname.split(':', 1) password = None if username and ':' in username: username, pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ssh_agent_keys(logger): """ Ask the SSH agent for a list of keys, and return it. :return: A reference to the SSH agent and a list of keys. """
agent, agent_keys = None, None try: agent = paramiko.agent.Agent() _agent_keys = agent.get_keys() if not _agent_keys: agent.close() logger.error( "SSH agent didn't provide any valid key. Trying to continue..." ) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_parser(): """Create the CLI argument parser."""
parser = argparse.ArgumentParser( description='Sync a local and a remote folder through SFTP.' ) parser.add_argument( "path", type=str, metavar="local-path", help="the path of the local folder", ) parser.add_argument( "remote", type=str, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(args=None): """The main."""
parser = create_parser() args = vars(parser.parse_args(args)) log_mapping = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET': logging.NOTSET, } log_level = log_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _must_be_deleted(local_path, r_st): """Return True if the remote correspondent of local_path has to be deleted. i.e. if it doesn't exists locally or if it ha...
# if the file doesn't exists if not os.path.lexists(local_path): return True # or if the file type is different l_st = os.lstat(local_path) if S_IFMT(r_st.st_mode) != S_IFMT(l_st.st_mode): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_upload(self, local_path, remote_path, l_st): """Upload local_path to remote_path and set permission and mtime."""
self.sftp.put(local_path, remote_path) self._match_modes(remote_path, l_st)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remote_delete(self, remote_path, r_st): """Remove the remote directory node."""
# If it's a directory, then delete content and directory if S_ISDIR(r_st.st_mode): for item in self.sftp.listdir_attr(remote_path): full_path = path_join(remote_path, item.filename) self.remote_delete(full_path, item) self.sftp.rmdir(remote_path) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_deletion(self, relative_path=None): """Traverse the entire remote_path tree. Find files/directories that need to be deleted, not being present in t...
if not relative_path: relative_path = str() # root of shared directory tree remote_path = path_join(self.remote_path, relative_path) local_path = path_join(self.local_path, relative_path) for remote_st in self.sftp.listdir_attr(remote_path): r_lstat = self.sft...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_update_symlink(self, link_destination, remote_path): """Create a new link pointing to link_destination in remote_path position."""
try: # if there's anything, delete it self.sftp.remove(remote_path) except IOError: # that's fine, nothing exists there! pass finally: # and recreate the link try: self.sftp.symlink(link_destination, remote_path) except OSError ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run the sync. Confront the local and the remote directories and perform the needed changes."""
# Check if remote path is present try: self.sftp.stat(self.remote_path) except FileNotFoundError as e: if self.create_remote_directory: self.sftp.mkdir(self.remote_path) self.logger.info( "Created missing remote dir: '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_files(start_path): """tree unix command replacement."""
s = u'\n' for root, dirs, files in os.walk(start_path): level = root.replace(start_path, '').count(os.sep) indent = ' ' * 4 * level s += u'{}{}/\n'.format(indent, os.path.basename(root)) sub_indent = ' ' * 4 * (level + 1) for f in files: s += u'{}{}\n'.format...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_tree(start_path): """ Create a nested dictionary that represents the folder structure of `start_path`. Liberally adapted from http://code.activestate.co...
nested_dirs = {} root_dir = start_path.rstrip(os.sep) start = root_dir.rfind(os.sep) + 1 for path, dirs, files in os.walk(root_dir): folders = path[start:].split(os.sep) subdir = dict.fromkeys(files) parent = reduce(dict.get, folders[:-1], nested_dirs) parent[folders[-1]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capture_sys_output(): """Capture standard output and error."""
capture_out, capture_err = StringIO(), StringIO() current_out, current_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = capture_out, capture_err yield capture_out, capture_err finally: sys.stdout, sys.stderr = current_out, current_err
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def suppress_logging(log_level=logging.CRITICAL): """Suppress logging."""
logging.disable(log_level) yield logging.disable(logging.NOTSET)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def override_env_variables(): """Override user environmental variables with custom one."""
env_vars = ("LOGNAME", "USER", "LNAME", "USERNAME") old = [os.environ[v] if v in os.environ else None for v in env_vars] for v in env_vars: os.environ[v] = "test" yield for i, v in enumerate(env_vars): if old[i]: os.environ[v] = old[i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(): """Get the configurations from .tldrrc and return it as a dict."""
config_path = path.join( (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')), '.tldrrc') if not path.exists(config_path): sys.exit("Can't find config file at: {0}. You may use `tldr init` " "to init the config file.".format(config_path)) with io.open(config...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_man_page(command, platform): """Parse the man page and return the parsed lines."""
page_path = find_page_location(command, platform) output_lines = parse_page(page_path) return output_lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_page_location(command, specified_platform): """Find the command man page in the pages directory."""
repo_directory = get_config()['repo_directory'] default_platform = get_config()['platform'] command_platform = ( specified_platform if specified_platform else default_platform) with io.open(path.join(repo_directory, 'pages/index.json'), encoding='utf-8') as f: index = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(command, on): """Find the command usage."""
output_lines = parse_man_page(command, on) click.echo(''.join(output_lines))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(): """Update to the latest pages."""
repo_directory = get_config()['repo_directory'] os.chdir(repo_directory) click.echo("Check for updates...") local = subprocess.check_output('git rev-parse master'.split()).strip() remote = subprocess.check_output( 'git ls-remote https://github.com/tldr-pages/tldr/ HEAD'.split() ).split...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(): """Init config file."""
default_config_path = path.join( (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')), '.tldrrc') if path.exists(default_config_path): click.echo("There is already a config file exists, " "skip initializing it.") else: repo_path = click.prompt("Inpu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def locate(command, on): """Locate the command's man page."""
location = find_page_location(command, on) click.echo(location)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_to(self, attrname, tablename=None, selectable=None, schema=None, base=None, mapper_args=util.immutabledict()): """Configure a mapping to the given attrna...
if attrname in self._cache: raise SQLSoupError( "Attribute '%s' is already mapped to '%s'" % ( attrname, class_mapper(self._cache[attrname]).mapped_table )) if tablename is not None: if not isinstance(tablename, basest...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map(self, selectable, base=None, **mapper_args): """Map a selectable directly. The class and its mapping are not cached and will be discarded once dereferenc...
return _class_for_table( self.session, self.engine, selectable, base or self.base, mapper_args )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_labels(self, selectable, base=None, **mapper_args): """Map a selectable directly, wrapping the selectable in a subquery with labels. The class and its m...
# TODO give meaningful aliases return self.map( expression._clause_element_as_expr(selectable). select(use_labels=True). alias('foo'), base=base, **mapper_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def left(self, f, n=1): """return the nearest n features strictly to the left of a Feature f. Overlapping features are not considered as to the left. f: a Featur...
intervals = self.intervals[f.chrom] if intervals == []: return [] iright = binsearch_left_start(intervals, f.start, 0 , len(intervals)) + 1 ileft = binsearch_left_start(intervals, f.start - self.max_len[f.chrom] - 1, 0, 0) results = sorted((distance(other, f), other) for othe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def right(self, f, n=1): """return the nearest n features strictly to the right of a Feature f. Overlapping features are not considered as to the right. f: a Fea...
intervals = self.intervals[f.chrom] ilen = len(intervals) iright = binsearch_right_end(intervals, f.end, 0, ilen) results = [] while iright < ilen: i = len(results) if i > n: if distance(f, results[i - 1]) != distance(f, results[i - 2]): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upstream(self, f, n=1): """find n upstream features where upstream is determined by the strand of the query Feature f Overlapping features are not considered...
if f.strand == -1: return self.right(f, n) return self.left(f, n)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def downstream(self, f, n=1): """find n downstream features where downstream is determined by the strand of the query Feature f Overlapping features are not cons...
if f.strand == -1: return self.left(f, n) return self.right(f, n)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sequence(db, chrom, start, end): """ return the sequence for a region using the UCSC DAS server. note the start is 1-based each feature will have it's own .s...
url = "http://genome.ucsc.edu/cgi-bin/das/%s" % db url += "/dna?segment=%s:%i,%i" xml = U.urlopen(url % (chrom, start, end)).read() return _seq_from_xml(xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_table(genome, table, table_name, connection_string, metadata): """ alter the table to work between different dialects """
table = Table(table_name, genome._metadata, autoload=True, autoload_with=genome.bind, extend_existing=True) #print "\t".join([c.name for c in table.columns]) # need to prefix the indexes with the table name to avoid collisions for i, idx in enumerate(table.indexes): idx.nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mirror(self, tables, dest_url): """ miror a set of `tables` from `dest_url` Returns a new Genome object Parameters tables : list an iterable of tables dest_u...
from mirror import mirror return mirror(self, tables, dest_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataframe(self, table): """ create a pandas dataframe from a table or query Parameters table : table a table in this database or a query limit: integer an in...
from pandas import DataFrame if isinstance(table, six.string_types): table = getattr(self, table) try: rec = table.first() except AttributeError: rec = table[0] if hasattr(table, "all"): records = table.all() else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def david_go(refseq_list, annot=('SP_PIR_KEYWORDS', 'GOTERM_BP_FAT', 'GOTERM_CC_FAT', 'GOTERM_MF_FAT')): """ open a web-browser to the DAVID online enrichment to...
URL = "http://david.abcc.ncifcrf.gov/api.jsp?type=REFSEQ_MRNA&ids=%s&tool=term2term&annot=" import webbrowser webbrowser.open(URL % ",".join(set(refseq_list)) + ",".join(annot))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bin_query(self, table, chrom, start, end): """ perform an efficient spatial query using the bin column if available. The possible bins are calculated from th...
if isinstance(table, six.string_types): table = getattr(self, table) try: tbl = table._table except AttributeError: tbl = table.column_descriptions[0]['type']._table q = table.filter(tbl.c.chrom == chrom) if hasattr(tbl.c, "bin"): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upstream(self, table, chrom_or_feat, start=None, end=None, k=1): """ Return k-nearest upstream features Parameters table : str or table table against which t...
res = self.knearest(table, chrom_or_feat, start, end, k, "up") end = getattr(chrom_or_feat, "end", end) start = getattr(chrom_or_feat, "start", start) rev = getattr(chrom_or_feat, "strand", "+") == "-" if rev: return [x for x in res if x.end > start] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def knearest(self, table, chrom_or_feat, start=None, end=None, k=1, _direction=None): """ Return k-nearest features Parameters table : str or table table against...
assert _direction in (None, "up", "down") # they sent in a feature if start is None: assert end is None chrom, start, end = chrom_or_feat.chrom, chrom_or_feat.start, chrom_or_feat.end # if the query is directional and the feature as a strand, # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate(self, fname, tables, feature_strand=False, in_memory=False, header=None, out=sys.stdout, parallel=False): """ annotate a file with a number of table...
from .annotate import annotate return annotate(self, fname, tables, feature_strand, in_memory, header=header, out=out, parallel=parallel)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bins(start, end): """ Get all the bin numbers for a particular interval defined by (start, end] """
if end - start < 536870912: offsets = [585, 73, 9, 1] else: raise BigException offsets = [4681, 585, 73, 9, 1] binFirstShift = 17 binNextShift = 3 start = start >> binFirstShift end = (end - 1) >> binFirstShift bins = [1] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_filepath_in_roots(filename): """Look for filename in all MEDIA_ROOTS, and return the first one found."""
for root in settings.DJANGO_STATIC_MEDIA_ROOTS: filepath = _filename2filepath(filename, root) if os.path.isfile(filepath): return filepath, root # havent found it in DJANGO_STATIC_MEDIA_ROOTS look for apps' files if we're # in DEBUG mode if settings.DEBUG: try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_combine_filenames_generator(filenames, max_length=40): """Return a new filename to use as the combined file name for a bunch of files. A precondition...
path = None names = [] extension = None timestamps = [] for filename in filenames: name = os.path.basename(filename) if not extension: extension = os.path.splitext(name)[1] elif os.path.splitext(name)[1] != extension: raise ValueError("Can't combine m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlaps(self, other): """ check for overlap with the other interval """
if self.chrom != other.chrom: return False if self.start >= other.end: return False if other.start >= self.end: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_upstream_of(self, other): """ check if this is upstream of the `other` interval taking the strand of the other interval into account """
if self.chrom != other.chrom: return None if getattr(other, "strand", None) == "+": return self.end <= other.start # other feature is on - strand, so this must have higher start return self.start >= other.end
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gene_features(self): """ return a list of features for the gene features of this object. This would include exons, introns, utrs, etc. """
nm, strand = self.gene_name, self.strand feats = [(self.chrom, self.start, self.end, nm, strand, 'gene')] for feat in ('introns', 'exons', 'utr5', 'utr3', 'cdss'): fname = feat[:-1] if feat[-1] == 's' else feat res = getattr(self, feat) if res is None or all(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tss(self, up=0, down=0): """ Return a start, end tuple of positions around the transcription-start site Parameters up : int if greature than 0, the strand is...
if not self.is_gene_pred: return None tss = self.txEnd if self.strand == '-' else self.txStart start, end = tss, tss if self.strand == '+': start -= up end += down else: start += up end -= down start, end = end, start ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def promoter(self, up=2000, down=0): """ Return a start, end tuple of positions for the promoter region of this gene Parameters up : int this distance upstream t...
if not self.is_gene_pred: return None return self.tss(up=up, down=down)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cds(self): """just the parts of the exons that are translated"""
ces = self.coding_exons if len(ces) < 1: return ces ces[0] = (self.cdsStart, ces[0][1]) ces[-1] = (ces[-1][0], self.cdsEnd) assert all((s < e for s, e in ces)) return ces
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_downstream_of(self, other): """ return a boolean indicating whether this feature is downstream of `other` taking the strand of other into account """
if self.chrom != other.chrom: return None if getattr(other, "strand", None) == "-": # other feature is on - strand, so this must have higher start return self.end <= other.start return self.start >= other.end
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def utr5(self): """ return the 5' UTR if appropriate """
if not self.is_coding or len(self.exons) < 2: return (None, None) if self.strand == "+": s, e = (self.txStart, self.cdsStart) else: s, e = (self.cdsEnd, self.txEnd) if s == e: return (None, None) return s, e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sequence(self, per_exon=False): """ Return the sequence for this feature. if per-exon is True, return an array of exon sequences This sequence is never rever...
db = self.db if not per_exon: start = self.txStart + 1 return _sequence(db, self.chrom, start, self.txEnd) else: # TODO: use same strategy as cds_sequence to reduce # of requests. seqs = [] for start, end in self.exons: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ncbi_blast(self, db="nr", megablast=True, sequence=None): """ perform an NCBI blast against the sequence of this feature """
import requests requests.defaults.max_retries = 4 assert sequence in (None, "cds", "mrna") seq = self.sequence() if sequence is None else ("".join(self.cds_sequence if sequence == "cds" else self.mrna_sequence)) r = requests.post('http://blast.ncbi.nlm.nih.gov/Blast.cgi', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blat(self, db=None, sequence=None, seq_type="DNA"): """ make a request to the genome-browsers BLAT interface sequence is one of None, "mrna", "cds" returns a...
from . blat_blast import blat, blat_all assert sequence in (None, "cds", "mrna") seq = self.sequence() if sequence is None else ("".join(self.cds_sequence if sequence == "cds" else self.mrna_sequence)) if isinstance(db, (tuple, list)): return blat_all(seq, self.gene_name, db...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bed(self, *attrs, **kwargs): """ return a bed formatted string of this feature """
exclude = ("chrom", "start", "end", "txStart", "txEnd", "chromStart", "chromEnd") if self.is_gene_pred: return self.bed12(**kwargs) return "\t".join(map(str, ( [self.chrom, self.start, self.end] + [getattr(self, attr) for attr in att...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dereference_url(url): """ Makes a HEAD request to find the final destination of a URL after following any redirects """
res = open_url(url, method='HEAD') res.close() return res.url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(url, **kwargs): """ Read the contents of a URL into memory, return """
response = open_url(url, **kwargs) try: return response.read() finally: response.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_extracted_paths(namelist, subdir=None): """ Check whether zip file paths are all relative, and optionally in a specified subdirectory, raises an except...
def relpath(p): # relpath strips a trailing sep # Windows paths may also use unix sep q = os.path.relpath(p) if p.endswith(os.path.sep) or p.endswith('/'): q += os.path.sep return q parent = os.path.abspath('.') if subdir: if os.path.isabs(subdir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_local_path(path, overwrite, progress=0, httpuser=None, httppassword=None): """ Automatically handle local and remote URLs, files and directories path:...
m = re.match('([A-Za-z]+)://', path) if m: # url_open handles multiple protocols so don't bother validating log.debug('Detected URL protocol: %s', m.group(1)) # URL should use / as the pathsep localpath = path.split('/')[-1] if not localpath: raise FileExcep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(fs, channels, application): """Allocates and initializes an encoder state."""
result_code = ctypes.c_int() result = _create(fs, channels, application, ctypes.byref(result_code)) if result_code.value is not constants.OK: raise OpusError(result_code.value) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode(encoder, pcm, frame_size, max_data_bytes): """Encodes an Opus frame Returns string output payload """
pcm = ctypes.cast(pcm, c_int16_pointer) data = (ctypes.c_char * max_data_bytes)() result = _encode(encoder, pcm, frame_size, data, max_data_bytes) if result < 0: raise OpusError(result) return array.array('c', data[:result]).tostring()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_float(encoder, pcm, frame_size, max_data_bytes): """Encodes an Opus frame from floating point input"""
pcm = ctypes.cast(pcm, c_float_pointer) data = (ctypes.c_char * max_data_bytes)() result = _encode_float(encoder, pcm, frame_size, data, max_data_bytes) if result < 0: raise OpusError(result) return array.array('c', data[:result]).tostring()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def __parse_tostr(self, text, **kwargs): '''Builds and returns the MeCab function for parsing Unicode text. Args: fn_name: MeCab function name that determines the function behavior, either 'mecab_sparse_tostr' or 'mecab_nbest_sparse_tostr'. Returns: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse(self, text, **kwargs): '''Parse the given text and return result from MeCab. :param text: the text to parse. :type text: str :param as_nodes: return generator of MeCabNodes if True; or string if False. :type as_nodes: bool, defaults to False :param ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(tagGroups, terms): """ create Tag Groups and Child Tags using data from terms dict """
rv = [] for pid in tagGroups: # In testing we may not have complete set if pid not in terms.keys(): continue groupData = terms[pid] groupName = "[%s] %s" % (pid, groupData['name']) groupDesc = groupData['desc'] children = [] group = dict(nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_args(self, cmd, args): """ We need to support deprecated behaviour for now which makes this quite complicated Current behaviour: - install: Installs ...
if cmd == 'install': if args.upgrade: # Current behaviour: install or upgrade if args.initdb or args.upgradedb: raise Stop(10, ( 'Deprecated --initdb --upgradedb flags ' 'are incompatible with --upgr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_database(self): """ Handle database initialisation and upgrade, taking into account command line arguments """
# TODO: When initdb and upgradedb are dropped we can just test # managedb, but for backwards compatibility we need to support # initdb without upgradedb and vice-versa if self.args.initdb or self.args.upgradedb: db = DbAdmin(self.dir, None, self.args, self.external) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, command): """ Runs a command as if from the command-line without the need for using popen or subprocess """
if isinstance(command, basestring): command = command.split() else: command = list(command) self.external.omero_cli(command)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_schemas(schemas): """Sort a list of SQL schemas in order"""
def keyfun(v): x = SQL_SCHEMA_REGEXP.match(v).groups() # x3: 'DEV' should come before '' return (int(x[0]), x[1], int(x[2]) if x[2] else None, x[3] if x[3] else 'zzz', int(x[4])) return sorted(schemas, key=keyfun)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_schema_files(files): """ Parse a list of SQL files and return a dictionary of valid schema files where each key is a valid schema file and the correspo...
f_dict = {} for f in files: root, ext = os.path.splitext(f) if ext != ".sql": continue vto, vfrom = os.path.split(root) vto = os.path.split(vto)[1] if is_schema(vto) and is_schema(vfrom): f_dict[f] = (vfrom, vto) return f_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self): """ Dump the database using the postgres custom format """
dumpfile = self.args.dumpfile if not dumpfile: db, env = self.get_db_args_env() dumpfile = fileutils.timestamp_filename( 'omero-database-%s' % db['name'], 'pgdump') log.info('Dumping database to %s', dumpfile) if not self.args.dry_run: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_db_args_env(self): """ Get a dictionary of database connection parameters, and create an environment for running postgres commands. Falls back to omego d...
db = { 'name': self.args.dbname, 'host': self.args.dbhost, 'user': self.args.dbuser, 'pass': self.args.dbpass } if not self.args.no_db_config: try: c = self.external.get_config(force=True) except Except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def psql(self, *psqlargs): """ Run a psql command """
db, env = self.get_db_args_env() args = [ '-v', 'ON_ERROR_STOP=on', '-d', db['name'], '-h', db['host'], '-U', db['user'], '-w', '-A', '-t' ] + list(psqlargs) stdout, stderr = External.run('psql', args, capturestd=True, env...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pgdump(self, *pgdumpargs): """ Run a pg_dump command """
db, env = self.get_db_args_env() args = ['-d', db['name'], '-h', db['host'], '-U', db['user'], '-w' ] + list(pgdumpargs) stdout, stderr = External.run( 'pg_dump', args, capturestd=True, env=env) if stderr: log.warn('stderr: %s', stderr) l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_server_dir(self, dir): """ Set the directory of the server to be controlled """
self.dir = os.path.abspath(dir) config = os.path.join(self.dir, 'etc', 'grid', 'config.xml') self.configured = os.path.exists(config)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(self, force=False): """ Returns a dictionary of all config.xml properties If `force = True` then ignore any cached state and read config.xml if po...
if not force and not self.has_config(): raise Exception('No config file') configxml = os.path.join(self.dir, 'etc', 'grid', 'config.xml') if not os.path.exists(configxml): raise Exception('No config file') try: # Attempt to open config.xml read-only...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_omero_cli(self): """ Imports the omero CLI module so that commands can be run directly. Note Python does not allow a module to be imported multiple tim...
if not self.dir: raise Exception('No server directory set') if 'omero.cli' in sys.modules: raise Exception('omero.cli can only be imported once') log.debug("Setting up omero CLI") lib = os.path.join(self.dir, "lib", "python") if not os.path.exists(lib):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_previous_omero_env(self, olddir, savevarsfile): """ Create a copy of the current environment for interacting with the current OMERO server installation...
env = self.get_environment(savevarsfile) def addpath(varname, p): if not os.path.exists(p): raise Exception("%s does not exist!" % p) current = env.get(varname) if current: env[varname] = p + os.pathsep + current else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def omero_cli(self, command): """ Runs a command as if from the OMERO command-line without the need for using popen or subprocess. """
assert isinstance(command, list) if not self.cli: raise Exception('omero.cli not initialised') log.info("Invoking CLI [current environment]: %s", " ".join(command)) self.cli.invoke(command, strict=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(exe, args, capturestd=False, env=None): """ Runs an executable with an array of arguments, optionally in the specified environment. Returns stdout and st...
command = [exe] + args if env: log.info("Executing [custom environment]: %s", " ".join(command)) else: log.info("Executing : %s", " ".join(command)) start = time.time() # Temp files will be automatically deleted on close() # If run() throws the g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def string_support(py3enc): '''Create byte-to-string and string-to-byte conversion functions for internal use. :param py3enc: Encoding used by Python 3 environment. :type py3enc: str ''' if sys.version < '3': def bytes2str(b): '''Identity, returns the argument string (bytes)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def splitter_support(py2enc): '''Create tokenizer for use in boundary constraint parsing. :param py2enc: Encoding used by Python 2 environment. :type py2enc: str ''' if sys.version < '3': def _fn_sentence(pattern, sentence): if REGEXTYPE == type(pattern): if patt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upsert(self, doc, namespace, timestamp, update_spec=None): """Insert a document into Elasticsearch."""
index, doc_type = self._index_and_mapping(namespace) # No need to duplicate '_id' in source document doc_id = u(doc.pop("_id")) metadata = { 'ns': namespace, '_ts': timestamp } # Index the source document, using lowercase namespace as index name....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bulk_upsert(self, docs, namespace, timestamp): """Insert multiple documents into Elasticsearch."""
def docs_to_upsert(): doc = None for doc in docs: # Remove metadata and redundant _id index, doc_type = self._index_and_mapping(namespace) doc_id = u(doc.pop("_id")) document_action = { '_index': index, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, document_id, namespace, timestamp): """Remove a document from Elasticsearch."""
index, doc_type = self._index_and_mapping(namespace) action = { '_op_type': 'delete', '_index': index, '_type': doc_type, '_id': u(document_id) } meta_action = { '_op_type': 'delete', '_index': self.meta_index_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_buffered_operations(self): """Send buffered operations to Elasticsearch. This method is periodically called by the AutoCommitThread. """
with self.lock: try: action_buffer = self.BulkBuffer.get_buffer() if action_buffer: successes, errors = bulk(self.elastic, action_buffer) LOG.debug("Bulk request finished, successfully sent %d " "o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_last_doc(self): """Get the most recently modified document from Elasticsearch. This method is used to help define a time window within which documents ma...
try: result = self.elastic.search( index=self.meta_index_name, body={ "query": {"match_all": {}}, "sort": [{"_ts": "desc"}], }, size=1 )["hits"]["hits"] for r in result: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_type_signature(sig): """ Parse a type signature """
match = TYPE_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Type signature invalid, got ' + sig) groups = match.groups() typ = groups[0] generic_types = groups[1] if not generic_types: generic_types = [] else: generic_types = split_sig(generic_types[1:-1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_attr_signature(sig): """ Parse an attribute signature """
match = ATTR_SIG_RE.match(sig.strip()) if not match: raise RuntimeError('Attribute signature invalid, got ' + sig) name, _, params = match.groups() if params is not None and params.strip() != '': params = split_sig(params) params = [parse_param_signature(x) for x in params] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_msdn_ref(name): """ Try and create a reference to a type on MSDN """
in_msdn = False if name in MSDN_VALUE_TYPES: name = MSDN_VALUE_TYPES[name] in_msdn = True if name.startswith('System.'): in_msdn = True if in_msdn: link = name.split('<')[0] if link in MSDN_LINK_MAP: link = MSDN_LINK_MAP[link] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shorten_type(typ): """ Shorten a type. E.g. drops 'System.' """
offset = 0 for prefix in SHORTEN_TYPE_PREFIXES: if typ.startswith(prefix): if len(prefix) > offset: offset = len(prefix) return typ[offset:]