output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def _button_plus_clicked(self, n):
"""
Create a new colorpoint.
"""
self._button_save.setEnabled(True)
self.insert_colorpoint(self._colorpoint_list[n][0],
self._colorpoint_list[n][1],
self._colorpoint_list[n][2])
... | Write a Python 3 function that can
create a new colorpoint and insert it into the GUI | As a Python code composer, you craft elegant and concise scripts. |
def _button_minus_clicked(self, n):
"""
Remove a new colorpoint.
"""
self._button_save.setEnabled(True)
self.pop_colorpoint(n)
self._build_gui() | Write a Python 3 function for
removing a new colorpoint. | As a python code expert, you are capable of creating scripts from specifications. |
Updates the colormap and plot
| Given the following Python 3 function, write the documentation
def _slider_changed(self, n):
self._button_save.setEnabled(True)
self.modify_colorpoint(n, self._sliders[n].value()*0.001, self._colorpoint_list[n][1], self._colorpoint_list[n][2]) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Searches the colormaps directory for all files and populates the list. | Given the following Python 3 function, write the documentation
def _load_cmap_list(self):
# store the current name
name = self.get_name()
# clear the list
self._combobox_cmaps.blockSignals(True)
self._combobox_cmaps.clear()
# list the existing contents
paths = _... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def save(filters='*.*', text='Save THIS, facehead!', default_directory='default_directory', force_extension=None):
"""
Pops up a save dialog and returns the string path of the selected file.
Parameters
----------
filters='*.*'
Which file types should appear in the dialog.
text='Save... | How would you implement a function in Python 3 that
displays a save dialog and returns the path of the selected file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Open a single file in a directory. Returns a string path or None. | Can you generate the documentation for the following Python 3 function
def load(filters="*.*", text='Select a file, FACEFACE!', default_directory='default_directory'):
# make sure the filters contains "*.*" as an option!
if not '*' in filters.split(';'): filters = filters + ";;All files (*)"
# if this ... | As a Python code composer, you craft elegant and concise scripts. |
Open multiple files. Returns a list of string paths or None. | Make a summary of the following Python 3 code
def load_multiple(filters="*.*", text='Select some files, FACEFACE!', default_directory='default_directory'):
# make sure the filters contains "*.*" as an option!
if not '*' in filters.split(';'): filters = filters + ";;All files (*)"
# if this type of pref... | As a python code expert, you are capable of creating scripts from specifications. |
Dumps the current preferences to the preferences. txt file. | Can you generate the documentation for the following Python 3 function
def Dump(self):
prefs_file = open(self.prefs_path, 'w')
for n in range(0,len(self.prefs)):
if len(list(self.prefs.items())[n]) > 1:
prefs_file.write(str(list(self.prefs.items())[n][0]) + ' = ' +
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Resolve and link all types in the scope. | Here you have a function in Python 3, explain what it does
def link(self):
type_specs = {}
types = []
for name, type_spec in self.scope.type_specs.items():
type_spec = type_spec.link(self.scope)
type_specs[name] = type_spec
if type_spec.surface is not None:... | You are a Python code architect, reviewing and designing scalable and efficient code |
Compiles a Thrift file and installs it as a submodule of the caller. | Given the following Python 3 function, write the documentation
def install(path, name=None):
if name is None:
name = os.path.splitext(os.path.basename(path))[0]
callermod = inspect.getmodule(inspect.stack()[1][0])
name = '%s.%s' % (callermod.__name__, name)
if name in sys.modules:
retu... | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse and compile the given Thrift IDL into a surface IDL. | Can you generate a brief explanation for the following Python 3 code
def loads(self, name, document):
return self.compiler.compile(name, document).link().surface | As a Python code composer, you craft elegant and concise scripts. |
Load and compile the given Thrift file. | Can you tell what is the following Python 3 function doing
def load(self, path, name=None):
if name is None:
name = os.path.splitext(os.path.basename(path))[0]
# TODO do we care if the file extension is .thrift?
with open(path, 'r') as f:
document = f.read()
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_url_implicit_flow_user(client_id, scope,
redirect_uri='https://oauth.vk.com/blank.html', display='page',
response_type='token', version=None, state=None, revoke=1):
"""
https://vk.com/dev/implicit_flow_user
:return: url
"""
url =... | Implement a Python 3 function for
getting the URL for implicit flow user. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function returns a URL that can be used to get the authorization code for a user access token. | Given the following Python 3 function, write the documentation
def get_url_authcode_flow_user(client_id, redirect_uri, display="page", scope=None, state=None):
url = "https://oauth.vk.com/authorize"
params = {
"client_id": client_id,
"redirect_uri": redirect_uri,
"display": display,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_fake_data(*a):
"""
Called whenever someone presses the "fire" button.
"""
# add columns of data to the databox
d['x'] = _n.linspace(0,10,100)
d['y'] = _n.cos(d['x']) + 0.1*_n.random.rand(100)
# update the curve
c.setData(d['x'], d['y']) | Implement a function in Python 3 to
call when someone presses the fire button. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def setOpts(self, **opts):
"""
Changes the behavior of the SpinBox. Accepts most of the arguments
allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`.
"""
#print opts
for k in opts:
if k == 'bounds':
#print opts[k]
... | Can you create a Python 3 function that
sets the behavior of the SpinBox. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def setMaximum(self, m, update=True):
"""Set the maximum allowed value (or None for no limit)"""
if m is not None:
m = D(asUnicode(m))
self.opts['bounds'][1] = m
if update:
self.setValue() | Write a Python 3 function that can
set the maximum allowed value for this option | As a Python code translator, you convert algorithms and pseudocode into Python. |
Select the numerical portion of the text to allow quick editing by the user. | Explain what the following Python 3 code does
def selectNumber(self):
le = self.lineEdit()
text = asUnicode(le.text())
if self.opts['suffix'] == '':
le.setSelection(0, len(text))
else:
try:
index = text.index(' ')
except ValueError:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def value(self):
"""
Return the value of this SpinBox.
"""
if self.opts['int']:
return int(self.val)
else:
return float(self.val) | Create a Python 3 function to
return the value of this SpinBox. | You are a Python code architect, reviewing and designing scalable and efficient code |
def setValue(self, value=None, update=True, delaySignal=False):
"""
Set the value of this spin.
If the value is out of bounds, it will be clipped to the nearest boundary.
If the spin is integer type, the value will be coerced to int.
Returns the actual value set.
... | Implement a Python 3 function for
setting the value of the current spin. | As a Python code composer, you craft elegant and concise scripts. |
def interpret(self):
"""Return value of text. Return False if text is invalid, raise exception if text is intermediate"""
strn = self.lineEdit().text()
suf = self.opts['suffix']
if len(suf) > 0:
if strn[-len(suf):] != suf:
return False
#raise Excep... | Can you write a function in Python 3 where it
returns value of text. Return False if text is invalid raise exception if text is intermediate | As a Python code analyst, you investigate and solve complex coding mysteries |
Edit has finished ; set value. | Can you generate the documentation for the following Python 3 function
def editingFinishedEvent(self):
#print "Edit finished."
if asUnicode(self.lineEdit().text()) == self.lastText:
#print "no text change."
return
try:
val = self.interpret()
except:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def make_factory(self, cls, count):
""" Get the generators from the Scaffolding class within the model.
"""
field_names = cls._meta.get_all_field_names()
fields = {}
text = []
finalizer = None
scaffold = scaffolding.scaffold_for_model(cls)
for field_name ... | How would you implement a function in Python 3 that
creates a factory for the given class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def compute_indel_length(fs_df):
"""Computes the indel length accounting for wether it is an insertion or
deletion.
Parameters
----------
fs_df : pd.DataFrame
mutation input as dataframe only containing indel mutations
Returns
-------
indel_len : pd.Series
length of ind... | Write a Python 3 script to
compute the indel length accounting for wether it is an insertion or deletion. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Filters out all mutations that are not indels. | Explain what the following Python 3 code does
def keep_indels(mut_df,
indel_len_col=True,
indel_type_col=True):
"""Filters out all mutations that are not indels.
Requires that one of the alleles have '-' indicating either an insertion
or deletion depending if found in refere... | You are a Python code architect, reviewing and designing scalable and efficient code |
Filters out all mutations that are not frameshift indels. | Here you have a function in Python 3, explain what it does
def keep_frameshifts(mut_df,
indel_len_col=True):
"""Filters out all mutations that are not frameshift indels.
Requires that one of the alleles have '-' indicating either an insertion
or deletion depending if found in reference... | As a python code expert, you are capable of creating scripts from specifications. |
Simple function that returns the lengths for each frameshift category in the tree. | Can you tell what is the following Python 3 function doing
def get_frameshift_lengths(num_bins):
fs_len = []
i = 1
tmp_bins = 0
while(tmp_bins<num_bins):
if i%3:
fs_len.append(i)
tmp_bins += 1
i += 1
return fs_len | You are a Python code analyst, evaluating scripts for potential improvements. |
def _init_context(self, gene_seq):
"""Initializes attributes defining mutation contexts and their position.
The self.context2pos and self.pos2context dictionaries map from
sequence context to sequence position and sequence position to
sequence context, respectively. These attributes all... | Write a Python 3 script to
initialize the attributes defining the mutation contexts and their positions. | You are a Python code architect, reviewing and designing scalable and efficient code |
Samples with replacement available positions matching the individual
sequence context. | Given the following Python 3 function, write the documentation
def random_context_pos(self, num, num_permutations, context):
# make sure provide context is valid
if not self.is_valid_context(context):
error_msg = 'Context ({0}) was never seen in sequence.'.format(context)
raise V... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def random_pos(self, context_iterable, num_permutations):
"""Obtains random positions w/ replacement which match sequence context.
Parameters
----------
context_iterable: iterable containing two element tuple
Records number of mutations in each context. context_iterable
... | Write a Python 3 script to
return a list of random positions w/ replacement which match sequence context. | You are a Python code analyst, evaluating scripts for potential improvements. |
def multiprocess_permutation(bed_dict, mut_df, opts, indel_df=None):
"""Handles parallelization of permutations by splitting work
by chromosome.
"""
chroms = sorted(bed_dict.keys(), key=lambda x: len(bed_dict[x]), reverse=True)
multiprocess_flag = opts['processes']>0
if multiprocess_flag:
... | How would you code a function in Python 3 to
handle parallelization of permutations by splitting work by chromosome. | As a Python code composer, you craft elegant and concise scripts. |
Performs a single - process permutation on a set of work items. | Make a summary of the following Python 3 code
def multiprocess_permutation(bed_dict, mut_df, opts):
chroms = sorted(bed_dict.keys())
multiprocess_flag = opts['processes']>0
if multiprocess_flag:
num_processes = opts['processes']
else:
num_processes = 1
num_permutations = opts['num_pe... | As a python code expert, you are capable of creating scripts from specifications. |
Retrieves scores from pickle files. | Given the following Python 3 function, write the documentation
def retrieve_scores(gname, sdir,
codon_pos, germ_aa, somatic_aa,
default_mga=5., default_vest=0,
no_file_flag=-1):
"""Retrieves scores from pickle files.
Used by summary script.
"""
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Reads in VEST scores for given gene. | Can you generate the documentation for the following Python 3 function
def read_vest_pickle(gname, score_dir):
vest_path = os.path.join(score_dir, gname+".vest.pickle")
if os.path.exists(vest_path):
if sys.version_info < (3,):
with open(vest_path) as handle:
gene_vest = pickl... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def compute_vest_stat(vest_dict, ref_aa, somatic_aa, codon_pos,
stat_func=np.mean,
default_val=0.0):
"""Compute missense VEST score statistic.
Note: non-missense mutations are intentially not filtered out and will take
a default value of zero.
Parameters
... | How would you code a function in Python 3 to
compute missense VEST score statistic for a single mutation list. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the MGA Entropy statistic for a given codon. | Can you generate a brief explanation for the following Python 3 code
def compute_mga_entropy_stat(mga_vec, codon_pos,
stat_func=np.mean,
default_val=0.0):
"""Compute MGA entropy conservation statistic
Parameters
----------
mga_vec : np.array
... | As a python code expert, you are capable of creating scripts from specifications. |
def fetch_vest_scores(vest_dict,
ref_aa, somatic_aa, codon_pos,
default_vest=0.0):
"""Get VEST scores from pre-computed scores in dictionary.
Note: either all mutations should be missense or non-missense intended
to have value equal to default.
Parameters
... | Implement a Python 3 function for
getting VEST scores for a given mutation. | As a python code expert, you are capable of creating scripts from specifications. |
Get MGA Entropy conservation scores for a given codon. | Make a summary of the following Python 3 code
def fetch_mga_scores(mga_vec,
codon_pos,
default_mga=None):
"""Get MGAEntropy scores from pre-computed scores in array.
Parameters
----------
mga_vec : np.array
numpy vector containing MGA Entropy conservati... | You are a Python code architect, reviewing and designing scalable and efficient code |
Reads in neighbor graph for given gene. | Make a summary of the following Python 3 code
def read_neighbor_graph_pickle(gname, graph_dir):
graph_path = os.path.join(graph_dir, gname+".pickle")
if os.path.exists(graph_path):
with open(graph_path) as handle:
gene_graph = pickle.load(handle)
return gene_graph
else:
r... | As a Python code analyst, you investigate and solve complex coding mysteries |
Compute the clustering score for a gene on its neighbor graph. | Make a summary of the following Python 3 code
def compute_ng_stat(gene_graph, pos_ct, alpha=.5):
# skip if there are no missense mutations
if not len(pos_ct):
return 1.0, 0
max_pos = max(gene_graph)
codon_vals = np.zeros(max_pos+1)
# smooth out mutation counts
for pos in pos_ct:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def count_frameshift_total(mut_df,
bed_path,
use_unmapped=False,
to_zero_based=False):
"""Count frameshifts for each gene.
Parameters
----------
mut_df : pd.DataFrame
mutation input
bed_path : str
path ... | How would you implement a function in Python 3 that
counts the total number of frameshifts in a single mutation. | You are a Python code architect, reviewing and designing scalable and efficient code |
Retreives the 3 SS sequence flanking the specified exon. | Here you have a function in Python 3, explain what it does
def _fetch_3ss_fasta(fasta, gene_name, exon_num,
chrom, strand, start, end):
"""Retreives the 3' SS sequence flanking the specified exon.
Returns a string in fasta format with the first line containing
a ">" and the second line... | You are a Python code analyst, evaluating scripts for potential improvements. |
Retreive a single gene in FASTA format. | Can you generate a brief explanation for the following Python 3 code
def fetch_gene_fasta(gene_bed, fasta_obj):
gene_fasta = ''
strand = gene_bed.strand
exons = gene_bed.get_exons()
if strand == '-':
exons.reverse() # order exons 5' to 3', so reverse if '-' strand
# iterate over exons
... | As a Python code composer, you craft elegant and concise scripts. |
Updates the attributes of the object to the default values. | Can you tell what is the following Python 3 function doing
def _reset_seq(self):
exon_seq_list, five_ss_seq_list, three_ss_seq_list = self._fetch_seq()
self.exon_seq = ''.join(exon_seq_list)
self.three_prime_seq = three_ss_seq_list
self.five_prime_seq = five_ss_seq_list
self._to... | As a Python code composer, you craft elegant and concise scripts. |
This method adds potential germline variants into the gene sequence. | Can you generate a brief explanation for the following Python 3 code
def add_germline_variants(self, germline_nucs, coding_pos):
if len(germline_nucs) != len(coding_pos):
raise ValueError('Each germline nucleotide should have a coding position')
es = list(self.exon_seq)
for i in ran... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _to_upper(self):
"""Convert sequences to upper case."""
self.exon_seq = self.exon_seq.upper()
self.three_prime_seq = [s.upper() for s in self.three_prime_seq]
self.five_prime_seq = [s.upper() for s in self.five_prime_seq] | Implement a Python 3 function for
converting sequences to upper case. | You are a Python code analyst, evaluating scripts for potential improvements. |
Fetches gene sequence from PySAM fasta object. | Make a summary of the following Python 3 code
def _fetch_seq(self):
exons = []
three_prime_ss = []
five_prime_ss = []
num_exons = self.bed.get_num_exons()
for i in range(num_exons):
# add exon sequence
tmp_id = '{0};exon{1}'.format(self.bed.gene_name, i)
... | As a Python code composer, you craft elegant and concise scripts. |
Make sure chromosome names follow UCSC chr convention. | Explain what the following Python 3 code does
def correct_chrom_names(chroms):
chrom_list = []
for chrom in chroms:
# fix chrom numbering
chrom = str(chrom)
chrom = chrom.replace('23', 'X')
chrom = chrom.replace('24', 'Y')
chrom = chrom.replace('25', 'Mt')
if not ... | You are a Python code analyst, evaluating scripts for potential improvements. |
A python implementation of the cummin function in R | How would you explain what the following Python 3 function does
def cummin(x):
for i in range(1, len(x)):
if x[i-1] < x[i]:
x[i] = x[i-1]
return x | As a python code expert, you are capable of creating scripts from specifications. |
def calc_deleterious_p_value(mut_info,
unmapped_mut_info,
sc,
gs,
bed,
num_permutations,
stop_thresh,
del_threshold,
... | Create a Python 3 function for
calculating the p - value for the number of inactivating SNV mutations. | You are a Python code analyst, evaluating scripts for potential improvements. |
Calculates the p - value for clustering on a neighbor graph composed of codons connected with edges. | Can you tell what is the following Python 3 function doing
def calc_protein_p_value(mut_info,
unmapped_mut_info,
sc,
gs,
bed,
graph_dir,
num_permutations,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the shannon entropy in bits. | Can you tell what is the following Python 3 function doing
def shannon_entropy(p):
return -np.sum(np.where(p!=0, p * np.log2(p), 0)) | As a Python code analyst, you investigate and solve complex coding mysteries |
def normalized_mutation_entropy(counts, total_cts=None):
"""Calculate the normalized mutation entropy based on a list/array
of mutation counts.
Note: Any grouping of mutation counts together should be done before hand
Parameters
----------
counts : np.array_like
array/list of mutation ... | Create a Python 3 function for
calculating the normalized mutation entropy based on a list of mutation counts. | As a Python code analyst, you investigate and solve complex coding mysteries |
def kl_divergence(p, q):
"""Compute the Kullback-Leibler (KL) divergence for discrete distributions.
Parameters
----------
p : np.array
"Ideal"/"true" Probability distribution
q : np.array
Approximation of probability distribution p
Returns
-------
kl : float
KL... | How would you code a function in Python 3 to
compute the Kullback - Leibler divergence for discrete distributions. | As a python code expert, you are capable of creating scripts from specifications. |
Compute the Jensen - Shannon Divergence between two discrete distributions. | Can you generate a brief explanation for the following Python 3 code
def js_divergence(p, q):
m = .5 * (p+q)
js_div = .5*kl_divergence(p, m) + .5*kl_divergence(q, m)
return js_div | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the Jensen - Shannon distance between two discrete distributions. | Explain what the following Python 3 code does
def js_distance(p, q):
js_dist = np.sqrt(js_divergence(p, q))
return js_dist | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _filter_utr(self, ex):
"""Filter out UTR regions from the exon list (ie retain only coding regions).
Coding regions are defined by the thickStart and thickEnd attributes.
Parameters
----------
ex : list of tuples
list of exon positions, [(ex1_start, ex1_end), ..... | How would you implement a function in Python 3 that
filters out UTR regions from the exon list. | As a Python code analyst, you investigate and solve complex coding mysteries |
Sets a list of position intervals for each exon. | Given the following Python 3 function, write the documentation
def _init_exons(self):
exon_starts = [self.chrom_start + int(s)
for s in self.bed_tuple.blockStarts.strip(',').split(',')]
exon_sizes = list(map(int, self.bed_tuple.blockSizes.strip(',').split(',')))
# get chr... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates the self. seqpos2genome dictionary that converts positions relative to the sequence to genome coordinates. | Explain what the following Python 3 code does
def init_genome_coordinates(self) :
self.seqpos2genome = {}
# record genome positions for each sequence position
seq_pos = 0
for estart, eend in self.exons:
for genome_pos in range(estart, eend):
if self.strand ==... | You are a Python code generator, capable of creating scripts from specifications. |
def query_position(self, strand, chr, genome_coord):
"""Provides the relative position on the coding sequence for a given
genomic position.
Parameters
----------
chr : str
chromosome, provided to check validity of query
genome_coord : int
0-based ... | Write a Python 3 script to
return the relative position on the coding sequence for a given genomic position. | As a Python code analyst, you investigate and solve complex coding mysteries |
Start logging information into the log directory. | Here you have a function in Python 3, explain what it does
def start_logging(log_file='', log_level='INFO', verbose=False):
if not log_file:
# create log directory if it doesn't exist
log_dir = os.path.abspath('log') + '/'
if not os.path.isdir(log_dir):
os.mkdir(log_dir)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def log_error_decorator(f):
"""Writes exception to log file if occured in decorated function.
This decorator wrapper is needed for multiprocess logging since otherwise
the python multiprocessing module will obscure the actual line of the error.
"""
@wraps(f)
def wrapper(*args, **kwds):
... | Write a Python 3 function for
writing exception to log file if occured in decorated function. This decorator wrapper is needed for multiprocess logging since otherwise the python multiprocessing module will obscure the actual line of the error. | As a Python code composer, you craft elegant and concise scripts. |
Removes indices from a list. | Given the following Python 3 function, write the documentation
def filter_list(mylist, bad_ixs):
# indices need to be in reverse order for filtering
# to prevent .pop() from yielding eroneous results
bad_ixs = sorted(bad_ixs, reverse=True)
for i in bad_ixs:
mylist.pop(i)
return mylist | As a Python code analyst, you investigate and solve complex coding mysteries |
def rev_comp(seq):
"""Get reverse complement of sequence.
rev_comp will maintain the case of the sequence.
Parameters
----------
seq : str
nucleotide sequence. valid {a, c, t, g, n}
Returns
-------
rev_comp_seq : str
reverse complement of sequence
"""
rev_seq =... | Can you create a Python 3 function that
gets reverse complement of sequence. | As a Python code analyst, you investigate and solve complex coding mysteries |
def bed_generator(bed_path):
"""Iterates through a BED file yielding parsed BED lines.
Parameters
----------
bed_path : str
path to BED file
Yields
------
BedLine(line) : BedLine
A BedLine object which has parsed the individual line in
a BED file.
"""
with o... | Can you implement a function in Python 3 that
iterates through a BED file yielding parsed BED lines. | You are a Python code analyst, evaluating scripts for potential improvements. |
def read_bed(file_path, restricted_genes=None):
"""Reads BED file and populates a dictionary separating genes
by chromosome.
Parameters
----------
file_path : str
path to BED file
filtered_genes: list
list of gene names to not use
Returns
-------
bed_dict: dict
... | Write a Python 3 function that can
read a BED file and populates a dictionary separating genes by chromosome. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _fix_mutation_df(mutation_df, only_unique=False):
"""Drops invalid mutations and corrects for 1-based coordinates.
TODO: Be smarter about what coordinate system is put in the provided
mutations.
Parameters
----------
mutation_df : pd.DataFrame
user provided mutations
only_uniqu... | Create a Python 3 function to
remove invalid and correct mutations for 1 - based coordinates. | As a Python code analyst, you investigate and solve complex coding mysteries |
def calc_windowed_sum(aa_mut_pos,
germ_aa,
somatic_aa,
window=[3]):
"""Calculate the sum of mutations within a window around a particular mutated
codon.
Parameters
----------
aa_mut_pos : list
list of mutated amino acid posit... | Can you write a function in Python 3 where it
calculates the sum of mutations within a particular window around a particular mutated amino acid. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a list of all base context names for a given context number. | Make a summary of the following Python 3 code
def get_all_context_names(context_num):
if context_num == 0:
return ['None']
elif context_num == 1:
return ['A', 'C', 'T', 'G']
elif context_num == 1.5:
return ['C*pG', 'CpG*', 'TpC*', 'G*pA',
'A', 'C', 'T', 'G']
elif ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the ChASM s mutation context acording to CHASM s NUC string. | How would you explain what the following Python 3 function does
def get_chasm_context(tri_nuc):
# check if string is correct length
if len(tri_nuc) != 3:
raise ValueError('Chasm context requires a three nucleotide string '
'(Provided: "{0}")'.format(tri_nuc))
# try dinuc co... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_aa_mut_info(coding_pos, somatic_base, gene_seq):
"""Retrieves relevant information about the effect of a somatic
SNV on the amino acid of a gene.
Information includes the germline codon, somatic codon, codon
position, germline AA, and somatic AA.
Parameters
----------
coding_pos : ... | Can you write a function in Python 3 where it
retrieves relevant information about the effect of a somatic mutation effect on the amino acid of a gene. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def handle_tsg_results(permutation_result):
"""Handles result from TSG results.
Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe.
Parameters
----------
permutation_result : list
output from multiprocess_permutation
Returns
---... | Create a Python 3 function for
handling result from TSG process and converts to dataframe. | You are a Python code analyst, evaluating scripts for potential improvements. |
Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe. | Can you tell what is the following Python 3 function doing
def handle_oncogene_results(permutation_result, num_permutations):
mycols = ['gene', 'num recurrent', 'position entropy',
'mean vest score', 'entropy p-value',
'vest p-value', 'Total Mutations', 'Unmapped to Ref Tx']
permutat... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def handle_hotmaps_results(permutation_result):
"""Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe.
Parameters
----------
permutation_result : list
output from multiprocess_permutation
Returns
-------
permutation_df : pd.DataF... | Create a Python 3 function to
take in output from multiprocess_permutation function and converts to a better formatted dataframe. | As a Python code composer, you craft elegant and concise scripts. |
Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe. | Here you have a function in Python 3, explain what it does
def handle_protein_results(permutation_result):
mycols = ['gene', 'num recurrent', 'normalized graph-smoothed position entropy',
'normalized graph-smoothed position entropy p-value',
'Total Mutations', 'Unmapped to Ref Tx']
p... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe. | Can you generate the documentation for the following Python 3 function
def handle_effect_results(permutation_result):
mycols = ['gene', 'num recurrent', 'num inactivating', 'entropy-on-effect',
'entropy-on-effect p-value',
'Total Mutations', 'Unmapped to Ref Tx']
permutation_df = pd.... | As a Python code composer, you craft elegant and concise scripts. |
Counts the number of frameshifts stratified by a given length. | How would you explain what the following Python 3 function does
def get_frameshift_info(fs_df, bins):
fs_df = compute_indel_length(fs_df)
# count the number INDELs with length non-dividable by 3
num_indels = []
indel_len = []
num_categories = 0
i = 1
while(num_categories<bins):
# no... | You are a Python code generator, capable of creating scripts from specifications. |
Sets the mutation type attribute to a single label based on the attribute flags. | Can you generate the documentation for the following Python 3 function
def set_mutation_type(self, mut_type=''):
if mut_type:
# user specifies a mutation type
self.mutation_type = mut_type
else:
# mutation type is taken from object attributes
if not self.i... | You are a Python code generator, capable of creating scripts from specifications. |
def set_amino_acid(self, aa):
"""Set amino acid change and position."""
aa = aa.upper() # make sure it is upper case
aa = aa[2:] if aa.startswith('P.') else aa # strip "p."
self.__set_mutation_status() # set flags detailing the type of mutation
self.__parse_hgvs_syntax(aa) | Can you write a function in Python 3 where it
sets amino acid change and position. | As a Python code composer, you craft elegant and concise scripts. |
Interpret the mutation type and set appropriate flags. | Can you tell what is the following Python 3 function doing
def __set_mutation_type(self, hgvs_string):
self.__set_lost_stop_status(hgvs_string)
self.__set_lost_start_status(hgvs_string)
self.__set_missense_status(hgvs_string) # missense mutations
self.__set_indel_status() # indel mutat... | As a python code expert, you are capable of creating scripts from specifications. |
def __set_missense_status(self, hgvs_string):
"""Sets the self.is_missense flag."""
# set missense status
if re.search('^[A-Z?]\d+[A-Z?]$', hgvs_string):
self.is_missense = True
self.is_non_silent = True
else:
self.is_missense = False | How would you implement a function in Python 3 that
sets the self. is_missense flag. | As a Python code composer, you craft elegant and concise scripts. |
Sets the self. is_lost_start flag. | Explain what the following Python 3 code does
def __set_lost_start_status(self, hgvs_string):
# set is lost start status
mymatch = re.search('^([A-Z?])(\d+)([A-Z?])$', hgvs_string)
if mymatch:
grps = mymatch.groups()
if int(grps[1]) == 1 and grps[0] != grps[2]:
... | As a python code expert, you are capable of creating scripts from specifications. |
Check for frame shift and set the self. is_frame_shift flag. | Make a summary of the following Python 3 code
def __set_frame_shift_status(self):
if 'fs' in self.hgvs_original:
self.is_frame_shift = True
self.is_non_silent = True
elif re.search('[A-Z]\d+[A-Z]+\*', self.hgvs_original):
# it looks like some mutations dont follow the... | You are a Python code analyst, evaluating scripts for potential improvements. |
def __set_lost_stop_status(self, hgvs_string):
"""Check if the stop codon was mutated to something other than
a stop codon."""
lost_stop_pattern = '^\*\d+[A-Z?]+\*?$'
if re.search(lost_stop_pattern, hgvs_string):
self.is_lost_stop = True
self.is_non_silent = True
... | Write a Python 3 script to
check if the stop codon was mutated to something other than a stop codon. | As a Python code composer, you craft elegant and concise scripts. |
Set whether there is a premature stop codon. | Given the following Python 3 function, write the documentation
def __set_premature_stop_codon_status(self, hgvs_string):
if re.search('.+\*(\d+)?$', hgvs_string):
self.is_premature_stop_codon = True
self.is_non_silent = True
# check if it is also a nonsense mutation
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the status of the indel in the current state of the mutation being an indel. | Here you have a function in Python 3, explain what it does
def __set_indel_status(self):
# set indel status
if "ins" in self.hgvs_original:
# mutation is insertion
self.is_insertion = True
self.is_deletion = False
self.is_indel = True
self.is_n... | You are a Python code analyst, evaluating scripts for potential improvements. |
def __set_unkown_effect(self, hgvs_string):
"""Sets a flag for unkown effect according to HGVS syntax. The
COSMIC database also uses unconventional questionmarks to denote
missing information.
Args:
hgvs_string (str): hgvs syntax with "p." removed
"""
# Stand... | Write a Python 3 function for
setting a flag for unkown effect according to HGVS syntax. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set a flag for no protein expected. | Explain what the following Python 3 code does
def __set_no_protein(self, hgvs_string):
no_protein_list = ['0', '0?'] # no protein symbols
if hgvs_string in no_protein_list:
self.is_no_protein = True
self.is_non_silent = True
else:
self.is_no_protein = False | You are a Python code analyst, evaluating scripts for potential improvements. |
def __parse_hgvs_syntax(self, aa_hgvs):
"""Convert HGVS syntax for amino acid change into attributes.
Specific details of the mutation are stored in attributes like
self.intial (prior to mutation), sel.pos (mutation position),
self.mutated (mutation), and self.stop_pos (position of stop... | Can you implement a function in Python 3 that
converts HGVS syntax into attributes. | You are a Python code analyst, evaluating scripts for potential improvements. |
def deleterious_permutation(obs_del,
context_counts,
context_to_mut,
seq_context,
gene_seq,
num_permutations=10000,
stop_criteria=100,
... | Write a Python 3 function that can
perform null - permutations for the given set of null mutations for a single gene. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def position_permutation(obs_stat,
context_counts,
context_to_mut,
seq_context,
gene_seq,
gene_vest=None,
num_permutations=10000,
stop_criteria=1... | Write a Python 3 script for
performing null - permutations for position - based mutation statistics in a single gene. | You are a Python code generator, capable of creating scripts from specifications. |
def hotmaps_permutation(obs_stat,
context_counts,
context_to_mut,
seq_context,
gene_seq,
window,
num_permutations=10000,
stop_criteria=100,
... | Can you implement a function in Python 3 that
performs null - permutations for position - based mutation statistics in a single gene. | As a Python code analyst, you investigate and solve complex coding mysteries |
Performs null - simulations for position - based mutation statistics in a single gene. | Can you generate a brief explanation for the following Python 3 code
def protein_permutation(graph_score,
num_codons_obs,
context_counts,
context_to_mut,
seq_context,
gene_seq,
... | As a Python code composer, you craft elegant and concise scripts. |
Performs null - permutations for effect - based mutation statistics in a single gene. | Can you tell what is the following Python 3 function doing
def effect_permutation(context_counts,
context_to_mut,
seq_context,
gene_seq,
num_permutations=10000,
pseudo_count=0):
"""Performs null-permut... | You are a Python code analyst, evaluating scripts for potential improvements. |
Performs null - permutations for non - silent ratio across all genes. | Here you have a function in Python 3, explain what it does
def non_silent_ratio_permutation(context_counts,
context_to_mut,
seq_context,
gene_seq,
num_permutations=10000):
"""Performs ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Performs null - permutations and summarizes the results as features over the gene. | Can you generate the documentation for the following Python 3 function
def summary_permutation(context_counts,
context_to_mut,
seq_context,
gene_seq,
score_dir,
num_permutations=10000,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Performs null - permutations across all genes and records the results in a MAF file. | Can you generate the documentation for the following Python 3 function
def maf_permutation(context_counts,
context_to_mut,
seq_context,
gene_seq,
num_permutations=10000,
drop_silent=False):
"""Performs null-permutati... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Render a given value optionally using varios extensions. | Explain what the following Python 3 code does
def markdown(value, extensions=settings.MARKDOWN_EXTENSIONS,
extension_configs=settings.MARKDOWN_EXTENSION_CONFIGS,
safe=False):
""" Render markdown over a given value, optionally using varios extensions.
Default extensions could be define... | As a Python code analyst, you investigate and solve complex coding mysteries |
def editor_js_initialization(selector, **extra_settings):
""" Return script tag with initialization code. """
init_template = loader.get_template(
settings.MARKDOWN_EDITOR_INIT_TEMPLATE)
options = dict(
previewParserPath=reverse('django_markdown_preview'),
**settings.MARKDOWN_EDITO... | How would you code a function in Python 3 to
return script tag with initialization code. | As a Python code analyst, you investigate and solve complex coding mysteries |
Render preview page.
:returns: A rendered preview | Can you generate a brief explanation for the following Python 3 code
def preview(request):
if settings.MARKDOWN_PROTECT_PREVIEW:
user = getattr(request, 'user', None)
if not user or not user.is_staff:
from django.contrib.auth.views import redirect_to_login
return redirect_to_... | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.