prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
<|fim_middle|>
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | code_form = code_str[17 - code_len:21] |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
<|fim_middle|>
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | code_form = code_str[16 - code_len:21] |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
<|fim_middle|>
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | code_form = code_str[15 - code_len:21] |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
<|fim_middle|>
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | code_form = code_str[14 - code_len:21] |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
<|fim_middle|>
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq) |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
<|fim_middle|>
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq) |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def <|fim_middle|>(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | format_code |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def <|fim_middle|>(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | create |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def <|fim_middle|>(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def copy(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | write |
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
def format_code(code_seq):
code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + str(code[3]) + str(code[4]),
str(code[5]) + str(code[6]) + str(code[7]),
str(code[8]) + str(code[9]) + str(code[10]),
str(code[11]) + str(code[12]) + str(code[13]),
str(code[14]) + str(code[15]))
if code_len <= 3:
code_form = code_str[18 - code_len:21]
elif code_len > 3 and code_len <= 6:
code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
return code_form
class clv_insured(models.Model):
_inherit = 'clv_insured'
code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/',
help='Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).write(vals)
@api.one
def <|fim_middle|>(self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
<|fim▁end|> | copy |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, 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
#
# 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.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------<|fim▁hole|>
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
"""
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def __init__(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC
@classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs
def _handleInput(self, paramInput):
"""
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings)<|fim▁end|> | |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, 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
#
# 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.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
<|fim_middle|>
<|fim▁end|> | """
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def __init__(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC
@classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs
def _handleInput(self, paramInput):
"""
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings) |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, 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
#
# 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.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
"""
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def __init__(self):
<|fim_middle|>
@classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs
def _handleInput(self, paramInput):
"""
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings)
<|fim▁end|> | """
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, 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
#
# 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.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
"""
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def __init__(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC
@classmethod
def getInputSpecification(cls):
<|fim_middle|>
def _handleInput(self, paramInput):
"""
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings)
<|fim▁end|> | """
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, 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
#
# 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.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
"""
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def __init__(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC
@classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs
def _handleInput(self, paramInput):
<|fim_middle|>
<|fim▁end|> | """
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings) |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, 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
#
# 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.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
"""
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def <|fim_middle|>(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC
@classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs
def _handleInput(self, paramInput):
"""
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings)
<|fim▁end|> | __init__ |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, 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
#
# 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.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
"""
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def __init__(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC
@classmethod
def <|fim_middle|>(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs
def _handleInput(self, paramInput):
"""
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings)
<|fim▁end|> | getInputSpecification |
<|file_name|>LassoLarsIC.py<|end_file_name|><|fim▁begin|># Copyright 2017 Battelle Energy Alliance, 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
#
# 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.
"""
Created on Jan 21, 2020
@author: alfoa, wangc
Lasso model fit with Lars using BIC or AIC for model selection.
"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------
#External Modules------------------------------------------------------------------------------------
from numpy import finfo
#External Modules End--------------------------------------------------------------------------------
#Internal Modules------------------------------------------------------------------------------------
from SupervisedLearning.ScikitLearn import ScikitLearnBase
from utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------
class LassoLarsIC(ScikitLearnBase):
"""
Lasso model fit with Lars using BIC or AIC for model selection
"""
info = {'problemtype':'regression', 'normalize':False}
def __init__(self):
"""
Constructor that will appropriately initialize a supervised learning object
@ In, None
@ Out, None
"""
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.LassoLarsIC
@classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ In, cls, the class for which we are retrieving the specification
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(LassoLarsIC, cls).getInputSpecification()
specs.description = r"""The \xmlNode{LassoLarsIC} (\textit{Lasso model fit with Lars using BIC or AIC for model selection})
is a Lasso model fit with Lars using BIC or AIC for model selection.
The optimization objective for Lasso is:
$(1 / (2 * n\_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1$
AIC is the Akaike information criterion and BIC is the Bayes Information criterion. Such criteria
are useful to select the value of the regularization parameter by making a trade-off between the
goodness of fit and the complexity of the model. A good model should explain well the data
while being simple.
\zNormalizationNotPerformed{LassoLarsIC}
"""
specs.addSub(InputData.parameterInputFactory("criterion", contentType=InputTypes.makeEnumType("criterion", "criterionType",['bic', 'aic']),
descr=r"""The type of criterion to use.""", default='aic'))
specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
descr=r"""Whether the intercept should be estimated or not. If False,
the data is assumed to be already centered.""", default=True))
specs.addSub(InputData.parameterInputFactory("normalize", contentType=InputTypes.BoolType,
descr=r"""This parameter is ignored when fit_intercept is set to False. If True,
the regressors X will be normalized before regression by subtracting the mean and
dividing by the l2-norm.""", default=True))
specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
descr=r"""The maximum number of iterations.""", default=500))
specs.addSub(InputData.parameterInputFactory("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in the computation of the Cholesky
diagonal factors. Increase this for very ill-conditioned systems. Unlike the tol
parameter in some iterative optimization-based algorithms, this parameter does not
control the tolerance of the optimization.""", default=finfo(float).eps))
specs.addSub(InputData.parameterInputFactory("positive", contentType=InputTypes.BoolType,
descr=r"""When set to True, forces the coefficients to be positive.""", default=False))
specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.BoolType,
descr=r"""Amount of verbosity.""", default=False))
return specs
def <|fim_middle|>(self, paramInput):
"""
Function to handle the common parts of the distribution parameter input.
@ In, paramInput, ParameterInput, the already parsed input.
@ Out, None
"""
super()._handleInput(paramInput)
settings, notFound = paramInput.findNodesAndExtractValues(['fit_intercept','max_iter', 'normalize', 'precompute',
'eps','positive','criterion', 'verbose'])
# notFound must be empty
assert(not notFound)
self.initializeModel(settings)
<|fim▁end|> | _handleInput |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:<|fim▁hole|> select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def __init__(self):
self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
"""
def runCheck(self, db_connection):
unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments]))
return violations
def get_violated_segments_query(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
)<|fim▁end|> | unique_indexes_query = """ |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:
<|fim_middle|>
<|fim▁end|> | unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def __init__(self):
self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
"""
def runCheck(self, db_connection):
unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments]))
return violations
def get_violated_segments_query(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
) |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:
unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def __init__(self):
<|fim_middle|>
def runCheck(self, db_connection):
unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments]))
return violations
def get_violated_segments_query(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
)
<|fim▁end|> | self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
""" |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:
unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def __init__(self):
self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
"""
def runCheck(self, db_connection):
<|fim_middle|>
def get_violated_segments_query(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
)
<|fim▁end|> | unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments]))
return violations |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:
unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def __init__(self):
self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
"""
def runCheck(self, db_connection):
unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments]))
return violations
def get_violated_segments_query(self, table_name, column_names):
<|fim_middle|>
<|fim▁end|> | return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
) |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:
unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def __init__(self):
self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
"""
def runCheck(self, db_connection):
unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
<|fim_middle|>
return violations
def get_violated_segments_query(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
)
<|fim▁end|> | violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments])) |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:
unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def <|fim_middle|>(self):
self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
"""
def runCheck(self, db_connection):
unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments]))
return violations
def get_violated_segments_query(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
)
<|fim▁end|> | __init__ |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:
unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def __init__(self):
self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
"""
def <|fim_middle|>(self, db_connection):
unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments]))
return violations
def get_violated_segments_query(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
)
<|fim▁end|> | runCheck |
<|file_name|>unique_index_violation_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
class UniqueIndexViolationCheck:
unique_indexes_query = """
select table_oid, index_name, table_name, array_agg(attname) as column_names
from pg_attribute, (
select pg_index.indrelid as table_oid, index_class.relname as index_name, table_class.relname as table_name, unnest(pg_index.indkey) as column_index
from pg_index, pg_class index_class, pg_class table_class
where pg_index.indisunique='t'
and index_class.relnamespace = (select oid from pg_namespace where nspname = 'pg_catalog')
and index_class.relkind = 'i'
and index_class.oid = pg_index.indexrelid
and table_class.oid = pg_index.indrelid
) as unique_catalog_index_columns
where attnum = column_index
and attrelid = table_oid
group by table_oid, index_name, table_name;
"""
def __init__(self):
self.violated_segments_query = """
select distinct(gp_segment_id) from (
(select gp_segment_id, %s
from gp_dist_random('%s')
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
union
(select gp_segment_id, %s
from %s
where (%s) is not null
group by gp_segment_id, %s
having count(*) > 1)
) as violations
"""
def runCheck(self, db_connection):
unique_indexes = db_connection.query(self.unique_indexes_query).getresult()
violations = []
for (table_oid, index_name, table_name, column_names) in unique_indexes:
column_names = ",".join(column_names)
sql = self.get_violated_segments_query(table_name, column_names)
violated_segments = db_connection.query(sql).getresult()
if violated_segments:
violations.append(dict(table_oid=table_oid,
table_name=table_name,
index_name=index_name,
column_names=column_names,
violated_segments=[row[0] for row in violated_segments]))
return violations
def <|fim_middle|>(self, table_name, column_names):
return self.violated_segments_query % (
column_names, table_name, column_names, column_names, column_names, table_name, column_names, column_names
)
<|fim▁end|> | get_violated_segments_query |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2015-2018 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
from . import mass_reconcile<|fim▁hole|>from . import advanced_reconciliation<|fim▁end|> | |
<|file_name|>load_ICD9_structure.py<|end_file_name|><|fim▁begin|>import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
def getEdges(t, outfile):
for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile)
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
<|fim▁hole|>
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfile)
outfile.close()
print 'creating edges file'
outfile = file('code.edges', 'w')
getEdges(tree, outfile)
outfile.close()
print 'cleaning up'
#os.chdir('..')
#subprocess.call('rm -rf icd9', shell=1)<|fim▁end|> | sys.path.append('icd9')
from icd9 import ICD9 |
<|file_name|>load_ICD9_structure.py<|end_file_name|><|fim▁begin|>import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
<|fim_middle|>
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
def getEdges(t, outfile):
for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile)
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfile)
outfile.close()
print 'creating edges file'
outfile = file('code.edges', 'w')
getEdges(tree, outfile)
outfile.close()
print 'cleaning up'
#os.chdir('..')
#subprocess.call('rm -rf icd9', shell=1)
<|fim▁end|> | txt = ''.join(filter(lambda c: c in printable, txt))
return txt |
<|file_name|>load_ICD9_structure.py<|end_file_name|><|fim▁begin|>import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
<|fim_middle|>
def getEdges(t, outfile):
for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile)
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfile)
outfile.close()
print 'creating edges file'
outfile = file('code.edges', 'w')
getEdges(tree, outfile)
outfile.close()
print 'cleaning up'
#os.chdir('..')
#subprocess.call('rm -rf icd9', shell=1)
<|fim▁end|> | print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile) |
<|file_name|>load_ICD9_structure.py<|end_file_name|><|fim▁begin|>import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
def getEdges(t, outfile):
<|fim_middle|>
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfile)
outfile.close()
print 'creating edges file'
outfile = file('code.edges', 'w')
getEdges(tree, outfile)
outfile.close()
print 'cleaning up'
#os.chdir('..')
#subprocess.call('rm -rf icd9', shell=1)
<|fim▁end|> | for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile) |
<|file_name|>load_ICD9_structure.py<|end_file_name|><|fim▁begin|>import sys
import os
import subprocess
import string
printable = set(string.printable)
def <|fim_middle|>(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
def getEdges(t, outfile):
for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile)
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfile)
outfile.close()
print 'creating edges file'
outfile = file('code.edges', 'w')
getEdges(tree, outfile)
outfile.close()
print 'cleaning up'
#os.chdir('..')
#subprocess.call('rm -rf icd9', shell=1)
<|fim▁end|> | sanitize |
<|file_name|>load_ICD9_structure.py<|end_file_name|><|fim▁begin|>import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def <|fim_middle|>(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
def getEdges(t, outfile):
for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile)
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfile)
outfile.close()
print 'creating edges file'
outfile = file('code.edges', 'w')
getEdges(tree, outfile)
outfile.close()
print 'cleaning up'
#os.chdir('..')
#subprocess.call('rm -rf icd9', shell=1)
<|fim▁end|> | traverse |
<|file_name|>load_ICD9_structure.py<|end_file_name|><|fim▁begin|>import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
def <|fim_middle|>(t, outfile):
for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile)
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfile)
outfile.close()
print 'creating edges file'
outfile = file('code.edges', 'w')
getEdges(tree, outfile)
outfile.close()
print 'cleaning up'
#os.chdir('..')
#subprocess.call('rm -rf icd9', shell=1)
<|fim▁end|> | getEdges |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:<|fim▁hole|> }, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201<|fim▁end|> | print(e)
return {
'description': 'Failed to update message.' |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
<|fim_middle|>
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | @api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
<|fim_middle|>
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
<|fim_middle|>
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
<|fim_middle|>
<|fim▁end|> | @api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
<|fim_middle|>
<|fim▁end|> | req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
<|fim_middle|>
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | return {'message': {'email': 'No email provided'}}, 400 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
<|fim_middle|>
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | return {'message': {'email': 'Invalid email provided'}}, 400 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
<|fim_middle|>
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | return {'message': {'content': 'No content provided'}}, 400 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
<|fim_middle|>
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | return {'message': 'User not authenticated'}, 401 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
<|fim_middle|>
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
<|fim_middle|>
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | return {'message': 'Not authorised'}, 401 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
<|fim_middle|>
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | return {'message': {'id': 'No id provided'}}, 400 |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def <|fim_middle|>(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | post |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def <|fim_middle|>(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | get |
<|file_name|>contact.py<|end_file_name|><|fim▁begin|>import re
from datetime import datetime
from flask import current_app as app
from flask_jwt import current_identity
from flask_restplus import Namespace, Resource, fields, reqparse
from sqlalchemy.exc import IntegrityError
from packr.models import Message
api = Namespace('contact',
description='Operations related to the contact form')
message = api.model('Contact', {
'email': fields.String(required=True,
description='Contact email'),
'content': fields.String(required=True,
description='Message'),
})
message_id = api.model('ContactCompletion', {
'id': fields.Integer(required=True,
description='id')
})
@api.route('/')
class MessageItem(Resource):
@api.expect(message)
@api.response(204, 'Message successfully received.')
def post(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('email', type=str, required=True,
help='No email provided',
location='json')
req_parse.add_argument('content', type=str, required=True,
help='No message provided',
location='json')
args = req_parse.parse_args()
email = args.get('email')
content = args.get('content')
if email == '':
return {'message': {'email': 'No email provided'}}, 400
elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$",
email):
return {'message': {'email': 'Invalid email provided'}}, 400
if content == '':
return {'message': {'content': 'No content provided'}}, 400
new_message = Message(email=email,
content=content,
time=datetime.now())
try:
new_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to send message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'email': new_message.email}, 201
def get(self):
if not current_identity and not app.config.get('TESTING'):
return {'message': 'User not authenticated'}, 401
if app.config.get('TESTING') \
or current_identity.role.role_name == "ADMIN":
messages = dict()
for message_row in Message.query.filter_by(done=False).all():
messages[message_row.id] = {
"email": message_row.email,
"time": message_row.time.isoformat(),
"content": message_row.content
}
return messages, 201
else:
return {'message': 'Not authorised'}, 401
@api.route('/complete')
class CompleteItem(Resource):
@api.expect(message_id)
@api.response(204, 'Message successfully updated.')
def <|fim_middle|>(self):
req_parse = reqparse.RequestParser(bundle_errors=True)
req_parse.add_argument('id', type=int, required=True,
help='No id provided',
location='json')
args = req_parse.parse_args()
id = args.get('id')
if id == 0:
return {'message': {'id': 'No id provided'}}, 400
completed_message = Message.query.filter_by(id=id).first()
completed_message.done = True
try:
completed_message.save()
except IntegrityError as e:
print(e)
return {
'description': 'Failed to update message.'
}, 409
except Exception as e:
print(e)
return {'description': 'Server encountered an error.'}, 500
return {'message': "Message updated"}, 201
<|fim▁end|> | post |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>import os
ADMINS = (
# ('Eduardo Lopez', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(os.path.dirname(__file__), 'highways.db'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Mexico_City'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'es-MX'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/static/'<|fim▁hole|># trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'bre7b$*6!iagzqyi1%q@%_ofbb)e!rawcnm9apx^%kf@b%)le!'
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'project.urls'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.admindocs',
'carreteras',
)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), "templates"),
)<|fim▁end|> |
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a |
<|file_name|>test_tf_nn_moments.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: violinsolo
# Created on 08/03/2018
import tensorflow as tf
import numpy as np
x_shape = [5, 3, 3, 2]
x = np.arange(reduce(lambda t, s: t*s, list(x_shape), 1))
print x
x = x.reshape([5, 3, 3, -1])
print x.shape
X = tf.Variable(x)
with tf.Session() as sess:
m = tf.nn.moments(X, axes=[0])
# m = tf.nn.moments(X, axes=[0,1])
# m = tf.nn.moments(X, axes=np.arange(len(x_shape)-1))
mean, variance = m<|fim▁hole|><|fim▁end|> |
print(sess.run(m, feed_dict={X: x}))
# print(sess.run(m, feed_dict={X: x})) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):<|fim▁hole|> _fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)<|fim▁end|> | return self.enum_cls._fields[value]
class Playlist(APIObject): |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
<|fim_middle|>
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value] |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
<|fim_middle|>
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | self.help = help
self.enum_cls = enum_cls |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
<|fim_middle|>
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
<|fim_middle|>
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | return self.enum_cls._fields[value] |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
<|fim_middle|>
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | _fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
<|fim_middle|>
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | return '<Playlist name=\'{0}\'>'.format(self.name) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
<|fim_middle|>
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | _fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
<|fim_middle|>
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | return '<Show name=\'{0}\'>'.format(self.showName) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
<|fim_middle|>
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | _fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
<|fim_middle|>
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
<|fim_middle|>
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | _item_class = Show
items = ListField(Show) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
<|fim_middle|>
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | _item_class = Playlist
items = ListField(Playlist) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
<|fim_middle|>
<|fim▁end|> | _item_class = AMFRendition
items = ListField(AMFRendition) |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
<|fim_middle|>
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | return field |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def <|fim_middle|>(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | __init__ |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def <|fim_middle|>(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | to_python |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def <|fim_middle|>(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | from_python |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def <|fim_middle|>(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | __repr__ |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def <|fim_middle|>(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def __repr__(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | __repr__ |
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>#
# NineMSN CatchUp TV Video API Library
#
# This code is forked from Network Ten CatchUp TV Video API Library
# Copyright (c) 2013 Adam Malcontenti-Wilson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField
from brightcove.objects import ItemCollection, enum
ChannelNameEnum = enum('ten', 'eleven', 'one')
PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview')
MediaDeliveryEnum = enum('default', 'http', 'http_ios')
class EnumNumField(Field):
def __init__(self, enum_cls, help=None):
self.help = help
self.enum_cls = enum_cls
def to_python(self, value):
for i, field in enumerate(self.enum_cls._fields):
if i == value:
return field
raise Exception('Invalid Enum: %s' % value)
def from_python(self, value):
return self.enum_cls._fields[value]
class Playlist(APIObject):
_fields = ['name', 'type', 'season', 'week', 'query']
type = EnumField(PlaylistTypeEnum)
def __repr__(self):
return '<Playlist name=\'{0}\'>'.format(self.name)
class Show(APIObject):
_fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists']
channelName = EnumField(ChannelNameEnum)
playlists = ListField(Playlist)
def __repr__(self):
return '<Show name=\'{0}\'>'.format(self.showName)
class AMFRendition(APIObject):
_fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate',
'frameHeight', 'frameWidth', 'size',
'videoCodec', 'videoContainer']
mediaDeliveryType = EnumNumField(MediaDeliveryEnum)
def <|fim_middle|>(self):
return '<Rendition bitrate=\'{0}\' type=\'{1}\' frameSize=\'{2}x{3}\'>'.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight)
class ShowItemCollection(ItemCollection):
_item_class = Show
items = ListField(Show)
class PlaylistItemCollection(ItemCollection):
_item_class = Playlist
items = ListField(Playlist)
class MediaRenditionItemCollection(ItemCollection):
_item_class = AMFRendition
items = ListField(AMFRendition)
<|fim▁end|> | __repr__ |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
super(CategoricalType, self ).__init__(definition)<|fim▁hole|>
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var)
def comparator(self, field_1, field_2) :
if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
return self.cat_comparator(0, 0)
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True<|fim▁end|> |
self.cat_comparator = CategoricalComparator([0,1]) |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
<|fim_middle|>
<|fim▁end|> | type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
super(CategoricalType, self ).__init__(definition)
self.cat_comparator = CategoricalComparator([0,1])
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var)
def comparator(self, field_1, field_2) :
if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
return self.cat_comparator(0, 0)
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
<|fim_middle|>
def comparator(self, field_1, field_2) :
if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
return self.cat_comparator(0, 0)
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True
<|fim▁end|> | super(CategoricalType, self ).__init__(definition)
self.cat_comparator = CategoricalComparator([0,1])
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var) |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
super(CategoricalType, self ).__init__(definition)
self.cat_comparator = CategoricalComparator([0,1])
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var)
def comparator(self, field_1, field_2) :
<|fim_middle|>
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True
<|fim▁end|> | if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
return self.cat_comparator(0, 0) |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
super(CategoricalType, self ).__init__(definition)
self.cat_comparator = CategoricalComparator([0,1])
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var)
def comparator(self, field_1, field_2) :
if field_1 and field_2 :
<|fim_middle|>
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
return self.cat_comparator(0, 0)
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True
<|fim▁end|> | return self.cat_comparator(1, 1) |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
super(CategoricalType, self ).__init__(definition)
self.cat_comparator = CategoricalComparator([0,1])
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var)
def comparator(self, field_1, field_2) :
if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
<|fim_middle|>
else :
return self.cat_comparator(0, 0)
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True
<|fim▁end|> | return self.cat_comparator(0, 1) |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
super(CategoricalType, self ).__init__(definition)
self.cat_comparator = CategoricalComparator([0,1])
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var)
def comparator(self, field_1, field_2) :
if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
<|fim_middle|>
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True
<|fim▁end|> | return self.cat_comparator(0, 0) |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def <|fim_middle|>(self, definition) :
super(CategoricalType, self ).__init__(definition)
self.cat_comparator = CategoricalComparator([0,1])
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var)
def comparator(self, field_1, field_2) :
if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
return self.cat_comparator(0, 0)
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True
<|fim▁end|> | __init__ |
<|file_name|>exists.py<|end_file_name|><|fim▁begin|>from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
class ExistsType(CategoricalType) :
type = "Exists"
_predicate_functions = []
def __init__(self, definition) :
super(CategoricalType, self ).__init__(definition)
self.cat_comparator = CategoricalComparator([0,1])
self.higher_vars = []
for higher_var in self.cat_comparator.dummy_names :
dummy_var = DerivedType({'name' : higher_var,
'type' : 'Dummy',
'has missing' : self.has_missing})
self.higher_vars.append(dummy_var)
def <|fim_middle|>(self, field_1, field_2) :
if field_1 and field_2 :
return self.cat_comparator(1, 1)
elif field_1 or field_2 :
return self.cat_comparator(0, 1)
else :
return self.cat_comparator(0, 0)
# This flag tells fieldDistances in dedupe.core to pass
# missing values (None) into the comparator
comparator.missing = True
<|fim▁end|> | comparator |
<|file_name|>general_script_L1_PACS.py<|end_file_name|><|fim▁begin|>### This script fetches level-1 PACS imaging data, using a list generated by the
### archive (in the CSV format), attaches sky coordinates and masks to them
### (by calling the convertL1ToScanam task) and save them to disk in the correct
### format for later use by Scanamorphos.
### See important instructions below.
<|fim▁hole|>
#######################################################
### This script is part of the Scanamorphos package.
### HCSS is free software: you can redistribute it and/or modify
### it under the terms of the GNU Lesser General Public License as
### published by the Free Software Foundation, either version 3 of
### the License, or (at your option) any later version.
#######################################################
## Import classes and definitions:
import os
from herschel.pacs.spg.phot import ConvertL1ToScanamTask
#######################################################
## local settings:
dir_root = "/pcdisk/stark/aribas/Desktop/modeling_TDs/remaps_Cha/PACS/scanamorphos/"
path = dir_root +"L1/"
### number of observations:
n_obs = 2
#######################################################
## Do a multiple target search in the archive and use the "save all results as CSV" option.
## --> ascii table 'results.csv' where lines can be edited
## (suppress unwanted observations and correct target names)
## Create the directories contained in the dir_out variables (l. 57)
## before running this script.
#######################################################
## observations:
table_obs = asciiTableReader(file=dir_root+'results_fast.csv', tableType='CSV', skipRows=1)
list_obsids = table_obs[0].data
list_names = table_obs[1].data
for i_obs in range(n_obs):
##
num_obsid = list_obsids[i_obs]
source = list_names[i_obs]
source = str.lower(str(source))
dir_out = path+source+"_processed_obsids"
# create directory if it does not exist
if not(os.path.exists(dir_out)):
os.system('mkdir '+dir_out)
##
print ""
print "Downloading obsid " + `num_obsid`
obs = getObservation(num_obsid, useHsa=True, instrument="PACS", verbose=True)
###
frames = obs.level1.refs["HPPAVGR"].product.refs[0].product
convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)
###
frames = obs.level1.refs["HPPAVGB"].product.refs[0].product
convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)
### END OF SCRIPT
#######################################################<|fim▁end|> | |
<|file_name|>general_script_L1_PACS.py<|end_file_name|><|fim▁begin|>### This script fetches level-1 PACS imaging data, using a list generated by the
### archive (in the CSV format), attaches sky coordinates and masks to them
### (by calling the convertL1ToScanam task) and save them to disk in the correct
### format for later use by Scanamorphos.
### See important instructions below.
#######################################################
### This script is part of the Scanamorphos package.
### HCSS is free software: you can redistribute it and/or modify
### it under the terms of the GNU Lesser General Public License as
### published by the Free Software Foundation, either version 3 of
### the License, or (at your option) any later version.
#######################################################
## Import classes and definitions:
import os
from herschel.pacs.spg.phot import ConvertL1ToScanamTask
#######################################################
## local settings:
dir_root = "/pcdisk/stark/aribas/Desktop/modeling_TDs/remaps_Cha/PACS/scanamorphos/"
path = dir_root +"L1/"
### number of observations:
n_obs = 2
#######################################################
## Do a multiple target search in the archive and use the "save all results as CSV" option.
## --> ascii table 'results.csv' where lines can be edited
## (suppress unwanted observations and correct target names)
## Create the directories contained in the dir_out variables (l. 57)
## before running this script.
#######################################################
## observations:
table_obs = asciiTableReader(file=dir_root+'results_fast.csv', tableType='CSV', skipRows=1)
list_obsids = table_obs[0].data
list_names = table_obs[1].data
for i_obs in range(n_obs):
##
num_obsid = list_obsids[i_obs]
source = list_names[i_obs]
source = str.lower(str(source))
dir_out = path+source+"_processed_obsids"
# create directory if it does not exist
if not(os.path.exists(dir_out)):
<|fim_middle|>
print ""
print "Downloading obsid " + `num_obsid`
obs = getObservation(num_obsid, useHsa=True, instrument="PACS", verbose=True)
###
frames = obs.level1.refs["HPPAVGR"].product.refs[0].product
convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)
###
frames = obs.level1.refs["HPPAVGB"].product.refs[0].product
convertL1ToScanam(frames, cancelGlitch=1, assignRaDec=1, outDir=dir_out)
### END OF SCRIPT
#######################################################
<|fim▁end|> | os.system('mkdir '+dir_out)
## |
<|file_name|>source_list.py<|end_file_name|><|fim▁begin|>#
# Copyright 2014-2015 Boundary, Inc.
#
# 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
#
# 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.
#<|fim▁hole|>from boundary import ApiCli
class SourceList(ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.path = "v1/account/sources/"
self.method = "GET"
def getDescription(self):
return "Lists the sources in a Boundary account"<|fim▁end|> | |
<|file_name|>source_list.py<|end_file_name|><|fim▁begin|>#
# Copyright 2014-2015 Boundary, Inc.
#
# 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
#
# 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.
#
from boundary import ApiCli
class SourceList(ApiCli):
<|fim_middle|>
<|fim▁end|> | def __init__(self):
ApiCli.__init__(self)
self.path = "v1/account/sources/"
self.method = "GET"
def getDescription(self):
return "Lists the sources in a Boundary account" |
<|file_name|>source_list.py<|end_file_name|><|fim▁begin|>#
# Copyright 2014-2015 Boundary, Inc.
#
# 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
#
# 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.
#
from boundary import ApiCli
class SourceList(ApiCli):
def __init__(self):
<|fim_middle|>
def getDescription(self):
return "Lists the sources in a Boundary account"
<|fim▁end|> | ApiCli.__init__(self)
self.path = "v1/account/sources/"
self.method = "GET" |
<|file_name|>source_list.py<|end_file_name|><|fim▁begin|>#
# Copyright 2014-2015 Boundary, Inc.
#
# 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
#
# 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.
#
from boundary import ApiCli
class SourceList(ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.path = "v1/account/sources/"
self.method = "GET"
def getDescription(self):
<|fim_middle|>
<|fim▁end|> | return "Lists the sources in a Boundary account" |
<|file_name|>source_list.py<|end_file_name|><|fim▁begin|>#
# Copyright 2014-2015 Boundary, Inc.
#
# 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
#
# 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.
#
from boundary import ApiCli
class SourceList(ApiCli):
def <|fim_middle|>(self):
ApiCli.__init__(self)
self.path = "v1/account/sources/"
self.method = "GET"
def getDescription(self):
return "Lists the sources in a Boundary account"
<|fim▁end|> | __init__ |
<|file_name|>source_list.py<|end_file_name|><|fim▁begin|>#
# Copyright 2014-2015 Boundary, Inc.
#
# 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
#
# 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.
#
from boundary import ApiCli
class SourceList(ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.path = "v1/account/sources/"
self.method = "GET"
def <|fim_middle|>(self):
return "Lists the sources in a Boundary account"
<|fim▁end|> | getDescription |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass<|fim▁hole|>class AddressBook(object):
"""can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def get_contacts(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
return []
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
<|fim_middle|>
class AddressBook(object):
"""can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def get_contacts(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
return []
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res
<|fim▁end|> | pass |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass
class AddressBook(object):
<|fim_middle|>
<|fim▁end|> | """can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def get_contacts(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
return []
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass
class AddressBook(object):
"""can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
<|fim_middle|>
@abc.abstractmethod
def get_contacts(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
return []
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res
<|fim▁end|> | self.reflags = re.IGNORECASE if ignorecase else 0 |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass
class AddressBook(object):
"""can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def get_contacts(self): # pragma no cover
<|fim_middle|>
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res
<|fim▁end|> | """list all contacts tuples in this abook as (name, email) tuples"""
return [] |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass
class AddressBook(object):
"""can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def get_contacts(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
return []
def lookup(self, query=''):
<|fim_middle|>
<|fim▁end|> | """looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass
class AddressBook(object):
"""can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def get_contacts(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
return []
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
<|fim_middle|>
return res
<|fim▁end|> | res.append((name, email)) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass
class AddressBook(object):
"""can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def <|fim_middle|>(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def get_contacts(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
return []
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res
<|fim▁end|> | __init__ |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011-2015 Patrick Totzke <[email protected]>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass
class AddressBook(object):
"""can look up email addresses and realnames for contacts.
.. note::
This is an abstract class that leaves :meth:`get_contacts`
unspecified. See :class:`AbookAddressBook` and
:class:`ExternalAddressbook` for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def <|fim_middle|>(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
return []
def lookup(self, query=''):
"""looks up all contacts where name or address match query"""
res = []
query = re.compile('.*%s.*' % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res
<|fim▁end|> | get_contacts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.