members = self.get_members_json(self.base_uri,<EOL>query_params=query_params)<EOL>members_list = []<EOL>for member_json in members:<EOL><INDENT>members_list.append(self.create_member(member_json))<EOL><DEDENT>return members_list<EOL>

Get Members attached to this board. Returns a list of Member objects.

Returns:
    list(Member): The members attached to this board


organisation_json = self.get_organisations_json(<EOL>self.base_uri, query_params=query_params)<EOL>return self.create_organisation(organisation_json)<EOL>

Get the Organisation for this board. Returns Organisation object.

Returns:
    list(Organisation): The organisation attached to this board


board_json = self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>http_method='<STR_LIT>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_board(board_json)<EOL>

Update this board's information. Returns a new board.


list_json = self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_list(list_json)<EOL>

Create a list for a board. Returns a new List object.


list_json = self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_label(list_json)<EOL>

Create a label for a board. Returns a new Label object.


def add_member_by_id(self, member_id, membership_type='<STR_LIT>'):

return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>' % member_id,<EOL>http_method='<STR_LIT>',<EOL>query_params={<EOL>'<STR_LIT:type>': membership_type<EOL>}<EOL>)<EOL>

Add a member to the board using the id. Membership type can be
normal or admin. Returns JSON of all members if successful or raises an
Unauthorised exception if not.


def add_member(self, email, fullname, membership_type='<STR_LIT>'):

return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT>',<EOL>query_params={<EOL>'<STR_LIT:email>': email,<EOL>'<STR_LIT>': fullname,<EOL>'<STR_LIT:type>': membership_type<EOL>}<EOL>)<EOL>

Add a member to the board. Membership type can be normal or admin.
Returns JSON of all members if successful or raises an Unauthorised
exception if not.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>' % member_id,<EOL>http_method='<STR_LIT>'<EOL>)<EOL>

Remove a member from the organisation.Returns JSON of all members if
successful or raises an Unauthorised exception if not.


return self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>query_params=query_params or {}<EOL>)<EOL>

Get information for this card. Returns a dictionary of values.


board_json = self.get_board_json(self.base_uri,<EOL>query_params=query_params)<EOL>return self.create_board(board_json)<EOL>

Get board information for this card. Returns a Board object.

Returns:
    Board: The board this card is attached to


list_json = self.get_list_json(self.base_uri,<EOL>query_params=query_params)<EOL>return self.create_list(list_json)<EOL>

Get list information for this card. Returns a List object.

Returns:
    List: The list this card is attached to


checklists = self.get_checklist_json(self.base_uri,<EOL>query_params=query_params)<EOL>checklists_list = []<EOL>for checklist_json in checklists:<EOL><INDENT>checklists_list.append(self.create_checklist(checklist_json))<EOL><DEDENT>return checklists_list<EOL>

Get the checklists for this card. Returns a list of Checklist objects.

Returns:
    list(Checklist): The checklists attached to this card


Get all members attached to this card. Returns a list of Member
objects.

Returns:
    list(Member): The members attached to this card


card_json = self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>http_method='<STR_LIT>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_card(card_json)<EOL>

Update information for this card. Returns a new Card object.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params={'<STR_LIT:text>': comment_text}<EOL>)<EOL>

Adds a comment to this card by the current user.


def add_attachment(self, filename, open_file):

fields = {<EOL>'<STR_LIT>': self.client.api_key,<EOL>'<STR_LIT>': self.client.user_auth_token<EOL>}<EOL>content_type, body = self.encode_multipart_formdata(<EOL>fields=fields,<EOL>filename=filename,<EOL>file_values=open_file<EOL>)<EOL>return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>body=body,<EOL>headers={'<STR_LIT:Content-Type>': content_type},<EOL>)<EOL>


checklist_json = self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_checklist(checklist_json)<EOL>

Add a checklist to this card. Returns a Checklist object.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params=query_params or {}<EOL>)<EOL>

Add a label to this card, from a dictionary.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params={'<STR_LIT:value>': label.id}<EOL>)<EOL>


members = self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params={'<STR_LIT:value>': member_id}<EOL>)<EOL>members_list = []<EOL>for member_json in members:<EOL><INDENT>members_list.append(self.create_member(member_json))<EOL><DEDENT>return members_list<EOL>

Add a member to this card. Returns a list of Member objects.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>' + member_id,<EOL>http_method='<STR_LIT>'<EOL>)<EOL>


return self.update_card({'<STR_LIT>': '<STR_LIT:true>'})<EOL>


return self.close_card()<EOL>

Close (archive) this card. (Synonym for close_card().)


return self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>http_method='<STR_LIT>'<EOL>)<EOL>


def encode_multipart_formdata(self, fields, filename, file_values):

boundary = '<STR_LIT>'<EOL>crlf = '<STR_LIT:\r\n>'<EOL>data = []<EOL>for key in fields:<EOL><INDENT>data.append('<STR_LIT>' + boundary)<EOL>data.append('<STR_LIT>' % key)<EOL>data.append('<STR_LIT>')<EOL>data.append(fields[key])<EOL><DEDENT>data.append('<STR_LIT>' + boundary)<EOL>data.append(<EOL>'<STR_LIT>' %<EOL>filename)<EOL>data.append('<STR_LIT>' % self.get_content_type(filename))<EOL>data.append('<STR_LIT>')<EOL>data.append(file_values)<EOL>data.append('<STR_LIT>' + boundary + '<STR_LIT>')<EOL>data.append('<STR_LIT>')<EOL>data = [str(segment) for segment in data]<EOL>body = crlf.join(data)<EOL>content_type = '<STR_LIT>' % boundary<EOL>return content_type, body<EOL>

Encodes data to updload a file to Trello.
Fields is a dictionary of api_key and token. Filename is the name of
the file and file_values is the open(file).read() string.


Get information fot this organisation. Returns a dictionary of values.


boards = self.get_boards_json(self.base_uri, query_params=query_params)<EOL>boards_list = []<EOL>for board_json in boards:<EOL><INDENT>boards_list.append(self.create_board(board_json))<EOL><DEDENT>return boards_list<EOL>

Get all the boards for this organisation. Returns a list of Board s.

Returns:
    list(Board): The boards attached to this organisation


members = self.get_members_json(self.base_uri,<EOL>query_params=query_params)<EOL>members_list = []<EOL>for member_json in members:<EOL><INDENT>members_list.append(self.create_member(member_json))<EOL><DEDENT>return members_list<EOL>

Get all members attached to this organisation. Returns a list of
Member objects

Returns:
    list(Member): The members attached to this organisation


organisation_json = self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>http_method='<STR_LIT>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_organisation(organisation_json)<EOL>

Update this organisations information. Returns a new organisation
object.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>' % member_id,<EOL>http_method='<STR_LIT>'<EOL>)<EOL>

Remove a member from the organisation.Returns JSON of all members if
successful or raises an Unauthorised exception if not.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>' % member_id,<EOL>http_method='<STR_LIT>',<EOL>query_params={<EOL>'<STR_LIT:type>': membership_type<EOL>}<EOL>)<EOL>

Add a member to the board using the id. Membership type can be
normal or admin. Returns JSON of all members if successful or raises an
Unauthorised exception if not.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT>',<EOL>query_params={<EOL>'<STR_LIT:email>': email,<EOL>'<STR_LIT>': fullname,<EOL>'<STR_LIT:type>': membership_type<EOL>}<EOL>)<EOL>

Add a member to the board. Membership type can be normal or admin.
Returns JSON of all members if successful or raises an Unauthorised
exception if not.


return self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>query_params=query_params or {}<EOL>)<EOL>

Get all information for this Label. Returns a dictionary of values.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>query_params=query_params or {}<EOL>)<EOL>

Get all the items for this label. Returns a list of dictionaries.
Each dictionary has the values for an item.


label_json = self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>http_method='<STR_LIT>',<EOL>query_params={'<STR_LIT:name>': name}<EOL>)<EOL>return self.create_label(label_json)<EOL>

Update the current label's name. Returns a new Label object.


label_json = self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>http_method='<STR_LIT>',<EOL>query_params=query_params<EOL>)<EOL>return self.create_label(label_json)<EOL>

Update the current label. Returns a new Label object.


def __init__(self, trello_client, **kwargs):

super(TrelloObject, self).__init__()<EOL>self.client = trello_client<EOL>self.data = kwargs.get('<STR_LIT:data>', {})<EOL>

A Trello client, Oauth of HTTP client is required for each object.


def create_organisation(self, organisation_json, **kwargs):

return self.client.create_organisation(organisation_json, **kwargs)<EOL>

Create an Organisation object from a JSON object

Returns:
    Organisation: The organisation from the given `organisation_json`.


def create_board(self, board_json, **kwargs):

return self.client.create_board(board_json, **kwargs)<EOL>

Create Board object from a JSON object

Returns:
    Board: The board from the given `board_json`.


def create_list(self, list_json, **kwargs):

return self.client.create_list(list_json, **kwargs)<EOL>

Create List object from JSON object

Returns:
    List: The list from the given `list_json`.


def create_label(self, label_json, **kwargs):

return self.client.create_label(label_json, **kwargs)<EOL>

Create Label object from JSON object

Returns:
    Label: The label from the given `label_json`.


def create_card(self, card_json, **kwargs):

return self.client.create_card(card_json, **kwargs)<EOL>

Create a Card object from JSON object

Returns:
    Card: The card from the given `card_json`.


def create_checklist(self, checklist_json, **kwargs):

return self.client.create_checklist(checklist_json, **kwargs)<EOL>

Create a Checklist object from JSON object

Returns:
    Checklist: The checklist from the given `checklist_json`.


def create_checklist_item(self, card_id, checklist_id, checklistitem_json, **kwargs):

return self.client.create_checklist_item(card_id, checklist_id, checklistitem_json, **kwargs)<EOL>

Create a ChecklistItem object from JSON object


def create_member(self, member_json, **kwargs):

return self.client.create_member(member_json, **kwargs)<EOL>

Create a Member object from JSON object

Returns:
    Member: The member from the given `member_json`.


def get_authorisation_url(self, application_name, token_expire='<STR_LIT>'):

