text stringlengths 18 773k |
|---|
def _get_indicators_for_report_page_generator(self, report_id, start_page=0, page_size=None):
"""
Creates a generator from the |get_indicators_for_report_page| method that returns each successive page.
:param str report_id: The ID of the report to get indicators for.
:param int start_pa... |
def _get_related_indicators_page_generator(self, indicators=None, enclave_ids=None, start_page=0, page_size=None):
"""
Creates a generator from the |get_related_indicators_page| method that returns each
successive page.
:param indicators: list of indicator values to search for
:... |
def _get_whitelist_page_generator(self, start_page=0, page_size=None):
"""
Creates a generator from the |get_whitelist_page| method that returns each successive page.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator... |
def points(self, size=1.0, highlight=None, colorlist=None, opacity=1.0):
"""Display the system as points.
:param float size: the size of the points.
"""
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
if highlight is not N... |
def labels(self, text=None, coordinates=None, colorlist=None, sizes=None, fonts=None, opacity=1.0):
'''Display atomic labels for the system'''
if coordinates is None:
coordinates=self.coordinates
l=len(coordinates)
if text is None:
if len(self.topology.get('atom_t... |
def remove_labels(self):
'''Remove all atomic labels from the system'''
for rep_id in self.representations.keys():
if self.representations[rep_id]['rep_type']=='text' and rep_id not in self._axes_reps:
self.remove_representation(rep_id) |
def toggle_axes(self, parameters = None):
'''Toggle axes [x,y,z] on and off for the current representation
Parameters: dictionary of parameters to control axes:
position/p: origin of axes
length/l: length of axis
offset/o: offset to place axis labels
... |
def lines(self):
'''Display the system bonds as lines.
'''
if "bonds" not in self.topology:
return
bond_start, bond_end = zip(*self.topology['bonds'])
bond_start = np.array(bond_start)
bond_end = np.array(bond_end)
color_array = np.array([get_atom_c... |
def wireframe(self, pointsize=0.2, opacity=1.0):
'''Display atoms as points of size *pointsize* and bonds as lines.'''
self.points(pointsize, opacity=opacity)
self.lines() |
def ball_and_sticks(self, ball_radius=0.05, stick_radius=0.02, colorlist=None, opacity=1.0):
"""Display the system using a ball and stick representation.
"""
# Add the spheres
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
... |
def line_ribbon(self):
'''Display the protein secondary structure as a white lines that passes through the
backbone chain.
'''
# Control points are the CA (C alphas)
backbone = np.array(self.topology['atom_names']) == 'CA'
smoothline = self.add_representation('smoothl... |
def cylinder_and_strand(self):
'''Display the protein secondary structure as a white,
solid tube and the alpha-helices as yellow cylinders.
'''
top = self.topology
# We build a mini-state machine to find the
# start end of helices and such
in_helix = False
... |
def cartoon(self, cmap=None):
'''Display a protein secondary structure as a pymol-like cartoon representation.
:param cmap: is a dictionary that maps the secondary type
(H=helix, E=sheet, C=coil) to a hexadecimal color (0xffffff for white)
'''
# Parse secondary struc... |
def add_isosurface(self, function, isolevel=0.3, resolution=32, style="wireframe", color=0xffffff):
'''Add an isosurface to the current scene.
:param callable function: A function that takes x, y, z coordinates as input and is broadcastable using numpy. Typically simple
... |
def add_isosurface_grid_data(self, data, origin, extent, resolution,
isolevel=0.3, scale=10,
style="wireframe", color=0xffffff):
"""
Add an isosurface to current scence using pre-computed data on a grid
"""
spacing = np.ar... |
def _refresh_token(self):
"""
Retrieves the OAuth2 token generated by the user's API key and API secret.
Sets the instance property 'token' to this new token.
If the current token is still live, the server will simply return that.
"""
# use basic auth with API key and se... |
def _get_headers(self, is_json=False):
"""
Create headers dictionary for a request.
:param boolean is_json: Whether the request body is a json.
:return: The headers dictionary.
"""
headers = {"Authorization": "Bearer " + self._get_token()}
if self.client_type i... |
def _is_expired_token_response(cls, response):
"""
Determine whether the given response indicates that the token is expired.
:param response: The response object.
:return: True if the response indicates that the token is expired.
"""
EXPIRED_MESSAGE = "Expired oauth2 ac... |
def request(self, method, path, headers=None, params=None, data=None, **kwargs):
"""
A wrapper around ``requests.request`` that handles boilerplate code specific to TruStar's API.
:param str method: The method of the request (``GET``, ``PUT``, ``POST``, or ``DELETE``)
:param str path: T... |
def isosurface_from_data(data, isolevel, origin, spacing):
"""Small wrapper to get directly vertices and faces to feed into programs
"""
spacing = np.array(extent/resolution)
if isolevel >= 0:
triangles = marching_cubes(data, isolevel)
else: # Wrong traingle unwinding roder -- god only knows... |
def _get_gtf_column(column_name, gtf_path, df):
"""
Helper function which returns a dictionary column or raises an ValueError
abou the absence of that column in a GTF file.
"""
if column_name in df.columns:
return list(df[column_name])
else:
raise ValueError(
"Missin... |
def load_transcript_fpkm_dict_from_gtf(
gtf_path,
transcript_id_column_name="reference_id",
fpkm_column_name="FPKM",
feature_column_name="feature"):
"""
Load a GTF file generated by StringTie which contains transcript-level
quantification of abundance. Returns a dictionary ma... |
def predict_from_named_sequences(
self, name_to_sequence_dict):
"""
Parameters
----------
name_to_sequence_dict : (str->str) dict
Dictionary mapping sequence names to amino acid sequences
Returns pandas.DataFrame with the following columns:
- ... |
def predict_from_sequences(self, sequences):
"""
Predict MHC ligands for sub-sequences of each input sequence.
Parameters
----------
sequences : list of str
Multiple amino acid sequences (without any names or IDs)
Returns DataFrame with the following fields:... |
def predict_from_mutation_effects(
self,
effects,
transcript_expression_dict=None,
gene_expression_dict=None):
"""Given a Varcode.EffectCollection of predicted protein effects,
return predicted epitopes around each mutation.
Parameters
---... |
def predict_from_variants(
self,
variants,
transcript_expression_dict=None,
gene_expression_dict=None):
"""
Predict epitopes from a Variant collection, filtering options, and
optional gene and transcript expression data.
Parameters
... |
def main(args_list=None):
"""
Script entry-point to predict neo-epitopes from genomic variants using
Topiary.
"""
args = parse_args(args_list)
print("Topiary commandline arguments:")
print(args)
df = predict_epitopes_from_args(args)
write_outputs(df, args)
print("Total count: %d"... |
def render_povray(scene, filename='ipython', width=600, height=600,
antialiasing=0.01, extra_opts={}):
'''Render the scene with povray for publication.
:param dict scene: The scene to render
:param string filename: Output filename or 'ipython' to render in the notebook.
:param int wid... |
def rmatrixquaternion(q):
"""Create a rotation matrix from q quaternion rotation.
Quaternions are typed as Numeric Python numpy.arrays of length 4.
"""
assert np.allclose(math.sqrt(np.dot(q,q)), 1.0)
x, y, z, w = q
xx = x*x
xy = x*y
xz = x*z
xw = x*w
yy = y*y
yz = y*z
y... |
def rna_transcript_expression_dict_from_args(args):
"""
Returns a dictionary mapping Ensembl transcript IDs to FPKM expression
values or None if neither Cufflinks tracking file nor StringTie GTF file
were specified.
"""
if args.rna_transcript_fpkm_tracking_file:
return load_cufflinks_fpk... |
def get_total_pages(self):
"""
:return: The total number of pages on the server.
"""
if self.total_elements is None or self.page_size is None:
return None
return math.ceil(float(self.total_elements) / float(self.page_size)) |
def has_more_pages(self):
"""
:return: ``True`` if there are more pages available on the server.
"""
# if has_next property exists, it represents whether more pages exist
if self.has_next is not None:
return self.has_next
# otherwise, try to compute whether ... |
def from_dict(page, content_type=None):
"""
Create a |Page| object from a dictionary. This method is intended for internal use, to construct a
|Page| object from the body of a response json from a paginated endpoint.
:param page: The dictionary.
:param content_type: The class t... |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the page.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the page.
"""
items = []
... |
def get_page_generator(func, start_page=0, page_size=None):
"""
Constructs a generator for retrieving pages from a paginated endpoint. This method is intended for internal
use.
:param func: Should take parameters ``page_number`` and ``page_size`` and return the corresponding |Page| obj... |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the object.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: The dictionary representation.
"""
if remove_nones:
... |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the object.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the report.
"""
if remove... |
def from_dict(cls, report):
"""
Create a report object from a dictionary. This method is intended for internal use, to construct a
:class:`Report` object from the body of a response json. It expects the keys of the dictionary to match those
of the json that would be found in a response... |
def serialize_to_dict(dictionary):
'''Make a json-serializable dictionary from input dictionary by converting
non-serializable data types such as numpy arrays.'''
retval = {}
for k, v in dictionary.items():
if isinstance(v, dict):
retval[k] = serialize_to_dict(v)
else:
... |
def make_graph(pkg):
"""Returns a dictionary of information about pkg & its recursive deps.
Given a string, which can be parsed as a requirement specifier, return a
dictionary where each key is the name of pkg or one of its recursive
dependencies, and each value is a dictionary returned by research_pac... |
def get_report_details(self, report_id, id_type=None):
"""
Retrieves a report by its ID. Internal and external IDs are both allowed.
:param str report_id: The ID of the incident report.
:param str id_type: Indicates whether ID is internal or external.
:return: The retrieved |R... |
def get_reports_page(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None,
from_time=None, to_time=None):
"""
Retrieves a page of reports, filtering by time window, distribution type, enclave association, and tag.
The results are sorted by updated time.
... |
def submit_report(self, report):
"""
Submits a report.
* If ``report.is_enclave`` is ``True``, then the report will be submitted to the enclaves
identified by ``report.enclaves``; if that field is ``None``, then the enclave IDs registered with this
|TruStar| object will be u... |
def update_report(self, report):
"""
Updates the report identified by the ``report.id`` field; if this field does not exist, then
``report.external_id`` will be used if it exists. Any other fields on ``report`` that are not ``None``
will overwrite values on the report in TruSTAR's syste... |
def delete_report(self, report_id, id_type=None):
"""
Deletes the report with the given ID.
:param report_id: the ID of the report to delete
:param id_type: indicates whether the ID is internal or an external ID provided by the user
:return: the response object
Example:... |
def get_correlated_report_ids(self, indicators):
"""
DEPRECATED!
Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:return: The list of IDs of reports that co... |
def get_correlated_reports_page(self, indicators, enclave_ids=None, is_enclave=True,
page_size=None, page_number=None):
"""
Retrieves a page of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve... |
def search_reports_page(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None,
page_size=None,
... |
def _get_reports_page_generator(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None,
from_time=None, to_time=None):
"""
Creates a generator from the |get_reports_page| method that returns each successive page.
:param boolean is_enclave: rest... |
def get_reports(self, is_enclave=None, enclave_ids=None, tag=None, excluded_tags=None, from_time=None, to_time=None):
"""
Uses the |get_reports_page| method to create a generator that returns each successive report as a trustar
report object.
:param boolean is_enclave: restrict reports ... |
def _get_correlated_reports_page_generator(self, indicators, enclave_ids=None, is_enclave=True,
start_page=0, page_size=None):
"""
Creates a generator from the |get_correlated_reports_page| method that returns each
successive page.
:param i... |
def get_correlated_reports(self, indicators, enclave_ids=None, is_enclave=True):
"""
Uses the |get_correlated_reports_page| method to create a generator that returns each successive report.
:param indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_... |
def _search_reports_page_generator(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
exclude... |
def search_reports(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None):
"""
Uses the |search_reports_page| method to create a generator th... |
def normalize_timestamp(date_time):
"""
TODO: get rid of this function and all references to it / uses of it.
Attempt to convert a string timestamp in to a TruSTAR compatible format for submission.
Will return current time with UTC time zone if None
:param date_time: int that is seconds or milliseco... |
def parse_boolean(value):
"""
Coerce a value to boolean.
:param value: the value, could be a string, boolean, or None
:return: the value as coerced to a boolean
"""
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, string_type... |
def config_from_file(config_file_path, config_role):
"""
Create a configuration dictionary from a config file section. This dictionary is what the TruStar
class constructor ultimately requires.
:param config_file_path: The path to the config file.
:param config_role: The sectio... |
def get_version(self):
"""
Get the version number of the API.
Example:
>>> ts.get_version()
1.3
"""
result = self._client.get("version").content
if isinstance(result, bytes):
result = result.decode('utf-8')
return result.strip('\n'... |
def get_user_enclaves(self):
"""
Gets the list of enclaves that the user has access to.
:return: A list of |EnclavePermissions| objects, each representing an enclave and whether the requesting user
has read, create, and update access to it.
"""
resp = self._client.g... |
def get_request_quotas(self):
"""
Gets the request quotas for the user's company.
:return: A list of |RequestQuota| objects.
"""
resp = self._client.get("request-quotas")
return [RequestQuota.from_dict(quota) for quota in resp.json()] |
def configure_logging():
"""
Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored.
"""
if not parse_boolean(os.environ.get('DISABLE_TRUSTAR_LOGGING')):
# configure
dictConfig(DEFAULT_LOGGING_CONFIG)
... |
def from_dict(cls, enclave):
"""
Create a enclave object from a dictionary.
:param enclave: The dictionary.
:return: The enclave object.
"""
return Enclave(id=enclave.get('id'),
name=enclave.get('name'),
type=EnclaveType.fro... |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the enclave.
"""
if remo... |
def from_dict(cls, d):
"""
Create a enclave object from a dictionary.
:param d: The dictionary.
:return: The EnclavePermissions object.
"""
enclave = super(cls, EnclavePermissions).from_dict(d)
enclave_permissions = cls.from_enclave(enclave)
enclave_per... |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the enclave.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the EnclavePermissions object.
""... |
def from_enclave(cls, enclave):
"""
Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object
"""
return EnclavePermissions(id=enclave.id,
name=enclave.name,... |
def get_enclave_tags(self, report_id, id_type=None):
"""
Retrieves all enclave tags present in a specific report.
:param report_id: the ID of the report
:param id_type: indicates whether the ID internal or an external ID provided by the user
:return: A list of |Tag| objects.
... |
def add_enclave_tag(self, report_id, name, enclave_id, id_type=None):
"""
Adds a tag to a specific report, for a specific enclave.
:param report_id: The ID of the report
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will be added... |
def delete_enclave_tag(self, report_id, tag_id, id_type=None):
"""
Deletes a tag from a specific report, in a specific enclave.
:param string report_id: The ID of the report
:param string tag_id: ID of the tag to delete
:param string id_type: indicates whether the ID internal or... |
def get_all_enclave_tags(self, enclave_ids=None):
"""
Retrieves all tags present in the given enclaves. If the enclave list is empty, the tags returned include all
tags for all enclaves the user has access to.
:param (string) list enclave_ids: list of enclave IDs
:return: The li... |
def add_indicator_tag(self, indicator_value, name, enclave_id):
"""
Adds a tag to a specific indicator, for a specific enclave.
:param indicator_value: The value of the indicator
:param name: The name of the tag to be added
:param enclave_id: ID of the enclave where the tag will... |
def delete_indicator_tag(self, indicator_value, tag_id):
"""
Deletes a tag from a specific indicator, in a specific enclave.
:param indicator_value: The value of the indicator to delete the tag from
:param tag_id: ID of the tag to delete
"""
params = {
'valu... |
def from_dict(cls, tag):
"""
Create a tag object from a dictionary. This method is intended for internal use, to construct a
:class:`Tag` object from the body of a response json. It expects the keys of the dictionary to match those
of the json that would be found in a response to an AP... |
def to_dict(self, remove_nones=False):
"""
Creates a dictionary representation of the tag.
:param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``.
:return: A dictionary representation of the tag.
"""
if remove_nones... |
def infer_delimiter(filename, comment_char="#", n_lines=3):
"""
Given a file which contains data separated by one of the following:
- commas
- tabs
- spaces
Return the most likely separator by sniffing the first few lines
of the file's contents.
"""
lines = []
with op... |
def check_required_columns(df, filename, required_columns):
"""
Ensure that all required columns are present in the given dataframe,
otherwise raise an exception.
"""
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
... |
def topology_mdtraj(traj):
'''Generate topology spec for the MolecularViewer from mdtraj.
:param mdtraj.Trajectory traj: the trajectory
:return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj.
'''
import mdtraj as md
top = {}
top['atom_types'] = [a.elemen... |
def encode_numpy(array):
'''Encode a numpy array as a base64 encoded string, to be JSON serialized.
:return: a dictionary containing the fields:
- *data*: the base64 string
- *type*: the array type
- *shape*: the array shape
'''
return {'data' : base64.... |
def load_cufflinks_dataframe(
filename,
id_column=ID_COLUMN,
fpkm_column=FPKM_COLUMN,
status_column=STATUS_COLUMN,
locus_column=LOCUS_COLUMN,
gene_names_column=GENE_NAMES_COLUMN,
drop_failed=True,
drop_lowdata=False,
drop_hidata=True,
repla... |
def load_cufflinks_dict(*args, **kwargs):
"""
Returns dictionary mapping feature identifier (either transcript or gene ID)
to a DataFrame row with fields:
id : str
novel : bool
fpkm : float
chr : str
start : int
end : int
gene_names : str list
"""
... |
def load_cufflinks_fpkm_dict(*args, **kwargs):
"""
Returns dictionary mapping feature identifier (either transcript or gene ID)
to FPKM expression value.
"""
return {
row.id: row.fpkm
for (_, row)
in load_cufflinks_dataframe(*args, **kwargs).iterrows()
} |
def enable_notebook(verbose=0):
"""Enable IPython notebook widgets to be displayed.
This function should be called before using the chemview widgets.
"""
libs = ['objexporter.js',
'ArcballControls.js', 'filesaver.js',
'base64-arraybuffer.js', 'context.js',
'chemview.... |
def extract_pdf(file_name):
"""
Extract text from a pdf file
:param file_name path to pdf to read
:return text from pdf
"""
rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()
sio = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, sio, codec='utf-8', laparams=laparams)... |
def process_file(source_file):
"""
Extract text from a file (pdf, txt, eml, csv, json)
:param source_file path to file to read
:return text from file
"""
if source_file.endswith(('.pdf', '.PDF')):
txt = extract_pdf(source_file)
elif source_file.endswith(('.txt', '.eml', '.csv', '.jso... |
def from_string(cls, string):
"""
Simply logs a warning if the desired enum value is not found.
:param string:
:return:
"""
# find enum value
for attr in dir(cls):
value = getattr(cls, attr)
if value == string:
return valu... |
def validate(self, value):
"""
Validate (and possibly typecast) the given parameter value value.
:param value: Parameter value
:return: Typecast parameter value
:raises ValidationErrors: if there were validation errors
"""
errors = []
value = self._valida... |
def format_cli(self, value):
"""
Build a single parameter argument.
:return: list of CLI strings -- not escaped. If the parameter should not be expressed, returns None.
:rtype: list[str]|None
"""
if value is None or (self.type == 'flag' and not value):
return... |
def listify(value):
"""
Wrap the given value into a list, with the below provisions:
* If the value is a list or a tuple, it's coerced into a new list.
* If the value is None, an empty list is returned.
* Otherwise, a single-element list is returned, containing the value.
:param value: A value... |
def build_command(command, parameter_map):
"""
Build command line(s) using the given parameter map.
Even if the passed a single `command`, this function will return a list
of shell commands. It is the caller's responsibility to concatenate them,
likely using the semicolon or double ampersands.
... |
def validate(yaml, raise_exc=True):
"""
Validate the given YAML document and return a list of errors.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param raise_exc: Whether to raise a meta-exception containing all discovered error... |
def build_parameters(self):
"""
Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str]
"""
param_bits = []
for name in self.parameters:
param_bits.extend(self.build_parameter_by_name(name) ... |
def parse(cls, data):
"""
Parse a Config structure out of a Python dict (that's likely deserialized from YAML).
:param data: Config-y dict
:type data: dict
:return: Config object
:rtype: valohai_yaml.objs.Config
"""
parsers = {
'step': ([], St... |
def get_step_by(self, **kwargs):
"""
Get the first step that matches all the passed named arguments.
Has special argument index not present in the real step.
Usage:
config.get_step_by(name='not found')
config.get_step_by(index=0)
config.get_step_by(n... |
def parse(yaml, validate=True):
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to ... |
def get_parameter_defaults(self, include_flags=True):
"""
Get a dict mapping parameter names to their defaults (if set).
:rtype: dict[str, object]
"""
return {
name: parameter.default
for (name, parameter)
in self.parameters.items()
... |
def build_command(self, parameter_values, command=None):
"""
Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibil... |
def lint_file(file_path):
"""
Validate & lint `file_path` and return a LintResult.
:param file_path: YAML filename
:type file_path: str
:return: LintResult object
"""
with open(file_path, 'r') as yaml:
try:
return lint(yaml)
except Exception as e:
lr... |
def update(self):
"""Actual update process goes here using auxialary ``get_currencies``
and ``get_exchangerates`` methods. This method creates or updates
corresponding ``Currency`` and ``ExchangeRate`` models
"""
currencies = self.get_currencies()
currency_objects = {}
... |
def _re_flatten(p):
''' Turn all capturing groups in a regular expression pattern into
non-capturing groups. '''
if '(' not in p: return p
return re.sub(r'(\\*)(\(\?P<[^>]+>|\((?!\?))',
lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p) |
def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if not code:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
res = response.copy(cls=HTTPResponse)
res.status = code
res.body = ""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.