func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def ape(self, ape_path=None):
# TODO: simplify - make ApE look in PATH only
cmd = 'ApE'
if ape_path is None:
# Check for ApE in PATH
ape_executables = []
for path in os.environ['PATH'].split(os.pathsep):
exepath = os.path.join(path, cm... | Open in ApE if `ApE` is in your command line path. |
def copy(self):
# Significant performance improvements by skipping alphabet check
features_copy = [feature.copy() for feature in self.features]
copy = type(self)(self.top.seq, circular=self.circular,
features=features_copy, name=self.name,
... | Create a copy of the current instance.
:returns: A safely-editable copy of the current sequence.
:rtype: coral.DNA |
def circularize(self):
if self.top[-1].seq == '-' and self.bottom[0].seq == '-':
raise ValueError('Cannot circularize - termini disconnected.')
if self.bottom[-1].seq == '-' and self.top[0].seq == '-':
raise ValueError('Cannot circularize - termini disconnected.')
... | Circularize linear DNA.
:returns: A circularized version of the current sequence.
:rtype: coral.DNA |
def display(self):
try:
from IPython.display import HTML
import uuid
except ImportError:
raise IPythonDisplayImportError
sequence_json = self.json()
d3cdn = '//d3js.org/d3.v3.min.js'
div_id = 'sequence_{}'.format(uuid.uuid1())
... | Display a visualization of the sequence in an IPython notebook. |
def excise(self, feature):
rotated = self.rotate_to_feature(feature)
excised = rotated[feature.stop - feature.start:]
return excised | Removes feature from circular plasmid and linearizes. Automatically
reorients at the base just after the feature. This operation is
complementary to the .extract() method.
:param feature_name: The feature to remove.
:type feature_name: coral.Feature |
def extract(self, feature, remove_subfeatures=False):
extracted = self[feature.start:feature.stop]
# Turn gaps into Ns or Xs
for gap in feature.gaps:
for i in range(*gap):
extracted[i] = self._any_char
if remove_subfeatures:
# Keep only th... | Extract a feature from the sequence. This operation is complementary
to the .excise() method.
:param feature: Feature object.
:type feature: coral.sequence.Feature
:param remove_subfeatures: Remove all features in the extracted
sequence aside from the ... |
def flip(self):
copy = self.copy()
copy.top, copy.bottom = copy.bottom, copy.top
copy.features = [_flip_feature(f, len(self)) for f in copy.features]
return copy | Flip the DNA - swap the top and bottom strands.
:returns: Flipped DNA (bottom strand is now top strand, etc.).
:rtype: coral.DNA |
def linearize(self, index=0):
if not self.circular:
raise ValueError('Cannot relinearize linear DNA.')
copy = self.copy()
# Snip at the index
if index:
return copy[index:] + copy[:index]
copy.circular = False
copy.top.circular = False
... | Linearize circular DNA at an index.
:param index: index at which to linearize.
:type index: int
:returns: A linearized version of the current sequence.
:rtype: coral.DNA
:raises: ValueError if the input is linear DNA. |
def locate(self, pattern):
top_matches = self.top.locate(pattern)
bottom_matches = self.bottom.locate(pattern)
return [top_matches, bottom_matches] | Find sequences matching a pattern. For a circular sequence, the
search extends over the origin.
:param pattern: str or NucleicAcidSequence for which to find matches.
:type pattern: str or coral.DNA
:returns: A list of top and bottom strand indices of matches.
:rtype: list of lis... |
def rotate(self, n):
if not self.circular and n != 0:
raise ValueError('Cannot rotate linear DNA')
else:
copy = self.copy()
copy.top = self.top.rotate(n)
copy.bottom = self.bottom.rotate(-n)
copy.features = []
for feature i... | Rotate Sequence by n bases.
:param n: Number of bases to rotate.
:type n: int
:returns: The current sequence reoriented at `index`.
:rtype: coral.DNA
:raises: ValueError if applied to linear sequence or `index` is
negative. |
def reverse_complement(self):
copy = self.copy()
# Note: if sequence is double-stranded, swapping strand is basically
# (but not entirely) the same thing - gaps affect accuracy.
copy.top = self.top.reverse_complement()
copy.bottom = self.bottom.reverse_complement()
... | Reverse complement the DNA.
:returns: A reverse-complemented instance of the current sequence.
:rtype: coral.DNA |
def select_features(self, term, by='name', fuzzy=False):
features = []
if fuzzy:
fuzzy_term = term.lower()
for feature in self.features:
if fuzzy_term in feature.__getattribute__(by).lower():
features.append(feature)
else:
... | Select features from the features list based on feature name,
gene, or locus tag.
:param term: Search term.
:type term: str
:param by: Feature attribute to search by. Options are 'name',
'gene', and 'locus_tag'.
:type by: str
:param fuzzy: If ... |
def to_feature(self, name=None, feature_type='misc_feature'):
if name is None:
if not self.name:
raise ValueError('name attribute missing from DNA instance'
' and arguments')
name = self.name
return Feature(name, start=0, ... | Create a feature from the current object.
:param name: Name for the new feature. Must be specified if the DNA
instance has no .name attribute.
:type name: str
:param feature_type: The type of feature (genbank standard).
:type feature_type: str |
def cuts_outside(self):
for index in self.cut_site:
if index < 0 or index > len(self.recognition_site) + 1:
return True
return False | Report whether the enzyme cuts outside its recognition site.
Cutting at the very end of the site returns True.
:returns: Whether the enzyme will cut outside its recognition site.
:rtype: bool |
def copy(self):
return type(self)(self.anneal, self.tm, overhang=self.overhang,
name=self.name, note=self.note) | Generate a Primer copy.
:returns: A safely-editable copy of the current primer.
:rtype: coral.DNA |
def tm(seq, dna_conc=50, salt_conc=50, parameters='cloning'):
if parameters == 'breslauer':
params = tm_params.BRESLAUER
elif parameters == 'sugimoto':
params = tm_params.SUGIMOTO
elif parameters == 'santalucia96':
params = tm_params.SANTALUCIA96
elif parameters == 'santaluc... | Calculate nearest-neighbor melting temperature (Tm).
:param seq: Sequence for which to calculate the tm.
:type seq: coral.DNA
:param dna_conc: DNA concentration in nM.
:type dna_conc: float
:param salt_conc: Salt concentration in mM.
:type salt_conc: float
:param parameters: Nearest-neighbo... |
def _pair_deltas(seq, pars):
delta0 = 0
delta1 = 0
for i in range(len(seq) - 1):
curchar = seq[i:i + 2]
delta0 += pars['delta_h'][curchar]
delta1 += pars['delta_s'][curchar]
return delta0, delta1 | Add up nearest-neighbor parameters for a given sequence.
:param seq: DNA sequence for which to sum nearest neighbors
:type seq: str
:param pars: parameter set to use
:type pars: dict
:returns: nearest-neighbor delta_H and delta_S sums.
:rtype: tuple of floats |
def breslauer_corrections(seq, pars_error):
deltas_corr = [0, 0]
contains_gc = 'G' in str(seq) or 'C' in str(seq)
only_at = str(seq).count('A') + str(seq).count('T') == len(seq)
symmetric = seq == seq.reverse_complement()
terminal_t = str(seq)[0] == 'T' + str(seq)[-1] == 'T'
for i, delta in... | Sum corrections for Breslauer '84 method.
:param seq: sequence for which to calculate corrections.
:type seq: str
:param pars_error: dictionary of error corrections
:type pars_error: dict
:returns: Corrected delta_H and delta_S parameters
:rtype: list of floats |
def santalucia98_corrections(seq, pars_error):
deltas_corr = [0, 0]
first = str(seq)[0]
last = str(seq)[-1]
start_gc = first == 'G' or first == 'C'
start_at = first == 'A' or first == 'T'
end_gc = last == 'G' or last == 'C'
end_at = last == 'A' or last == 'T'
init_gc = start_gc + en... | Sum corrections for SantaLucia '98 method (unified parameters).
:param seq: sequence for which to calculate corrections.
:type seq: str
:param pars_error: dictionary of error corrections
:type pars_error: dict
:returns: Corrected delta_H and delta_S parameters
:rtype: list of floats |
def MAFFT(sequences, gap_open=1.53, gap_extension=0.0, retree=2):
arguments = ['mafft']
arguments += ['--op', str(gap_open)]
arguments += ['--ep', str(gap_extension)]
arguments += ['--retree', str(retree)]
arguments.append('input.fasta')
tempdir = tempfile.mkdtemp()
try:
with op... | A Coral wrapper for the MAFFT command line multiple sequence aligner.
:param sequences: A list of sequences to align.
:type sequences: List of homogeneous sequences (all DNA, or all RNA,
etc.)
:param gap_open: --op (gap open) penalty in MAFFT cli.
:type gap_open: float
:param g... |
def repeats(seq, size):
seq = str(seq)
n_mers = [seq[i:i + size] for i in range(len(seq) - size + 1)]
counted = Counter(n_mers)
# No one cares about patterns that appear once, so exclude them
found_repeats = [(key, value) for key, value in counted.iteritems() if
value > 1]
... | Count times that a sequence of a certain size is repeated.
:param seq: Input sequence.
:type seq: coral.DNA or coral.RNA
:param size: Size of the repeat to count.
:type size: int
:returns: Occurrences of repeats and how many
:rtype: tuple of the matched sequence and how many times it occurs |
def gibson(seq_list, linear=False, homology=10, tm=63.0):
# FIXME: Preserve features in overlap
# TODO: set a max length?
# TODO: add 'expected' keyword argument somewhere to automate
# validation
# Remove any redundant (identical) sequences
seq_list = list(set(seq_list))
for seq in seq... | Simulate a Gibson reaction.
:param seq_list: list of DNA sequences to Gibson
:type seq_list: list of coral.DNA
:param linear: Attempt to produce linear, rather than circular,
fragment from input fragments.
:type linear: bool
:param homology_min: minimum bp of homology allowed
... |
def _find_fuse_next(working_list, homology, tm):
# 1. Take the first sequence and find all matches
# Get graphs:
# a) pattern watson : targets watson
# b) pattern watson : targets crick
# c) pattern crick: targets watson
# d) pattern crick: targets crick
pattern = working_list[0... | Find the next sequence to fuse, and fuse it (or raise exception).
:param homology: length of terminal homology in bp
:type homology: int
:raises: AmbiguousGibsonError if there is more than one way for the
fragment ends to combine.
GibsonOverlapError if no homology match can be fou... |
def _fuse_last(working_list, homology, tm):
# 1. Construct graph on self-self
# (destination, size, strand1, strand2)
pattern = working_list[0]
def graph_strands(strand1, strand2):
matchlen = homology_report(pattern, pattern, strand1, strand2,
cutoff=ho... | With one sequence left, attempt to fuse it to itself.
:param homology: length of terminal homology in bp.
:type homology: int
:raises: AmbiguousGibsonError if either of the termini are palindromic
(would bind self-self).
ValueError if the ends are not compatible. |
def homology_report(seq1, seq2, strand1, strand2, cutoff=0, min_tm=63.0,
top_two=False, max_size=500):
# Ensure that strand 1 is Watson and strand 2 is Crick
if strand1 == 'c':
seq1 = seq1.reverse_complement()
if strand2 == 'w':
seq2 = seq2.reverse_complement()
#... | Given two sequences (seq1 and seq2), report the size of all perfect
matches between the 3' end of the top strand of seq1 and the 3' end of
either strand of seq2. In short, in a Gibson reaction, what would bind the
desired part of seq1, given a seq2?
:param seq1: Sequence for which to test 3\' binding o... |
def fetch_yeast_locus_sequence(locus_name, flanking_size=0):
from intermine.webservice import Service
service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')
# Get a new query on the class (table) you will be querying:
query = service.new_query('Gene')
if flanking_size > 0:
... | Acquire a sequence from SGD http://www.yeastgenome.org.
:param locus_name: Common name or systematic name for the locus (e.g. ACT1
or YFL039C).
:type locus_name: str
:param flanking_size: The length of flanking DNA (on each side) to return
:type flanking_size: int |
def get_yeast_sequence(chromosome, start, end, reverse_complement=False):
import requests
if start != end:
if reverse_complement:
rev_option = '-REV'
else:
rev_option = ''
param_url = '&chr=' + str(chromosome) + '&beg=' + str(start) + \
'&... | Acquire a sequence from SGD http://www.yeastgenome.org
:param chromosome: Yeast chromosome.
:type chromosome: int
:param start: A biostart.
:type start: int
:param end: A bioend.
:type end: int
:param reverse_complement: Get the reverse complement.
:type revervse_complement: bool
:re... |
def get_yeast_gene_location(gene_name):
from intermine.webservice import Service
service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')
# Get a new query on the class (table) you will be querying:
query = service.new_query('Gene')
# The view specifies the output columns
que... | Acquire the location of a gene from SGD http://www.yeastgenome.org
:param gene_name: Name of the gene.
:type gene_name: string
:returns location: [int: chromosome, int:biostart, int:bioend, int:strand]
:rtype location: list |
def get_gene_id(gene_name):
from intermine.webservice import Service
service = Service('http://yeastmine.yeastgenome.org/yeastmine/service')
# Get a new query on the class (table) you will be querying:
query = service.new_query('Gene')
# The view specifies the output columns
query.add_view(... | Retrieve systematic yeast gene name from the common name.
:param gene_name: Common name for yeast gene (e.g. ADE2).
:type gene_name: str
:returns: Systematic name for yeast gene (e.g. YOR128C).
:rtype: str |
def get_yeast_promoter_ypa(gene_name):
import requests
loc = get_yeast_gene_location(gene_name)
gid = get_gene_id(gene_name)
ypa_baseurl = 'http://ypa.csbb.ntu.edu.tw/do'
params = {'act': 'download',
'nucle': 'InVitro',
'right': str(loc[2]),
'left': str... | Retrieve promoter from Yeast Promoter Atlas
(http://ypa.csbb.ntu.edu.tw).
:param gene_name: Common name for yeast gene.
:type gene_name: str
:returns: Double-stranded DNA sequence of the promoter.
:rtype: coral.DNA |
def _grow_overlaps(dna, melting_temp, require_even, length_max, overlap_min,
min_exception):
# TODO: prevent growing overlaps from bumping into each other -
# should halt when it happens, give warning, let user decide if they still
# want the current construct
# Another option wo... | Grows equidistant overlaps until they meet specified constraints.
:param dna: Input sequence.
:type dna: coral.DNA
:param melting_temp: Ideal Tm of the overlaps, in degrees C.
:type melting_temp: float
:param require_even: Require that the number of oligonucleotides is even.
:type require_even:... |
def _recalculate_overlaps(dna, overlaps, oligo_indices):
for i, overlap in enumerate(overlaps):
first_index = oligo_indices[0][i + 1]
second_index = oligo_indices[1][i]
overlap = dna[first_index:second_index]
overlaps[i] = overlap
return overlaps | Recalculate overlap sequences based on the current overlap indices.
:param dna: Sequence being split into oligos.
:type dna: coral.DNA
:param overlaps: Current overlaps - a list of DNA sequences.
:type overlaps: coral.DNA list
:param oligo_indices: List of oligo indices (starts and stops).
:typ... |
def _expand_overlap(dna, oligo_indices, index, oligos, length_max):
left_len = len(oligos[index])
right_len = len(oligos[index + 1])
# If one of the oligos is max size, increase the other one
if right_len == length_max:
oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right')
... | Given an overlap to increase, increases smaller oligo.
:param dna: Sequence being split into oligos.
:type dna: coral.DNA
:param oligo_indices: index of oligo starts and stops
:type oligo_indices: list
:param index: index of the oligo
:type index: int
:param left_len: length of left oligo
... |
def _adjust_overlap(positions_list, index, direction):
if direction == 'left':
positions_list[index + 1] -= 1
elif direction == 'right':
positions_list[index] += 1
else:
raise ValueError('direction must be \'left\' or \'right\'.')
return positions_list | Increase overlap to the right or left of an index.
:param positions_list: list of overlap positions
:type positions_list: list
:param index: index of the overlap to increase.
:type index: int
:param direction: which side of the overlap to increase - left or right.
:type direction: str
:retu... |
def design_assembly(self):
# Input parameters needed to design the oligos
length_range = self.kwargs['length_range']
oligo_number = self.kwargs['oligo_number']
require_even = self.kwargs['require_even']
melting_temp = self.kwargs['tm']
overlap_min = self.kwargs['... | Design the overlapping oligos.
:returns: Assembly oligos, and the sequences, Tms, and indices of their
overlapping regions.
:rtype: dict |
def primers(self, tm=60):
self.primers = coral.design.primers(self.template, tm=tm)
return self.primers | Design primers for amplifying the assembled sequence.
:param tm: melting temperature (lower than overlaps is best).
:type tm: float
:returns: Primer list (the output of coral.design.primers).
:rtype: list |
def write(self, path):
with open(path, 'wb') as oligo_file:
oligo_writer = csv.writer(oligo_file, delimiter=',',
quoting=csv.QUOTE_MINIMAL)
oligo_writer.writerow(['name', 'oligo', 'notes'])
for i, oligo in enumerate(self.oligos):... | Write assembly oligos and (if applicable) primers to csv.
:param path: path to csv file, including .csv extension.
:type path: str |
def write_map(self, path):
starts = [index[0] for index in self.overlap_indices]
features = []
for i, start in enumerate(starts):
stop = start + len(self.overlaps[i])
name = 'overlap {}'.format(i + 1)
feature_type = 'misc'
strand = 0
... | Write genbank map that highlights overlaps.
:param path: full path to .gb file to write.
:type path: str |
def coding_sequence(rna):
if isinstance(rna, coral.DNA):
rna = transcribe(rna)
codons_left = len(rna) // 3
start_codon = coral.RNA('aug')
stop_codons = [coral.RNA('uag'), coral.RNA('uga'), coral.RNA('uaa')]
start = None
stop = None
valid = [None, None]
index = 0
while co... | Extract coding sequence from an RNA template.
:param seq: Sequence from which to extract a coding sequence.
:type seq: coral.RNA
:param material: Type of sequence ('dna' or 'rna')
:type material: str
:returns: The first coding sequence (start codon -> stop codon) matched
from 5' to 3'... |
def update(self):
# Download http://rebase.neb.com/rebase/link_withref to tmp
self._tmpdir = tempfile.mkdtemp()
try:
self._rebase_file = self._tmpdir + '/rebase_file'
print 'Downloading latest enzyme definitions'
url = 'http://rebase.neb.com/rebase/li... | Update definitions. |
def _process_file(self):
print 'Processing file'
with open(self._rebase_file, 'r') as f:
raw = f.readlines()
names = [line.strip()[3:] for line in raw if line.startswith('<1>')]
seqs = [line.strip()[3:] for line in raw if line.startswith('<5>')]
if len(names)... | Process rebase file into dict with name and cut site information. |
def copy(self):
return type(self)(str(self._sequence), features=self.features,
run_checks=False) | Create a copy of the current instance.
:returns: A safely editable copy of the current sequence.
:rtype: coral.Peptide |
def tempdir(fun):
def wrapper(*args, **kwargs):
self = args[0]
if os.path.isdir(self._tempdir):
shutil.rmtree(self._tempdir)
self._tempdir = tempfile.mkdtemp()
# If the method raises an exception, delete the temporary dir
try:
retval = fun(*args, ... | For use as a decorator of instance methods - creates a temporary dir
named self._tempdir and then deletes it after the method runs.
:param fun: function to decorate
:type fun: instance method |
def convert_sequence(seq, to_material):
if isinstance(seq, coral.DNA) and to_material == 'rna':
# Transcribe
# Can't transcribe a gap
if '-' in seq:
raise ValueError('Cannot transcribe gapped DNA')
# Convert DNA chars to RNA chars
origin = ALPHABETS['dna'][:-... | Translate a DNA sequence into peptide sequence.
The following conversions are supported:
Transcription (seq is DNA, to_material is 'rna')
Reverse transcription (seq is RNA, to_material is 'dna')
Translation (seq is RNA, to_material is 'peptide')
:param seq: DNA or RNA sequence.
:ty... |
def gc(self):
gc = len([base for base in self.seq if base == 'C' or base == 'G'])
return float(gc) / len(self) | Find the frequency of G and C in the current sequence. |
def is_rotation(self, other):
if len(self) != len(other):
return False
for i in range(len(self)):
if self.rotate(i) == other:
return True
return False | Determine whether two sequences are the same, just at different
rotations.
:param other: The sequence to check for rotational equality.
:type other: coral.sequence._sequence.Sequence |
def linearize(self, index=0):
if not self.circular and index != 0:
raise ValueError('Cannot relinearize a linear sequence.')
copy = self.copy()
# Snip at the index
if index:
return copy[index:] + copy[:index]
copy.circular = False
return c... | Linearize the Sequence at an index.
:param index: index at which to linearize.
:type index: int
:returns: A linearized version of the current sequence.
:rtype: coral.sequence._sequence.Sequence
:raises: ValueError if the input is a linear sequence. |
def locate(self, pattern):
if self.circular:
if len(pattern) >= 2 * len(self):
raise ValueError('Search pattern longer than searchable ' +
'sequence.')
seq = self + self[:len(pattern) - 1]
return super(NucleicAcid, seq... | Find sequences matching a pattern.
:param pattern: Sequence for which to find matches.
:type pattern: str
:returns: Indices of pattern matches.
:rtype: list of ints |
def mw(self):
counter = collections.Counter(self.seq.lower())
mw_a = counter['a'] * 313.2
mw_t = counter['t'] * 304.2
mw_g = counter['g'] * 289.2
mw_c = counter['c'] * 329.2
mw_u = counter['u'] * 306.2
if self.material == 'dna':
return mw_a + ... | Calculate the molecular weight.
:returns: The molecular weight of the current sequence in amu.
:rtype: float |
def rotate(self, n):
if not self.circular and n != 0:
raise ValueError('Cannot rotate a linear sequence')
else:
rotated = self[-n:] + self[:-n]
return rotated.circularize() | Rotate Sequence by n bases.
:param n: Number of bases to rotate.
:type n: int
:returns: The current sequence reoriented at `index`.
:rtype: coral.sequence._sequence.Sequence
:raises: ValueError if applied to linear sequence or `index` is
negative. |
def five_resect(dna, n_bases):
new_instance = dna.copy()
if n_bases >= len(dna):
new_instance.top.seq = ''.join(['-' for i in range(len(dna))])
else:
new_instance.top.seq = '-' * n_bases + str(dna)[n_bases:]
new_instance = _remove_end_gaps(new_instance)
return new_instance | Remove bases from 5' end of top strand.
:param dna: Sequence to resect.
:type dna: coral.DNA
:param n_bases: Number of bases cut back.
:type n_bases: int
:returns: DNA sequence resected at the 5' end by n_bases.
:rtype: coral.DNA |
def _remove_end_gaps(sequence):
# Count terminal blank sequences
def count_end_gaps(seq):
gap = coral.DNA('-')
count = 0
for base in seq:
if base == gap:
count += 1
else:
break
return count
top_left = count_end_gaps... | Removes double-stranded gaps from ends of the sequence.
:returns: The current sequence with terminal double-strand gaps ('-')
removed.
:rtype: coral.DNA |
def needle(reference, query, gap_open=-15, gap_extend=0,
matrix=submat.DNA_SIMPLE):
# Align using cython Needleman-Wunsch
aligned_ref, aligned_res = aligner(str(reference),
str(query),
gap_open=gap_open,
... | Do a Needleman-Wunsch alignment.
:param reference: Reference sequence.
:type reference: coral.DNA
:param query: Sequence to align against the reference.
:type query: coral.DNA
:param gapopen: Penalty for opening a gap.
:type gapopen: float
:param gapextend: Penalty for extending a gap.
... |
def needle_msa(reference, results, gap_open=-15, gap_extend=0,
matrix=submat.DNA_SIMPLE):
gap = '-'
# Convert alignments to list of strings
alignments = []
for result in results:
ref_dna, res_dna, score = needle(reference, result, gap_open=gap_open,
... | Create a multiple sequence alignment based on aligning every result
sequence against the reference, then inserting gaps until every aligned
reference is identical |
def needle_multi(references, queries, gap_open=-15, gap_extend=0,
matrix=submat.DNA_SIMPLE):
pool = multiprocessing.Pool()
try:
args_list = [[ref, que, gap_open, gap_extend, matrix] for ref, que in
zip(references, queries)]
aligned = pool.map(run_needle... | Batch process of sequencing split over several cores. Acts just like
needle but sequence inputs are lists.
:param references: References sequence.
:type references: coral.DNA list
:param queries: Sequences to align against the reference.
:type queries: coral.DNA list
:param gap_open: Penalty fo... |
def import_global(
name, modules=None, exceptions=DummyException, locals_=None,
globals_=None, level=-1):
frame = None
try:
# If locals_ or globals_ are not given, autodetect them by inspecting
# the current stack
if locals_ is None or globals_ is None:
i... | Import the requested items into the global scope
WARNING! this method _will_ overwrite your global scope
If you have a variable named "path" and you call import_global('sys')
it will be overwritten with sys.path
Args:
name (str): the name of the module to import, e.g. sys
modules (str)... |
def camel_to_underscore(name):
output = []
for i, c in enumerate(name):
if i > 0:
pc = name[i - 1]
if c.isupper() and not pc.isupper() and pc != '_':
# Uppercase and the previous character isn't upper/underscore?
# Add the underscore
... | Convert camel case style naming to underscore style naming
If there are existing underscores they will be collapsed with the
to-be-added underscores. Multiple consecutive capital letters will not be
split except for the last one.
>>> camel_to_underscore('SpamEggsAndBacon')
'spam_eggs_and_bacon'
... |
def timesince(dt, default='just now'):
if isinstance(dt, datetime.timedelta):
diff = dt
else:
now = datetime.datetime.now()
diff = abs(now - dt)
periods = (
(diff.days / 365, 'year', 'years'),
(diff.days % 365 / 30, 'month', 'months'),
(diff.days % 30 / 7... | Returns string representing 'time since' e.g.
3 days ago, 5 hours ago etc.
>>> now = datetime.datetime.now()
>>> timesince(now)
'just now'
>>> timesince(now - datetime.timedelta(seconds=1))
'1 second ago'
>>> timesince(now - datetime.timedelta(seconds=2))
'2 seconds ago'
>>> timesin... |
def timedelta_to_seconds(delta):
# Only convert to float if needed
if delta.microseconds:
total = delta.microseconds * 1e-6
else:
total = 0
total += delta.seconds
total += delta.days * 60 * 60 * 24
return total | Convert a timedelta to seconds with the microseconds as fraction
Note that this method has become largely obsolete with the
`timedelta.total_seconds()` method introduced in Python 2.7.
>>> from datetime import timedelta
>>> '%d' % timedelta_to_seconds(timedelta(days=1))
'86400'
>>> '%d' % time... |
def format_time(timestamp, precision=datetime.timedelta(seconds=1)):
precision_seconds = precision.total_seconds()
if isinstance(timestamp, six.string_types + six.integer_types + (float, )):
try:
castfunc = six.integer_types[-1]
timestamp = datetime.timedelta(seconds=castfun... | Formats timedelta/datetime/seconds
>>> format_time('1')
'0:00:01'
>>> format_time(1.234)
'0:00:01'
>>> format_time(1)
'0:00:01'
>>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
'2000-01-02 03:04:05'
>>> format_time(datetime.date(2000, 1, 2))
'2000-01-02'
>>> format... |
def get_terminal_size(): # pragma: no cover
try:
# Default to 79 characters for IPython notebooks
from IPython import get_ipython
ipython = get_ipython()
from ipykernel import zmqshell
if isinstance(ipython, zmqshell.ZMQInteractiveShell):
return 79, 24
e... | Get the current size of your terminal
Multiple returns are not always a good idea, but in this case it greatly
simplifies the code so I believe it's justified. It's not the prettiest
function but that's never really possible with cross-platform code.
Returns:
width, height: Two integers contai... |
def AsyncSearchUsers(self, Target):
if not hasattr(self, '_AsyncSearchUsersCommands'):
self._AsyncSearchUsersCommands = []
self.RegisterEventHandler('Reply', self._AsyncSearchUsersReplyHandler)
command = Command('SEARCH USERS %s' % tounicode(Target), 'USERS', False, self... | Asynchronously searches for Skype users.
:Parameters:
Target : unicode
Search target (name or email address).
:return: A search identifier. It will be passed along with the results to the
`SkypeEvents.AsyncSearchUsersFinished` event after the search is completed.... |
def Attach(self, Protocol=5, Wait=True):
try:
self._Api.protocol = Protocol
self._Api.attach(self.Timeout, Wait)
except SkypeAPIError:
self.ResetCache()
raise | Establishes a connection to Skype.
:Parameters:
Protocol : int
Minimal Skype protocol version.
Wait : bool
If set to False, blocks forever until the connection is established. Otherwise, timeouts
after the `Timeout`. |
def Call(self, Id=0):
o = Call(self, Id)
o.Status # Test if such a call exists.
return o | Queries a call object.
:Parameters:
Id : int
Call identifier.
:return: Call object.
:rtype: `call.Call` |
def ChangeUserStatus(self, Status):
if self.CurrentUserStatus.upper() == Status.upper():
return
self._ChangeUserStatus_Event = threading.Event()
self._ChangeUserStatus_Status = Status.upper()
self.RegisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus)
... | Changes the online status for the current user.
:Parameters:
Status : `enums`.cus*
New online status for the user.
:note: This function waits until the online status changes. Alternatively, use the
`CurrentUserStatus` property to perform an immediate change of stat... |
def Chat(self, Name=''):
o = Chat(self, Name)
o.Status # Tests if such a chat really exists.
return o | Queries a chat object.
:Parameters:
Name : str
Chat name.
:return: A chat object.
:rtype: `chat.Chat` |
def ClearCallHistory(self, Username='ALL', Type=chsAllCalls):
cmd = 'CLEAR CALLHISTORY %s %s' % (str(Type), Username)
self._DoCommand(cmd, cmd) | Clears the call history.
:Parameters:
Username : str
Skypename of the user. A special value of 'ALL' means that entries of all users should
be removed.
Type : `enums`.clt*
Call type. |
def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1):
from api import Command as CommandClass
return CommandClass(Command, Reply, Block, Timeout, Id) | Creates an API command object.
:Parameters:
Command : unicode
Command string.
Reply : unicode
Expected reply. By default any reply is accepted (except errors which raise an
`SkypeError` exception).
Block : bool
If set to True, `SendC... |
def Conference(self, Id=0):
o = Conference(self, Id)
if Id <= 0 or not o.Calls:
raise SkypeError(0, 'Unknown conference')
return o | Queries a call conference object.
:Parameters:
Id : int
Conference Id.
:return: A conference object.
:rtype: `Conference` |
def CreateChatWith(self, *Usernames):
return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1]) | Creates a chat with one or more users.
:Parameters:
Usernames : str
One or more Skypenames of the users.
:return: A chat object
:rtype: `Chat`
:see: `Chat.AddMembers` |
def CreateGroup(self, GroupName):
groups = self.CustomGroups
self._DoCommand('CREATE GROUP %s' % tounicode(GroupName))
for g in self.CustomGroups:
if g not in groups and g.DisplayName == GroupName:
return g
raise SkypeError(0, 'Group creating failed') | Creates a custom contact group.
:Parameters:
GroupName : unicode
Group name.
:return: A group object.
:rtype: `Group`
:see: `DeleteGroup` |
def CreateSms(self, MessageType, *TargetNumbers):
return SmsMessage(self, chop(self._DoCommand('CREATE SMS %s %s' % (MessageType, ', '.join(TargetNumbers))), 2)[1]) | Creates an SMS message.
:Parameters:
MessageType : `enums`.smsMessageType*
Message type.
TargetNumbers : str
One or more target SMS numbers.
:return: An sms message object.
:rtype: `SmsMessage` |
def Greeting(self, Username=''):
for v in self.Voicemails:
if Username and v.PartnerHandle != Username:
continue
if v.Type in (vmtDefaultGreeting, vmtCustomGreeting):
return v | Queries the greeting used as voicemail.
:Parameters:
Username : str
Skypename of the user.
:return: A voicemail object.
:rtype: `Voicemail` |
def Message(self, Id=0):
o = ChatMessage(self, Id)
o.Status # Test if such an id is known.
return o | Queries a chat message object.
:Parameters:
Id : int
Message Id.
:return: A chat message object.
:rtype: `ChatMessage` |
def PlaceCall(self, *Targets):
calls = self.ActiveCalls
reply = self._DoCommand('CALL %s' % ', '.join(Targets))
# Skype for Windows returns the call status which gives us the call Id;
if reply.startswith('CALL '):
return Call(self, chop(reply, 2)[1])
# On lin... | Places a call to a single user or creates a conference call.
:Parameters:
Targets : str
One or more call targets. If multiple targets are specified, a conference call is
created. The call target can be a Skypename, phone number, or speed dial code.
:return: A call obj... |
def Property(self, ObjectType, ObjectId, PropName, Set=None):
return self._Property(ObjectType, ObjectId, PropName, Set) | Queries/sets the properties of an object.
:Parameters:
ObjectType : str
Object type ('USER', 'CALL', 'CHAT', 'CHATMESSAGE', ...).
ObjectId : str
Object Id, depends on the object type.
PropName : str
Name of the property to access.
Set ... |
def SendCommand(self, Command):
try:
self._Api.send_command(Command)
except SkypeAPIError:
self.ResetCache()
raise | Sends an API command.
:Parameters:
Command : `Command`
Command to send. Use `Command` method to create a command. |
def SendSms(self, *TargetNumbers, **Properties):
sms = self.CreateSms(smsMessageTypeOutgoing, *TargetNumbers)
for name, value in Properties.items():
if isinstance(getattr(sms.__class__, name, None), property):
setattr(sms, name, value)
else:
... | Creates and sends an SMS message.
:Parameters:
TargetNumbers : str
One or more target SMS numbers.
Properties
Message properties. Properties available are same as `SmsMessage` object properties.
:return: An sms message object. The message is already sent at ... |
def SendVoicemail(self, Username):
if self._Api.protocol >= 6:
self._DoCommand('CALLVOICEMAIL %s' % Username)
else:
self._DoCommand('VOICEMAIL %s' % Username) | Sends a voicemail to a specified user.
:Parameters:
Username : str
Skypename of the user.
:note: Should return a `Voicemail` object. This is not implemented yet. |
def User(self, Username=''):
if not Username:
Username = self.CurrentUserHandle
o = User(self, Username)
o.OnlineStatus # Test if such a user exists.
return o | Queries a user object.
:Parameters:
Username : str
Skypename of the user.
:return: A user object.
:rtype: `user.User` |
def Voicemail(self, Id):
o = Voicemail(self, Id)
o.Type # Test if such a voicemail exists.
return o | Queries the voicemail object.
:Parameters:
Id : int
Voicemail Id.
:return: A voicemail object.
:rtype: `Voicemail` |
def Connect(self, Username, WaitConnected=False):
if WaitConnected:
self._Connect_Event = threading.Event()
self._Connect_Stream = [None]
self._Connect_Username = Username
self._Connect_ApplicationStreams(self, self.Streams)
self._Owner.Regist... | Connects application to user.
:Parameters:
Username : str
Name of the user to connect to.
WaitConnected : bool
If True, causes the method to wait until the connection is established.
:return: If ``WaitConnected`` is True, returns the stream which can be used... |
def SendDatagram(self, Text, Streams=None):
if Streams is None:
Streams = self.Streams
for s in Streams:
s.SendDatagram(Text) | Sends datagram to application streams.
:Parameters:
Text : unicode
Text to send.
Streams : sequence of `ApplicationStream`
Streams to send the datagram to or None if all currently connected streams should be
used. |
def SendDatagram(self, Text):
self.Application._Alter('DATAGRAM', '%s %s' % (self.Handle, tounicode(Text))) | Sends datagram to stream.
:Parameters:
Text : unicode
Datagram to send. |
def Write(self, Text):
self.Application._Alter('WRITE', '%s %s' % (self.Handle, tounicode(Text))) | Writes data to stream.
:Parameters:
Text : unicode
Data to send. |
def CreateEvent(self, EventId, Caption, Hint):
self._Skype._DoCommand('CREATE EVENT %s CAPTION %s HINT %s' % (tounicode(EventId),
quote(tounicode(Caption)), quote(tounicode(Hint))))
return PluginEvent(self._Skype, EventId) | Creates a custom event displayed in Skype client's events pane.
:Parameters:
EventId : unicode
Unique identifier for the event.
Caption : unicode
Caption text.
Hint : unicode
Hint text. Shown when mouse hoovers over the event.
:return: ... |
def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True,
ContactType=pluginContactTypeAll, MultipleContacts=False):
cmd = 'CREATE MENU_ITEM %s CONTEXT %s CAPTION %s ENABLED %s' % (tounicode(MenuItemId), PluginContext,
q... | Creates custom menu item in Skype client's "Do More" menus.
:Parameters:
MenuItemId : unicode
Unique identifier for the menu item.
PluginContext : `enums`.pluginContext*
Menu item context. Allows to choose in which client windows will the menu item appear.
... |
def Focus(self):
self._Skype._Api.allow_focus(self._Skype.Timeout)
self._Skype._DoCommand('FOCUS') | Brings the client window into focus. |
def OpenDialog(self, Name, *Params):
self._Skype._Api.allow_focus(self._Skype.Timeout)
params = filter(None, (str(Name),) + Params)
self._Skype._DoCommand('OPEN %s' % tounicode(' '.join(params))) | Open dialog. Use this method to open dialogs added in newer Skype versions if there is no
dedicated method in Skype4Py.
:Parameters:
Name : str
Dialog name.
Params : unicode
One or more optional parameters. |
def OpenMessageDialog(self, Username, Text=u''):
self.OpenDialog('IM', Username, tounicode(Text)) | Opens "Send an IM Message" dialog.
:Parameters:
Username : str
Message target.
Text : unicode
Message text. |
def Start(self, Minimized=False, Nosplash=False):
self._Skype._Api.startup(Minimized, Nosplash) | Starts Skype application.
:Parameters:
Minimized : bool
If True, Skype is started minimized in system tray.
Nosplash : bool
If True, no splash screen is displayed upon startup. |
def start(self):
if not self.thread_started:
super(SkypeAPI, self).start()
self.thread_started = True | Start the thread associated with this API object.
Ensure that the call is made no more than once,
to avoid raising a RuntimeError. |
def threads_init(gtk=True):
# enable X11 multithreading
x11.XInitThreads()
if gtk:
from gtk.gdk import threads_init
threads_init() | Enables multithreading support in Xlib and PyGTK.
See the module docstring for more info.
:Parameters:
gtk : bool
May be set to False to skip the PyGTK module. |
def get_skype(self):
skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True)
if not skype_inst:
return
type_ret = Atom()
format_ret = c_int()
nitems_ret = c_ulong()
bytes_after_ret = c_ulong()
winp = pointer(Window())
fail = x... | Returns Skype window ID or None if Skype not running. |
def Join(self, Id):
#self._Alter('JOIN_CONFERENCE', Id)
reply = self._Owner._DoCommand('SET CALL %s JOIN_CONFERENCE %s' % (self.Id, Id),
'CALL %s CONF_ID' % self.Id)
return Conference(self._Owner, reply.split()[-1]) | Joins with another call to form a conference.
:Parameters:
Id : int
Call Id of the other call to join to the conference.
:return: Conference object.
:rtype: `Conference` |
def Avatar(self, Id=1, Set=None):
from warnings import warn
warn('Settings.Avatar: Use Settings.LoadAvatarFromFile instead.', DeprecationWarning, stacklevel=2)
if Set is None:
raise TypeError('Argument \'Set\' is mandatory!')
self.LoadAvatarFromFile(Set, Id) | Sets user avatar picture from file.
:Parameters:
Id : int
Optional avatar Id.
Set : str
New avatar file name.
:deprecated: Use `LoadAvatarFromFile` instead. |
def LoadAvatarFromFile(self, Filename, AvatarId=1):
s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename))
self._Skype._DoCommand('SET %s' % s, s) | Loads user avatar picture from file.
:Parameters:
Filename : str
Name of the avatar file.
AvatarId : int
Optional avatar Id. |
def RingTone(self, Id=1, Set=None):
if Set is None:
return unicode2path(self._Skype._Property('RINGTONE', Id, ''))
self._Skype._Property('RINGTONE', Id, '', path2unicode(Set)) | Returns/sets a ringtone.
:Parameters:
Id : int
Ringtone Id
Set : str
Path to new ringtone or None if the current path should be queried.
:return: Current path if Set=None, None otherwise.
:rtype: str or None |
def RingToneStatus(self, Id=1, Set=None):
if Set is None:
return (self._Skype._Property('RINGTONE', Id, 'STATUS') == 'ON')
self._Skype._Property('RINGTONE', Id, 'STATUS', cndexp(Set, 'ON', 'OFF')) | Enables/disables a ringtone.
:Parameters:
Id : int
Ringtone Id
Set : bool
True/False if the ringtone should be enabled/disabled or None if the current status
should be queried.
:return: Current status if Set=None, None otherwise.
:rtype: ... |
def SaveAvatarToFile(self, Filename, AvatarId=1):
s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename))
self._Skype._DoCommand('GET %s' % s, s) | Saves user avatar picture to file.
:Parameters:
Filename : str
Destination path.
AvatarId : int
Avatar Id |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.