Search is not available for this dataset
text stringlengths 75 104k |
|---|
async def run_tasks(self):
""" Run the tasks attached to the instance """
tasks = self.get_tasks()
self._gathered_tasks = asyncio.gather(*tasks, loop=self.loop)
try:
await self._gathered_tasks
except CancelledError:
pass |
async def close(self):
""" properly close the client """
tasks = self._get_close_tasks()
if tasks:
await asyncio.wait(tasks)
self._session = None |
async def _get_twitter_configuration(self):
"""
create a ``twitter_configuration`` attribute with the response
of the endpoint
https://api.twitter.com/1.1/help/configuration.json
"""
api = self['api', general.twitter_api_version,
".json", general.twitte... |
async def _get_user(self):
"""
create a ``user`` attribute with the response of the endpoint
https://api.twitter.com/1.1/account/verify_credentials.json
"""
api = self['api', general.twitter_api_version,
".json", general.twitter_base_api_url]
return aw... |
async def _chunked_upload(self, media, media_size,
path=None,
media_type=None,
media_category=None,
chunk_size=2**20,
**params):
"""
upload media in c... |
async def upload_media(self, file_,
media_type=None,
media_category=None,
chunked=None,
size_limit=None,
**params):
"""
upload a media on twitter
Parameters... |
def split_stdout_lines(stdout):
"""
Given the standard output from NetMHC/NetMHCpan/NetMHCcons tools,
drop all {comments, lines of hyphens, empty lines} and split the
remaining lines by whitespace.
"""
# all the NetMHC formats use lines full of dashes before any actual
# binding results
... |
def clean_fields(fields, ignored_value_indices, transforms):
"""
Sometimes, NetMHC* has fields that are only populated sometimes, which results
in different count/indexing of the fields when that happens.
We handle this by looking for particular strings at particular indices, and
deleting them.
... |
def parse_stdout(
stdout,
prediction_method_name,
sequence_key_mapping,
key_index,
offset_index,
peptide_index,
allele_index,
ic50_index,
rank_index,
log_ic50_index,
ignored_value_indices={},
transforms={}):
"""
Gene... |
def parse_netmhc3_stdout(
stdout,
prediction_method_name="netmhc3",
sequence_key_mapping=None):
"""
Parse the output format for NetMHC 3.x, which looks like:
----------------------------------------------------------------------------------------------------
pos peptide ... |
def parse_netmhc4_stdout(
stdout,
prediction_method_name="netmhc4",
sequence_key_mapping=None):
"""
# Peptide length 9
# Rank Threshold for Strong binding peptides 0.500
# Rank Threshold for Weak binding peptides 2.000
-----------------------------------------------------... |
def parse_netmhcpan28_stdout(
stdout,
prediction_method_name="netmhcpan",
sequence_key_mapping=None):
"""
# Affinity Threshold for Strong binding peptides 50.000',
# Affinity Threshold for Weak binding peptides 500.000',
# Rank Threshold for Strong binding peptides 0.500',
... |
def parse_netmhcpan3_stdout(
stdout,
prediction_method_name="netmhcpan",
sequence_key_mapping=None):
"""
# Rank Threshold for Strong binding peptides 0.500
# Rank Threshold for Weak binding peptides 2.000
-----------------------------------------------------------------------... |
def parse_netmhcpan4_stdout(
stdout,
prediction_method_name="netmhcpan",
sequence_key_mapping=None):
"""
# NetMHCpan version 4.0
# Tmpdir made /var/folders/jc/fyrvcrcs3sb8g4mkdg6nl_t80000gp/T//netMHCpanuH3SvY
# Input is in PEPTIDE format
# Make binding affinity predictions
... |
def _parse_iedb_response(response):
"""Take the binding predictions returned by IEDB's web API
and parse them into a DataFrame
Expect response to look like:
allele seq_num start end length peptide ic50 percentile_rank
HLA-A*01:01 1 2 10 9 LYNTVATLY 2145.70 3.7
HLA-A*01:01 1 5 ... |
def _query_iedb(request_values, url):
"""
Call into IEDB's web API for MHC binding prediction using request dictionary
with fields:
- "method"
- "length"
- "sequence_text"
- "allele"
Parse the response into a DataFrame.
"""
data = urlencode(request_values)
re... |
def predict_subsequences(self, sequence_dict, peptide_lengths=None):
"""Given a dictionary mapping unique keys to amino acid sequences,
run MHC binding predictions on all candidate epitopes extracted from
sequences and return a EpitopeCollection.
Parameters
----------
fa... |
def get_args(func, skip=0):
"""
Hackish way to get the arguments of a function
Parameters
----------
func : callable
Function to get the arguments from
skip : int, optional
Arguments to skip, defaults to 0 set it to 1 to skip the
``self`` argument of a method.
R... |
def log_error(msg=None, exc_info=None, logger=None, **kwargs):
"""
log an exception and its traceback on the logger defined
Parameters
----------
msg : str, optional
A message to add to the error
exc_info : tuple
Information about the current exception
logger : logging.L... |
async def get_media_metadata(data, path=None):
"""
Get all the file's metadata and read any kind of file object
Parameters
----------
data : bytes
first bytes of the file (the mimetype shoudl be guessed from the
file headers
path : str, optional
path to the file
... |
async def get_size(media):
"""
Get the size of a file
Parameters
----------
media : file object
The file object of the media
Returns
-------
int
The size of the file
"""
if hasattr(media, 'seek'):
await execute(media.seek(0, os.SEEK_END))
siz... |
async def get_type(media, path=None):
"""
Parameters
----------
media : file object
A file object of the image
path : str, optional
The path to the file
Returns
-------
str
The mimetype of the media
str
The category of the media on Twitter
"""
... |
def set_debug():
""" activates error messages, useful during development """
logging.basicConfig(level=logging.WARNING)
peony.logger.setLevel(logging.DEBUG) |
def clone_with_updates(self, **kwargs):
"""Returns new BindingPrediction with updated fields"""
fields_dict = self.to_dict()
fields_dict.update(kwargs)
return BindingPrediction(**fields_dict) |
def NetMHCpan(
alleles,
program_name="netMHCpan",
process_limit=-1,
default_peptide_lengths=[9],
extra_flags=[]):
"""
This function wraps NetMHCpan28 and NetMHCpan3 to automatically detect which class
to use, with the help of the miraculous and strange '--version' net... |
def get_data(self, response):
""" Get the data from the response """
if self._response_list:
return response
elif self._response_key is None:
if hasattr(response, "items"):
for key, data in response.items():
if (hasattr(data, "__getitem... |
async def call_on_response(self, data):
"""
Try to fill the gaps and strip last tweet from the response
if its id is that of the first tweet of the last response
Parameters
----------
data : list
The response data
"""
since_id = self.kwargs.ge... |
async def get_oauth_token(consumer_key, consumer_secret, callback_uri="oob"):
"""
Get a temporary oauth token
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret : str
Your consumer secret
callback_uri : str, optional
Callback uri, defaults to ... |
async def get_oauth_verifier(oauth_token):
"""
Open authorize page in a browser,
print the url if it didn't work
Arguments
---------
oauth_token : str
The oauth token received in :func:`get_oauth_token`
Returns
-------
str
The PIN entered by the user
"""
url... |
async def get_access_token(consumer_key, consumer_secret,
oauth_token, oauth_token_secret,
oauth_verifier, **kwargs):
"""
get the access token of the user
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret... |
async def async_oauth_dance(consumer_key, consumer_secret, callback_uri="oob"):
"""
OAuth dance to get the user's access token
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret : str
Your consumer secret
callback_uri : str
Callback uri, d... |
def parse_token(response):
"""
parse the responses containing the tokens
Parameters
----------
response : str
The response containing the tokens
Returns
-------
dict
The parsed tokens
"""
items = response.split("&")
items = [item.split("=") for item in items... |
def oauth_dance(consumer_key, consumer_secret,
oauth_callback="oob", loop=None):
"""
OAuth dance to get the user's access token
It calls async_oauth_dance and create event loop of not given
Parameters
----------
consumer_key : str
Your consumer key
consumer_secr... |
def oauth2_dance(consumer_key, consumer_secret, loop=None):
"""
oauth2 dance
Parameters
----------
consumer_key : str
Your consumer key
consumer_secret : str
Your consumer secret
loop : event loop, optional
event loop to use
Returns
-------
str
... |
def predict(self, sequences):
"""
Return netChop predictions for each position in each sequence.
Parameters
-----------
sequences : list of string
Amino acid sequences to predict cleavage for
Returns
-----------
list of list of float
... |
def parse_netchop(netchop_output):
"""
Parse netChop stdout.
"""
line_iterator = iter(netchop_output.decode().split("\n"))
scores = []
for line in line_iterator:
if "pos" in line and 'AA' in line and 'score' in line:
scores.append([])
... |
def to_dataframe(
self,
columns=BindingPrediction.fields + ("length",)):
"""
Converts collection of BindingPrediction objects to DataFrame
"""
return pd.DataFrame.from_records(
[tuple([getattr(x, name) for name in columns]) for x in self],
... |
def NetMHC(alleles,
default_peptide_lengths=[9],
program_name="netMHC"):
"""
This function wraps NetMHC3 and NetMHC4 to automatically detect which class
to use. Currently based on running the '-h' command and looking for
discriminating substrings between the versions.
"""
#... |
def predict_peptides(self, peptides):
"""
Predict MHC affinity for peptides.
"""
# importing locally to avoid slowing down CLI applications which
# don't use MHCflurry
from mhcflurry.encodable_sequences import EncodableSequences
binding_predictions = []
... |
def seq_to_str(obj, sep=","):
"""
Given a sequence convert it to a comma separated string.
If, however, the argument is a single object, return its string
representation.
"""
if isinstance(obj, string_classes):
return obj
elif isinstance(obj, (list, tuple)):
return sep.join([... |
def convert(img, formats):
"""
Convert the image to all the formats specified
Parameters
----------
img : PIL.Image.Image
The image to convert
formats : list
List of all the formats to use
Returns
-------
io.BytesIO
A file object containing the converted i... |
def optimize_media(file_, max_size, formats):
"""
Optimize an image
Resize the picture to the ``max_size``, defaulting to the large
photo size of Twitter in :meth:`PeonyClient.upload_media` when
used with the ``optimize_media`` argument.
Parameters
----------
file_ : file object
... |
def create_input_peptides_files(
peptides,
max_peptides_per_file=None,
group_by_length=False):
"""
Creates one or more files containing one peptide per line,
returns names of files.
"""
if group_by_length:
peptide_lengths = {len(p) for p in peptides}
peptide_g... |
def _check_peptide_lengths(self, peptide_lengths=None):
"""
If peptide lengths not specified, then try using the default
lengths associated with this predictor object. If those aren't
a valid non-empty sequence of integers, then raise an exception.
Otherwise return the peptide le... |
def _check_peptide_inputs(self, peptides):
"""
Check peptide sequences to make sure they are valid for this predictor.
"""
require_iterable_of(peptides, string_types)
check_X = not self.allow_X_in_peptides
check_lower = not self.allow_lowercase_in_peptides
check_m... |
def predict_subsequences(
self,
sequence_dict,
peptide_lengths=None):
"""
Given a dictionary mapping sequence names to amino acid strings,
and an optional list of peptide lengths, returns a
BindingPredictionCollection.
"""
if isinstance... |
def _check_hla_alleles(
alleles,
valid_alleles=None):
"""
Given a list of HLA alleles and an optional list of valid
HLA alleles, return a set of alleles that we will pass into
the MHC binding predictor.
"""
require_iterable_of(alleles, string_types... |
async def _connect(self):
"""
Connect to the stream
Returns
-------
asyncio.coroutine
The streaming response
"""
logger.debug("connecting to the stream")
await self.client.setup
if self.session is None:
self.session = s... |
async def connect(self):
"""
Create the connection
Returns
-------
self
Raises
------
exception.PeonyException
On a response status in 4xx that are not status 420 or 429
Also on statuses in 1xx or 3xx since this should not be ... |
async def init_restart(self, error=None):
"""
Restart the stream on error
Parameters
----------
error : bool, optional
Whether to print the error or not
"""
if error:
utils.log_error(logger=logger)
if self.state == DISCONNECTI... |
async def restart_stream(self):
"""
Restart the stream on error
"""
await self.response.release()
await asyncio.sleep(self._error_timeout)
await self.connect()
logger.info("Reconnected to the stream")
self._reconnecting = False
return {'stream... |
def with_prefix(self, prefix, strict=False):
"""
decorator to handle commands with prefixes
Parameters
----------
prefix : str
the prefix of the command
strict : bool, optional
If set to True the command must be at the beginning
of... |
def envelope(self):
""" returns an :class:`Event` that can be used for site streams """
def enveloped_event(data):
return 'for_user' in data and self._func(data.get('message'))
return self.__class__(enveloped_event, self.__name__) |
async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() |
def run_command(args, **kwargs):
"""
Given a list whose first element is a command name, followed by arguments,
execute it and show timing info.
"""
assert len(args) > 0
start_time = time.time()
process = AsyncProcess(args, **kwargs)
process.wait()
elapsed_time = time.time() - start_... |
def run_multiple_commands_redirect_stdout(
multiple_args_dict,
print_commands=True,
process_limit=-1,
polling_freq=0.5,
**kwargs):
"""
Run multiple shell commands in parallel, write each of their
stdout output to files associated with each command.
Parameters
... |
def _determine_supported_alleles(command, supported_allele_flag):
"""
Try asking the commandline predictor (e.g. netMHCpan)
which alleles it supports.
"""
try:
# convert to str since Python3 returns a `bytes` object
supported_alleles_output = check_output(... |
def loads(json_data, encoding="utf-8", **kwargs):
"""
Custom loads function with an object_hook and automatic decoding
Parameters
----------
json_data : str
The JSON data to decode
*args
Positional arguments, passed to :func:`json.loads`
encoding : :obj:`str`, optional
... |
async def read(response, loads=loads, encoding=None):
"""
read the data of the response
Parameters
----------
response : aiohttp.ClientResponse
response
loads : callable
json loads function
encoding : :obj:`str`, optional
character encoding of the response, if se... |
def doc(func):
"""
Find the message shown when someone calls the help command
Parameters
----------
func : function
the function
Returns
-------
str
The help message for this command
"""
stripped_chars = " \t"
if hasattr(func, '__doc__'):
docstr... |
def permission_check(data, command_permissions,
command=None, permissions=None):
"""
Check the permissions of the user requesting a command
Parameters
----------
data : dict
message data
command_permissions : dict
permissions of the command, contains all... |
def main(args_list=None):
"""
Script to make pMHC binding predictions from amino acid sequences.
Usage example:
mhctools
--sequence SFFPIQQQQQAAALLLI \
--sequence SILQQQAQAQQAQAASSSC \
--extract-subsequences \
--mhc-predictor netmhc \
--mh... |
def _prepare_drb_allele_name(self, parsed_beta_allele):
"""
Assume that we're dealing with a human DRB allele
which NetMHCIIpan treats differently because there is
little population diversity in the DR-alpha gene
"""
if "DRB" not in parsed_beta_allele.gene:
ra... |
def prepare_allele_name(self, allele_name):
"""
netMHCIIpan has some unique requirements for allele formats,
expecting the following forms:
- DRB1_0101 (for non-alpha/beta pairs)
- HLA-DQA10501-DQB10636 (for alpha and beta pairs)
Other than human class II alleles, the ... |
def get_error(data):
""" return the error if there is a corresponding exception """
if isinstance(data, dict):
if 'errors' in data:
error = data['errors'][0]
else:
error = data.get('error', None)
if isinstance(error, dict):
if error.get('code') in err... |
async def throw(response, loads=None, encoding=None, **kwargs):
""" Get the response data if possible and raise an exception """
if loads is None:
loads = data_processing.loads
data = await data_processing.read(response, loads=loads,
encoding=encoding)
err... |
def code(self, code):
""" Decorator to associate a code to an exception """
def decorator(exception):
self[code] = exception
return exception
return decorator |
async def prepare_request(self, method, url,
headers=None,
skip_params=False,
proxy=None,
**kwargs):
"""
prepare all the arguments for the request
Parameters
---------... |
def _user_headers(self, headers=None):
""" Make sure the user doesn't override the Authorization header """
h = self.copy()
if headers is not None:
keys = set(headers.keys())
if h.get('Authorization', False):
keys -= {'Authorization'}
for key... |
def process_keys(func):
"""
Raise error for keys that are not strings
and add the prefix if it is missing
"""
@wraps(func)
def decorated(self, k, *args):
if not isinstance(k, str):
msg = "%s: key must be a string" % self.__class__.__name__
raise ValueError(msg)
... |
def _get(self, text):
"""
Analyze the text to get the right function
Parameters
----------
text : str
The text that could call a function
"""
if self.strict:
match = self.prog.match(text)
if match:
cmd = mat... |
async def run(self, *args, data):
""" run the function you want """
cmd = self._get(data.text)
try:
if cmd is not None:
command = self[cmd](*args, data=data)
return await peony.utils.execute(command)
except:
fmt = "Error occurred ... |
def get_cartesian(r, theta):
"""
Given a radius and theta, return the cartesian (x, y) coordinates.
"""
x = r*np.sin(theta)
y = r*np.cos(theta)
return x, y |
def simplified_edges(self):
"""
A generator for getting all of the edges without consuming extra
memory.
"""
for group, edgelist in self.edges.items():
for u, v, d in edgelist:
yield (u, v) |
def initialize_major_angle(self):
"""
Computes the major angle: 2pi radians / number of groups.
"""
num_groups = len(self.nodes.keys())
self.major_angle = 2 * np.pi / num_groups |
def initialize_minor_angle(self):
"""
Computes the minor angle: 2pi radians / 3 * number of groups.
"""
num_groups = len(self.nodes.keys())
self.minor_angle = 2 * np.pi / (6 * num_groups) |
def plot_radius(self):
"""
Computes the plot radius: maximum of length of each list of nodes.
"""
plot_rad = 0
for group, nodelist in self.nodes.items():
proposed_radius = len(nodelist) * self.scale
if proposed_radius > plot_rad:
plot_rad =... |
def has_edge_within_group(self, group):
"""
Checks whether there are within-group edges or not.
"""
assert group in self.nodes.keys(),\
"{0} not one of the group of nodes".format(group)
nodelist = self.nodes[group]
for n1, n2 in self.simplified_edges():
... |
def plot_axis(self, rs, theta):
"""
Renders the axis.
"""
xs, ys = get_cartesian(rs, theta)
self.ax.plot(xs, ys, 'black', alpha=0.3) |
def plot_nodes(self, nodelist, theta, group):
"""
Plots nodes to screen.
"""
for i, node in enumerate(nodelist):
r = self.internal_radius + i * self.scale
x, y = get_cartesian(r, theta)
circle = plt.Circle(xy=(x, y), radius=self.dot_radius,
... |
def group_theta(self, group):
"""
Computes the theta along which a group's nodes are aligned.
"""
for i, g in enumerate(self.nodes.keys()):
if g == group:
break
return i * self.major_angle |
def add_axes_and_nodes(self):
"""
Adds the axes (i.e. 2 or 3 axes, not to be confused with matplotlib
axes) and the nodes that belong to each axis.
"""
for i, (group, nodelist) in enumerate(self.nodes.items()):
theta = self.group_theta(group)
if self.has_... |
def find_node_group_membership(self, node):
"""
Identifies the group for which a node belongs to.
"""
for group, nodelist in self.nodes.items():
if node in nodelist:
return group |
def get_idx(self, node):
"""
Finds the index of the node in the sorted list.
"""
group = self.find_node_group_membership(node)
return self.nodes[group].index(node) |
def node_radius(self, node):
"""
Computes the radial position of the node.
"""
return self.get_idx(node) * self.scale + self.internal_radius |
def node_theta(self, node):
"""
Convenience function to find the node's theta angle.
"""
group = self.find_node_group_membership(node)
return self.group_theta(group) |
def draw_edge(self, n1, n2, d, group):
"""
Renders the given edge (n1, n2) to the plot.
"""
start_radius = self.node_radius(n1)
start_theta = self.node_theta(n1)
end_radius = self.node_radius(n2)
end_theta = self.node_theta(n2)
start_theta, end_theta = s... |
def add_edges(self):
"""
Draws all of the edges in the graph.
"""
for group, edgelist in self.edges.items():
for (u, v, d) in edgelist:
self.draw_edge(u, v, d, group) |
def draw(self):
"""
The master function that is called that draws everything.
"""
self.ax.set_xlim(-self.plot_radius(), self.plot_radius())
self.ax.set_ylim(-self.plot_radius(), self.plot_radius())
self.add_axes_and_nodes()
self.add_edges()
self.ax.axis(... |
def adjust_angles(self, start_node, start_angle, end_node, end_angle):
"""
This function adjusts the start and end angles to correct for
duplicated axes.
"""
start_group = self.find_node_group_membership(start_node)
end_group = self.find_node_group_membership(end_node)
... |
def correct_angles(self, start_angle, end_angle):
"""
This function corrects for the following problems in the edges:
"""
# Edges going the anti-clockwise direction involves angle = 0.
if start_angle == 0 and (end_angle - start_angle > np.pi):
start_angle = np.pi * 2
... |
def mods_genre(self):
"""
Guesses an appropriate MODS XML genre type.
"""
type2genre = {
'conference': 'conference publication',
'book chapter': 'bibliography',
'unpublished': 'article'
}
tp = str(self.type).lower()
return type2genre.get(tp, tp) |
def _produce_author_lists(self):
"""
Parse authors string to create lists of authors.
"""
# post-process author names
self.authors = self.authors.replace(', and ', ', ')
self.authors = self.authors.replace(',and ', ', ')
self.authors = self.authors.replace(' and ', ', ')
self.authors = self.authors.rep... |
def get_publications(context, template='publications/publications.html'):
"""
Get all publications.
"""
types = Type.objects.filter(hidden=False)
publications = Publication.objects.select_related()
publications = publications.filter(external=False, type__in=types)
publications = publications.order_by('-year', '... |
def get_publication(context, id):
"""
Get a single publication.
"""
pbl = Publication.objects.filter(pk=int(id))
if len(pbl) < 1:
return ''
pbl[0].links = pbl[0].customlink_set.all()
pbl[0].files = pbl[0].customfile_set.all()
return render_template(
'publications/publication.html', context['request'], {... |
def get_publication_list(context, list, template='publications/publications.html'):
"""
Get a publication list.
"""
list = List.objects.filter(list__iexact=list)
if not list:
return ''
list = list[0]
publications = list.publication_set.all()
publications = publications.order_by('-year', '-month', '-id')
... |
def tex_parse(string):
"""
Renders some basic TeX math to HTML.
"""
string = string.replace('{', '').replace('}', '')
def tex_replace(match):
return \
sub(r'\^(\w)', r'<sup>\1</sup>',
sub(r'\^\{(.*?)\}', r'<sup>\1</sup>',
sub(r'\_(\w)', r'<sub>\1</sub>',
sub(r'\_\{(.*?)\}', r'<sub>\1</sub>',
sub(... |
def parse(string):
"""
Takes a string in BibTex format and returns a list of BibTex entries, where
each entry is a dictionary containing the entries' key-value pairs.
@type string: string
@param string: bibliography in BibTex format
@rtype: list
@return: a list of dictionaries representing a bibliography
"""... |
def swap(self, qs):
"""
Swap the positions of this object with a reference object.
"""
try:
replacement = qs[0]
except IndexError:
# already first/last
return
if not self._valid_ordering_reference(replacement):
raise ValueEr... |
def up(self):
"""
Move this object up one position.
"""
self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('-order')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.