output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Returns the object that the view is displaying. | Explain what the following Python 3 code does
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
try:
return queryset.get(user__pk=self.request.user.pk)
except ObjectDoesNotExist:
raise Http404 | You are a Python code analyst, evaluating scripts for potential improvements. |
Check if the user can manage groups. | Can you tell what is the following Python 3 function doing
def can_manage_groups(cls, user):
if user.is_authenticated:
return cls.has_management_permission(user) or user.leads_groups.all()
return False | You are a Python code analyst, evaluating scripts for potential improvements. |
Check if the given user can manage the given group | Given the following Python 3 function, write the documentation
def can_manage_group(cls, user, group):
if user.is_authenticated:
return cls.has_management_permission(user) or user.leads_groups.filter(group=group).exists()
return False | You are a Python code generator, capable of creating scripts from specifications. |
Create the AuthGroup model when a group is created | Can you tell what is the following Python 3 function doing
def create_auth_group(sender, instance, created, **kwargs):
if created:
AuthGroup.objects.create(group=instance) | As a Python code composer, you craft elegant and concise scripts. |
Construct a TS3 formatted command string | Can you generate a brief explanation for the following Python 3 code
def construct_command(self, command, keys=None, opts=None):
cstr = [command]
# Add the keys and values, escape as needed
if keys:
for key in keys:
if isinstance(keys[key], list):
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Parses a TS3 command string into a dictionary of command keys and opts. | Can you generate the documentation for the following Python 3 function
def parse_command(self, commandstr):
if len(commandstr.split('|')) > 1:
vals = []
for cmd in commandstr.split('|'):
vals.append(self.parse_command(cmd))
return vals
cmdlist = comm... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _escape_str(value):
"""
Escape a value into a TS3 compatible string
@param value: Value
@type value: string/int
"""
if isinstance(value, int):
return "%d" % value
value = value.replace("\\", r'\\')
for i, j in ts3_escape.items():
... | Write a Python 3 function for
escaping a value into a TS3 compatible string | You are a Python code architect, reviewing and designing scalable and efficient code |
Unescape a TS3 compatible string into a normal string | Make a summary of the following Python 3 code
def _unescape_str(value):
if isinstance(value, int):
return "%d" % value
value = value.replace(r"\\", "\\")
for i, j in ts3_escape.items():
value = value.replace(j, i)
return value | As a Python code analyst, you investigate and solve complex coding mysteries |
def login(self, username, password):
"""
Login to the TS3 Server
@param username: Username
@type username: str
@param password: Password
@type password: str
"""
d = self.send_command('login', keys={'client_login_name': username, 'client_login_password': pa... | Write a Python 3 script to
login to the TS3 Server | As a python code expert, you are capable of creating scripts from specifications. |
Use a particular Virtual Server instance | Given the following Python 3 function, write the documentation
def use(self, id):
if self._connected and id > 0:
self.send_command('use', keys={'sid': id}) | You are a Python code generator, capable of creating scripts from specifications. |
Example for rendering the services control panel row | Can you generate the documentation for the following Python 3 function
def render_services_ctrl(self, request):
urls = self.Urls()
urls.auth_activate = 'auth_example_activate'
urls.auth_deactivate = 'auth_example_deactivate'
urls.auth_reset_password = 'auth_example_reset_password'
... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the EveAllianceInfo object for this alliance. | Can you generate the documentation for the following Python 3 function
def alliance(self) -> Union[EveAllianceInfo, None]:
if self.alliance_id is None:
return None
return EveAllianceInfo.objects.get(alliance_id=self.alliance_id) | As a Python code composer, you craft elegant and concise scripts. |
Checks if enable was toggled on group config and deletes groups if necessary. | Make a summary of the following Python 3 code
def pre_save_config(sender, instance, *args, **kwargs):
logger.debug("Received pre_save from {}".format(instance))
if not instance.pk:
# new model being created
return
try:
old_instance = AutogroupsConfig.objects.get(pk=instance.pk)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Trigger check when main character or state changes. | Explain what the following Python 3 code does
def check_groups_on_profile_update(sender, instance, created, *args, **kwargs):
AutogroupsConfig.objects.update_groups_for_user(instance.user) | You are a Python code analyst, evaluating scripts for potential improvements. |
def autogroups_states_changed(sender, instance, action, reverse, model, pk_set, *args, **kwargs):
"""
Trigger group membership update when a state is added or removed from
an autogroup config.
"""
if action.startswith('post_'):
for pk in pk_set:
try:
state = State... | Write a Python 3 function for
triggering group membership update when a state is added or removed from a group. | You are a Python code architect, reviewing and designing scalable and efficient code |
def make_service_hooks_update_groups_action(service):
"""
Make a admin action for the given service
:param service: services.hooks.ServicesHook
:return: fn to update services groups for the selected users
"""
def update_service_groups(modeladmin, request, queryset):
for user in queryset:... | Create a Python 3 function for
returning a function that can be used to update the groups for the selected users | As a python code expert, you are capable of creating scripts from specifications. |
def make_service_hooks_sync_nickname_action(service):
"""
Make a sync_nickname admin action for the given service
:param service: services.hooks.ServicesHook
:return: fn to sync nickname for the selected users
"""
def sync_nickname(modeladmin, request, queryset):
for user in queryset: #... | Can you create a Python 3 function that
returns a function that will be used to sync the nicknames for the selected users | You are a Python code analyst, evaluating scripts for potential improvements. |
def renavactive(request, pattern):
"""
{% renavactive request "^/a_regex" %}
"""
if re.search(pattern, request.path):
return getattr(settings, "NAVHELPER_ACTIVE_CLASS", "active")
return getattr(settings, "NAVHELPER_NOT_ACTIVE_CLASS", "") | Implement a Python 3 function for
returning the active or not active class for the current page. | You are a Python code architect, reviewing and designing scalable and efficient code |
def navactive(request, urls):
"""
{% navactive request "view_name another_view_name" %}
"""
url_list = set(urls.split())
resolved = resolve(request.path)
resolved_urls = set()
if resolved.url_name:
resolved_urls.add(resolved.url_name)
if resolved.namespaces:
resolved_url... | Create a Python 3 function to
return the active navclass for the given urls. | As a python code expert, you are capable of creating scripts from specifications. |
Update all the Group memberships for the users who have a state. | Explain what the following Python 3 code does
def update_groups_for_state(self, state: State):
users = get_users_for_state(state)
for config in self.filter(states=state):
logger.debug("in state loop")
for user in users:
logger.debug("in user loop for {}".format(us... | You are a Python code architect, reviewing and designing scalable and efficient code |
Update the group memberships for the given users state | Explain what the following Python 3 code does
def update_groups_for_user(self, user: User, state: State = None):
if state is None:
state = user.profile.state
for config in self.filter(states=state):
# grant user new groups for their state
config.update_group_membershi... | As a Python code analyst, you investigate and solve complex coding mysteries |
Replace spaces in the given name based on the config
property. | Can you generate a brief explanation for the following Python 3 code
def _replace_spaces(self, name: str) -> str:
if self.replace_spaces:
return name.strip().replace(' ', str(self.replace_spaces_with))
return name | You are a Python code generator, capable of creating scripts from specifications. |
Decorator for handling API 429 Too Many Requests messages from the Discord API. | Can you tell what is the following Python 3 function doing
def api_backoff(func):
class PerformBackoff(Exception):
def __init__(self, retry_after, retry_datetime, global_ratelimit):
super(Exception, self).__init__()
self.retry_after = int(retry_after)
self.retry_datetime... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a random string of length string_length. | Can you tell what is the following Python 3 function doing
def random_string(string_length=10):
random = str(uuid.uuid4()) # Convert UUID format to a Python string.
random = random.upper() # Make all characters uppercase.
random = random.replace("-", "") # Remove the UUID '-'.
return random[0:string_... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the names of all imported genomes | How would you explain what the following Python 3 function does
def getGenomeList() :
import rabaDB.filters as rfilt
f = rfilt.RabaQuery(Genome_Raba)
names = []
for g in f.iterRun() :
names.append(g.name)
return names | You are a Python code generator, capable of creating scripts from specifications. |
def iterCodons(self) :
"""iterates through the codons"""
for i in range(len(self.cDNA)/3) :
yield self.getCodon(i) | Write a Python 3 function for
iterating through the codons | You are a Python code generator, capable of creating scripts from specifications. |
removes duplicated lines from a inFileName CSV file | How would you explain what the following Python 3 function does
def removeDuplicates(inFileName, outFileName) :
f = open(inFileName)
legend = f.readline()
data = ''
h = {}
h[legend] = 0
lines = f.readlines()
for l in lines :
if not h.has_key(l) :
h[l] = 0
data += l
f.flush()
f.close()
f = open... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Concatenates all csv in folder and wites the results in ouputFileName. | How would you explain what the following Python 3 function does
def catCSVs(folder, ouputFileName, removeDups = False) :
strCmd = r"""cat %s/*.csv > %s""" %(folder, ouputFileName)
os.system(strCmd)
if removeDups :
removeDuplicates(ouputFileName, ouputFileName) | As a Python code analyst, you investigate and solve complex coding mysteries |
This function joins all CSVs according to the values in the column and writes the results in a new file ouputFileName. | Given the following Python 3 function, write the documentation
def joinCSVs(csvFilePaths, column, ouputFileName, separator = ',') :
res = ''
legend = []
csvs = []
for f in csvFilePaths :
c = CSVFile()
c.parse(f)
csvs.append(c)
legend.append(separator.join(c.legend.keys()))
legend = separator.join(legen... | As a python code expert, you are capable of creating scripts from specifications. |
add a filed to the legend | Make a summary of the following Python 3 code
def addField(self, field) :
if field.lower() in self.legend :
raise ValueError("%s is already in the legend" % field.lower())
self.legend[field.lower()] = len(self.legend)
if len(self.strLegend) > 0 :
self.strLegend += self.separator + field
else :
self.st... | You are a Python code generator, capable of creating scripts from specifications. |
Loads a CSV file and parses it into a list of dictionaries. | Can you generate the documentation for the following Python 3 function
def parse(self, filePath, skipLines=0, separator = ',', stringSeparator = '"', lineSeparator = '\n') :
self.filename = filePath
f = open(filePath)
if lineSeparator == '\n' :
lines = f.readlines()
else :
lines = f.read().split(lineSe... | You are a Python code generator, capable of creating scripts from specifications. |
def streamToFile(self, filename, keepInMemory = False, writeRate = 1) :
"""Starts a stream to a file. Every line must be committed (l.commit()) to be appended in to the file.
If keepInMemory is set to True, the parser will keep a version of the whole CSV in memory, writeRate is the number
of lines that must be c... | Implement a function in Python 3 to
start a stream to a file. | You are a Python code generator, capable of creating scripts from specifications. |
def commitLine(self, line) :
"""Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError"""
if self.streamBuffer is None :
raise ValueError("Commit lines is only for when you are streaming to a file")
self.streamBuffer.append(l... | Can you write a function in Python 3 where it
commits a line to a file and saves the current buffer if needed. | You are a Python code architect, reviewing and designing scalable and efficient code |
Appends the remaining lines and closes the stream. | Given the following Python 3 function, write the documentation
def closeStreamToFile(self) :
if self.streamBuffer is None :
raise ValueError("Commit lines is only for when you are streaming to a file")
for i in xrange(len(self.streamBuffer)) :
self.streamBuffer[i] = str(self.streamBuffer[i])
self.streamFil... | As a python code expert, you are capable of creating scripts from specifications. |
def newLine(self) :
"""Appends an empty line at the end of the CSV and returns it"""
l = CSVEntry(self)
if self.keepInMemory :
self.lines.append(l)
return l | How would you code a function in Python 3 to
append an empty line at the end of the CSV and returns it | As a Python code translator, you convert algorithms and pseudocode into Python. |
def insertLine(self, i) :
"""Inserts an empty line at position i and returns it"""
self.data.insert(i, CSVEntry(self))
return self.lines[i] | Write a Python 3 script for
inserting an empty line at position i and returns it | You are a Python code architect, reviewing and designing scalable and efficient code |
save the CSV to a file | Can you generate the documentation for the following Python 3 function
def save(self, filePath) :
self.filename = filePath
f = open(filePath, 'w')
f.write(self.toStr())
f.flush()
f.close() | You are a Python code analyst, evaluating scripts for potential improvements. |
returns a string version of the CSV | Can you tell what is the following Python 3 function doing
def toStr(self) :
s = [self.strLegend]
for l in self.lines :
s.append(l.toStr())
return self.lineSeparator.join(s) | You are a Python code generator, capable of creating scripts from specifications. |
def count(self, objectType, *args, **coolArgs) :
"""Returns the number of elements satisfying the query"""
return self._makeLoadQuery(objectType, *args, **coolArgs).count() | Can you write a function in Python 3 where it
returns the number of elements satisfying the query | You are a Python code analyst, evaluating scripts for potential improvements. |
Same as get but retuns the elements one by one. | Make a summary of the following Python 3 code
def iterGet(self, objectType, *args, **coolArgs) :
for e in self._makeLoadQuery(objectType, *args, **coolArgs).iterRun() :
if issubclass(objectType, pyGenoRabaObjectWrapper) :
yield objectType(wrapped_object_and_bag = (e, self.bagKey))
else :
yield e | You are a Python code analyst, evaluating scripts for potential improvements. |
deletes a set of polymorphisms | How would you explain what the following Python 3 function does
def deleteSNPs(setName) :
con = conf.db
try :
SMaster = SNPMaster(setName = setName)
con.beginTransaction()
SNPType = SMaster.SNPType
con.delete(SNPType, 'setName = ?', (setName,))
SMaster.delete()
con.endTransaction()
except KeyError :
ra... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function will also create an index on start -> chromosomeNumber -> setName. Warning : pyGeno wil interpret all positions as 0 based | Explain what the following Python 3 code does
def _importSNPs_AgnosticSNP(setName, species, genomeSource, snpsFile) :
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno wil interpret all positions as 0 based"
printf('importing SNP set %s for species %s...' % (setName, speci... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function will also create an index on start -> chromosomeNumber -> setName. Warning : pyGeno positions are 0 based | Here you have a function in Python 3, explain what it does
def _importSNPs_CasavaSNP(setName, species, genomeSource, snpsFile) :
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based"
printf('importing SNP set %s for species %s...' % (setName, species))
... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function will also create an index on start -> chromosomeNumber -> setName. Warning : pyGeno positions are 0 based | Can you tell what is the following Python 3 function doing
def _importSNPs_dbSNPSNP(setName, species, genomeSource, snpsFile) :
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based"
snpData = VCFFile(snpsFile, gziped = True, stream = True)
dbSNPSNP.drop... | You are a Python code generator, capable of creating scripts from specifications. |
def getSNPSetsList() :
"""Return the names of all imported snp sets"""
import rabaDB.filters as rfilt
f = rfilt.RabaQuery(SNPMaster)
names = []
for g in f.iterRun() :
names.append(g.setName)
return names | Write a Python 3 script to
return the names of all imported snp sets | You are a Python code analyst, evaluating scripts for potential improvements. |
def printf(*s) :
'print + sys.stdout.flush()'
for e in s[:-1] :
print e,
print s[-1]
sys.stdout.flush() | Write a Python 3 script to
print a list of strings | You are a Python code architect, reviewing and designing scalable and efficient code |
def parseFile(self, fil) :
"""Opens a file and parses it"""
f = open(fil)
self.parseStr(f.read())
f.close() | Write a Python 3 function that can
open a file and parses it | You are a Python code architect, reviewing and designing scalable and efficient code |
def add(self, header, data) :
"""appends a new entry to the file"""
if header[0] != '>' :
self.data.append(('>'+header, data))
else :
self.data.append((header, data)) | Write a Python 3 function that can
append a new entry to the file | As a Python code composer, you craft elegant and concise scripts. |
def findAll(haystack, needle) :
"""returns a list of all occurances of needle in haystack"""
h = haystack
res = []
f = haystack.find(needle)
offset = 0
while (f >= 0) :
#print h, needle, f, offset
res.append(f+offset)
offset += f+len(needle)
h = h[f+len(needle):]
f = h.find(needle)
return res | Can you implement a function in Python 3 that
returns a list of all occurances of needle in haystack | As a Python code translator, you convert algorithms and pseudocode into Python. |
def complementTab(seq=[]):
"""returns a list of complementary sequence without inversing it"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R', 'M': 'K', 'K': 'M',
'W': 'W', 'S': 'S', 'B': 'V', 'D': 'H', 'H': 'D', 'V': 'B', 'N': 'N', 'a': 't',
'c': 'g... | How would you implement a function in Python 3 that
returns a list of complementary sequence without inversing it | As a Python code composer, you craft elegant and concise scripts. |
returns 6 translation of sequence. One for each reading frame | Make a summary of the following Python 3 code
def translateDNA_6Frames(sequence) :
trans = (
translateDNA(sequence, 'f1'),
translateDNA(sequence, 'f2'),
translateDNA(sequence, 'f3'),
translateDNA(sequence, 'r1'),
translateDNA(sequence, 'r2'),
translateDNA(sequence, 'r3'),
)
return trans | As a Python code analyst, you investigate and solve complex coding mysteries |
def translateDNA(sequence, frame = 'f1', translTable_id='default') :
"""Translates DNA code, frame : fwd1, fwd2, fwd3, rev1, rev2, rev3"""
protein = ""
if frame == 'f1' :
dna = sequence
elif frame == 'f2':
dna = sequence[1:]
elif frame == 'f3' :
dna = sequence[2:]
elif frame == 'r1' :
dna = reverseCompl... | Write a Python 3 script for
translating a DNA code to a protein code. | You are a Python code generator, capable of creating scripts from specifications. |
def getSequenceCombinaisons(polymorphipolymorphicDnaSeqSeq, pos = 0) :
"""Takes a dna sequence with polymorphismes and returns all the possible sequences that it can yield"""
if type(polymorphipolymorphicDnaSeqSeq) is not types.ListType :
seq = list(polymorphipolymorphicDnaSeqSeq)
else :
seq = polymorphipolymor... | Write a Python 3 function that can
take a dna sequence with polymorphismes and returns all the possible sequences that it can yield | As a Python code composer, you craft elegant and concise scripts. |
def encodePolymorphicNucleotide(polySeq) :
"""returns a single character encoding all nucletides of polySeq
in a single character. PolySeq must have one of the following forms:
['A', 'T', 'G'], 'ATG', 'A/T/G'"""
if type(polySeq) is types.StringType :
if polySeq.find("/") < 0 :
sseq = list(polySeq)
else :... | Can you implement a function in Python 3 that
returns a single character encoding all nucletides of a given polySeq in a single character. | You are a Python code architect, reviewing and designing scalable and efficient code |
decode a polymorphic nucleotide into a sequence of nucleotides | Here you have a function in Python 3, explain what it does
def decodePolymorphicNucleotide(nuc) :
if nuc in polymorphicNucleotides :
return polymorphicNucleotides[nuc]
if nuc in nucleotides :
return nuc
raise ValueError('nuc: %s, is not a valid nucleotide' % nuc) | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the entire codon of the nucleotide at pos x1 in sequence and
and the position of that nocleotide in the codon in a tuple | Make a summary of the following Python 3 code
def getNucleotideCodon(sequence, x1) :
if x1 < 0 or x1 >= len(sequence) :
return None
p = x1%3
if p == 0 :
return (sequence[x1: x1+3], 0)
elif p ==1 :
return (sequence[x1-1: x1+2], 1)
elif p == 2 :
return (sequence[x1-2: x1+1], 2) | As a Python code composer, you craft elegant and concise scripts. |
Returns a string that shows the differences between seq1 and seq2. | Here you have a function in Python 3, explain what it does
def showDifferences(seq1, seq2) :
ret = []
for i in range(max(len(seq1), len(seq2))) :
if i >= len(seq1) :
c1 = '#'
else :
c1 = seq1[i]
if i >= len(seq2) :
c2 = '#'
else :
c2 = seq2[i]
if c1 != c2 :
ret.append('%s|%s' % (c1, c2))
... | You are a Python code analyst, evaluating scripts for potential improvements. |
returns a sequence where the subsequence in [ x1 x2 is placed
in bewteen start and stop | How would you explain what the following Python 3 function does
def highlightSubsequence(sequence, x1, x2, start=' [', stop = '] ') :
seq = list(sequence)
print x1, x2-1, len(seq)
seq[x1] = start + seq[x1]
seq[x2-1] = seq[x2-1] + stop
return ''.join(seq) | As a Python code composer, you craft elegant and concise scripts. |
Removes a genome from the database | Given the following Python 3 function, write the documentation
def deleteGenome(species, name) :
printf('deleting genome (%s, %s)...' % (species, name))
conf.db.beginTransaction()
objs = []
allGood = True
try :
genome = Genome_Raba(name = name, species = species.lower())
objs.appen... | As a Python code analyst, you investigate and solve complex coding mysteries |
def importGenome(packageFile, batchSize = 50, verbose = 0) :
"""Import a pyGeno genome package. A genome packages is folder or a tar.gz ball that contains at it's root:
* gziped fasta files for all chromosomes, or URLs from where them must be downloaded
* gziped GTF gene_set file from Ensembl, or an U... | Can you implement a function in Python 3 that
imports a pyGeno genome package. | As a python code expert, you are capable of creating scripts from specifications. |
def _importGenomeObjects(gtfFilePath, chroSet, genome, batchSize, verbose = 0) :
"""verbose must be an int [0, 4] for various levels of verbosity"""
class Store(object) :
def __init__(self, conf) :
self.conf = conf
self.chromosomes = {}
self.gen... | How would you implement a function in Python 3 that
imports Chromosome objects from a GTF file. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _importSequence(chromosome, fastaFile, targetDir) :
"Serializes fastas into .dat files"
f = gzip.open(fastaFile)
header = f.readline()
strRes = f.read().upper().replace('\n', '').replace('\r', '')
f.close()
fn = '%s/chromosome%s.dat' % (targetDir, chromosome.number)
f = open(fn, 'w')
... | Can you implement a function in Python 3 that
serializes fastas into. dat files | As a python code expert, you are capable of creating scripts from specifications. |
def createDefaultConfigFile() :
"""Creates a default configuration file"""
s = "[pyGeno_config]\nsettings_dir=%s\nremote_location=%s" % (pyGeno_SETTINGS_DIR, pyGeno_REMOTE_LOCATION)
f = open('%s/config.ini' % pyGeno_SETTINGS_DIR, 'w')
f.write(s)
f.close() | Can you create a Python 3 function that
creates a default configuration file | You are a Python code generator, capable of creating scripts from specifications. |
Returns the path where the settings are stored | Explain what the following Python 3 code does
def getSettingsPath() :
parser = SafeConfigParser()
try :
parser.read(os.path.normpath(pyGeno_SETTINGS_DIR+'/config.ini'))
return parser.get('pyGeno_config', 'settings_dir')
except :
createDefaultConfigFile()
return getSettingsPath() | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function is automatically called at launch | Can you generate a brief explanation for the following Python 3 code
def pyGeno_init() :
global db, dbConf
global pyGeno_SETTINGS_PATH
global pyGeno_RABA_DBFILE
global pyGeno_DATA_PATH
if not checkPythonVersion() :
raise PythonVersionError("==> FATAL: pyGeno only works with python 2.7 and above, please upg... | As a Python code composer, you craft elegant and concise scripts. |
Returns a copy of the exon and sets the value of self. transcript into str. | Make a summary of the following Python 3 code
def pluck(self) :
e = copy.copy(self)
e.transcript = str(self.transcript)
return e | You are a Python code analyst, evaluating scripts for potential improvements. |
def previousExon(self) :
"""Returns the previous exon of the transcript, or None if there is none"""
if self.number == 0 :
return None
try :
return self.transcript.exons[self.number-1]
except IndexError :
return None | Can you create a Python 3 function that
returns the previous exon of the transcript or None if there is no exon. | You are a Python code analyst, evaluating scripts for potential improvements. |
returns the ith entry | Explain what the following Python 3 code does
def get(self, li) :
i = li*4
self.__splitEntry(i)
return self.data[i] | As a python code expert, you are capable of creating scripts from specifications. |
Returns a new entry in the CSV | Can you tell what is the following Python 3 function doing
def newEntry(self, ident = "", seq = "", plus = "", qual = "") :
e = FastqEntry()
self.data.append(e)
return e | As a python code expert, you are capable of creating scripts from specifications. |
def listRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) :
"""Lists all the datawraps availabe from a remote a remote location."""
loc = location + "/datawraps.json"
response = urllib2.urlopen(loc)
js = json.loads(response.read())
return js | Can you implement a function in Python 3 that
lists all the datawraps availabe from a remote location. | You are a Python code analyst, evaluating scripts for potential improvements. |
Print all available datawraps from a remote location. | Explain what the following Python 3 code does
def printRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) :
l = listRemoteDatawraps(location)
printf("Available datawraps for bootstraping\n")
print json.dumps(l["Ordered"], sort_keys=True, indent=4, separators=(',', ': ')) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def importRemoteGenome(name, batchSize = 100) :
"""Import a genome available from http://pygeno.iric.ca (might work)."""
try :
dw = listRemoteDatawraps()["Flat"]["Reference genomes"][name]
except AttributeError :
raise AttributeError("There's no remote genome datawrap by the name of: '%s'" % name)
finalFile = ... | Create a Python 3 function to
import a genome from the remote genomes. | You are a Python code architect, reviewing and designing scalable and efficient code |
def importRemoteSNPs(name) :
"""Import a SNP set available from http://pygeno.iric.ca (might work)."""
try :
dw = listRemoteDatawraps()["Flat"]["SNPs"]
except AttributeError :
raise AttributeError("There's no remote genome datawrap by the name of: '%s'" % name)
finalFile = _DW(name, dw["url"])
PS.importSNPs(f... | Implement a function in Python 3 to
import a remote SNP set from the IRAF CA. | As a Python code analyst, you investigate and solve complex coding mysteries |
Lists all the datawraps pyGeno comes with | Can you tell what is the following Python 3 function doing
def listDatawraps() :
l = {"Genomes" : [], "SNPs" : []}
for f in os.listdir(os.path.join(this_dir, "bootstrap_data/genomes")) :
if f.find(".tar.gz") > -1 :
l["Genomes"].append(f)
for f in os.listdir(os.path.join(this_dir, "bootstrap_data/SNPs")) :
i... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def printDatawraps() :
"""print all available datawraps for bootstraping"""
l = listDatawraps()
printf("Available datawraps for boostraping\n")
for k, v in l.iteritems() :
printf(k)
printf("~"*len(k) + "|")
for vv in v :
printf(" "*len(k) + "|" + "~~~:> " + vv)
printf('\n') | Can you implement a function in Python 3 that
prints all available datawraps for bootstrapping | As a python code expert, you are capable of creating scripts from specifications. |
def importGenome(name, batchSize = 100) :
"""Import a genome shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties."""
path = os.path.join(this_dir, "bootstrap_data", "genomes/" + name)
PG.importGenome(path, batchSize) | How would you implement a function in Python 3 that
imports a genome shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties. | You are a Python code analyst, evaluating scripts for potential improvements. |
def importSNPs(name) :
"""Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties."""
path = os.path.join(this_dir, "bootstrap_data", "SNPs/" + name)
PS.importSNPs(path) | Can you implement a function in Python 3 that
imports a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties. | As a Python code analyst, you investigate and solve complex coding mysteries |
logs stats about the progression without printing anything on screen | Can you generate the documentation for the following Python 3 function
def log(self) :
self.logs['epochDuration'].append(self.lastEpochDuration)
self.logs['avg'].append(self.avg)
self.logs['runtime'].append(self.runtime)
self.logs['remtime'].append(self.remtime) | As a Python code composer, you craft elegant and concise scripts. |
dumps logs into a nice pickle | Given the following Python 3 function, write the documentation
def saveLogs(self, filename) :
f = open(filename, 'wb')
cPickle.dump(self.logs, f)
f.close() | You are a Python code architect, reviewing and designing scalable and efficient code |
update the internal state of the object | Explain what the following Python 3 code does
def update(self, label = '', forceRefresh = False, log = False) :
self.currEpoch += 1
tim = time.time()
if (tim - self.lastPrintTime > self.minRefeshTime) or forceRefresh :
self._update()
wheelState = self.wheel[self.currEpoch%len(self.wheel)]
if labe... | As a Python code composer, you craft elegant and concise scripts. |
This a private function that inserts a child tree into a parent tree. | Explain what the following Python 3 code does
def aux_insertTree(childTree, parentTree):
if childTree.x1 != None and childTree.x2 != None :
parentTree.insert(childTree.x1, childTree.x2, childTree.name, childTree.referedObject)
for c in childTree.children:
aux_insertTree(c, parentTree) | As a Python code analyst, you investigate and solve complex coding mysteries |
This function is a private recursive function that translates tree to a given x1 and tree s children to a given x2 | Here you have a function in Python 3, explain what it does
def aux_moveTree(offset, tree):
if tree.x1 != None and tree.x2 != None :
tree.x1, tree.x2 = tree.x1+offset, tree.x2+offset
for c in tree.children:
aux_moveTree(offset, c) | As a Python code analyst, you investigate and solve complex coding mysteries |
Insert the segment in it s right place and returns it. | Here you have a function in Python 3, explain what it does
def insert(self, x1, x2, name = '', referedObject = []) :
if x1 > x2 :
xx1, xx2 = x2, x1
else :
xx1, xx2 = x1, x2
rt = None
insertId = None
childrenToRemove = []
for i in range(len(self.children)) :
if self.children[i].x1 == xx1 and xx2... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of all segments intersected by x1 and x2. | Here you have a function in Python 3, explain what it does
def intersect(self, x1, x2 = None) :
def condition(x1, x2, tree) :
#print self.id, tree.x1, tree.x2, x1, x2
if (tree.x1 != None and tree.x2 != None) and (tree.x1 <= x1 and x1 < tree.x2 or tree.x1 <= x2 and x2 < tree.x2) :
return True
return Fa... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Radiates down : walks self. children downward until condition is no longer verifed until there s no childrens left | Can you tell what is the following Python 3 function doing
def __radiateDown(self, x1, x2, childId, condition) :
"Radiates down: walks self.children downward until condition is no longer verifed or there's no childrens left "
ret = []
i = childId
while 0 <= i :
if condition(x1, x2, self.children[i]) :
re... | As a python code expert, you are capable of creating scripts from specifications. |
Radiates uo : walks self. children upward until condition is no longer verifed until there s no childrens left | Make a summary of the following Python 3 code
def __radiateUp(self, x1, x2, childId, condition) :
"Radiates uo: walks self.children upward until condition is no longer verifed or there's no childrens left "
ret = []
i = childId
while i < len(self.children):
if condition(x1, x2, self.children[i]) :
ret.ap... | As a python code expert, you are capable of creating scripts from specifications. |
def removeGaps(self) :
"""Remove all gaps between regions"""
for i in range(1, len(self.children)) :
if self.children[i].x1 > self.children[i-1].x2:
aux_moveTree(self.children[i-1].x2-self.children[i].x1, self.children[i]) | Write a Python 3 function that can
remove all gaps between regions | As a python code expert, you are capable of creating scripts from specifications. |
def getIndexedLength(self) :
"""Returns the total length of indexed regions"""
if self.x1 != None and self.x2 != None:
return self.x2 - self.x1
else :
if len(self.children) == 0 :
return 0
else :
l = self.children[0].x2 - self.children[0].x1
for i in range(1, len(self.children)) :
l += s... | Can you implement a function in Python 3 that
returns the total length of indexed regions | You are a Python code analyst, evaluating scripts for potential improvements. |
def getFirstLevel(self) :
"""returns a list of couples (x1, x2) of all the first level indexed regions"""
res = []
if len(self.children) > 0 :
for c in self.children:
res.append((c.x1, c.x2))
else :
if self.x1 != None :
res = [(self.x1, self.x2)]
else :
res = None
return res | How would you code a function in Python 3 to
return a list of couples ( x1 x2 ) of all the first level indexed regions | As a Python code analyst, you investigate and solve complex coding mysteries |
def flatten(self) :
"""Flattens the tree. The tree become a tree of depth 1 where overlapping regions have been merged together"""
if len(self.children) > 1 :
children = self.children
self.emptyChildren()
children[0].emptyChildren()
x1 = children[0].x1
x2 = children[0].x2
refObjs = [children[0... | Create a Python 3 function to
flatten the tree. The tree become a tree of depth 1 where overlapping regions have been merged together. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Moves tree to a new starting position updates x1s of children | Can you generate the documentation for the following Python 3 function
def move(self, newX1) :
if self.x1 != None and self.x2 != None :
offset = newX1-self.x1
aux_moveTree(offset, self)
elif len(self.children) > 0 :
offset = newX1-self.children[0].x1
aux_moveTree(offset, self) | As a Python code composer, you craft elegant and concise scripts. |
def encode(self, sequence):
"""Returns a tuple (binary reprensentation, default sequence, polymorphisms list)"""
polymorphisms = []
defaultSequence = ''
binSequence = array.array(self.forma.typecode)
b = 0
i = 0
trueI = 0 #not inc in case if poly
poly = set()
while i < len(sequence)-1:
b = b | ... | Write a Python 3 function for
encoding a binary reprensentation default sequence and polymorphisms list | As a Python code composer, you craft elegant and concise scripts. |
def __getSequenceVariants(self, x1, polyStart, polyStop, listSequence) :
"""polyStop, is the polymorphisme at wixh number where the calcul of combinaisons stops"""
if polyStart < len(self.polymorphisms) and polyStart < polyStop:
sequence = copy.copy(listSequence)
ret = []
pk = self.polymorphisms[polyS... | Write a Python 3 function for
getting the list of variants from a polymorphisme | You are a Python code analyst, evaluating scripts for potential improvements. |
returns the sequences resulting from all combinaisons between x1 and x2 | Here you have a function in Python 3, explain what it does
def getSequenceVariants(self, x1 = 0, x2 = -1, maxVariantNumber = 128) :
if x2 == -1 :
xx2 = len(self.defaultSequence)
else :
xx2 = x2
polyStart = None
nbP = 1
stopped = False
j = 0
for p in self.polymorphisms :
if p[0] >= xx2 :
br... | You are a Python code architect, reviewing and designing scalable and efficient code |
returns the nb of variants of sequences between x1 and x2 | Here you have a function in Python 3, explain what it does
def getNbVariants(self, x1, x2 = -1) :
if x2 == -1 :
xx2 = len(self.defaultSequence)
else :
xx2 = x2
nbP = 1
for p in self.polymorphisms:
if x1 <= p[0] and p[0] <= xx2 :
nbP *= len(p[1])
return nbP | As a python code expert, you are capable of creating scripts from specifications. |
dichotomic search, if lst is None, will return the first position found. If it's a list, will return a list of all positions in lst. returns -1 or [] if no match found | Given the following Python 3 function, write the documentation
def _dichFind(self, needle, currHaystack, offset, lst = None) :
if len(currHaystack) == 1 :
if (offset <= (len(self) - len(needle))) and (currHaystack[0] & needle[0]) > 0 and (self[offset+len(needle)-1] & needle[-1]) > 0 :
found = True
for i... | As a python code expert, you are capable of creating scripts from specifications. |
def _kmp_search_first(self, pInput_sequence, pPattern):
"""use KMP algorithm to search the first occurrence in the input_sequence of the pattern. both arguments are integer arrays. return the position of the occurence if found; otherwise, -1."""
input_sequence, pattern = pInput_sequence,... | Write a Python 3 function for
using KMP algorithm to search the first occurrence in the input_sequence of the pattern. both arguments are integer arrays. return the position of the first occurrence if found ; otherwise - 1. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _kmp_search_all(self, pInput_sequence, pPattern):
"""use KMP algorithm to search all occurrence in the input_sequence of the pattern. both arguments are integer arrays. return a list of the positions of the occurences if found; otherwise, []."""
r = []
input_sequence,... | How would you code a function in Python 3 to
use KMP algorithm to search all occurences in the input_sequence of the pattern. both arguments are integer arrays. return a list of the positions of the occurences if found otherwise []. | As a python code expert, you are capable of creating scripts from specifications. |
find with KMP - searching. | Make a summary of the following Python 3 code
def _kmp_find(self, needle, haystack, lst = None):
if lst != None: return self._kmp_search_all(haystack, needle)
else: return self._kmp_search_first(haystack, needle) | As a Python code translator, you convert algorithms and pseudocode into Python. |
returns the first occurence of strSeq in self. Takes polymorphisms into account | Explain what the following Python 3 code does
def findByBiSearch(self, strSeq) :
arr = self.encode(strSeq)
return self._dichFind(arr[0], self, 0, lst = None) | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.