query_params = {<EOL>'<STR_LIT:name>': application_name,<EOL>'<STR_LIT>': token_expire,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>authorisation_url = self.build_uri(<EOL>path='<STR_LIT>',<EOL>query_params=self.add_authorisation(query_params)<EOL>)<EOL>print('<STR_LIT>'<EOL>'<STR_LIT>', authorisation_url)<EOL>return authorisation_url<EOL>

Returns a URL that needs to be opened in a browser to retrieve an
access token.


dispatcher = singledispatch(method)<EOL>def wrapper(*args, **kw):<EOL><INDENT>return dispatcher.dispatch(args[<NUM_LIT:1>].__class__)(*args, **kw)<EOL><DEDENT>wrapper.register = dispatcher.register<EOL>update_wrapper(wrapper, dispatcher)<EOL>return wrapper<EOL>

Enable singledispatch for class methods.

See http://stackoverflow.com/a/24602374/274318


Get information for this list. Returns a dictionary of values.


board_json = self.get_board_json(self.base_uri)<EOL>return self.create_board(board_json)<EOL>

Get the board that this list belongs to. Returns a Board object.

Returns:
    Board: The board this list is attached to


cards = self.get_cards_json(self.base_uri)<EOL>cards_list = []<EOL>for card_json in cards:<EOL><INDENT>cards_list.append(self.create_card(card_json))<EOL><DEDENT>return cards_list<EOL>

Get cards for this list. Returns a list of Card objects

Returns:
    list(Card): The cards attached to this list


list_json = self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>http_method='<STR_LIT>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_list(list_json)<EOL>

Update information for this list. Returns a new List object.


card_json = self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_card(card_json)<EOL>

Create a card for this list. Returns a Card object.


def __init__(self, api_key, user_auth_token=None):

self.api_key = api_key<EOL>self.user_auth_token = user_auth_token<EOL>self.client = httplib2.Http()<EOL>

Takes the API key and User Auth Token, which are needed for all Trello
API calls to allow access to requested information


query_params['<STR_LIT:key>'] = self.api_key<EOL>if self.user_auth_token:<EOL><INDENT>query_params['<STR_LIT>'] = self.user_auth_token<EOL><DEDENT>return query_params<EOL>

Adds the API key and user auth token to the query parameters


if path[<NUM_LIT:0>] != '<STR_LIT:/>':<EOL><INDENT>path = '<STR_LIT:/>' + path<EOL><DEDENT>return path<EOL>


if response.status == <NUM_LIT>:<EOL><INDENT>raise trolly.Unauthorised(uri, response)<EOL><DEDENT>if response.status != <NUM_LIT:200>:<EOL><INDENT>raise trolly.ResourceUnavailable(uri, response)<EOL><DEDENT>


def build_uri(self, path, query_params):

url = '<STR_LIT>' + self.clean_path(path)<EOL>url += '<STR_LIT:?>' + urlencode(query_params)<EOL>return url<EOL>


def fetch_json(self, uri_path, http_method='<STR_LIT:GET>', query_params=None,<EOL>body=None, headers=None):

query_params = query_params or {}<EOL>headers = headers or {}<EOL>query_params = self.add_authorisation(query_params)<EOL>uri = self.build_uri(uri_path, query_params)<EOL>allowed_methods = ("<STR_LIT:POST>", "<STR_LIT>", "<STR_LIT>")<EOL>if http_method in allowed_methods and '<STR_LIT:Content-Type>' not in headers:<EOL><INDENT>headers['<STR_LIT:Content-Type>'] = '<STR_LIT:application/json>'<EOL><DEDENT>headers['<STR_LIT>'] = '<STR_LIT:application/json>'<EOL>response, content = self.client.request(<EOL>uri=uri,<EOL>method=http_method,<EOL>body=body,<EOL>headers=headers<EOL>)<EOL>self.check_errors(uri, response)<EOL>return json.loads(content.decode('<STR_LIT:utf-8>'))<EOL>

Make a call to Trello API and capture JSON response. Raises an error
when it fails.

Returns:
    dict: Dictionary with the JSON data


Create an Organisation object from a JSON object

Returns:
    Organisation: The organisation from the given `organisation_json`.


return trolly.board.Board(<EOL>trello_client=self,<EOL>board_id=board_json['<STR_LIT:id>'],<EOL>name=board_json['<STR_LIT:name>'],<EOL>data=board_json,<EOL>)<EOL>

Create Board object from a JSON object

Returns:
    Board: The board from the given `board_json`.


return trolly.label.Label(<EOL>trello_client=self,<EOL>label_id=label_json['<STR_LIT:id>'],<EOL>name=label_json['<STR_LIT:name>'],<EOL>data=label_json,<EOL>)<EOL>

Create Label object from JSON object

Returns:
    Label: The label from the given `label_json`.


return trolly.list.List(<EOL>trello_client=self,<EOL>list_id=list_json['<STR_LIT:id>'],<EOL>name=list_json['<STR_LIT:name>'],<EOL>data=list_json,<EOL>)<EOL>

Create List object from JSON object

Returns:
    List: The list from the given `list_json`.


return trolly.card.Card(<EOL>trello_client=self,<EOL>card_id=card_json['<STR_LIT:id>'],<EOL>name=card_json['<STR_LIT:name>'],<EOL>data=card_json,<EOL>)<EOL>

Create a Card object from JSON object

Returns:
    Card: The card from the given `card_json`.


return trolly.checklist.Checklist(<EOL>trello_client=self,<EOL>checklist_id=checklist_json['<STR_LIT:id>'],<EOL>name=checklist_json['<STR_LIT:name>'],<EOL>data=checklist_json,<EOL>)<EOL>

Create a Checklist object from JSON object

Returns:
    Checklist: The checklist from the given `checklist_json`.


def create_checklist_item(self, card_id, checklist_id, checklistitem_json):

Create a ChecklistItem object from JSON object


return trolly.member.Member(<EOL>trello_client=self,<EOL>member_id=member_json['<STR_LIT:id>'],<EOL>name=member_json['<STR_LIT>'],<EOL>data=member_json,<EOL>)<EOL>

Create a Member object from JSON object

Returns:
    Member: The member from the given `member_json`.


def get_organisation(self, id, name=None):

return self.create_organisation(dict(id=id, name=name))<EOL>

Get an organisation

Returns:
    Organisation: The organisation with the given `id`


return self.create_board(dict(id=id, name=name))<EOL>

Get a board

Returns:
    Board: The board with the given `id`


return self.create_list(dict(id=id, name=name))<EOL>

Get a list

Returns:
    List: The list with the given `id`


return self.create_card(dict(id=id, name=name))<EOL>

Get a card

Returns:
    Card: The card with the given `id`


return self.create_checklist(dict(id=id, name=name))<EOL>

Get a checklist

Returns:
    Checklist: The checklist with the given `id`


def get_member(self, id='<STR_LIT>', name=None):

return self.create_member(dict(id=id, fullName=name))<EOL>

Get a member or your current member if `id` wasn't given.

Returns:
    Member: The member with the given `id`, defaults to the
    logged in member.


return self.get_member().get_boards(**query_params)<EOL>

Get all boards this member is attached to. Returns a list of Board
objects.

Returns:
    list(Board): Return all boards for this member


return self.get_member().get_cards(**query_params)<EOL>

Get all cards this member is attached to. Return a list of Card
objects.

Returns:
    list(Card): Return all cards this member is attached to


return self.get_member().get_organisations(**query_params)<EOL>

Get all organisations this member is part of. Return a list of
Organisation objects.

Returns:
    list(Organisation): Return all organisations this member is
    part of


return self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>query_params=query_params or {}<EOL>)<EOL>

Get Information for a member. Returns a dictionary of values.

Returns:
    dict


boards = self.get_boards_json(self.base_uri, query_params=query_params)<EOL>boards_list = []<EOL>for board_json in boards:<EOL><INDENT>boards_list.append(self.create_board(board_json))<EOL><DEDENT>return boards_list<EOL>


cards = self.get_cards_json(self.base_uri, query_params=query_params)<EOL>cards_list = []<EOL>for card_json in cards:<EOL><INDENT>cards_list.append(self.create_card(card_json))<EOL><DEDENT>return cards_list<EOL>


organisations = self.get_organisations_json(self.base_uri,<EOL>query_params=query_params)<EOL>organisations_list = []<EOL>for organisation_json in organisations:<EOL><INDENT>organisations_list.append(<EOL>self.create_organisation(organisation_json))<EOL><DEDENT>return organisations_list<EOL>

Get all organisations this member is attached to. Return a list of
Organisation objects.

Returns:
    list(Organisation): Return all organisations this member is
    attached to


board_json = self.fetch_json(<EOL>uri_path='<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params=query_params or {}<EOL>)<EOL>return self.create_board(board_json)<EOL>

Create a new board. name is required in query_params. Returns a Board
object.

Returns:
    Board: Returns the created board


<EOL>return self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>query_params=query_params or {}<EOL>)<EOL>

Get all information for this Checklist. Returns a dictionary of values.


card_id = self.get_checklist_information().get('<STR_LIT>', None)<EOL>if card_id:<EOL><INDENT>return self.client.get_card(card_id)<EOL><DEDENT>


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>query_params=query_params or {}<EOL>)<EOL>

Get all the items for this checklist. Returns a list of dictionaries.
Each dictionary has the values for an item.


card = self.get_card()<EOL>checklistitems_list = []<EOL>for checklistitem_json in self.get_items(query_params):<EOL><INDENT>checklistitems_list.append(self.create_checklist_item(card.id, self.id, checklistitem_json))<EOL><DEDENT>return checklistitems_list<EOL>

Get the items for this checklist. Returns a list of ChecklistItem objects.


checklist_json = self.fetch_json(<EOL>uri_path=self.base_uri,<EOL>http_method='<STR_LIT>',<EOL>query_params={'<STR_LIT:name>': name}<EOL>)<EOL>return self.create_checklist(checklist_json)<EOL>

Update the current checklist. Returns a new Checklist object.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>',<EOL>http_method='<STR_LIT:POST>',<EOL>query_params=query_params or {}<EOL>)<EOL>

Add an item to this checklist. Returns a dictionary of values of new
item.


return self.fetch_json(<EOL>uri_path=self.base_uri + '<STR_LIT>' + item_id,<EOL>http_method='<STR_LIT>'<EOL>)<EOL>


checklistitem_json = self.fetch_json(<EOL>uri_path = self.base_uri + '<STR_LIT>',<EOL>http_method = '<STR_LIT>',<EOL>query_params = {'<STR_LIT:value>': name}<EOL>)<EOL>return self.create_checklist_item(self.idCard, self.idChecklist, checklistitem_json)<EOL>

Rename the current checklist item. Returns a new ChecklistItem object.


checklistitem_json = self.fetch_json(<EOL>uri_path = self.base_uri + '<STR_LIT>',<EOL>http_method = '<STR_LIT>',<EOL>query_params = {'<STR_LIT:value>': '<STR_LIT>' if state else '<STR_LIT>'}<EOL>)<EOL>return self.create_checklist_item(self.idCard, self.idChecklist, checklistitem_json)<EOL>

Set the state of the current checklist item. Returns a new ChecklistItem object.


for k,v in source.items():<EOL><INDENT>if isinstance(v, dict) and k in target and isinstance(source[k], dict):<EOL><INDENT>update_dict(target[k], v)<EOL><DEDENT>else:<EOL><INDENT>target[k] = v<EOL><DEDENT><DEDENT>

Recursively merge values from a nested dictionary into another nested
dictionary.

For example:

>>> target = {
...     'thing': 123,
...     'thang': {
...         'a': 1,
...         'b': 2
...     }
... }
>>> source = {
...     'thang': {
...         'a': 666,
...         'c': 777
...     }
... }
>>> update_dict(target, source)
>>> target
{
    'thing': 123,
    'thang': {
        'a': 666,
        'b': 2,
        'c': 777
    }
}


if self._path:<EOL><INDENT>path = '<STR_LIT>'.format(self._path, path)<EOL><DEDENT>return ConfigNode(root=self._root, path=path)<EOL>

Return a ConfigNode object representing a child node with the specified
relative path.


<EOL>if type(self._path) == str:<EOL><INDENT>key_path = self._path.split('<STR_LIT:.>')<EOL><DEDENT>else:<EOL><INDENT>key_path = [self._path]<EOL><DEDENT>node = self._root._data<EOL>nodes = [self._root._data]<EOL>while len(key_path):<EOL><INDENT>key = key_path.pop(<NUM_LIT:0>)<EOL>try:<EOL><INDENT>key = int(key)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>if create:<EOL><INDENT>if type(node) == dict and key not in node:<EOL><INDENT>node[key] = {}<EOL><DEDENT>elif type(node) == list and type(key) == int and len(node) < key:<EOL><INDENT>node.append([None for i in range(key-len(node))])<EOL><DEDENT><DEDENT>nodes.append(node)<EOL>try:<EOL><INDENT>node = node[key]<EOL><DEDENT>except TypeError:<EOL><INDENT>if type(key) == int:<EOL><INDENT>raise IndexError(key)<EOL><DEDENT>else:<EOL><INDENT>raise KeyError(key)<EOL><DEDENT><DEDENT><DEDENT>return (nodes[-<NUM_LIT:1>], key)<EOL>

Returns a tuple of a reference to the last container in the path, and
the last component in the key path.

For example, with a self._value like this:

{
    'thing': {
        'another': {
            'some_leaf': 5,
            'one_more': {
                'other_leaf': 'x'
            }
        }
    }
}

And a self._path of: 'thing.another.some_leaf'

This will return a tuple of a reference to the 'another' dict, and
'some_leaf', allowing the setter and casting methods to directly access
the item referred to by the key path.


if self._path:<EOL><INDENT>try:<EOL><INDENT>container, last = self._resolve_path()<EOL>return container[last]<EOL><DEDENT>except KeyError:<EOL><INDENT>return None<EOL><DEDENT>except IndexError:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return self._data<EOL><DEDENT>


<EOL>for key in options:<EOL><INDENT>self[key] = options[key]<EOL><DEDENT>if isinstance(data, ConfigNode):<EOL><INDENT>data = data._get_value()<EOL><DEDENT>update_dict(self._get_value(), data)<EOL>

Update the configuration with new data.

This can be passed either or both `data` and `options`.

