prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from distutils.core import setup setup(name='django-modeltranslation', version='0.4.0-alpha1', description='Translates Django models using a registration approach.', long_description='The modeltranslation application can be used to ' 'translate dynamic content of existing models to an ' 'arbitrary number of languages without having to ' 'change the original model classes. It uses a ' 'registration approach (comparable to Django\'s admin ' 'app) to be able to add translations to existing or ' 'new projects and is fully integrated into the Django ' 'admin backend.', author='Peter Eschler', author_email='[email protected]', maintainer='Dirk Eschler', maintainer_email='[email protected]',<|fim▁hole|> packages=['modeltranslation', 'modeltranslation.management', 'modeltranslation.management.commands'], package_data={'modeltranslation': ['static/modeltranslation/css/*.css', 'static/modeltranslation/js/*.js']}, include_package_data = True, requires=['django(>=1.0)'], download_url='http://django-modeltranslation.googlecode.com/files/django-modeltranslation-0.4.0-alpha1.tar.gz', classifiers=['Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License'], license='New BSD')<|fim▁end|>
url='http://code.google.com/p/django-modeltranslation/',
<|file_name|>func_noerror_query_heir.py<|end_file_name|><|fim▁begin|># pylint:disable=R0201 from OpenOrange import * from User import User from RetroactiveAccounts import RetroactiveAccounts class HeirFinder(RetroactiveAccounts): def doReplacements(self, txt): d = {1:"ONE", 2:"TWO"} us = User.bring("USER") txt = txt.replace(":1", us.Name + d[1]) return txt def run(self): query8 = self.getQuery()<|fim▁hole|> #pylint:disable=E6601 query8.open() #there will be missing tables here<|fim▁end|>
query8.sql = self.doReplacements(query8.sql)
<|file_name|>func_noerror_query_heir.py<|end_file_name|><|fim▁begin|># pylint:disable=R0201 from OpenOrange import * from User import User from RetroactiveAccounts import RetroactiveAccounts class HeirFinder(RetroactiveAccounts): <|fim_middle|> <|fim▁end|>
def doReplacements(self, txt): d = {1:"ONE", 2:"TWO"} us = User.bring("USER") txt = txt.replace(":1", us.Name + d[1]) return txt def run(self): query8 = self.getQuery() query8.sql = self.doReplacements(query8.sql) #pylint:disable=E6601 query8.open() #there will be missing tables here
<|file_name|>func_noerror_query_heir.py<|end_file_name|><|fim▁begin|># pylint:disable=R0201 from OpenOrange import * from User import User from RetroactiveAccounts import RetroactiveAccounts class HeirFinder(RetroactiveAccounts): def doReplacements(self, txt): <|fim_middle|> def run(self): query8 = self.getQuery() query8.sql = self.doReplacements(query8.sql) #pylint:disable=E6601 query8.open() #there will be missing tables here <|fim▁end|>
d = {1:"ONE", 2:"TWO"} us = User.bring("USER") txt = txt.replace(":1", us.Name + d[1]) return txt
<|file_name|>func_noerror_query_heir.py<|end_file_name|><|fim▁begin|># pylint:disable=R0201 from OpenOrange import * from User import User from RetroactiveAccounts import RetroactiveAccounts class HeirFinder(RetroactiveAccounts): def doReplacements(self, txt): d = {1:"ONE", 2:"TWO"} us = User.bring("USER") txt = txt.replace(":1", us.Name + d[1]) return txt def run(self): <|fim_middle|> <|fim▁end|>
query8 = self.getQuery() query8.sql = self.doReplacements(query8.sql) #pylint:disable=E6601 query8.open() #there will be missing tables here
<|file_name|>func_noerror_query_heir.py<|end_file_name|><|fim▁begin|># pylint:disable=R0201 from OpenOrange import * from User import User from RetroactiveAccounts import RetroactiveAccounts class HeirFinder(RetroactiveAccounts): def <|fim_middle|>(self, txt): d = {1:"ONE", 2:"TWO"} us = User.bring("USER") txt = txt.replace(":1", us.Name + d[1]) return txt def run(self): query8 = self.getQuery() query8.sql = self.doReplacements(query8.sql) #pylint:disable=E6601 query8.open() #there will be missing tables here <|fim▁end|>
doReplacements
<|file_name|>func_noerror_query_heir.py<|end_file_name|><|fim▁begin|># pylint:disable=R0201 from OpenOrange import * from User import User from RetroactiveAccounts import RetroactiveAccounts class HeirFinder(RetroactiveAccounts): def doReplacements(self, txt): d = {1:"ONE", 2:"TWO"} us = User.bring("USER") txt = txt.replace(":1", us.Name + d[1]) return txt def <|fim_middle|>(self): query8 = self.getQuery() query8.sql = self.doReplacements(query8.sql) #pylint:disable=E6601 query8.open() #there will be missing tables here <|fim▁end|>
run
<|file_name|>DataTypeMapIntFloat.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2]))<|fim▁hole|>assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}}<|fim▁end|>
def to_objectset(xs): return set([frozenset(x.items()) for x in xs])
<|file_name|>DataTypeMapIntFloat.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def to_objectset(xs): <|fim_middle|> assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}} <|fim▁end|>
return set([frozenset(x.items()) for x in xs])
<|file_name|>DataTypeMapIntFloat.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def <|fim_middle|>(xs): return set([frozenset(x.items()) for x in xs]) assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}} <|fim▁end|>
to_objectset
<|file_name|>test_issue_064.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
def test_is_generator_alias(): from nose.util import is_generator, isgenerator
<|file_name|>test_issue_064.py<|end_file_name|><|fim▁begin|>def test_is_generator_alias(): <|fim_middle|> <|fim▁end|>
from nose.util import is_generator, isgenerator
<|file_name|>test_issue_064.py<|end_file_name|><|fim▁begin|>def <|fim_middle|>(): from nose.util import is_generator, isgenerator <|fim▁end|>
test_is_generator_alias
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted<|fim▁hole|> a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'}<|fim▁end|>
:status 404: Bot was not found """
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): <|fim_middle|> @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
"""Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]}
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): <|fim_middle|> @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
"""Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize()
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): <|fim_middle|> @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
"""Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)}
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): <|fim_middle|> @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
return NotImplemented
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): <|fim_middle|> @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
"""Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'}
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): <|fim_middle|> <|fim▁end|>
"""Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'}
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: <|fim_middle|> db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
return {'message': 'No such bot'}, 404
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def <|fim_middle|>(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
get_abusehelper
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def <|fim_middle|>(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
get_got
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def <|fim_middle|>(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
add_bot
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def <|fim_middle|>(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
update_bot
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def <|fim_middle|>(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
delete_bot
<|file_name|>abusehelper.py<|end_file_name|><|fim▁begin|>from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "abusehelper": [ { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """ bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/<int:bot_id>', methods=['GET']) @json_response def get_got(bot_id): """Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """ a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { "name": "ShadowServerBot", "url": "http://sample.com/path.html" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { "bot": { "name": "ShadowServerBot", "url": "http://sample.com/path.html", "id": 1 }, 'message': "Bot added" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :<json integer name: Bot name :>jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """ a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/<int:bot_id>', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/<int:bot_id>', methods=['DELETE']) @json_response def delete_bot(bot_id): """Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bot deleted" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def <|fim_middle|>(): """Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { "message": "Bots deleted" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} <|fim▁end|>
delete_abusehelper
<|file_name|>EasyDialogs_AskYesNoCancel.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import EasyDialogs valid_responses = { 1:'yes', 0:'no', -1:'cancel', } response = EasyDialogs.AskYesNoCancel('Select an option')<|fim▁hole|><|fim▁end|>
print 'You selected:', valid_responses[response]
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta'))<|fim▁hole|> def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main()<|fim▁end|>
except OSError: pass
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): <|fim_middle|> def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role))
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): <|fim_middle|> def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {}
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): <|fim_middle|> def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
"""Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): <|fim_middle|> def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): <|fim_middle|> def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
"""Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): <|fim_middle|> def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return []
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): <|fim_middle|> def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
"""Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): <|fim_middle|> metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): <|fim_middle|> def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): <|fim_middle|> def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): <|fim_middle|> def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
create_role(into) for role in roles: move(role, target_role=into, copy=copy)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): <|fim_middle|> def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3])
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): <|fim_middle|> def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
raise Exception('could not create role "{}"'.format(role))
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): <|fim_middle|> else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
return os.path.join(for_destination, 'roles', dep)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: <|fim_middle|> metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
return dep
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: <|fim_middle|> concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
os.chdir(roles_path)
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
main()
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def <|fim_middle|>(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
create_role
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def <|fim_middle|>(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
get_metadata
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def <|fim_middle|>(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
ensure_meta
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def <|fim_middle|>(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
set_metadata
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def <|fim_middle|>(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
add_dependency
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def <|fim_middle|>(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
sub_roles
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def <|fim_middle|>(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
fix_dependency
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def <|fim_middle|>(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
f
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def <|fim_middle|>(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
fix_dependencies
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def <|fim_middle|>(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
move
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def <|fim_middle|>(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
concat
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def <|fim_middle|>(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
test
<|file_name|>concat_roles.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import glob import os import shutil import subprocess import sys import yaml def create_role(role): ret = subprocess.check_output( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role "{}"'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """Ensure the role has a meta directory""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """Add metadata saying that 'target_role' depends on 'src_role'""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """ metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def <|fim_middle|>(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() <|fim▁end|>
main
<|file_name|>0005_auto_20170521_0103.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('maposmatic', '0004_maprenderingjob_track'), ] operations = [ migrations.AlterField(<|fim▁hole|> ]<|fim▁end|>
model_name='maprenderingjob', name='track', field=models.FileField(null=True, upload_to=b'upload/tracks/', blank=True), ),
<|file_name|>0005_auto_20170521_0103.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('maposmatic', '0004_maprenderingjob_track'), ] operations = [ migrations.AlterField( model_name='maprenderingjob', name='track', field=models.FileField(null=True, upload_to=b'upload/tracks/', blank=True), ), ]
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): <|fim▁hole|> ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None)<|fim▁end|>
for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename:
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): <|fim_middle|> class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): <|fim_middle|> def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output))
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): <|fim_middle|> class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): <|fim_middle|> class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html'
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): <|fim_middle|> class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
template_name = 'admin/attachment/widgets/preview_image_input_vertical.html'
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): <|fim_middle|> <|fim▁end|>
def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None)
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): <|fim_middle|> <|fim▁end|>
for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None)
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: <|fim_middle|> return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: <|fim_middle|> filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
ext = u"." + filename.rpartition('.')[2]
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): <|fim_middle|> return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. <|fim_middle|> # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
return FILE_INPUT_CONTRADICTION
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: <|fim_middle|> filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
ext = u"." + filename.rpartition('.')[2]
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def <|fim_middle|>(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
render
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def <|fim_middle|>(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
value_from_datadict
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def <|fim_middle|>(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) <|fim▁end|>
value_from_datadict
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" <|fim▁hole|> fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order)<|fim▁end|>
return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs,
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): <|fim_middle|> def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
""" Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): <|fim_middle|> def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
""" Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.')
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): <|fim_middle|> def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
""" Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): <|fim_middle|> def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
""" Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): <|fim_middle|> def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
""" Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label]))
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): <|fim_middle|> def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
""" Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n')
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): <|fim_middle|> <|fim▁end|>
""" Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order)
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): <|fim_middle|> qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.')
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: <|fim_middle|> # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
raise ValueError('Fasta label %s not found in quality score ' % label + 'file.')
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): <|fim_middle|> def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.')
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): <|fim_middle|> fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
output_dir += '/'
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def <|fim_middle|>(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
parse_fasta_file
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def <|fim_middle|>(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
verify_equivalency
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def <|fim_middle|>(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
truncate_seqs
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def <|fim_middle|>(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
get_output_filepaths
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def <|fim_middle|>(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
write_trunc_fasta
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def <|fim_middle|>(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def truncate_fasta_qual(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
write_trunc_qual
<|file_name|>truncate_fasta_qual_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # File created Sept 29, 2010 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Greg Caporaso"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "William Walters" __email__ = "[email protected]" from os.path import basename from skbio.parse.sequences import parse_fasta from qiime.parse import parse_qual_score def parse_fasta_file(fasta_lines): """ Parses fasta file, generates dict of label:seq, list of seqs order fasta_lines: list of lines from fasta file. """ fasta_seqs = {} seq_order = [] for label, seq in parse_fasta(fasta_lines): fasta_seqs[label.split()[0].strip()] = seq seq_order.append(label) return fasta_seqs, seq_order def verify_equivalency(fasta_seqs, qual_scores): """ Tests for equivalent labels, base positions between fasta and qual file fasta_seqs: dict of label:seq from fasta file qual_scores: dict of label: qual scores """ if len(fasta_seqs) != len(qual_scores): raise ValueError('Number of sequences not equal in input fasta ' + 'and qual file.') qual_scores_labels = set(qual_scores.keys()) for label in fasta_seqs.keys(): # Should have equivalent labels if label not in qual_scores_labels: raise ValueError('Fasta label %s not found in quality score ' % label + 'file.') # should have equivalent lengths if len(fasta_seqs[label]) != len(qual_scores[label]): raise ValueError('Sequence %s does not have equivalent ' % label + 'base positions between fasta and quality score file.') def truncate_seqs(fasta_seqs, qual_scores, base_pos): """ Truncates sequences to base position specified with base_pos fasta_seqs: dict of seq label: seq string qual_scores: dict of seq label: numpy array of int scores base_pos: index in sequence to truncate at """ trunc_fasta_seqs = {} trunc_qual_scores = {} for seq in fasta_seqs: trunc_fasta_seqs[seq] = fasta_seqs[seq][:base_pos] trunc_qual_scores[seq] = qual_scores[seq][:base_pos] return trunc_fasta_seqs, trunc_qual_scores def get_output_filepaths(output_dir, fasta_fp, qual_fp): """ Returns output filepaths for filtered fasta and quality files output_dir: output directory fasta_fp: input fasta filepath qual_fp: input quality scores filepath """ if not output_dir.endswith('/'): output_dir += '/' fasta_out_fp = output_dir + basename(fasta_fp).split('.')[0] +\ "_filtered.fasta" qual_out_fp = output_dir + basename(qual_fp).split('.')[0] +\ "_filtered.qual" return fasta_out_fp, qual_out_fp def write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order): """ Writes truncated fasta seqs in order specified with seq_order trunc_fasta_seqs: dict of fasta label: truncated sequence string fasta_out_fp: output filepath to write to seq_order: list of fasta labels in the order of the original input fasta """ fasta_out = open(fasta_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) def write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order): """ Writes truncated quality score files out in proper format trunc_qual_scores: dict of seq label: numpy array of scores as ints qual_out_fp: output filepath to write truncated quality scores to seq_order: List of full fasta labels to write to output filepath and maintain the same order as input quality file. """ qual_line_size = 60 qual_out = open(qual_out_fp, "w") for label in seq_order: trunc_label = label.split()[0].strip() current_trunc_qual_scores = trunc_qual_scores[trunc_label] qual_out.write(">%s\n" % label) current_qual_scores_lines = [] # Quality score format is a string of 60 base calls, followed by a # newline, until the last N bases are written for slice in range(0, len(trunc_qual_scores[trunc_label]), qual_line_size): # current_segment = map(str, # current_trunc_qual_scores[slice:slice + qual_line_size]) current_segment = current_trunc_qual_scores[ slice:slice + qual_line_size] current_qual_scores_lines.append(" ".join(current_segment)) qual_out.write('\n'.join(current_qual_scores_lines)) qual_out.write('\n') def <|fim_middle|>(fasta_fp, qual_fp, output_dir, base_pos): """ Main program function for generating quality score histogram fasta_fp: fasta filepath qual_fp: quality score filepath output_dir: output directory base_pos: Nucleotide position to truncate the fasta and quality score at. """ qual_lines = open(qual_fp, "U") fasta_lines = open(fasta_fp, "U") qual_scores = parse_qual_score(qual_lines, value_cast_f=str) # Get dict of fasta label:seq, and the sequence order (so output can # be in the same order as the input sequences. fasta_seqs, seq_order = parse_fasta_file(fasta_lines) # Make sure the quality scores and fasta sequences have corresponding # labels and base numbers verify_equivalency(fasta_seqs, qual_scores) # Truncate seqs to base_pos index trunc_fasta_seqs, trunc_qual_scores = truncate_seqs(fasta_seqs, qual_scores, base_pos) # Get output filepaths fasta_out_fp, qual_out_fp = get_output_filepaths(output_dir, fasta_fp, qual_fp) # Write truncated sequences out write_trunc_fasta(trunc_fasta_seqs, fasta_out_fp, seq_order) write_trunc_qual(trunc_qual_scores, qual_out_fp, seq_order) <|fim▁end|>
truncate_fasta_qual
<|file_name|>0013_show2.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('setlist', '0012_remove_show_leg'), ] operations = [ migrations.CreateModel( name='Show2', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('venue', models.ForeignKey(to='setlist.Venue', to_field='id')), ('tour', models.ForeignKey(to='setlist.Tour', to_field='id')), ('date', models.DateField(db_index=True)), ('setlist', models.TextField(default=b'', blank=True)), ('notes', models.TextField(default=b'', blank=True)), ('source', models.TextField(default=b'', blank=True)), ], options={<|fim▁hole|> bases=(models.Model,), ), ]<|fim▁end|>
},
<|file_name|>0013_show2.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('setlist', '0012_remove_show_leg'), ] operations = [ migrations.CreateModel( name='Show2', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('venue', models.ForeignKey(to='setlist.Venue', to_field='id')), ('tour', models.ForeignKey(to='setlist.Tour', to_field='id')), ('date', models.DateField(db_index=True)), ('setlist', models.TextField(default=b'', blank=True)), ('notes', models.TextField(default=b'', blank=True)), ('source', models.TextField(default=b'', blank=True)), ], options={ }, bases=(models.Model,), ), ]
<|file_name|>test_attachment.py<|end_file_name|><|fim▁begin|>from O365 import attachment import unittest import json import base64 from random import randint att_rep = open('attachment.json','r').read() att_j = json.loads(att_rep) class TestAttachment (unittest.TestCase): def setUp(self): self.att = attachment.Attachment(att_j['value'][0])<|fim▁hole|> self.assertTrue(self.att.isType('txt')) def test_getType(self): self.assertEqual(self.att.getType(),'.txt') def test_save(self): name = self.att.json['Name'] name1 = self.newFileName(name) self.att.json['Name'] = name1 self.assertTrue(self.att.save('/tmp')) with open('/tmp/'+name1,'r') as ins: f = ins.read() self.assertEqual('testing w00t!',f) name2 = self.newFileName(name) self.att.json['Name'] = name2 self.assertTrue(self.att.save('/tmp/')) with open('/tmp/'+name2,'r') as ins: f = ins.read() self.assertEqual('testing w00t!',f) def newFileName(self,val): for i in range(4): val = str(randint(0,9)) + val return val def test_getByteString(self): self.assertEqual(self.att.getByteString(),b'testing w00t!') def test_getBase64(self): self.assertEqual(self.att.getBase64(),'dGVzdGluZyB3MDB0IQ==\n') def test_setByteString(self): test_string = b'testing testie test' self.att.setByteString(test_string) enc = base64.encodebytes(test_string) self.assertEqual(self.att.json['ContentBytes'],enc) def setBase64(self): wrong_test_string = 'I am sooooo not base64 encoded.' right_test_string = 'Base64 <3 all around!' enc = base64.encodestring(right_test_string) self.assertRaises(self.att.setBase64(wrong_test_string)) self.assertEqual(self.att.json['ContentBytes'],'dGVzdGluZyB3MDB0IQ==\n') self.att.setBase64(enc) self.assertEqual(self.att.json['ContentBytes'],enc) if __name__ == '__main__': unittest.main()<|fim▁end|>
def test_isType(self):