prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .. import Provider as CompanyProvider
class Provider(CompanyProvider):
<|fim_middle|>
<|fim▁end|> | formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{large_company}}",
)
large_companies = (
"AZAL",
"Azergold",
"SOCAR",
"Socar Polymer",
"Global Export Fruits",
"Baku Steel Company",
"Azersun",
"Sun Food",
"Azərbaycan Şəkər İstehsalat Birliyi",
"Azərsu",
"Xəzər Dəniz Gəmiçiliyi",
"Azərenerji",
"Bakıelektrikşəbəkə",
"Azəralüminium",
"Bravo",
"Azərpambıq Aqrar Sənaye Kompleksi",
"CTS-Agro",
"Azərtütün Aqrar Sənaye Kompleksi",
"Azəripək",
"Azfruittrade",
"AF Holding",
"Azinko Holding",
"Gilan Holding",
"Azpetrol",
"Azərtexnolayn",
"Bakı Gəmiqayırma Zavodu",
"Gəncə Tekstil Fabriki",
"Mətanət A",
"İrşad Electronics",
)
company_suffixes = (
"ASC",
"QSC",
"MMC",
)
def large_company(self):
"""
:example: 'SOCAR'
"""
return self.random_element(self.large_companies)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .. import Provider as CompanyProvider
class Provider(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{large_company}}",
)
large_companies = (
"AZAL",
"Azergold",
"SOCAR",
"Socar Polymer",
"Global Export Fruits",
"Baku Steel Company",
"Azersun",
"Sun Food",
"Azərbaycan Şəkər İstehsalat Birliyi",
"Azərsu",
"Xəzər Dəniz Gəmiçiliyi",
"Azərenerji",
"Bakıelektrikşəbəkə",
"Azəralüminium",
"Bravo",
"Azərpambıq Aqrar Sənaye Kompleksi",
"CTS-Agro",
"Azərtütün Aqrar Sənaye Kompleksi",
"Azəripək",
"Azfruittrade",
"AF Holding",
"Azinko Holding",
"Gilan Holding",
"Azpetrol",
"Azərtexnolayn",
"Bakı Gəmiqayırma Zavodu",
"Gəncə Tekstil Fabriki",
"Mətanət A",
"İrşad Electronics",
)
company_suffixes = (
"ASC",
"QSC",
"MMC",
)
def large_company(self):
"""
:example: 'SOCAR'
<|fim_middle|>
<|fim▁end|> | """
return self.random_element(self.large_companies)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .. import Provider as CompanyProvider
class Provider(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{large_company}}",
)
large_companies = (
"AZAL",
"Azergold",
"SOCAR",
"Socar Polymer",
"Global Export Fruits",
"Baku Steel Company",
"Azersun",
"Sun Food",
"Azərbaycan Şəkər İstehsalat Birliyi",
"Azərsu",
"Xəzər Dəniz Gəmiçiliyi",
"Azərenerji",
"Bakıelektrikşəbəkə",
"Azəralüminium",
"Bravo",
"Azərpambıq Aqrar Sənaye Kompleksi",
"CTS-Agro",
"Azərtütün Aqrar Sənaye Kompleksi",
"Azəripək",
"Azfruittrade",
"AF Holding",
"Azinko Holding",
"Gilan Holding",
"Azpetrol",
"Azərtexnolayn",
"Bakı Gəmiqayırma Zavodu",
"Gəncə Tekstil Fabriki",
"Mətanət A",
"İrşad Electronics",
)
company_suffixes = (
"ASC",
"QSC",
"MMC",
)
def large_company(self):
"""
<|fim_middle|>'SOCAR'
"""
return self.random_element(self.large_companies)
<|fim▁end|> | :example: |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
<|fim▁hole|> admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header<|fim▁end|> | @pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self, |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
<|fim_middle|>
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False) |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
<|fim_middle|>
<|fim▁end|> | @pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
<|fim_middle|>
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
<|fim_middle|>
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
<|fim_middle|>
<|fim▁end|> | monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
<|fim_middle|>
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year) |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
<|fim_middle|>
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar() |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
<|fim_middle|>
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | response = response.decode('utf-8') |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
<|fim_middle|>
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | response = response.decode('utf-8') |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
<|fim_middle|>
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | response = response.decode('utf-8') |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def <|fim_middle|>():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | birthdays |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def <|fim_middle|>(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | test_attendee_birthday_calendar |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def <|fim_middle|>(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | test_event_birthday_calendar |
<|file_name|>test_summary.py<|end_file_name|><|fim▁begin|>from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def <|fim_middle|>(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
<|fim▁end|> | test_event_birthday_calendar_correct_birthday_years |
<|file_name|>0527.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*-
import logging
unicode_string = u"Татьяна"
utf8_string = "'Татьяна' is an invalid string value"
logging.warning(unicode_string)
logging.warning(utf8_string)
try:
raise Exception(utf8_string)
except Exception,e:
print "--- (Log a traceback of the exception):"
logging.exception(e)
print "--- Everything okay until here, but now we run into trouble:"<|fim▁hole|> logging.warning(u"1 Deferred %s : %s",unicode_string,e)
logging.warning(u"2 Deferred %s : %s",unicode_string,utf8_string)
print "--- some workarounds:"
logging.warning(u"3 Deferred %s : %s",unicode_string,utf8_string.decode('UTF-8'))
from django.utils.encoding import force_unicode
logging.warning(u"4 Deferred %s : %s",unicode_string,force_unicode(utf8_string))<|fim▁end|> | |
<|file_name|>send-message-suggested-action-dial.py<|end_file_name|><|fim▁begin|>## Copyright 2022 Google LLC
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## https://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
"""Sends a text mesage to the user with a suggestion action to dial a phone number.
Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action<|fim▁hole|>"""
import uuid
from businessmessages import businessmessages_v1_client as bm_client
from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest
from businessmessages.businessmessages_v1_messages import BusinessMessagesDialAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage
from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion
from oauth2client.service_account import ServiceAccountCredentials
# Edit the values below:
path_to_service_account_key = './service_account_key.json'
conversation_id = 'EDIT_HERE'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
path_to_service_account_key,
scopes=['https://www.googleapis.com/auth/businessmessages'])
client = bm_client.BusinessmessagesV1(credentials=credentials)
representative_type_as_string = 'BOT'
if representative_type_as_string == 'BOT':
representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT
else:
representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN
# Create a text message with a dial action and fallback text
message = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BusinessMessagesRepresentative(
representativeType=representative_type
),
text='Contact support for help with this issue.',
fallback='Give us a call at +12223334444.',
suggestions=[
BusinessMessagesSuggestion(
action=BusinessMessagesSuggestedAction(
text='Call support',
postbackData='call-support',
dialAction=BusinessMessagesDialAction(
phoneNumber='+12223334444'))
),
])
# Create the message request
create_request = BusinessmessagesConversationsMessagesCreateRequest(
businessMessagesMessage=message,
parent='conversations/' + conversation_id)
# Send the message
bm_client.BusinessmessagesV1.ConversationsMessagesService(
client=client).Create(request=create_request)<|fim▁end|> |
This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library. |
<|file_name|>send-message-suggested-action-dial.py<|end_file_name|><|fim▁begin|>## Copyright 2022 Google LLC
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## https://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
"""Sends a text mesage to the user with a suggestion action to dial a phone number.
Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action
This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""
import uuid
from businessmessages import businessmessages_v1_client as bm_client
from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest
from businessmessages.businessmessages_v1_messages import BusinessMessagesDialAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage
from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion
from oauth2client.service_account import ServiceAccountCredentials
# Edit the values below:
path_to_service_account_key = './service_account_key.json'
conversation_id = 'EDIT_HERE'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
path_to_service_account_key,
scopes=['https://www.googleapis.com/auth/businessmessages'])
client = bm_client.BusinessmessagesV1(credentials=credentials)
representative_type_as_string = 'BOT'
if representative_type_as_string == 'BOT':
<|fim_middle|>
else:
representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN
# Create a text message with a dial action and fallback text
message = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BusinessMessagesRepresentative(
representativeType=representative_type
),
text='Contact support for help with this issue.',
fallback='Give us a call at +12223334444.',
suggestions=[
BusinessMessagesSuggestion(
action=BusinessMessagesSuggestedAction(
text='Call support',
postbackData='call-support',
dialAction=BusinessMessagesDialAction(
phoneNumber='+12223334444'))
),
])
# Create the message request
create_request = BusinessmessagesConversationsMessagesCreateRequest(
businessMessagesMessage=message,
parent='conversations/' + conversation_id)
# Send the message
bm_client.BusinessmessagesV1.ConversationsMessagesService(
client=client).Create(request=create_request)
<|fim▁end|> | representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT |
<|file_name|>send-message-suggested-action-dial.py<|end_file_name|><|fim▁begin|>## Copyright 2022 Google LLC
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## https://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
"""Sends a text mesage to the user with a suggestion action to dial a phone number.
Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action
This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""
import uuid
from businessmessages import businessmessages_v1_client as bm_client
from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest
from businessmessages.businessmessages_v1_messages import BusinessMessagesDialAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage
from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion
from oauth2client.service_account import ServiceAccountCredentials
# Edit the values below:
path_to_service_account_key = './service_account_key.json'
conversation_id = 'EDIT_HERE'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
path_to_service_account_key,
scopes=['https://www.googleapis.com/auth/businessmessages'])
client = bm_client.BusinessmessagesV1(credentials=credentials)
representative_type_as_string = 'BOT'
if representative_type_as_string == 'BOT':
representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT
else:
<|fim_middle|>
# Create a text message with a dial action and fallback text
message = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BusinessMessagesRepresentative(
representativeType=representative_type
),
text='Contact support for help with this issue.',
fallback='Give us a call at +12223334444.',
suggestions=[
BusinessMessagesSuggestion(
action=BusinessMessagesSuggestedAction(
text='Call support',
postbackData='call-support',
dialAction=BusinessMessagesDialAction(
phoneNumber='+12223334444'))
),
])
# Create the message request
create_request = BusinessmessagesConversationsMessagesCreateRequest(
businessMessagesMessage=message,
parent='conversations/' + conversation_id)
# Send the message
bm_client.BusinessmessagesV1.ConversationsMessagesService(
client=client).Create(request=create_request)
<|fim▁end|> | representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
<|fim▁hole|> def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()<|fim▁end|> | |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
<|fim_middle|>
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql') |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
<|fim_middle|>
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version) |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
<|fim_middle|>
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql") |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
<|fim_middle|>
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | sudo('svcadm restart postgresql') |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
<|fim_middle|>
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | sudo('svcadm disable postgresql') |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
<|fim_middle|>
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | sudo('svcadm enable postgresql') |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
<|fim_middle|>
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | """
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1' |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
<|fim_middle|>
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | """
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup' |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
<|fim_middle|>
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | """
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer') |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
<|fim_middle|>
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name) |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
<|fim_middle|>
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name)) |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
<|fim_middle|>
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name) |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
<|fim_middle|>
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
<|fim_middle|>
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | """
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer') |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
<|fim_middle|>
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | return output.stdout |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
<|fim_middle|>
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | section = 'db-server' |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def <|fim_middle|>(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | _get_data_dir |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def <|fim_middle|>(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | _install_package |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def <|fim_middle|>(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | _restart_db_server |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def <|fim_middle|>(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | _stop_db_server |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def <|fim_middle|>(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | _start_db_server |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def <|fim_middle|>(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | install_package |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def <|fim_middle|>(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | _setup_parameter |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def <|fim_middle|>(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | _get_passwd |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def <|fim_middle|>(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def run(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | _get_username |
<|file_name|>postgres.py<|end_file_name|><|fim▁begin|>import os
import sys
import tempfile
from fabric.api import run, sudo, env, local, hide, settings
from fabric.contrib.files import append, sed, exists, contains
from fabric.context_managers import prefix
from fabric.operations import get, put
from fabric.context_managers import cd
from fabric.tasks import Task
from fab_deploy.functions import random_password
from fab_deploy.base import postgres as base_postgres
class JoyentMixin(object):
version_directory_join = ''
def _get_data_dir(self, db_version):
# Try to get from svc first
output = run('svcprop -p config/data postgresql')
if output.stdout and exists(output.stdout, use_sudo=True):
return output.stdout
return base_postgres.PostgresInstall._get_data_dir(self, db_version)
def _install_package(self, db_version):
sudo("pkg_add postgresql%s-server" %db_version)
sudo("pkg_add postgresql%s-replicationtools" %db_version)
sudo("svcadm enable postgresql")
def _restart_db_server(self, db_version):
sudo('svcadm restart postgresql')
def _stop_db_server(self, db_version):
sudo('svcadm disable postgresql')
def _start_db_server(self, db_version):
sudo('svcadm enable postgresql')
class PostgresInstall(JoyentMixin, base_postgres.PostgresInstall):
"""
Install postgresql on server
install postgresql package;
enable postgres access from localhost without password;
enable all other user access from other machines with password;
setup a few parameters related with streaming replication;
database server listen to all machines '*';
create a user for database with password.
"""
name = 'master_setup'
db_version = '9.1'
class SlaveSetup(JoyentMixin, base_postgres.SlaveSetup):
"""
Set up master-slave streaming replication: slave node
"""
name = 'slave_setup'
class PGBouncerInstall(Task):
"""
Set up PGBouncer on a database server
"""
name = 'setup_pgbouncer'
pgbouncer_src = 'http://pkgsrc.smartos.org/packages/SmartOS/2012Q2/databases/pgbouncer-1.4.2.tgz'
pkg_name = 'pgbouncer-1.4.2.tgz'
config_dir = '/etc/opt/pkg'
config = {
'*': 'host=127.0.0.1',
'logfile': '/var/log/pgbouncer/pgbouncer.log',
'listen_addr': '*',
'listen_port': '6432',
'unix_socket_dir': '/tmp',
'auth_type': 'md5',
'auth_file': '%s/pgbouncer.userlist' %config_dir,
'pool_mode': 'session',
'admin_users': 'postgres',
'stats_users': 'postgres',
}
def install_package(self):
sudo('pkg_add libevent')
with cd('/tmp'):
run('wget %s' %self.pgbouncer_src)
sudo('pkg_add %s' %self.pkg_name)
def _setup_parameter(self, file_name, **kwargs):
for key, value in kwargs.items():
origin = "%s =" %key
new = "%s = %s" %(key, value)
sudo('sed -i "/%s/ c\%s" %s' %(origin, new, file_name))
def _get_passwd(self, username):
with hide('output'):
string = run('echo "select usename, passwd from pg_shadow where '
'usename=\'%s\' order by 1" | sudo su postgres -c '
'"psql"' %username)
user, passwd = string.split('\n')[2].split('|')
user = user.strip()
passwd = passwd.strip()
__, tmp_name = tempfile.mkstemp()
fn = open(tmp_name, 'w')
fn.write('"%s" "%s" ""\n' %(user, passwd))
fn.close()
put(tmp_name, '%s/pgbouncer.userlist'%self.config_dir, use_sudo=True)
local('rm %s' %tmp_name)
def _get_username(self, section=None):
try:
names = env.config_object.get_list(section, env.config_object.USERNAME)
username = names[0]
except:
print ('You must first set up a database server on this machine, '
'and create a database user')
raise
return username
def <|fim_middle|>(self, section=None):
"""
"""
sudo('mkdir -p /opt/pkg/bin')
sudo("ln -sf /opt/local/bin/awk /opt/pkg/bin/nawk")
sudo("ln -sf /opt/local/bin/sed /opt/pkg/bin/nbsed")
self.install_package()
svc_method = os.path.join(env.configs_dir, 'pgbouncer.xml')
put(svc_method, self.config_dir, use_sudo=True)
home = run('bash -c "echo ~postgres"')
bounce_home = os.path.join(home, 'pgbouncer')
pidfile = os.path.join(bounce_home, 'pgbouncer.pid')
self._setup_parameter('%s/pgbouncer.ini' %self.config_dir,
pidfile=pidfile, **self.config)
if not section:
section = 'db-server'
username = self._get_username(section)
self._get_passwd(username)
# postgres should be the owner of these config files
sudo('chown -R postgres:postgres %s' %self.config_dir)
sudo('mkdir -p %s' % bounce_home)
sudo('chown postgres:postgres %s' % bounce_home)
sudo('mkdir -p /var/log/pgbouncer')
sudo('chown postgres:postgres /var/log/pgbouncer')
# set up log
sudo('logadm -C 3 -p1d -c -w /var/log/pgbouncer/pgbouncer.log -z 1')
run('svccfg import %s/pgbouncer.xml' %self.config_dir)
# start pgbouncer
sudo('svcadm enable pgbouncer')
setup = PostgresInstall()
slave_setup = SlaveSetup()
setup_pgbouncer = PGBouncerInstall()
<|fim▁end|> | run |
<|file_name|>DP20150713A.py<|end_file_name|><|fim▁begin|>"""
[2015-07-13] Challenge #223 [Easy] Garland words
https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/
# Description
A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the
same N letters in the same order, for some N greater than 0, but less than the length of the word. I'll call the
maximum N for which this works the garland word's _degree_. For instance, "onion" is a garland word of degree 2,
because its first 2 letters "on" are the same as its last 2 letters. The name "garland word" comes from the fact that
you can make chains of the word in this manner:
onionionionionionionionionionion...
Today's challenge is to write a function `garland` that, given a lowercase word, returns the degree of the word if it's
a garland word, and 0 otherwise.
# Examples
garland("programmer") -> 0
garland("ceramic") -> 1
garland("onion") -> 2
garland("alfalfa") -> 4
# Optional challenges
1. Given a garland word, print out the chain using that word, as with "onion" above. You can make it as long or short
as you like, even infinite.
1. Find the largest degree of any garland word in the [enable1 English word
list](https://code.google.com/p/dotnetperls-controls/downloads/detail?name=enable1.txt).
1. Find a word list for some other language, and see if you can find a language with a garland word with a higher
degree.
*Thanks to /u/skeeto for submitting this challenge on /r/dailyprogrammer_ideas!*
"""
<|fim▁hole|>
if __name__ == "__main__":
main()<|fim▁end|> |
def main():
pass |
<|file_name|>DP20150713A.py<|end_file_name|><|fim▁begin|>"""
[2015-07-13] Challenge #223 [Easy] Garland words
https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/
# Description
A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the
same N letters in the same order, for some N greater than 0, but less than the length of the word. I'll call the
maximum N for which this works the garland word's _degree_. For instance, "onion" is a garland word of degree 2,
because its first 2 letters "on" are the same as its last 2 letters. The name "garland word" comes from the fact that
you can make chains of the word in this manner:
onionionionionionionionionionion...
Today's challenge is to write a function `garland` that, given a lowercase word, returns the degree of the word if it's
a garland word, and 0 otherwise.
# Examples
garland("programmer") -> 0
garland("ceramic") -> 1
garland("onion") -> 2
garland("alfalfa") -> 4
# Optional challenges
1. Given a garland word, print out the chain using that word, as with "onion" above. You can make it as long or short
as you like, even infinite.
1. Find the largest degree of any garland word in the [enable1 English word
list](https://code.google.com/p/dotnetperls-controls/downloads/detail?name=enable1.txt).
1. Find a word list for some other language, and see if you can find a language with a garland word with a higher
degree.
*Thanks to /u/skeeto for submitting this challenge on /r/dailyprogrammer_ideas!*
"""
def main():
<|fim_middle|>
if __name__ == "__main__":
main()
<|fim▁end|> | pass |
<|file_name|>DP20150713A.py<|end_file_name|><|fim▁begin|>"""
[2015-07-13] Challenge #223 [Easy] Garland words
https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/
# Description
A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the
same N letters in the same order, for some N greater than 0, but less than the length of the word. I'll call the
maximum N for which this works the garland word's _degree_. For instance, "onion" is a garland word of degree 2,
because its first 2 letters "on" are the same as its last 2 letters. The name "garland word" comes from the fact that
you can make chains of the word in this manner:
onionionionionionionionionionion...
Today's challenge is to write a function `garland` that, given a lowercase word, returns the degree of the word if it's
a garland word, and 0 otherwise.
# Examples
garland("programmer") -> 0
garland("ceramic") -> 1
garland("onion") -> 2
garland("alfalfa") -> 4
# Optional challenges
1. Given a garland word, print out the chain using that word, as with "onion" above. You can make it as long or short
as you like, even infinite.
1. Find the largest degree of any garland word in the [enable1 English word
list](https://code.google.com/p/dotnetperls-controls/downloads/detail?name=enable1.txt).
1. Find a word list for some other language, and see if you can find a language with a garland word with a higher
degree.
*Thanks to /u/skeeto for submitting this challenge on /r/dailyprogrammer_ideas!*
"""
def main():
pass
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | main() |
<|file_name|>DP20150713A.py<|end_file_name|><|fim▁begin|>"""
[2015-07-13] Challenge #223 [Easy] Garland words
https://www.reddit.com/r/dailyprogrammer/comments/3d4fwj/20150713_challenge_223_easy_garland_words/
# Description
A [_garland word_](http://blog.vivekhaldar.com/post/89763722591/garland-words) is one that starts and ends with the
same N letters in the same order, for some N greater than 0, but less than the length of the word. I'll call the
maximum N for which this works the garland word's _degree_. For instance, "onion" is a garland word of degree 2,
because its first 2 letters "on" are the same as its last 2 letters. The name "garland word" comes from the fact that
you can make chains of the word in this manner:
onionionionionionionionionionion...
Today's challenge is to write a function `garland` that, given a lowercase word, returns the degree of the word if it's
a garland word, and 0 otherwise.
# Examples
garland("programmer") -> 0
garland("ceramic") -> 1
garland("onion") -> 2
garland("alfalfa") -> 4
# Optional challenges
1. Given a garland word, print out the chain using that word, as with "onion" above. You can make it as long or short
as you like, even infinite.
1. Find the largest degree of any garland word in the [enable1 English word
list](https://code.google.com/p/dotnetperls-controls/downloads/detail?name=enable1.txt).
1. Find a word list for some other language, and see if you can find a language with a garland word with a higher
degree.
*Thanks to /u/skeeto for submitting this challenge on /r/dailyprogrammer_ideas!*
"""
def <|fim_middle|>():
pass
if __name__ == "__main__":
main()
<|fim▁end|> | main |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def is_prime(x):<|fim▁hole|> return False
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
ans += 1
print ans<|fim▁end|> | for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0: |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def is_prime(x):
<|fim_middle|>
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
ans += 1
print ans
<|fim▁end|> | for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def is_prime(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
<|fim_middle|>
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
ans += 1
print ans
<|fim▁end|> | res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def is_prime(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
<|fim_middle|>
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
ans += 1
print ans
<|fim▁end|> | return False |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def is_prime(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
<|fim_middle|>
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
ans += 1
print ans
<|fim▁end|> | break |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def is_prime(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
<|fim_middle|>
if flag:
ans += 1
print ans
<|fim▁end|> | flag = False |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def is_prime(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
<|fim_middle|>
print ans
<|fim▁end|> | ans += 1 |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def <|fim_middle|>(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True
def rotate(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
ans += 1
print ans
<|fim▁end|> | is_prime |
<|file_name|>35.py<|end_file_name|><|fim▁begin|>from math import sqrt
def is_prime(x):
for i in xrange(2, int(sqrt(x) + 1)):
if x % i == 0:
return False
return True
def <|fim_middle|>(v):
res = []
u = str(v)
while True:
u = u[1:] + u[0]
w = int(u)
if w == v:
break
res.append(w)
return res
MILLION = 1000000
primes = filter(is_prime, range(2, MILLION))
s = set(primes)
ans = 0
for item in primes:
flag = True
print item
for y in rotate(item):
if y not in s:
flag = False
if flag:
ans += 1
print ans
<|fim▁end|> | rotate |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | from .gaussian_process import RandomFeatureGaussianProcess, mean_field_logits
from .spectral_normalization import SpectralNormalization |
<|file_name|>O2.4 SS, Single agent model.py<|end_file_name|><|fim▁begin|>import complexism as cx
import complexism.agentbased.statespace as ss
import epidag as dag
dbp = cx.read_dbp_script(cx.load_txt('../scripts/SIR_BN.txt'))
pc = dag.quick_build_parameter_core(cx.load_txt('../scripts/pSIR.txt'))
dc = dbp.generate_model('M1', **pc.get_samplers())<|fim▁hole|>model = cx.SingleIndividualABM('M1', ag)
model.add_observing_attribute('State')
print(cx.simulate(model, None, 0, 10, 1))<|fim▁end|> |
ag = ss.StSpAgent('Helen', dc['Sus'], pc)
|
<|file_name|>dist_async_kvstore.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information<|fim▁hole|># to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
kv = mx.kv.create('dist_async')
my_rank = kv.rank
nworker = kv.num_workers
def test_gluon_trainer_type():
def check_trainer_kv_update(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
kvstore=kv, update_on_kvstore=update_on_kv)
trainer._init_kvstore()
assert trainer._kv_initialized
assert trainer._update_on_kvstore is True
except ValueError:
assert update_on_kv is False
check_trainer_kv_update('default', False)
check_trainer_kv_update('default', True)
check_trainer_kv_update('default', None)
check_trainer_kv_update('row_sparse', False)
check_trainer_kv_update('row_sparse', True)
check_trainer_kv_update('row_sparse', None)
print('worker ' + str(my_rank) + ' passed test_gluon_trainer_type')
if __name__ == "__main__":
test_gluon_trainer_type()<|fim▁end|> | # regarding copyright ownership. The ASF licenses this file |
<|file_name|>dist_async_kvstore.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
kv = mx.kv.create('dist_async')
my_rank = kv.rank
nworker = kv.num_workers
def test_gluon_trainer_type():
<|fim_middle|>
if __name__ == "__main__":
test_gluon_trainer_type()
<|fim▁end|> | def check_trainer_kv_update(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
kvstore=kv, update_on_kvstore=update_on_kv)
trainer._init_kvstore()
assert trainer._kv_initialized
assert trainer._update_on_kvstore is True
except ValueError:
assert update_on_kv is False
check_trainer_kv_update('default', False)
check_trainer_kv_update('default', True)
check_trainer_kv_update('default', None)
check_trainer_kv_update('row_sparse', False)
check_trainer_kv_update('row_sparse', True)
check_trainer_kv_update('row_sparse', None)
print('worker ' + str(my_rank) + ' passed test_gluon_trainer_type') |
<|file_name|>dist_async_kvstore.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
kv = mx.kv.create('dist_async')
my_rank = kv.rank
nworker = kv.num_workers
def test_gluon_trainer_type():
def check_trainer_kv_update(weight_stype, update_on_kv):
<|fim_middle|>
check_trainer_kv_update('default', False)
check_trainer_kv_update('default', True)
check_trainer_kv_update('default', None)
check_trainer_kv_update('row_sparse', False)
check_trainer_kv_update('row_sparse', True)
check_trainer_kv_update('row_sparse', None)
print('worker ' + str(my_rank) + ' passed test_gluon_trainer_type')
if __name__ == "__main__":
test_gluon_trainer_type()
<|fim▁end|> | x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
kvstore=kv, update_on_kvstore=update_on_kv)
trainer._init_kvstore()
assert trainer._kv_initialized
assert trainer._update_on_kvstore is True
except ValueError:
assert update_on_kv is False |
<|file_name|>dist_async_kvstore.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
kv = mx.kv.create('dist_async')
my_rank = kv.rank
nworker = kv.num_workers
def test_gluon_trainer_type():
def check_trainer_kv_update(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
kvstore=kv, update_on_kvstore=update_on_kv)
trainer._init_kvstore()
assert trainer._kv_initialized
assert trainer._update_on_kvstore is True
except ValueError:
assert update_on_kv is False
check_trainer_kv_update('default', False)
check_trainer_kv_update('default', True)
check_trainer_kv_update('default', None)
check_trainer_kv_update('row_sparse', False)
check_trainer_kv_update('row_sparse', True)
check_trainer_kv_update('row_sparse', None)
print('worker ' + str(my_rank) + ' passed test_gluon_trainer_type')
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | test_gluon_trainer_type() |
<|file_name|>dist_async_kvstore.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
kv = mx.kv.create('dist_async')
my_rank = kv.rank
nworker = kv.num_workers
def <|fim_middle|>():
def check_trainer_kv_update(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
kvstore=kv, update_on_kvstore=update_on_kv)
trainer._init_kvstore()
assert trainer._kv_initialized
assert trainer._update_on_kvstore is True
except ValueError:
assert update_on_kv is False
check_trainer_kv_update('default', False)
check_trainer_kv_update('default', True)
check_trainer_kv_update('default', None)
check_trainer_kv_update('row_sparse', False)
check_trainer_kv_update('row_sparse', True)
check_trainer_kv_update('row_sparse', None)
print('worker ' + str(my_rank) + ' passed test_gluon_trainer_type')
if __name__ == "__main__":
test_gluon_trainer_type()
<|fim▁end|> | test_gluon_trainer_type |
<|file_name|>dist_async_kvstore.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: skip-file
import sys
sys.path.insert(0, "../../python/")
import mxnet as mx
kv = mx.kv.create('dist_async')
my_rank = kv.rank
nworker = kv.num_workers
def test_gluon_trainer_type():
def <|fim_middle|>(weight_stype, update_on_kv):
x = mx.gluon.Parameter('x', shape=(10,1), lr_mult=1.0, stype=weight_stype)
x.initialize(ctx=[mx.cpu(0), mx.cpu(1)], init='zeros')
try:
trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 0.1},
kvstore=kv, update_on_kvstore=update_on_kv)
trainer._init_kvstore()
assert trainer._kv_initialized
assert trainer._update_on_kvstore is True
except ValueError:
assert update_on_kv is False
check_trainer_kv_update('default', False)
check_trainer_kv_update('default', True)
check_trainer_kv_update('default', None)
check_trainer_kv_update('row_sparse', False)
check_trainer_kv_update('row_sparse', True)
check_trainer_kv_update('row_sparse', None)
print('worker ' + str(my_rank) + ' passed test_gluon_trainer_type')
if __name__ == "__main__":
test_gluon_trainer_type()
<|fim▁end|> | check_trainer_kv_update |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test<|fim▁hole|> return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)<|fim▁end|> | :return: True if the title should be recycled; otherwise, False.
:rtype: bool
""" |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
<|fim_middle|>
<|fim▁end|> | """
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20) |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
<|fim_middle|>
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter() |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
<|fim_middle|>
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | """
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name)) |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
<|fim_middle|>
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | """
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
<|fim_middle|>
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | """
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
<|fim_middle|>
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | """
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0 |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
<|fim_middle|>
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | """
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
<|fim_middle|>
<|fim▁end|> | """
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20) |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
<|fim_middle|>
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name)) |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
<|fim_middle|>
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name)) |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
<|fim_middle|>
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | return True |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
<|fim_middle|>
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
<|fim_middle|>
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
<|fim_middle|>
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | worker_result = WorkerResult.ERROR |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
<|fim_middle|>
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | return item_filter_config.get('keep', 20) |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
<|fim_middle|>
<|fim▁end|> | item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20) |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
<|fim_middle|>
<|fim▁end|> | return item_filter_config.get('keep', 20) |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def <|fim_middle|>(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | initialize |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def <|fim_middle|>(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | _validate_item_filter |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def <|fim_middle|>(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | should_run |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def <|fim_middle|>(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | work |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def <|fim_middle|>(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | item_should_be_recycled |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def <|fim_middle|>(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def get_amount_to_keep(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | get_amount_to_recycle |
<|file_name|>recycle_items.py<|end_file_name|><|fim▁begin|>import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import ConfigException
from pokemongo_bot.worker_result import WorkerResult
DEFAULT_MIN_EMPTY_SPACE = 6
class RecycleItems(BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be able to loot.
Example config :
{
"type": "RecycleItems",
"config": {
"min_empty_space": 6, # 6 by default
"item_filter": {
"Pokeball": {"keep": 20},
"Greatball": {"keep": 50},
"Ultraball": {"keep": 100},
"Potion": {"keep": 0},
"Super Potion": {"keep": 0},
"Hyper Potion": {"keep": 20},
"Max Potion": {"keep": 50},
"Revive": {"keep": 0},
"Max Revive": {"keep": 20},
"Razz Berry": {"keep": 20}
}
}
}
"""
SUPPORTED_TASK_API_VERSION = 1
def initialize(self):
self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter()
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
for config_item_name, bag_count in self.items_filter.iteritems():
if config_item_name not in item_list.viewvalues():
if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns a value indicating whether the recycling process should be run.
:return: True if the recycling process should be run; otherwise, False.
:rtype: bool
"""
if inventory.Items.get_space_left() < (DEFAULT_MIN_EMPTY_SPACE if self.min_empty_space is None else self.min_empty_space):
return True
return False
def work(self):
"""
Start the process of recycling items if necessary.
:return: Returns whether or not the task went well
:rtype: WorkerResult
"""
# TODO: Use new inventory everywhere and then remove this inventory update
inventory.refresh_inventory()
worker_result = WorkerResult.SUCCESS
if self.should_run():
for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory):
# Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self.bot, item_in_inventory, self.get_amount_to_recycle(item_in_inventory)).work() == WorkerResult.ERROR:
worker_result = WorkerResult.ERROR
return worker_result
def item_should_be_recycled(self, item):
"""
Returns a value indicating whether the item should be recycled.
:param item: The Item to test
:return: True if the title should be recycled; otherwise, False.
:rtype: bool
"""
return (item.name in self.items_filter or str(item.id) in self.items_filter) and self.get_amount_to_recycle(item) > 0
def get_amount_to_recycle(self, item):
"""
Determine the amount to recycle accordingly to user config
:param item: Item to determine the amount to recycle.
:return: The amount to recycle
:rtype: int
"""
amount_to_keep = self.get_amount_to_keep(item)
return 0 if amount_to_keep is None else item.count - amount_to_keep
def <|fim_middle|>(self, item):
"""
Determine item's amount to keep in inventory.
:param item:
:return: Item's amount to keep in inventory.
:rtype: int
"""
item_filter_config = self.items_filter.get(item.name, 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
else:
item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20)
<|fim▁end|> | get_amount_to_keep |
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest
import pysal
from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO
import tempfile
import os
class test_ArcGISSwmIO(unittest.TestCase):
def setUp(self):
self.test_file = test_file = pysal.examples.get_path('ohio.swm')
self.obj = ArcGISSwmIO(test_file, 'r')
def test_close(self):
f = self.obj
f.close()
self.failUnlessRaises(ValueError, f.read)
def test_read(self):
w = self.obj.read()
self.assertEqual(88, w.n)
self.assertEqual(5.25, w.mean_neighbors)
self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values())
def test_seek(self):
self.test_read()<|fim▁hole|> def test_write(self):
w = self.obj.read()
f = tempfile.NamedTemporaryFile(
suffix='.swm', dir=pysal.examples.get_path(''))
fname = f.name
f.close()
o = pysal.open(fname, 'w')
o.write(w)
o.close()
wnew = pysal.open(fname, 'r').read()
self.assertEqual(wnew.pct_nonzero, w.pct_nonzero)
os.remove(fname)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | self.failUnlessRaises(StopIteration, self.obj.read)
self.obj.seek(0)
self.test_read()
|
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest
import pysal
from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO
import tempfile
import os
class test_ArcGISSwmIO(unittest.TestCase):
<|fim_middle|>
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | def setUp(self):
self.test_file = test_file = pysal.examples.get_path('ohio.swm')
self.obj = ArcGISSwmIO(test_file, 'r')
def test_close(self):
f = self.obj
f.close()
self.failUnlessRaises(ValueError, f.read)
def test_read(self):
w = self.obj.read()
self.assertEqual(88, w.n)
self.assertEqual(5.25, w.mean_neighbors)
self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values())
def test_seek(self):
self.test_read()
self.failUnlessRaises(StopIteration, self.obj.read)
self.obj.seek(0)
self.test_read()
def test_write(self):
w = self.obj.read()
f = tempfile.NamedTemporaryFile(
suffix='.swm', dir=pysal.examples.get_path(''))
fname = f.name
f.close()
o = pysal.open(fname, 'w')
o.write(w)
o.close()
wnew = pysal.open(fname, 'r').read()
self.assertEqual(wnew.pct_nonzero, w.pct_nonzero)
os.remove(fname) |
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest
import pysal
from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO
import tempfile
import os
class test_ArcGISSwmIO(unittest.TestCase):
def setUp(self):
<|fim_middle|>
def test_close(self):
f = self.obj
f.close()
self.failUnlessRaises(ValueError, f.read)
def test_read(self):
w = self.obj.read()
self.assertEqual(88, w.n)
self.assertEqual(5.25, w.mean_neighbors)
self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values())
def test_seek(self):
self.test_read()
self.failUnlessRaises(StopIteration, self.obj.read)
self.obj.seek(0)
self.test_read()
def test_write(self):
w = self.obj.read()
f = tempfile.NamedTemporaryFile(
suffix='.swm', dir=pysal.examples.get_path(''))
fname = f.name
f.close()
o = pysal.open(fname, 'w')
o.write(w)
o.close()
wnew = pysal.open(fname, 'r').read()
self.assertEqual(wnew.pct_nonzero, w.pct_nonzero)
os.remove(fname)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | self.test_file = test_file = pysal.examples.get_path('ohio.swm')
self.obj = ArcGISSwmIO(test_file, 'r') |
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest
import pysal
from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO
import tempfile
import os
class test_ArcGISSwmIO(unittest.TestCase):
def setUp(self):
self.test_file = test_file = pysal.examples.get_path('ohio.swm')
self.obj = ArcGISSwmIO(test_file, 'r')
def test_close(self):
<|fim_middle|>
def test_read(self):
w = self.obj.read()
self.assertEqual(88, w.n)
self.assertEqual(5.25, w.mean_neighbors)
self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values())
def test_seek(self):
self.test_read()
self.failUnlessRaises(StopIteration, self.obj.read)
self.obj.seek(0)
self.test_read()
def test_write(self):
w = self.obj.read()
f = tempfile.NamedTemporaryFile(
suffix='.swm', dir=pysal.examples.get_path(''))
fname = f.name
f.close()
o = pysal.open(fname, 'w')
o.write(w)
o.close()
wnew = pysal.open(fname, 'r').read()
self.assertEqual(wnew.pct_nonzero, w.pct_nonzero)
os.remove(fname)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | f = self.obj
f.close()
self.failUnlessRaises(ValueError, f.read) |
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest
import pysal
from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO
import tempfile
import os
class test_ArcGISSwmIO(unittest.TestCase):
def setUp(self):
self.test_file = test_file = pysal.examples.get_path('ohio.swm')
self.obj = ArcGISSwmIO(test_file, 'r')
def test_close(self):
f = self.obj
f.close()
self.failUnlessRaises(ValueError, f.read)
def test_read(self):
<|fim_middle|>
def test_seek(self):
self.test_read()
self.failUnlessRaises(StopIteration, self.obj.read)
self.obj.seek(0)
self.test_read()
def test_write(self):
w = self.obj.read()
f = tempfile.NamedTemporaryFile(
suffix='.swm', dir=pysal.examples.get_path(''))
fname = f.name
f.close()
o = pysal.open(fname, 'w')
o.write(w)
o.close()
wnew = pysal.open(fname, 'r').read()
self.assertEqual(wnew.pct_nonzero, w.pct_nonzero)
os.remove(fname)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | w = self.obj.read()
self.assertEqual(88, w.n)
self.assertEqual(5.25, w.mean_neighbors)
self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.