`options` is a dict of keypath/value pairs like this (similar to
CherryPy's config mechanism:

    >>> c.update(options={
    ...     'server.port': 8080,
    ...     'server.host': 'localhost',
    ...     'admin.email': 'admin@lol'
    ... })

`data` is a dict of actual config data, like this:

    >>> c.update(data={
    ...     'server': {
    ...         'port': 8080,
    ...         'host': 'localhost'
    ...     },
    ...     'admin': {
    ...         'email': 'admin@lol'
    ...     }
    ... })


self._data = copy.deepcopy(self._defaults)<EOL>


return self._get_value()<EOL>


if reload or not self._loaded:<EOL><INDENT>if self._defaults_file and type(self._defaults_file) == str:<EOL><INDENT>self._defaults_file = File(self._defaults_file, parent=self._parent)<EOL><DEDENT>defaults = {}<EOL>if self._defaults_file:<EOL><INDENT>defaults = yaml.safe_load(self._defaults_file.read().replace('<STR_LIT:\t>', '<STR_LIT:U+0020>'))<EOL><DEDENT>data = {}<EOL>if self.exists:<EOL><INDENT>data = yaml.safe_load(self.read().replace('<STR_LIT:\t>', '<STR_LIT:U+0020>'))<EOL><DEDENT>self._defaults = defaults<EOL>self._data = copy.deepcopy(self._defaults)<EOL>self.update(data=data)<EOL>if self._apply_env:<EOL><INDENT>self.update(ConfigEnv(self._env_prefix))<EOL><DEDENT>self._loaded = True<EOL><DEDENT>return self<EOL>

Load the config and defaults from files.


self.write(yaml.safe_dump(self._data))<EOL>

Save the config back to the config file.


self.load()<EOL>

Load the file when the Directory/Environment prepares us.


if type(obj) == str:<EOL><INDENT>return self.apply_to_str(obj)<EOL><DEDENT>


toks = re.split('<STR_LIT>', obj)<EOL>newtoks = []<EOL>try:<EOL><INDENT>while len(toks):<EOL><INDENT>tok = toks.pop(<NUM_LIT:0>)<EOL>if tok == '<STR_LIT>':<EOL><INDENT>var = toks.pop(<NUM_LIT:0>)<EOL>val = self.config[var]<EOL>if type(val) == ConfigNode and val == None:<EOL><INDENT>raise KeyError("<STR_LIT>".format(var))<EOL><DEDENT>newtoks.append(str(val))<EOL>toks.pop(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>newtoks.append(tok)<EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(newtoks)<EOL><DEDENT>except IndexError:<EOL><INDENT>pass<EOL><DEDENT>return obj<EOL>


if type(self._fpath) == str:<EOL><INDENT>self._fpath = applicator.apply(self._fpath)<EOL><DEDENT>

Replace any config tokens in the file's path with values from the config.


open(self.path, '<STR_LIT:a>').close()<EOL>

Create the file if it doesn't already exist.


if self.exists:<EOL><INDENT>os.unlink(self.path)<EOL><DEDENT>


if self._create:<EOL><INDENT>self.create()<EOL><DEDENT>

Prepare the file for use in an Environment or Directory.

This will create the file if the create flag is set.


if self._cleanup:<EOL><INDENT>self.remove()<EOL><DEDENT>

Clean up the file after use in an Environment or Directory.

This will remove the file if the cleanup flag is set.


if self._parent:<EOL><INDENT>return os.path.join(self._parent.path, self._fpath)<EOL><DEDENT>else:<EOL><INDENT>return self._fpath<EOL><DEDENT>

Get the path to the file relative to its parent.


return os.path.basename(self.path)<EOL>


return os.path.splitext(self.path)[<NUM_LIT:1>]<EOL>


return self.read()<EOL>


return self.path and os.path.exists(self.path)<EOL>


with open(self.path) as f:<EOL><INDENT>d = f.read()<EOL><DEDENT>return d<EOL>

Read and return the contents of the file.


def write(self, data, mode='<STR_LIT:w>'):

with open(self.path, mode) as f:<EOL><INDENT>f.write(data)<EOL><DEDENT>

Write data to the file.

`data` is the data to write
`mode` is the mode argument to pass to `open()`


self.configure()<EOL>


<EOL>handler = logging.FileHandler(self.path, delay=True)<EOL>if self._format:<EOL><INDENT>handler.setFormatter(logging.Formatter(self._format))<EOL><DEDENT>if type(self._formatter) == str:<EOL><INDENT>if self._env and self._env.config.logging.dict_config.formatters[self._formatter]:<EOL><INDENT>d = self._env.config.logging.dict_config.formatters[self._formatter].to_dict()<EOL>handler.setFormatter(logging.Formatter(**d))<EOL><DEDENT><DEDENT>elif type(self._formatter) == dict:<EOL><INDENT>handler.setFormatter(logging.Formatter(**self._formatter))<EOL><DEDENT>if len(self._loggers):<EOL><INDENT>for name in self._loggers:<EOL><INDENT>logging.getLogger(name).addHandler(handler)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logging.getLogger().addHandler(handler)<EOL><DEDENT>

Configure the Python logging module for this file.


if not os.path.exists(self.path):<EOL><INDENT>open(self.path, '<STR_LIT:a>').close()<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>".format(self.path))<EOL><DEDENT>

Create the file.

If the file already exists an exception will be raised


return yaml.safe_load(self.read())<EOL>

Parse the file contents into a dictionary.


if type(self._path) == str:<EOL><INDENT>self._path = applicator.apply(self._path)<EOL><DEDENT>for key in self._children:<EOL><INDENT>self._children[key].apply_config(applicator)<EOL><DEDENT>

Replace any config tokens with values from the config.


p = '<STR_LIT>'<EOL>if self._parent and self._parent.path:<EOL><INDENT>p = os.path.join(p, self._parent.path)<EOL><DEDENT>if self._base:<EOL><INDENT>p = os.path.join(p, self._base)<EOL><DEDENT>if self._path:<EOL><INDENT>p = os.path.join(p, self._path)<EOL><DEDENT>return p<EOL>


if not self.exists:<EOL><INDENT>os.mkdir(self.path)<EOL><DEDENT>

Create the directory.

Directory will only be created if the create flag is set.


def remove(self, recursive=True, ignore_error=True):

try:<EOL><INDENT>if recursive or self._cleanup == '<STR_LIT>':<EOL><INDENT>shutil.rmtree(self.path)<EOL><DEDENT>else:<EOL><INDENT>os.rmdir(self.path)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>if not ignore_error:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT>


if self._create:<EOL><INDENT>self.create()<EOL><DEDENT>for k in self._children:<EOL><INDENT>self._children[k]._env = self._env<EOL>self._children[k].prepare()<EOL><DEDENT>

Prepare the Directory for use in an Environment.

This will create the directory if the create flag is set.


for k in self._children:<EOL><INDENT>self._children[k].cleanup()<EOL><DEDENT>if self._cleanup:<EOL><INDENT>self.remove(True)<EOL><DEDENT>

Clean up children and remove the directory.

Directory will only be removed if the cleanup flag is set.


return os.path.join(self.path, str(path))<EOL>

Find the path to something inside this directory.


return os.path.exists(self.path)<EOL>


return [File(f, parent=self) for f in os.listdir(self.path)]<EOL>


def write(self, filename, data, mode='<STR_LIT:w>'):

with open(self.path_to(str(filename)), mode) as f:<EOL><INDENT>f.write(data)<EOL><DEDENT>


with open(self.path_to(str(filename))) as f:<EOL><INDENT>d = f.read()<EOL><DEDENT>return d<EOL>


for key in kwargs:<EOL><INDENT>if isinstance(kwargs[key], str):<EOL><INDENT>self._children[key] = File(kwargs[key])<EOL><DEDENT>else:<EOL><INDENT>self._children[key] = kwargs[key]<EOL><DEDENT>self._children[key]._parent = self<EOL>self._children[key]._env = self._env<EOL><DEDENT>added = []<EOL>for arg in args:<EOL><INDENT>if isinstance(arg, File):<EOL><INDENT>self._children[arg.name] = arg<EOL>self._children[arg.name]._parent = self<EOL>self._children[arg.name]._env = self._env<EOL><DEDENT>elif isinstance(arg, str):<EOL><INDENT>f = File(arg)<EOL>added.append(f)<EOL>self._children[arg] = f<EOL>self._children[arg]._parent = self<EOL>self._children[arg]._env = self._env<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(type(arg))<EOL><DEDENT><DEDENT>if len(added) == <NUM_LIT:1>:<EOL><INDENT>return added[<NUM_LIT:0>]<EOL><DEDENT>if len(args) == <NUM_LIT:1>:<EOL><INDENT>return args[<NUM_LIT:0>]<EOL><DEDENT>


super(PluginDirectory, self).prepare()<EOL>self.load()<EOL>

Preparing a plugin directory just loads the plugins.


named_config = None<EOL>found_config = None<EOL>if '<STR_LIT>' in children:<EOL><INDENT>if type(children['<STR_LIT>']) == str:<EOL><INDENT>children['<STR_LIT>'] = ConfigFile(children['<STR_LIT>'])<EOL><DEDENT>elif isinstance(children['<STR_LIT>'], Config):<EOL><INDENT>children['<STR_LIT>'] = children['<STR_LIT>']<EOL><DEDENT>elif type(children['<STR_LIT>']) == dict:<EOL><INDENT>children['<STR_LIT>'] = Config(data=children['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>".format(type(children['<STR_LIT>'])))<EOL><DEDENT>named_config = children['<STR_LIT>']<EOL><DEDENT>for k in children:<EOL><INDENT>if isinstance(children[k], Config):<EOL><INDENT>found_config = children[k]<EOL><DEDENT><DEDENT>for k in children:<EOL><INDENT>if isinstance(children[k], Directory):<EOL><INDENT>for j in children[k]._children:<EOL><INDENT>if j == '<STR_LIT>' and not named_config:<EOL><INDENT>named_config = children[k]._children[j]<EOL><DEDENT>if isinstance(children[k]._children[j], Config):<EOL><INDENT>found_config = children[k]._children[j]<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if named_config:<EOL><INDENT>return named_config<EOL><DEDENT>else:<EOL><INDENT>return found_config<EOL><DEDENT>

Find a config in our children so we can fill in variables in our other
children with its data.


for key in kwargs:<EOL><INDENT>if type(kwargs[key]) == str:<EOL><INDENT>self._children[key] = Directory(kwargs[key])<EOL><DEDENT>else:<EOL><INDENT>self._children[key] = kwargs[key]<EOL><DEDENT>self._children[key]._env = self<EOL>self._children[key].apply_config(ConfigApplicator(self.config))<EOL>self._children[key].prepare()<EOL><DEDENT>


for key in self._children:<EOL><INDENT>self._children[key].cleanup()<EOL><DEDENT>


with open(self.path, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(yaml.dump(dict(self.d)))<EOL><DEDENT>


if os.path.exists(self.path):<EOL><INDENT>with open(self.path, '<STR_LIT:r>') as f:<EOL><INDENT>self.d = yaml.safe_load(f.read().replace('<STR_LIT:\t>', '<STR_LIT:U+0020>'*<NUM_LIT:4>))<EOL><DEDENT><DEDENT>


if os.path.exists(self.path):<EOL><INDENT>os.remove(self.path)<EOL><DEDENT>


<EOL>for filename in os.listdir(directory):<EOL><INDENT>filepath = os.path.join(directory, filename)<EOL>modname, ext = os.path.splitext(filename)<EOL>if os.path.isfile(filepath) and ext == '<STR_LIT>':<EOL><INDENT>file, path, descr = imp.find_module(modname, [directory])<EOL>if file:<EOL><INDENT>mod = imp.load_module(modname, file, path, descr)<EOL><DEDENT><DEDENT>if os.path.isdir(filepath):<EOL><INDENT>self.load_plugins(filepath)<EOL><DEDENT><DEDENT>

Loads plugins from the specified directory.

`directory` is the full path to a directory containing python modules
which each contain a subclass of the Plugin class.

There is no criteria for a valid plugin at this level - any python
module found in the directory will be loaded. Only modules that
implement a subclass of the Plugin class above will be collected.

The directory will be traversed recursively.


pass<EOL>


@cli.command('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=<NUM_LIT:1>, type=int)<EOL>def cmd_encode(integer):

encode(integer)<EOL>

Encode an integer up to 64 bit to Varint.


Decode an integer up to 64 bit from Varint.


encodeVarint(sys.stdout.buffer.write, value, True)<EOL>

Output the encoded value to the standard output.

    Args:
        value (int):  the integer to be encoded.


print(decodeVarint(input_file.read(), <NUM_LIT:0>)[<NUM_LIT:0>])<EOL>

Output the decoded value to the standard output.

    Args:
        input_file (file handler):  input file handler.


mode = '<STR_LIT:rb>'<EOL>if isinstance(ifp, str):<EOL><INDENT>istream = open(ifp, mode=mode, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>istream = open(fileobj=ifp, mode=mode, **kwargs)<EOL><DEDENT>with istream:<EOL><INDENT>for data in istream:<EOL><INDENT>pb_obj = pb_cls()<EOL>pb_obj.ParseFromString(data)<EOL>yield pb_obj<EOL><DEDENT><DEDENT>

Parse a stream.

    Args:
        ifp (string or file-like object): input stream.
        pb_cls (protobuf.message.Message.__class__): The class object of
            the protobuf message type encoded in the stream.


mode = '<STR_LIT:wb>'<EOL>if isinstance(ofp, str):<EOL><INDENT>ostream = open(ofp, mode=mode, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>ostream = open(fileobj=ofp, mode=mode, **kwargs)<EOL><DEDENT>with ostream:<EOL><INDENT>ostream.write(*pb_objs)<EOL><DEDENT>

Write to a stream.

    Args:
        ofp (string or file-like object): output stream.
        pb_objs (*protobuf.message.Message): list of protobuf message objects
            to be written.


def open(filename=None, mode='<STR_LIT:rb>',  <EOL>**kwargs):

return Stream(filename, mode, **kwargs)<EOL>


def __init__(self, filename=None, mode='<STR_LIT:rb>', fileobj=None, **kwargs):

self._myfd = None<EOL>if fileobj is None:<EOL><INDENT>if kwargs.get('<STR_LIT>', True):<EOL><INDENT>self._fd = gzip.open(filename, mode)<EOL><DEDENT>else:<EOL><INDENT>import builtins<EOL>self._fd = builtins.open(filename, mode)<EOL><DEDENT>self._myfd = self._fd<EOL><DEDENT>else:<EOL><INDENT>self._fd = fileobj<EOL><DEDENT>if not mode.startswith('<STR_LIT:r>'):<EOL><INDENT>self._buffer_size = kwargs.pop('<STR_LIT>', <NUM_LIT:0>)<EOL>self._write_buff = []<EOL><DEDENT>else:<EOL><INDENT>self._group_delim = kwargs.pop('<STR_LIT>', False)<EOL>self._delimiter = kwargs.pop('<STR_LIT>', None)<EOL><DEDENT>

Constructor for the Stream class.

        Args:
            filename (string): Path of the working file.
            mode (string): The mode argument can be any of 'r', 'rb', 'a',
                'ab', 'w', or 'wb', depending on whether the file will be read
                or written. The default is 'rb'.
            fileobj (file-like object): input/output stream object.

        Keyword args:
            buffer_size (int): Write buffer size. The objects will be buffered
                before writing. No buffering will be made if buffer_size is 0.
                It means that size of the group will be determined by the size
                of object list provided on `write` call. Setting `buffer_size`
                to -1 means infinite buffer size. Method `flush` should be
                called manually or by closing stream. All objects will be write
                in one group upon `flush` or `close` events.
            group_delimiter (boolean): indicate the end of a message group if
                True by yielding a delimiter after reading each group.
            delimiter_cls (class): delimiter class.
            gzip (bool): Whether or not to use gzip compression on the given
                file. (default is True)


return self<EOL>

Enter the runtime context related to Stream class. It will be
        automatically run by `with` statement.


self.close()<EOL>

Exit the runtime context related to Stream class. It will be
        automatically run by `with` statement. It closes the stream.


return self._get_objs()<EOL>

Return the iterator object of the stream.


buff = self._fd.read(<NUM_LIT:1>)<EOL>if buff == b'<STR_LIT>':<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>while (bytearray(buff)[-<NUM_LIT:1>] & <NUM_LIT>) >> <NUM_LIT:7> == <NUM_LIT:1>:  <EOL><INDENT>new_byte = self._fd.read(<NUM_LIT:1>)<EOL>if new_byte == b'<STR_LIT>':<EOL><INDENT>raise EOFError('<STR_LIT>')<EOL><DEDENT>buff += new_byte<EOL><DEDENT>varint, _ = decodeVarint(buff, <NUM_LIT:0>)<EOL>return varint<EOL>

Read a varint from file, parse it, and return the decoded integer.


while True:<EOL><INDENT>count = self._read_varint()<EOL>if count == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>for _ in range(count):<EOL><INDENT>size = self._read_varint()<EOL>if size == <NUM_LIT:0>:<EOL><INDENT>raise EOFError('<STR_LIT>')<EOL><DEDENT>yield self._fd.read(size)<EOL><DEDENT>if self._group_delim:<EOL><INDENT>yield self._delimiter() if self._delimiter is not Noneelse None<EOL><DEDENT><DEDENT>

A generator yielding all protobuf object data in the file. It is the
        main parser of the stream encoding.


if hasattr(self, '<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Check whether the stream is output stream or not.


self.flush()<EOL>if self._myfd is not None:<EOL><INDENT>self._myfd.close()<EOL>self._myfd = None<EOL><DEDENT>


base = len(self._write_buff)<EOL>for idx, obj in enumerate(pb2_obj):<EOL><INDENT>if self._buffer_size > <NUM_LIT:0> and(idx + base) != <NUM_LIT:0> and(idx + base) % self._buffer_size == <NUM_LIT:0>:<EOL><INDENT>self.flush()<EOL><DEDENT>self._write_buff.append(obj)<EOL><DEDENT>if self._buffer_size == <NUM_LIT:0>:<EOL><INDENT>self.flush()<EOL><DEDENT>

Write a group of one or more protobuf objects to the file. Multiple
        object groups can be written by calling this method several times
        before closing stream or exiting the runtime context.

        The input protobuf objects get buffered and will be written down when
        the number of buffered objects exceed the `self._buffer_size`.

        Args:
            pb2_obj (*protobuf.message.Message): list of protobuf messages.


if not self.is_output():<EOL><INDENT>return<EOL><DEDENT>count = len(self._write_buff)<EOL>if count == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>encodeVarint(self._fd.write, count, True)<EOL>for obj in self._write_buff:<EOL><INDENT>obj_str = obj.SerializeToString()<EOL>encodeVarint(self._fd.write, len(obj_str), True)<EOL>self._fd.write(obj_str)<EOL><DEDENT>self._write_buff = []<EOL>


with stream.open(fpath, '<STR_LIT:rb>', **kwargs) as istream:<EOL><INDENT>for data in istream:<EOL><INDENT>aln = vg_pb2.Alignment()<EOL>aln.ParseFromString(data)<EOL>yield aln<EOL><DEDENT><DEDENT>

Read protobuf objects from a file by using `with` statement.

    Here, as an example, the file is a GAM file containing Alignment messages
    defined in vg_pb2.

    Args:
        fpath (string): path of the file to be read.


nof_groups = <NUM_LIT:0><EOL>mode = '<STR_LIT:rb>'<EOL>if kwargs.get('<STR_LIT>', True):<EOL><INDENT>ifs = gzip.open(fpath, mode)<EOL><DEDENT>else:<EOL><INDENT>ifs = open(fpath, mode)<EOL><DEDENT>with ifs:<EOL><INDENT>istream = stream.open(fileobj=ifs, group_delimiter=True, **kwargs)<EOL>for data in istream:<EOL><INDENT>if data is None:<EOL><INDENT>nof_groups += <NUM_LIT:1><EOL>continue<EOL><DEDENT>aln = vg_pb2.Alignment()<EOL>aln.ParseFromString(data)<EOL>yield aln<EOL><DEDENT>istream.close()<EOL><DEDENT>assert nof_groups == <NUM_LIT:2><EOL>

Read protobuf objects from a file without using `with` statement.

    Here, as an example, the file is a GAM file containing Alignment messages
    defined in vg_pb2.

    NOTE: Does the same as `read_alns1`.

    Args:
        fpath (string): path of the file to be read.


def write_objs1(fpath, *objs_list, **kwargs):

with stream.open(fpath, '<STR_LIT:wb>', **kwargs) as ostream:<EOL><INDENT>length = len(objs_list)<EOL>ostream.write(*objs_list[:length//<NUM_LIT:2>])<EOL>ostream.write(*objs_list[length//<NUM_LIT:2>:])<EOL><DEDENT>

Write protobuf message objects into the file by using `with` statement.

    It writes half of objects in one group, and then the other half in another
    one.

    Args:
        fpath (string): path of the file to be written.
        objs_list (*protobuf.message.Message): list of objects to be written.


def write_objs2(fpath, *objs_list, **kwargs):

mode = '<STR_LIT:wb>'<EOL>if kwargs.get('<STR_LIT>', True):<EOL><INDENT>ofs = gzip.open(fpath, mode)<EOL><DEDENT>else:<EOL><INDENT>ofs = open(fpath, mode)<EOL><DEDENT>with ofs:<EOL><INDENT>ostream = stream.open(fileobj=ofs, mode='<STR_LIT:wb>',<EOL>buffer_size=(len(objs_list)//<NUM_LIT:2>), **kwargs)<EOL>ostream.write(*objs_list)<EOL>ostream.close()<EOL><DEDENT>

Write protobuf message objects into the file w/o using `with` statement.

    It writes half of them in one group, and then the other half in another one
    by setting buffer size to half of the object list size.

    NOTE: Does the same as `write_objs1`.

    Args:
        fpath (string): path of the file to be written.
        objs_list (*protobuf.message.Message): list of objects to be written.


ungz_first = '<STR_LIT>'.join(os.path.splitext(first))<EOL>ungz_second = '<STR_LIT>'.join(os.path.splitext(second))<EOL>with gzip.open(first, '<STR_LIT:rb>') as gfp, open(ungz_first, '<STR_LIT:wb>') as ufp:<EOL><INDENT>ufp.write(gfp.read())<EOL><DEDENT>with gzip.open(second, '<STR_LIT:rb>') as gfp, open(ungz_second, '<STR_LIT:wb>') as ufp:<EOL><INDENT>ufp.write(gfp.read())<EOL><DEDENT>result = filecmp.cmp(ungz_first, ungz_second)<EOL>os.remove(ungz_first)<EOL>os.remove(ungz_second)<EOL>return result<EOL>

Compare two gzipped stream files.

    Since the stream files are gzipped and the file name is included in the
    compressed file, they need to be decompressed first before comparing their
    contents.

    Args:
        first (string): path to the first stream file.
        second (string): path to the second stream file.


if kwargs.get('<STR_LIT>', True):<EOL><INDENT>return compare_gzipped(first, second)<EOL><DEDENT>return filecmp.cmp(first, second)<EOL>

Compare two stream files.

    The stream can be gzipped or not specified by `gzipped` keyword argument.


if os.path.exists(self.connection.cache_directory):<EOL><INDENT>shutil.rmtree(self.connection.cache_directory)<EOL><DEDENT>

Clean up by removing the test image that was downloaded.


return self.connection.url<EOL>


<EOL>if self.connection.has_changed():<EOL><INDENT>image_path = self.connection.download_image()<EOL>image = Image.open(image_path)<EOL>self.text_cache = pytesseract.image_to_string(image)<EOL>image.close()<EOL><DEDENT>return self.text_cache<EOL>

Returns the text from an image at a given url.


<EOL>words = self.read().split()<EOL>for word in words:<EOL><INDENT>if word.lstrip('<STR_LIT:->').replace('<STR_LIT:.>', '<STR_LIT>', <NUM_LIT:1>).isdigit():<EOL><INDENT>return True<EOL><DEDENT>if word.isalpha() and (len(word) > <NUM_LIT:1> or len(word) <= <NUM_LIT:20>):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Returns true or false based on if the OCR process has read
actual words. This is needed to prevent non-words from being
added to the queue since the ocr process can sometimes return
values that are not meaningfull.


<EOL>if not self.connection.has_changed():<EOL><INDENT>return self.image_brightness<EOL><DEDENT>image_path = self.connection.download_image()<EOL>converted_image = Image.open(image_path).convert('<STR_LIT:L>')<EOL>statistics = ImageStat.Stat(converted_image)<EOL>self.image_brightness = statistics.mean[<NUM_LIT:0>]<EOL>return self.image_brightness<EOL>

Return the average brightness of the image.


split = urlsplit(self.url)<EOL>filename = split.path.split("<STR_LIT:/>")[-<NUM_LIT:1>]<EOL>if not os.path.exists(self.cache_directory):<EOL><INDENT>os.makedirs(self.cache_directory)<EOL><DEDENT>filepath = os.path.join(self.cache_directory, filename)<EOL>data = urllib_request.urlopen(self.url)<EOL>with open(filepath, "<STR_LIT:wb>") as image:<EOL><INDENT>image.write(data.read())<EOL><DEDENT>return filepath<EOL>

Download the image and return the
local path to the image file.


request = urllib_request.Request(self.url)<EOL>request.get_method = lambda: '<STR_LIT>'<EOL>response = urllib_request.urlopen(request)<EOL>information = response.info()<EOL>if '<STR_LIT>' in information:<EOL><INDENT>last_modified = information['<STR_LIT>']<EOL>if last_modified == self.image_last_modified:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>self.image_last_modified = last_modified<EOL>return True<EOL>

Method to check if an image has changed
since it was last downloaded. By making
a head request, this check can be done
quicker that downloading and processing
the whole file.


init_py = open(os.path.join(package, '<STR_LIT>')).read()<EOL>return re.search("<STR_LIT>", init_py).group(<NUM_LIT:1>)<EOL>

Return package version as listed in `__version__` in `init.py`.


return [t.strip("<STR_LIT:'>") for t in toks]<EOL>

Strip the actual quotes from the tokens in `toks`.

    Note: This is because it turned out `QuotedString` was stripping
    first and last characters of a matched string regardless. If
    there's a way to avoid having this function - by all means it
    should be removed.


from mysqlparse.grammar.sql_file import sql_file_syntax<EOL>if hasattr(file_or_string, '<STR_LIT>') and hasattr(file_or_string.read, '<STR_LIT>'):<EOL><INDENT>return sql_file_syntax.parseString(file_or_string.read())<EOL><DEDENT>elif isinstance(file_or_string, six.string_types):<EOL><INDENT>return sql_file_syntax.parseString(file_or_string)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>".format(<EOL>type_name=type(file_or_string).__name__,<EOL>))<EOL><DEDENT>

Parse a file-like object or string.

    Args:
        file_or_string (file, str): File-like object or string.

    Returns:
        ParseResults: instance of pyparsing parse results.


def integrate_ivp(u0=<NUM_LIT:1.0>, v0=<NUM_LIT:0.0>, mu=<NUM_LIT:1.0>, tend=<NUM_LIT>, dt0=<NUM_LIT>, nt=<NUM_LIT:0>,<EOL>nsteps=<NUM_LIT>, t0=<NUM_LIT:0.0>, atol=<NUM_LIT>, rtol=<NUM_LIT>, plot=False,<EOL>savefig='<STR_LIT:None>', method='<STR_LIT>', dpi=<NUM_LIT:100>, verbose=False):

f, j = get_f_and_j(mu)<EOL>if nt > <NUM_LIT:1>:<EOL><INDENT>tout = np.linspace(t0, tend, nt)<EOL>yout, nfo = integrate_predefined(<EOL>f, j, [u0, v0], tout, dt0, atol, rtol, nsteps=nsteps,<EOL>check_indexing=False, method=method)<EOL><DEDENT>else:<EOL><INDENT>tout, yout, nfo = integrate_adaptive(<EOL>f, j, [u0, v0], t0, tend, dt0, atol, rtol, nsteps=nsteps,<EOL>check_indexing=False, method=method)  <EOL><DEDENT>if verbose:<EOL><INDENT>print(nfo)<EOL><DEDENT>if plot:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>plt.plot(tout, yout[:, <NUM_LIT:1>], '<STR_LIT>')<EOL>plt.plot(tout, yout[:, <NUM_LIT:0>], '<STR_LIT>', linewidth=<NUM_LIT:2>)<EOL>if savefig == '<STR_LIT:None>':<EOL><INDENT>plt.show()<EOL><DEDENT>else:<EOL><INDENT>plt.savefig(savefig, dpi=dpi)<EOL><DEDENT><DEDENT>

Example program integrating an IVP problem of van der Pol oscillator


def f(t, y, fout):<EOL><INDENT>x, v = y<EOL>fout[<NUM_LIT:0>] = v<EOL>fout[<NUM_LIT:1>] = -g<EOL><DEDENT>def jac(t, y, jmat_out, dfdx_out=None, fy=None):<EOL><INDENT>jmat_out[<NUM_LIT:0>, <NUM_LIT:0>] = <NUM_LIT:0><EOL>jmat_out[<NUM_LIT:0>, <NUM_LIT:1>] = <NUM_LIT:1><EOL>jmat_out[<NUM_LIT:1>, <NUM_LIT:0>] = <NUM_LIT:0><EOL>jmat_out[<NUM_LIT:0>, <NUM_LIT:1>] = <NUM_LIT:0><EOL><DEDENT>def jtimes(v, Jv, t, y, fy, user_data=None, tmp=None):<EOL><INDENT>Jv[<NUM_LIT:0>] = v[<NUM_LIT:1>]<EOL>Jv[<NUM_LIT:1>] = <NUM_LIT:0><EOL><DEDENT>return f, jac, jtimes<EOL>

RHS, jacobian, and jacobian-vector product for
        particle falling under influence of gravity


x0, v0 = y0<EOL>t0 = tout[<NUM_LIT:0>]<EOL>return np.column_stack((x0 - <NUM_LIT:0.5> * g * (tout - t0)**<NUM_LIT:2>, v0 - g * (tout - t0)))<EOL>

Analytic solution to the above at times tout


def integrate_adaptive(rhs, jac, y0, x0, xend, atol, rtol, dx0=<NUM_LIT>,<EOL>dx_min=<NUM_LIT>, dx_max=<NUM_LIT>, nsteps=<NUM_LIT>, method=None, nderiv=<NUM_LIT:0>,<EOL>roots=None, nroots=<NUM_LIT:0>, return_on_root=False,<EOL>check_callable=False, check_indexing=False,<EOL>**kwargs):

<EOL>lband, uband = kwargs.get('<STR_LIT>', None), kwargs.get('<STR_LIT>', None)<EOL>nnz = kwargs.get('<STR_LIT>', None)<EOL>_check_jac_type(lband=lband, uband=uband, nnz=nnz)<EOL>if check_callable:<EOL><INDENT>_check_callable(rhs, jac, x0, y0, lband, uband, nnz)<EOL><DEDENT>if check_indexing:<EOL><INDENT>_check_indexing(rhs, jac, x0, y0, lband, uband, nnz)<EOL><DEDENT>return adaptive(rhs, jac, np.ascontiguousarray(y0, dtype=np.float64), x0, xend,<EOL>atol, rtol, method or ('<STR_LIT>' if jac is None else '<STR_LIT>'),<EOL>nsteps, dx0, dx_min, dx_max, nderiv=nderiv, roots=roots, nroots=nroots,<EOL>return_on_root=return_on_root, **kwargs)<EOL>

Integrates a system of ordinary differential equations.

    Solves the initial value problem (IVP) defined by the user supplied
    arguments. The solver chooses at what values of the independent variable
    results should be reported.

    Parameters
    ----------
    rhs : callable
        Function with signature f(t, y, fout) which modifies fout *inplace*.
    jac : callable
        Function with signature either jac(t, y, jmat_out, dfdx_out) for
        dense/banded jacobians, or jac(t, y, data, colptrs, rowvals) for
        sparse (CSC) jacobians. ``jac`` should modify ``jmat_out``, ``dfdx_out``
        (dense, banded) or (``data``, ``colptrs``, ``rowvals``) *inplace*.
        (see also ``lband``, ``uband``, ``nnz``)
    y0 : array_like
        Initial values of the dependent variables.
    x0 : float
        Initial value of the independent variable.
    xend : float
        Stopping value for the independent variable.
    dx0 : float
        Initial step-size.
    atol : float
        Absolute tolerance.
    rtol : float
        Relative tolerance.
    dx_min : float
        Minimum step (default: 0.0).
    dx_max : float
        Maximum step (default: 0.0).
    nsteps : int
        Maximum number of steps (default: 500).
    method : str
        One of: 'adams' or 'bdf' (default: 'bdf')
    nderiv : int
        Number of derivatives (default: 0).
    roots : callback
        With signature ``roots(x, yarr[:ny], out[:nroots]) -> None``.
    nroots : int
        Number of root functions in roots.
    return_on_root : bool
        Exit early (on first found root).
    check_callable : bool
        perform signature sanity checks on ``rhs`` and ``jac``
    check_indexing : bool
        Perform item setting sanity checks on ``rhs`` and ``jac``.
    \*\*kwargs:
        'lband' : int
            Number of lower bands.
            Indexing: ``banded[row_i - col_i + uband, col_i]``.
        'uband' : int
            Number of upper bands.
            Indexing: ``banded[row_i - col_i + uband, col_i]``.
        'iter_type' : str (default: 'default')
            One of: 'default', 'functional', 'newton'
        'linear_solver': str (default: 'default')
            One of: 'default', 'dense', 'banded', 'gmres',
            'gmres_classic', 'bicgstab', 'tfqmr'
        'return_on_error' : bool
            Returns on error without raising an excpetion (with ``'success'==False``).
        'autorestart' : int
            Useful for autonomous systems where conditions change during integration.
            Will restart the integration with ``x==0``. Maximum number of steps is then
            given by ``autorestart * nsteps``.
        'record_rhs_xvals' : bool
            When True: will return x values for rhs calls in ``info['rhs_xvals']``.
        'record_jac_xvals' : bool
            When True will return x values for jac calls in ``info['jac_xvals']``.
        'record_order' : bool
            When True will return used time stepper order in ``info['orders']``.
        'record_fpe' : bool
            When True will return observed floating point errors in ``info['fpes']``. (see ``fpes``)
        'record_steps' : bool
            When True will return stepsizes taken in ``info['steps']``.
        'dx0cb' : callable
            Callback for calculating dx0 (make sure to pass ``dx0==0.0``) to enable.
            Signature: ``f(x, y[:]) -> float``.
        'dx_max_cb' : callable
            Callback for calculating dx_max.
            Signature: ``f(x, y[:]) -> float``.
        'autonomous_exprs' bool
            Whether expressions contain the independent variable. If not, autorestart
            is allowed to shift the independent variable to zero at restart).
        'nnz' : int
            Maximum number of nonzero entries in the sparse (CSC) jacobian (default: -1).
            Must set ``nnz >= 0`` and ``linear_solver`` to 'klu' to enable use of sparse
            ``jac`` signature.
        'jtimes' : callable
            Function with signature f(v, Jv, t, y, fy) to calculate the product of the
            Jacobian evaluated at t, y with a vector v. Should modify Jv *inplace*.
            For use with linear solvers 'gmres', 'gmres_classic', 'bicgstab', 'tfqmr'.
        'ew_ele' : bool
            Whether to return error_weights, estimated_local_errors in info dict.
        'constraints': array
            Per component constraints 0.0: no constraint, 1.0: >=0, -1.0: <=0, 2.0: >0.0, -2.0: <0.0.

    Returns
    -------
    (xout, yout, info):
        xout: 1-dimensional array of values for the independent variable
        yout: 2-dimensional array of the dependent variables (axis 1) for
            values corresponding to xout (axis 0).
        info: Dictionary with information about the integration.


def integrate_predefined(rhs, jac, y0, xout, atol, rtol, jac_type="<STR_LIT>",<EOL>dx0=<NUM_LIT>, dx_min=<NUM_LIT>, dx_max=<NUM_LIT>, nsteps=<NUM_LIT>, method=None,<EOL>nderiv=<NUM_LIT:0>, roots=None, nroots=<NUM_LIT:0>, check_callable=False,<EOL>check_indexing=False, **kwargs):

<EOL>x0 = xout[<NUM_LIT:0>]<EOL>lband, uband = kwargs.get('<STR_LIT>', None), kwargs.get('<STR_LIT>', None)<EOL>nnz = kwargs.get('<STR_LIT>', None)<EOL>_check_jac_type(lband=lband, uband=uband, nnz=nnz)<EOL>if check_callable:<EOL><INDENT>_check_callable(rhs, jac, x0, y0, lband, uband, nnz)<EOL><DEDENT>if check_indexing:<EOL><INDENT>_check_indexing(rhs, jac, x0, y0, lband, uband, nnz)<EOL><DEDENT>return predefined(<EOL>rhs, jac,<EOL>np.ascontiguousarray(y0, dtype=np.float64),<EOL>np.ascontiguousarray(xout, dtype=np.float64),<EOL>atol, rtol, method or ('<STR_LIT>' if jac is None else '<STR_LIT>'),<EOL>nsteps, dx0, dx_min, dx_max, nderiv=nderiv, roots=roots,<EOL>nroots=nroots, **kwargs)<EOL>

Integrates a system of ordinary differential equations.

    Solves the initial value problem (IVP) defined by the user supplied
    arguments. The user chooses at what values of the independent variable
    results should be reported.

    Parameters
    ----------
    rhs : callable
        Function with signature f(t, y, fout) which modifies fout *inplace*.
    jac : callable
        Function with signature either jac(t, y, jmat_out, dfdx_out) for
        dense/banded jacobians, or jac(t, y, data, colptrs, rowvals) for
        sparse (CSC) jacobians. ``jac`` should modify ``jmat_out``, ``dfdx_out``
        (dense, banded) or (``data``, ``colptrs``, ``rowvals``) *inplace*.
        (see also ``lband``, ``uband``, ``nnz``)
    y0 : array_like
        Initial values of the dependent variables.
    xout : array_like
        Values of the independent variable.
    dx0 : float
        Initial step-size.
    atol : float
        Absolute tolerance.
    rtol : float
        Relative tolerance.
    dx_min : float
        Minimum step (default: 0.0).
    dx_max : float
        Maximum step (default: 0.0).
    nsteps : int
        Maximum number of steps (default: 500).
    method : str
        One of: 'adams' or 'bdf' (default: 'bdf').
    nderiv : int
        Number of derivatives (default: 0).
    roots : callback (default: None)
        With signature ``roots(x, yarr[:ny], out[:nroots]) -> None``,
        see info['root_indices'], note that xout is unaffected.
    nroots : int (default: 0)
        Number of root functions in roots.
    check_callable : bool (default: False)
        Perform signature sanity checks on ``rhs`` and ``jac``.
    check_indexing : bool (default: False)
        Perform item setting sanity checks on ``rhs`` and ``jac``.
    \*\*kwargs:
        'lband' : int
            Number of lower bands.
            Indexing: ``banded[row_i - col_i + uband, col_i]``.
        'uband' : int
            Number of upper bands.
            Indexing: ``banded[row_i - col_i + uband, col_i]``.
        'iter_type' : str (default: 'default')
            One of: 'default', 'functional', 'newton'.
        'linear_solver' : str (default: 'default')
            One of: 'default', 'dense', 'banded', 'gmres',
            'gmres_classic', 'bicgstab', 'tfqmr', 'klu'.
        'return_on_error' : bool
            Returns on error without raising an excpetion (with ``'success'==False``).
        'autorestart' : int
            Useful for autonomous systems where conditions change during integration.
            Will restart the integration with ``x==0``. Maximum number of steps is then
            given by ``2**autorestart * nsteps``.
        'record_rhs_xvals' : bool
            When True: will return x values for rhs calls in ``info['rhs_xvals']``.
        'record_jac_xvals' : bool
            When True will return x values for jac calls in ``info['jac_xvals']``.
        'record_order' : bool
            When True will return used time stepper order in ``info['orders']``.
        'record_fpe' : bool
            When True will return observed floating point errors in ``info['fpes']``. (see ``fpes``)
        'record_steps' : bool
            When True will return stepsizes taken in ``info['steps']``.
        'dx0cb': callable
            Callback for calculating dx0 (make sure to pass ``dx0==0.0``) to enable.
            Signature: ``f(x, y[:]) -> float``.
        'dx_max_cb' : callable
            Callback for calculating dx_max.
            Signature: ``f(x, y[:]) -> float``.
        'autonomous_exprs' : bool
            Whether expressions contain the independent variable. If not, autorestart
            is allowed to shift the independent variable to zero at restart).
        'nnz' : int
            Maximum number of nonzero entries in the sparse (CSC) jacobian (default: -1).
            Must set ``nnz >= 0`` and ``linear_solver`` to 'klu' to enable use of sparse
            ``jac`` signature.
        'jtimes' : callable
            Function with signature f(v, Jv, t, y, fy) to calculate the product of the
            Jacobian evaluated at t, y with a vector v. Should modify Jv *inplace*.
            For use with linear solvers 'gmres', 'gmres_classic', 'bicgstab', 'tfqmr'.
        'ew_ele' : bool
            Whether to return error_weights, estimated_local_errors in info dict.
        'constraints': array
            Per component constraints 0.0: no constraint, 1.0: >=0, -1.0: <=0, 2.0: >0.0, -2.0: <0.0.

    Returns
    -------
    (yout, info):
        yout: 2-dimensional array of the dependent variables (axis 1) for
            values corresponding to xout (axis 0)
        info: Dictionary with information about the integration.


<EOL>byte = ord(data.read(<NUM_LIT:1>)) <EOL>value = byte & <NUM_LIT><EOL>shift = <NUM_LIT:1><EOL>while byte & <NUM_LIT> != <NUM_LIT:0>:<EOL><INDENT>byte = ord(data.read(<NUM_LIT:1>))<EOL>value = ((byte & <NUM_LIT>) << shift * <NUM_LIT:7>) | value<EOL>shift += <NUM_LIT:1><EOL><DEDENT>return value<EOL>

Read one VLQ-encoded integer value from an input data stream.


def read_field(field_name):<EOL><INDENT>data.read(<NUM_LIT:2>)<EOL>table[field_name] = vlq2int(data) / <NUM_LIT:2><EOL>if field_name == '<STR_LIT>':<EOL><INDENT>del table[field_name]<EOL><DEDENT><DEDENT>table = {}<EOL>for field in fields:<EOL><INDENT>read_field(field)<EOL><DEDENT>return table<EOL>

Read a table structure.

    These are used by Blizzard to collect pieces of data together. Each
    value is prefixed by two bytes, first denoting (doubled) index and the
    second denoting some sort of key -- so far it has always been '09'. The
    actual value follows as a Variable-Length Quantity, also known as uintvar.
    The actual value is also doubled.

    In some tables the keys might jump from 0A 09 to 04 09 for example.
    I have no idea why this happens, as the next logical key is 0C. Perhaps
    it's a table in a table? Some sort of headers might exist for these
    tables, I'd imagine at least denoting length. Further research required.


header = OrderedDict()<EOL>user_data_header = self.archive.header['<STR_LIT>']['<STR_LIT:content>']<EOL>if re.search(r'<STR_LIT>', user_data_header):<EOL><INDENT>user_data_header = io.StringIO(user_data_header)<EOL>user_data_header.seek(<NUM_LIT:30>) <EOL>header.update(read_table(user_data_header, ['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']))<EOL>header['<STR_LIT:version>'] = '<STR_LIT>' % (header['<STR_LIT>'],<EOL>header['<STR_LIT>'],<EOL>header['<STR_LIT>'],<EOL>header['<STR_LIT>'])<EOL>if not header['<STR_LIT>']:<EOL><INDENT>header['<STR_LIT:version>'] += '<STR_LIT>'<EOL><DEDENT>header['<STR_LIT>'] /= <NUM_LIT:16><EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return header<EOL>

Parse the user data header portion of the replay.


duration = "<STR_LIT>"<EOL>minutes, seconds = divmod(seconds, <NUM_LIT>)<EOL>if minutes >= <NUM_LIT>:<EOL><INDENT>hours, minutes = divmod(minutes, <NUM_LIT>)<EOL>duration = "<STR_LIT>" % hours<EOL><DEDENT>duration += "<STR_LIT>" % (minutes, seconds)<EOL>return duration<EOL>

Transform duration into a human-readable form.


print('<STR_LIT>', self.map)<EOL>print('<STR_LIT>', self.duration)<EOL>print('<STR_LIT>', self.version)<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>for player in self.players:<EOL><INDENT>print('<STR_LIT>'.format(**player))<EOL><DEDENT>


if not args: return url<EOL>if url[-<NUM_LIT:1>] not in ('<STR_LIT:?>', '<STR_LIT:&>'):<EOL><INDENT>url += '<STR_LIT:&>' if ('<STR_LIT:?>' in url) else '<STR_LIT:?>'<EOL><DEDENT>return url + urllib.urlencode(args)<EOL>

Concatenate url and argument dictionary regardless of whether
    url has existing query parameters.

    >>> url_concat("http://example.com/foo?a=b", dict(c="d"))
    'http://example.com/foo?a=b&c=d'


def parse_multipart_form_data(boundary, data, arguments, files):

<EOL>if boundary.startswith(b('<STR_LIT:">')) and boundary.endswith(b('<STR_LIT:">')):<EOL><INDENT>boundary = boundary[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL><DEDENT>if data.endswith(b("<STR_LIT:\r\n>")):<EOL><INDENT>footer_length = len(boundary) + <NUM_LIT:6><EOL><DEDENT>else:<EOL><INDENT>footer_length = len(boundary) + <NUM_LIT:4><EOL><DEDENT>parts = data[:-footer_length].split(b("<STR_LIT>") + boundary + b("<STR_LIT:\r\n>"))<EOL>for part in parts:<EOL><INDENT>if not part: continue<EOL>eoh = part.find(b("<STR_LIT>"))<EOL>if eoh == -<NUM_LIT:1>:<EOL><INDENT>logging.warning("<STR_LIT>")<EOL>continue<EOL><DEDENT>headers = HTTPHeaders.parse(part[:eoh].decode("<STR_LIT:utf-8>"))<EOL>disp_header = headers.get("<STR_LIT>", "<STR_LIT>")<EOL>disposition, disp_params = _parse_header(disp_header)<EOL>if disposition != "<STR_LIT>" or not part.endswith(b("<STR_LIT:\r\n>")):<EOL><INDENT>logging.warning("<STR_LIT>")<EOL>continue<EOL><DEDENT>value = part[eoh + <NUM_LIT:4>:-<NUM_LIT:2>]<EOL>if not disp_params.get("<STR_LIT:name>"):<EOL><INDENT>logging.warning("<STR_LIT>")<EOL>continue<EOL><DEDENT>name = disp_params["<STR_LIT:name>"]<EOL>if disp_params.get("<STR_LIT:filename>"):<EOL><INDENT>ctype = headers.get("<STR_LIT:Content-Type>", "<STR_LIT>")<EOL>files.setdefault(name, []).append(dict(<EOL>filename=disp_params["<STR_LIT:filename>"], body=value,<EOL>content_type=ctype))<EOL><DEDENT>else:<EOL><INDENT>arguments.setdefault(name, []).append(value)<EOL><DEDENT><DEDENT>

Parses a multipart/form-data body.

    The boundary and data parameters are both byte strings.
    The dictionaries given in the arguments and files parameters
    will be updated with the contents of the body.


parts = _parseparam('<STR_LIT:;>' + line)<EOL>key = parts.next()<EOL>pdict = {}<EOL>for p in parts:<EOL><INDENT>i = p.find('<STR_LIT:=>')<EOL>if i >= <NUM_LIT:0>:<EOL><INDENT>name = p[:i].strip().lower()<EOL>value = p[i+<NUM_LIT:1>:].strip()<EOL>if len(value) >= <NUM_LIT:2> and value[<NUM_LIT:0>] == value[-<NUM_LIT:1>] == '<STR_LIT:">':<EOL><INDENT>value = value[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>value = value.replace('<STR_LIT>', '<STR_LIT:\\>').replace('<STR_LIT>', '<STR_LIT:">')<EOL><DEDENT>pdict[name] = value<EOL><DEDENT><DEDENT>return key, pdict<EOL>

Parse a Content-type like header.

    Return the main content-type and a dictionary of options.


norm_name = HTTPHeaders._normalize_name(name)<EOL>self._last_key = norm_name<EOL>if norm_name in self:<EOL><INDENT>dict.__setitem__(self, norm_name, self[norm_name] + '<STR_LIT:U+002C>' + value)<EOL>self._as_list[norm_name].append(value)<EOL><DEDENT>else:<EOL><INDENT>self[norm_name] = value<EOL><DEDENT>


norm_name = HTTPHeaders._normalize_name(name)<EOL>return self._as_list.get(norm_name, [])<EOL>

Returns all values for the given header as a list.


for name, list in self._as_list.iteritems():<EOL><INDENT>for value in list:<EOL><INDENT>yield (name, value)<EOL><DEDENT><DEDENT>

Returns an iterable of all (name, value) pairs.

        If a header has multiple values, multiple pairs will be
        returned with the same name.


if line[<NUM_LIT:0>].isspace():<EOL><INDENT>new_part = '<STR_LIT:U+0020>' + line.lstrip()<EOL>self._as_list[self._last_key][-<NUM_LIT:1>] += new_part<EOL>dict.__setitem__(self, self._last_key,<EOL>self[self._last_key] + new_part)<EOL><DEDENT>else:<EOL><INDENT>name, value = line.split("<STR_LIT::>", <NUM_LIT:1>)<EOL>self.add(name, value.strip())<EOL><DEDENT>

Updates the dictionary with a single header line.

        >>> h = HTTPHeaders()
        >>> h.parse_line("Content-Type: text/html")
        >>> h.get('content-type')
        'text/html'


h = cls()<EOL>for line in headers.splitlines():<EOL><INDENT>if line:<EOL><INDENT>h.parse_line(line)<EOL><DEDENT><DEDENT>return h<EOL>

Returns a dictionary from HTTP header text.

        >>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
        >>> sorted(h.iteritems())
        [('Content-Length', '42'), ('Content-Type', 'text/html')]


try:<EOL><INDENT>return HTTPHeaders._normalized_headers[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>if HTTPHeaders._NORMALIZED_HEADER_RE.match(name):<EOL><INDENT>normalized = name<EOL><DEDENT>else:<EOL><INDENT>normalized = "<STR_LIT:->".join([w.capitalize() for w in name.split("<STR_LIT:->")])<EOL><DEDENT>HTTPHeaders._normalized_headers[name] = normalized<EOL>return normalized<EOL><DEDENT>

Converts a name to Http-Header-Case.

        >>> HTTPHeaders._normalize_name("coNtent-TYPE")
        'Content-Type'


return _XHTML_ESCAPE_RE.sub(lambda match: _XHTML_ESCAPE_DICT[match.group(<NUM_LIT:0>)],<EOL>to_basestring(value))<EOL>

Escapes a string so it is valid within XML or XHTML.


return re.sub(r"<STR_LIT>", _convert_entity, _unicode(value))<EOL>


<EOL>return _json_encode(recursive_unicode(value)).replace("<STR_LIT>", "<STR_LIT>")<EOL>


return _json_decode(to_basestring(value))<EOL>

Returns Python objects for the given JSON string.


return re.sub(r"<STR_LIT>", "<STR_LIT:U+0020>", value).strip()<EOL>

Replace all sequences of whitespace chars with a single space.


return urllib.parse.quote_plus(utf8(value))<EOL>

Returns a valid URL-encoded version of the given value.


if isinstance(value, _UTF8_TYPES):<EOL><INDENT>return value<EOL><DEDENT>assert isinstance(value, str)<EOL>return value.encode("<STR_LIT:utf-8>")<EOL>

Converts a string argument to a byte string.

    If the argument is already a byte string or None, it is returned unchanged.
    Otherwise it must be a unicode string and is encoded as utf8.


if isinstance(value, _TO_UNICODE_TYPES):<EOL><INDENT>return value<EOL><DEDENT>assert isinstance(value, bytes)<EOL>return value.decode("<STR_LIT:utf-8>")<EOL>

Converts a string argument to a unicode string.

    If the argument is already a unicode string or None, it is returned
    unchanged.  Otherwise it must be a byte string and is decoded as utf8.


if isinstance(value, _BASESTRING_TYPES):<EOL><INDENT>return value<EOL><DEDENT>assert isinstance(value, bytes)<EOL>return value.decode("<STR_LIT:utf-8>")<EOL>

Converts a string argument to a subclass of basestring.

    In python2, byte and unicode strings are mostly interchangeable,
    so functions that deal with a user-supplied argument in combination
    with ascii string constants can use either and should return the type
    the user supplied.  In python3, the two types are not interchangeable,
    so this method is needed to convert byte strings to unicode.


if isinstance(obj, dict):<EOL><INDENT>return dict((recursive_unicode(k), recursive_unicode(v)) for (k,v) in obj.items())<EOL><DEDENT>elif isinstance(obj, list):<EOL><INDENT>return list(recursive_unicode(i) for i in obj)<EOL><DEDENT>elif isinstance(obj, tuple):<EOL><INDENT>return tuple(recursive_unicode(i) for i in obj)<EOL><DEDENT>elif isinstance(obj, bytes):<EOL><INDENT>return to_unicode(obj)<EOL><DEDENT>else:<EOL><INDENT>return obj<EOL><DEDENT>

Walks a simple data structure, converting byte strings to unicode.

    Supports lists, tuples, and dictionaries.


def linkify(text, shorten=False, extra_params="<STR_LIT>",<EOL>require_protocol=False, permitted_protocols=["<STR_LIT:http>", "<STR_LIT>"]):

if extra_params:<EOL><INDENT>extra_params = "<STR_LIT:U+0020>" + extra_params.strip()<EOL><DEDENT>def make_link(m):<EOL><INDENT>url = m.group(<NUM_LIT:1>)<EOL>proto = m.group(<NUM_LIT:2>)<EOL>if require_protocol and not proto:<EOL><INDENT>return url  <EOL><DEDENT>if proto and proto not in permitted_protocols:<EOL><INDENT>return url  <EOL><DEDENT>href = m.group(<NUM_LIT:1>)<EOL>if not proto:<EOL><INDENT>href = "<STR_LIT>" + href   <EOL><DEDENT>params = extra_params<EOL>max_len = <NUM_LIT:30><EOL>if shorten and len(url) > max_len:<EOL><INDENT>before_clip = url<EOL>if proto:<EOL><INDENT>proto_len = len(proto) + <NUM_LIT:1> + len(m.group(<NUM_LIT:3>) or "<STR_LIT>")  <EOL><DEDENT>else:<EOL><INDENT>proto_len = <NUM_LIT:0><EOL><DEDENT>parts = url[proto_len:].split("<STR_LIT:/>")<EOL>if len(parts) > <NUM_LIT:1>:<EOL><INDENT>url = url[:proto_len] + parts[<NUM_LIT:0>] + "<STR_LIT:/>" +parts[<NUM_LIT:1>][:<NUM_LIT:8>].split('<STR_LIT:?>')[<NUM_LIT:0>].split('<STR_LIT:.>')[<NUM_LIT:0>]<EOL><DEDENT>if len(url) > max_len * <NUM_LIT>:  <EOL><INDENT>url = url[:max_len]<EOL><DEDENT>if url != before_clip:<EOL><INDENT>amp = url.rfind('<STR_LIT:&>')<EOL>if amp > max_len - <NUM_LIT:5>:<EOL><INDENT>url = url[:amp]<EOL><DEDENT>url += "<STR_LIT>"<EOL>if len(url) >= len(before_clip):<EOL><INDENT>url = before_clip<EOL><DEDENT>else:<EOL><INDENT>params += '<STR_LIT>' % href<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>' % (href, params, url)<EOL><DEDENT>text = _unicode(xhtml_escape(text))<EOL>return _URL_RE.sub(make_link, text)<EOL>

Converts plain text into HTML with links.

    For example: ``linkify("Hello http://tornadoweb.org!")`` would return
    ``Hello http://tornadoweb.org!``

    Parameters:

    shorten: Long urls will be shortened for display.

    extra_params: Extra text to include in the link tag,
        e.g. linkify(text, extra_params='rel="nofollow" class="external"')

    require_protocol: Only linkify urls which include a protocol. If this is
        False, urls such as www.facebook.com will also be linkified.

    permitted_protocols: List (or set) of protocols which should be linkified,
        e.g. linkify(text, permitted_protocols=["http", "ftp", "mailto"]).
        It is very unsafe to include protocols such as "javascript".


def _oauth_signature(consumer_token, method, url, parameters={}, token=None):

parts = urlparse.urlparse(url)<EOL>scheme, netloc, path = parts[:<NUM_LIT:3>]<EOL>normalized_url = scheme.lower() + "<STR_LIT>" + netloc.lower() + path<EOL>base_elems = []<EOL>base_elems.append(method.upper())<EOL>base_elems.append(normalized_url)<EOL>base_elems.append("<STR_LIT:&>".join("<STR_LIT>" % (k, _oauth_escape(str(v)))<EOL>for k, v in sorted(parameters.items())))<EOL>base_string =  "<STR_LIT:&>".join(_oauth_escape(e) for e in base_elems)<EOL>key_elems = [consumer_token["<STR_LIT>"]]<EOL>key_elems.append(token["<STR_LIT>"] if token else "<STR_LIT>")<EOL>key = "<STR_LIT:&>".join(key_elems)<EOL>hash = hmac.new(key, base_string, hashlib.sha1)<EOL>return binascii.b2a_base64(hash.digest())[:-<NUM_LIT:1>]<EOL>

Calculates the HMAC-SHA1 OAuth signature for the given request.

    See http://oauth.net/core/1.0/#signing_process


def _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):

parts = urlparse.urlparse(url)<EOL>scheme, netloc, path = parts[:<NUM_LIT:3>]<EOL>normalized_url = scheme.lower() + "<STR_LIT>" + netloc.lower() + path<EOL>base_elems = []<EOL>base_elems.append(method.upper())<EOL>base_elems.append(normalized_url)<EOL>base_elems.append("<STR_LIT:&>".join("<STR_LIT>" % (k, _oauth_escape(str(v)))<EOL>for k, v in sorted(parameters.items())))<EOL>base_string =  "<STR_LIT:&>".join(_oauth_escape(e) for e in base_elems)<EOL>key_elems = [urllib.quote(consumer_token["<STR_LIT>"], safe='<STR_LIT>')]<EOL>key_elems.append(urllib.quote(token["<STR_LIT>"], safe='<STR_LIT>') if token else "<STR_LIT>")<EOL>key = "<STR_LIT:&>".join(key_elems)<EOL>hash = hmac.new(key, base_string, hashlib.sha1)<EOL>return binascii.b2a_base64(hash.digest())[:-<NUM_LIT:1>]<EOL>

Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.

    See http://oauth.net/core/1.0a/#signing_process


def require_setting(self, name, feature="<STR_LIT>"):

if name not in self.settings:<EOL><INDENT>raise Exception("<STR_LIT>"<EOL>"<STR_LIT>" % (name, feature))<EOL><DEDENT>

Raises an exception if the given app setting is not defined.


def get_argument(self, name, default=_ARG_DEFAULT, strip=True):

args = self.get_arguments(name, strip=strip)<EOL>if not args:<EOL><INDENT>if default is self._ARG_DEFAULT:<EOL><INDENT>raise HTTPError(<NUM_LIT>, "<STR_LIT>" % name)<EOL><DEDENT>return default<EOL><DEDENT>return args[-<NUM_LIT:1>]<EOL>

Returns the value of the argument with the given name.

        If default is not provided, the argument is considered to be
        required, and we throw an HTTP 400 exception if it is missing.

        If the argument appears in the url more than once, we return the
        last value.

        The returned value is always unicode.


def get_arguments(self, name, strip=True):

values = []<EOL>for v in self.request.params.getall(name):<EOL><INDENT>v = self.decode_argument(v, name=name)<EOL>if isinstance(v, unicode):<EOL><INDENT>v = re.sub(r"<STR_LIT>", "<STR_LIT:U+0020>", v)<EOL><DEDENT>if strip:<EOL><INDENT>v = v.strip()<EOL><DEDENT>values.append(v)<EOL><DEDENT>return values<EOL>

Returns a list of the arguments with the given name.

        If the argument is not present, returns an empty list.

        The returned values are always unicode.


def decode_argument(self, value, name=None):

return _unicode(value)<EOL>

Decodes an argument from the request.

        The argument has been percent-decoded and is now a byte string.
        By default, this method decodes the argument as utf-8 and returns
        a unicode string, but this may be overridden in subclasses.

        This method is used as a filter for both get_argument() and for
        values extracted from the url and passed to get()/post()/etc.

        The name of the argument is provided if known, but may be None
        (e.g. for unnamed groups in the url regex).


def async_callback(self, callback, *args, **kwargs):

if callback is None:<EOL><INDENT>return None<EOL><DEDENT>if args or kwargs:<EOL><INDENT>callback = functools.partial(callback, *args, **kwargs)<EOL><DEDENT>return callback<EOL>

Obsolete - catches exceptions from the wrapped function.

        This function is unnecessary since Tornado 1.1.


def get_cookie(self, name, default=None):

assert self.cookie_monster, '<STR_LIT>'<EOL>return self.cookie_monster.get_cookie(name, default)<EOL>

Gets the value of the cookie with the given name, else default.


def set_cookie(self, name, value, domain=None, expires=None, path="<STR_LIT:/>",<EOL>expires_days=None, **kwargs):

assert self.cookie_monster, '<STR_LIT>'<EOL>self.cookie_monster.set_cookie(name, value)<EOL>

Sets the given cookie name/value with the given options.

        Additional keyword arguments are set on the Cookie.Morsel
        directly.
        See http://docs.python.org/library/cookie.html#morsel-objects
        for available attributes.


def clear_cookie(self, name, path="<STR_LIT:/>", domain=None):

assert self.cookie_monster, '<STR_LIT>'<EOL>self.cookie_monster.delete_cookie(name)<EOL>


def authenticate_redirect(<EOL>self, callback_uri=None, ax_attrs=["<STR_LIT:name>", "<STR_LIT:email>", "<STR_LIT>",<EOL>"<STR_LIT:username>"]):

callback_uri = callback_uri or self.request.uri<EOL>args = self._openid_args(callback_uri, ax_attrs=ax_attrs)<EOL>self.redirect(self._OPENID_ENDPOINT + "<STR_LIT:?>" + urllib.urlencode(args))<EOL>

Returns the authentication URL for this service.

        After authentication, the service will redirect back to the given
        callback URI.

        We request the given attributes for the authenticated user by
        default (name, email, language, and username). If you don't need
        all those attributes for your app, you can request fewer with
        the ax_attrs keyword argument.


<EOL>args = dict((k, unicode(v[-<NUM_LIT:1>]).encode('<STR_LIT:utf-8>')) for k, v in self.request.arguments.iteritems())<EOL>args["<STR_LIT>"] = u"<STR_LIT>"<EOL>url = self._OPENID_ENDPOINT<EOL>http = httpclient.AsyncHTTPClient()<EOL>log.debug("<STR_LIT>".format(args, url))<EOL>http.fetch(url, self.async_callback(<EOL>self._on_authentication_verified, callback),<EOL>method="<STR_LIT:POST>", body=urllib.urlencode(args))<EOL>

Fetches the authenticated user data upon redirect.

        This method should be called by the handler that receives the
        redirect from the authenticate_redirect() or authorize_redirect()
        methods.


def authorize_redirect(self, callback_uri=None, extra_params=None):

if callback_uri and getattr(self, "<STR_LIT>", False):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>http = httpclient.AsyncHTTPClient()<EOL>if getattr(self, "<STR_LIT>", "<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>http.fetch(self._oauth_request_token_url(callback_uri=callback_uri,<EOL>extra_params=extra_params),<EOL>self.async_callback(<EOL>self._on_request_token,<EOL>self._OAUTH_AUTHORIZE_URL,<EOL>callback_uri))<EOL><DEDENT>else:<EOL><INDENT>http.fetch(self._oauth_request_token_url(), self.async_callback(<EOL>self._on_request_token, self._OAUTH_AUTHORIZE_URL, callback_uri))<EOL><DEDENT>

Redirects the user to obtain OAuth authorization for this service.

        Twitter and FriendFeed both require that you register a Callback
        URL with your application. You should call this method to log the
        user in, and then call get_authenticated_user() in the handler
        you registered as your Callback URL to complete the authorization
        process.

        This method sets a cookie called _oauth_request_token which is
        subsequently used (and cleared) in get_authenticated_user for
        security purposes.


request_key = self.get_argument("<STR_LIT>")<EOL>oauth_verifier = self.get_argument("<STR_LIT>", None)<EOL>request_cookie = self.get_cookie("<STR_LIT>")<EOL>if not request_cookie:<EOL><INDENT>log.warning("<STR_LIT>")<EOL>callback(None)<EOL>return<EOL><DEDENT>self.clear_cookie("<STR_LIT>")<EOL>cookie_key, cookie_secret = [base64.b64decode(i) for i in request_cookie.split("<STR_LIT:|>")]<EOL>if cookie_key != request_key:<EOL><INDENT>log.warning("<STR_LIT>")<EOL>callback(None)<EOL>return<EOL><DEDENT>token = dict(key=cookie_key, secret=cookie_secret)<EOL>if oauth_verifier:<EOL><INDENT>token["<STR_LIT>"] = oauth_verifier<EOL><DEDENT>http = httpclient.AsyncHTTPClient()<EOL>http.fetch(self._oauth_access_token_url(token), self.async_callback(<EOL>self._on_access_token, callback))<EOL>

Gets the OAuth authorized user and access token on callback.

        This method should be called from the handler for your registered
        OAuth Callback URL to complete the registration process. We call
        callback with the authenticated user, which in addition to standard
        attributes like 'name' includes the 'access_key' attribute, which
        contains the OAuth access you can use to make authorized requests
        to this service on behalf of the user.


def _oauth_request_parameters(self, url, access_token, parameters={},<EOL>method="<STR_LIT:GET>"):

consumer_token = self._oauth_consumer_token()<EOL>base_args = dict(<EOL>oauth_consumer_key=consumer_token["<STR_LIT:key>"],<EOL>oauth_token=access_token["<STR_LIT:key>"],<EOL>oauth_signature_method="<STR_LIT>",<EOL>oauth_timestamp=str(int(time.time())),<EOL>oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),<EOL>oauth_version=getattr(self, "<STR_LIT>", "<STR_LIT>"),<EOL>)<EOL>args = {}<EOL>args.update(base_args)<EOL>args.update(parameters)<EOL>if getattr(self, "<STR_LIT>", "<STR_LIT>") == "<STR_LIT>":<EOL><INDENT>signature = _oauth10a_signature(consumer_token, method, url, args,<EOL>access_token)<EOL><DEDENT>else:<EOL><INDENT>signature = _oauth_signature(consumer_token, method, url, args,<EOL>access_token)<EOL><DEDENT>base_args["<STR_LIT>"] = signature<EOL>return base_args<EOL>

Returns the OAuth parameters as a dict for the given request.

        parameters should include all POST arguments and query string arguments
        that will be sent with the request.


def authorize_redirect(self, redirect_uri=None, client_id=None,<EOL>client_secret=None, extra_params=None ):

args = {<EOL>"<STR_LIT>": redirect_uri,<EOL>"<STR_LIT>": client_id<EOL>}<EOL>if extra_params: args.update(extra_params)<EOL>self.redirect(<EOL>url_concat(self._OAUTH_AUTHORIZE_URL, args))<EOL>

Redirects the user to obtain OAuth authorization for this service.

        Some providers require that you register a Callback
        URL with your application. You should call this method to log the
        user in, and then call get_authenticated_user() in the handler
        you registered as your Callback URL to complete the authorization
        process.


http = httpclient.AsyncHTTPClient()<EOL>http.fetch(self._oauth_request_token_url(), self.async_callback(<EOL>self._on_request_token, self._OAUTH_AUTHENTICATE_URL, None))<EOL>

Just like authorize_redirect(), but auto-redirects if authorized.

        This is generally the right interface to use if you are using
        Twitter for single-sign on.


def twitter_request(self, path, callback, access_token=None,<EOL>post_args=None, **args):

<EOL>url = "<STR_LIT>" + path + "<STR_LIT>"<EOL>if access_token:<EOL><INDENT>all_args = {}<EOL>all_args.update(args)<EOL>all_args.update(post_args or {})<EOL>consumer_token = self._oauth_consumer_token()<EOL>method = "<STR_LIT:POST>" if post_args is not None else "<STR_LIT:GET>"<EOL>oauth = self._oauth_request_parameters(<EOL>url, access_token, all_args, method=method)<EOL>args.update(oauth)<EOL><DEDENT>if args: url += "<STR_LIT:?>" + urllib.urlencode(args)<EOL>callback = self.async_callback(self._on_twitter_request, callback)<EOL>http = httpclient.AsyncHTTPClient()<EOL>if post_args is not None:<EOL><INDENT>http.fetch(url, method="<STR_LIT:POST>", body=urllib.urlencode(post_args),<EOL>callback=callback)<EOL><DEDENT>else:<EOL><INDENT>http.fetch(url, callback=callback)<EOL><DEDENT>

Fetches the given API path, e.g., "/statuses/user_timeline/btaylor"

        The path should not include the format (we automatically append
        ".json" and parse the JSON output).

        If the request is a POST, post_args should be provided. Query
        string arguments should be given as keyword arguments.

        All the Twitter methods are documented at
        http://apiwiki.twitter.com/Twitter-API-Documentation.

        Many methods require an OAuth access token which you can obtain
        through authorize_redirect() and get_authenticated_user(). The
        user returned through that process includes an 'access_token'
        attribute that can be used to make authenticated requests via
        this method. Example usage::

            class MainHandler(tornado.web.RequestHandler,
                              tornado.auth.TwitterMixin):
                @tornado.web.authenticated
                @tornado.web.asynchronous
                def get(self):
                    self.twitter_request(
                        "/statuses/update",
                        post_args={"status": "Testing Tornado Web Server"},
                        access_token=user["access_token"],
                        callback=self.async_callback(self._on_post))

                def _on_post(self, new_entry):
                    if not new_entry:
                        # Call failed; perhaps missing permission?
                        self.authorize_redirect()
                        return
                    self.finish("Posted a message!")


def friendfeed_request(self, path, callback, access_token=None,<EOL>post_args=None, **args):

<EOL>url = "<STR_LIT>" + path<EOL>if access_token:<EOL><INDENT>all_args = {}<EOL>all_args.update(args)<EOL>all_args.update(post_args or {})<EOL>consumer_token = self._oauth_consumer_token()<EOL>method = "<STR_LIT:POST>" if post_args is not None else "<STR_LIT:GET>"<EOL>oauth = self._oauth_request_parameters(<EOL>url, access_token, all_args, method=method)<EOL>args.update(oauth)<EOL><DEDENT>if args: url += "<STR_LIT:?>" + urllib.urlencode(args)<EOL>callback = self.async_callback(self._on_friendfeed_request, callback)<EOL>http = httpclient.AsyncHTTPClient()<EOL>if post_args is not None:<EOL><INDENT>http.fetch(url, method="<STR_LIT:POST>", body=urllib.urlencode(post_args),<EOL>callback=callback)<EOL><DEDENT>else:<EOL><INDENT>http.fetch(url, callback=callback)<EOL><DEDENT>

Fetches the given relative API path, e.g., "/bret/friends"

        If the request is a POST, post_args should be provided. Query
        string arguments should be given as keyword arguments.

        All the FriendFeed methods are documented at
        http://friendfeed.com/api/documentation.

        Many methods require an OAuth access token which you can obtain
        through authorize_redirect() and get_authenticated_user(). The
        user returned through that process includes an 'access_token'
        attribute that can be used to make authenticated requests via
        this method. Example usage::

            class MainHandler(tornado.web.RequestHandler,
                              tornado.auth.FriendFeedMixin):
                @tornado.web.authenticated
                @tornado.web.asynchronous
                def get(self):
                    self.friendfeed_request(
                        "/entry",
                        post_args={"body": "Testing Tornado Web Server"},
                        access_token=self.current_user["access_token"],
                        callback=self.async_callback(self._on_post))

                def _on_post(self, new_entry):
                    if not new_entry:
                        # Call failed; perhaps missing permission?
                        self.authorize_redirect()
                        return
                    self.finish("Posted a message!")


callback_uri = callback_uri or self.request.uri<EOL>args = self._openid_args(callback_uri, ax_attrs=ax_attrs,<EOL>oauth_scope=oauth_scope)<EOL>self.redirect(self._OPENID_ENDPOINT + "<STR_LIT:?>" + urllib.urlencode(args))<EOL>

Authenticates and authorizes for the given Google resource.

        Some of the available resources are:

        * Gmail Contacts - http://www.google.com/m8/feeds/
        * Calendar - http://www.google.com/calendar/feeds/
        * Finance - http://finance.google.com/finance/feeds/

        You can authorize multiple resources by separating the resource
        URLs with a space.


<EOL>oauth_ns = "<STR_LIT>"<EOL>for name, values in self.request.arguments.iteritems():<EOL><INDENT>if name.startswith("<STR_LIT>") andvalues[-<NUM_LIT:1>] == u"<STR_LIT>":<EOL><INDENT>oauth_ns = name[<NUM_LIT:10>:]<EOL>break<EOL><DEDENT><DEDENT>token = self.get_argument("<STR_LIT>" + oauth_ns + "<STR_LIT>", "<STR_LIT>")<EOL>if token:<EOL><INDENT>http = httpclient.AsyncHTTPClient()<EOL>token = dict(key=token, secret="<STR_LIT>")<EOL>http.fetch(self._oauth_access_token_url(token),<EOL>self.async_callback(self._on_access_token, callback))<EOL><DEDENT>else:<EOL><INDENT>OpenIdMixin.get_authenticated_user(self, callback)<EOL><DEDENT>

Fetches the authenticated user data upon redirect.


def authenticate_redirect(self, callback_uri=None, cancel_uri=None,<EOL>extended_permissions=None):

self.require_setting("<STR_LIT>", "<STR_LIT>")<EOL>callback_uri = callback_uri or self.request.uri<EOL>args = {<EOL>"<STR_LIT>": self.settings["<STR_LIT>"],<EOL>"<STR_LIT:v>": "<STR_LIT:1.0>",<EOL>"<STR_LIT>": "<STR_LIT:true>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": urlparse.urljoin(self.request.full_url(), callback_uri),<EOL>"<STR_LIT>": "<STR_LIT:true>",<EOL>}<EOL>if cancel_uri:<EOL><INDENT>args["<STR_LIT>"] = urlparse.urljoin(<EOL>self.request.full_url(), cancel_uri)<EOL><DEDENT>if extended_permissions:<EOL><INDENT>if isinstance(extended_permissions, (unicode, bytes_type)):<EOL><INDENT>extended_permissions = [extended_permissions]<EOL><DEDENT>args["<STR_LIT>"] = "<STR_LIT:U+002C>".join(extended_permissions)<EOL><DEDENT>self.redirect("<STR_LIT>" +<EOL>urllib.urlencode(args))<EOL>

Authenticates/installs this app for the current user.


def authorize_redirect(self, extended_permissions, callback_uri=None,<EOL>cancel_uri=None):

self.authenticate_redirect(callback_uri, cancel_uri,<EOL>extended_permissions)<EOL>

Redirects to an authorization request for the given FB resource.

        The available resource names are listed at
        http://wiki.developers.facebook.com/index.php/Extended_permission.
        The most common resource types include:

        * publish_stream
        * read_stream
        * email
        * sms

        extended_permissions can be a single permission name or a list of
        names. To get the session secret and session key, call
        get_authenticated_user() just as you would with
        authenticate_redirect().


Fetches the authenticated Facebook user.

        The authenticated user includes the special Facebook attributes
        'session_key' and 'facebook_uid' in addition to the standard
        user attributes like 'name'.


def facebook_request(self, method, callback, **args):

self.require_setting("<STR_LIT>", "<STR_LIT>")<EOL>self.require_setting("<STR_LIT>", "<STR_LIT>")<EOL>if not method.startswith("<STR_LIT>"):<EOL><INDENT>method = "<STR_LIT>" + method<EOL><DEDENT>args["<STR_LIT>"] = self.settings["<STR_LIT>"]<EOL>args["<STR_LIT:v>"] = "<STR_LIT:1.0>"<EOL>args["<STR_LIT>"] = method<EOL>args["<STR_LIT>"] = str(long(time.time() * <NUM_LIT>))<EOL>args["<STR_LIT>"] = "<STR_LIT>"<EOL>args["<STR_LIT>"] = self._signature(args)<EOL>url = "<STR_LIT>" +urllib.urlencode(args)<EOL>http = httpclient.AsyncHTTPClient()<EOL>http.fetch(url, callback=self.async_callback(<EOL>self._parse_response, callback))<EOL>

Makes a Facebook API REST request.

        We automatically include the Facebook API key and signature, but
        it is the callers responsibility to include 'session_key' and any
        other required arguments to the method.

        The available Facebook methods are documented here:
        http://wiki.developers.facebook.com/index.php/API

        Here is an example for the stream.get() method::

            class MainHandler(tornado.web.RequestHandler,
                              tornado.auth.FacebookMixin):
                @tornado.web.authenticated
                @tornado.web.asynchronous
                def get(self):
                    self.facebook_request(
                        method="stream.get",
                        callback=self.async_callback(self._on_stream),
                        session_key=self.current_user["session_key"])

                def _on_stream(self, stream):
                    if stream is None:
                       # Not authorized to read the stream yet?
                       self.redirect(self.authorize_redirect("read_stream"))
                       return
                    self.render("stream.html", stream=stream)


def get_authenticated_user(self, redirect_uri, client_id, client_secret,<EOL>code, callback, fields=None):

http = httpclient.AsyncHTTPClient()<EOL>args = {<EOL>"<STR_LIT>": redirect_uri,<EOL>"<STR_LIT:code>": code,<EOL>"<STR_LIT>": client_id,<EOL>"<STR_LIT>": client_secret,<EOL>}<EOL>if fields:<EOL><INDENT>fields = fields.split('<STR_LIT:U+002C>')<EOL><DEDENT>http.fetch(self._oauth_request_token_url(**args),<EOL>self.async_callback(self._on_access_token, redirect_uri, client_id,<EOL>client_secret, callback, fields))<EOL>

Handles the login for the Facebook user, returning a user object.

        Example usage::

            class FacebookGraphLoginHandler(LoginHandler, tornado.auth.FacebookGraphMixin):
              @tornado.web.asynchronous
              def get(self):
                  if self.get_argument("code", False):
                      self.get_authenticated_user(
                        redirect_uri='/auth/facebookgraph/',
                        client_id=self.settings["facebook_api_key"],
                        client_secret=self.settings["facebook_secret"],
                        code=self.get_argument("code"),
                        callback=self.async_callback(
                          self._on_login))
                      return
                  self.authorize_redirect(redirect_uri='/auth/facebookgraph/',
                                          client_id=self.settings["facebook_api_key"],
                                          extra_params={"scope": "read_stream,offline_access"})

              def _on_login(self, user):
                log.error(user)
                self.finish()