code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Add the spheres
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
sizes = [ball_radius] * len(self.topology['atom_types'])
spheres = self.add_representation('spheres', {'coordinates': self.coordinates.astype('float32'),
... | 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. | 2.490456 | 2.523668 | 0.98684 |
'''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('smoothline', {'coordinates': s... | def line_ribbon(self) | Display the protein secondary structure as a white lines that passes through the
backbone chain. | 9.991117 | 6.254487 | 1.597432 |
'''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
helices_starts = []
... | def cylinder_and_strand(self) | Display the protein secondary structure as a white,
solid tube and the alpha-helices as yellow cylinders. | 3.309683 | 2.93463 | 1.127802 |
'''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 structure
top = self.topolo... | 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) | 8.363423 | 5.042269 | 1.658663 |
'''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
functions that involve standard arithmetic operations and functions
... | 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
functions that involve standard arithmetic operations and functions
such as... | 3.97909 | 2.199551 | 1.809047 |
spacing = np.array(extent/resolution)/scale
if isolevel >= 0:
triangles = marching_cubes(data, isolevel)
else:
triangles = marching_cubes(-data, -isolevel)
faces = []
verts = []
for i, t in enumerate(triangles):
faces.append([i... | 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 | 3.150219 | 3.272181 | 0.962728 |
# use basic auth with API key and secret
client_auth = requests.auth.HTTPBasicAuth(self.api_key, self.api_secret)
# make request
post_data = {"grant_type": "client_credentials"}
response = requests.post(self.auth, auth=client_auth, data=post_data, proxies=self.proxies)... | 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. | 3.310399 | 3.057885 | 1.082578 |
headers = {"Authorization": "Bearer " + self._get_token()}
if self.client_type is not None:
headers["Client-Type"] = self.client_type
if self.client_version is not None:
headers["Client-Version"] = self.client_version
if self.client_metatag is not Non... | 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. | 2.099992 | 2.216995 | 0.947224 |
EXPIRED_MESSAGE = "Expired oauth2 access token"
INVALID_MESSAGE = "Invalid oauth2 access token"
if response.status_code == 400:
try:
body = response.json()
if str(body.get('error_description')) in [EXPIRED_MESSAGE, INVALID_MESSAGE]:
... | 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. | 2.96333 | 3.019466 | 0.981409 |
retry = self.retry
attempted = False
while not attempted or retry:
# get headers and merge with headers from method parameter if it exists
base_headers = self._get_headers(is_json=method in ["POST", "PUT"])
if headers is not None:
ba... | 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: The path of the request, i.e. the piece of the URL after the base URL
:param dict headers: A d... | 3.078809 | 3.044809 | 1.011167 |
spacing = np.array(extent/resolution)
if isolevel >= 0:
triangles = marching_cubes(data, isolevel)
else: # Wrong traingle unwinding roder -- god only knows why
triangles = marching_cubes(-data, -isolevel)
faces = []
verts = []
for i, t in enumerate(triangles):
faces.a... | def isosurface_from_data(data, isolevel, origin, spacing) | Small wrapper to get directly vertices and faces to feed into programs | 4.931453 | 4.77726 | 1.032276 |
if column_name in df.columns:
return list(df[column_name])
else:
raise ValueError(
"Missing '%s' in columns of %s, available: %s" % (
column_name,
gtf_path,
list(df.columns))) | 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. | 3.197585 | 3.063183 | 1.043876 |
df = gtfparse.read_gtf(
gtf_path,
column_converters={fpkm_column_name: float})
transcript_ids = _get_gtf_column(transcript_id_column_name, gtf_path, df)
fpkm_values = _get_gtf_column(fpkm_column_name, gtf_path, df)
features = _get_gtf_column(feature_column_name, gtf_path, df)
lo... | 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 mapping Ensembl
IDs of transcripts to FPKM values. | 2.198694 | 2.273652 | 0.967032 |
df = self.mhc_model.predict_subsequences_dataframe(name_to_sequence_dict)
return df.rename(
columns={
"length": "peptide_length",
"offset": "peptide_offset"}) | 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:
- source_sequence_name
- peptide
- peptide_offset
- peptide_le... | 5.527843 | 4.692901 | 1.177916 |
# make each sequence its own unique ID
sequence_dict = {
seq: seq
for seq in sequences
}
df = self.predict_from_named_sequences(sequence_dict)
return df.rename(columns={"source_sequence_name": "source_sequence"}) | 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:
- source_sequence
- peptide
... | 6.382766 | 5.641851 | 1.131325 |
# pre-filter variants by checking if any of the genes or
# transcripts they overlap have sufficient expression.
# I'm tolerating the redundancy of this code since it's much cheaper
# to filter a variant *before* trying to predict its impact/effect
# on the protein sequen... | 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
----------
variants : varcode.VariantCollection
transcript_expression_dict : dict
Maps from Ensembl transcript IDs to FPKM expression values.
... | 4.23618 | 4.336137 | 0.976948 |
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" % len(df)) | def main(args_list=None) | Script entry-point to predict neo-epitopes from genomic variants using
Topiary. | 6.486223 | 4.208237 | 1.541316 |
'''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 width: Width in pixels.
:param int height: Height in pixels.
:param dict extra_opts: Dictionary to merge/override wi... | 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 width: Width in pixels.
:param int height: Height in pixels.
:param dict extra_opts: Dictionary to merge/override with the ... | 4.003008 | 3.571562 | 1.1208 |
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
yw = y*w
zz = z*z
zw = z*w
r00 = 1.0 - 2.0 * (yy + zz)
r01 = 2.0 * (xy - zw)
r02 = 2.0 * (xz + yw)
r10 = 2.0 * (xy +... | def rmatrixquaternion(q) | Create a rotation matrix from q quaternion rotation.
Quaternions are typed as Numeric Python numpy.arrays of length 4. | 1.349443 | 1.384518 | 0.974666 |
if args.rna_transcript_fpkm_tracking_file:
return load_cufflinks_fpkm_dict(args.rna_transcript_fpkm_tracking_file)
elif args.rna_transcript_fpkm_gtf_file:
return load_transcript_fpkm_dict_from_gtf(
args.rna_transcript_fpkm_gtf_file)
else:
return None | 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. | 2.302573 | 1.989935 | 1.15711 |
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 get_total_pages(self) | :return: The total number of pages on the server. | 3.009226 | 2.763778 | 1.088809 |
# 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 or not more pages exist
total_pages = self.get_total_pages()
if self.page_number is None or total_pa... | def has_more_pages(self) | :return: ``True`` if there are more pages available on the server. | 4.025838 | 3.735597 | 1.077696 |
result = Page(items=page.get('items'),
page_number=page.get('pageNumber'),
page_size=page.get('pageSize'),
total_elements=page.get('totalElements'),
has_next=page.get('hasNext'))
if content_type is not Non... | 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 that the contents should be deserialized into.
:retur... | 2.412876 | 2.441428 | 0.988305 |
items = []
# attempt to replace each item with its dictionary representation if possible
for item in self.items:
if hasattr(item, 'to_dict'):
items.append(item.to_dict(remove_nones=remove_nones))
else:
items.append(item)
... | 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. | 2.605922 | 2.604956 | 1.000371 |
# initialize starting values
page_number = start_page
more_pages = True
# continuously request the next page as long as more pages exist
while more_pages:
# get next page
page = func(page_number=page_number, page_size=page_size)
yi... | 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| object.
:param start_page: The page to start on.
:param page_size: ... | 3.164191 | 3.2474 | 0.974377 |
if remove_nones:
return {k: v for k, v in self.to_dict().items() if v is not None}
else:
raise NotImplementedError() | 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. | 2.613691 | 2.858493 | 0.91436 |
if remove_nones:
report_dict = super().to_dict(remove_nones=True)
else:
report_dict = {
'title': self.title,
'reportBody': self.body,
'timeBegan': self.time_began,
'externalUrl': self.external_url,
... | 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. | 3.126082 | 3.119052 | 1.002254 |
# determine distribution type
distribution_type = report.get('distributionType')
if distribution_type is not None:
is_enclave = distribution_type.upper() != DistributionType.COMMUNITY
else:
is_enclave = None
return Report(id=report.get('id'),
... | 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 to an API call such as ``GET /report/{id}``.
... | 3.039696 | 3.08057 | 0.986732 |
'''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:
# This is when custom se... | def serialize_to_dict(dictionary) | Make a json-serializable dictionary from input dictionary by converting
non-serializable data types such as numpy arrays. | 4.292911 | 3.01629 | 1.423242 |
ignore = ['argparse', 'pip', 'setuptools', 'wsgiref']
pkg_deps = recursive_dependencies(pkg_resources.Requirement.parse(pkg))
dependencies = {key: {} for key in pkg_deps if key not in ignore}
installed_packages = pkg_resources.working_set
versions = {package.key: package.version for package in... | 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_package.
(No, it's not real... | 3.522463 | 3.506605 | 1.004522 |
params = {'idType': id_type}
resp = self._client.get("reports/%s" % report_id, params=params)
return Report.from_dict(resp.json()) | 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 |Report| object.
Example:
>>> report = ts.get_report_detail... | 3.607204 | 4.417632 | 0.816547 |
distribution_type = None
# explicitly compare to True and False to distinguish from None (which is treated as False in a conditional)
if is_enclave:
distribution_type = DistributionType.ENCLAVE
elif not is_enclave:
distribution_type = DistributionType.C... | 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.
This method does not take ``page_number`` and ``page_size`` parameters. Instead, each successive page must be
found by adjusting the ``from_time`` and ... | 3.327139 | 3.283209 | 1.01338 |
# make distribution type default to "enclave"
if report.is_enclave is None:
report.is_enclave = True
if report.enclave_ids is None:
# use configured enclave_ids by default if distribution type is ENCLAVE
if report.is_enclave:
report.... | 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 used.
* If ``report.time_began`` is ``None``, ... | 3.455041 | 3.147885 | 1.097575 |
# default to interal ID type if ID field is present
if report.id is not None:
id_type = IdType.INTERNAL
report_id = report.id
# if no ID field is present, but external ID field is, default to external ID type
elif report.external_id is not None:
... | 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 system. Any fields that are ``None`` will simply be ign... | 3.468542 | 3.459448 | 1.002629 |
params = {'idType': id_type}
self._client.delete("reports/%s" % report_id, params=params) | 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:
>>> response = ts.delete_report("4d1fcaee-5009-4620-b239-2b2... | 4.790965 | 6.477366 | 0.739647 |
params = {'indicators': indicators}
resp = self._client.get("reports/correlate", params=params)
return resp.json() | 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 correlated.
Example:
>>> report_ids = ts.get_correlat... | 4.937021 | 6.874696 | 0.718144 |
if is_enclave:
distribution_type = DistributionType.ENCLAVE
else:
distribution_type = DistributionType.COMMUNITY
params = {
'indicators': indicators,
'enclaveIds': enclave_ids,
'distributionType': distribution_type,
... | 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 correlated reports for.
:param enclave_ids: The enclaves to search in.
:param is_enclave: Whether to search enclave reports or community reports.
:para... | 2.58135 | 2.943745 | 0.876893 |
body = {
'searchTerm': search_term
}
params = {
'enclaveIds': enclave_ids,
'from': from_time,
'to': to_time,
'tags': tags,
'excludedTags': excluded_tags,
'pageSize': page_size,
'pageNumber'... | 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,
... | Search for reports containing a search term.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restrict reports to specific enclaves (optional - by
... | 2.121412 | 2.332729 | 0.909412 |
get_page = functools.partial(self.get_reports_page, is_enclave, enclave_ids, tag, excluded_tags)
return get_time_based_page_generator(
get_page=get_page,
get_next_to_time=lambda x: x.items[-1].updated if len(x.items) > 0 else None,
from_time=from_time,
... | 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: restrict reports to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_ids: list of enclave ids used to restrict... | 3.164901 | 3.411485 | 0.927719 |
return Page.get_generator(page_generator=self._get_reports_page_generator(is_enclave, enclave_ids, tag,
excluded_tags, from_time, to_time)) | 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 to specific distribution type (optional - by default all accessible
reports are returned).
:param list(str) enclave_id... | 4.409959 | 4.288621 | 1.028293 |
get_page = functools.partial(self.get_correlated_reports_page, indicators, enclave_ids, is_enclave)
return Page.get_page_generator(get_page, start_page, page_size) | 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 indicators: A list of indicator values to retrieve correlated reports for.
:param enclave_ids:
:param is_enclave:
:return: The generator. | 2.803054 | 3.26448 | 0.858653 |
return Page.get_generator(page_generator=self._get_correlated_reports_page_generator(indicators,
enclave_ids,
is_enc... | 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_ids: The enclaves to search in.
:param is_enclave: Whether to search enclave reports or commu... | 5.287646 | 5.208423 | 1.01521 |
get_page = functools.partial(self.search_reports_page, search_term, enclave_ids, from_time, to_time, tags,
excluded_tags)
return Page.get_page_generator(get_page, start_page, page_size) | def _search_reports_page_generator(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
exclude... | Creates a generator from the |search_reports_page| method that returns each successive page.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to restri... | 2.704342 | 3.163298 | 0.854912 |
return Page.get_generator(page_generator=self._search_reports_page_generator(search_term, enclave_ids,
from_time, to_time, tags,
exc... | 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 that returns each successive report.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to re... | 3.824917 | 3.904315 | 0.979664 |
# if timestamp is null, just return the same null.
if not date_time:
return date_time
datetime_dt = datetime.now()
# get current time in seconds-since-epoch
current_time = int(time.time()) * 1000
try:
# identify type of timestamp and convert to datetime object
i... | 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 milliseconds since epoch, or string/datetime object conta... | 3.630234 | 3.584085 | 1.012876 |
if value is None:
return None
if isinstance(value, bool):
return value
if isinstance(value, string_types):
value = value.lower()
if value == 'false':
return False
if value == 'true':
return True
raise ValueError("Could not convert ... | 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 | 2.096053 | 1.999704 | 1.048182 |
# read config file depending on filetype, parse into dictionary
ext = os.path.splitext(config_file_path)[-1]
if ext in ['.conf', '.ini']:
config_parser = configparser.RawConfigParser()
config_parser.read(config_file_path)
roles = dict(config_parser)
... | 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 section within the file to use.
:return: The configuration dictionary. | 2.522761 | 2.547003 | 0.990482 |
result = self._client.get("version").content
if isinstance(result, bytes):
result = result.decode('utf-8')
return result.strip('\n') | def get_version(self) | Get the version number of the API.
Example:
>>> ts.get_version()
1.3 | 5.607347 | 6.335195 | 0.88511 |
resp = self._client.get("enclaves")
return [EnclavePermissions.from_dict(enclave) for enclave in resp.json()] | 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. | 6.978346 | 4.208528 | 1.658144 |
resp = self._client.get("request-quotas")
return [RequestQuota.from_dict(quota) for quota in resp.json()] | def get_request_quotas(self) | Gets the request quotas for the user's company.
:return: A list of |RequestQuota| objects. | 5.904792 | 5.113626 | 1.154717 |
if not parse_boolean(os.environ.get('DISABLE_TRUSTAR_LOGGING')):
# configure
dictConfig(DEFAULT_LOGGING_CONFIG)
# construct error logger
error_logger = logging.getLogger("error")
# log all uncaught exceptions
def log_exception(exc_type, exc_value, exc_traceba... | def configure_logging() | Initialize logging configuration to defaults. If the environment variable DISABLE_TRUSTAR_LOGGING is set to true,
this will be ignored. | 3.980309 | 3.129642 | 1.27181 |
return Enclave(id=enclave.get('id'),
name=enclave.get('name'),
type=EnclaveType.from_string(enclave.get('type'))) | def from_dict(cls, enclave) | Create a enclave object from a dictionary.
:param enclave: The dictionary.
:return: The enclave object. | 3.15678 | 3.117976 | 1.012445 |
if remove_nones:
return super().to_dict(remove_nones=True)
return {
'id': self.id,
'name': self.name,
'type': self.type
} | 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. | 2.398822 | 2.668156 | 0.899056 |
enclave = super(cls, EnclavePermissions).from_dict(d)
enclave_permissions = cls.from_enclave(enclave)
enclave_permissions.read = d.get('read')
enclave_permissions.create = d.get('create')
enclave_permissions.update = d.get('update')
return enclave_permissions | def from_dict(cls, d) | Create a enclave object from a dictionary.
:param d: The dictionary.
:return: The EnclavePermissions object. | 3.427633 | 2.665532 | 1.28591 |
d = super().to_dict(remove_nones=remove_nones)
d.update({
'read': self.read,
'create': self.create,
'update': self.update
})
return d | 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. | 2.847218 | 3.052818 | 0.932653 |
return EnclavePermissions(id=enclave.id,
name=enclave.name,
type=enclave.type) | def from_enclave(cls, enclave) | Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object | 5.604954 | 4.608729 | 1.21616 |
params = {'idType': id_type}
resp = self._client.get("reports/%s/tags" % report_id, params=params)
return [Tag.from_dict(indicator) for indicator in resp.json()] | 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. | 4.087464 | 4.118067 | 0.992569 |
params = {
'idType': id_type,
'name': name,
'enclaveId': enclave_id
}
resp = self._client.post("reports/%s/tags" % report_id, params=params)
return str(resp.content) | 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
:param id_type: indicates whether the ID internal or an external ID provided by t... | 2.927066 | 3.100035 | 0.944204 |
params = {
'idType': id_type
}
self._client.delete("reports/%s/tags/%s" % (report_id, tag_id), params=params) | 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 an external ID provided by the user
:return: The response body. | 3.26994 | 3.700252 | 0.883707 |
params = {'enclaveIds': enclave_ids}
resp = self._client.get("reports/tags", params=params)
return [Tag.from_dict(indicator) for indicator in resp.json()] | 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 list of |Tag| objects. | 5.085891 | 5.279993 | 0.963238 |
data = {
'value': indicator_value,
'tag': {
'name': name,
'enclaveId': enclave_id
}
}
resp = self._client.post("indicators/tags", data=json.dumps(data))
return Tag.from_dict(resp.json()) | 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 be added
:return: A |Tag| object representing the tag that was created. | 2.740456 | 2.55093 | 1.074297 |
params = {
'value': indicator_value
}
self._client.delete("indicators/tags/%s" % tag_id, params=params) | 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 | 3.962363 | 4.80238 | 0.825083 |
return Tag(name=tag.get('name'),
id=tag.get('guid'),
enclave_id=tag.get('enclaveId')) | 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 API call such as ``GET /enclave-tags``.
... | 6.165196 | 4.800462 | 1.284292 |
if remove_nones:
d = super().to_dict(remove_nones=True)
else:
d = {
'name': self.name,
'id': self.id,
'enclaveId': self.enclave_id
}
return d | 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. | 2.892471 | 3.083554 | 0.938032 |
lines = []
with open(filename, "r") as f:
for line in f:
if line.startswith(comment_char):
continue
if len(lines) < n_lines:
lines.append(line)
else:
break
if len(lines) < n_lines:
raise ValueError(
... | 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. | 1.995919 | 2.043774 | 0.976585 |
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
raise ValueError("FPKM tracking file %s missing column '%s'" % (
filename,
column_name)) | def check_required_columns(df, filename, required_columns) | Ensure that all required columns are present in the given dataframe,
otherwise raise an exception. | 3.906697 | 3.632968 | 1.075346 |
'''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.element.symbol for a in traj.topo... | 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. | 3.178066 | 2.082486 | 1.526092 |
'''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.b64encode(array.data).dec... | 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 | 4.186757 | 2.012578 | 2.080295 |
return {
row.id: row
for (_, row)
in load_cufflinks_dataframe(*args, **kwargs).iterrows()
} | 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 | 5.17964 | 5.810458 | 0.891434 |
return {
row.id: row.fpkm
for (_, row)
in load_cufflinks_dataframe(*args, **kwargs).iterrows()
} | def load_cufflinks_fpkm_dict(*args, **kwargs) | Returns dictionary mapping feature identifier (either transcript or gene ID)
to FPKM expression value. | 4.598651 | 4.760256 | 0.966051 |
libs = ['objexporter.js',
'ArcballControls.js', 'filesaver.js',
'base64-arraybuffer.js', 'context.js',
'chemview.js', 'three.min.js', 'jquery-ui.min.js',
'context.standalone.css', 'chemview_widget.js',
'trajectory_controls_widget.js', "layout_widget.j... | def enable_notebook(verbose=0) | Enable IPython notebook widgets to be displayed.
This function should be called before using the chemview widgets. | 6.924949 | 6.744442 | 1.026764 |
rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()
sio = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, sio, codec='utf-8', laparams=laparams)
interpreter = pdfminer.pdfinterp.PDFPageInterpreter(rsrcmgr, device)
# Extract text from pdf file
with open(file_name, 'rb') ... | def extract_pdf(file_name) | Extract text from a pdf file
:param file_name path to pdf to read
:return text from pdf | 2.02531 | 2.014993 | 1.00512 |
if source_file.endswith(('.pdf', '.PDF')):
txt = extract_pdf(source_file)
elif source_file.endswith(('.txt', '.eml', '.csv', '.json')):
with open(source_file, 'r') as f:
txt = f.read()
else:
logger.info("Unsupported file extension for file {}".format(source_file))
... | 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 | 2.880044 | 2.593514 | 1.110479 |
# find enum value
for attr in dir(cls):
value = getattr(cls, attr)
if value == string:
return value
# if not found, log warning and return the value passed in
logger.warning("{} is not a valid enum value for {}.".format(string, cls.__nam... | def from_string(cls, string) | Simply logs a warning if the desired enum value is not found.
:param string:
:return: | 4.199674 | 3.333803 | 1.259724 |
errors = []
value = self._validate_type(value, errors)
self._validate_value(value, errors)
if errors:
raise ValidationErrors(errors)
return value | 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 | 4.163313 | 3.916206 | 1.063099 |
if value is None or (self.type == 'flag' and not value):
return None
pass_as_bits = text_type(self.pass_as or self.default_pass_as).split()
env = dict(name=self.name, value=value, v=value)
return [bit.format(**env) for bit in pass_as_bits] | 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 | 5.879937 | 5.7419 | 1.02404 |
if value is None:
return []
if isinstance(value, (list, tuple)):
return list(value)
return [value] | 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.
:return: a list!
:rtyp... | 2.26387 | 2.419166 | 0.935806 |
if isinstance(parameter_map, list): # Partially emulate old (pre-0.7) API for this function.
parameter_map = LegacyParameterMap(parameter_map)
out_commands = []
for command in listify(command):
# Only attempt formatting if the string smells like it should be formatted.
# This... | 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.
:param command: The command to interpolate params int... | 6.6131 | 6.424836 | 1.029303 |
data = read_yaml(yaml)
validator = get_validator()
# Nb: this uses a list instead of being a generator function in order to be
# easier to call correctly. (Were it a generator function, a plain
# `validate(..., raise_exc=True)` would not do anything.
errors = list(validator.iter_errors(data... | 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 errors after validation.
:type raise_exc: bool
... | 8.529844 | 8.90818 | 0.957529 |
param_bits = []
for name in self.parameters:
param_bits.extend(self.build_parameter_by_name(name) or [])
return param_bits | def build_parameters(self) | Build the CLI command line from the parameter values.
:return: list of CLI strings -- not escaped!
:rtype: list[str] | 5.678528 | 5.201346 | 1.091742 |
parsers = {
'step': ([], Step.parse),
'endpoint': ([], Endpoint.parse),
}
for datum in data:
assert isinstance(datum, dict)
for type, (items, parse) in parsers.items():
if type in datum:
items.append(par... | 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 | 3.781731 | 3.985914 | 0.948774 |
if not kwargs:
return None
for index, step in enumerate(self.steps.values()):
extended_step = dict(step.serialize(), index=index)
# check if kwargs is a subset of extended_step
if all(item in extended_step.items() for item in kwargs.items()):
... | 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(name="greeting", command='echo HELLO MORDOR')
... | 3.952482 | 3.776739 | 1.046533 |
data = read_yaml(yaml)
if validate: # pragma: no branch
from .validation import validate
validate(data, raise_exc=True)
return Config.parse(data) | 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 parse it.
:type validate: bool
:retu... | 5.663413 | 6.214853 | 0.911271 |
return {
name: parameter.default
for (name, parameter)
in self.parameters.items()
if parameter.default is not None and (include_flags or parameter.type != 'flag')
} | def get_parameter_defaults(self, include_flags=True) | Get a dict mapping parameter names to their defaults (if set).
:rtype: dict[str, object] | 3.120854 | 2.934568 | 1.06348 |
command = (command or self.command)
# merge defaults with passed values
# ignore flag default values as they are special
# undefined flag will remain undefined regardless of default value
values = dict(self.get_parameter_defaults(include_flags=False), **parameter_values... | 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
responsibility to concatenate them, likely using the semicolon or
double ampersa... | 7.095982 | 7.889042 | 0.899473 |
with open(file_path, 'r') as yaml:
try:
return lint(yaml)
except Exception as e:
lr = LintResult()
lr.add_error('could not parse YAML: %s' % e, exception=e)
return lr | 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 | 4.447756 | 4.009264 | 1.10937 |
currencies = self.get_currencies()
currency_objects = {}
for code, name in currencies:
currency_objects[code], created = Currency.objects.get_or_create(
code=code, defaults={'name': name})
if created:
logger.info('currency: %s crea... | 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 | 2.472789 | 2.325495 | 1.063339 |
''' 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 _re_flatten(p) | Turn all capturing groups in a regular expression pattern into
non-capturing groups. | 4.593424 | 3.759465 | 1.221829 |
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 = ""
res.set_header('Location', urljoin(request.url, url))
raise res | def redirect(url, code=None) | Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. | 4.003815 | 3.761566 | 1.064401 |
''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
fp.seek(offset)
while bytes > 0:
part = fp.read(min(bytes, maxread))
if not part: break
bytes -= len(part)
yield part | def _file_iter_range(fp, offset, bytes, maxread=1024*1024) | Yield chunks from a range in a file. No chunk is bigger than maxread. | 3.933193 | 2.409744 | 1.632204 |
root = os.path.abspath(root) + os.sep
filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
headers = dict()
if not filename.startswith(root):
return HTTPError(403, "Access denied.")
if not os.path.exists(filename) or not os.path.isfile(filename):
return HTTPEr... | def static_file(filename, root, mimetype='auto', download=False, charset='UTF-8') | Open a file in a safe way and return :exc:`HTTPResponse` with status
code 200, 305, 403 or 404. The ``Content-Type``, ``Content-Encoding``,
``Content-Length`` and ``Last-Modified`` headers are set if possible.
Special support for ``If-Modified-Since``, ``Range`` and ``HEAD``
requests.
... | 1.994075 | 2.007266 | 0.993429 |
global DEBUG
if mode: warnings.simplefilter('default')
DEBUG = bool(mode) | def debug(mode=True) | Change the debug level.
There is only one debug level supported at the moment. | 7.869839 | 9.422729 | 0.835197 |
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
return user, pwd
except (KeyError, ValueError):
return None | def parse_auth(header) | Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None | 3.295381 | 3.093231 | 1.065352 |
''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive.'''
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, end in ranges:
try:
if... | def parse_range_header(header, maxlen=0) | Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive. | 2.951097 | 2.391683 | 1.2339 |
''' Callback decorator to require HTTP auth (basic).
TODO: Add route(check_auth=...) parameter. '''
def decorator(func):
def wrapper(*a, **ka):
user, password = request.auth or (None, None)
if user is None or not check(user, password):
err = HTTPError(401,... | def auth_basic(check, realm="private", text="Access denied") | Callback decorator to require HTTP auth (basic).
TODO: Add route(check_auth=...) parameter. | 4.097979 | 2.561047 | 1.600119 |
''' Decorator: renders a template for a handler.
The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not
process the template, but return the handler result... | def view(tpl_name, **defaults) | Decorator: renders a template for a handler.
The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not
process the template, but return the handler result as is.
... | 6.698278 | 1.824643 | 3.671008 |
''' Add a new rule or replace the target for an existing rule. '''
anons = 0 # Number of anonymous wildcards found
keys = [] # Names of keys
pattern = '' # Regular expression pattern with named groups
filters = [] # Lists of wildcard input filters
bu... | def add(self, rule, method, target, name=None) | Add a new rule or replace the target for an existing rule. | 3.789721 | 3.767812 | 1.005815 |
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
url = ''.join([f(query.pop(n)) if n... | def build(self, _name, *anons, **query) | Build an URL by filling the wildcards in a rule. | 6.268879 | 5.402112 | 1.16045 |
''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). '''
verb = environ['REQUEST_METHOD'].upper()
path = environ['PATH_INFO'] or '/'
target = None
if verb == 'HEAD':
methods = ['PROXY', verb, 'GET', 'ANY']
else:
methods = ['PROXY'... | def match(self, environ) | Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). | 3.217067 | 2.74679 | 1.17121 |
''' Return the callback. If the callback is a decorated function, try to
recover the original function. '''
func = self.callback
func = getattr(func, '__func__' if py3k else 'im_func', func)
closure_attr = '__closure__' if py3k else 'func_closure'
while hasattr(func, ... | def get_undecorated_callback(self) | Return the callback. If the callback is a decorated function, try to
recover the original function. | 3.527848 | 2.623693 | 1.344612 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.