Search is not available for this dataset
text stringlengths 75 104k |
|---|
def get(self, item, default_value=None):
"""
Get the requested header entry by keyword name
"""
found, name = self._contains_and_name(item)
if found:
return self._record_map[name]['value']
else:
return default_value |
def next(self):
"""
for iteration over the header entries
"""
if self._current < len(self._record_list):
rec = self._record_list[self._current]
key = rec['name']
self._current += 1
return key
else:
raise StopIteration |
def _record2card(self, record):
"""
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello ... |
def set_record(self, record, **kw):
"""
check the record is valid and set keys in the dict
parameters
----------
record: string
Dict representing a record or a string representing a FITS header
card
"""
if isstring(record):
ca... |
def _check_equals(self):
"""
check for = in position 8, set attribute _has_equals
"""
card_string = self['card_string']
if len(card_string) < 9:
self._has_equals = False
elif card_string[8] == '=':
self._has_equals = True
else:
... |
def _convert_value(self, value_orig):
"""
things like 6 and 1.25 are converted with ast.literal_value
Things like 'hello' are stripped of quotes
"""
import ast
if value_orig is None:
return value_orig
if value_orig.startswith("'") and value_orig.ends... |
def _update_threads(self):
"""Update available thread count post-construction.
To be called any number of times from run() method"""
if self.remaining_clusters is not None:
self.threads = max(1,self.threads_total//self.remaining_clusters.value)
#otherwise just keep the curren... |
def _report_completion(self):
"""Update shared counters to signal that we are done with this cluster.
Call just before exiting run() method (in a finally clause)"""
rem_clust = self.remaining_clusters
if rem_clust is not None:
# -= is non-atomic, need to acquire a lock
... |
def _make_reads_for_assembly(number_of_wanted_reads, total_reads, reads_in1, reads_in2, reads_out1, reads_out2, random_seed=None):
'''Makes fastq files that are random subset of input files. Returns total number of reads in output files.
If the number of wanted reads is >= total reads, then just make... |
def report_to_resistance_dict(infile):
'''Takes final ariba report.tsv file, and extracts
resistance calls, returning a dict of
drug name -> list of mutations.
each "mutation" in the list is a tuple of (gene name, mutation).
Mutation is of the form X42Y, or "incomplete_gene" for katG and
pncA wh... |
def genbank_to_gene_coords(infile, genes):
'''Input file in genbank format. genes = list of gene names to find.
Returns dict of gene name -> {start: x, end: y}, where x and y are
zero-based. x<y iff gene is on forwards strand'''
coords = {}
for seq_record in SeqIO.parse(infile, "genbank"):
... |
def load_mutations(gene_coords, mutation_to_drug_json, variants_txt, upstream_before=100):
'''Load mutations from "mykrobe-style" files. mutation_to_drug_json is json file
of mutation -> list of drugs. variants_txt is text file of variants used my mykrobe's
make probes. gene_coords should be dict of gene co... |
def write_prepareref_fasta_file(outfile, gene_coords, genes_need_upstream, genes_non_upstream, upstream_before=100, upstream_after=100):
'''Writes fasta file to be used with -f option of prepareref'''
tmp_dict = {}
fasta_in = os.path.join(data_dir, 'NC_000962.3.fa.gz')
pyfastaq.tasks.file_to_dict(fasta_... |
def _get_known_noncoding_het_snp(data_dict):
'''If ref is coding, return None. If the data dict has a known snp, and
samtools made a call, then return the string ref_name_change and the
% of reads supporting the variant type. If noncoding, but no
samtools call, then return None'... |
def _get_nonsynonymous_var(data_dict):
'''if data_dict has a non synonymous variant, return string:
ref_name.change. Otherwise return None'''
has_nonsyn = SummaryCluster._has_nonsynonymous(data_dict)
if has_nonsyn == 'no':
return None
elif data_dict['known_var_change... |
def _has_match(self, assembled_summary):
'''assembled_summary should be output of _to_cluster_summary_assembled'''
if assembled_summary.startswith('yes'):
if self.data[0]['var_only'] == '0' or self._to_cluster_summary_has_known_nonsynonymous(assembled_summary) == 'yes':
retur... |
def has_var_groups(self):
'''Returns a set of the variant group ids that this cluster has'''
ids = set()
for d in self.data:
if self._has_known_variant(d) != 'no' and d['var_group'] != '.':
ids.add(d['var_group'])
return ids |
def column_summary_data(self):
'''Returns a dictionary of column name -> value, for cluster-level results'''
assembled_summary = self._to_cluster_summary_assembled()
pct_id, read_depth = self._pc_id_and_read_depth_of_longest()
columns = {
'assembled': self._to_cluster_summar... |
def cat_files(infiles, outfile):
'''Cats all files in list infiles into outfile'''
f_out = pyfastaq.utils.open_file_write(outfile)
for filename in infiles:
if os.path.exists(filename):
f_in = pyfastaq.utils.open_file_read(filename)
for line in f_in:
print(lin... |
def _check_spades_log_file(logfile):
'''SPAdes can fail with a strange error. Stop everything if this happens'''
f = pyfastaq.utils.open_file_read(logfile)
for line in f:
if line.startswith('== Error == system call for:') and line.rstrip().endswith('finished abnormally, err code: -... |
def _fix_contig_orientation(contigs_fa, ref_fa, outfile, min_id=90, min_length=20, breaklen=200):
'''Changes orientation of each contig to match the reference, when possible.
Returns a set of names of contigs that had hits in both orientations to the reference'''
if not os.path.exists(contigs... |
def _parse_nucmer_coords_file(coords_file, ref_name):
'''Input is coords file made by self._run_nucmer. Reference should have one sequence only.
ref_name is name fo the reference sequence, to sanity check the coords file.
Returns dictionary. Key = assembly contig name. Value = list of nucm... |
def _nucmer_hits_to_percent_identity(nucmer_hits):
'''Input is hits made by self._parse_nucmer_coords_file.
Returns dictionary. key = contig name. Value = percent identity of hits to that contig'''
percent_identities = {}
max_lengths = {}
for contig in nucmer_hits:
... |
def _nucmer_hits_to_assembly_coords(nucmer_hits):
'''Input is hits made by self._parse_nucmer_coords_file.
Returns dictionary. key = contig name. Value = list of coords that match
to the reference gene'''
coords = {}
for l in nucmer_hits.values():
for hit in l:
... |
def nucmer_hits_to_ref_coords(cls, nucmer_hits, contig=None):
'''Input is hits made by self._parse_nucmer_coords_file.
Returns dictionary. Key = contig name. Value = list of coords in the
reference sequence for that contig.
if contig=contig_name, then just gets the ref coords fr... |
def nucmer_hits_to_ref_and_qry_coords(cls, nucmer_hits, contig=None):
'''Same as nucmer_hits_to_ref_coords, except removes containing hits first,
and returns ref and qry coords lists'''
if contig is None:
ctg_coords = {key: [] for key in nucmer_hits.keys()}
else:
... |
def ref_cov_per_contig(nucmer_hits):
'''Input is hits made by self._parse_nucmer_coords_file.
Returns dictionary. key = contig name. Value = number of bases that
match to the reference sequence.'''
coords = AssemblyCompare.nucmer_hits_to_ref_coords(nucmer_hits)
return {x: p... |
def _get_assembled_reference_sequences(nucmer_hits, ref_sequence, assembly):
'''nucmer_hits = hits made by self._parse_nucmer_coords_file.
ref_gene = reference sequence (pyfastaq.sequences.Fasta object)
assembly = dictionary of contig name -> contig.
Makes a set of Fasta object... |
def _whole_gene_covered_by_nucmer_hits(nucmer_hits, ref_seq, percent_threshold, max_nt_extend):
'''Returns true iff the reference sequence is covered by nucmer hits.
nucmer_hits = hits made by self._parse_nucmer_coords_file.
Counts as covered if (total ref bases covered) / len(ref_seq) >= ... |
def _ref_has_region_assembled_twice(nucmer_hits, ref_seq, threshold):
'''Returns true iff there is a part of the reference that is assembled
more than once (ie covered by >1 nucmer hit).
Needs a minimum proportin of the ref to be assembled more than once,
determined by threshold... |
def _ref_covered_by_at_least_one_full_length_contig(nucmer_hits, percent_threshold, max_nt_extend):
'''Returns true iff there exists a contig that completely
covers the reference sequence
nucmer_hits = hits made by self._parse_nucmer_coords_file.'''
for l in nucmer_hits.values():
... |
def nucmer_hit_containing_reference_position(nucmer_hits, ref_name, ref_position, qry_name=None):
'''Returns the first nucmer match found that contains the given
reference location. nucmer_hits = hits made by self._parse_nucmer_coords_file.
Returns None if no matching hit found'''
... |
def _get_exe(prog):
'''Given a program name, return what we expect its exectuable to be called'''
if prog in prog_to_env_var:
env_var = prog_to_env_var[prog]
if env_var in os.environ:
return os.environ[env_var]
return prog_to_default[prog] |
def _get_version(prog, path):
'''Given a program name and expected path, tries to determine its version.
Returns tuple (bool, version). First element True iff found version ok.
Second element is version string (if found), otherwise an error message'''
assert prog in prog_to_version... |
def _get_read_depths(cls, read_depths_file, sequence_name, position):
'''Returns total read depth and depth of reads supporting alternative (if present)'''
assert os.path.exists(read_depths_file)
assert os.path.exists(read_depths_file + '.tbi')
tbx = pysam.TabixFile(read_depths_file)
... |
def variants_in_coords(nucmer_matches, vcf_file):
'''nucmer_matches = made by assembly_compare.assembly_match_coords().
Returns number of variants that lie in nucmer_matches'''
found_variants = {}
f = pyfastaq.utils.open_file_read(vcf_file)
for line in f:
if line.s... |
def fake_run(self):
'''Doesn't actually run cd-hit. Instead, puts each input sequence into its own cluster. So it's as if cdhit was run, but didn't cluster anything'''
clusters = {}
used_names = set()
seq_reader = pyfastaq.sequences.file_reader(self.infile)
for seq in seq_reader... |
def run_get_clusters_from_file(self, clusters_infile, all_ref_seqs, rename_dict=None):
'''Instead of running cdhit, gets the clusters info from the input file.'''
if rename_dict is None:
rename_dict = {}
# check that every sequence in the clusters file can be
# found in the ... |
def get_total_alignment_score(bam):
'''Returns total of AS: tags in the input BAM'''
sam_reader = pysam.Samfile(bam, "rb")
total = 0
for sam in sam_reader.fetch(until_eof=True):
try:
total += sam.opt('AS')
except:
pass
return total |
def sam_to_fastq(sam):
'''Given a pysam alignment, returns the sequence a Fastq object.
Reverse complements as required and add suffix /1 or /2 as appropriate from the flag'''
name = sam.qname
if sam.is_read1:
name += '/1'
elif sam.is_read2:
name += '/2'
else:
raise Er... |
def sam_pair_to_insert(s1, s2):
'''Returns insert size from pair of sam records, as long as their orientation is "innies".
Otherwise returns None.'''
if s1.is_unmapped or s2.is_unmapped or (s1.tid != s2.tid) or (s1.is_reverse == s2.is_reverse):
return None
# If here, reads are both mapped to... |
def update_from_sam(self, sam, sam_reader):
'''Updates graph info from a pysam.AlignedSegment object'''
if sam.is_unmapped \
or sam.mate_is_unmapped \
or (sam.reference_id == sam.next_reference_id):
return
new_link = link.Link(sam, sam_reader, self.ref_lengths)
... |
def _make_graph(self, max_insert):
'''helper function to construct graph from current state of object'''
if len(self.partial_links) != 0:
raise Error('Error in _make_graph(). Cannot continue because there are partial links')
self.contig_links = {}
for key in self.lin... |
def nucleotide_range(self):
'''Returns the nucleotide (start, end) positions inclusive of this variant.
start==end if it's an amino acid variant, otherwise start+2==end'''
if self.variant_type == 'p':
return 3 * self.position, 3 * self.position + 2
else:
return... |
def _sam_to_soft_clipped(self, sam):
'''Returns tuple of whether or not the left and right end of the mapped read in the sam record is soft-clipped'''
if sam.is_unmapped:
raise Error('Cannot get soft clip info from an unmapped read')
if sam.cigar is None or len(sam.cigar) == 0:
... |
def _report_line_to_dict(cls, line):
'''Takes report line string as input. Returns a dict of column name -> value in line'''
data = line.split('\t')
if len(data) != len(report.columns):
return None
d = dict(zip(report.columns, data))
for key in report.int_columns:
... |
def _dict_to_report_line(cls, report_dict):
'''Takes a report_dict as input and returns a report line'''
return '\t'.join([str(report_dict[x]) for x in report.columns]) |
def _load_report(infile):
'''Loads report file into a dictionary. Key=reference name.
Value = list of report lines for that reference'''
report_dict = {}
f = pyfastaq.utils.open_file_read(infile)
first_line = True
for line in f:
line = line.rstrip()
... |
def _filter_dicts(self):
'''Filters out all the report_dicts that do not pass the cutoffs. If any ref sequence
loses all of its report_dicts, then it is completely removed.'''
keys_to_remove = set()
for ref_name in self.report:
for ctg_name in self.report[ref_name]:
... |
def merge(self, other):
'''Merge another link into this one. Expected that each link was created from each mate from a pair. We only know both distances to contig ends when we have read info from both mappings in a BAM file. All other info should be the same.'''
assert self.refnames == other.refnames
... |
def insert_size(self):
'''Returns insert size, defined as distance from outer edges of reads (and assumes gap length of zero)'''
try:
distances = self._distance_to_contig_ends()
except:
raise Error('Error getting insert size from Link:\n' + str(self))
return sum(... |
def _load_fofn(cls, fofn):
'''Returns dictionary of filename -> short name. Value is None
whenever short name is not provided'''
filenames = {}
f = pyfastaq.utils.open_file_read(fofn)
for line in f:
fields = line.rstrip().split()
if len(fields) == 1:
... |
def _filter_matrix_rows(cls, matrix):
'''matrix = output from _to_matrix'''
indexes_to_keep = []
for i in range(len(matrix)):
keep_row = False
for element in matrix[i]:
if element not in {'NA', 'no'}:
keep_row = True
... |
def _filter_matrix_columns(cls, matrix, phandango_header, csv_header):
'''phandango_header, csv_header, matrix = output from _to_matrix'''
indexes_to_keep = set()
for row in matrix:
for i in range(len(row)):
if row[i] not in {'NA', 'no'}:
indexes_... |
def _get_variant_effect(cls, variants, ref_sequence):
'''variants = list of variants in the same codon.
returns type of variant (cannot handle more than one indel in the same codon).'''
assert len(variants) != 0
var_types = [x.var_type for x in variants]
if len(set(var_types)... |
def _get_remaining_known_ref_variants(known_ref_variants, used_ref_variants, nucmer_coords):
'''Finds variants where ref has the variant and so does the contig. Which means
that there was no mummer call to flag it up so need to look through the known
ref variants. Also need to check that t... |
def get_variants(self, ref_sequence_name, allowed_ctg_coords, allowed_ref_coords, nucmer_matches=None):
'''Nucmr coords = dict. Key=contig name. Value = list of intervals of ref coords that match the contig.
Made by assembly_compare.AssemblyCompare.nucmer_hits_to_ref_coords
Returns diction... |
def _fix_virulencefinder_fasta_file(cls, infile, outfile):
'''Some line breaks are missing in the FASTA files from
viruslence finder. Which means there are lines like this:
AAGATCCAATAACTGAAGATGTTGAACAAACAATTCATAATATTTATGGTCAATATGCTATTTTCGTTGA
AGGTGTTGCGCATTTACCTGGACATCTCTCTCCATTATTAAAAA... |
def _samtools_depths_at_known_snps_all_wild(sequence_meta, contig_name, cluster, variant_list):
'''Input is a known variants, as sequence_metadata object. The
assumption is that both the reference and the assembly have the
variant type, not wild type. The list variant_list should be a list
of p... |
def abbr(value: Any, limit: int=20) -> str:
"""
Converts a value into its string representation and abbreviates that
representation based on the given length `limit` if necessary.
"""
rep = repr(value)
if len(rep) > limit:
if limit < 3:
raise ValueError('Abbreviation limit m... |
def invalidate_value(
cls,
value: Any,
exc: Type[Exception]=EncodingTypeError,
msg: Optional[str]=None,
) -> None:
"""
Throws a standard exception for when a value is not encodable by an
encoder.
"""
raise exc(
"Value `{rep}` of typ... |
def parse_type_str(expected_base=None, with_arrlist=False):
"""
Used by BaseCoder subclasses as a convenience for implementing the
``from_type_str`` method required by ``ABIRegistry``. Useful if normalizing
then parsing a type string with an (optional) expected base is required in
that method.
... |
def parse_tuple_type_str(old_from_type_str):
"""
Used by BaseCoder subclasses as a convenience for implementing the
``from_type_str`` method required by ``ABIRegistry``. Useful if normalizing
then parsing a tuple type string is required in that method.
"""
@functools.wraps(old_from_type_str)
... |
def seek_in_frame(self, pos, *args, **kwargs):
"""
Seeks relative to the total offset of the current contextual frames.
"""
super().seek(self._total_offset + pos, *args, **kwargs) |
def push_frame(self, offset):
"""
Pushes a new contextual frame onto the stack with the given offset and a
return position at the current cursor position then seeks to the new
total offset.
"""
self._frames.append((offset, self.tell()))
self._total_offset += offse... |
def pop_frame(self):
"""
Pops the current contextual frame off of the stack and returns the
cursor to the frame's return position.
"""
try:
offset, return_pos = self._frames.pop()
except IndexError:
raise IndexError('no frames to pop')
self... |
def has_arrlist(type_str):
"""
A predicate that matches a type string with an array dimension list.
"""
try:
abi_type = grammar.parse(type_str)
except exceptions.ParseError:
return False
return abi_type.arrlist is not None |
def is_base_tuple(type_str):
"""
A predicate that matches a tuple type with no array dimension list.
"""
try:
abi_type = grammar.parse(type_str)
except exceptions.ParseError:
return False
return isinstance(abi_type, grammar.TupleType) and abi_type.arrlist is None |
def register_encoder(self, lookup: Lookup, encoder: Encoder, label: str=None) -> None:
"""
Registers the given ``encoder`` under the given ``lookup``. A unique
string label may be optionally provided that can be used to refer to
the registration by name. For more information about argu... |
def register_decoder(self, lookup: Lookup, decoder: Decoder, label: str=None) -> None:
"""
Registers the given ``decoder`` under the given ``lookup``. A unique
string label may be optionally provided that can be used to refer to
the registration by name. For more information about argu... |
def register(self, lookup: Lookup, encoder: Encoder, decoder: Decoder, label: str=None) -> None:
"""
Registers the given ``encoder`` and ``decoder`` under the given
``lookup``. A unique string label may be optionally provided that can
be used to refer to the registration by name.
... |
def unregister(self, label: str) -> None:
"""
Unregisters the entries in the encoder and decoder registries which
have the label ``label``.
"""
self.unregister_encoder(label)
self.unregister_decoder(label) |
def has_encoder(self, type_str: abi.TypeStr) -> bool:
"""
Returns ``True`` if an encoder is found for the given type string
``type_str``. Otherwise, returns ``False``. Raises
:class:`~eth_abi.exceptions.MultipleEntriesFound` if multiple encoders
are found.
"""
t... |
def copy(self):
"""
Copies a registry such that new registrations can be made or existing
registrations can be unregistered without affecting any instance from
which a copy was obtained. This is useful if an existing registry
fulfills most of a user's needs but requires one or t... |
def encode_single(self, typ: TypeStr, arg: Any) -> bytes:
"""
Encodes the python value ``arg`` as a binary value of the ABI type
``typ``.
:param typ: The string representation of the ABI type that will be used
for encoding e.g. ``'uint256'``, ``'bytes[]'``, ``'(int,int)'``,
... |
def encode_abi(self, types: Iterable[TypeStr], args: Iterable[Any]) -> bytes:
"""
Encodes the python values in ``args`` as a sequence of binary values of
the ABI types in ``types`` via the head-tail mechanism.
:param types: An iterable of string representations of the ABI types
... |
def is_encodable(self, typ: TypeStr, arg: Any) -> bool:
"""
Determines if the python value ``arg`` is encodable as a value of the
ABI type ``typ``.
:param typ: A string representation for the ABI type against which the
python value ``arg`` will be checked e.g. ``'uint256'``,... |
def decode_single(self, typ: TypeStr, data: Decodable) -> Any:
"""
Decodes the binary value ``data`` of the ABI type ``typ`` into its
equivalent python value.
:param typ: The string representation of the ABI type that will be used for
decoding e.g. ``'uint256'``, ``'bytes[]'... |
def decode_abi(self, types: Iterable[TypeStr], data: Decodable) -> Tuple[Any, ...]:
"""
Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of stri... |
def parse(self, type_str):
"""
Parses a type string into an appropriate instance of
:class:`~eth_abi.grammar.ABIType`. If a type string cannot be parsed,
throws :class:`~eth_abi.exceptions.ParseError`.
:param type_str: The type string to be parsed.
:returns: An instance... |
async def create_turn_endpoint(protocol_factory, server_addr, username, password,
lifetime=600, ssl=False, transport='udp'):
"""
Create datagram connection relayed over TURN.
"""
loop = asyncio.get_event_loop()
if transport == 'tcp':
_, inner_protocol = await l... |
async def connect(self):
"""
Create a TURN allocation.
"""
request = stun.Message(message_method=stun.Method.ALLOCATE,
message_class=stun.Class.REQUEST)
request.attributes['LIFETIME'] = self.lifetime
request.attributes['REQUESTED-TRANSPORT']... |
async def delete(self):
"""
Delete the TURN allocation.
"""
if self.refresh_handle:
self.refresh_handle.cancel()
self.refresh_handle = None
request = stun.Message(message_method=stun.Method.REFRESH,
message_class=stun.Class.... |
async def refresh(self):
"""
Periodically refresh the TURN allocation.
"""
while True:
await asyncio.sleep(5/6 * self.lifetime)
request = stun.Message(message_method=stun.Method.REFRESH,
message_class=stun.Class.REQUEST)
... |
async def request(self, request):
"""
Execute a STUN transaction and return the response.
"""
assert request.transaction_id not in self.transactions
if self.integrity_key:
self.__add_authentication(request)
transaction = stun.Transaction(request, self.server... |
async def send_data(self, data, addr):
"""
Send data to a remote host via the TURN server.
"""
channel = self.peer_to_channel.get(addr)
if channel is None:
channel = self.channel_number
self.channel_number += 1
self.channel_to_peer[channel] = a... |
def send_stun(self, message, addr):
"""
Send a STUN message to the TURN server.
"""
logger.debug('%s > %s %s', self, addr, message)
self._send(bytes(message)) |
def get_extra_info(self, name, default=None):
"""
Return optional transport information.
- `'related_address'`: the related address
- `'sockname'`: the relayed address
"""
if name == 'related_address':
return self.__inner_protocol.transport.get_extra_info('so... |
def sendto(self, data, addr):
"""
Sends the `data` bytes to the remote peer given `addr`.
This will bind a TURN channel as necessary.
"""
asyncio.ensure_future(self.__inner_protocol.send_data(data, addr)) |
def candidate_foundation(candidate_type, candidate_transport, base_address):
"""
See RFC 5245 - 4.1.1.3. Computing Foundations
"""
key = '%s|%s|%s' % (candidate_type, candidate_transport, base_address)
return hashlib.md5(key.encode('ascii')).hexdigest() |
def candidate_priority(candidate_component, candidate_type, local_pref=65535):
"""
See RFC 5245 - 4.1.2.1. Recommended Formula
"""
if candidate_type == 'host':
type_pref = 126
elif candidate_type == 'prflx':
type_pref = 110
elif candidate_type == 'srflx':
type_pref = 100
... |
def from_sdp(cls, sdp):
"""
Parse a :class:`Candidate` from SDP.
.. code-block:: python
Candidate.from_sdp(
'6815297761 1 udp 659136 1.2.3.4 31102 typ host generation 0')
"""
bits = sdp.split()
if len(bits) < 8:
raise ValueError('SDP d... |
def to_sdp(self):
"""
Return a string representation suitable for SDP.
"""
sdp = '%s %d %s %d %s %d typ %s' % (
self.foundation,
self.component,
self.transport,
self.priority,
self.host,
self.port,
self.t... |
def can_pair_with(self, other):
"""
A local candidate is paired with a remote candidate if and only if
the two candidates have the same component ID and have the same IP
address version.
"""
a = ipaddress.ip_address(self.host)
b = ipaddress.ip_address(other.host)
... |
def candidate_pair_priority(local, remote, ice_controlling):
"""
See RFC 5245 - 5.7.2. Computing Pair Priority and Ordering Pairs
"""
G = ice_controlling and local.priority or remote.priority
D = ice_controlling and remote.priority or local.priority
return (1 << 32) * min(G, D) + 2 * max(G, D) +... |
def get_host_addresses(use_ipv4, use_ipv6):
"""
Get local IP addresses.
"""
addresses = []
for interface in netifaces.interfaces():
ifaddresses = netifaces.ifaddresses(interface)
for address in ifaddresses.get(socket.AF_INET, []):
if use_ipv4 and address['addr'] != '127.0... |
async def server_reflexive_candidate(protocol, stun_server):
"""
Query STUN server to obtain a server-reflexive candidate.
"""
# lookup address
loop = asyncio.get_event_loop()
stun_server = (
await loop.run_in_executor(None, socket.gethostbyname, stun_server[0]),
stun_server[1])
... |
def sort_candidate_pairs(pairs, ice_controlling):
"""
Sort a list of candidate pairs.
"""
def pair_priority(pair):
return -candidate_pair_priority(pair.local_candidate,
pair.remote_candidate,
ice_controlling)
pa... |
async def request(self, request, addr, integrity_key=None, retransmissions=None):
"""
Execute a STUN transaction and return the response.
"""
assert request.transaction_id not in self.transactions
if integrity_key is not None:
request.add_message_integrity(integrity_... |
def send_stun(self, message, addr):
"""
Send a STUN message.
"""
self.__log_debug('> %s %s', addr, message)
self.transport.sendto(bytes(message), addr) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.