sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
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 for overlap with the other interval | entailment |
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 if this is upstream of the `other` interval taking the strand of
the other interval into account | entailment |
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 ... | 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 of the interval
end : int
if `other_or_start` is an integer, this ... | entailment |
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 exons [(start, stop)] for this object if appropriate | entailment |
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 list of features for the gene features of this object.
This would include exons, introns, utrs, etc. | entailment |
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 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
down : int
if greature than 0, the str... | entailment |
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... | 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 this many downstream bases into the gene. | entailment |
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 [(... | includes the entire exon as long as any of it is > cdsStart and <
cdsEnd | entailment |
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 | just the parts of the exons that are translated | entailment |
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 a boolean indicating whether this feature is downstream of
`other` taking the strand of other into account | entailment |
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 e.g. "intron;exon" if the other_start, end overlap introns and
exons | entailment |
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 (start, end) of the region before the geneStart | entailment |
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 5' UTR if appropriate | entailment |
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... | Return the sequence for this feature.
if per-exon is True, return an array of exon sequences
This sequence is never reverse complemented | entailment |
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... | perform an NCBI blast against the sequence of this feature | entailment |
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... | 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. | entailment |
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 bed formatted string of this feature | entailment |
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... | return a bed12 (http://genome.ucsc.edu/FAQ/FAQformat.html#format1)
representation of this interval | entailment |
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... | convert global coordinate(s) to local taking
introns into account and cds/tx-Start depending on cdna=True kwarg | entailment |
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... | 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 of the interval
end : int
if `other_or_start` is an integer, this ... | entailment |
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... | 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 dis... | entailment |
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),
... | External entry point which calls main() and
if Stop is raised, calls sys.exit() | entailment |
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... | 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 reponsible for calling close() on the returned object | entailment |
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 | Makes a HEAD request to find the final destination of a URL after
following any redirects | entailment |
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() | Read the contents of a URL into memory, return | entailment |
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... | 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,
defaul... | entailment |
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)... | Append a backup prefix to a file or directory, with an increasing numeric
suffix (.N) if a file already exists | entailment |
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, ... | Return a string of the form [basename-TIMESTAMP.ext]
where TIMESTAMP is of the form YYYYMMDD-HHMMSS-MILSEC | entailment |
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... | 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 this subdirectory
Python docs are unclear about the securi... | entailment |
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... | 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
return: If match_dir is T... | entailment |
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):
... | 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 | entailment |
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... | 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 automatically
expanded by default.
overwrite: Whether to overwrite an existing file:
'error': Raise an except... | entailment |
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 | Allocates and initializes an encoder state. | entailment |
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
Returns string output payload | entailment |
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... | Encodes an Opus frame from floating point input | entailment |
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 Unicode text.
Args:
fn_name: MeCab function name that determines the function
behavior, either 'mecab_sparse_tostr' or
'mecab_nbest_sparse_tostr'.
Returns:
A function definition, tailored to parsi... | entailment |
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:
... | 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:
A function which returns a Generator, tailore... | entailment |
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 ... | 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 boundary_constraints: regular expression for... | entailment |
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... | MAX_TERM_COUNT = 10000 # There are 39,000 terms in the GO! | entailment |
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" ... | create Tag Groups and Child Tags using data from terms dict | entailment |
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... | 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
- install --managedb: Automatically initialise or upgrade th... | entailment |
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... | Either downloads and/or unzips the server if necessary
return: the directory of the unzipped server | entailment |
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... | Handle database initialisation and upgrade, taking into account
command line arguments | entailment |
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 a command as if from the command-line
without the need for using popen or subprocess | entailment |
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) | Runs the omero command-line client with an array of arguments using the
old environment | entailment |
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'... | 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. | entailment |
def query(request):
"""Query encoder/decoder with a request value"""
def inner(func, obj):
result_code = func(obj, request)
if result_code is not constants.OK:
raise OpusError(result_code)
return result_code
return inner | Query encoder/decoder with a request value | entailment |
def get(request, result_type):
"""Get CTL value from a encoder/decoder"""
def inner(func, obj):
result = result_type()
result_code = func(obj, request, ctypes.byref(result))
if result_code is not constants.OK:
raise OpusError(result_code)
return result.value
r... | Get CTL value from a encoder/decoder | entailment |
def set(request):
"""Set new CTL value to a encoder/decoder"""
def inner(func, obj, value):
result_code = func(obj, request, value)
if result_code is not constants.OK:
raise OpusError(result_code)
return inner | Set new CTL value to a encoder/decoder | entailment |
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(schem... | Sort a list of SQL schemas in order | entailment |
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 corresponding value is
a tuple containing the source and the target schema.
"""
f_dict = {}
for f in files:
root, ext = os.path.spl... | Parse a list of SQL files and return a dictionary of valid schema
files where each key is a valid schema file and the corresponding value is
a tuple containing the source and the target schema. | entailment |
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')
... | Dump the database using the postgres custom format | entailment |
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 defaults.
"""
db = {
'name': self.args.dbname,
'host': self.args.dbhost,
'us... | Get a dictionary of database connection parameters, and create an
environment for running postgres commands.
Falls back to omego defaults. | entailment |
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(psqla... | Run a psql command | entailment |
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=Tr... | Run a pg_dump command | entailment |
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) | Set the directory of the server to be controlled | entailment |
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 possible
setup_omero_cli() must be called before this method to import the
correct omero module to minimise the... | Returns a dictionary of all config.xml properties
If `force = True` then ignore any cached state and read config.xml
if possible
setup_omero_cli() must be called before this method to import the
correct omero module to minimise the possibility of version conflicts | entailment |
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 times,
so this will only work with a single omero instance.
This can have several surprising effects, so setup_omero_cli(... | Imports the omero CLI module so that commands can be run directly.
Note Python does not allow a module to be imported multiple times,
so this will only work with a single omero instance.
This can have several surprising effects, so setup_omero_cli()
must be explcitly called. | entailment |
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):
... | Create a copy of the current environment for interacting with the
current OMERO server installation | entailment |
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... | Runs a command as if from the OMERO command-line without the need
for using popen or subprocess. | entailment |
def omero_bin(self, command):
"""
Runs the omero command-line client with an array of arguments using the
old environment
"""
assert isinstance(command, list)
if not self.old_env:
raise Exception('Old environment not initialised')
log.info("Running [ol... | Runs the omero command-line client with an array of arguments using the
old environment | entailment |
def run(exe, args, capturestd=False, env=None):
"""
Runs an executable with an array of arguments, optionally in the
specified environment.
Returns stdout and stderr
"""
command = [exe] + args
if env:
log.info("Executing [custom environment]: %s", " ".... | Runs an executable with an array of arguments, optionally in the
specified environment.
Returns stdout and stderr | entailment |
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)... | Create byte-to-string and string-to-byte conversion functions for
internal use.
:param py3enc: Encoding used by Python 3 environment.
:type py3enc: str | entailment |
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... | Create tokenizer for use in boundary constraint parsing.
:param py2enc: Encoding used by Python 2 environment.
:type py2enc: str | entailment |
def update(self, document_id, update_spec, namespace, timestamp):
"""Apply updates given in update_spec to the document whose id
matches that of doc.
"""
index, doc_type = self._index_and_mapping(namespace)
with self.lock:
# Check if document source is stored in loca... | Apply updates given in update_spec to the document whose id
matches that of doc. | entailment |
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,
... | Insert a document into Elasticsearch. | entailment |
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)
... | Insert multiple documents into Elasticsearch. | entailment |
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)
... | Remove a document from Elasticsearch. | entailment |
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:
... | Send buffered operations to Elasticsearch.
This method is periodically called by the AutoCommitThread. | entailment |
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
may be in conflict after a MongoDB rollback.
"""
try:
result = self.elastic.search(
index=se... | Get the most recently modified document from Elasticsearch.
This method is used to help define a time window within which documents
may be in conflict after a MongoDB rollback. | entailment |
def split_sig(params):
"""
Split a list of parameters/types by commas,
whilst respecting brackets.
For example:
String arg0, int arg2 = 1, List<int> arg3 = [1, 2, 3]
=> ['String arg0', 'int arg2 = 1', 'List<int> arg3 = [1, 2, 3]']
"""
result = []
current = ''
level = 0
f... | Split a list of parameters/types by commas,
whilst respecting brackets.
For example:
String arg0, int arg2 = 1, List<int> arg3 = [1, 2, 3]
=> ['String arg0', 'int arg2 = 1', 'List<int> arg3 = [1, 2, 3]'] | entailment |
def parse_method_signature(sig):
""" Parse a method signature of the form: modifier* type name (params) """
match = METH_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Method signature invalid: ' + sig)
modifiers, return_type, name, generic_types, params = match.groups()
if para... | Parse a method signature of the form: modifier* type name (params) | entailment |
def parse_property_signature(sig):
""" Parse a property signature of the form:
modifier* type name { (get;)? (set;)? } """
match = PROP_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Property signature invalid: ' + sig)
groups = match.groups()
if groups[0] is not None:
... | Parse a property signature of the form:
modifier* type name { (get;)? (set;)? } | entailment |
def parse_indexer_signature(sig):
""" Parse a indexer signature of the form:
modifier* type this[params] { (get;)? (set;)? } """
match = IDXR_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Indexer signature invalid: ' + sig)
modifiers, return_type, params, getter, setter = m... | Parse a indexer signature of the form:
modifier* type this[params] { (get;)? (set;)? } | entailment |
def parse_param_signature(sig):
""" Parse a parameter signature of the form: type name (= default)? """
match = PARAM_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Parameter signature invalid, got ' + sig)
groups = match.groups()
modifiers = groups[0].split()
typ, name, _, ... | Parse a parameter signature of the form: type name (= default)? | entailment |
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 = ... | Parse a type signature | entailment |
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(p... | Parse an attribute signature | entailment |
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 i... | Try and create a reference to a type on MSDN | entailment |
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:] | Shorten a type. E.g. drops 'System.' | entailment |
def parse_mecab_options(self, options):
'''Parses the MeCab options, returning them in a dictionary.
Lattice-level option has been deprecated; please use marginal or nbest
instead.
:options string or dictionary of options to use when instantiating
the MeCab insta... | Parses the MeCab options, returning them in a dictionary.
Lattice-level option has been deprecated; please use marginal or nbest
instead.
:options string or dictionary of options to use when instantiating
the MeCab instance. May be in short- or long-form, or in a
... | entailment |
def build_options_str(self, options):
'''Returns a string concatenation of the MeCab options.
Args:
options: dictionary of options to use when instantiating the MeCab
instance.
Returns:
A string concatenation of the options used when instantiatin... | Returns a string concatenation of the MeCab options.
Args:
options: dictionary of options to use when instantiating the MeCab
instance.
Returns:
A string concatenation of the options used when instantiating the
MeCab instance, in long-form. | entailment |
def create(fs, channels):
"""Allocates and initializes a decoder state"""
result_code = ctypes.c_int()
result = _create(fs, channels, ctypes.byref(result_code))
if result_code.value is not 0:
raise OpusError(result_code.value)
return result | Allocates and initializes a decoder state | entailment |
def packet_get_bandwidth(data):
"""Gets the bandwidth of an Opus packet."""
data_pointer = ctypes.c_char_p(data)
result = _packet_get_bandwidth(data_pointer)
if result < 0:
raise OpusError(result)
return result | Gets the bandwidth of an Opus packet. | entailment |
def packet_get_nb_channels(data):
"""Gets the number of channels from an Opus packet"""
data_pointer = ctypes.c_char_p(data)
result = _packet_get_nb_channels(data_pointer)
if result < 0:
raise OpusError(result)
return result | Gets the number of channels from an Opus packet | entailment |
def packet_get_nb_frames(data, length=None):
"""Gets the number of frames in an Opus packet"""
data_pointer = ctypes.c_char_p(data)
if length is None:
length = len(data)
result = _packet_get_nb_frames(data_pointer, ctypes.c_int(length))
if result < 0:
raise OpusError(result)
r... | Gets the number of frames in an Opus packet | entailment |
def packet_get_samples_per_frame(data, fs):
"""Gets the number of samples per frame from an Opus packet"""
data_pointer = ctypes.c_char_p(data)
result = _packet_get_nb_frames(data_pointer, ctypes.c_int(fs))
if result < 0:
raise OpusError(result)
return result | Gets the number of samples per frame from an Opus packet | entailment |
def decode(decoder, data, length, frame_size, decode_fec, channels=2):
"""Decode an Opus frame
Unlike the `opus_decode` function , this function takes an additional parameter `channels`,
which indicates the number of channels in the frame
"""
pcm_size = frame_size * channels * ctypes.sizeof(ctypes... | Decode an Opus frame
Unlike the `opus_decode` function , this function takes an additional parameter `channels`,
which indicates the number of channels in the frame | entailment |
def label_list_parser(self, url):
"""
Extracts comma separate tag=value pairs from a string
Assumes all characters other than / and , are valid
"""
labels = re.findall('([^/,]+=[^/,]+)', url)
slabels = set(labels)
if '' in slabels:
slabels.remove('')
... | Extracts comma separate tag=value pairs from a string
Assumes all characters other than / and , are valid | entailment |
def init(app, register_blueprint=True, url_prefix='/fm', access_control_function=None,
custom_config_json_path=None, custom_init_js_path=None):
"""
:param app: The Flask app
:param register_blueprint: Override to False to stop the blueprint from automatically being registered to the
... | :param app: The Flask app
:param register_blueprint: Override to False to stop the blueprint from automatically being registered to the
app
:param url_prefix: The URL prefix for the blueprint, defaults to /fm
:param access_control_function: Pass in a function here to implement... | entailment |
def get_file(path=None, content=None):
"""
:param path: relative path, or None to get from request
:param content: file content, output in data. Used for editfile
"""
if path is None:
path = request.args.get('path')
if path is None:
return error('No path in request')
fi... | :param path: relative path, or None to get from request
:param content: file content, output in data. Used for editfile | entailment |
def __get_charset(self):
'''Return the character encoding (charset) used internally by MeCab.
Charset is that of the system dictionary used by MeCab. Will defer to
the user-specified MECAB_CHARSET environment variable, if set.
Defaults to shift-jis on Windows.
Defaults t... | Return the character encoding (charset) used internally by MeCab.
Charset is that of the system dictionary used by MeCab. Will defer to
the user-specified MECAB_CHARSET environment variable, if set.
Defaults to shift-jis on Windows.
Defaults to utf-8 on Mac OS.
Defaults ... | entailment |
def __get_libpath(self):
'''Return the absolute path to the MeCab library.
On Windows, the path to the system dictionary is used to deduce the
path to libmecab.dll.
Otherwise, mecab-config is used find the libmecab shared object or
dynamic library (*NIX or Mac OS, respec... | Return the absolute path to the MeCab library.
On Windows, the path to the system dictionary is used to deduce the
path to libmecab.dll.
Otherwise, mecab-config is used find the libmecab shared object or
dynamic library (*NIX or Mac OS, respectively).
Will defer to the... | entailment |
def __regkey_value(self, path, name='', start_key=None):
r'''Return the data of value mecabrc at MeCab HKEY node.
On Windows, the path to the mecabrc as set in the Windows Registry is
used to deduce the path to libmecab.dll.
Returns:
The full path to the mecabrc on W... | r'''Return the data of value mecabrc at MeCab HKEY node.
On Windows, the path to the mecabrc as set in the Windows Registry is
used to deduce the path to libmecab.dll.
Returns:
The full path to the mecabrc on Windows.
Raises:
WindowsError: A problem wa... | entailment |
def diff(old_html, new_html, cutoff=0.0, plaintext=False, pretty=False):
"""Show the differences between the old and new html document, as html.
Return the document html with extra tags added to show changes. Add <ins>
tags around newly added sections, and <del> tags to show sections that have
been del... | Show the differences between the old and new html document, as html.
Return the document html with extra tags added to show changes. Add <ins>
tags around newly added sections, and <del> tags to show sections that have
been deleted. | entailment |
def adjusted_ops(opcodes):
"""
Iterate through opcodes, turning them into a series of insert and delete
operations, adjusting indices to account for the size of insertions and
deletions.
>>> def sequence_opcodes(old, new): return difflib.SequenceMatcher(a=old, b=new).get_opcodes()
>>> list(adju... | Iterate through opcodes, turning them into a series of insert and delete
operations, adjusting indices to account for the size of insertions and
deletions.
>>> def sequence_opcodes(old, new): return difflib.SequenceMatcher(a=old, b=new).get_opcodes()
>>> list(adjusted_ops(sequence_opcodes('abc', 'b')))... | entailment |
def match_indices(match):
"""Yield index tuples (old_index, new_index) for each place in the match."""
a, b, size = match
for i in range(size):
yield a + i, b + i | Yield index tuples (old_index, new_index) for each place in the match. | entailment |
def get_opcodes(matching_blocks):
"""Use difflib to get the opcodes for a set of matching blocks."""
sm = difflib.SequenceMatcher(a=[], b=[])
sm.matching_blocks = matching_blocks
return sm.get_opcodes() | Use difflib to get the opcodes for a set of matching blocks. | entailment |
def match_blocks(hash_func, old_children, new_children):
"""Use difflib to find matching blocks."""
sm = difflib.SequenceMatcher(
_is_junk,
a=[hash_func(c) for c in old_children],
b=[hash_func(c) for c in new_children],
)
return sm | Use difflib to find matching blocks. | entailment |
def get_nonmatching_blocks(matching_blocks):
"""Given a list of matching blocks, output the gaps between them.
Non-matches have the format (alo, ahi, blo, bhi). This specifies two index
ranges, one in the A sequence, and one in the B sequence.
"""
i = j = 0
for match in matching_blocks:
... | Given a list of matching blocks, output the gaps between them.
Non-matches have the format (alo, ahi, blo, bhi). This specifies two index
ranges, one in the A sequence, and one in the B sequence. | entailment |
def merge_blocks(a_blocks, b_blocks):
"""Given two lists of blocks, combine them, in the proper order.
Ensure that there are no overlaps, and that they are for sequences of the
same length.
"""
# Check sentinels for sequence length.
assert a_blocks[-1][2] == b_blocks[-1][2] == 0 # sentinel size... | Given two lists of blocks, combine them, in the proper order.
Ensure that there are no overlaps, and that they are for sequences of the
same length. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.