output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def compare_profiles(profile1, profile2):
"""
Given two profiles, determine the ratio of similarity, i.e.
the hamming distance between the strings.
Args:
profile1/2 (str): profile string
Returns:
similarity_ratio (float): the ratio of similiarity (0-1)
"... | How would you implement a function in Python 3 that
gives two profiles, determine the ratio of similarity, i.e. the hamming distance between the strings. Args: profile1/2 (str): profile string Returns: similarity_ratio (float): the ratio of similiarity (0-1) | You are a Python code architect, reviewing and designing scalable and efficient code |
def update_profiles(adapter):
"""
For all cases having vcf_path, update the profile string for the samples
Args:
adapter (MongoAdapter): Adapter to mongodb
"""
for case in adapter.cases():
#If the case has a vcf_path, get the profiles and update the
#case with new profil... | Create a Python 3 function for
updating the profile string for all samples in the specified vcf | You are a Python code generator, capable of creating scripts from specifications. |
def profile_stats(adapter, threshold = 0.9):
"""
Compares the pairwise hamming distances for all the sample profiles in
the database. Returns a table of the number of distances within given
ranges.
Args:
adapter (MongoAdapter): Adapter to mongodb
threshold (... | Write a Python 3 function that can
return a dictionary with the number of hamming distances for all the sample profiles in the database. | You are a Python code analyst, evaluating scripts for potential improvements. |
def purity(labels, true_labels):
"""
Calculates the purity score for the given labels.
Args:
labels (array): 1D array of integers
true_labels (array): 1D array of integers - true labels
Returns:
purity score - a float bewteen 0 and 1. Closer to 1 is better.
"""
purity =... | Can you implement a function in Python 3 that
calculates the purity score for the given labels. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the minimum description length score of the model given its log - likelihood and k the number of cell types. | Can you tell what is the following Python 3 function doing
def mdl(ll, k, data):
"""
N - no. of genes
n - no. of cells
k - no. of cell types
R - sum(Dataset) i.e. total no. of reads
function TotCost = TotBits(N,m,p,R,C)
# C is the cost from the cost function
TotCost = C + (N*m... | You are a Python code architect, reviewing and designing scalable and efficient code |
Finds the indices of all genes in the dataset that have a mean < 0. 9 variance. Returns an array of booleans. | Make a summary of the following Python 3 code
def find_nb_genes(data):
data_means = data.mean(1)
data_vars = data.var(1)
nb_indices = data_means < 0.9*data_vars
return nb_indices | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the log of the n - cr function given that a < b. | Make a summary of the following Python 3 code
def log_ncr(a, b):
val = gammaln(a+1) - gammaln(a-b+1) - gammaln(b+1)
return val | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the negative binomial log - likelihood of the data. | Explain what the following Python 3 code does
def nb_ll(data, P, R):
# TODO: include factorial...
#data = data + eps
genes, cells = data.shape
clusters = P.shape[1]
lls = np.zeros((cells, clusters))
for c in range(clusters):
P_c = P[:,c].reshape((genes, 1))
R_c = R[:,c].reshape((... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the zero - inflated negative binomial log - likelihood of the data. | How would you explain what the following Python 3 function does
def zinb_ll(data, P, R, Z):
lls = nb_ll(data, P, R)
clusters = P.shape[1]
for c in range(clusters):
pass
return lls | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the negative LL of a single row. | Here you have a function in Python 3, explain what it does
def nb_ll_row(params, data_row):
p = params[0]
r = params[1]
n = len(data_row)
ll = np.sum(gammaln(data_row + r)) - np.sum(gammaln(data_row + 1))
ll -= n*gammaln(r)
ll += np.sum(data_row)*np.log(p)
ll += n*r*np.log(1-p)
return -l... | As a Python code composer, you craft elegant and concise scripts. |
Fits the NB distribution to data using method of moments. | Given the following Python 3 function, write the documentation
def nb_fit(data, P_init=None, R_init=None, epsilon=1e-8, max_iters=100):
means = data.mean(1)
variances = data.var(1)
if (means > variances).any():
raise ValueError("For NB fit, means must be less than variances")
genes, cells = data... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function performs negative binomial clustering on the given data. | Can you generate the documentation for the following Python 3 function
def nb_cluster(data, k, P_init=None, R_init=None, assignments=None, means=None, max_iters=10):
genes, cells = data.shape
if P_init is None:
P_init = np.random.random((genes, k))
if R_init is None:
R_init = np.random.randi... | As a Python code analyst, you investigate and solve complex coding mysteries |
Fits NB / poisson params to a cluster. | Here you have a function in Python 3, explain what it does
def fit_cluster(data, assignments, k, P_init, R_init, means):
for c in range(k):
if data[:,assignments==c].shape[1] == 0:
_, assignments = kmeans_pp(data, k)
genes, cells = data.shape
nb_gene_indices = np.array([True for i in ran... | You are a Python code analyst, evaluating scripts for potential improvements. |
def zip_ll(data, means, M):
"""
Calculates the zero-inflated Poisson log-likelihood.
Args:
data (array): genes x cells
means (array): genes x k
M (array): genes x k - this is the zero-inflation parameter.
Returns:
cells x k array of log-likelihood for each cell/cluster ... | Create a Python 3 function for
calculating the zero - inflated Poisson log - likelihood for each cell in the cluster. | You are a Python code generator, capable of creating scripts from specifications. |
def zip_ll_row(params, data_row):
"""
Returns the negative log-likelihood of a row given ZIP data.
Args:
params (list): [lambda zero-inf]
data_row (array): 1d array
Returns:
negative log-likelihood
"""
l = params[0]
pi = params[1]
d0 = (data_row==0)
likeliho... | Can you write a function in Python 3 where it
returns the negative log - likelihood of a row given ZIP data. | You are a Python code analyst, evaluating scripts for potential improvements. |
def migrate_database(adapter):
"""Migrate an old loqusdb instance to 1.0
Args:
adapter
Returns:
nr_updated(int): Number of variants that where updated
"""
all_variants = adapter.get_variants()
nr_variants = all_variants.count()
nr_updated = 0
with progressb... | Can you write a function in Python 3 where it
migrates an old loqusdb instance to 1. 0 WorkItem | As a Python code translator, you convert algorithms and pseudocode into Python. |
def calculate_bounding_box(data):
"""
Returns a 2 x m array indicating the min and max along each
dimension.
"""
mins = data.min(0)
maxes = data.max(0)
return mins, maxes | Write a Python 3 function for
calculating the bounding box of each node in each cluster. | As a Python code composer, you craft elegant and concise scripts. |
def calculate_gap(data, clustering, km, B=50, **kwargs):
"""
See: https://datasciencelab.wordpress.com/2013/12/27/finding-the-k-in-k-means-clustering/
https://web.stanford.edu/~hastie/Papers/gap.pdf
Returns two results: the gap score, and s_k.
"""
k = len(set(clustering))
Wk = km.inertia_
... | Write a Python 3 script to
calculate the gap score and sk for a given set of clustered income classes. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def run_gap_k_selection(data, k_min=1, k_max=50, B=5,
skip=5, **kwargs):
"""
Runs gap score for all k from k_min to k_max.
"""
if k_min == k_max:
return k_min
gap_vals = []
sk_vals = []
k_range = list(range(k_min, k_max, skip))
min_k = 0
min_i = 0
for i, k in enum... | Can you create a Python 3 function that
runs gap score for all k from k_min to k_max. | As a Python code composer, you craft elegant and concise scripts. |
Make a request against the RainMachine device. | How would you explain what the following Python 3 function does
async def _request(
self,
method: str,
url: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None) -> dict:
"""Make a request against the RainMachine... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return list of VeSync devices | Make a summary of the following Python 3 code
def get_devices(self) -> list:
if not self.enabled:
return None
self.in_process = True
response, _ = helpers.call_api(
'/cloud/v1/deviceManaged/devices',
'post',
headers=helpers.req_headers(self),
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def login(self) -> bool:
"""Return True if log in request succeeds"""
user_check = isinstance(self.username, str) and len(self.username) > 0
pass_check = isinstance(self.password, str) and len(self.password) > 0
if user_check and pass_check:
response, _ = helpers.call_api(
... | Implement a Python 3 function for
logging in with username and password. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update(self):
"""Fetch updated information about devices"""
if self.device_time_check():
if not self.in_process:
outlets, switches, fans = self.get_devices()
self.outlets = helpers.resolve_updates(self.outlets, outlets)
self.switches = h... | Implement a function in Python 3 to
fetch updated information about devices | As a python code expert, you are capable of creating scripts from specifications. |
def update_energy(self, bypass_check=False):
"""Fetch updated energy information about devices"""
for outlet in self.outlets:
outlet.update_energy(bypass_check) | Create a Python 3 function to
fetch updated energy information about devices | You are a Python code analyst, evaluating scripts for potential improvements. |
def DistFitDataset(Dat):
"""
Given a data matrix, this returns the per-gene fit error for the
Poisson, Normal, and Log-Normal distributions.
Args:
Dat (array): numpy array with shape (genes, cells)
Returns:
d (dict): 'poiss', 'norm', 'lognorm' give the fit error for each distributi... | Implement a Python 3 function for
giving a data matrix, this returns the per-gene fit error for the Poisson, Normal, and Log-Normal distributions. Args: Dat (array): numpy array with shape (genes, cells) Returns: d (dict): 'poiss', 'norm', 'lognorm' give the fit error for each distribution. | You are a Python code analyst, evaluating scripts for potential improvements. |
def delete(adapter, case_obj, update=False, existing_case=False):
"""Delete a case and all of it's variants from the database.
Args:
adapter: Connection to database
case_obj(models.Case)
update(bool): If we are in the middle of an update
existing_case(models.Case): If someth... | Can you write a function in Python 3 where it
deletes a case and all of its variants from the database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def delete_variants(adapter, vcf_obj, case_obj, case_id=None):
"""Delete variants for a case in the database
Args:
adapter(loqusdb.plugins.Adapter)
vcf_obj(iterable(dict))
ind_positions(dict)
case_id(str)
Returns:
nr_deleted (int): Number of deleted variants... | Implement a Python 3 function for
deleting variants for a given VCF file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def annotate(ctx, variant_file, sv):
"""Annotate the variants in a VCF
"""
adapter = ctx.obj['adapter']
variant_path = os.path.abspath(variant_file)
expected_type = 'snv'
if sv:
expected_type = 'sv'
if 'sv':
nr_cases = adapter.nr_cases(sv_cases=True)
else:
nr_... | How would you implement a function in Python 3 that
annotates the variants in a VCF | You are a Python code architect, reviewing and designing scalable and efficient code |
Get tracking info for one or more tracking numbers. | Can you generate a brief explanation for the following Python 3 code
async def find(self, *tracking_numbers: str) -> list:
data = {'data': [{'num': num} for num in tracking_numbers]}
tracking_resp = await self._request('post', API_URL_TRACK, json=data)
print(tracking_resp)
if not track... | You are a Python code generator, capable of creating scripts from specifications. |
binarizes an expression dataset. | Can you tell what is the following Python 3 function doing
def binarize(qualitative):
thresholds = qualitative.min(1) + (qualitative.max(1) - qualitative.min(1))/2.0
binarized = qualitative > thresholds.reshape((len(thresholds), 1)).repeat(8,1)
return binarized.astype(int) | You are a Python code generator, capable of creating scripts from specifications. |
def qualNorm_filter_genes(data, qualitative, pval_threshold=0.05, smoothing=1e-5, eps=1e-5):
"""
Does qualNorm but returns a filtered gene set, based on a p-value threshold.
"""
genes, cells = data.shape
clusters = qualitative.shape[1]
output = np.zeros((genes, clusters))
missing_indices = [... | Implement a Python 3 function for
doing qualNorm but returns a filtered gene set based on a p - value threshold. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generates starting positions for state estimation or qualitative data. | Explain what the following Python 3 code does
def qualNorm(data, qualitative):
genes, cells = data.shape
clusters = qualitative.shape[1]
output = np.zeros((genes, clusters))
missing_indices = []
qual_indices = []
thresholds = qualitative.min(1) + (qualitative.max(1) - qualitative.min(1))/2.0
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Generates starting positions for state estimation or qualitative data for a given gene. | Can you generate the documentation for the following Python 3 function
def qualNormGaussian(data, qualitative):
genes, cells = data.shape
clusters = qualitative.shape[1]
output = np.zeros((genes, clusters))
missing_indices = []
qual_indices = []
for i in range(genes):
if qualitative[i,:]... | You are a Python code architect, reviewing and designing scalable and efficient code |
def script_dir(pyobject, follow_symlinks=True):
"""Get current script's directory
Args:
pyobject (Any): Any Python object in the script
follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.
Returns:
str: Current script's directory
"""
if getattr(sys, '... | Write a Python 3 function that can
get the directory of the current script s contents. | You are a Python code generator, capable of creating scripts from specifications. |
Get current script s directory and then append a filename | How would you explain what the following Python 3 function does
def script_dir_plus_file(filename, pyobject, follow_symlinks=True):
return join(script_dir(pyobject, follow_symlinks), filename) | As a Python code analyst, you investigate and solve complex coding mysteries |
Check how well SVs are working in the database | How would you explain what the following Python 3 function does
def identity(ctx, variant_id):
if not variant_id:
LOG.warning("Please provide a variant id")
ctx.abort()
adapter = ctx.obj['adapter']
version = ctx.obj['version']
LOG.info("Search variants {0}".format(adapter))
... | You are a Python code generator, capable of creating scripts from specifications. |
Return the register entity id for the given resource. | Can you generate the documentation for the following Python 3 function
def registration_authority_entity_id(self):
if ATTR_ENTITY_REGISTRATION_AUTHORITY in self.raw:
try:
return self.raw[
ATTR_ENTITY_REGISTRATION_AUTHORITY][
ATTR_ENTITY_REGIST... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def legal_form(self):
"""In some cases, the legal form is stored in the JSON-data.
In other cases, an ELF-code, consisting of mix of exactly
four letters and numbers are stored. This ELF-code
can be looked up in a registry where a code maps to
a organizational type. ELF-codes are... | Write a Python 3 function that can
return the ELF - code for the specified resource. | As a python code expert, you are capable of creating scripts from specifications. |
Loop through data to find a valid record. Return list of LEI. | Make a summary of the following Python 3 code
def valid_child_records(self):
child_lei = list()
"""Loop through data to find a valid record. Return list of LEI."""
for d in self.raw['data']:
# We're not very greedy here, but it seems some records have
# lapsed even thro... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Annotate a cyvcf variant with observations
| Here you have a function in Python 3, explain what it does
def annotate_variant(variant, var_obj=None):
if var_obj:
variant.INFO['Obs'] = var_obj['observations']
if var_obj.get('homozygote'):
variant.INFO['Hom'] = var_obj['homozygote']
if var_obj.get('hemizygote'):
... | You are a Python code generator, capable of creating scripts from specifications. |
def annotate_snv(adpter, variant):
"""Annotate an SNV/INDEL variant
Args:
adapter(loqusdb.plugin.adapter)
variant(cyvcf2.Variant)
"""
variant_id = get_variant_id(variant)
variant_obj = adapter.get_variant(variant={'_id':variant_id})
annotated_variant = annotated_variant... | Write a Python 3 function for
annotating an SNV variant in a new CNV record | As a Python code translator, you convert algorithms and pseudocode into Python. |
def annotate_svs(adapter, vcf_obj):
"""Annotate all SV variants in a VCF
Args:
adapter(loqusdb.plugin.adapter)
vcf_obj(cyvcf2.VCF)
Yields:
variant(cyvcf2.Variant)
"""
for nr_variants, variant in enumerate(vcf_obj, 1):
variant_info = get_coords(variant)
... | Write a Python 3 function that can
annotate all SV variants in a VCF | You are a Python code architect, reviewing and designing scalable and efficient code |
Annotate all variants in a VCF in a VCF
| Explain what the following Python 3 code does
def annotate_snvs(adapter, vcf_obj):
variants = {}
for nr_variants, variant in enumerate(vcf_obj, 1):
# Add the variant to current batch
variants[get_variant_id(variant)] = variant
# If batch len == 1000 we annotate the batch
if ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_geojson(geojson, srid=4326):
"""
Create a Geometry from a GeoJSON. The SRID can be overridden from the
expected 4326.
"""
type_ = geojson["type"].lower()
if type_ == "geometrycollection":
geometries = []
for geometry in geojson["geometries... | Can you write a function in Python 3 where it
creates a Geometry from a GeoJSON object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def from_shapely(sgeom, srid=None):
"""
Create a Geometry from a Shapely geometry and the specified SRID.
The Shapely geometry will not be modified.
"""
if SHAPELY:
WKBWriter.defaults["include_srid"] = True
if srid:
lgeos.GEOSSetSRID(sgeom... | How would you code a function in Python 3 to
create a Geometry from a Shapely geometry and the specified SRID. | As a Python code analyst, you investigate and solve complex coding mysteries |
def wkb(self):
"""
Get the geometry as an (E)WKB.
"""
return self._to_wkb(use_srid=True, dimz=self.dimz, dimm=self.dimm) | Write a Python 3 script to
return the geometry as an E ) WKB. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the type of the geometry in PostGIS format including additional additional
dimensions and SRID. | How would you explain what the following Python 3 function does
def postgis_type(self):
dimz = "Z" if self.dimz else ""
dimm = "M" if self.dimm else ""
if self.srid:
return "geometry({}{}{},{})".format(self.type, dimz, dimm, self.srid)
else:
return "geometry({}{}{... | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the Poisson log - likelihood for each cell in the cluster pair. | Explain what the following Python 3 code does
def poisson_ll(data, means):
if sparse.issparse(data):
return sparse_poisson_ll(data, means)
genes, cells = data.shape
clusters = means.shape[1]
ll = np.zeros((cells, clusters))
for i in range(clusters):
means_i = np.tile(means[:,i], (cel... | As a python code expert, you are capable of creating scripts from specifications. |
Calculates Poisson LL of two points p1 and p2. | Make a summary of the following Python 3 code
def poisson_ll_2(p1, p2):
p1_1 = p1 + eps
p2_1 = p2 + eps
return np.sum(-p2_1 + p1_1*np.log(p2_1)) | As a Python code composer, you craft elegant and concise scripts. |
def poisson_dist(p1, p2):
"""
Calculates the Poisson distance between two vectors.
p1 can be a sparse matrix, while p2 has to be a dense matrix.
"""
# ugh...
p1_ = p1 + eps
p2_ = p2 + eps
return np.dot(p1_-p2_, np.log(p1_/p2_)) | How would you implement a function in Python 3 that
calculates the Poisson distance between two vectors. | As a python code expert, you are capable of creating scripts from specifications. |
Delete the variants of a case. | How would you explain what the following Python 3 function does
def delete(ctx, family_file, family_type, case_id):
if not (family_file or case_id):
LOG.error("Please provide a family file")
ctx.abort()
adapter = ctx.obj['adapter']
# Get a ped_parser.Family object from family file
fami... | As a Python code composer, you craft elegant and concise scripts. |
Builds weekly monthly and yearly dictionaries | How would you explain what the following Python 3 function does
def update_energy(self, bypass_check: bool = False):
if bypass_check or (not bypass_check and self.update_time_check):
self.get_weekly_energy()
if 'week' in self.energy:
self.get_monthly_energy()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
A simple wrapper for the echo_sedml command. | Here you have a function in Python 3, explain what it does
def main (args):
if len(args) != 3:
print(main.__doc__)
sys.exit(1)
d = libsedml.readSedML(args[1]);
if ( d.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0):
print (d.getErrorLog().toString());
else:
libsedml.writ... | As a python code expert, you are capable of creating scripts from specifications. |
async def main() -> None:
"""Create the aiohttp session and run the example."""
logging.basicConfig(level=logging.INFO)
async with ClientSession() as websession:
try:
client = Client(websession)
await client.profile.login('<EMAIL>', '<PASSWORD>')
_LOGGER.info('A... | How would you implement a function in Python 3 that
creates the aiohttp session and run the example. | You are a Python code architect, reviewing and designing scalable and efficient code |
This function will check if the user has set FACEBOOK_LIKE_APP_ID correctly in the django settings and if so will return True and the intercom_tag template to be displayed. | Can you tell what is the following Python 3 function doing
def like_button_js_tag(context):
if FACEBOOK_APP_ID is None:
log.warning("FACEBOOK_APP_ID isn't setup correctly in your settings")
# make sure FACEBOOK_APP_ID is setup correct and user is authenticated
if FACEBOOK_APP_ID:
request =... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function will check if the user has set the FACEBOOK_APP_ID and if so will check if they have the FACEBOOK_APP_ID setup correctly in the django settings and then will pass the data
along to the intercom_tag template to be displayed. | Can you tell what is the following Python 3 function doing
def like_button_tag(context):
if FACEBOOK_APP_ID is None:
log.warning("FACEBOOK_APP_ID isn't setup correctly in your settings")
# make sure INTERCOM_APPID is setup correct and user is authenticated
if FACEBOOK_APP_ID:
request = co... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_structural_variant(self, variant, max_window = 3000):
"""Add a variant to the structural variants collection
The process of adding an SV variant differs quite a bit from the
more straight forward case of SNV/INDEL.
Variants are represented in the database by cl... | How would you code a function in Python 3 to
add a single variant to the structural variants collection | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_structural_variant(self, variant):
"""Check if there are any overlapping sv clusters
Search the sv variants with chrom start end_chrom end and sv_type
Args:
variant (dict): A variant dictionary
Returns:
variant (dict): A variant dictionary
"""
... | How would you code a function in Python 3 to
return the structural variant that is found in the database | As a python code expert, you are capable of creating scripts from specifications. |
def get_sv_variants(self, chromosome=None, end_chromosome=None, sv_type=None,
pos=None, end=None):
"""Return all structural variants in the database
Args:
chromosome (str)
end_chromosome (str)
sv_type (str)
pos (int): Left positio... | Implement a function in Python 3 to
return all structural variants in the database | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_clusters(self, variant_id):
"""Search what clusters a variant belongs to
Args:
variant_id(str): From ID column in vcf
Returns:
clusters()
"""
query = {'variant_id':variant_id}
identities = self.db.identity.find(query)
... | Implement a function in Python 3 to
search what clusters a variant belongs to | As a python code expert, you are capable of creating scripts from specifications. |
Runs state estimation for multiple initializations returning the result with the highest log - likelihood. | Explain what the following Python 3 code does
def run_state_estimation(data, clusters, dist='Poiss', reps=1, **kwargs):
clusters = int(clusters)
func = poisson_estimate_state
dist = dist.lower()
if dist=='poiss' or dist=='poisson':
pass
elif dist=='nb':
func = nb_estimate_state
e... | You are a Python code generator, capable of creating scripts from specifications. |
Turn Air Purifier on | How would you explain what the following Python 3 function does
def turn_on(self):
if self.device_status != 'on':
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
body['status'] = 'on'
head = helpers.req_headers(self.manager)
... | You are a Python code generator, capable of creating scripts from specifications. |
def fan_speed(self, speed: int = None) -> bool:
"""Adjust Fan Speed by Specifying 1,2,3 as argument or cycle
through speeds increasing by one"""
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
head = helpers.req_headers(self.manager)
if ... | Implement a function in Python 3 to
adjust the fan speed by Specifying 1 2 3 as argument or cycle through speeds increasing by one | As a python code expert, you are capable of creating scripts from specifications. |
Set mode to manual auto or sleep | Make a summary of the following Python 3 code
def mode_toggle(self, mode: str) -> bool:
head = helpers.req_headers(self.manager)
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
if mode != body['mode'] and mode in ['sleep', 'auto', 'manual']:
bod... | As a Python code composer, you craft elegant and concise scripts. |
Compute the number of fourier series of a given interval x. | Here you have a function in Python 3, explain what it does
def fourier_series(x, *a):
output = 0
output += a[0]/2
w = a[1]
for n in range(2, len(a), 2):
n_ = n/2
val1 = a[n]
val2 = a[n+1]
output += val1*np.sin(n_*x*w)
output += val2*np.cos(n_*x*w)
return outpu... | You are a Python code generator, capable of creating scripts from specifications. |
def graph_distances(start, edges, distances):
"""
Given an undirected adjacency list and a pairwise distance matrix between
all nodes: calculates distances along graph from start node.
Args:
start (int): start node
edges (list): adjacency list of tuples
distances (array): 2d arr... | Create a Python 3 function to
calculate the distances along a graph from a start node to a new node. | You are a Python code architect, reviewing and designing scalable and efficient code |
def pseudotime(starting_node, edges, fitted_vals):
"""
Args:
starting_node (int): index of the starting node
edges (list): list of tuples (node1, node2)
fitted_vals (array): output of lineage (2 x cells)
Returns:
A 1d array containing the pseudotime value of each cell.
"... | Create a Python 3 function for
returning a 1d array containing the pseudotime value of each cell in the tree. | You are a Python code generator, capable of creating scripts from specifications. |
Add countries data from country information to the internal dictionary. | How would you explain what the following Python 3 function does
def _add_countriesdata(cls, iso3, country):
# type: (str, hxl.Row) -> None
"""
Set up countries data from data in form provided by UNStats and World Bank
Args:
iso3 (str): ISO3 code for country
count... | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets up countries data from data provided by UNStats and World Bank. | Here you have a function in Python 3, explain what it does
def set_countriesdata(cls, countries):
# type: (str) -> None
"""
Set up countries data from data in form provided by UNStats and World Bank
Args:
countries (str): Countries data in HTML format provided by UNStats
... | As a Python code composer, you craft elegant and concise scripts. |
def countriesdata(cls, use_live=True):
# type: (bool) -> List[Dict[Dict]]
"""
Read countries data from OCHA countries feed (falling back to file)
Args:
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
Returns:
... | Can you implement a function in Python 3 that
reads countries data from OCHA and stores it in the class s _countriesdata attribute. | As a Python code composer, you craft elegant and concise scripts. |
def set_ocha_url(cls, url=None):
# type: (str) -> None
"""
Set World Bank url from which to retrieve countries data
Args:
url (str): World Bank url from which to retrieve countries data. Defaults to internal value.
Returns:
None
"""
if ur... | How would you implement a function in Python 3 that
sets the World Bank url from which to retrieve countries data. | As a Python code composer, you craft elegant and concise scripts. |
def get_country_info_from_iso3(cls, iso3, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]
"""Get country information from ISO3 code
Args:
iso3 (str): ISO3 code for which to get country information
use_live (bool):... | How would you code a function in Python 3 to
return the country information for a given ISO3 code. | As a python code expert, you are capable of creating scripts from specifications. |
def get_country_name_from_iso3(cls, iso3, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
"""Get country name from ISO3 code
Args:
iso3 (str): ISO3 code for which to get country name
use_live (bool): Try to get use late... | Implement a Python 3 function for
returning the name of the country from ISO3 code. | As a Python code composer, you craft elegant and concise scripts. |
Get ISO2 code from ISO3 code. | Can you generate a brief explanation for the following Python 3 code
def get_iso2_from_iso3(cls, iso3, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
"""Get ISO2 from ISO3 code
Args:
iso3 (str): ISO3 code for which to get ISO2 cod... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the country name from ISO2 code. | Can you tell what is the following Python 3 function doing
def get_country_info_from_iso2(cls, iso2, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]
"""Get country name from ISO2 code
Args:
iso2 (str): ISO2 code for which to ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the name of the country from ISO2 code. | Can you generate a brief explanation for the following Python 3 code
def get_country_name_from_iso2(cls, iso2, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
"""Get country name from ISO2 code
Args:
iso2 (str): ISO2 code for which... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_m49_from_iso3(cls, iso3, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[int]
"""Get M49 from ISO3 code
Args:
iso3 (str): ISO3 code for which to get M49 code
use_live (bool): Try to get use latest data from web rathe... | How would you implement a function in Python 3 that
gets M49 code from ISO3 code. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get country name from M49 code. | Can you generate the documentation for the following Python 3 function
def get_country_info_from_m49(cls, m49, use_live=True, exception=None):
# type: (int, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]
"""Get country name from M49 code
Args:
m49 (int): M49 numeric cod... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the country name from M49 code. | Here you have a function in Python 3, explain what it does
def get_country_name_from_m49(cls, m49, use_live=True, exception=None):
# type: (int, bool, Optional[ExceptionUpperBound]) -> Optional[str]
"""Get country name from M49 code
Args:
m49 (int): M49 numeric code for which to get... | You are a Python code architect, reviewing and designing scalable and efficient code |
Expands abbreviation in country name in various ways. | Make a summary of the following Python 3 code
def expand_countryname_abbrevs(cls, country):
# type: (str) -> List[str]
"""Expands abbreviation(s) in country name in various ways (eg. FED -> FEDERATED, FEDERAL etc.)
Args:
country (str): Country with abbreviation(s)to expand
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Simplifies a country name by removing descriptive text eg. DEMOCRATIC REPUBLIC OF etc. | How would you explain what the following Python 3 function does
def simplify_countryname(cls, country):
# type: (str) -> (str, List[str])
"""Simplifies country name by removing descriptive text eg. DEMOCRATIC, REPUBLIC OF etc.
Args:
country (str): Country name to simplify
R... | As a python code expert, you are capable of creating scripts from specifications. |
def get_iso3_country_code(cls, country, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
"""Get ISO3 code for cls. Only exact matches or None are returned.
Args:
country (str): Country for which to get ISO3 code
use_live... | Implement a function in Python 3 to
return ISO3 code for a given country. Only exact matches or None are returned. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the ISO3 code for a given country. | Can you generate a brief explanation for the following Python 3 code
def get_iso3_country_code_fuzzy(cls, country, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Tuple[[Optional[str], bool]]
"""Get ISO3 code for cls. A tuple is returned with the first value being t... | You are a Python code generator, capable of creating scripts from specifications. |
def get_countries_in_region(cls, region, use_live=True, exception=None):
# type: (Union[int,str], bool, Optional[ExceptionUpperBound]) -> List[str]
"""Get countries (ISO3 codes) in region
Args:
region (Union[int,str]): Three digit UNStats M49 region code or region name
u... | Can you implement a function in Python 3 that
returns a list of countries in a given region | You are a Python code analyst, evaluating scripts for potential improvements. |
def load_profile(ctx, variant_file, update, stats, profile_threshold):
"""
Command for profiling of samples. User may upload variants used in profiling
from a vcf, update the profiles for all samples, and get some stats
from the profiles in the database.
Profiling is used to monito... | Implement a Python 3 function for
loading the profile of samples. | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_profile_variants(self, profile_variants):
"""Add several variants to the profile_variant collection in the
database
Args:
profile_variants(list(models.ProfileVariant))
"""
results = self.db.profile_variant.insert_many(profile_variants)
return res... | Can you write a function in Python 3 where it
adds several variants to the profile_variant collection in the database | As a Python code analyst, you investigate and solve complex coding mysteries |
def zip_fit_params(data):
"""
Returns the ZIP parameters that best fit a given data set.
Args:
data (array): 2d array of genes x cells belonging to a given cluster
Returns:
L (array): 1d array of means
M (array): 1d array of zero-inflation parameter
"""
genes, cells = d... | Can you write a function in Python 3 where it
returns the ZIP parameters that best fit a given data set. | You are a Python code analyst, evaluating scripts for potential improvements. |
def zip_cluster(data, k, init=None, max_iters=100):
"""
Performs hard EM clustering using the zero-inflated Poisson distribution.
Args:
data (array): A 2d array- genes x cells
k (int): Number of clusters
init (array, optional): Initial centers - genes x k array. Default: None, use k... | Write a Python 3 script to
perform hard EM clustering using the zero - inflated Poisson distribution. | You are a Python code analyst, evaluating scripts for potential improvements. |
Dimensionality reduction using MDS | Can you tell what is the following Python 3 function doing
def diffusion_mds(means, weights, d, diffusion_rounds=10):
for i in range(diffusion_rounds):
weights = weights*weights
weights = weights/weights.sum(0)
X = dim_reduce(means, weights, d)
if X.shape[0]==2:
return X.dot(weights)... | As a Python code analyst, you investigate and solve complex coding mysteries |
Dimensionality reduction using MDS. | Make a summary of the following Python 3 code
def mds(means, weights, d):
X = dim_reduce(means, weights, d)
if X.shape[0]==2:
return X.dot(weights)
else:
return X.T.dot(weights) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Does a MDS on the data directly not on the means. | Can you generate the documentation for the following Python 3 function
def dim_reduce_data(data, d):
genes, cells = data.shape
distances = np.zeros((cells, cells))
for i in range(cells):
for j in range(cells):
distances[i,j] = poisson_dist(data[:,i], data[:,j])
# do MDS on the distan... | As a Python code analyst, you investigate and solve complex coding mysteries |
def case(self, case):
"""Get a case from the database
Search the cases with the case id
Args:
case (dict): A case dictionary
Returns:
mongo_case (dict): A mongo case dictionary
"""
LOG.debug("Getting case {0} from database".f... | Write a Python 3 script for
getting a case from the database | As a Python code composer, you craft elegant and concise scripts. |
Return the number of cases in the database | Can you tell what is the following Python 3 function doing
def nr_cases(self, snv_cases=None, sv_cases=None):
query = {}
if snv_cases:
query = {'vcf_path': {'$exists':True}}
if sv_cases:
query = {'vcf_sv_path': {'$exists':True}}
if snv_cases and sv_cases:... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_case(self, case, update=False):
"""Add a case to the case collection
If the case exists and update is False raise error.
Args:
db (MongoClient): A connection to the mongodb
case (dict): A case dictionary
update(bool): If existing case should be updat... | How would you implement a function in Python 3 that
adds a case to the case collection | You are a Python code analyst, evaluating scripts for potential improvements. |
def delete_case(self, case):
"""Delete case from the database
Delete a case from the database
Args:
case (dict): A case dictionary
"""
mongo_case = self.case(case)
if not mongo_case:
raise CaseError("Tried to delete case {0} but cou... | Can you create a Python 3 function that
deletes a case from the database | You are a Python code analyst, evaluating scripts for potential improvements. |
Build a list of sink proxies for each driver. | How would you explain what the following Python 3 function does
def make_sink_proxies(drivers):
''' Build a list of sink proxies. sink proxies are a two-level ordered
dictionary. The first level contains the lst of drivers, and the second
level contains the list of sink proxies for each driver:
drv1-->... | You are a Python code architect, reviewing and designing scalable and efficient code |
Builds a ProfileVariant object from a Cyvcf2. Variant object. | Here you have a function in Python 3, explain what it does
def build_profile_variant(variant):
chrom = variant.CHROM
if chrom.startswith(('chr', 'CHR', 'Chr')):
chrom = chrom[3:]
pos = int(variant.POS)
variant_id = get_variant_id(variant)
ref = variant.REF
alt = variant.ALT[0]
m... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add loqus specific information to a VCF header | Given the following Python 3 function, write the documentation
def add_headers(vcf_obj, nr_cases=None, sv=False):
vcf_obj.add_info_to_header(
{
'ID':"Obs",
'Number': '1',
'Type': 'Integer',
'Description': "The number of observations for the variant"}
)
... | As a python code expert, you are capable of creating scripts from specifications. |
def get_file_handle(file_path):
"""Return cyvcf2 VCF object
Args:
file_path(str)
Returns:
vcf_obj(cyvcf2.VCF)
"""
LOG.debug("Check if file end is correct")
if not os.path.exists(file_path):
raise IOError("No such file:{0}".format(file_path))
if not os.path.splitex... | Write a Python 3 script for
returning a VCF object for a given file path. | You are a Python code architect, reviewing and designing scalable and efficient code |
def check_vcf(vcf_path, expected_type='snv'):
"""Check if there are any problems with the vcf file
Args:
vcf_path(str)
expected_type(str): 'sv' or 'snv'
Returns:
vcf_info(dict): dict like
{
'nr_variants':<INT>,
'variant_type': <STR> in ['snv', 'sv'],... | Implement a Python 3 function for
checking if the vcf file is in correct format. | 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.