rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
sci_name=organism_element.text elif organism_element.attrib['type']== 'common': com_name=organism_element.text else:
if organism_element.text: sci_name=organism_element.text if (organism_element.attrib['type']== 'common') and not sci_name: if organism_element.text: com_name=organism_element.text if (sci_name == '') and (com_name == ''):
def _parse_organism(element): com_name=sci_name='' for organism_element in element.getchildren(): if organism_element.tag==NS + 'name': if organism_element.attrib['type']== 'scientific': sci_name=organism_element.text elif organism_element.attrib['type']== 'common': com_name=organism_element.text else: append_to_annota...
""" return (self.get_path(target, **kwargs) is not None)
""" return self.get_path(target, **kwargs) is not None
def is_parent_of(self, target=None, **kwargs): """True if target is a descendent of this tree.
outstr = join(outstr, '\n')
outstr = "\n".join(outstr)
def __str__(self): """ __str__(self) -> ""
if element is None :
if not element:
def __init__(self, name, coord, bfactor, occupancy, altloc, fullname, serial_number, element=None): """ Atom object.
lasty = trackheight*(val-minval)/resolution + \
lasty = trackheight*(val-midval)/resolution + \
def draw_line_graph(self, graph): """ draw_line_graph(self, graph) -> [element, element,...]
(self.dbid, value))[0])
(self.dbid, bioentry_id))[0])
def __contains__(self, value): """Check if a primary (internal) id is this namespace (sub database).""" sql = "SELECT COUNT(bioentry_id) FROM bioentry " + \ "WHERE biodatabase_id=%s AND bioentry_id=%s;" return bool(self.adaptor.execute_and_fetch_col0(sql, (self.dbid, value))[0])
answer.features.sort(cmp=lambda x,y: cmp(x.location.start.position, y.location.start.position))
answer.features.sort(key=lambda x : x.location.start.position)
def reverse_complement(self, id=False, name=False, description=False, features=True, annotations=False, letter_annotations=True, dbxrefs=False): """Returns new SeqRecord with reverse complement sequence.
line = line.strip()
line = line[5:].strip()
def __create_motif(line): line = line.strip() ls = line.split() motif = MEMEMotif() motif.length = int(ls[4]) motif._numoccurrences(ls[7]) motif._evalue(ls[13]) return motif
motif.length = int(ls[4]) motif._numoccurrences(ls[7]) motif._evalue(ls[13])
motif.length = int(ls[3]) motif._numoccurrences(ls[6]) motif._evalue(ls[12])
def __create_motif(line): line = line.strip() ls = line.split() motif = MEMEMotif() motif.length = int(ls[4]) motif._numoccurrences(ls[7]) motif._evalue(ls[13]) return motif
from_res = "<%s" % to_res
from_res = "<%s" % str(to_res).lstrip("<").lstrip(">")
def _make_seqfeature(name, from_res, to_res, description, ft_id): """Construct SeqFeature from feature data from parser (PRIVATE).""" #print name, repr(from_res), repr(to_res), "..." if from_res == "?" and to_res == "?": #If this does happen, will need to think about this some more! raise ValueError("Swiss file FT loca...
to_res = ">%s" % from_res
to_res = ">%s" % str(from_res).lstrip("<").lstrip(">")
def _make_seqfeature(name, from_res, to_res, description, ft_id): """Construct SeqFeature from feature data from parser (PRIVATE).""" #print name, repr(from_res), repr(to_res), "..." if from_res == "?" and to_res == "?": #If this does happen, will need to think about this some more! raise ValueError("Swiss file FT loca...
align = AlignIO.read(open("output.2.nex"), "nexus") for old, new in zip(records, align): self.assertEqual(old.id[:9], new.id) self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-",""))
try: align = AlignIO.read(open("output.2.nex"), "nexus") for old, new in zip(records, align): self.assertEqual(old.id[:9], new.id) self.assertEqual(str(new.seq).replace("-",""), str(old.seq).replace("-","")) except NexusError: pass
def test_Prank_simple_with_NEXUS_output(self): """Simple round-trip through app with infile, output in NEXUS output.?.??? files written to cwd - no way to redirect """ records = list(SeqIO.parse(open(self.infile1),"fasta")) #Try using keyword argument, cmdline = PrankCommandline(prank_exe, d=self.infile1, noxml=True) #...
if not isinstance(date, str) or len(date) != 11 \
if not isinstance(date, basestring) or len(date) != 11 \
def _get_date(self, record) : default = "01-JAN-1980" try : date = record.annotations["date"] except KeyError : return default #Cope with a list of one string: if isinstance(date, list) and len(date)==1 : date = date[0] #TODO - allow a Python date object if not isinstance(date, str) or len(date) != 11 \ or date[2] != "...
sys.stderr.write(str(m2))
sys.stderr.write(str(motif))
def compare_motifs (self, motif): if isinstance(motif, MEMEMotif): if not self.pssm: raise ValueError('This motif does not have a PSSM') if not motif.pssm: raise ValueError('The other motif does not have a PSSM') mylen = len(self.pssm) yourlen = len(motif.pssm) myr = None if mylen == yourlen: myr = _corr(self.pssm, mot...
def test_blasp(self):
def test_blastp(self):
def test_blasp(self): """Pairwise BLASTP search""" global exe_names cline = Applications.NcbiblastpCommandline(exe_names["blastp"], query="Fasta/rose.pro", subject="GenBank/NC_005816.faa", evalue=1) self.assertEqual(str(cline), exe_names["blastp"] \ + " -query Fasta/rose.pro -evalue 1" \ + " -subject GenBank/NC_005816....
self.assertTrue(key in id_list)
self.assertTrue(key in ids)
def check_dict_methods(self, rec_dict, keys, ids): self.assertEqual(set(keys), set(rec_dict.keys())) #This is redundant, I just want to make sure len works: self.assertEqual(len(keys), len(rec_dict)) #Make sure boolean evaluation works self.assertEqual(bool(keys), bool(rec_dict)) for key,id in zip(keys, ids): self.asse...
intersect=sets.set(self.ambiguous_values[seqsite]).intersection(sets.set(site[1]))
intersect = set(self.ambiguous_values[seqsite]).intersection(set(site[1]))
def constant(self,matrix=None,delete=[],exclude=[]): """Return a list with all constant characters.""" if not matrix: matrix=self.matrix undelete=[t for t in self.taxlabels if t in matrix and t not in delete] if not undelete: return None elif len(undelete)==1: return [x for x in range(len(matrix[undelete[0]])) if x not...
% ', '.join(sets.set(delete).difference(self.taxlabels)))
% ', '.join(set(delete).difference(self.taxlabels)))
def crop_matrix(self,matrix=None, delete=[], exclude=[]): """Return a matrix without deleted taxa and excluded characters.""" if not matrix: matrix=self.matrix if [t for t in delete if not self._check_taxlabels(t)]: raise NexusError('Unknown taxa: %s' \ % ', '.join(sets.set(delete).difference(self.taxlabels))) if exclu...
handle.close()
file.close()
def quicker_apply_on_multi_fasta(file, function, *args): """Apply a function on each sequence in a multiple FASTA file (OBSOLETE). file - filename of a FASTA format file function - the function you wish to invoke on each record *args - any extra arguments you want passed to the function This function will use quick_F...
self.assert_("STEP 2 / 2 d" in stderrdata)
self.assert_("Progressive alignment ..." in stderrdata, stderrdata)
def test_Mafft_simple(self): """Simple round-trip through app with infile. Result passed to stdout. """ #Use a keyword argument at init, cmdline = MafftCommandline(mafft_exe, input=self.infile1) self.assertEqual(str(eval(repr(cmdline))), str(cmdline)) child = subprocess.Popen(str(cmdline), stdout=subprocess.PIPE, stder...
"Your description cannot be broken into nice lines!"
"Your description cannot be broken into nice lines!:\n%s" \ % repr(text)
def _split_multi_line(self, text, max_len): "Returns a list of strings.""" #TODO - Do the line spliting while preserving white space? text = text.strip() if len(text) < max_len: return [text]
start_end = identifier.rsplit("/",1)[1]
name, start_end = identifier.rsplit("/",1)
def _identifier_split(self, identifier): """Returns (name,start,end) string tuple from an identier.""" if identifier.find("/")!=-1: start_end = identifier.rsplit("/",1)[1] if start_end.count("-")==1: start, end = map(int, start_end.split("-")) name = identifier.split("/",1)[0] return (name, start, end) return (identifi...
name = identifier.split("/",1)[0]
def _identifier_split(self, identifier): """Returns (name,start,end) string tuple from an identier.""" if identifier.find("/")!=-1: start_end = identifier.rsplit("/",1)[1] if start_end.count("-")==1: start, end = map(int, start_end.split("-")) name = identifier.split("/",1)[0] return (name, start, end) return (identifi...
def values(self): """Would be a list of the SeqRecord objects, but not implemented. In general you can be indexing very very large files, with millions of sequences. Loading all these into memory at once as SeqRecord objects would (probably) use up all the RAM. Therefore we simply don't support this dictionary method....
if hasattr(dict, "iteritems"): def values(self): """Would be a list of the SeqRecord objects, but not implemented. In general you can be indexing very very large files, with millions of sequences. Loading all these into memory at once as SeqRecord objects would (probably) use up all the RAM. Therefore we simply don't...
def values(self): """Would be a list of the SeqRecord objects, but not implemented.
Copes mixed case seuqneces, and with the ambiguous nucleotide S (G or C)
Copes mixed case sequences, and with the ambiguous nucleotide S (G or C)
def GC(seq): """Calculates G+C content, returns the percentage (float between 0 and 100). Copes mixed case seuqneces, and with the ambiguous nucleotide S (G or C) when counting the G and C content. The percentage is calculated against the full length, e.g.: >>> from Bio.SeqUtils import GC >>> GC("ACTGN") 40.0 Note ...
start_end = identifier.split("/",1)[1]
start_end = identifier.rsplit("/",1)[1]
def _identifier_split(self, identifier): """Returns (name,start,end) string tuple from an identier.""" if identifier.find("/")!=-1: start_end = identifier.split("/",1)[1] if start_end.count("-")==1: start, end = map(int, start_end.split("-")) name = identifier.split("/",1)[0] return (name, start, end) return (identifie...
f.write("POP\n")
start_pop = True
def remove_population(self, pos, fname): """Removes a population (by position).
f.write("POP\n")
def remove_population(self, pos, fname): """Removes a population (by position).
clade.node_id = elem.text and elem.text.strip() or None
clade.node_id = PX.Id(elem.text.strip(), elem.attrib.get('provider'))
def _parse_clade(self, parent): """Parse a Clade node and its children, recursively.""" clade = PX.Clade(**parent.attrib) if clade.branch_length is not None: clade.branch_length = float(clade.branch_length) # NB: Only evaluate nodes at the current level tag_stack = [] for event, elem in self.context: namespace, tag = s...
Roche SFF indices use base 255 not 256, meaning we see bytes in range the range 0 to 254 only. This appears to be so that byte 0xFF (character 255) can be used as a marker character to separate entries (required if the read name lengths vary). Note that since only four bytes are used for the read offset, this is limit...
Roche SFF indices use base 255 not 256, meaning we see bytes in range the range 0 to 254 only. This appears to be so that byte 0xFF (character 255) can be used as a marker character to separate entries (required if the read name lengths vary). Note that since only four bytes are used for the read offset, this is limit...
def _sff_read_roche_index(handle): """Reads any existing Roche style read index provided in the SFF file (PRIVATE). Will use the handle seek/tell functions. This works on ".srt1.00" and ".mft1.00" style Roche SFF index blocks. Roche SFF indices use base 255 not 256, meaning we see bytes in range the range 0 to 254 o...
"to store in the Roche SFF index structure. No index " "block will be recorded." % (name, offset))
"to store in the Roche SFF index structure. No " "index block will be recorded." % (name, offset))
def write_record(self, record): """Write a single additional record to the output file.
if type(seq)!=type("aa"): seq=seq.tostring()
def gcg(seq): """Returns the GCG checksum (int) for a sequence (string or Seq object). Given a nucleotide or amino-acid secuence (or any string), returns the GCG checksum (int). Checksum used by GCG program. seq type = str. Based on BioPerl GCG_checksum. Adapted by Sebastian Bassi with the help of John Lenton, Pablo Z...
if type(seq)!=type("aa"): seq=seq.tostring().upper() else: seq=seq.upper() m.update(seq)
def seguid(seq): """Returns the SEGUID (string) for a sequence (string or Seq object). Given a nucleotide or amino-acid secuence (or any string), returns the SEGUID string (A SEquence Globally Unique IDentifier). seq type = str. For more information about SEGUID, see: http://bioinformatics.anl.gov/seguid/ DOI: 10.1002...
seq = seq.tostring() except AttributeError: pass m.update(seq.upper().encode()) try: return base64.encodebytes(m.digest()).decode().replace("\n","").rstrip("=") except AttributeError: pass try:
def seguid(seq): """Returns the SEGUID (string) for a sequence (string or Seq object). Given a nucleotide or amino-acid secuence (or any string), returns the SEGUID string (A SEquence Globally Unique IDentifier). seq type = str. For more information about SEGUID, see: http://bioinformatics.anl.gov/seguid/ DOI: 10.1002...
self.assertEqual(self.ctrl.get_alleles(0,"Locus3"), [3, 20])
self.assertEqual(set(self.ctrl.get_alleles(0,"Locus3")), set([3, 20]))
def test_get_alleles(self): """Test get alleles. """ self.assertEqual(self.ctrl.get_alleles(0,"Locus3"), [3, 20])
dx = float(max_d - values[-1]) / (values[-1] - values[-2])
dx = len(values) > 1 and float(max_d - values[-1]) / \ (values[-1] - values[-2]) or max_d
def field_size(self, axis): size = {'x': 'width', 'y': 'height'}[axis] side = {'x': 'right', 'y': 'top'}[axis] values = getattr(self, 'get_%s_values' % axis)() max_d = self.data_max(axis) dx = float(max_d - values[-1]) / (values[-1] - values[-2]) graph_size = getattr(self, 'graph_%s' % size) side_font = getattr(self, '...
lisp.push_mark()
marker_ring = self.get('marker_ring') marker = lisp.point_marker() lisp.ring_insert(marker_ring, marker) def pop_mark(self): marker_ring = self.get('marker_ring') if lisp.ring_empty_p(marker_ring): self.message("There are no more marked buffers in \ the rope-marker-ring") else: oldbuf = lisp.current_buffer() marker = ...
def push_mark(self): lisp.push_mark()
conf.registerPlugin('Bantracker', True)
Bantracker = conf.registerPlugin('Bantracker', True)
def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default)
output("%r is an invalid value, it must be an integer or float greater or equal to 0", review)
output("%r is an invalid value, it must be an integer or float greater or equal to 0" % review)
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.request.review._default))
from supybot.question import yn, something, output
from supybot.questions import yn, something, output
def configure(advanced): from supybot.question import yn, something, output import sqlite import re import os from supybot.utils.str import format def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default) conf.registerPlugin(...
review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.request.review._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
output(format("The available request types are %L", type)) types = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.type._default))
output(format("The available request types are %L", Bantracker.request.type._default)) types = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.type._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
type.append(name)
type.add(name)
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
ignores = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.ignore._default))
ignores = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.ignore._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
forwards = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.forward._default))
forwards = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.forward._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
channels_i = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.channels._default))
channels_i = anything("Separate types by spaces or commas:", default=', '.join(Bantracker.request.forward._default))
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
for name in re.split(r',?\s+', channel_i):
for name in re.split(r',?\s+', channels_i):
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
type = Bantracker.type._default ignore = Bantracker.ignore._default forward = Bantracker.forward._default channels = Bantracker.channels._default review = Bantracker.review._default
type = Bantracker.request.type._default ignore = Bantracker.request.ignore._default forward = Bantracker.request.forward._default channels = Bantracker.request.forward.channels._default review = Bantracker.request.review._default
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
Bantracker.type.setValue(type) Bantracker.ignore.setValue(ignore) Bantracker.forward.setValue(forward) Bantracker.channels.setValue(channels) Bantracker.review.setValue(review)
Bantracker.request.type.setValue(type) Bantracker.request.ignore.setValue(ignore) Bantracker.request.forward.setValue(forward) Bantracker.request.forward.channels.setValue(channels) Bantracker.request.review.setValue(review)
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
con.begin()
def getReviewTime(): output("How many days should the bot wait before requesting a ban/quiet review?") review = something("Can be an integer or decimal value. Zero disables reviews.", default=str(Bantracker.review._default))
a0 = np.array([1, 2, 3, 4, 5, 6, nan, nan, 7, 8, 9]) a1 = np.arange(10) a2 = np.array([[9.0, 3.0, nan, nan, 9.0, nan], [1.0, 1.0, 1.0, nan, nan, nan], [2.0, 2.0, 0.1, nan, 1.0, nan], [3.0, 9.0, 2.0, nan, nan, nan], [4.0, 4.0, 3.0, 9.0, 2.0, nan], [5.0, 5.0, 4.0, 4.0, nan, nan]]) a3 = np.arange(12).reshape(3,4) a4 = np....
def unit_maker(func, func0): "Test that ny.nanxxx gives the same output as np.." a0 = np.array([1, 2, 3, 4, 5, 6, nan, nan, 7, 8, 9]) a1 = np.arange(10) a2 = np.array([[9.0, 3.0, nan, nan, 9.0, nan], [1.0, 1.0, 1.0, nan, nan, nan], [2.0, 2.0, 0.1, nan, 1.0, nan], [3.0, 9.0, 2.0, nan, nan, nan], [4.0, 4.0, 3.0, 9.0, 2.0...
for i, arr in enumerate(arrs):
msg += '\nInput array:\n%s\n' for i, arr in enumerate(arrays()):
def unit_maker(func, func0): "Test that ny.nanxxx gives the same output as np.." a0 = np.array([1, 2, 3, 4, 5, 6, nan, nan, 7, 8, 9]) a1 = np.arange(10) a2 = np.array([[9.0, 3.0, nan, nan, 9.0, nan], [1.0, 1.0, 1.0, nan, nan, nan], [2.0, 2.0, 0.1, nan, 1.0, nan], [3.0, 9.0, 2.0, nan, nan, nan], [4.0, 4.0, 3.0, 9.0, 2.0...
str(axis))
str(axis), arr)
def unit_maker(func, func0): "Test that ny.nanxxx gives the same output as np.." a0 = np.array([1, 2, 3, 4, 5, 6, nan, nan, 7, 8, 9]) a1 = np.arange(10) a2 = np.array([[9.0, 3.0, nan, nan, 9.0, nan], [1.0, 1.0, 1.0, nan, nan, nan], [2.0, 2.0, 0.1, nan, 1.0, nan], [3.0, 9.0, 2.0, nan, nan, nan], [4.0, 4.0, 3.0, 9.0, 2.0...
name = py3_b(name)
def _inotify_event(self, mask, name, target=None): """ Callback for inotify. """ name = py3_b(name) if mask & INotify.MODIFY and self._bursthandler.is_growing(name): # A file was modified. Do this check as fast as we can because the # events may come in bursts when a file is just copied. In this case # a timer is alrea...
'beacon.id': 'kaa.beacon.root-' + get_machine_uuid(),
'beacon.id': 'root-' + get_machine_uuid(),
def __init__(self, dbdir, scheduler=None): log.info('start beacon') try: self.ipc = kaa.rpc.Server('beacon') except IOError, e: kaa.beacon.thumbnail.thumbnail.disconnect() log.error('beacon: %s' % e) time.sleep(0.1) sys.exit(0)
'zope.container',
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
for user in self.users:
for user in list(self.users):
def watchConnection(self, connection, sockThread): sockThread.join() if(connection.closed): log(self, "%s's thread ended, connection was marked closed" % connection.user, 3) else: log(self, "%s's thread ended unexpectedly, cleaning up" % connection.user, 3) # send a quit message if(connection.type == self.IRC_Connectio...
for server in self.servers:
for server in list(self.servers):
def watchConnection(self, connection, sockThread): sockThread.join() if(connection.closed): log(self, "%s's thread ended, connection was marked closed" % connection.user, 3) else: log(self, "%s's thread ended unexpectedly, cleaning up" % connection.user, 3) # send a quit message if(connection.type == self.IRC_Connectio...
rmChans = list() for channel in user.channels: rmChans.append(channel) for channel in rmChans:
for channel in list(user.channels):
def removeUser(self, user): # perform all the cleanup that needs to be done to get a user out of the system log(self, "Removing %s from server" % user, 3) if(user in self.users): self.users.remove(user) else: log(self, "WARNING: %s wasn't in userlist" % user, 3) log(self, "Removing %s from channels %s" % (user, user.ch...
connection.send(msg.toString()) msg = self.IRC_Message("005 :are supported by this server") msg.prefix = self.hostname msg.params = [ connection.user.nick, "CHANTYPES=%s" % (self.chan_types), \ "PREFIX=(%s)%s" % (self.cuser_modes, self.cuser_sigils), \ "CHANMODES=%s" % (self.chan_modes), \ "NETWORK=%s" % (self.network...
def sendMOTD(self, connection): msg = self.IRC_Message("001 :Welcome, %s" % connection.user.nick) # WTF: Unknown reply type msg.params.append(connection.user.nick) msg.prefix = self.hostname # stick this in there somewhere: CHANTYPES=#&+ PREFIX=(Naohv)$&@%+ CHANMODES=be,k,l,cimnpqstAKMNORS STATUSMSG=$&@%+ NETWORK=Nadru...
if(connection.type == self.IRC_Connection.CLIENT): self.removeUser(connection.user) else: self.removeServer(connection.user)
self.removeServer(connection.user) else: connection.sock.close() self.connections.remove(connection)
def watchConnection(self, connection, sockThread): sockThread.join() if(not connection.closed): # send a quit message if(connection.type == self.IRC_Connection.CLIENT): msg = self.IRC_Message("QUIT :Lost connection") msg.prefix = connection.user.fullUser() self.localBroadcast(msg, connection.user, connection) # this me...
log(self, "WARNING: Channel %s wasn't %s's channel list" % (self, user), 3)
log(self, "WARNING: Channel %s wasn't in %s's channel list" % (self, user), 3)
def removeUser(self, user): log(self, "Attempting to remove %s from %s" % (user, self), 3) for cuser in self.users: if(cuser.user == user): self.users.remove(cuser) log(self, "Removed %s from %s's userlist" % (cuser, self), 3) if(self in user.channels): user.channels.remove(self) log(self, "Removed %s from %s's channel...
userMsg.prefix = user.nick
userMsg.prefix = user.fullUser()
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail ...
self.users.append(self.Channel_User(user))
cuser = self.Channel_User(user) self.users.append(cuser) log(self, "Added cuser %s to %s's userlist" % (cuser, self), 3)
def addUser(self, user): if(self.findCUser(user.nick) == None): self.users.append(self.Channel_User(user)) user.channels.append(self) return True return False
user.channels.remove(self)
log(self, "Removed %s from %s's userlist" % (cuser, self), 3) if(self in user.channels): user.channels.remove(self) log(self, "Removed %s from %s's channel list" % (self, user), 3) else: log(self, "WARNING: Channel %s wasn't %s's channel list" % (self, user), 3)
def removeUser(self, user): for cuser in self.users: if(cuser.user == user): self.users.remove(cuser) user.channels.remove(self)
if(not connection.closed):
if(connection.closed): log(self, "%s's thread ended, connection was marked closed" % connection.user, 3) else: log(self, "%s's thread ended unexpectedly, cleaning up" % connection.user, 3)
def watchConnection(self, connection, sockThread): sockThread.join() if(not connection.closed): # send a quit message if(connection.type == self.IRC_Connection.CLIENT): msg = self.IRC_Message("QUIT :Lost connection") msg.prefix = connection.user.fullUser() self.localBroadcast(msg, connection.user, connection) # this me...
if(connection.user.nick):
if(connection.user and connection.user.nick):
def checkClientNick(self, connection, nick): if(self.findUser(nick)): # check that nobody's taken the nick already errmsg = self.IRC_Message("433 :Nickname is already in use") errmsg.prefix = self.hostname if(connection.user.nick): errmsg.params = [connection.user.nick, nick] else: errmsg.params = ["*", nick] connectio...
userMsg.prefix = self.hostname
userMsg.prefix = user.nick
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail ...
logging = newPrefs.pop(pref)
logging = int(newPrefs[pref])
def readPrefs(self, filename="CCServer.conf"): global logging log(self, "reading %s" % filename) prefsFile = file(filename, 'r') prefsData = prefsFile.read() prefsFile.close() newPrefs = parseToDict(prefsData, ':', '\n') for pref in newPrefs: newPrefs[pref] = newPrefs[pref].strip() if(newPrefs[pref].isdigit()): newPref...
filename = part["headers"]["Content-Disposition"]["filename"] newFileURI = "images/%s" % filename[1:-1]
filename = part["headers"]["Content-Disposition"]["filename"][1:-1] if(filename == ""): log(self, "empty filename", 3) self.writeHTTP(sock, 400, {}, "empty filename") return newFileURI = "images/%s" % filename
def handleReq(self, sock, addr, method, resource, protocol, headers, body, getOptions): #lazy parsing of escape sequences :P resource = resource.replace("%20", ' ') if(self.redirects.has_key(resource)): self.writeHTTP(sock, 301, {"Location": self.redirects[resource]}, "301 Redirect") log(self, "redirected %s from %s to...
errmsg = self.IRC_Message("433 :Nickname is already in use") errmsg.prefix = self.hostname if(connection.user and connection.user.nick): errmsg.params = [connection.user.nick, nick] else: errmsg.params = ["*", nick] connection.send(errmsg.toString())
self.sendReply(connection, 433, [nick])
def checkClientNick(self, connection, nick): if(self.findUser(nick)): # check that nobody's taken the nick already errmsg = self.IRC_Message("433 :Nickname is already in use") errmsg.prefix = self.hostname if(connection.user and connection.user.nick): errmsg.params = [connection.user.nick, nick] else: errmsg.params = [...
self.users.append(self.Channel_User(user)) user.channels.append(self)
if(self.findCUser(user.nick) == None): self.users.append(self.Channel_User(user)) user.channels.append(self) return True return False
def addUser(self, user): self.users.append(self.Channel_User(user)) user.channels.append(self)
break
def removeUser(self, user): for cuser in self.users: if(cuser.user == user): self.users.remove(cuser) break user.channels.remove(self)
if(not user): return self.users.remove(user)
if(user in self.users): self.users.remove(user)
def removeUser(self, user): # perform all the cleanup that needs to be done to get a user out of the system if(not user): return self.users.remove(user) for channel in user.channels: channel.removeUser(user) if(user.connection.type == self.IRC_Connection.CLIENT): user.connection.sock.close() user.connection.closed = Tr...
msg.params = [sever.hostname]
msg.params = [server.hostname]
def watchConnection(self, connection, sockThread): sockThread.join() if(not connection.closed): # send a quit message if(connection.type == self.IRC_Connection.CLIENT): msg = self.IRC_Message("QUIT :Lost connection") msg.prefix = connection.user.fullUser() self.localBroadcast(msg, connection.user, connection) # this me...
userMsg.prefix = self.hostname userMsg.params = [user.nick]
userMsg.params = [user.nick, "1"]
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail ...
channelModes.append(channel.findUser(user).flags)
channelModes.append(channel.findCUser(user.nick).flags)
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail ...
for channel in len(channelModes):
for channel in range(len(channelModes)):
def sendServerData(self, connection): # respond with our own PASS, SERVER combo passMsg = self.IRC_Message("PASS") passMsg.prefix = self.hostname passMsg.params = [self.prefs["server_password"]] connection.send(passMsg.toString()) servMsg = self.IRC_Message("SERVER") servMsg.params = [self.hostname, "1"] servMsg.trail ...
args.reverse()
def __init__(self, message): self.prefix = str() self.command = str() self.params = list() self.trail = str() args = message.split(' ') args.reverse() if(message.startswith(':')): # the prefix, if present, indicates the origin of the message self.prefix = args.pop()[0:] # a command is required for all messages self.com...
self.prefix = args.pop()[0:]
self.prefix = args.pop(0)[1:]
def __init__(self, message): self.prefix = str() self.command = str() self.params = list() self.trail = str() args = message.split(' ') args.reverse() if(message.startswith(':')): # the prefix, if present, indicates the origin of the message self.prefix = args.pop()[0:] # a command is required for all messages self.com...
self.command = args.pop() while(len(args) > 0 and not args[-1].startswith(':')):
self.command = args.pop(0) while(len(args) > 0 and not args[0].startswith(':')):
def __init__(self, message): self.prefix = str() self.command = str() self.params = list() self.trail = str() args = message.split(' ') args.reverse() if(message.startswith(':')): # the prefix, if present, indicates the origin of the message self.prefix = args.pop()[0:] # a command is required for all messages self.com...
self.params.append(args.pop())
self.params.append(args.pop(0))
def __init__(self, message): self.prefix = str() self.command = str() self.params = list() self.trail = str() args = message.split(' ') args.reverse() if(message.startswith(':')): # the prefix, if present, indicates the origin of the message self.prefix = args.pop()[0:] # a command is required for all messages self.com...
self.flags = ""
self.flags = IRC_Server.IRC_Flags()
def __init__(self, connection, user="", hopcount = 0): self.username = str() self.hostname = str() args = user.split("!") self.nick = args[0] if(len(args) == 2): args = args[1].split("@") self.username = args[0] if(len(args) == 2): self.hostname = args[1] self.realname = str() self.servername = str() self.flags = "" se...
return "<%s +%s>" % (self.fullUser(), self.flags)
return "<%s %s>" % (self.fullUser(), self.flags)
def __repr__(self): return "<%s +%s>" % (self.fullUser(), self.flags)
self.flags = ""
self.flags = IRC_Server.IRC_Flags()
def __init__(self, user): self.user = user self.flags = ""
if(self.flags.find("v") != -1):
if('v' in self.flags):
def sigil(self): if(self.flags.find("v") != -1): return "+" if(self.flags.find("o") != -1): return "@" return ""
if(self.flags.find("o") != -1):
if('o' in self.flags):
def sigil(self): if(self.flags.find("v") != -1): return "+" if(self.flags.find("o") != -1): return "@" return ""
self.flags = ""
self.flags = IRC_Server.IRC_Flags()
def __init__(self, name): self.name = name self.topic = str() self.flags = "" self.users = list()
return "<%s +%s>" % (self.name, self.flags)
return "<%s %s>" % (self.name, self.flags)
def __repr__(self): return "<%s +%s>" % (self.name, self.flags)
def broadcast(self, msg, exclude=None):
def findCUser(self, nick): nick = nick.split("!")[0] for cuser in self.users: if(cuser.user.nick == nick): return cuser return None def broadcast(self, msg, exclude=None, localOnly=False):
def broadcast(self, msg, exclude=None): connections = list() for cuser in self.users: connection = cuser.user.connection if((not connection in connections) and connection != exclude): connections.append(connection) for connection in connections: connection.send(msg.toString())
if((not connection in connections) and connection != exclude):
if((not connection in connections) and connection != exclude and \ (localOnly == False or connection.type == IRC_Server.IRC_Connection.CLIENT)):
def broadcast(self, msg, exclude=None): connections = list() for cuser in self.users: connection = cuser.user.connection if((not connection in connections) and connection != exclude): connections.append(connection) for connection in connections: connection.send(msg.toString())
log(self, "Looking for %s in %s" % (nick, self.users), 3)
log(self, "Looking for %s in %s" % (nick, self.users), 4)
def findUser(self, nick): log(self, "Looking for %s in %s" % (nick, self.users), 3) nick = nick.split("!")[0] for user in self.users: if(user.nick == nick): log(self, "Found user %s" % user, 3) return user log(self, "Didn't find user", 3) return None
log(self, "Found user %s" % user, 3)
log(self, "Found user %s" % user, 4)
def findUser(self, nick): log(self, "Looking for %s in %s" % (nick, self.users), 3) nick = nick.split("!")[0] for user in self.users: if(user.nick == nick): log(self, "Found user %s" % user, 3) return user log(self, "Didn't find user", 3) return None
log(self, "Didn't find user", 3)
log(self, "Didn't find user", 4)
def findUser(self, nick): log(self, "Looking for %s in %s" % (nick, self.users), 3) nick = nick.split("!")[0] for user in self.users: if(user.nick == nick): log(self, "Found user %s" % user, 3) return user log(self, "Didn't find user", 3) return None
log(self, "Looking for %s in %s" % (name, self.channels), 3)
log(self, "Looking for %s in %s" % (name, self.channels), 4)
def findChannel(self, name): log(self, "Looking for %s in %s" % (name, self.channels), 3) for channel in self.channels: if(channel.name == name): log(self, "Found channel %s" % channel, 3) return channel log(self, "Didn't find channel", 3) return None
log(self, "Found channel %s" % channel, 3)
log(self, "Found channel %s" % channel, 4)
def findChannel(self, name): log(self, "Looking for %s in %s" % (name, self.channels), 3) for channel in self.channels: if(channel.name == name): log(self, "Found channel %s" % channel, 3) return channel log(self, "Didn't find channel", 3) return None
log(self, "Didn't find channel", 3)
log(self, "Didn't find channel", 4)
def findChannel(self, name): log(self, "Looking for %s in %s" % (name, self.channels), 3) for channel in self.channels: if(channel.name == name): log(self, "Found channel %s" % channel, 3) return channel log(self, "Didn't find channel", 3) return None
self.connections.remove(user.connection)
if(not user): return
def removeUser(self, user): # perform all the cleanup that needs to be done to get a user out of the system self.connections.remove(user.connection) self.users.remove(user) for channel in user.channels: channel.removeUser(user) if(user.connection.type == self.IRC_Connection.CLIENT): user.connection.sock.close() self.co...
def localBroadcast(self, msg, relUser):
def localBroadcast(self, msg, relUser, excludeConn=None):
def localBroadcast(self, msg, relUser): localUsers = list() for channel in relUser.channels: for cuser in channel.users: if((not cuser.user in localUsers) and cuser.user.connection.type == self.IRC_Connection.CLIENT): localUsers.append(cuser.user) for user in localUsers: user.connection.send(msg.toString())
if((not cuser.user in localUsers) and cuser.user.connection.type == self.IRC_Connection.CLIENT): localUsers.append(cuser.user)
user = cuser.user connection = cuser.user.connection if((not user in localUsers) and connection.type == self.IRC_Connection.CLIENT and connection != excludeConn): localUsers.append(user)
def localBroadcast(self, msg, relUser): localUsers = list() for channel in relUser.channels: for cuser in channel.users: if((not cuser.user in localUsers) and cuser.user.connection.type == self.IRC_Connection.CLIENT): localUsers.append(cuser.user) for user in localUsers: user.connection.send(msg.toString())