code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
def delete(self):
self.requester.delete(
'/{endpoint}/{id}', endpoint=self.endpoint,
id=self.id
)
return self | Delete the current :class:`InstanceResource` |
def to_dict(self):
self_dict = {}
for key, value in six.iteritems(self.__dict__):
if self.allowed_params and key in self.allowed_params:
self_dict[key] = value
return self_dict | Get a dictionary representation of :class:`InstanceResource` |
def parse(cls, requester, entry):
if not type(entry) is dict:
return entry
for key_to_parse, cls_to_parse in six.iteritems(cls.parser):
if key_to_parse in entry:
entry[key_to_parse] = cls_to_parse.parse(
requester, entry[key_to_parse]
)
return cls(requester, **entry) | Turns a JSON object into a model instance. |
def set_attribute(self, id, value, version=1):
attributes = self._get_attributes(cache=True)
formatted_id = '{0}'.format(id)
attributes['attributes_values'][formatted_id] = value
response = self.requester.patch(
'/{endpoint}/custom-attributes-values/{id}',
endpoint=self.endpoint, id=self.id,
payload={
'attributes_values': attributes['attributes_values'],
'version': version
}
)
cache_key = self.requester.get_full_url(
'/{endpoint}/custom-attributes-values/{id}',
endpoint=self.endpoint, id=self.id
)
self.requester.cache.put(cache_key, response)
return response.json() | Set attribute to a specific value
:param id: id of the attribute
:param value: value of the attribute
:param version: version of the attribute (default = 1) |
def create(self, project, name, **attrs):
attrs.update(
{
'project': project, 'name': name
}
)
return self._new_resource(payload=attrs) | Create a new :class:`CustomAttribute`.
:param project: :class:`Project` id
:param name: name of the custom attribute
:param attrs: optional attributes of the custom attributes |
def starred_projects(self):
response = self.requester.get(
'/{endpoint}/{id}/starred', endpoint=self.endpoint,
id=self.id
)
return Projects.parse(self.requester, response.json()) | Get a list of starred :class:`Project`. |
def create(self, project, email, role, **attrs):
attrs.update({'project': project, 'email': email, 'role': role})
return self._new_resource(payload=attrs) | Create a new :class:`Membership`.
:param project: :class:`Project` id
:param email: email of the :class:`Membership`
:param role: role of the :class:`Membership`
:param attrs: optional attributes of the :class:`Membership` |
def create(self, project, object_id, attached_file, **attrs):
attrs.update({'project': project, 'object_id': object_id})
if isinstance(attached_file, file):
attachment = attached_file
elif isinstance(attached_file, six.string_types):
try:
attachment = open(attached_file, 'rb')
except IOError:
raise exceptions.TaigaException(
"Attachment must be a IOBase or a path to an existing file"
)
else:
raise exceptions.TaigaException(
"Attachment must be a IOBase or a path to an existing file"
)
return self._new_resource(
files={'attached_file': attachment},
payload=attrs
) | Create a new :class:`Attachment`.
:param project: :class:`Project` id
:param object_id: id of the current object
:param ref: :class:`Task` reference
:param attached_file: file path that you want to upload
:param attrs: optional attributes for the :class:`Attachment` |
def add_task(self, subject, status, **attrs):
return Tasks(self.requester).create(
self.project, subject, status,
user_story=self.id, **attrs
) | Add a :class:`Task` to the current :class:`UserStory` and return it.
:param subject: subject of the :class:`Task`
:param status: status of the :class:`Task`
:param attrs: optional attributes for :class:`Task` |
def create(self, project, subject, **attrs):
attrs.update({'project': project, 'subject': subject})
return self._new_resource(payload=attrs) | Create a new :class:`UserStory`.
:param project: :class:`Project` id
:param subject: subject of the :class:`UserStory`
:param attrs: optional attributes of the :class:`UserStory` |
def stats(self):
response = self.requester.get(
'/{endpoint}/{id}/stats',
endpoint=self.endpoint, id=self.id
)
return response.json() | Get the stats for the current :class:`Milestone` |
def create(self, project, name, estimated_start,
estimated_finish, **attrs):
if isinstance(estimated_start, datetime.datetime):
estimated_start = estimated_start.strftime('%Y-%m-%d')
if isinstance(estimated_finish, datetime.datetime):
estimated_finish = estimated_finish.strftime('%Y-%m-%d')
attrs.update({
'project': project,
'name': name,
'estimated_start': estimated_start,
'estimated_finish': estimated_finish
})
return self._new_resource(payload=attrs) | Create a new :class:`Milestone`.
:param project: :class:`Project` id
:param name: name of the :class:`Milestone`
:param estimated_start: est. start time of the :class:`Milestone`
:param estimated_finish: est. finish time of the :class:`Milestone`
:param attrs: optional attributes of the :class:`Milestone` |
def attach(self, attached_file, **attrs):
return TaskAttachments(self.requester).create(
self.project, self.id,
attached_file, **attrs
) | Attach a file to the :class:`Task`
:param attached_file: file path to attach
:param attrs: optional attributes for the attached file |
def upvote(self):
self.requester.post(
'/{endpoint}/{id}/upvote',
endpoint=self.endpoint, id=self.id
)
return self | Upvote :class:`Issue`. |
def downvote(self):
self.requester.post(
'/{endpoint}/{id}/downvote',
endpoint=self.endpoint, id=self.id
)
return self | Downvote :class:`Issue`. |
def create(self, project, subject, priority, status,
issue_type, severity, **attrs):
attrs.update(
{
'project': project, 'subject': subject,
'priority': priority, 'status': status,
'type': issue_type, 'severity': severity
}
)
return self._new_resource(payload=attrs) | Create a new :class:`Task`.
:param project: :class:`Project` id
:param subject: subject of the :class:`Issue`
:param priority: priority of the :class:`Issue`
:param status: status of the :class:`Issue`
:param issue_type: Issue type of the :class:`Issue`
:param severity: severity of the :class:`Issue`
:param attrs: optional attributes of the :class:`Task` |
def get_task_by_ref(self, ref):
response = self.requester.get(
'/{endpoint}/by_ref?ref={task_ref}&project={project_id}',
endpoint=Task.endpoint,
task_ref=ref,
project_id=self.id
)
return Task.parse(self.requester, response.json()) | Get a :class:`Task` by ref.
:param ref: :class:`Task` reference |
def get_userstory_by_ref(self, ref):
response = self.requester.get(
'/{endpoint}/by_ref?ref={us_ref}&project={project_id}',
endpoint=UserStory.endpoint,
us_ref=ref,
project_id=self.id
)
return UserStory.parse(self.requester, response.json()) | Get a :class:`UserStory` by ref.
:param ref: :class:`UserStory` reference |
def get_issue_by_ref(self, ref):
response = self.requester.get(
'/{endpoint}/by_ref?ref={us_ref}&project={project_id}',
endpoint=Issue.endpoint,
us_ref=ref,
project_id=self.id
)
return Issue.parse(self.requester, response.json()) | Get a :class:`Issue` by ref.
:param ref: :class:`Issue` reference |
def issues_stats(self):
response = self.requester.get(
'/{endpoint}/{id}/issues_stats',
endpoint=self.endpoint, id=self.id
)
return response.json() | Get stats for issues of the project |
def like(self):
self.requester.post(
'/{endpoint}/{id}/like',
endpoint=self.endpoint, id=self.id
)
return self | Like the project |
def unlike(self):
self.requester.post(
'/{endpoint}/{id}/unlike',
endpoint=self.endpoint, id=self.id
)
return self | Unlike the project |
def star(self):
warnings.warn(
"Deprecated! Update Taiga and use .like() instead",
DeprecationWarning
)
self.requester.post(
'/{endpoint}/{id}/star',
endpoint=self.endpoint, id=self.id
)
return self | Stars the project
.. deprecated:: 0.8.5
Update Taiga and use like instead |
def add_membership(self, email, role, **attrs):
return Memberships(self.requester).create(
self.id, email, role, **attrs
) | Add a Membership to the project and returns a
:class:`Membership` resource.
:param email: email for :class:`Membership`
:param role: role for :class:`Membership`
:param attrs: role for :class:`Membership`
:param attrs: optional :class:`Membership` attributes |
def add_user_story(self, subject, **attrs):
return UserStories(self.requester).create(
self.id, subject, **attrs
) | Adds a :class:`UserStory` and returns a :class:`UserStory` resource.
:param subject: subject of the :class:`UserStory`
:param attrs: other :class:`UserStory` attributes |
def import_user_story(self, subject, status, **attrs):
return UserStories(self.requester).import_(
self.id, subject, status, **attrs
) | Import an user story and returns a :class:`UserStory` resource.
:param subject: subject of the :class:`UserStory`
:param status: status of the :class:`UserStory`
:param attrs: optional :class:`UserStory` attributes |
def add_issue(self, subject, priority, status,
issue_type, severity, **attrs):
return Issues(self.requester).create(
self.id, subject, priority, status,
issue_type, severity, **attrs
) | Adds a Issue and returns a :class:`Issue` resource.
:param subject: subject of the :class:`Issue`
:param priority: priority of the :class:`Issue`
:param priority: status of the :class:`Issue`
:param issue_type: type of the :class:`Issue`
:param severity: severity of the :class:`Issue`
:param attrs: other :class:`Issue` attributes |
def import_issue(self, subject, priority, status,
issue_type, severity, **attrs):
return Issues(self.requester).import_(
self.id, subject, priority, status,
issue_type, severity, **attrs
) | Import and issue and returns a :class:`Issue` resource.
:param subject: subject of :class:`Issue`
:param priority: priority of :class:`Issue`
:param status: status of :class:`Issue`
:param issue_type: issue type of :class:`Issue`
:param severity: severity of :class:`Issue`
:param attrs: optional :class:`Issue` attributes |
def add_milestone(self, name, estimated_start, estimated_finish, **attrs):
return Milestones(self.requester).create(
self.id, name, estimated_start,
estimated_finish, **attrs
) | Add a Milestone to the project and returns a :class:`Milestone` object.
:param name: name of the :class:`Milestone`
:param estimated_start: estimated start time of the
:class:`Milestone`
:param estimated_finish: estimated finish time of the
:class:`Milestone`
:param attrs: optional attributes for :class:`Milestone` |
def import_milestone(self, name, estimated_start, estimated_finish,
**attrs):
return Milestones(self.requester).import_(
self.id, name, estimated_start,
estimated_finish, **attrs
) | Import a Milestone and returns a :class:`Milestone` object.
:param name: name of the :class:`Milestone`
:param estimated_start: estimated start time of the
:class:`Milestone`
:param estimated_finish: estimated finish time of the
:class:`Milestone`
:param attrs: optional attributes for :class:`Milestone` |
def list_milestones(self, **queryparams):
return Milestones(self.requester).list(project=self.id, **queryparams) | Get the list of :class:`Milestone` resources for the project. |
def add_point(self, name, value, **attrs):
return Points(self.requester).create(self.id, name, value, **attrs) | Add a Point to the project and returns a :class:`Point` object.
:param name: name of the :class:`Point`
:param value: value of the :class:`Point`
:param attrs: optional attributes for :class:`Point` |
def add_task_status(self, name, **attrs):
return TaskStatuses(self.requester).create(self.id, name, **attrs) | Add a Task status to the project and returns a
:class:`TaskStatus` object.
:param name: name of the :class:`TaskStatus`
:param attrs: optional attributes for :class:`TaskStatus` |
def import_task(self, subject, status, **attrs):
return Tasks(self.requester).import_(
self.id, subject, status, **attrs
) | Import a Task and return a :class:`Task` object.
:param subject: subject of the :class:`Task`
:param status: status of the :class:`Task`
:param attrs: optional attributes for :class:`Task` |
def add_user_story_status(self, name, **attrs):
return UserStoryStatuses(self.requester).create(self.id, name, **attrs) | Add a UserStory status to the project and returns a
:class:`UserStoryStatus` object.
:param name: name of the :class:`UserStoryStatus`
:param attrs: optional attributes for :class:`UserStoryStatus` |
def add_issue_type(self, name, **attrs):
return IssueTypes(self.requester).create(self.id, name, **attrs) | Add a Issue type to the project and returns a
:class:`IssueType` object.
:param name: name of the :class:`IssueType`
:param attrs: optional attributes for :class:`IssueType` |
def add_severity(self, name, **attrs):
return Severities(self.requester).create(self.id, name, **attrs) | Add a Severity to the project and returns a :class:`Severity` object.
:param name: name of the :class:`Severity`
:param attrs: optional attributes for :class:`Severity` |
def add_role(self, name, **attrs):
return Roles(self.requester).create(self.id, name, **attrs) | Add a Role to the project and returns a :class:`Role` object.
:param name: name of the :class:`Role`
:param attrs: optional attributes for :class:`Role` |
def add_priority(self, name, **attrs):
return Priorities(self.requester).create(self.id, name, **attrs) | Add a Priority to the project and returns a :class:`Priority` object.
:param name: name of the :class:`Priority`
:param attrs: optional attributes for :class:`Priority` |
def add_issue_status(self, name, **attrs):
return IssueStatuses(self.requester).create(self.id, name, **attrs) | Add a Issue status to the project and returns a
:class:`IssueStatus` object.
:param name: name of the :class:`IssueStatus`
:param attrs: optional attributes for :class:`IssueStatus` |
def add_wikipage(self, slug, content, **attrs):
return WikiPages(self.requester).create(
self.id, slug, content, **attrs
) | Add a Wiki page to the project and returns a :class:`WikiPage` object.
:param name: name of the :class:`WikiPage`
:param attrs: optional attributes for :class:`WikiPage` |
def import_wikipage(self, slug, content, **attrs):
return WikiPages(self.requester).import_(
self.id, slug, content, **attrs
) | Import a Wiki page and return a :class:`WikiPage` object.
:param slug: slug of the :class:`WikiPage`
:param content: content of the :class:`WikiPage`
:param attrs: optional attributes for :class:`Task` |
def add_wikilink(self, title, href, **attrs):
return WikiLinks(self.requester).create(self.id, title, href, **attrs) | Add a Wiki link to the project and returns a :class:`WikiLink` object.
:param title: title of the :class:`WikiLink`
:param href: href of the :class:`WikiLink`
:param attrs: optional attributes for :class:`WikiLink` |
def import_wikilink(self, title, href, **attrs):
return WikiLinks(self.requester).import_(self.id, title, href, **attrs) | Import a Wiki link and return a :class:`WikiLink` object.
:param title: title of the :class:`WikiLink`
:param href: href of the :class:`WikiLink`
:param attrs: optional attributes for :class:`WikiLink` |
def add_issue_attribute(self, name, **attrs):
return IssueAttributes(self.requester).create(
self.id, name, **attrs
) | Add a new Issue attribute and return a :class:`IssueAttribute` object.
:param name: name of the :class:`IssueAttribute`
:param attrs: optional attributes for :class:`IssueAttribute` |
def add_task_attribute(self, name, **attrs):
return TaskAttributes(self.requester).create(
self.id, name, **attrs
) | Add a new Task attribute and return a :class:`TaskAttribute` object.
:param name: name of the :class:`TaskAttribute`
:param attrs: optional attributes for :class:`TaskAttribute` |
def add_user_story_attribute(self, name, **attrs):
return UserStoryAttributes(self.requester).create(
self.id, name, **attrs
) | Add a new User Story attribute and return a
:class:`UserStoryAttribute` object.
:param name: name of the :class:`UserStoryAttribute`
:param attrs: optional attributes for :class:`UserStoryAttribute` |
def add_webhook(self, name, url, key, **attrs):
return Webhooks(self.requester).create(
self.id, name, url, key, **attrs
) | Add a new Webhook and return a :class:`Webhook` object.
:param name: name of the :class:`Webhook`
:param url: payload url of the :class:`Webhook`
:param key: secret key of the :class:`Webhook`
:param attrs: optional attributes for :class:`Webhook` |
def create(self, name, description, **attrs):
attrs.update({'name': name, 'description': description})
return self._new_resource(payload=attrs) | Create a new :class:`Project`
:param name: name of the :class:`Project`
:param description: description of the :class:`Project`
:param attrs: optional attributes for :class:`Project` |
def get_by_slug(self, slug):
response = self.requester.get(
'/{endpoint}/by_slug?slug={slug}',
endpoint=self.instance.endpoint,
slug=slug
)
return self.instance.parse(self.requester, response.json()) | Get a :class:`Project` by slug
:param slug: the slug of the :class:`Project` |
def create(self, project, slug, content, **attrs):
attrs.update({'project': project, 'slug': slug, 'content': content})
return self._new_resource(payload=attrs) | create a new :class:`WikiPage`
:param project: :class:`Project` id
:param slug: slug of the wiki page
:param content: content of the wiki page
:param attrs: optional attributes for the :class:`WikiPage` |
def create(self, project, title, href, **attrs):
attrs.update({'project': project, 'title': title, 'href': href})
return self._new_resource(payload=attrs) | Create a new :class:`WikiLink`
:param project: :class:`Project` id
:param title: title of the wiki link
:param href: href for the wiki link
:param attrs: optional attributes for the :class:`WikiLink` |
def get(self, resource_id):
response = self.requester.get(
'/{endpoint}/{entity}/{id}',
endpoint=self.endpoint, entity=self.entity, id=resource_id,
paginate=False
)
return response.json() | Get a history element
:param resource_id: ... |
def delete_comment(self, resource_id, ent_id):
self.requester.post(
'/{endpoint}/{entity}/{id}/delete_comment?id={ent_id}',
endpoint=self.endpoint, entity=self.entity,
id=resource_id, ent_id=ent_id
) | Delete a comment
:param resource_id: ...
:param ent_id: ... |
def parse(cls, value):
if is_list_annotation(cls):
if not isinstance(value, list):
raise TypeError('Could not parse {} because value is not a list'.format(cls))
return [parse(cls.__args__[0], o) for o in value]
else:
return GenericParser(cls, ModelProviderImpl()).parse(value) | Takes a class and a dict and try to build an instance of the class
:param cls: The class to parse
:param value: either a dict, a list or a scalar value |
def dump(obj, fp, **kwargs):
kwargs['default'] = serialize
return json.dump(obj, fp, **kwargs) | wrapper for :py:func:`json.dump` |
def load(cls, fp, **kwargs):
json_obj = json.load(fp, **kwargs)
return parse(cls, json_obj) | wrapper for :py:func:`json.load` |
def loads(cls, s, **kwargs):
json_obj = json.loads(s, **kwargs)
return parse(cls, json_obj) | wrapper for :py:func:`json.loads` |
def convert_ensembl_to_entrez(self, ensembl):
if 'ENST' in ensembl:
pass
else:
raise (IndexError)
# Submit resquest to NCBI eutils/Gene database
server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + self.options + "&db=gene&term={0}".format(
ensembl)
r = requests.get(server, headers={"Content-Type": "text/xml"})
if not r.ok:
r.raise_for_status()
sys.exit()
# Process Request
response = r.text
info = xmltodict.parse(response)
try:
geneId = info['eSearchResult']['IdList']['Id']
except TypeError:
raise (TypeError)
return geneId | Convert Ensembl Id to Entrez Gene Id |
def convert_entrez_to_uniprot(self, entrez):
server = "http://www.uniprot.org/uniprot/?query=%22GENEID+{0}%22&format=xml".format(entrez)
r = requests.get(server, headers={"Content-Type": "text/xml"})
if not r.ok:
r.raise_for_status()
sys.exit()
response = r.text
info = xmltodict.parse(response)
try:
data = info['uniprot']['entry']['accession'][0]
return data
except TypeError:
data = info['uniprot']['entry'][0]['accession'][0]
return data | Convert Entrez Id to Uniprot Id |
def convert_uniprot_to_entrez(self, uniprot):
# Submit request to NCBI eutils/Gene Database
server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?" + self.options + "&db=gene&term={0}".format(
uniprot)
r = requests.get(server, headers={"Content-Type": "text/xml"})
if not r.ok:
r.raise_for_status()
sys.exit()
# Process Request
response = r.text
info = xmltodict.parse(response)
geneId = info['eSearchResult']['IdList']['Id']
# check to see if more than one result is returned
# if you have more than more result then check which Entrez Id returns the same uniprot Id entered.
if len(geneId) > 1:
for x in geneId:
c = self.convert_entrez_to_uniprot(x)
c = c.lower()
u = uniprot.lower()
if c == u:
return x
else:
return geneId | Convert Uniprot Id to Entrez Id |
def convert_accession_to_taxid(self, accessionid):
# Submit request to NCBI eutils/Taxonomy Database
server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?" + self.options + "&db=nuccore&id={0}&retmode=xml".format(
accessionid)
r = requests.get(server, headers={"Content-Type": "text/xml"})
if not r.ok:
r.raise_for_status()
sys.exit()
# Process Request
response = r.text
records = xmltodict.parse(response)
try:
for i in records['GBSet']['GBSeq']['GBSeq_feature-table']['GBFeature']['GBFeature_quals']['GBQualifier']:
for key, value in i.items():
if value == 'db_xref':
taxid = i['GBQualifier_value']
taxid = taxid.split(':')[1]
return taxid
except:
for i in records['GBSet']['GBSeq']['GBSeq_feature-table']['GBFeature'][0]['GBFeature_quals']['GBQualifier']:
for key, value in i.items():
if value == 'db_xref':
taxid = i['GBQualifier_value']
taxid = taxid.split(':')[1]
return taxid
return | Convert Accession Id to Tax Id |
def convert_symbol_to_entrezid(self, symbol):
entrezdict = {}
server = "http://rest.genenames.org/fetch/symbol/{0}".format(symbol)
r = requests.get(server, headers={"Content-Type": "application/json"})
if not r.ok:
r.raise_for_status()
sys.exit()
response = r.text
info = xmltodict.parse(response)
for data in info['response']['result']['doc']['str']:
if data['@name'] == 'entrez_id':
entrezdict[data['@name']] = data['#text']
if data['@name'] == 'symbol':
entrezdict[data['@name']] = data['#text']
return entrezdict | Convert Symbol to Entrez Gene Id |
def log_local_message(message_format, *args):
prefix = '{} {}'.format(color('INFO', fg=248), color('request', fg=5))
message = message_format % args
sys.stderr.write('{} {}\n'.format(prefix, message)) | Log a request so that it matches our local log format. |
def serialize(obj):
if isinstance(obj, list):
return [serialize(o) for o in obj]
return GenericSerializer(ModelProviderImpl()).serialize(obj) | Takes a object and produces a dict-like representation
:param obj: the object to serialize |
def of(self, *indented_blocks) -> "CodeBlock":
if self.closed_by is None:
self.expects_body_or_pass = True
for block in indented_blocks:
if block is not None:
self._blocks.append((1, block))
# Finalise it so that we cannot add more sub-blocks to this block.
self.finalise()
return self | By default, marks the block as expecting an indented "body" blocks of which are then supplied
as arguments to this method.
Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones,
this will generate a "pass" statement as the body. If there is a "closed_by" specified, then
that will be used on the same indentation level as the opening of the block.
After all the arguments have been handled, this block is marked as finalised and no more blocks
can be appended to it.
None blocks are skipped.
Returns the block itself. |
def add(self, *blocks, indentation=0) -> "CodeBlock":
for block in blocks:
if block is not None:
self._blocks.append((indentation, block))
return self | Adds sub-blocks at the specified indentation level, which defaults to 0.
Nones are skipped.
Returns the parent block itself, useful for chaining. |
def get_blocks(self):
self.process_triple_quoted_doc_string()
num_indented_blocks = 0
for indentation, block in self._blocks:
if indentation > 0:
num_indented_blocks += 1
yield indentation, block
if self.expects_body_or_pass and num_indented_blocks == 0:
yield 1, "pass"
return | Override this method for custom content, but then you are responsible for:
- generating doc string (you can call self.process_triple_quoted_doc_string())
- generating "pass" on empty body |
def to_code(self, context: Context =None):
# Do not override this method!
context = context or Context()
for imp in self.imports:
if imp not in context.imports:
context.imports.append(imp)
counter = Counter()
lines = list(self.to_lines(context=context, counter=counter))
if counter.num_indented_non_doc_blocks == 0:
if self.expects_body_or_pass:
lines.append(" pass")
elif self.closed_by:
lines[-1] += self.closed_by
else:
if self.closed_by:
lines.append(self.closed_by)
return join_lines(*lines) + self._suffix | Generate the code and return it as a string. |
def exec(self, globals=None, locals=None):
if locals is None:
locals = {}
builtins.exec(self.to_code(), globals, locals)
return locals | Execute simple code blocks.
Do not attempt this on modules or other blocks where you have
imports as they won't work.
Instead write the code to a file and use runpy.run_path() |
def block(self, *blocks, **kwargs) -> "CodeBlock":
assert "name" not in kwargs
kwargs.setdefault("code", self)
code = CodeBlock(**kwargs)
for block in blocks:
if block is not None:
code._blocks.append((0, block))
return code | Build a basic code block.
Positional arguments should be instances of CodeBlock or strings.
All code blocks passed as positional arguments are added at indentation level 0.
None blocks are skipped. |
def dict_from_locals(self, name, params: List[Parameter], not_specified_literal=Constants.VALUE_NOT_SET):
code = self.block(f"{name} = {{}}")
for p in params:
code.add(
self.block(f"if {p.name} is not {not_specified_literal}:").of(
f"{name}[{p.name!r}] = {p.name}"
),
)
return code | Generate code for a dictionary of locals whose value is not the specified literal. |
def import_generated_autoboto(self):
if str(self.config.build_dir) not in sys.path:
sys.path.append(str(self.config.build_dir))
return importlib.import_module(self.config.target_package) | Imports the autoboto package generated in the build directory (not target_dir).
For example:
autoboto = botogen.import_generated_autoboto() |
def import_generated_autoboto_module(self, name):
if str(self.config.build_dir) not in sys.path:
sys.path.append(str(self.config.build_dir))
return importlib.import_module(f"{self.config.target_package}.{name}") | Imports a module from the generated autoboto package in the build directory (not target_dir).
For example, to import autoboto.services.s3.shapes, call:
botogen.import_generated_autoboto_module("services.s3.shapes") |
def search(self, project, text=''):
result = self.raw_request.get(
'search', query={'project': project, 'text': text}
)
result = result.json()
search_result = SearchResult()
search_result.tasks = self.tasks.parse_list(result['tasks'])
search_result.issues = self.issues.parse_list(result['issues'])
search_result.user_stories = self.user_stories.parse_list(
result['userstories']
)
search_result.wikipages = self.wikipages.parse_list(
result['wikipages']
)
return search_result | Search in your Taiga.io instance
:param project: the project id
:param text: the query of your search |
def auth(self, username, password):
headers = {
'Content-type': 'application/json'
}
payload = {
'type': self.auth_type,
'username': username,
'password': password
}
try:
full_url = utils.urljoin(self.host, '/api/v1/auth')
response = requests.post(
full_url,
data=json.dumps(payload),
headers=headers,
verify=self.tls_verify
)
except RequestException:
raise exceptions.TaigaRestException(
full_url, 400,
'NETWORK ERROR', 'POST'
)
if response.status_code != 200:
raise exceptions.TaigaRestException(
full_url,
response.status_code,
response.text,
'POST'
)
self.token = response.json()['auth_token']
self.raw_request = RequestMaker('/api/v1', self.host, self.token,
'Bearer', self.tls_verify)
self._init_resources() | Authenticate you
:param username: your username
:param password: your password |
def auth_app(self, app_id, app_secret, auth_code, state=''):
headers = {
'Content-type': 'application/json'
}
payload = {
'application': app_id,
'auth_code': auth_code,
'state': state
}
try:
full_url = utils.urljoin(
self.host,
'/api/v1/application-tokens/validate'
)
response = requests.post(
full_url,
data=json.dumps(payload),
headers=headers,
verify=self.tls_verify
)
except RequestException:
raise exceptions.TaigaRestException(
full_url, 400,
'NETWORK ERROR', 'POST'
)
if response.status_code != 200:
raise exceptions.TaigaRestException(
full_url,
response.status_code,
response.text,
'POST'
)
cyphered_token = response.json().get('cyphered_token', '')
if cyphered_token:
from jwkest.jwk import SYMKey
from jwkest.jwe import JWE
sym_key = SYMKey(key=app_secret, alg='A128KW')
data, success = JWE().decrypt(cyphered_token, keys=[sym_key]), True
if isinstance(data, tuple):
data, success = data
try:
self.token = json.loads(data.decode('utf-8')).get('token', None)
except ValueError: # pragma: no cover
self.token = None
if not success:
self.token = None
else:
self.token = None
if self.token is None:
raise exceptions.TaigaRestException(
full_url, 400,
'INVALID TOKEN', 'POST'
)
self.raw_request = RequestMaker('/api/v1', self.host, self.token,
'Application', self.tls_verify)
self._init_resources() | Authenticate an app
:param app_id: the app id
:param app_secret: the app secret
:param auth_code: the app auth code |
def sorted_members(self):
members = collections.OrderedDict()
required_names = self.metadata.get("required", ())
for name, shape in self.members.items():
members[name] = AbShapeMember(name=name, shape=shape, is_required=name in required_names)
if self.is_output_shape:
# ResponseMetadata is the first member for all output shapes.
yield AbShapeMember(
name="ResponseMetadata",
shape=self._shape_resolver.get_shape_by_name("ResponseMetadata"),
is_required=True,
)
yield from sorted(members.values(), key=lambda m: not m.is_required) | Iterate over sorted members of shape in the same order in which
the members are declared except yielding the required members before
any optional members. |
def update(self):
self.frontends = []
self.backends = []
self.listeners = []
csv = [ l for l in self._fetch().strip(' #').split('\n') if l ]
if self.failed:
return
#read fields header to create keys
self.fields = [ f for f in csv.pop(0).split(',') if f ]
#add frontends and backends first
for line in csv:
service = HAProxyService(self.fields, line.split(','), self.name)
if service.svname == 'FRONTEND':
self.frontends.append(service)
elif service.svname == 'BACKEND':
service.listeners = []
self.backends.append(service)
else:
self.listeners.append(service)
#now add listener names to corresponding backends
for listener in self.listeners:
for backend in self.backends:
if backend.iid == listener.iid:
backend.listeners.append(listener)
self.last_update = datetime.utcnow() | Fetch and parse stats |
def _decode(value):
if value.isdigit():
return int(value)
if isinstance(value, bytes):
return value.decode('utf-8')
else:
return value | decode byte strings and convert to int where needed |
def markdown(text, renderer=None, **options):
ext, rndr = make_flags(**options)
if renderer:
md = misaka.Markdown(renderer,ext)
result = md(text)
else:
result = misaka.html(text, extensions=ext, render_flags=rndr)
if options.get("smartypants"):
result = misaka.smartypants(result)
return Markup(result) | Parses the provided Markdown-formatted text into valid HTML, and returns
it as a :class:`flask.Markup` instance.
:param text: Markdown-formatted text to be rendered into HTML
:param renderer: A custom misaka renderer to be used instead of the default one
:param options: Additional options for customizing the default renderer
:return: A :class:`flask.Markup` instance representing the rendered text |
def render(self, text, **overrides):
options = self.defaults
if overrides:
options = copy(options)
options.update(overrides)
return markdown(text, self.renderer, **options) | It delegates to the :func:`markdown` function, passing any default
options or renderer set in the :meth:`__init__` method.
The ``markdown`` template filter calls this method.
:param text: Markdown-formatted text to be rendered to HTML
:param overrides: Additional options which may override the defaults
:return: A :class:`flask.Markup` instance representing the rendered text |
def caseinsensitive(cls):
if not issubclass(cls, Enum):
raise TypeError('caseinsensitive decorator can only be applied to subclasses of enum.Enum')
enum_options = getattr(cls, PYCKSON_ENUM_OPTIONS, {})
enum_options[ENUM_CASE_INSENSITIVE] = True
setattr(cls, PYCKSON_ENUM_OPTIONS, enum_options)
return cls | Annotation function to set an Enum to be case insensitive on parsing |
def win32_utf8_argv():
try:
from ctypes import POINTER, byref, cdll, c_int, windll
from ctypes.wintypes import LPCWSTR, LPWSTR
GetCommandLineW = cdll.kernel32.GetCommandLineW
GetCommandLineW.argtypes = []
GetCommandLineW.restype = LPCWSTR
CommandLineToArgvW = windll.shell32.CommandLineToArgvW
CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
CommandLineToArgvW.restype = POINTER(LPWSTR)
cmd = GetCommandLineW()
argc = c_int(0)
argv = CommandLineToArgvW(cmd, byref(argc))
if argc.value > 0:
# Remove Python executable if present
if argc.value - len(sys.argv) == 1:
start = 1
else:
start = 0
return [argv[i].encode('utf-8') for i in
range(start, argc.value)]
except Exception:
pass | Uses shell32.GetCommandLineArgvW to get sys.argv as a list of UTF-8
strings.
Versions 2.5 and older of Python don't support Unicode in sys.argv on
Windows, with the underlying Windows API instead replacing multi-byte
characters with '?'.
Returns None on failure.
Example usage:
>>> def main(argv=None):
... if argv is None:
... argv = win32_utf8_argv() or sys.argv
... |
def encrypt_ascii(self, data, key=None, v=None, extra_bytes=0,
digest="hex"):
digests = {"hex": binascii.b2a_hex,
"base64": binascii.b2a_base64,
"hqx": binascii.b2a_hqx}
digestor = digests.get(digest)
if not digestor:
TripleSecError(u"Digestor not supported.")
binary_result = self.encrypt(data, key, v, extra_bytes)
result = digestor(binary_result)
return result | Encrypt data and return as ascii string. Hexadecimal digest as default.
Avaiable digests:
hex: Hexadecimal
base64: Base 64
hqx: hexbin4 |
def decrypt_ascii(self, ascii_string, key=None, digest="hex"):
digests = {"hex": binascii.a2b_hex,
"base64": binascii.a2b_base64,
"hqx": binascii.a2b_hqx}
digestor = digests.get(digest)
if not digestor:
TripleSecError(u"Digestor not supported.")
binary_string = digestor(ascii_string)
result = self.decrypt(binary_string, key)
return result | Receive ascii string and return decrypted data.
Avaiable digests:
hex: Hexadecimal
base64: Base 64
hqx: hexbin4 |
def resolve_movie(self, title, year=None):
r = self.search_movie(title)
return self._match_results(r, title, year) | Tries to find a movie with a given title and year |
def resolve_tv_show(self, title, year=None):
r = self.search_tv_show(title)
return self._match_results(r, title, year) | Tries to find a movie with a given title and year |
def load_heroes():
filename = os.path.join(os.path.dirname(__file__), "data", "heroes.json")
with open(filename) as f:
heroes = json.loads(f.read())["result"]["heroes"]
for hero in heroes:
HEROES_CACHE[hero["id"]] = hero | Load hero details from JSON file into memoy |
def load_items():
filename = os.path.join(os.path.dirname(__file__), "data", "items.json")
with open(filename) as f:
items = json.loads(f.read())["result"]["items"]
for item in items:
ITEMS_CACHE[item["id"]] = item | Load item details fom JSON file into memory |
def added(self, context):
context.cmd_tree = self._build_cmd_tree(self.command)
context.cmd_toplevel = context.cmd_tree.cmd_obj
# Collect spices from the top-level command
for spice in context.cmd_toplevel.get_cmd_spices():
context.bowl.add_spice(spice) | Ingredient method called before anything else.
Here this method just builds the full command tree and stores it inside
the context as the ``cmd_tree`` attribute. The structure of the tree is
explained by the :func:`build_cmd_tree()` function. |
def _build_cmd_tree(self, cmd_cls, cmd_name=None):
if isinstance(cmd_cls, type):
cmd_obj = cmd_cls()
else:
cmd_obj = cmd_cls
if cmd_name is None:
cmd_name = cmd_obj.get_cmd_name()
return cmd_tree_node(cmd_name, cmd_obj, tuple([
self._build_cmd_tree(subcmd_cls, subcmd_name)
for subcmd_name, subcmd_cls in cmd_obj.get_sub_commands()])) | Build a tree of commands.
:param cmd_cls:
The Command class or object to start with.
:param cmd_name:
Hard-coded name of the command (can be None for auto-detection)
:returns:
A tree structure represented as tuple
``(cmd_obj, cmd_name, children)``
Where ``cmd_obj`` is a Command instance, cmd_name is its name, if
any (it might be None) and ``children`` is a tuple of identical
tuples.
Note that command name auto-detection relies on
:meth:`guacamole.recipes.cmd.Command.get_cmd_name()`.
Let's look at a simple git-like example::
>>> from guacamole import Command
>>> class git_log(Command):
>>> pass
>>> class git_stash_list(Command):
>>> pass
>>> class git_stash(Command):
>>> sub_commands = (('list', git_stash_list),)
>>> class git(Command):
>>> sub_commands = (('log', git_log),
>>> ('stash', git_stash))
>>> build_cmd_tree(git)
(None, '<git>', (
('log', <git_log>, ()),
('stash', <git_stash>, (
('list', <git_stash_list>, ()),),),),) |
def debug_dump(message, file_prefix="dump"):
global index
index += 1
with open("%s_%s.dump" % (file_prefix, index), 'w') as f:
f.write(message.SerializeToString())
f.close() | Utility while developing to dump message data to play with in the
interpreter |
def get_side_attr(attr, invert, player):
t = player.team
if invert:
t = not player.team
return getattr(player, "%s_%s" % ("goodguy" if t else "badguy", attr)) | Get a player attribute that depends on which side the player is on.
A creep kill for a radiant hero is a badguy_kill, while a creep kill
for a dire hero is a goodguy_kill. |
def creep_kill(self, target, timestamp):
self.creep_kill_types[target] += 1
matched = False
for k, v in self.creep_types.iteritems():
if target.startswith(k):
matched = True
setattr(self, v, getattr(self, v) + 1)
break
if not matched:
print('> unhandled creep type'.format(target)) | A creep was tragically killed. Need to split this into radiant/dire
and neutrals |
def calculate_kills(self):
aegises = deque(self.aegis)
next_aegis = aegises.popleft() if aegises else None
aegis_expires = None
active_aegis = None
real_kills = []
for kill in self.kills:
if next_aegis and next_aegis[0] < kill["tick"]:
active_aegis = next_aegis[1]
aegis_expires = next_aegis[0] + 1800 * 10 # 10 minutes
self.indexed_players[active_aegis].aegises += 1
next_aegis = aegises.popleft() if aegises else None
elif aegis_expires and kill["tick"] > aegis_expires:
active_aegis = None
aegis_expires = None
source = kill["source"]
target = kill["target"]
timestamp = kill["timestamp"]
if active_aegis == self.heroes[target].index:
#This was an aegis kill
active_aegis = None
aegis_expires = None
self.heroes[target].aegis_deaths += 1
else:
real_kills.append(kill)
self.heroes[target].add_death(source, timestamp)
if target != source:
#Don't count a deny as a kill
self.heroes[source].add_kill(target, timestamp)
self.kills = real_kills | At the end of the game calculate kills/deaths, taking aegis into account
This has to be done at the end when we have a playerid : hero map |
def parse_say_text(self, event):
if event.chat and event.format == "DOTA_Chat_All":
self.chatlog.append((event.prefix, event.text)) | All chat |
def parse_dota_um(self, event):
if event.type == dota_usermessages_pb2.CHAT_MESSAGE_AEGIS:
self.aegis.append((self.tick, event.playerid_1)) | The chat messages that arrive when certain events occur.
The most useful ones are CHAT_MESSAGE_RUNE_PICKUP,
CHAT_MESSAGE_RUNE_BOTTLE, CHAT_MESSAGE_GLYPH_USED,
CHAT_MESSAGE_TOWER_KILL |
def parse_player_info(self, player):
if not player.ishltv:
self.player_info[player.name] = {
"user_id": player.userID,
"guid": player.guid,
"bot": player.fakeplayer,
} | Parse a PlayerInfo struct. This arrives before a FileInfo message |
def parse_file_info(self, file_info):
self.info["playback_time"] = file_info.playback_time
self.info["match_id"] = file_info.game_info.dota.match_id
self.info["game_mode"] = file_info.game_info.dota.game_mode
self.info["game_winner"] = file_info.game_info.dota.game_winner
for index, player in enumerate(file_info.game_info.dota.player_info):
p = self.heroes[player.hero_name]
p.name = player.player_name
p.index = index
p.team = 0 if index < 5 else 1
self.indexed_players[index] = p
self.info["players"][player.player_name] = p | The CDemoFileInfo contains our winners as well as the length of the
demo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.