code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
start = time.clock()
it = iter(self.reader)
if self.args.max_records:
it = itertools.islice(it, self.args.max_records)
num = self.work(it)
end = time.clock()
print("Read {} records in {} seconds".format(num, (end - start)), file=sys.stderr) | def run(self) | Main program entry point after parsing arguments | 3.414151 | 3.18161 | 1.073089 |
polynomial = 0x31;
crc = 0xFF;
index = 0
for index in range(0, len(buffer)):
crc ^= buffer[index]
for i in range(8, 0, -1):
if crc & 0x80:
crc = (crc << 1) ^ polynomial
else:
crc ... | def _crc8(self, buffer) | Polynomial 0x31 (x8 + x5 +x4 +1) | 2.489928 | 2.138627 | 1.164264 |
orig_key, value = pair_str.split("=", 1)
key = orig_key.strip()
if key != orig_key:
warnings.warn(
"Mapping key {} has leading or trailing space".format(repr(orig_key)),
LeadingTrailingSpaceInKey,
)
return key, value | def split_mapping(pair_str) | Split the ``str`` in ``pair_str`` at ``'='``
Warn if key needs to be stripped | 4.487218 | 4.06729 | 1.103245 |
if not value.startswith("<") or not value.endswith(">"):
raise exceptions.InvalidHeaderException(
"Header mapping value was not wrapped in angular brackets"
)
# split the comma-separated list into pairs, ignoring commas in quotes
pairs = split_quoted_string(value[1:-1], deli... | def parse_mapping(value) | Parse the given VCF header line mapping
Such a mapping consists of "key=value" pairs, separated by commas and
wrapped into angular brackets ("<...>"). Strings are usually quoted,
for certain known keys, exceptions are made, depending on the tag key.
this, however, only gets important when serializing.... | 3.826777 | 3.366038 | 1.136879 |
result = {
"ALT": MappingHeaderLineParser(header.AltAlleleHeaderLine),
"contig": MappingHeaderLineParser(header.ContigHeaderLine),
"FILTER": MappingHeaderLineParser(header.FilterHeaderLine),
"FORMAT": MappingHeaderLineParser(header.FormatHeaderLine),
"INFO": MappingHeade... | def build_header_parsers() | Return mapping for parsers to use for each VCF header type
Inject the WarningHelper into the parsers. | 2.754812 | 2.483021 | 1.10946 |
if value == ".":
return None
elif type_ in ("Character", "String"):
if "%" in value:
for k, v in record.UNESCAPE_MAPPING:
value = value.replace(k, v)
return value
else:
try:
return _CONVERTERS[type_](value)
except ValueErro... | def convert_field_value(type_, value) | Convert atomic field value according to the type | 5.213596 | 5.011128 | 1.040404 |
if field_info.id == "FT":
return [x for x in value.split(";") if x != "."]
elif field_info.type == "Flag":
return True
elif field_info.number == 1:
return convert_field_value(field_info.type, value)
else:
if value == ".":
return []
else:
... | def parse_field_value(field_info, value) | Parse ``value`` according to ``field_info`` | 3.215536 | 3.236537 | 0.993512 |
arr = BREAKEND_PATTERN.split(alt_str)
mate_chrom, mate_pos = arr[1].split(":", 1)
mate_pos = int(mate_pos)
if mate_chrom[0] == "<":
mate_chrom = mate_chrom[1:-1]
within_main_assembly = False
else:
within_main_assembly = True
FWD_REV = {True: record.FORWARD, False: re... | def parse_breakend(alt_str) | Parse breakend and return tuple with results, parameters for BreakEnd
constructor | 2.99419 | 2.981429 | 1.00428 |
if len(alt_str) == 0:
raise exceptions.InvalidRecordException("Invalid VCF, empty ALT")
elif len(alt_str) == 1:
if ref[0] == alt_str[0]:
return record.Substitution(record.DEL, alt_str)
else:
return record.Substitution(record.INDEL, alt_str)
else:
... | def process_sub_grow(ref, alt_str) | Process substution where the string grows | 2.843886 | 2.891263 | 0.983614 |
if len(ref) == 0:
raise exceptions.InvalidRecordException("Invalid VCF, empty REF")
elif len(ref) == 1:
if ref[0] == alt_str[0]:
return record.Substitution(record.INS, alt_str)
else:
return record.Substitution(record.INDEL, alt_str)
else:
return r... | def process_sub_shrink(ref, alt_str) | Process substution where the string shrink | 3.006865 | 3.130543 | 0.960493 |
if len(ref) == len(alt_str):
if len(ref) == 1:
return record.Substitution(record.SNV, alt_str)
else:
return record.Substitution(record.MNV, alt_str)
elif len(ref) > len(alt_str):
return process_sub_grow(ref, alt_str)
else: # len(ref) < len(alt_str):
... | def process_sub(ref, alt_str) | Process substitution | 2.40727 | 2.34248 | 1.027659 |
return record.BreakEnd(*parse_breakend(alt_str))
elif alt_str[0] == "." and len(alt_str) > 0:
return record.SingleBreakEnd(record.FORWARD, alt_str[1:])
elif alt_str[-1] == "." and len(alt_str) > 0:
return record.SingleBreakEnd(record.REVERSE, alt_str[:-1])
elif alt_str[0] == "<" and ... | def process_alt(header, ref, alt_str): # pylint: disable=W0613
# By its nature, this function contains a large number of case distinctions
if "]" in alt_str or "[" in alt_str | Process alternative value using Header in ``header`` | 3.217297 | 3.1299 | 1.027923 |
begins, ends = [0], []
# transition table
DISPATCH = {
self.NORMAL: self._handle_normal,
self.QUOTED: self._handle_quoted,
self.ARRAY: self._handle_array,
self.DELIM: self._handle_delim,
self.ESCAPED: self._handle_escaped,
... | def run(self, s) | Split string ``s`` at delimiter, correctly interpreting quotes
Further, interprets arrays wrapped in one level of ``[]``. No
recursive brackets are interpreted (as this would make the grammar
non-regular and currently this complexity is not needed). Currently,
quoting inside of braces... | 3.443212 | 3.417731 | 1.007456 |
if not line or not line.startswith("##"):
raise exceptions.InvalidHeaderException(
'Invalid VCF header line (must start with "##") {}'.format(line)
)
if "=" not in line:
raise exceptions.InvalidHeaderException(
'Invalid VCF hea... | def parse_line(self, line) | Parse VCF header ``line`` (trailing '\r\n' or '\n' is ignored)
:param str line: ``str`` with line to parse
:param dict sub_parsers: ``dict`` mapping header line types to
appropriate parser objects
:returns: appropriate :py:class:`HeaderLine` parsed from ``line``
:raises: :py... | 4.023713 | 3.53429 | 1.138478 |
line_str = line_str.rstrip()
if not line_str:
return None # empty line, EOF
arr = self._split_line(line_str)
# CHROM
chrom = arr[0]
# POS
pos = int(arr[1])
# IDS
if arr[2] == ".":
ids = []
else:
... | def parse_line(self, line_str) | Parse line from file (including trailing line break) and return
resulting Record | 2.651851 | 2.609871 | 1.016085 |
if format_str not in self._format_cache:
self._format_cache[format_str] = list(map(self.header.get_format_field_info, format_))
# per-sample calls
calls = []
for sample, raw_data in zip(self.samples.names, arr[9:]):
if self.samples.is_parsed(sample):
... | def _handle_calls(self, alts, format_, format_str, arr) | Handle FORMAT and calls columns, factored out of parse_line | 4.59941 | 4.380735 | 1.049917 |
arr = line_str.rstrip().split("\t")
if len(arr) != self.expected_fields:
raise exceptions.InvalidRecordException(
(
"The line contains an invalid number of fields. Was "
"{} but expected {}\n{}".format(len(arr), 9 + len(self.sa... | def _split_line(self, line_str) | Split line and check number of columns | 5.851295 | 5.327427 | 1.098334 |
result = OrderedDict()
if info_str == ".":
return result
# The standard is very nice to parsers, we can simply split at
# semicolon characters, although I (Manuel) don't know how strict
# programs follow this
for entry in info_str.split(";"):
... | def _parse_info(self, info_str, num_alts) | Parse INFO column from string | 6.534781 | 5.967412 | 1.095078 |
data = OrderedDict()
# The standard is very nice to parsers, we can simply split at
# colon characters, although I (Manuel) don't know how strict
# programs follow this
for key, info, value in zip(format_, infos, gt_str.split(":")):
data[key] = parse_field_va... | def _parse_calls_data(klass, format_, infos, gt_str) | Parse genotype call information from arrays using format array
:param list format: List of strings with format names
:param gt_str arr: string with genotype information values | 13.964754 | 15.619094 | 0.894082 |
if not header_lines:
raise exceptions.InvalidHeaderException(
"The VCF file did not contain any header lines!"
)
first = header_lines[0]
if first.key != "fileformat":
raise exceptions.InvalidHeaderException("The VCF file did not start ... | def _check_header_lines(self, header_lines) | Check header lines, in particular for starting file "##fileformat" | 3.608927 | 3.185138 | 1.133052 |
field_info = self.header.get_info_field_info(key)
if not isinstance(value, list):
return
TABLE = {
".": len(value),
"A": num_alts,
"R": num_alts + 1,
"G": binomial(num_alts + 1, 2), # diploid only at the moment
}
... | def run(self, key, value, num_alts) | Check value in INFO[key] of record
Currently, only checks for consistent counts are implemented
:param str key: key of INFO entry to check
:param value: value to check
:param int alts: list of alternative alleles, for length | 5.16697 | 4.70579 | 1.098003 |
for key, value in call.data.items():
self._check_count(call, key, value, num_alts) | def run(self, call, num_alts) | Check ``FORMAT`` of a record.Call
Currently, only checks for consistent counts are implemented | 5.545017 | 4.794049 | 1.156646 |
prev_line = self._line
self._line = self.stream.readline()
return prev_line | def _read_next_line(self) | Read next line store in self._line and return old one | 5.39542 | 3.229418 | 1.67071 |
# parse header lines
sub_parser = HeaderParser()
header_lines = []
while self._line and self._line.startswith("##"):
header_lines.append(sub_parser.parse_line(self._line))
self._read_next_line()
# parse sample info line
self.samples = self... | def parse_header(self, parsed_samples=None) | Read and parse :py:class:`vcfpy.header.Header` from file, set
into ``self.header`` and return it
:param list parsed_samples: ``list`` of ``str`` for subsetting the
samples to parse
:returns: ``vcfpy.header.Header``
:raises: ``vcfpy.exceptions.InvalidHeaderException`` in the ... | 4.107193 | 4.013747 | 1.023281 |
if not self._line or not self._line.startswith("#CHROM"):
raise exceptions.IncorrectVCFFormat('Missing line starting with "#CHROM"')
# check for space before INFO
line = self._line.rstrip()
pos = line.find("FORMAT") if ("FORMAT" in line) else line.find("INFO")
... | def _handle_sample_line(self, parsed_samples=None) | Check and interpret the "##CHROM" line and return samples | 5.339088 | 4.84672 | 1.101588 |
if len(arr) <= len(REQUIRE_NO_SAMPLE_HEADER):
if tuple(arr) != REQUIRE_NO_SAMPLE_HEADER:
raise exceptions.IncorrectVCFFormat(
"Sample header line indicates no sample but does not "
"equal required prefix {}".format("\t".join(REQUIRE_NO... | def _check_samples_line(klass, arr) | Peform additional check on samples line | 4.41713 | 4.15047 | 1.064248 |
'''Lazily import the numpy module'''
if LazyImport.numpy_module is None:
try:
LazyImport.numpy_module = __import__('numpypy')
except ImportError:
try:
LazyImport.numpy_module = __import__('numpy')
except ImportEr... | def numpy() | Lazily import the numpy module | 3.152024 | 2.809245 | 1.122018 |
'''Lazily import the rpy2 module'''
if LazyImport.rpy2_module is None:
try:
rpy2 = __import__('rpy2.robjects')
except ImportError:
raise ImportError('The rpy2 module is required')
LazyImport.rpy2_module = rpy2
try:
... | def rpy2() | Lazily import the rpy2 module | 2.669743 | 2.533391 | 1.053822 |
posiction_dict = dict(zip(range(1, 17), [i for i in range(30, 62) if i % 2]))
return posiction_dict[pos] | def map_position(pos) | Map natural position to machine code postion | 7.604163 | 6.289404 | 1.209043 |
if path is None:
path = "/tmp"
else:
path = path.rstrip("/")
day_dir = datetime.datetime.now().strftime("%d%m%Y")
hour_dir = datetime.datetime.now().strftime("%H%M")
ensure_snapshot_dir(path+"/"+self.cam_id+"/"+day_dir+"/"+hour_dir)
f_path... | def snap(self, path=None) | Get a snapshot and save it to disk. | 3.162431 | 3.07442 | 1.028627 |
try:
payload = {"address":self.address, "user": self.user, "pwd": self.pswd, "pos": map_position(pos)}
resp = requests.get(
"http://{address}/decoder_control.cgi?command={pos}&user={user}&pwd={pwd}".format(**payload)
)
except KeyError:
... | def move(self, pos) | Move cam to given preset position.
pos - must be within 1 to 16.
Returns: CamException in case of errors, "ok" otherwise. | 5.918091 | 4.526031 | 1.307568 |
resp = requests.get("http://{0}/get_status.cgi".format(self.address))
data = resp.text.replace(";", "")
data = data.replace("var", "")
data_s = data.split("\n")
# Last is an empty line
data_s.pop()
data_array = [s.split("=") for s in data_s]
ret... | def status(self) | Retrieve some configuration params.
Note: info are returned even without password | 5.108684 | 4.518813 | 1.130537 |
'''
Searches for matching words in the dictionary with regular expressions
wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword
can take three different values: 'ok', 'only', or 'no'.
pos: a tag in the Penn Part of Speech tagset
see isletool.posList for the full list... | def search(searchList, matchStr, numSyllables=None, wordInitial='ok',
wordFinal='ok', spanSyllable='ok', stressedSyllable='ok',
multiword='ok', pos=None) | Searches for matching words in the dictionary with regular expressions
wordInitial, wordFinal, spanSyllable, stressSyllable, and multiword
can take three different values: 'ok', 'only', or 'no'.
pos: a tag in the Penn Part of Speech tagset
see isletool.posList for the full list of possible... | 3.951203 | 2.115763 | 1.867507 |
'''
Parses the pronunciation string
Returns the list of syllables and a list of primary and
secondary stress locations
'''
retList = []
for syllableTxt in pronunciationStr.split("#"):
if syllableTxt == "":
continue
syllableList = [x.split() for x in syllableT... | def _parsePronunciation(pronunciationStr) | Parses the pronunciation string
Returns the list of syllables and a list of primary and
secondary stress locations | 2.709448 | 2.229943 | 1.21503 |
'''
Get the number of syllables and phones in this word
If maxFlag=True, use the longest pronunciation. Otherwise, take the
average length.
'''
phoneCount = 0
syllableCount = 0
syllableCountList = []
phoneCountList = []
wordList = isleDict.lookup(word)
entryLi... | def getNumPhones(isleDict, word, maxFlag) | Get the number of syllables and phones in this word
If maxFlag=True, use the longest pronunciation. Otherwise, take the
average length. | 2.807417 | 2.302112 | 1.219496 |
'''
Returns all of the out-of-dictionary words found in a list of utterances
'''
oodList = []
for word in wordList:
try:
isleDict.lookup(word)
except WordNotInISLE:
oodList.append(word)
oodList = list(set(oodList))
oodList.sort()
... | def findOODWords(isleDict, wordList) | Returns all of the out-of-dictionary words found in a list of utterances | 3.269463 | 2.454213 | 1.332184 |
'''
Tests whether adjacent words are OOD or not
It returns complete wordLists with the matching words replaced.
Each match yields one sentence.
e.g.
red ball chaser
would return
[[red_ball chaser], [red ball_chaser]], [0, 1]
if 'red_ball' and 'ball_chaser' were both in... | def autopair(isleDict, wordList) | Tests whether adjacent words are OOD or not
It returns complete wordLists with the matching words replaced.
Each match yields one sentence.
e.g.
red ball chaser
would return
[[red_ball chaser], [red ball_chaser]], [0, 1]
if 'red_ball' and 'ball_chaser' were both in the diction... | 5.755168 | 1.979204 | 2.90782 |
'''
Builds the isle textfile into a dictionary for fast searching
'''
lexDict = {}
with io.open(self.islePath, "r", encoding='utf-8') as fd:
wordList = [line.rstrip('\n') for line in fd]
for row in wordList:
word, pronunciation = row.split... | def _buildDict(self) | Builds the isle textfile into a dictionary for fast searching | 4.244707 | 3.264849 | 1.300124 |
'''
Lookup a word and receive a list of syllables and stressInfo
Output example for the word 'another' which has two pronunciations
[(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]),
([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))]
'''
... | def lookup(self, word) | Lookup a word and receive a list of syllables and stressInfo
Output example for the word 'another' which has two pronunciations
[(([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ɚ']], [1], [1]),
([[u'ə'], [u'n', u'ˈʌ'], [u'ð', u'ə', u'ɹ']], [1], [1]))] | 5.516415 | 2.224939 | 2.479356 |
'''
for help on isletool.LexicalTool.search(), see see isletool.search()
'''
return search(self.data.items(), matchStr, numSyllables=numSyllables,
wordInitial=wordInitial, wordFinal=wordFinal,
spanSyllable=spanSyllable,
st... | def search(self, matchStr, numSyllables=None, wordInitial='ok',
wordFinal='ok', spanSyllable='ok', stressedSyllable='ok',
multiword='ok', pos=None) | for help on isletool.LexicalTool.search(), see see isletool.search() | 4.289315 | 2.02088 | 2.122498 |
'''Get all timestamps from all series in the group.'''
timestamps = set()
for series in self.groups.itervalues():
timestamps |= set(series.timestamps)
return sorted(list(timestamps)) | def timestamps(self) | Get all timestamps from all series in the group. | 6.184923 | 4.027923 | 1.535512 |
'''Calculate a trend for all series in the group. See the
`TimeSeries.trend()` method for more information.'''
return DataFrame({ name: series.trend(**kwargs) \
for name, series in self.groups.iteritems() }) | def trend(self, **kwargs) | Calculate a trend for all series in the group. See the
`TimeSeries.trend()` method for more information. | 8.235874 | 4.166579 | 1.976651 |
'''Forecast all time series in the group. See the
`TimeSeries.forecast()` method for more information.'''
return DataFrame({ name: series.forecast(horizon, **kwargs) \
for name, series in self.groups.iteritems() }) | def forecast(self, horizon, **kwargs) | Forecast all time series in the group. See the
`TimeSeries.forecast()` method for more information. | 8.29121 | 4.033488 | 2.055593 |
colour = colours[colours_pos % colours_len]
colours_pos += 1
if not overlay:
pylab.subplot(plots, 1, colours_pos)
kwargs = {}
if name in labels:
name = labels[name]
if name is not None:
kwargs['label'... | def plot(self, overlay=True, **labels): # pragma: no cover
'''Plot all time series in the group.'''
pylab = LazyImport.pylab()
colours = list('rgbymc')
colours_len = len(colours)
colours_pos = 0
plots = len(self.groups)
for name, series in self.groups.iteritems() | Plot all time series in the group. | 2.367717 | 2.130236 | 1.111481 |
'''Rename series in the group.'''
for old, new in kwargs.iteritems():
if old in self.groups:
self.groups[new] = self.groups[old]
del self.groups[old] | def rename(self, **kwargs) | Rename series in the group. | 3.894231 | 3.338246 | 1.16655 |
record_checks = record_checks or []
if tabix_path and not path:
raise ValueError("Must give path if tabix_path is given")
return Reader(
stream=stream,
path=path,
tabix_path=tabix_path,
record_checks=record_checks,
... | def from_stream(
klass, stream, path=None, tabix_path=None, record_checks=None, parsed_samples=None
) | Create new :py:class:`Reader` from file
.. note::
If you use the ``parsed_samples`` feature and you write out
records then you must not change the ``FORMAT`` of the record.
:param stream: ``file``-like object to read from
:param path: optional string with path to store ... | 2.341482 | 2.735015 | 0.856113 |
record_checks = record_checks or []
path = str(path)
if path.endswith(".gz"):
f = gzip.open(path, "rt")
if not tabix_path:
tabix_path = path + ".tbi"
if not os.path.exists(tabix_path):
tabix_path = None # guess... | def from_path(klass, path, tabix_path=None, record_checks=None, parsed_samples=None) | Create new :py:class:`Reader` from path
.. note::
If you use the ``parsed_samples`` feature and you write out
records then you must not change the ``FORMAT`` of the record.
:param path: the path to load from (converted to ``str`` for
compatibility with ``path.py``)
... | 2.122262 | 2.382233 | 0.890871 |
if begin is not None and end is None:
raise ValueError("begin and end must both be None or neither")
# close tabix file if any and is open
if self.tabix_file and not self.tabix_file.closed:
self.tabix_file.close()
# open tabix file if not yet open
... | def fetch(self, chrom_or_region, begin=None, end=None) | Jump to the start position of the given chromosomal position
and limit iteration to the end position
:param str chrom_or_region: name of the chromosome to jump to if
begin and end are given and a samtools region string otherwise
(e.g. "chr1:123,456-123,900").
:param int ... | 2.426723 | 2.381397 | 1.019033 |
if self.tabix_file and not self.tabix_file.closed:
self.tabix_file.close()
if self.stream:
self.stream.close() | def close(self) | Close underlying stream | 3.527969 | 3.343766 | 1.055088 |
if key in QUOTE_FIELDS:
return json.dumps(value)
elif isinstance(value, str):
if " " in value or "\t" in value:
return json.dumps(value)
else:
return value
elif isinstance(value, list):
return "[{}]".format(", ".join(value))
else:
retu... | def serialize_for_header(key, value) | Serialize value for the given mapping key for a VCF header line | 2.5836 | 2.592029 | 0.996748 |
remove = set(remove)
# Copy over lines that are not removed
lines = []
for line in header.lines:
if hasattr(line, "mapping"):
if (line.key, line.mapping.get("ID", None)) in remove:
continue # filter out
else:
if (line.key, line.value) in remo... | def header_without_lines(header, remove) | Return :py:class:`Header` without lines given in ``remove``
``remove`` is an iterable of pairs ``key``/``ID`` with the VCF header key
and ``ID`` of entry to remove. In the case that a line does not have
a ``mapping`` entry, you can give the full value to remove.
.. code-block:: python
# head... | 3.834824 | 3.610049 | 1.062264 |
result = ["<"]
for i, (key, value) in enumerate(mapping.items()):
if i > 0:
result.append(",")
result += [key, "=", serialize_for_header(key, value)]
result += [">"]
return "".join(result) | def mapping_to_str(mapping) | Convert mapping to string | 3.656699 | 3.656441 | 1.00007 |
result = {key: OrderedDict() for key in LINES_WITH_ID}
for line in self.lines:
if line.key in LINES_WITH_ID:
result.setdefault(line.key, OrderedDict())
if line.mapping["ID"] in result[line.key]:
warnings.warn(
... | def _build_indices(self) | Build indices for the different field types | 3.780464 | 3.532617 | 1.07016 |
return Header([line.copy() for line in self.lines], self.samples.copy()) | def copy(self) | Return a copy of this header | 14.404255 | 9.47425 | 1.520358 |
if key in self._indices:
return self._indices[key].values()
else:
return [] | def get_lines(self, key) | Return header lines having the given ``key`` as their type | 5.086463 | 5.188349 | 0.980362 |
if key not in self._indices:
return False
else:
return id_ in self._indices[key] | def has_header_line(self, key, id_) | Return whether there is a header line with the given ID of the
type given by ``key``
:param key: The VCF header key/line type.
:param id_: The ID value to compare fore
:return: ``True`` if there is a header line starting with ``##${key}=``
in the VCF file having the mapping... | 4.200268 | 5.647682 | 0.743715 |
self.lines.append(header_line)
self._indices.setdefault(header_line.key, OrderedDict())
if not hasattr(header_line, "mapping"):
return False # no registration required
if self.has_header_line(header_line.key, header_line.mapping["ID"]):
warnings.warn(
... | def add_line(self, header_line) | Add header line, updating any necessary support indices
:return: ``False`` on conflicting line and ``True`` otherwise | 3.670128 | 3.575309 | 1.026521 |
mapping = OrderedDict(self.mapping.items())
return self.__class__(self.key, self.value, mapping) | def copy(self) | Return a copy | 7.400507 | 7.232241 | 1.023266 |
try:
return int(number)
except ValueError as e:
if number in VALID_NUMBERS:
return number
else:
raise e | def _parse_number(klass, number) | Parse ``number`` into an ``int`` or return ``number`` if a valid
expression for a INFO/FORMAT "Number".
:param str number: ``str`` to parse and check | 4.212604 | 4.38126 | 0.961505 |
'''
Inserts spaces into a syllable if needed
Originally the phone list and syllable list contained the same number
of phones. But the adjustedPhoneList may have some insertions which are
not accounted for in the syllableList.
'''
i = 0
retSyllableList = []
for syllableNum, syll... | def _adjustSyllabification(adjustedPhoneList, syllableList) | Inserts spaces into a syllable if needed
Originally the phone list and syllable list contained the same number
of phones. But the adjustedPhoneList may have some insertions which are
not accounted for in the syllableList. | 3.283119 | 2.258676 | 1.453559 |
'''
Words may have multiple candidates in ISLE; returns the 'optimal' one.
'''
aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory
numDiffList = []
withStress = []
i = 0
alignedSyllabificationList = []
alignedActualPronunciationList = []
for wordTupl... | def _findBestPronunciation(isleWordList, aPron) | Words may have multiple candidates in ISLE; returns the 'optimal' one. | 3.82823 | 3.548303 | 1.07889 |
'''
Given a phone list and a syllable list, syllabify the phones
Typically used by findBestSyllabification which first aligns the phoneList
with a dictionary phoneList and then uses the dictionary syllabification
to syllabify the input phoneList.
'''
numPhoneList = [len(syllable) f... | def _syllabifyPhones(phoneList, syllableList) | Given a phone list and a syllable list, syllabify the phones
Typically used by findBestSyllabification which first aligns the phoneList
with a dictionary phoneList and then uses the dictionary syllabification
to syllabify the input phoneList. | 4.07031 | 1.948941 | 2.088473 |
'''
Align the phones in two pronunciations
'''
# First prep the two pronunctions
pronI = [char for char in pronI]
pronA = [char for char in pronA]
# Remove any elements not in the other list (but maintain order)
pronITmp = pronI
pronATmp = pronA
# Find the longest sequ... | def alignPronunciations(pronI, pronA) | Align the phones in two pronunciations | 3.06306 | 3.034027 | 1.009569 |
'''
Find the best syllabification for a word
First find the closest pronunciation to a given pronunciation. Then take
the syllabification for that pronunciation and map it onto the
input pronunciation.
'''
retList = _findBestPronunciation(inputIsleWordList,
... | def _findBestSyllabification(inputIsleWordList, actualPronunciationList) | Find the best syllabification for a word
First find the closest pronunciation to a given pronunciation. Then take
the syllabification for that pronunciation and map it onto the
input pronunciation. | 3.286239 | 2.792156 | 1.176954 |
'''
Given the phones in a syllable, retrieves the vowel index
'''
cvList = ['V' if isletool.isVowel(phone) else 'C' for phone in phoneList]
vowelCount = cvList.count('V')
if vowelCount > 1:
raise TooManyVowelsInSyllable(phoneList, cvList)
if vowelCount == 1:
stressI... | def _getSyllableNucleus(phoneList) | Given the phones in a syllable, retrieves the vowel index | 5.059773 | 3.873852 | 1.306135 |
'''
Find the closest dictionary pronunciation to a provided pronunciation
'''
retList = _findBestPronunciation(inputIsleWordList, aPron)
isleWordList = retList[0]
bestIndex = retList[3]
return isleWordList[bestIndex] | def findClosestPronunciation(inputIsleWordList, aPron) | Find the closest dictionary pronunciation to a provided pronunciation | 4.364094 | 3.403252 | 1.282331 |
switch = None
if type == "A":
group, device = settings.split(",")
switch = pi_switch.RCSwitchA(group, device)
elif type == "B":
addr, channel = settings.split(",")
addr = int(addr)
channel = int(channel)
switch = pi_switch.RCSwitchB(addr, channel)
elif type == "C":
family, group, device = setting... | def create_switch(type, settings, pin) | Create a switch.
Args:
type: (str): type of the switch [A,B,C,D]
settings (str): a comma separted list
pin (int): wiringPi pin
Returns:
switch | 2.266886 | 2.275501 | 0.996214 |
# Perform escaping
if isinstance(value, str):
if any(r in value for r in record.RESERVED_CHARS):
for k, v in record.ESCAPE_MAPPING:
value = value.replace(k, v)
# String-format the given value
if value is None:
return "."
else:
return str(value... | def format_atomic(value) | Format atomic value
This function also takes care of escaping the value in case one of the
reserved characters occurs in the value. | 6.27772 | 5.470559 | 1.147546 |
if section == "FORMAT" and field_info.id == "FT":
if not value:
return "."
elif isinstance(value, list):
return ";".join(map(format_atomic, value))
elif field_info.number == 1:
if value is None:
return "."
else:
return format_a... | def format_value(field_info, value, section) | Format possibly compound value given the FieldInfo | 3.363657 | 3.175172 | 1.059362 |
if use_bgzf or (use_bgzf is None and path and path.endswith(".gz")):
stream = bgzf.BgzfWriter(fileobj=stream)
return Writer(stream, header, path) | def from_stream(klass, stream, header, path=None, use_bgzf=None) | Create new :py:class:`Writer` from file
Note that for getting bgzf support, you have to pass in a stream
opened in binary mode. Further, you either have to provide a ``path``
ending in ``".gz"`` or set ``use_bgzf=True``. Otherwise, you will
get the notorious "TypeError: 'str' does not... | 3.782468 | 3.240619 | 1.167205 |
path = str(path)
use_bgzf = False # we already interpret path
if path.endswith(".gz"):
f = bgzf.BgzfWriter(filename=path)
else:
f = open(path, "wt")
return klass.from_stream(f, header, path, use_bgzf=use_bgzf) | def from_path(klass, path, header) | Create new :py:class:`Writer` from path
:param path: the path to load from (converted to ``str`` for
compatibility with ``path.py``)
:param header: VCF header to use, lines and samples are deep-copied | 4.936071 | 5.26539 | 0.937456 |
for line in self.header.lines:
print(line.serialize(), file=self.stream)
if self.header.samples.names:
print(
"\t".join(list(parser.REQUIRE_SAMPLE_HEADER) + self.header.samples.names),
file=self.stream,
)
else:
... | def _write_header(self) | Write out the header | 4.144238 | 3.947941 | 1.049721 |
f = self._empty_to_dot
row = [record.CHROM, record.POS]
row.append(f(";".join(record.ID)))
row.append(f(record.REF))
if not record.ALT:
row.append(".")
else:
row.append(",".join([f(a.serialize()) for a in record.ALT]))
row.append(f... | def _serialize_record(self, record) | Serialize whole Record | 3.113278 | 3.049896 | 1.020782 |
result = []
for key, value in record.INFO.items():
info = self.header.get_info_field_info(key)
if info.type == "Flag":
result.append(key)
else:
result.append("{}={}".format(key, format_value(info, value, "INFO")))
retur... | def _serialize_info(self, record) | Return serialized version of record.INFO | 3.882692 | 3.235466 | 1.200041 |
if isinstance(call, record.UnparsedCall):
return call.unparsed_data
else:
result = [
format_value(self.header.get_format_field_info(key), call.data.get(key), "FORMAT")
for key in format_
]
return ":".join(result) | def _serialize_call(self, format_, call) | Return serialized version of the Call using the record's FORMAT | 7.25821 | 5.95587 | 1.218665 |
jinja_a = None
jinja_b = None
ext_node = None
ext_nodes = []
for node in nodes:
if isinstance(node, EmptyLine):
continue
if node.has_children():
node.children = self._create_extended_jinja_tags(node.children)
... | def _create_extended_jinja_tags(self, nodes) | Loops through the nodes and looks for special jinja tags that
contains more than one tag but only one ending tag. | 2.415909 | 2.35037 | 1.027885 |
"returns False if children is empty or contains only empty lines else True."
return bool([x for x in self.children if not isinstance(x, EmptyLine)]) | def has_children(self) | returns False if children is empty or contains only empty lines else True. | 11.704679 | 4.766853 | 2.455431 |
requirements = []
with open(path, "rt") as reqs_f:
for line in reqs_f:
line = line.strip()
if line.startswith("-r"):
fname = line.split()[1]
inner_path = os.path.join(os.path.dirname(path), fname)
requirements += parse_requirem... | def parse_requirements(path) | Parse ``requirements.txt`` at ``path``. | 1.96416 | 1.991411 | 0.986316 |
user = None
pswd = None
name = None
address = "{address}:{port}".format(**cam_c)
if "user" in cam_c:
user = cam_c["user"]
if "pswd" in cam_c:
pswd = cam_c["pswd"]
if "name" in cam_c:
name = cam_c["name"]
return {"user": user, "pswd": pswd, "name": nam... | def __parse_args(cam_c) | Arrange class init params from conf file.
Returns: a dict with values. | 2.109958 | 2.172688 | 0.971128 |
with open(conf_file, "r") as c_file:
lines = c_file.readlines()
cams_conf = [json.loads(j) for j in lines]
cams = []
for cam_c in cams_conf:
init_params = __parse_args(cam_c)
cams.append(cam_types[cam_c["type"]](**init_params))
return cams | def load_cams(conf_file) | Reads cams conf from file and intantiate appropiate classes.
Returns: an array of IpCam classes. | 2.886384 | 2.802684 | 1.029864 |
while True:
for c in cams:
c.snap(path)
time.sleep(delay) | def watch(cams, path=None, delay=10) | Get screenshots from all cams at defined intervall. | 3.731745 | 3.28768 | 1.13507 |
return self.post(SCORE_RESOURCE.format(phone_number=phone_number),
account_lifecycle_event=account_lifecycle_event,
**params) | def score(self, phone_number, account_lifecycle_event, **params) | Score is an API that delivers reputation scoring based on phone number intelligence, traffic patterns, machine
learning, and a global data consortium.
See https://developer.telesign.com/docs/score-api for detailed API documentation. | 3.313377 | 3.517871 | 0.94187 |
with open(filename) as source:
text = source.read()
match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", text)
if not match:
msg = "Unable to find version number in {}".format(filename)
raise RuntimeError(msg)
version = match.group(1)
return v... | def load_version(filename='fuzzyhashlib/version.py') | Parse a __version__ number from a source file | 2.050739 | 1.8881 | 1.086139 |
if date_rfc2616 is None:
date_rfc2616 = formatdate(usegmt=True)
if nonce is None:
nonce = str(uuid.uuid4())
if not content_type:
content_type = "application/x-www-form-urlencoded" if method_name in ("POST", "PUT") else ""
auth_metho... | def generate_telesign_headers(customer_id,
api_key,
method_name,
resource,
url_encoded_fields,
date_rfc2616=None,
no... | Generates the TeleSign REST API headers used to authenticate requests.
Creates the canonicalized string_to_sign and generates the HMAC signature. This is used to authenticate requests
against the TeleSign REST API.
See https://developer.telesign.com/docs/authentication for detailed API documen... | 1.62731 | 1.660816 | 0.979826 |
return self._execute(self.session.post, 'POST', resource, **params) | def post(self, resource, **params) | Generic TeleSign REST API POST handler.
:param resource: The partial resource URI to perform the request against, as a string.
:param params: Body params to perform the POST request with, as a dictionary.
:return: The RestClient Response object. | 5.832465 | 9.688257 | 0.602014 |
return self._execute(self.session.get, 'GET', resource, **params) | def get(self, resource, **params) | Generic TeleSign REST API GET handler.
:param resource: The partial resource URI to perform the request against, as a string.
:param params: Body params to perform the GET request with, as a dictionary.
:return: The RestClient Response object. | 6.20531 | 9.509217 | 0.652557 |
return self._execute(self.session.put, 'PUT', resource, **params) | def put(self, resource, **params) | Generic TeleSign REST API PUT handler.
:param resource: The partial resource URI to perform the request against, as a string.
:param params: Body params to perform the PUT request with, as a dictionary.
:return: The RestClient Response object. | 6.687411 | 10.435177 | 0.640853 |
return self._execute(self.session.delete, 'DELETE', resource, **params) | def delete(self, resource, **params) | Generic TeleSign REST API DELETE handler.
:param resource: The partial resource URI to perform the request against, as a string.
:param params: Body params to perform the DELETE request with, as a dictionary.
:return: The RestClient Response object. | 6.243559 | 9.656781 | 0.646547 |
resource_uri = "{api_host}{resource}".format(api_host=self.api_host, resource=resource)
url_encoded_fields = self._encode_params(params)
headers = RestClient.generate_telesign_headers(self.customer_id,
self.api_key,
... | def _execute(self, method_function, method_name, resource, **params) | Generic TeleSign REST API request handler.
:param method_function: The Requests HTTP request function to perform the request.
:param method_name: The HTTP method name, as an upper case string.
:param resource: The partial resource URI to perform the request against, as a string.
:param ... | 3.293275 | 3.036479 | 1.084571 |
return self.post(MESSAGING_RESOURCE,
phone_number=phone_number,
message=message,
message_type=message_type,
**params) | def message(self, phone_number, message, message_type, **params) | Send a message to the target phone_number.
See https://developer.telesign.com/docs/messaging-api for detailed API documentation. | 3.436919 | 3.416182 | 1.00607 |
return self.get(MESSAGING_STATUS_RESOURCE.format(reference_id=reference_id),
**params) | def status(self, reference_id, **params) | Retrieves the current status of the message.
See https://developer.telesign.com/docs/messaging-api for detailed API documentation. | 7.111567 | 6.282103 | 1.132036 |
return self.post(PHONEID_RESOURCE.format(phone_number=phone_number),
**params) | def phoneid(self, phone_number, **params) | The PhoneID API provides a cleansed phone number, phone type, and telecom carrier information to determine the
best communication method - SMS or voice.
See https://developer.telesign.com/docs/phoneid-api for detailed API documentation. | 5.99578 | 6.680563 | 0.897496 |
if self._pre_computed_hash is None:
return libssdeep_wrapper.fuzzy_digest(self._state, 0)
else:
return self._pre_computed_hash | def hexdigest(self) | Return the digest value as a string of hexadecimal digits. | 9.765282 | 8.921836 | 1.094537 |
if self._updatable:
return libssdeep_wrapper.fuzzy_update(self._state, buf)
else:
raise InvalidOperation("Cannot update sdeep created from hash") | def update(self, buf) | Update this hash object's state with the provided string. | 24.187918 | 21.868124 | 1.106081 |
if self._pre_computed_hash is None:
temp = ssdeep(buf="")
else:
temp = ssdeep(hash=hash)
libssdeep_wrapper.fuzzy_free(temp._state)
temp._state = libssdeep_wrapper.fuzzy_clone(self._state)
temp._updatable = self._updatable
temp._pre_compute... | def copy(self) | Returns a new instance which identical to this instance. | 6.495664 | 5.957749 | 1.090288 |
if not self._final:
if self._buf_len >= self._MIN_LEN:
self._tlsh.final()
self._final = True
else:
raise ValueError("tlsh requires buffer with length >= %d "
"for mode where force = %s" % \
... | def hexdigest(self) | Return the digest value as a string of hexadecimal digits. | 7.076076 | 7.016393 | 1.008506 |
if self._final:
raise InvalidOperation("Cannot update finalised tlsh")
else:
self._buf_len += len(buf)
return self._tlsh.update(buf) | def update(self, buf) | Update this hash object's state with the provided string. | 11.165527 | 11.786191 | 0.94734 |
return self.post(VOICE_RESOURCE,
phone_number=phone_number,
message=message,
message_type=message_type,
**params) | def call(self, phone_number, message, message_type, **params) | Send a voice call to the target phone_number.
See https://developer.telesign.com/docs/voice-api for detailed API documentation. | 3.495397 | 3.15248 | 1.108777 |
return self.get(VOICE_STATUS_RESOURCE.format(reference_id=reference_id),
**params) | def status(self, reference_id, **params) | Retrieves the current status of the voice call.
See https://developer.telesign.com/docs/voice-api for detailed API documentation. | 8.225366 | 6.366012 | 1.292075 |
return self.get(APPVERIFY_STATUS_RESOURCE.format(external_id=external_id),
**params) | def status(self, external_id, **params) | Retrieves the verification result for an App Verify transaction by external_id. To ensure a secure verification
flow you must check the status using TeleSign's servers on your backend. Do not rely on the SDK alone to
indicate a successful verification.
See https://developer.telesign.com/docs/ap... | 9.23243 | 5.715557 | 1.615316 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.