text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _list_patient_ids(self): """ Utility function to return a list of patient ids in the Cohort """
results = [] for patient in self: results.append(patient.id) return(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summarize_provenance_per_cache(self): """Utility function to summarize provenance files for cached items used by a Cohort, for each cache_dir that exists. On...
provenance_summary = {} df = self.as_dataframe() for cache in self.cache_names: cache_name = self.cache_names[cache] cache_provenance = None num_discrepant = 0 this_cache_dir = path.join(self.cache_dir, cache_name) if path.exists(this_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summarize_provenance(self): """Utility function to summarize provenance files for cached items used by a Cohort. At the moment, most PROVENANCE files contain...
provenance_per_cache = self.summarize_provenance_per_cache() summary_provenance = None num_discrepant = 0 for cache in provenance_per_cache: if not(summary_provenance): ## pick arbitrary provenance & call this the "summary" (for now) summary_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summarize_data_sources(self): """Utility function to summarize data source status for this Cohort, useful for confirming the state of data used for an analys...
provenance_file_summary = self.summarize_provenance() dataframe_hash = self.summarize_dataframe() results = { "provenance_file_summary": provenance_file_summary, "dataframe_hash": dataframe_hash } return(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strelka_somatic_variant_stats(variant, variant_metadata): """Parse out the variant calling statistics for a given variant from a Strelka VCF Parameters varia...
sample_info = variant_metadata["sample_info"] # Ensure there are exactly two samples in the VCF, a tumor and normal assert len(sample_info) == 2, "More than two samples found in the somatic VCF" tumor_stats = _strelka_variant_stats(variant, sample_info["TUMOR"]) normal_stats = _strelka_variant_sta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _strelka_variant_stats(variant, sample_info): """Parse a single sample"s variant calling statistics based on Strelka VCF output Parameters variant : varcode....
if variant.is_deletion or variant.is_insertion: # ref: https://sites.google.com/site/strelkasomaticvariantcaller/home/somatic-variant-output ref_depth = int(sample_info['TAR'][0]) # number of reads supporting ref allele (non-deletion) alt_depth = int(sample_info['TIR'][0]) # number of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutect_somatic_variant_stats(variant, variant_metadata): """Parse out the variant calling statistics for a given variant from a Mutect VCF Parameters variant...
sample_info = variant_metadata["sample_info"] # Ensure there are exactly two samples in the VCF, a tumor and normal assert len(sample_info) == 2, "More than two samples found in the somatic VCF" # Find the sample with the genotype field set to variant in the VCF tumor_sample_infos = [info for inf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maf_somatic_variant_stats(variant, variant_metadata): """ Parse out the variant calling statistics for a given variant from a MAF file Assumes the MAF format...
tumor_stats = None normal_stats = None if "t_ref_count" in variant_metadata: tumor_stats = _maf_variant_stats(variant, variant_metadata, prefix="t") if "n_ref_count" in variant_metadata: normal_stats = _maf_variant_stats(variant, variant_metadata, prefix="n") return SomaticVariantSt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _vcf_is_strelka(variant_file, variant_metadata): """Return True if variant_file given is in strelka format """
if "strelka" in variant_file.lower(): return True elif "NORMAL" in variant_metadata["sample_info"].keys(): return True else: vcf_reader = vcf.Reader(open(variant_file, "r")) try: vcf_type = vcf_reader.metadata["content"] except KeyError: vcf_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variant_stats_from_variant(variant, metadata, merge_fn=(lambda all_stats: \ max(all_stats, key=(lambda stats: stats.tumor_stats.depth)))): """Parse the varia...
all_stats = [] for (variant_file, variant_metadata) in metadata.items(): if _vcf_is_maf(variant_file=variant_file): stats = maf_somatic_variant_stats(variant, variant_metadata) elif _vcf_is_strelka(variant_file=variant_file, variant_metadata=variant_meta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_ensembl_coverage(cohort, coverage_path, min_tumor_depth, min_normal_depth=0, pageant_dir_fn=None): """ Load in Pageant CoverageDepth results with Ensemb...
# Function to grab the pageant file name using the Patient if pageant_dir_fn is None: pageant_dir_fn = lambda patient: patient.id columns_both = [ "depth1", # Normal "depth2", # Tumor "onBP1", "onBP2", "numOnLoci", "fracBPOn1", "fracBPOn2", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vertical_percent(plot, percent=0.1): """ Using the size of the y axis, return a fraction of that size. """
plot_bottom, plot_top = plot.get_ylim() return percent * (plot_top - plot_bottom)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_significance_indicator(plot, col_a=0, col_b=1, significant=False): """ Add a p-value significance indicator. """
plot_bottom, plot_top = plot.get_ylim() # Give the plot a little room for the significance indicator line_height = vertical_percent(plot, 0.1) # Add some extra spacing below the indicator plot_top = plot_top + line_height # Add some extra spacing above the indicator plot.set_ylim(top=plot_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stripboxplot(x, y, data, ax=None, significant=None, **kwargs): """ Overlay a stripplot on top of a boxplot. """
ax = sb.boxplot( x=x, y=y, data=data, ax=ax, fliersize=0, **kwargs ) plot = sb.stripplot( x=x, y=y, data=data, ax=ax, jitter=kwargs.pop("jitter", 0.05), color=kwargs.pop("color", "0.3"), **kwargs ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fishers_exact_plot(data, condition1, condition2, ax=None, condition1_value=None, alternative="two-sided", **kwargs): """ Perform a Fisher's exact test to com...
plot = sb.barplot( x=condition1, y=condition2, ax=ax, data=data, **kwargs ) plot.set_ylabel("Percent %s" % condition2) condition1_mask = get_condition_mask(data, condition1, condition1_value) count_table = pd.crosstab(data[condition1], data[condition2]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mann_whitney_plot(data, condition, distribution, ax=None, condition_value=None, alternative="two-sided", skip_plot=False, **kwargs): """ Create a box plot co...
condition_mask = get_condition_mask(data, condition, condition_value) U, p_value = mannwhitneyu( data[condition_mask][distribution], data[~condition_mask][distribution], alternative=alternative ) plot = None if not skip_plot: plot = stripboxplot( x=condi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roc_curve_plot(data, value_column, outcome_column, bootstrap_samples=100, ax=None): """Create a ROC curve and compute the bootstrap AUC for the given variabl...
scores = bootstrap_auc(df=data, col=value_column, pred_col=outcome_column, n_bootstrap=bootstrap_samples) mean_bootstrap_auc = scores.mean() print("{}, Bootstrap (samples = {}) AUC:{}, std={}".format( value_column, boo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _strip_column_name(col_name, keep_paren_contents=True): """ Utility script applying several regexs to a string. Intended to be used by `strip_column_names`. ...
# start with input new_col_name = col_name # replace meaningful punctuation with text equivalents # surround each with whitespace to enforce consistent use of _ punctuation_to_text = { '<=': 'le', '>=': 'ge', '=<': 'le', '=>': 'ge', '<': 'lt', '>': 'g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strip_column_names(cols, keep_paren_contents=True): """ Utility script for renaming pandas columns to patsy-friendly names. Revised names have been: - stripp...
# strip/replace punctuation new_cols = [ _strip_column_name(col, keep_paren_contents=keep_paren_contents) for col in cols] if len(new_cols) != len(set(new_cols)): warn_str = 'Warning: strip_column_names (if run) would introduce duplicate names.' warn_str += ' Reverting col...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attributes(obj, additional_data): """ Given an object and a dictionary, give the object new attributes from that dictionary. Uses _strip_column_name to g...
for key, value in additional_data.items(): if hasattr(obj, key): raise ValueError("Key %s in additional_data already exists in this object" % key) setattr(obj, _strip_column_name(key), value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def return_obj(cols, df, return_cols=False): """Construct a DataFrameHolder and then return either that or the DataFrame."""
df_holder = DataFrameHolder(cols=cols, df=df) return df_holder.return_self(return_cols=return_cols)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_provenance( this_provenance, other_provenance, left_outer_diff = "In current but not comparison", right_outer_diff = "In comparison but not current"):...
## if either this or other items is null, return 0 if (not this_provenance or not other_provenance): return 0 this_items = set(this_provenance.items()) other_items = set(other_provenance.items()) # Two-way diff: are any modules introduced, and are any modules lost? new_diff = this_ite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_random_missense_variants(num_variants=10, max_search=100000, reference="GRCh37"): """ Generate a random collection of missense variants by trying ra...
variants = [] for i in range(max_search): bases = ["A", "C", "T", "G"] random_ref = choice(bases) bases.remove(random_ref) random_alt = choice(bases) random_contig = choice(["1", "2", "3", "4", "5"]) random_variant = Variant(contig=random_contig, start=randint(1,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_simple_vcf(filename, variant_collection): """ Output a very simple metadata-free VCF for each variant in a variant_collection. """
contigs = [] positions = [] refs = [] alts = [] for variant in variant_collection: contigs.append("chr" + variant.contig) positions.append(variant.start) refs.append(variant.ref) alts.append(variant.alt) df = pd.DataFrame() df["contig"] = contigs df["posi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_folder(self, path): """Looks up folder contents of `path.`"""
# Inspired by https://github.com/rspivak/sftpserver/blob/0.3/src/sftpserver/stub_sftp.py#L70 try: folder_contents = [] for f in os.listdir(path): attr = paramiko.SFTPAttributes.from_stat(os.stat(os.path.join(path, f))) attr.filename = f ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_variants(variant_collection, patient, filter_fn, **kwargs): """Filter variants from the Variant Collection Parameters variant_collection : varcode.Var...
if filter_fn: return variant_collection.clone_with_new_elements([ variant for variant in variant_collection if filter_fn(FilterableVariant( variant=variant, variant_collection=variant_collection, pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_effects(effect_collection, variant_collection, patient, filter_fn, all_effects, **kwargs): """Filter variants from the Effect Collection Parameters ef...
def top_priority_maybe(effect_collection): """ Always (unless all_effects=True) take the top priority effect per variant so we end up with a single effect per variant. """ if all_effects: return effect_collection return EffectCollection(list(effect_collec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def count_lines_in(filename): "Count lines in a file" f = open(filename) lines = 0 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def view_name_from(path): "Resolve a path to the full python module name of the related view function" try: return CACHED_VIEWS[path] except KeyError: view = resolve(path) module = path name = '' if hasattr(view.func, '__module__'): module = resol...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_table_from(data): "Output a nicely formatted ascii table" table = Texttable(max_width=120) table.add_row(["view", "method", "status", "count", "minimum", "maximum", "mean", "stdev", "queries", "querytime"]) table.set_cols_align(["l", "l", "l", "r", "r", "r", "r", "r", "r", "r"]) for i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def analyze_log_file(logfile, pattern, reverse_paths=True, progress=True): "Given a log file and regex group and extract the performance data" if progress: lines = count_lines_in(logfile) pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=lines+1).start() counter = 0 data ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_string(self, limit=None): """ Create a string representation of this collection, showing up to `limit` items. """
header = self.short_string() if len(self) == 0: return header contents = "" element_lines = [ " -- %s" % (element,) for element in self.elements[:limit] ] contents = "\n".join(element_lines) if limit is not None and len(self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_log_error(self, error: Exception, *info: str): """Log error failing silently on error"""
self.__do_safe(lambda: self.logger.error(error, *info))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_log_info(self, *info: str): """Log info failing silently on error"""
self.__do_safe(lambda: self.logger.info(*info))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _default_client(jws_client, reactor, key, alg): """ Make a client if we didn't get one. """
if jws_client is None: pool = HTTPConnectionPool(reactor) agent = Agent(reactor, pool=pool) jws_client = JWSClient(HTTPClient(agent=agent), key, alg) return jws_client
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_supported_challenge(authzr, responders): """ Find a challenge combination that consists of a single challenge that the responder can satisfy. :param ~a...
matches = [ (responder, challbs[0]) for challbs in authzr.body.resolved_combinations for responder in responders if [challb.typ for challb in challbs] == [responder.challenge_type]] if len(matches) == 0: raise NoSupportedChallenges(authzr) else: return matche...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def answer_challenge(authzr, client, responders): """ Complete an authorization using a responder. :param ~acme.messages.AuthorizationResource auth: The authoriz...
responder, challb = _find_supported_challenge(authzr, responders) response = challb.response(client.key) def _stop_responding(): return maybeDeferred( responder.stop_responding, authzr.body.identifier.value, challb.chall, response) return ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll_until_valid(authzr, clock, client, timeout=300.0): """ Poll an authorization until it is in a state other than pending or processing. :param ~acme.messa...
def repoll(result): authzr, retry_after = result if authzr.body.status in {STATUS_PENDING, STATUS_PROCESSING}: return ( deferLater(clock, retry_after, lambda: None) .addCallback(lambda _: client.poll(authzr)) .addCallback(repoll) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_url(cls, reactor, url, key, alg=RS256, jws_client=None): """ Construct a client from an ACME directory at a given URL. :param url: The ``twisted.python....
action = LOG_ACME_CONSUME_DIRECTORY( url=url, key_type=key.typ, alg=alg.name) with action.context(): check_directory_url_type(url) jws_client = _default_client(jws_client, reactor, key, alg) return ( DeferredContext(jws_client.get(url.asTe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, new_reg=None): """ Create a new registration with the ACME server. :param ~acme.messages.NewRegistration new_reg: The registration message to ...
if new_reg is None: new_reg = messages.NewRegistration() action = LOG_ACME_REGISTER(registration=new_reg) with action.context(): return ( DeferredContext( self.update_registration( new_reg, uri=self.directory[ne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _maybe_registered(self, failure, new_reg): """ If the registration already exists, we should just load it. """
failure.trap(ServerError) response = failure.value.response if response.code == http.CONFLICT: reg = new_reg.update( resource=messages.UpdateRegistration.resource_type) uri = self._maybe_location(response) return self.update_registration(reg, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def agree_to_tos(self, regr): """ Accept the terms-of-service for a registration. :param ~acme.messages.RegistrationResource regr: The registration to update. :r...
return self.update_registration( regr.update( body=regr.body.update( agreement=regr.terms_of_service)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_registration(self, regr, uri=None): """ Submit a registration to the server to update it. :param ~acme.messages.RegistrationResource regr: The registr...
if uri is None: uri = regr.uri if isinstance(regr, messages.RegistrationResource): message = messages.UpdateRegistration(**dict(regr.body)) else: message = regr action = LOG_ACME_UPDATE_REGISTRATION(uri=uri, registration=message) with action.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_regr_response(self, response, uri=None, new_authzr_uri=None, terms_of_service=None): """ Parse a registration response from the server. """
links = _parse_header_links(response) if u'terms-of-service' in links: terms_of_service = links[u'terms-of-service'][u'url'] if u'next' in links: new_authzr_uri = links[u'next'][u'url'] if new_authzr_uri is None: raise errors.ClientError('"next" link ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_regr(self, regr, new_reg): """ Check that a registration response contains the registration we were expecting. """
body = getattr(new_reg, 'body', new_reg) for k, v in body.items(): if k == 'resource' or not v: continue if regr.body[k] != v: raise errors.UnexpectedUpdate(regr) if regr.body.key != self.key.public_key(): raise errors.Unexpect...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request_challenges(self, identifier): """ Create a new authorization. :param ~acme.messages.Identifier identifier: The identifier to authorize. :return: The ...
action = LOG_ACME_CREATE_AUTHORIZATION(identifier=identifier) with action.context(): message = messages.NewAuthorization(identifier=identifier) return ( DeferredContext( self._client.post(self.directory[message], message)) .add...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _expect_response(cls, response, code): """ Ensure we got the expected response code. """
if response.code != code: raise errors.ClientError( 'Expected {!r} response but got {!r}'.format( code, response.code)) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_authorization(cls, response, uri=None): """ Parse an authorization resource. """
links = _parse_header_links(response) try: new_cert_uri = links[u'next'][u'url'] except KeyError: raise errors.ClientError('"next" link missing') return ( response.json() .addCallback( lambda body: messages.AuthorizationRes...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_authorization(cls, authzr, identifier): """ Check that the authorization we got is the one we expected. """
if authzr.body.identifier != identifier: raise errors.UnexpectedUpdate(authzr) return authzr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def answer_challenge(self, challenge_body, response): """ Respond to an authorization challenge. :param ~acme.messages.ChallengeBody challenge_body: The challeng...
action = LOG_ACME_ANSWER_CHALLENGE( challenge_body=challenge_body, response=response) with action.context(): return ( DeferredContext( self._client.post(challenge_body.uri, response)) .addCallback(self._parse_challenge) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_challenge(cls, response): """ Parse a challenge resource. """
links = _parse_header_links(response) try: authzr_uri = links['up']['url'] except KeyError: raise errors.ClientError('"up" link missing') return ( response.json() .addCallback( lambda body: messages.ChallengeResource( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_challenge(cls, challenge, challenge_body): """ Check that the challenge resource we got is the one we expected. """
if challenge.uri != challenge_body.uri: raise errors.UnexpectedUpdate(challenge.uri) return challenge
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retry_after(cls, response, default=5, _now=time.time): """ Parse the Retry-After value from a response. """
val = response.headers.getRawHeaders(b'retry-after', [default])[0] try: return int(val) except ValueError: return http.stringToDatetime(val) - _now()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request_issuance(self, csr): """ Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note tha...
action = LOG_ACME_REQUEST_CERTIFICATE() with action.context(): return ( DeferredContext( self._client.post( self.directory[csr], csr, content_type=DER_CONTENT_TYPE, headers=Headers({b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_certificate(cls, response): """ Parse a response containing a certificate resource. """
links = _parse_header_links(response) try: cert_chain_uri = links[u'up'][u'url'] except KeyError: cert_chain_uri = None return ( response.content() .addCallback( lambda body: messages.CertificateResource( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_chain(self, certr, max_length=10): """ Fetch the intermediary chain for a certificate. :param acme.messages.CertificateResource certr: The certificate ...
action = LOG_ACME_FETCH_CHAIN() with action.context(): if certr.cert_chain_uri is None: return succeed([]) elif max_length < 1: raise errors.ClientError('chain too long') return ( DeferredContext( se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_in_jws(self, nonce, obj): """ Wrap ``JSONDeSerializable`` object in JWS. .. todo:: Implement ``acmePath``. :param ~josepy.interfaces.JSONDeSerializable...
with LOG_JWS_SIGN(key_type=self._key.typ, alg=self._alg.name, nonce=nonce): jobj = obj.json_dumps().encode() return ( JWS.sign( payload=jobj, key=self._key, alg=self._alg, nonce=nonce) .json_dumps() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_response(cls, response, content_type=JSON_CONTENT_TYPE): """ Check response content and its type. .. note:: Unlike :mod:`acme.client`, checking is str...
def _got_failure(f): f.trap(ValueError) return None def _got_json(jobj): if 400 <= response.code < 600: if response_ct == JSON_ERROR_CONTENT_TYPE and jobj is not None: raise ServerError( messages.Error.from...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def head(self, url, *args, **kwargs): """ Send HEAD request without checking the response. Note that ``_check_response`` is not called, as there will be no respo...
with LOG_JWS_HEAD().context(): return DeferredContext( self._send_request(u'HEAD', url, *args, **kwargs) ).addActionFinish()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): """ Send GET request and check response. :param str method: The HTTP method to use. :param str url:...
with LOG_JWS_GET().context(): return ( DeferredContext(self._send_request(u'GET', url, **kwargs)) .addCallback(self._check_response, content_type=content_type) .addActionFinish())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_nonce(self, response): """ Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The respon...
nonce = response.headers.getRawHeaders( REPLAY_NONCE_HEADER, [None])[0] with LOG_JWS_ADD_NONCE(raw_nonce=nonce) as action: if nonce is None: raise errors.MissingNonce(response) else: try: decoded_nonce = Header._fie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_nonce(self, url): """ Get a nonce to use in a request, removing it from the nonces on hand. """
action = LOG_JWS_GET_NONCE() if len(self._nonces) > 0: with action: nonce = self._nonces.pop() action.add_success_fields(nonce=nonce) return succeed(nonce) else: with action.context(): return ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post(self, url, obj, content_type, **kwargs): """ POST an object and check the response. :param str url: The URL to request. :param ~josepy.interfaces.JSOND...
with LOG_JWS_POST().context(): headers = kwargs.setdefault('headers', Headers()) headers.setRawHeaders(b'content-type', [JSON_CONTENT_TYPE]) return ( DeferredContext(self._get_nonce(url)) .addCallback(self._wrap_in_jws, obj) .a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): """ POST an object and check the response. Retry once if a badNonce error is received. :param...
def retry_bad_nonce(f): f.trap(ServerError) # The current RFC draft defines the namespace as # urn:ietf:params:acme:error:<code>, but earlier drafts (and some # current implementations) use urn:acme:error:<code> instead. We # don't really care about t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _daemon_thread(*a, **kw): """ Create a `threading.Thread`, but always set ``daemon``. """
thread = Thread(*a, **kw) thread.daemon = True return thread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _defer_to_worker(deliver, worker, work, *args, **kwargs): """ Run a task in a worker, delivering the result as a ``Deferred`` in the reactor thread. """
deferred = Deferred() def wrapped_work(): try: result = work(*args, **kwargs) except BaseException: f = Failure() deliver(lambda: deferred.errback(f)) else: deliver(lambda: deferred.callback(result)) worker.do(wrapped_work) return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_zone(server_name, zone_name): """ Split the zone portion off from a DNS label. :param str server_name: The full DNS label. :param str zone_name: The z...
server_name = server_name.rstrip(u'.') zone_name = zone_name.rstrip(u'.') if not (server_name == zone_name or server_name.endswith(u'.' + zone_name)): raise NotInZone(server_name=server_name, zone_name=zone_name) return server_name[:-len(zone_name)].rstrip(u'.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_existing(driver, zone_name, server_name, validation): """ Get existing validation records. """
if zone_name is None: zones = sorted( (z for z in driver.list_zones() if server_name.rstrip(u'.') .endswith(u'.' + z.domain.rstrip(u'.'))), key=lambda z: len(z.domain), reverse=True) if len(zones) == 0: raise ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validation(response): """ Get the validation value for a challenge response. """
h = hashlib.sha256(response.key_authorization.encode("utf-8")) return b64encode(h.digest()).decode()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_or_create_client_key(pem_path): """ Load the client key from a directory, creating it if it does not exist. .. note:: The client key that will be create...
acme_key_file = pem_path.asTextMode().child(u'client.key') if acme_key_file.exists(): key = serialization.load_pem_private_key( acme_key_file.getContent(), password=None, backend=default_backend()) else: key = generate_private_key(u'rsa') acme_key...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse(reactor, directory, pemdir, *args, **kwargs): """ Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twiste...
def colon_join(items): return ':'.join([item.replace(':', '\\:') for item in items]) sub = colon_join(list(args) + ['='.join(item) for item in kwargs.items()]) pem_path = FilePath(pemdir).asTextMode() acme_key = load_or_create_client_key(pem_path) return AutoTLSEndpoint( reactor=rea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lazyread(f, delimiter): """ Generator which continually reads ``f`` to the next instance of ``delimiter``. This allows you to do batch processing on the cont...
# Get an empty string to start with. We need to make sure that if the # file is opened in binary mode, we're using byte strings, and similar # for Unicode. Otherwise trying to update the running string will # hit a TypeError. try: running = f.read(0) except Exception as e: # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_private_key(key_type): """ Generate a random private key using sensible parameters. :param str key_type: The type of key to generate. One of: ``rsa`...
if key_type == u'rsa': return rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend()) raise ValueError(key_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tap(f): """ "Tap" a Deferred callback chain with a function whose return value is ignored. """
@wraps(f) def _cb(res, *a, **kw): d = maybeDeferred(f, res, *a, **kw) d.addCallback(lambda ignored: res) return d return _cb
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_csr(b64der): """ Decode JOSE Base-64 DER-encoded CSR. :param str b64der: The encoded CSR. :rtype: `cryptography.x509.CertificateSigningRequest` :retur...
try: return x509.load_der_x509_csr( decode_b64jose(b64der), default_backend()) except ValueError as error: raise DeserializationError(error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def csr_for_names(names, key): """ Generate a certificate signing request for the given names and private key. .. seealso:: `acme.client.Client.request_issuance`...
if len(names) == 0: raise ValueError('Must have at least one name') if len(names[0]) > 64: common_name = u'san.too.long.invalid' else: common_name = names[0] return ( x509.CertificateSigningRequestBuilder() .subject_name(x509.Name([ x509.NameAttribute...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_parse(code, filename): """ async wrapper is required to avoid await calls raising a SyntaxError """
code = 'async def wrapper():\n' + indent(code, ' ') return ast.parse(code, filename=filename).body[0].body[0].value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def layers_to_solr(self, layers): """ Sync n layers in Solr. """
layers_dict_list = [] layers_success_ids = [] layers_errors_ids = [] for layer in layers: layer_dict, message = layer2dict(layer) if not layer_dict: layers_errors_ids.append([layer.id, message]) LOGGER.error(message) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def layer_to_solr(self, layer): """ Sync a layer in Solr. """
success = True message = 'Synced layer id %s to Solr' % layer.id layer_dict, message = layer2dict(layer) if not layer_dict: success = False else: layer_json = json.dumps(layer_dict) try: url_solr_update = '%s/solr/hypermap/upd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_solr(self, catalog="hypermap"): """Clear all indexes in the solr core"""
solr_url = "{0}/solr/{1}".format(SEARCH_URL, catalog) solr = pysolr.Solr(solr_url, timeout=60) solr.delete(q='*:*') LOGGER.debug('Solr core cleared')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None, catalog=None): """ Create a service from an endpoint if it does not already e...
from models import Service if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0: # check if endpoint is valid request = requests.get(endpoint) if request.status_code == 200: LOGGER.debug('Creating a %s service for endpoint=%s catalog=%s' % (service_type, end...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def service_url_parse(url): """ Function that parses from url the service and folder of services. """
endpoint = get_sanitized_endpoint(url) url_split_list = url.split(endpoint + '/') if len(url_split_list) != 0: url_split_list = url_split_list[1].split('/') else: raise Exception('Wrong url parsed') # Remove unnecessary items from list of the split url. parsed_url = [s for s in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inverse_mercator(xy): """ Given coordinates in spherical mercator, return a lon,lat tuple. """
lon = (xy[0] / 20037508.34) * 180 lat = (xy[1] / 20037508.34) * 180 lat = 180 / math.pi * \ (2 * math.atan(math.exp(lat * math.pi / 180)) - math.pi / 2) return (lon, lat)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_wms_version_negotiate(url, timeout=10): """ OWSLib wrapper function to perform version negotiation against owslib.wms.WebMapService """
try: LOGGER.debug('Trying a WMS 1.3.0 GetCapabilities request') return WebMapService(url, version='1.3.0', timeout=timeout) except Exception as err: LOGGER.warning('WMS 1.3.0 support not found: %s', err) LOGGER.debug('Trying a WMS 1.1.1 GetCapabilities request instead') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sanitized_endpoint(url): """ Sanitize an endpoint, as removing unneeded parameters """
# sanitize esri sanitized_url = url.rstrip() esri_string = '/rest/services' if esri_string in url: match = re.search(esri_string, sanitized_url) sanitized_url = url[0:(match.start(0)+len(esri_string))] return sanitized_url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_esri_extent(esriobj): """ Get the extent of an ESRI resource """
extent = None srs = None if 'fullExtent' in esriobj._json_struct: extent = esriobj._json_struct['fullExtent'] if 'extent' in esriobj._json_struct: extent = esriobj._json_struct['extent'] try: srs = extent['spatialReference']['wkid'] except KeyError, err: LOGGE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bbox2wktpolygon(bbox): """ Return OGC WKT Polygon of a simple bbox list of strings """
minx = float(bbox[0]) miny = float(bbox[1]) maxx = float(bbox[2]) maxy = float(bbox[3]) return 'POLYGON((%.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f))' \ % (minx, miny, minx, maxy, maxx, maxy, maxx, miny, minx, miny)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_solr_date(pydate, is_negative): """ Returns a date in a valid Solr format from a string. """
# check if date is valid and then set it to solr format YYYY-MM-DDThh:mm:ssZ try: if isinstance(pydate, datetime.datetime): solr_date = '%sZ' % pydate.isoformat()[0:19] if is_negative: LOGGER.debug('%s This layer has a negative date' % solr_date) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_date(layer): """ Returns a custom date representation. A date can be detected or from metadata. It can be a range or a simple date in isoformat. """
date = None sign = '+' date_type = 1 layer_dates = layer.get_layer_dates() # we index the first date! if layer_dates: sign = layer_dates[0][0] date = layer_dates[0][1] date_type = layer_dates[0][2] if date is None: date = layer.created # layer date > 2300...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_metadata_url_scheme(url): """detect whether a url is a Service type that HHypermap supports"""
scheme = None url_lower = url.lower() if any(x in url_lower for x in ['wms', 'service=wms']): scheme = 'OGC:WMS' if any(x in url_lower for x in ['wmts', 'service=wmts']): scheme = 'OGC:WMTS' elif all(x in url for x in ['/MapServer', 'f=json']): scheme = 'ESRI:ArcGIS:MapSer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_checks(check_set): """ Serialize a check_set for raphael """
check_set_list = [] for check in check_set.all()[:25]: check_set_list.append( { 'datetime': check.checked_datetime.isoformat(), 'value': check.response_time, 'success': 1 if check.success else 0 } ) return check_set_lis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def domains(request): """ A page with number of services and layers faceted on domains. """
url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings.SEARCH_TYPE == 'elasticsearch': url = '%s/select?q=%s' % (settings.SEARCH_URL, query) if settings.SEARCH_TYPE == 'solr': url = '%s/solr/hypermap/select?q=%s' % (set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tasks_runner(request): """ A page that let the admin to run global tasks. """
# server info cached_layers_number = 0 cached_layers = cache.get('layers') if cached_layers: cached_layers_number = len(cached_layers) cached_deleted_layers_number = 0 cached_deleted_layers = cache.get('deleted_layers') if cached_deleted_layers: cached_deleted_layers_numbe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def layer_mapproxy(request, catalog_slug, layer_uuid, path_info): """ Get Layer with matching catalog and uuid """
layer = get_object_or_404(Layer, uuid=layer_uuid, catalog__slug=catalog_slug) # for WorldMap layers we need to use the url of the layer if layer.service.type == 'Hypermap:WorldMap': layer.service.url = layer.url # Set up a mapproxy a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_datetime(date_str): """ Parses a date string to date object. for BCE dates, only supports the year part. """
is_common_era = True date_str_parts = date_str.split("-") if date_str_parts and date_str_parts[0] == '': is_common_era = False # for now, only support BCE years # assume the datetime comes complete, but # when it comes only the year, add the missing datetime info: i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_ids(self, ids): """ Query by list of identifiers """
results = self._get_repo_filter(Layer.objects).filter(uuid__in=ids).all() if len(results) == 0: # try services results = self._get_repo_filter(Service.objects).filter(uuid__in=ids).all() return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_domain(self, domain, typenames, domainquerytype='list', count=False): """ Query by property domain values """
objects = self._get_repo_filter(Layer.objects) if domainquerytype == 'range': return [tuple(objects.aggregate(Min(domain), Max(domain)).values())] else: if count: return [(d[domain], d['%s__count' % domain]) for d in objects.valu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_source(self, source): """ Query by source """
return self._get_repo_filter(Layer.objects).filter(url=source)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query(self, constraint, sortby=None, typenames=None, maxrecords=10, startposition=0): """ Query records from underlying repository """
# run the raw query and get total # we want to exclude layers which are not valid, as it is done in the search engine if 'where' in constraint: # GetRecords with constraint query = self._get_repo_filter(Layer.objects).filter( is_valid=True).extra(where=[constraint[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, resourcetype, source, insert_date=None): """ Insert a record into the repository """
caller = inspect.stack()[1][3] if caller == 'transaction': # insert of Layer hhclass = 'Layer' source = resourcetype resourcetype = resourcetype.csw_schema else: # insert of service hhclass = 'Service' if resourcetype not in HYPERM...