INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Match mod utime and uid/ gid with locals one. | def _match_modes(self, remote_path, l_st):
"""Match mod, utime and uid/gid with locals one."""
self.sftp.chmod(remote_path, S_IMODE(l_st.st_mode))
self.sftp.utime(remote_path, (l_st.st_atime, l_st.st_mtime))
if self.chown:
self.sftp.chown(remote_path, l_st.st_uid, l_st.st_gi... |
Upload local_path to remote_path and set permission and mtime. | 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) |
Remove the remote directory node. | 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)
... |
Traverse the entire remote_path tree. | 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 the local folder.
"""
if not relative_path:
relative_path = str() # root of shared directory tree
... |
Create a new link pointing to link_destination in remote_path position. | 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
... |
Check if the given directory tree node has to be uploaded/ created on the remote folder. | def node_check_for_upload_create(self, relative_path, f):
"""Check if the given directory tree node has to be uploaded/created on the remote folder."""
if not relative_path:
# we're at the root of the shared directory tree
relative_path = str()
# the (absolute) local add... |
Traverse the relative_path tree and check for files that need to be uploaded/ created. | def check_for_upload_create(self, relative_path=None):
"""Traverse the relative_path tree and check for files that need to be uploaded/created.
Relativity here refers to the shared directory tree."""
for f in os.listdir(
path_join(
self.local_path, relative_path) if ... |
Run the sync. | 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:
... |
tree unix command replacement. | 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 * (... |
Create a nested dictionary that represents the folder structure of start_path. | def file_tree(start_path):
"""
Create a nested dictionary that represents the folder structure of `start_path`.
Liberally adapted from
http://code.activestate.com/recipes/577879-create-a-nested-dictionary-from-oswalk/
"""
nested_dirs = {}
root_dir = start_path.rstrip(os.sep)
start = roo... |
Capture standard output and error. | 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, sy... |
Suppress logging. | def suppress_logging(log_level=logging.CRITICAL):
"""Suppress logging."""
logging.disable(log_level)
yield
logging.disable(logging.NOTSET) |
Override user environmental variables with custom one. | 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_... |
Override the $SSH_AUTH_SOCK env variable to mock the absence of an SSH agent. | def override_ssh_auth_env():
"""Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent."""
ssh_auth_sock = "SSH_AUTH_SOCK"
old_ssh_auth_sock = os.environ.get(ssh_auth_sock)
del os.environ[ssh_auth_sock]
yield
if old_ssh_auth_sock:
os.environ[ssh_auth_sock] = ol... |
Get the configurations from. tldrrc and return it as a dict. | 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` "
... |
Parse the man page and return the parsed lines. | 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 |
Find the command man page in the pages directory. | 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 ... |
Find the command usage. | def find(command, on):
"""Find the command usage."""
output_lines = parse_man_page(command, on)
click.echo(''.join(output_lines)) |
Update to the latest pages. | 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://gi... |
Init config file. | 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:... |
Locate the command s man page. | def locate(command, on):
"""Locate the command's man page."""
location = find_page_location(command, on)
click.echo(location) |
Produce a relationship between this mapped table and another one. This makes usage of SQLAlchemy s: func: sqlalchemy. orm. relationship construct. | def relate(cls, propname, *args, **kwargs):
"""Produce a relationship between this mapped table and another
one.
This makes usage of SQLAlchemy's :func:`sqlalchemy.orm.relationship`
construct.
"""
class_mapper(cls)._configure_property(propname, relation... |
Execute a SQL statement. | def execute(self, stmt, **params):
"""Execute a SQL statement.
The statement may be a string SQL string,
an :func:`sqlalchemy.sql.expression.select` construct, or a
:func:`sqlalchemy.sql.expression.text`
construct.
"""
return self.session.execute(sql.text(stmt... |
Configure a mapping to the given attrname. | def map_to(self, attrname, tablename=None, selectable=None,
schema=None, base=None, mapper_args=util.immutabledict()):
"""Configure a mapping to the given attrname.
This is the "master" method that can be used to create any
configuration.
:param attrname: String a... |
Map a selectable directly. | 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 dereferenced (as of 0.6.6).
:param selectable: an :func:`.expression.select` construct.
:param base: a Python class which will ... |
Map a selectable directly wrapping the selectable in a subquery with labels. | 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 mapping are not cached and will
be discarded once dereferenced (as of 0.6.6).
:param selectable: an :func:`.expressio... |
Create an: func:. expression. join and map to it. | def join(self, left, right, onclause=None, isouter=False,
base=None, **mapper_args):
"""Create an :func:`.expression.join` and map to it.
The class and its mapping are not cached and will
be discarded once dereferenced (as of 0.6.6).
:param left: a mapped class or tabl... |
Return the named entity from this: class:. SQLSoup or create if not present. | def entity(self, attr, schema=None):
"""Return the named entity from this :class:`.SQLSoup`, or
create if not present.
For more generalized mapping, see :meth:`.map_to`.
"""
try:
return self._cache[attr]
except KeyError, ke:
return self.map_to(a... |
\ Distance between 2 features. The integer result is always positive or zero. If the features overlap or touch it is zero. >>> from intersecter import Feature distance >>> distance ( Feature ( 1 2 ) Feature ( 12 13 )) 10 >>> distance ( Feature ( 1 2 ) Feature ( 2 3 )) 0 >>> distance ( Feature ( 1 100 ) Feature ( 20 30 ... | def distance(f1, f2):
"""\
Distance between 2 features. The integer result is always positive or zero.
If the features overlap or touch, it is zero.
>>> from intersecter import Feature, distance
>>> distance(Feature(1, 2), Feature(12, 13))
10
>>> distance(Feature(1, 2), Feature(2, 3))
0
... |
Return a object of all stored intervals intersecting between ( start end ) inclusive. | def find(self, start, end, chrom=None):
"""Return a object of all stored intervals intersecting between (start, end) inclusive."""
intervals = self.intervals[chrom]
ilen = len(intervals)
# NOTE: we only search for starts, since any feature that starts within max_len of
# the quer... |
return the nearest n features strictly to the left of a Feature f. Overlapping features are not considered as to the left. | 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 Feature object
n: the number of features to return
"""
intervals = self.intervals[f.chrom]
if intervals == [... |
return the nearest n features strictly to the right of a Feature f. Overlapping features are not considered as to the right. | 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 Feature object
n: the number of features to return
"""
intervals = self.intervals[f.chrom]
ilen = len(int... |
find n upstream features where upstream is determined by the strand of the query Feature f Overlapping features are not considered. | 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.
f: a Feature object
n: the number of features to return
"""
if f.strand == -1:
return se... |
find n downstream features where downstream is determined by the strand of the query Feature f Overlapping features are not considered. | 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 considered.
f: a Feature object
n: the number of features to return
"""
if f.strand == -1:
ret... |
return the n nearest neighbors to the given feature f: a Feature object k: the number of features to return | def knearest(self, f_or_start, end=None, chrom=None, k=1):
"""return the n nearest neighbors to the given feature
f: a Feature object
k: the number of features to return
"""
if end is not None:
f = Feature(f_or_start, end, chrom=chrom)
else:
f = ... |
find all elements between ( or overlapping ) start and end | def find(self, start, end):
"""find all elements between (or overlapping) start and end"""
if self.intervals and not end < self.intervals[0].start:
overlapping = [i for i in self.intervals if i.end >= start
and i.start <= end]
else:... |
return the sequence for a region using the UCSC DAS server. note the start is 1 - based each feature will have it s own. sequence method which sends the correct start and end to this function. | 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 .sequence method which sends
the correct start and end to this function.
>>> sequence('hg18', 'chr2', 2223, 2230)
'caacttag'
"""... |
alter the table to work between different dialects | 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 tab... |
internal: create a dburl from a set of parameters or the defaults on this object | def create_url(self, db="", user="genome", host="genome-mysql.cse.ucsc.edu",
password="", dialect="mysqldb"):
"""
internal: create a dburl from a set of parameters or the defaults on
this object
"""
if os.path.exists(db):
db = "sqlite:///" + db
# Is t... |
miror a set of tables from dest_url | 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_url: str
a dburl string, e.g. 'sqlite:///local.db'
"""
... |
create a pandas dataframe from a table or query | 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 integer limit on the query
offset: integer
an offset f... |
use some of the machinery in pandas to load a file into a table | def load_file(self, fname, table=None, sep="\t", bins=False, indexes=None):
"""
use some of the machinery in pandas to load a file into a table
Parameters
----------
fname : str
filename or filehandle to load
table : str
table to load the file t... |
open a web - browser to the DAVID online enrichment tool | 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 tool
Parameters
----------
refseq_list : list
list of refseq names ... |
perform an efficient spatial query using the bin column if available. The possible bins are calculated from the start and end sent to this function. | 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 the `start` and `end` sent to
this function.
Parameters
----------
table : str or table
tabl... |
Return k - nearest upstream features | 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 to query
chrom_or_feat : str or feat
either a chromosome, e.g. 'chr3' or a... |
Return k - nearest features | 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 which to query
chrom_or_feat : str or feat
either a chromoso... |
annotate a file with a number of tables | 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 tables
Parameters
----------
fname : str or file
file name or file-handle
tables : list
... |
Get all the bin numbers for a particular interval defined by ( start end ] | 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... |
write a bed12 file of the query. Parameters ---------- | def save_bed(cls, query, filename=sys.stdout):
"""
write a bed12 file of the query.
Parameters
----------
query : query
a table or query to save to file
filename : file
string or filehandle to write output
"""
out = _open(filename... |
For example: { % staticfile/ js/ foo. js % } or { % staticfile/ js/ foo. js as variable_name % } Or for multiples: { % staticfile/ foo. js ;/ bar. js % } or { % staticfile/ foo. js ;/ bar. js as variable_name % } | def staticfile_node(parser, token, optimize_if_possible=False):
"""For example:
{% staticfile "/js/foo.js" %}
or
{% staticfile "/js/foo.js" as variable_name %}
Or for multiples:
{% staticfile "/foo.js; /bar.js" %}
or
{% staticfile "/foo.js; /bar.js" as varia... |
works the way a good mkdir should: ) - already exists silently complete - regular file in the way raise an exception - parent directory ( ies ) does not exist make them as well | def _mkdir(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exception
- parent directory(ies) does not exist, make them as well
"""
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
... |
Look for filename in all MEDIA_ROOTS and return the first one found. | 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... |
Return a new filename to use as the combined file name for a bunch of files. A precondition is that they all have the same file extension | 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 is that they all have the same file extension
Given that the list of files can have different paths, we aim to use the
most common path.
... |
inspect the code and look for files that can be turned into combos. Basically the developer could type this: { % slimall % } <link href =/ one. css/ > <link href =/ two. css/ > { % endslimall % } And it should be reconsidered like this: <link href = { % slimfile/ one. css ;/ two. css % }/ > which we already have routin... | def render(self, context):
"""inspect the code and look for files that can be turned into combos.
Basically, the developer could type this:
{% slimall %}
<link href="/one.css"/>
<link href="/two.css"/>
{% endslimall %}
And it should be reconsidered like this:
... |
check for overlap with the other interval | 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 |
check if this is upstream of the other interval taking the strand of the other interval into account | 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
... |
check the distance between this an another interval Parameters ---------- | def distance(self, other_or_start=None, end=None, features=False):
"""
check the distance between this an another interval
Parameters
----------
other_or_start : Interval or int
either an integer or an Interval with a start attribute indicating
the start ... |
return a list of exons [ ( start stop ) ] for this object if appropriate | def exons(self):
"""
return a list of exons [(start, stop)] for this object if appropriate
"""
# drop the trailing comma
if not self.is_gene_pred: return []
if hasattr(self, "exonStarts"):
try:
starts = (long(s) for s in self.exonStarts[:-1].sp... |
return a list of features for the gene features of this object. This would include exons introns utrs etc. | 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 ('i... |
Return a start end tuple of positions around the transcription - start site | 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 used to add this many upstream
bases in the appropriate direction
... |
Return a start end tuple of positions for the promoter region of this gene | 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 that is considered the promoter
down : int
the strand is used to add... |
includes the entire exon as long as any of it is > cdsStart and < cdsEnd | def coding_exons(self):
"""
includes the entire exon as long as any of it is > cdsStart and <
cdsEnd
"""
# drop the trailing comma
starts = (long(s) for s in self.exonStarts[:-1].split(","))
ends = (long(s) for s in self.exonEnds[:-1].split(","))
return [(... |
just the parts of the exons that are translated | 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 |
return a boolean indicating whether this feature is downstream of other taking the strand of other into account | 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 ... |
return e. g. intron ; exon if the other_start end overlap introns and exons | def features(self, other_start, other_end):
"""
return e.g. "intron;exon" if the other_start, end overlap introns and
exons
"""
# completely encases gene.
if other_start <= self.start and other_end >= self.end:
return ['gene' if self.cdsStart != self.cdsEnd el... |
return the ( start end ) of the region before the geneStart | def upstream(self, distance):
"""
return the (start, end) of the region before the geneStart
"""
if getattr(self, "strand", None) == "+":
e = self.start
s = e - distance
else:
s = self.end
e = s + distance
return self._xstre... |
return the 5 UTR if appropriate | 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 ... |
Return the sequence for this feature. if per - exon is True return an array of exon sequences This sequence is never reverse complemented | 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 reverse complemented
"""
db = self.db
if not per_exon:
start = self.txStart + 1
retu... |
perform an NCBI blast against the sequence of this feature | 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 el... |
make a request to the genome - browsers BLAT interface sequence is one of None mrna cds returns a list of features that are hits to this sequence. | 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 list of features that are hits to this sequence.
"""
from . blat_blast import blat, blat_all
assert se... |
return a bed formatted string of this feature | 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,... |
return a bed12 ( http:// genome. ucsc. edu/ FAQ/ FAQformat. html#format1 ) representation of this interval | def bed12(self, score="0", rgb="."):
"""
return a bed12 (http://genome.ucsc.edu/FAQ/FAQformat.html#format1)
representation of this interval
"""
if not self.is_gene_pred:
raise CruzException("can't create bed12 from non genepred feature")
exons = list(self.exon... |
convert global coordinate ( s ) to local taking introns into account and cds/ tx - Start depending on cdna = True kwarg | def localize(self, *positions, **kwargs):
"""
convert global coordinate(s) to local taking
introns into account and cds/tx-Start depending on cdna=True kwarg
"""
cdna = kwargs.get('cdna', False)
# TODO: account for strand ?? add kwarg ??
# if it's to the CDNA, the... |
check the distance between this an another interval Parameters ---------- | def distance(self, other_or_start=None, end=None, features="unused",
shore_dist=3000):
"""
check the distance between this an another interval
Parameters
----------
other_or_start : Interval or int
either an integer or an Interval with a start attribute i... |
annotate bed file in fname with tables. distances are integers for distance. and intron/ exon/ utr5 etc for gene - pred tables. if the annotation features have a strand the distance reported is negative if the annotation feature is upstream of the feature in question if feature_strand is True then the distance is negat... | def annotate(g, fname, tables, feature_strand=False, in_memory=False,
header=None, out=sys.stdout, _chrom=None, parallel=False):
"""
annotate bed file in fname with tables.
distances are integers for distance. and intron/exon/utr5 etc for gene-pred
tables. if the annotation features have a stran... |
External entry point which calls main () and if Stop is raised calls sys. exit () | def entry_point():
"""
External entry point which calls main() and
if Stop is raised, calls sys.exit()
"""
try:
main("omego", items=[
(InstallCommand.NAME, InstallCommand),
(UpgradeCommand.NAME, UpgradeCommand),
(ConvertCommand.NAME, ConvertCommand),
... |
Open a URL using an opener that will simulate a browser user - agent url: The URL httpuser httppassword: HTTP authentication credentials ( either both or neither must be provided ) method: The HTTP method | def open_url(url, httpuser=None, httppassword=None, method=None):
"""
Open a URL using an opener that will simulate a browser user-agent
url: The URL
httpuser, httppassword: HTTP authentication credentials (either both or
neither must be provided)
method: The HTTP method
Caller is reponsi... |
Makes a HEAD request to find the final destination of a URL after following any redirects | 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 |
Read the contents of a URL into memory return | 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() |
Download a file optionally printing a simple progress bar url: The URL to download filename: The filename to save to default is to use the URL basename print_progress: The length of the progress bar use 0 to disable delete_fail: If True delete the file if the download was not successful default is to keep the temporary... | def download(url, filename=None, print_progress=0, delete_fail=True,
**kwargs):
"""
Download a file, optionally printing a simple progress bar
url: The URL to download
filename: The filename to save to, default is to use the URL basename
print_progress: The length of the progress bar, u... |
Append a backup prefix to a file or directory with an increasing numeric suffix (. N ) if a file already exists | def rename_backup(name, suffix='.bak'):
"""
Append a backup prefix to a file or directory, with an increasing numeric
suffix (.N) if a file already exists
"""
newname = '%s%s' % (name, suffix)
n = 0
while os.path.exists(newname):
n += 1
newname = '%s%s.%d' % (name, suffix, n)... |
Return a string of the form [ basename - TIMESTAMP. ext ] where TIMESTAMP is of the form YYYYMMDD - HHMMSS - MILSEC | def timestamp_filename(basename, ext=None):
"""
Return a string of the form [basename-TIMESTAMP.ext]
where TIMESTAMP is of the form YYYYMMDD-HHMMSS-MILSEC
"""
dt = datetime.now().strftime('%Y%m%d-%H%M%S-%f')
if ext:
return '%s-%s.%s' % (basename, dt, ext)
return '%s-%s' % (basename, ... |
Check whether zip file paths are all relative and optionally in a specified subdirectory raises an exception if not | def check_extracted_paths(namelist, subdir=None):
"""
Check whether zip file paths are all relative, and optionally in a
specified subdirectory, raises an exception if not
namelist: A list of paths from the zip file
subdir: If specified then check whether all paths in the zip file are
under t... |
Extract all files from a zip archive filename: The path to the zip file match_dir: If True all files in the zip must be contained in a subdirectory named after the archive file with extension removed destdir: Extract the zip into this directory default current directory | def unzip(filename, match_dir=False, destdir=None):
"""
Extract all files from a zip archive
filename: The path to the zip file
match_dir: If True all files in the zip must be contained in a subdirectory
named after the archive file with extension removed
destdir: Extract the zip into this dir... |
Create a new zip archive containing files filename: The name of the zip file to be created paths: A list of files or directories strip_dir: Remove this prefix from all file - paths before adding to zip | def zip(filename, paths, strip_prefix=''):
"""
Create a new zip archive containing files
filename: The name of the zip file to be created
paths: A list of files or directories
strip_dir: Remove this prefix from all file-paths before adding to zip
"""
if isinstance(paths, basestring):
... |
Automatically handle local and remote URLs files and directories | def get_as_local_path(path, overwrite, progress=0,
httpuser=None, httppassword=None):
"""
Automatically handle local and remote URLs, files and directories
path: Either a local directory, file or remote URL. If a URL is given
it will be fetched. If this is a zip it will be autom... |
Allocates and initializes an encoder state. | 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 |
Encodes an Opus frame | 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 ... |
Encodes an Opus frame from floating point input | 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 Op... |
Builds and returns the MeCab function for parsing Unicode text. | 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:
... |
Builds and returns the MeCab function for parsing to nodes using morpheme boundary constraints. | def __parse_tonodes(self, text, **kwargs):
'''Builds and returns the MeCab function for parsing to nodes using
morpheme boundary constraints.
Args:
format_feature: flag indicating whether or not to format the feature
value for each node yielded.
Returns:
... |
Parse the given text and return result from MeCab. | 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 ... |
MAX_TERM_COUNT = 10000 # There are 39 000 terms in the GO! | def parse(filename, MAX_TERM_COUNT=1000):
"""
MAX_TERM_COUNT = 10000 # There are 39,000 terms in the GO!
"""
with open(filename, "r") as f:
termId = None
name = None
desc = None
parents = []
termCount = 0
for l in f.readlines():
if l.st... |
create Tag Groups and Child Tags using data from terms dict | 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" ... |
We need to support deprecated behaviour for now which makes this quite complicated | def _handle_args(self, cmd, args):
"""
We need to support deprecated behaviour for now which makes this
quite complicated
Current behaviour:
- install: Installs a new server, existing server causes an error
- install --upgrade: Installs or upgrades a server
- ins... |
Either downloads and/ or unzips the server if necessary return: the directory of the unzipped server | def get_server_dir(self):
"""
Either downloads and/or unzips the server if necessary
return: the directory of the unzipped server
"""
if not self.args.server:
if self.args.skipunzip:
raise Stop(0, 'Unzip disabled, exiting')
log.info('Downl... |
Handle database initialisation and upgrade taking into account command line arguments | 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... |
Runs a command as if from the command - line without the need for using popen or subprocess | 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(co... |
Runs the omero command - line client with an array of arguments using the old environment | def bin(self, command):
"""
Runs the omero command-line client with an array of arguments using the
old environment
"""
if isinstance(command, basestring):
command = command.split()
self.external.omero_bin(command) |
The default symlink was changed from OMERO - CURRENT to OMERO. server. If -- sym was not specified and OMERO - CURRENT exists in the current directory stop and warn. | def symlink_check_and_set(self):
"""
The default symlink was changed from OMERO-CURRENT to OMERO.server.
If `--sym` was not specified and OMERO-CURRENT exists in the current
directory stop and warn.
"""
if self.args.sym == '':
if os.path.exists('OMERO-CURRENT'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.