code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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 datetime import datetime, timedelta import time from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT import openerp.addons.decimal_precision as dp from openerp import workflow class res_company(osv.Model): _inherit = "res.company" _columns = { 'sale_note': fields.text('Default Terms and Conditions', translate=True, help="Default terms and conditions for quotations."), } class sale_order(osv.osv): _name = "sale.order" _inherit = ['mail.thread', 'ir.needaction_mixin'] _description = "Sales Order" _track = { 'state': { 'sale.mt_order_confirmed': lambda self, cr, uid, obj, ctx=None: obj.state in ['manual', 'progress'], 'sale.mt_order_sent': lambda self, cr, uid, obj, ctx=None: obj.state in ['sent'] }, } def _amount_line_tax(self, cr, uid, line, context=None): val = 0.0 for c in self.pool.get('account.tax').compute_all(cr, uid, line.tax_id, line.price_unit * (1-(line.discount or 0.0)/100.0), line.product_uom_qty, line.product_id, line.order_id.partner_id)['taxes']: val += c.get('amount', 0.0) return val def _amount_all_wrapper(self, cr, uid, ids, field_name, arg, context=None): """ Wrapper because of direct method passing as parameter for function fields """ return self._amount_all(cr, uid, ids, field_name, arg, context=context) def _amount_all(self, cr, uid, ids, field_name, arg, context=None): cur_obj = self.pool.get('res.currency') res = {} for order in self.browse(cr, uid, ids, context=context): res[order.id] = { 'amount_untaxed': 0.0, 'amount_tax': 0.0, 'amount_total': 0.0, } val = val1 = 0.0 cur = order.pricelist_id.currency_id for line in order.order_line: val1 += line.price_subtotal val += self._amount_line_tax(cr, uid, line, context=context) res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val) res[order.id]['amount_untaxed'] = cur_obj.round(cr, uid, cur, val1) res[order.id]['amount_total'] = res[order.id]['amount_untaxed'] + res[order.id]['amount_tax'] return res def _invoiced_rate(self, cursor, user, ids, name, arg, context=None): res = {} for sale in self.browse(cursor, user, ids, context=context): if sale.invoiced: res[sale.id] = 100.0 continue tot = 0.0 for invoice in sale.invoice_ids: if invoice.state not in ('draft', 'cancel'): tot += invoice.amount_untaxed if tot: res[sale.id] = min(100.0, tot * 100.0 / (sale.amount_untaxed or 1.00)) else: res[sale.id] = 0.0 return res def _invoice_exists(self, cursor, user, ids, name, arg, context=None): res = {} for sale in self.browse(cursor, user, ids, context=context): res[sale.id] = False if sale.invoice_ids: res[sale.id] = True return res def _invoiced(self, cursor, user, ids, name, arg, context=None): res = {} for sale in self.browse(cursor, user, ids, context=context): res[sale.id] = True invoice_existence = False for invoice in sale.invoice_ids: if invoice.state!='cancel': invoice_existence = True if invoice.state != 'paid': res[sale.id] = False break if not invoice_existence or sale.state == 'manual': res[sale.id] = False return res def _invoiced_search(self, cursor, user, obj, name, args, context=None): if not len(args): return [] clause = '' sale_clause = '' no_invoiced = False for arg in args: if (arg[1] == '=' and arg[2]) or (arg[1] == '!=' and not arg[2]): clause += 'AND inv.state = \'paid\'' else: clause += 'AND inv.state != \'cancel\' AND sale.state != \'cancel\' AND inv.state <> \'paid\' AND rel.order_id = sale.id ' sale_clause = ', sale_order AS sale ' no_invoiced = True cursor.execute('SELECT rel.order_id ' \ 'FROM sale_order_invoice_rel AS rel, account_invoice AS inv '+ sale_clause + \ 'WHERE rel.invoice_id = inv.id ' + clause) res = cursor.fetchall() if no_invoiced: cursor.execute('SELECT sale.id ' \ 'FROM sale_order AS sale ' \ 'WHERE sale.id NOT IN ' \ '(SELECT rel.order_id ' \ 'FROM sale_order_invoice_rel AS rel) and sale.state != \'cancel\'') res.extend(cursor.fetchall()) if not res: return [('id', '=', 0)] return [('id', 'in', [x[0] for x in res])] def _get_order(self, cr, uid, ids, context=None): result = {} for line in self.pool.get('sale.order.line').browse(cr, uid, ids, context=context): result[line.order_id.id] = True return result.keys() def _get_default_company(self, cr, uid, context=None): company_id = self.pool.get('res.users')._get_company(cr, uid, context=context) if not company_id: raise osv.except_osv(_('Error!'), _('There is no default company for the current user!')) return company_id def _get_default_section_id(self, cr, uid, context=None): """ Gives default section by checking if present in the context """ section_id = self._resolve_section_id_from_context(cr, uid, context=context) or False if not section_id: section_id = self.pool.get('res.users').browse(cr, uid, uid, context).default_section_id.id or False return section_id def _resolve_section_id_from_context(self, cr, uid, context=None): """ Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team. """ if context is None: context = {} if type(context.get('default_section_id')) in (int, long): return context.get('default_section_id') if isinstance(context.get('default_section_id'), basestring): section_ids = self.pool.get('crm.case.section').name_search(cr, uid, name=context['default_section_id'], context=context) if len(section_ids) == 1: return int(section_ids[0][0]) return None _columns = { 'name': fields.char('Order Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, select=True), 'origin': fields.char('Source Document', help="Reference of the document that generated this sales order request."), 'client_order_ref': fields.char('Reference/Description', copy=False), 'state': fields.selection([ ('draft', 'Draft Quotation'), ('sent', 'Quotation Sent'), ('cancel', 'Cancelled'), ('waiting_date', 'Waiting Schedule'), ('progress', 'Sales Order'), ('manual', 'Sale to Invoice'), ('shipping_except', 'Shipping Exception'), ('invoice_except', 'Invoice Exception'), ('done', 'Done'), ], 'Status', readonly=True, copy=False, help="Gives the status of the quotation or sales order.\ \nThe exception status is automatically set when a cancel operation occurs \ in the invoice validation (Invoice Exception) or in the picking list process (Shipping Exception).\nThe 'Waiting Schedule' status is set when the invoice is confirmed\ but waiting for the scheduler to run on the order date.", select=True), 'date_order': fields.datetime('Date', required=True, readonly=True, select=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=False), 'create_date': fields.datetime('Creation Date', readonly=True, select=True, help="Date on which sales order is created."), 'date_confirm': fields.date('Confirmation Date', readonly=True, select=True, help="Date on which sales order is confirmed.", copy=False), 'user_id': fields.many2one('res.users', 'Salesperson', states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, select=True, track_visibility='onchange'), 'partner_id': fields.many2one('res.partner', 'Customer', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True, change_default=True, select=True, track_visibility='always'), 'partner_invoice_id': fields.many2one('res.partner', 'Invoice Address', readonly=True, required=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="Invoice address for current sales order."), 'partner_shipping_id': fields.many2one('res.partner', 'Delivery Address', readonly=True, required=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="Delivery address for current sales order."), 'order_policy': fields.selection([ ('manual', 'On Demand'), ], 'Create Invoice', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="""This field controls how invoice and delivery operations are synchronized."""), 'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="Pricelist for current sales order."), 'currency_id': fields.related('pricelist_id', 'currency_id', type="many2one", relation="res.currency", string="Currency", readonly=True, required=True), 'project_id': fields.many2one('account.analytic.account', 'Contract / Analytic', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="The analytic account related to a sales order."), 'order_line': fields.one2many('sale.order.line', 'order_id', 'Order Lines', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=True), 'invoice_ids': fields.many2many('account.invoice', 'sale_order_invoice_rel', 'order_id', 'invoice_id', 'Invoices', readonly=True, copy=False, help="This is the list of invoices that have been generated for this sales order. The same sales order may have been invoiced in several times (by line for example)."), 'invoiced_rate': fields.function(_invoiced_rate, string='Invoiced Ratio', type='float'), 'invoiced': fields.function(_invoiced, string='Paid', fnct_search=_invoiced_search, type='boolean', help="It indicates that an invoice has been paid."), 'invoice_exists': fields.function(_invoice_exists, string='Invoiced', fnct_search=_invoiced_search, type='boolean', help="It indicates that sales order has at least one invoice."), 'note': fields.text('Terms and conditions'), 'amount_untaxed': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Untaxed Amount', store={ 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), }, multi='sums', help="The amount without tax.", track_visibility='always'), 'amount_tax': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Taxes', store={ 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), }, multi='sums', help="The tax amount."), 'amount_total': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Total', store={ 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), }, multi='sums', help="The total amount."), 'payment_term': fields.many2one('account.payment.term', 'Payment Term'), 'fiscal_position': fields.many2one('account.fiscal.position', 'Fiscal Position'), 'company_id': fields.many2one('res.company', 'Company'), 'section_id': fields.many2one('crm.case.section', 'Sales Team'), 'procurement_group_id': fields.many2one('procurement.group', 'Procurement group', copy=False), 'product_id': fields.related('order_line', 'product_id', type='many2one', relation='product.product', string='Product'), } _defaults = { 'date_order': fields.datetime.now, 'order_policy': 'manual', 'company_id': _get_default_company, 'state': 'draft', 'user_id': lambda obj, cr, uid, context: uid, 'name': lambda obj, cr, uid, context: '/', 'partner_invoice_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['invoice'])['invoice'], 'partner_shipping_id': lambda self, cr, uid, context: context.get('partner_id', False) and self.pool.get('res.partner').address_get(cr, uid, [context['partner_id']], ['delivery'])['delivery'], 'note': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.sale_note, 'section_id': lambda s, cr, uid, c: s._get_default_section_id(cr, uid, c), } _sql_constraints = [ ('name_uniq', 'unique(name, company_id)', 'Order Reference must be unique per Company!'), ] _order = 'date_order desc, id desc' # Form filling def unlink(self, cr, uid, ids, context=None): sale_orders = self.read(cr, uid, ids, ['state'], context=context) unlink_ids = [] for s in sale_orders: if s['state'] in ['draft', 'cancel']: unlink_ids.append(s['id']) else: raise osv.except_osv(_('Invalid Action!'), _('In order to delete a confirmed sales order, you must cancel it before!')) return osv.osv.unlink(self, cr, uid, unlink_ids, context=context) def copy_quotation(self, cr, uid, ids, context=None): id = self.copy(cr, uid, ids[0], context=context) view_ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'sale', 'view_order_form') view_id = view_ref and view_ref[1] or False, return { 'type': 'ir.actions.act_window', 'name': _('Sales Order'), 'res_model': 'sale.order', 'res_id': id, 'view_type': 'form', 'view_mode': 'form', 'view_id': view_id, 'target': 'current', 'nodestroy': True, } def onchange_pricelist_id(self, cr, uid, ids, pricelist_id, order_lines, context=None): context = context or {} if not pricelist_id: return {} value = { 'currency_id': self.pool.get('product.pricelist').browse(cr, uid, pricelist_id, context=context).currency_id.id } if not order_lines or order_lines == [(6, 0, [])]: return {'value': value} warning = { 'title': _('Pricelist Warning!'), 'message' : _('If you change the pricelist of this order (and eventually the currency), prices of existing order lines will not be updated.') } return {'warning': warning, 'value': value} def get_salenote(self, cr, uid, ids, partner_id, context=None): context_lang = context.copy() if partner_id: partner_lang = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context).lang context_lang.update({'lang': partner_lang}) return self.pool.get('res.users').browse(cr, uid, uid, context=context_lang).company_id.sale_note def onchange_delivery_id(self, cr, uid, ids, company_id, partner_id, delivery_id, fiscal_position, context=None): r = {'value': {}} if not company_id: company_id = self._get_default_company(cr, uid, context=context) fiscal_position = self.pool['account.fiscal.position'].get_fiscal_position(cr, uid, company_id, partner_id, delivery_id, context=context) if fiscal_position: r['value']['fiscal_position'] = fiscal_position return r def onchange_partner_id(self, cr, uid, ids, part, context=None): if not part: return {'value': {'partner_invoice_id': False, 'partner_shipping_id': False, 'payment_term': False, 'fiscal_position': False}} part = self.pool.get('res.partner').browse(cr, uid, part, context=context) addr = self.pool.get('res.partner').address_get(cr, uid, [part.id], ['delivery', 'invoice', 'contact']) pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False invoice_part = self.pool.get('res.partner').browse(cr, uid, addr['invoice'], context=context) payment_term = invoice_part.property_payment_term and invoice_part.property_payment_term.id or False dedicated_salesman = part.user_id and part.user_id.id or uid val = { 'partner_invoice_id': addr['invoice'], 'partner_shipping_id': addr['delivery'], 'payment_term': payment_term, 'user_id': dedicated_salesman, } delivery_onchange = self.onchange_delivery_id(cr, uid, ids, False, part.id, addr['delivery'], False, context=context) val.update(delivery_onchange['value']) if pricelist: val['pricelist_id'] = pricelist if not self._get_default_section_id(cr, uid, context=context) and part.section_id: val['section_id'] = part.section_id.id sale_note = self.get_salenote(cr, uid, ids, part.id, context=context) if sale_note: val.update({'note': sale_note}) return {'value': val} def create(self, cr, uid, vals, context=None): if context is None: context = {} if vals.get('name', '/') == '/': vals['name'] = self.pool.get('ir.sequence').get(cr, uid, 'sale.order', context=context) or '/' if vals.get('partner_id') and any(f not in vals for f in ['partner_invoice_id', 'partner_shipping_id', 'pricelist_id', 'fiscal_position']): defaults = self.onchange_partner_id(cr, uid, [], vals['partner_id'], context=context)['value'] if not vals.get('fiscal_position') and vals.get('partner_shipping_id'): delivery_onchange = self.onchange_delivery_id(cr, uid, [], vals.get('company_id'), None, vals['partner_id'], vals.get('partner_shipping_id'), context=context) defaults.update(delivery_onchange['value']) vals = dict(defaults, **vals) ctx = dict(context or {}, mail_create_nolog=True) new_id = super(sale_order, self).create(cr, uid, vals, context=ctx) self.message_post(cr, uid, [new_id], body=_("Quotation created"), context=ctx) return new_id def button_dummy(self, cr, uid, ids, context=None): return True # FIXME: deprecated method, overriders should be using _prepare_invoice() instead. # can be removed after 6.1. def _inv_get(self, cr, uid, order, context=None): return {} def _prepare_invoice(self, cr, uid, order, lines, context=None): """Prepare the dict of values to create the new invoice for a sales order. This method may be overridden to implement custom invoice generation (making sure to call super() to establish a clean extension chain). :param browse_record order: sale.order record to invoice :param list(int) line: list of invoice line IDs that must be attached to the invoice :return: dict of value to create() the invoice """ if context is None: context = {} journal_ids = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'sale'), ('company_id', '=', order.company_id.id)], limit=1) if not journal_ids: raise osv.except_osv(_('Error!'), _('Please define sales journal for this company: "%s" (id:%d).') % (order.company_id.name, order.company_id.id)) invoice_vals = { 'name': order.client_order_ref or '', 'origin': order.name, 'type': 'out_invoice', 'reference': order.client_order_ref or order.name, 'account_id': order.partner_invoice_id.property_account_receivable.id, 'partner_id': order.partner_invoice_id.id, 'journal_id': journal_ids[0], 'invoice_line': [(6, 0, lines)], 'currency_id': order.pricelist_id.currency_id.id, 'comment': order.note, 'payment_term': order.payment_term and order.payment_term.id or False, 'fiscal_position': order.fiscal_position.id or order.partner_invoice_id.property_account_position.id, 'date_invoice': context.get('date_invoice', False), 'company_id': order.company_id.id, 'user_id': order.user_id and order.user_id.id or False, 'section_id' : order.section_id.id } # Care for deprecated _inv_get() hook - FIXME: to be removed after 6.1 invoice_vals.update(self._inv_get(cr, uid, order, context=context)) return invoice_vals def _make_invoice(self, cr, uid, order, lines, context=None): inv_obj = self.pool.get('account.invoice') obj_invoice_line = self.pool.get('account.invoice.line') if context is None: context = {} invoiced_sale_line_ids = self.pool.get('sale.order.line').search(cr, uid, [('order_id', '=', order.id), ('invoiced', '=', True)], context=context) from_line_invoice_ids = [] for invoiced_sale_line_id in self.pool.get('sale.order.line').browse(cr, uid, invoiced_sale_line_ids, context=context): for invoice_line_id in invoiced_sale_line_id.invoice_lines: if invoice_line_id.invoice_id.id not in from_line_invoice_ids: from_line_invoice_ids.append(invoice_line_id.invoice_id.id) for preinv in order.invoice_ids: if preinv.state not in ('cancel',) and preinv.id not in from_line_invoice_ids: for preline in preinv.invoice_line: inv_line_id = obj_invoice_line.copy(cr, uid, preline.id, {'invoice_id': False, 'price_unit': -preline.price_unit}) lines.append(inv_line_id) inv = self._prepare_invoice(cr, uid, order, lines, context=context) inv_id = inv_obj.create(cr, uid, inv, context=context) data = inv_obj.onchange_payment_term_date_invoice(cr, uid, [inv_id], inv['payment_term'], time.strftime(DEFAULT_SERVER_DATE_FORMAT)) if data.get('value', False): inv_obj.write(cr, uid, [inv_id], data['value'], context=context) inv_obj.button_compute(cr, uid, [inv_id]) return inv_id def print_quotation(self, cr, uid, ids, context=None): ''' This function prints the sales order and mark it as sent, so that we can see more easily the next step of the workflow ''' assert len(ids) == 1, 'This option should only be used for a single id at a time' self.signal_workflow(cr, uid, ids, 'quotation_sent') return self.pool['report'].get_action(cr, uid, ids, 'sale.report_saleorder', context=context) def manual_invoice(self, cr, uid, ids, context=None): """ create invoices for the given sales orders (ids), and open the form view of one of the newly created invoices """ mod_obj = self.pool.get('ir.model.data') # create invoices through the sales orders' workflow inv_ids0 = set(inv.id for sale in self.browse(cr, uid, ids, context) for inv in sale.invoice_ids) self.signal_workflow(cr, uid, ids, 'manual_invoice') inv_ids1 = set(inv.id for sale in self.browse(cr, uid, ids, context) for inv in sale.invoice_ids) # determine newly created invoices new_inv_ids = list(inv_ids1 - inv_ids0) res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form') res_id = res and res[1] or False, return { 'name': _('Customer Invoices'), 'view_type': 'form', 'view_mode': 'form', 'view_id': [res_id], 'res_model': 'account.invoice', 'context': "{'type':'out_invoice'}", 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'current', 'res_id': new_inv_ids and new_inv_ids[0] or False, } def action_view_invoice(self, cr, uid, ids, context=None): ''' This function returns an action that display existing invoices of given sales order ids. It can either be a in a list or in a form view, if there is only one invoice to show. ''' mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') result = mod_obj.get_object_reference(cr, uid, 'account', 'action_invoice_tree1') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] #compute the number of invoices to display inv_ids = [] for so in self.browse(cr, uid, ids, context=context): inv_ids += [invoice.id for invoice in so.invoice_ids] #choose the view_mode accordingly if len(inv_ids)>1: result['domain'] = "[('id','in',["+','.join(map(str, inv_ids))+"])]" else: res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form') result['views'] = [(res and res[1] or False, 'form')] result['res_id'] = inv_ids and inv_ids[0] or False return result def test_no_product(self, cr, uid, order, context): for line in order.order_line: if line.state == 'cancel': continue if line.product_id and (line.product_id.type<>'service'): return False return True def action_invoice_create(self, cr, uid, ids, grouped=False, states=None, date_invoice = False, context=None): if states is None: states = ['confirmed', 'done', 'exception'] res = False invoices = {} invoice_ids = [] invoice = self.pool.get('account.invoice') obj_sale_order_line = self.pool.get('sale.order.line') partner_currency = {} # If date was specified, use it as date invoiced, usefull when invoices are generated this month and put the # last day of the last month as invoice date if date_invoice: context = dict(context or {}, date_invoice=date_invoice) for o in self.browse(cr, uid, ids, context=context): currency_id = o.pricelist_id.currency_id.id if (o.partner_id.id in partner_currency) and (partner_currency[o.partner_id.id] <> currency_id): raise osv.except_osv( _('Error!'), _('You cannot group sales having different currencies for the same partner.')) partner_currency[o.partner_id.id] = currency_id lines = [] for line in o.order_line: if line.invoiced: continue elif (line.state in states): lines.append(line.id) created_lines = obj_sale_order_line.invoice_line_create(cr, uid, lines) if created_lines: invoices.setdefault(o.partner_invoice_id.id or o.partner_id.id, []).append((o, created_lines)) if not invoices: for o in self.browse(cr, uid, ids, context=context): for i in o.invoice_ids: if i.state == 'draft': return i.id for val in invoices.values(): if grouped: res = self._make_invoice(cr, uid, val[0][0], reduce(lambda x, y: x + y, [l for o, l in val], []), context=context) invoice_ref = '' origin_ref = '' for o, l in val: invoice_ref += (o.client_order_ref or o.name) + '|' origin_ref += (o.origin or o.name) + '|' self.write(cr, uid, [o.id], {'state': 'progress'}) cr.execute('insert into sale_order_invoice_rel (order_id,invoice_id) values (%s,%s)', (o.id, res)) self.invalidate_cache(cr, uid, ['invoice_ids'], [o.id], context=context) #remove last '|' in invoice_ref if len(invoice_ref) >= 1: invoice_ref = invoice_ref[:-1] if len(origin_ref) >= 1: origin_ref = origin_ref[:-1] invoice.write(cr, uid, [res], {'origin': origin_ref, 'name': invoice_ref}) else: for order, il in val: res = self._make_invoice(cr, uid, order, il, context=context) invoice_ids.append(res) self.write(cr, uid, [order.id], {'state': 'progress'}) cr.execute('insert into sale_order_invoice_rel (order_id,invoice_id) values (%s,%s)', (order.id, res)) self.invalidate_cache(cr, uid, ['invoice_ids'], [order.id], context=context) return res def action_invoice_cancel(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'invoice_except'}, context=context) return True def action_invoice_end(self, cr, uid, ids, context=None): for this in self.browse(cr, uid, ids, context=context): for line in this.order_line: if line.state == 'exception': line.write({'state': 'confirmed'}) if this.state == 'invoice_except': this.write({'state': 'progress'}) return True def action_cancel(self, cr, uid, ids, context=None): if context is None: context = {} sale_order_line_obj = self.pool.get('sale.order.line') account_invoice_obj = self.pool.get('account.invoice') for sale in self.browse(cr, uid, ids, context=context): for inv in sale.invoice_ids: if inv.state not in ('draft', 'cancel'): raise osv.except_osv( _('Cannot cancel this sales order!'), _('First cancel all invoices attached to this sales order.')) inv.signal_workflow('invoice_cancel') line_ids = [l.id for l in sale.order_line if l.state != 'cancel'] sale_order_line_obj.button_cancel(cr, uid, line_ids, context=context) self.write(cr, uid, ids, {'state': 'cancel'}) return True def action_button_confirm(self, cr, uid, ids, context=None): assert len(ids) == 1, 'This option should only be used for a single id at a time.' self.signal_workflow(cr, uid, ids, 'order_confirm') return True def action_wait(self, cr, uid, ids, context=None): context = context or {} for o in self.browse(cr, uid, ids): if not any(line.state != 'cancel' for line in o.order_line): raise osv.except_osv(_('Error!'),_('You cannot confirm a sales order which has no line.')) noprod = self.test_no_product(cr, uid, o, context) if (o.order_policy == 'manual') or noprod: self.write(cr, uid, [o.id], {'state': 'manual', 'date_confirm': fields.date.context_today(self, cr, uid, context=context)}) else: self.write(cr, uid, [o.id], {'state': 'progress', 'date_confirm': fields.date.context_today(self, cr, uid, context=context)}) self.pool.get('sale.order.line').button_confirm(cr, uid, [x.id for x in o.order_line if x.state != 'cancel']) return True def action_quotation_send(self, cr, uid, ids, context=None): ''' This function opens a window to compose an email, with the edi sale template message loaded by default ''' assert len(ids) == 1, 'This option should only be used for a single id at a time.' ir_model_data = self.pool.get('ir.model.data') try: template_id = ir_model_data.get_object_reference(cr, uid, 'sale', 'email_template_edi_sale')[1] except ValueError: template_id = False try: compose_form_id = ir_model_data.get_object_reference(cr, uid, 'mail', 'email_compose_message_wizard_form')[1] except ValueError: compose_form_id = False ctx = dict() ctx.update({ 'default_model': 'sale.order', 'default_res_id': ids[0], 'default_use_template': bool(template_id), 'default_template_id': template_id, 'default_composition_mode': 'comment', 'mark_so_as_sent': True }) return { 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'mail.compose.message', 'views': [(compose_form_id, 'form')], 'view_id': compose_form_id, 'target': 'new', 'context': ctx, } def action_done(self, cr, uid, ids, context=None): for order in self.browse(cr, uid, ids, context=context): self.pool.get('sale.order.line').write(cr, uid, [line.id for line in order.order_line if line.state != 'cancel'], {'state': 'done'}, context=context) return self.write(cr, uid, ids, {'state': 'done'}, context=context) def _prepare_order_line_procurement(self, cr, uid, order, line, group_id=False, context=None): date_planned = self._get_date_planned(cr, uid, order, line, order.date_order, context=context) return { 'name': line.name, 'origin': order.name, 'date_planned': date_planned, 'product_id': line.product_id.id, 'product_qty': line.product_uom_qty, 'product_uom': line.product_uom.id, 'product_uos_qty': (line.product_uos and line.product_uos_qty) or line.product_uom_qty, 'product_uos': (line.product_uos and line.product_uos.id) or line.product_uom.id, 'company_id': order.company_id.id, 'group_id': group_id, 'invoice_state': (order.order_policy == 'picking') and '2binvoiced' or 'none', 'sale_line_id': line.id } def _get_date_planned(self, cr, uid, order, line, start_date, context=None): date_planned = datetime.strptime(start_date, DEFAULT_SERVER_DATETIME_FORMAT) + timedelta(days=line.delay or 0.0) return date_planned def _prepare_procurement_group(self, cr, uid, order, context=None): return {'name': order.name, 'partner_id': order.partner_shipping_id.id} def procurement_needed(self, cr, uid, ids, context=None): #when sale is installed only, there is no need to create procurements, that's only #further installed modules (sale_service, sale_stock) that will change this. sale_line_obj = self.pool.get('sale.order.line') res = [] for order in self.browse(cr, uid, ids, context=context): res.append(sale_line_obj.need_procurement(cr, uid, [line.id for line in order.order_line if line.state != 'cancel'], context=context)) return any(res) def action_ignore_delivery_exception(self, cr, uid, ids, context=None): for sale_order in self.browse(cr, uid, ids, context=context): self.write(cr, uid, ids, {'state': 'progress' if sale_order.invoice_exists else 'manual'}, context=context) return True def action_ship_create(self, cr, uid, ids, context=None): """Create the required procurements to supply sales order lines, also connecting the procurements to appropriate stock moves in order to bring the goods to the sales order's requested location. :return: True """ context = context or {} context['lang'] = self.pool['res.users'].browse(cr, uid, uid).lang procurement_obj = self.pool.get('procurement.order') sale_line_obj = self.pool.get('sale.order.line') for order in self.browse(cr, uid, ids, context=context): proc_ids = [] vals = self._prepare_procurement_group(cr, uid, order, context=context) if not order.procurement_group_id: group_id = self.pool.get("procurement.group").create(cr, uid, vals, context=context) order.write({'procurement_group_id': group_id}) for line in order.order_line: if line.state == 'cancel': continue #Try to fix exception procurement (possible when after a shipping exception the user choose to recreate) if line.procurement_ids: #first check them to see if they are in exception or not (one of the related moves is cancelled) procurement_obj.check(cr, uid, [x.id for x in line.procurement_ids if x.state not in ['cancel', 'done']]) line.refresh() #run again procurement that are in exception in order to trigger another move except_proc_ids = [x.id for x in line.procurement_ids if x.state in ('exception', 'cancel')] procurement_obj.reset_to_confirmed(cr, uid, except_proc_ids, context=context) proc_ids += except_proc_ids elif sale_line_obj.need_procurement(cr, uid, [line.id], context=context): if (line.state == 'done') or not line.product_id: continue vals = self._prepare_order_line_procurement(cr, uid, order, line, group_id=order.procurement_group_id.id, context=context) ctx = context.copy() ctx['procurement_autorun_defer'] = True proc_id = procurement_obj.create(cr, uid, vals, context=ctx) proc_ids.append(proc_id) #Confirm procurement order such that rules will be applied on it #note that the workflow normally ensure proc_ids isn't an empty list procurement_obj.run(cr, uid, proc_ids, context=context) #if shipping was in exception and the user choose to recreate the delivery order, write the new status of SO if order.state == 'shipping_except': val = {'state': 'progress', 'shipped': False} if (order.order_policy == 'manual'): for line in order.order_line: if (not line.invoiced) and (line.state not in ('cancel', 'draft')): val['state'] = 'manual' break order.write(val) return True def onchange_fiscal_position(self, cr, uid, ids, fiscal_position, order_lines, context=None): '''Update taxes of order lines for each line where a product is defined :param list ids: not used :param int fiscal_position: sale order fiscal position :param list order_lines: command list for one2many write method ''' order_line = [] fiscal_obj = self.pool.get('account.fiscal.position') product_obj = self.pool.get('product.product') line_obj = self.pool.get('sale.order.line') fpos = False if fiscal_position: fpos = fiscal_obj.browse(cr, uid, fiscal_position, context=context) for line in order_lines: # create (0, 0, { fields }) # update (1, ID, { fields }) if line[0] in [0, 1]: prod = None if line[2].get('product_id'): prod = product_obj.browse(cr, uid, line[2]['product_id'], context=context) elif line[1]: prod = line_obj.browse(cr, uid, line[1], context=context).product_id if prod and prod.taxes_id: line[2]['tax_id'] = [[6, 0, fiscal_obj.map_tax(cr, uid, fpos, prod.taxes_id)]] order_line.append(line) # link (4, ID) # link all (6, 0, IDS) elif line[0] in [4, 6]: line_ids = line[0] == 4 and [line[1]] or line[2] for line_id in line_ids: prod = line_obj.browse(cr, uid, line_id, context=context).product_id if prod and prod.taxes_id: order_line.append([1, line_id, {'tax_id': [[6, 0, fiscal_obj.map_tax(cr, uid, fpos, prod.taxes_id)]]}]) else: order_line.append([4, line_id]) else: order_line.append(line) return {'value': {'order_line': order_line, 'amount_untaxed': False, 'amount_tax': False, 'amount_total': False}} def test_procurements_done(self, cr, uid, ids, context=None): for sale in self.browse(cr, uid, ids, context=context): for line in sale.order_line: if line.state == 'cancel': continue if not all([x.state == 'done' for x in line.procurement_ids]): return False return True def test_procurements_except(self, cr, uid, ids, context=None): for sale in self.browse(cr, uid, ids, context=context): for line in sale.order_line: if line.state == 'cancel': continue if any([x.state == 'cancel' for x in line.procurement_ids]): return True return False # TODO add a field price_unit_uos # - update it on change product and unit price # - use it in report if there is a uos class sale_order_line(osv.osv): def need_procurement(self, cr, uid, ids, context=None): #when sale is installed only, there is no need to create procurements, that's only #further installed modules (sale_service, sale_stock) that will change this. prod_obj = self.pool.get('product.product') for line in self.browse(cr, uid, ids, context=context): if prod_obj.need_procurement(cr, uid, [line.product_id.id], context=context): return True return False def _amount_line(self, cr, uid, ids, field_name, arg, context=None): tax_obj = self.pool.get('account.tax') cur_obj = self.pool.get('res.currency') res = {} if context is None: context = {} for line in self.browse(cr, uid, ids, context=context): price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) taxes = tax_obj.compute_all(cr, uid, line.tax_id, price, line.product_uom_qty, line.product_id, line.order_id.partner_id) cur = line.order_id.pricelist_id.currency_id res[line.id] = cur_obj.round(cr, uid, cur, taxes['total']) return res def _get_uom_id(self, cr, uid, *args): try: proxy = self.pool.get('ir.model.data') result = proxy.get_object_reference(cr, uid, 'product', 'product_uom_unit') return result[1] except Exception, ex: return False def _fnct_line_invoiced(self, cr, uid, ids, field_name, args, context=None): res = dict.fromkeys(ids, False) for this in self.browse(cr, uid, ids, context=context): res[this.id] = this.invoice_lines and \ all(iline.invoice_id.state != 'cancel' for iline in this.invoice_lines) return res def _order_lines_from_invoice(self, cr, uid, ids, context=None): # direct access to the m2m table is the less convoluted way to achieve this (and is ok ACL-wise) cr.execute("""SELECT DISTINCT sol.id FROM sale_order_invoice_rel rel JOIN sale_order_line sol ON (sol.order_id = rel.order_id) WHERE rel.invoice_id = ANY(%s)""", (list(ids),)) return [i[0] for i in cr.fetchall()] def _get_price_reduce(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, 0.0) for line in self.browse(cr, uid, ids, context=context): res[line.id] = line.price_subtotal / line.product_uom_qty return res _name = 'sale.order.line' _description = 'Sales Order Line' _columns = { 'order_id': fields.many2one('sale.order', 'Order Reference', required=True, ondelete='cascade', select=True, readonly=True, states={'draft':[('readonly',False)]}), 'name': fields.text('Description', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of sales order lines."), 'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], change_default=True, readonly=True, states={'draft': [('readonly', False)]}, ondelete='restrict'), 'invoice_lines': fields.many2many('account.invoice.line', 'sale_order_line_invoice_rel', 'order_line_id', 'invoice_id', 'Invoice Lines', readonly=True, copy=False), 'invoiced': fields.function(_fnct_line_invoiced, string='Invoiced', type='boolean', store={ 'account.invoice': (_order_lines_from_invoice, ['state'], 10), 'sale.order.line': (lambda self,cr,uid,ids,ctx=None: ids, ['invoice_lines'], 10) }), 'price_unit': fields.float('Unit Price', required=True, digits_compute= dp.get_precision('Product Price'), readonly=True, states={'draft': [('readonly', False)]}), 'price_subtotal': fields.function(_amount_line, string='Subtotal', digits_compute= dp.get_precision('Account')), 'price_reduce': fields.function(_get_price_reduce, type='float', string='Price Reduce', digits_compute=dp.get_precision('Product Price')), 'tax_id': fields.many2many('account.tax', 'sale_order_tax', 'order_line_id', 'tax_id', 'Taxes', readonly=True, states={'draft': [('readonly', False)]}), 'address_allotment_id': fields.many2one('res.partner', 'Allotment Partner',help="A partner to whom the particular product needs to be allotted."), 'product_uom_qty': fields.float('Quantity', digits_compute= dp.get_precision('Product UoS'), required=True, readonly=True, states={'draft': [('readonly', False)]}), 'product_uom': fields.many2one('product.uom', 'Unit of Measure ', required=True, readonly=True, states={'draft': [('readonly', False)]}), 'product_uos_qty': fields.float('Quantity (UoS)' ,digits_compute= dp.get_precision('Product UoS'), readonly=True, states={'draft': [('readonly', False)]}), 'product_uos': fields.many2one('product.uom', 'Product UoS'), 'discount': fields.float('Discount (%)', digits_compute= dp.get_precision('Discount'), readonly=True, states={'draft': [('readonly', False)]}), 'th_weight': fields.float('Weight', readonly=True, states={'draft': [('readonly', False)]}), 'state': fields.selection( [('cancel', 'Cancelled'),('draft', 'Draft'),('confirmed', 'Confirmed'),('exception', 'Exception'),('done', 'Done')], 'Status', required=True, readonly=True, copy=False, help='* The \'Draft\' status is set when the related sales order in draft status. \ \n* The \'Confirmed\' status is set when the related sales order is confirmed. \ \n* The \'Exception\' status is set when the related sales order is set as exception. \ \n* The \'Done\' status is set when the sales order line has been picked. \ \n* The \'Cancelled\' status is set when a user cancel the sales order related.'), 'order_partner_id': fields.related('order_id', 'partner_id', type='many2one', relation='res.partner', store=True, string='Customer'), 'salesman_id':fields.related('order_id', 'user_id', type='many2one', relation='res.users', store=True, string='Salesperson'), 'company_id': fields.related('order_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True), 'delay': fields.float('Delivery Lead Time', required=True, help="Number of days between the order confirmation and the shipping of the products to the customer", readonly=True, states={'draft': [('readonly', False)]}), 'procurement_ids': fields.one2many('procurement.order', 'sale_line_id', 'Procurements'), } _order = 'order_id desc, sequence, id' _defaults = { 'product_uom' : _get_uom_id, 'discount': 0.0, 'product_uom_qty': 1, 'product_uos_qty': 1, 'sequence': 10, 'state': 'draft', 'price_unit': 0.0, 'delay': 0.0, } def _get_line_qty(self, cr, uid, line, context=None): if line.product_uos: return line.product_uos_qty or 0.0 return line.product_uom_qty def _get_line_uom(self, cr, uid, line, context=None): if line.product_uos: return line.product_uos.id return line.product_uom.id def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None): """Prepare the dict of values to create the new invoice line for a sales order line. This method may be overridden to implement custom invoice generation (making sure to call super() to establish a clean extension chain). :param browse_record line: sale.order.line record to invoice :param int account_id: optional ID of a G/L account to force (this is used for returning products including service) :return: dict of values to create() the invoice line """ res = {} if not line.invoiced: if not account_id: if line.product_id: account_id = line.product_id.property_account_income.id if not account_id: account_id = line.product_id.categ_id.property_account_income_categ.id if not account_id: raise osv.except_osv(_('Error!'), _('Please define income account for this product: "%s" (id:%d).') % \ (line.product_id.name, line.product_id.id,)) else: prop = self.pool.get('ir.property').get(cr, uid, 'property_account_income_categ', 'product.category', context=context) account_id = prop and prop.id or False uosqty = self._get_line_qty(cr, uid, line, context=context) uos_id = self._get_line_uom(cr, uid, line, context=context) pu = 0.0 if uosqty: pu = round(line.price_unit * line.product_uom_qty / uosqty, self.pool.get('decimal.precision').precision_get(cr, uid, 'Product Price')) fpos = line.order_id.fiscal_position or False account_id = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, account_id) if not account_id: raise osv.except_osv(_('Error!'), _('There is no Fiscal Position defined or Income category account defined for default properties of Product categories.')) res = { 'name': line.name, 'sequence': line.sequence, 'origin': line.order_id.name, 'account_id': account_id, 'price_unit': pu, 'quantity': uosqty, 'discount': line.discount, 'uos_id': uos_id, 'product_id': line.product_id.id or False, 'invoice_line_tax_id': [(6, 0, [x.id for x in line.tax_id])], 'account_analytic_id': line.order_id.project_id and line.order_id.project_id.id or False, } return res def invoice_line_create(self, cr, uid, ids, context=None): if context is None: context = {} create_ids = [] sales = set() for line in self.browse(cr, uid, ids, context=context): vals = self._prepare_order_line_invoice_line(cr, uid, line, False, context) if vals: inv_id = self.pool.get('account.invoice.line').create(cr, uid, vals, context=context) self.write(cr, uid, [line.id], {'invoice_lines': [(4, inv_id)]}, context=context) sales.add(line.order_id.id) create_ids.append(inv_id) # Trigger workflow events for sale_id in sales: workflow.trg_write(uid, 'sale.order', sale_id, cr) return create_ids def button_cancel(self, cr, uid, ids, context=None): lines = self.browse(cr, uid, ids, context=context) for line in lines: if line.invoiced: raise osv.except_osv(_('Invalid Action!'), _('You cannot cancel a sales order line that has already been invoiced.')) procurement_obj = self.pool['procurement.order'] procurement_obj.cancel(cr, uid, sum([l.procurement_ids.ids for l in lines], []), context=context) return self.write(cr, uid, ids, {'state': 'cancel'}) def button_confirm(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'state': 'confirmed'}) def button_done(self, cr, uid, ids, context=None): res = self.write(cr, uid, ids, {'state': 'done'}) for line in self.browse(cr, uid, ids, context=context): workflow.trg_write(uid, 'sale.order', line.order_id.id, cr) return res def uos_change(self, cr, uid, ids, product_uos, product_uos_qty=0, product_id=None): product_obj = self.pool.get('product.product') if not product_id: return {'value': {'product_uom': product_uos, 'product_uom_qty': product_uos_qty}, 'domain': {}} product = product_obj.browse(cr, uid, product_id) value = { 'product_uom': product.uom_id.id, } # FIXME must depend on uos/uom of the product and not only of the coeff. try: value.update({ 'product_uom_qty': product_uos_qty / product.uos_coeff, 'th_weight': product_uos_qty / product.uos_coeff * product.weight }) except ZeroDivisionError: pass return {'value': value} def create(self, cr, uid, values, context=None): if values.get('order_id') and values.get('product_id') and any(f not in values for f in ['name', 'price_unit', 'type', 'product_uom_qty', 'product_uom']): order = self.pool['sale.order'].read(cr, uid, values['order_id'], ['pricelist_id', 'partner_id', 'date_order', 'fiscal_position'], context=context) defaults = self.product_id_change(cr, uid, [], order['pricelist_id'][0], values['product_id'], qty=float(values.get('product_uom_qty', False)), uom=values.get('product_uom', False), qty_uos=float(values.get('product_uos_qty', False)), uos=values.get('product_uos', False), name=values.get('name', False), partner_id=order['partner_id'][0], date_order=order['date_order'], fiscal_position=order['fiscal_position'][0] if order['fiscal_position'] else False, flag=False, # Force name update context=context )['value'] if defaults.get('tax_id'): defaults['tax_id'] = [[6, 0, defaults['tax_id']]] values = dict(defaults, **values) return super(sale_order_line, self).create(cr, uid, values, context=context) def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None): context = context or {} lang = lang or context.get('lang', False) if not partner_id: raise osv.except_osv(_('No Customer Defined!'), _('Before choosing a product,\n select a customer in the sales form.')) warning = False product_uom_obj = self.pool.get('product.uom') partner_obj = self.pool.get('res.partner') product_obj = self.pool.get('product.product') context = {'lang': lang, 'partner_id': partner_id} partner = partner_obj.browse(cr, uid, partner_id) lang = partner.lang context_partner = {'lang': lang, 'partner_id': partner_id} if not product: return {'value': {'th_weight': 0, 'product_uos_qty': qty}, 'domain': {'product_uom': [], 'product_uos': []}} if not date_order: date_order = time.strftime(DEFAULT_SERVER_DATE_FORMAT) result = {} warning_msgs = '' product_obj = product_obj.browse(cr, uid, product, context=context_partner) uom2 = False if uom: uom2 = product_uom_obj.browse(cr, uid, uom) if product_obj.uom_id.category_id.id != uom2.category_id.id: uom = False if uos: if product_obj.uos_id: uos2 = product_uom_obj.browse(cr, uid, uos) if product_obj.uos_id.category_id.id != uos2.category_id.id: uos = False else: uos = False fpos = False if not fiscal_position: fpos = partner.property_account_position or False else: fpos = self.pool.get('account.fiscal.position').browse(cr, uid, fiscal_position) if update_tax: #The quantity only have changed result['tax_id'] = self.pool.get('account.fiscal.position').map_tax(cr, uid, fpos, product_obj.taxes_id) if not flag: result['name'] = self.pool.get('product.product').name_get(cr, uid, [product_obj.id], context=context_partner)[0][1] if product_obj.description_sale: result['name'] += '\n'+product_obj.description_sale domain = {} if (not uom) and (not uos): result['product_uom'] = product_obj.uom_id.id if product_obj.uos_id: result['product_uos'] = product_obj.uos_id.id result['product_uos_qty'] = qty * product_obj.uos_coeff uos_category_id = product_obj.uos_id.category_id.id else: result['product_uos'] = False result['product_uos_qty'] = qty uos_category_id = False result['th_weight'] = qty * product_obj.weight domain = {'product_uom': [('category_id', '=', product_obj.uom_id.category_id.id)], 'product_uos': [('category_id', '=', uos_category_id)]} elif uos and not uom: # only happens if uom is False result['product_uom'] = product_obj.uom_id and product_obj.uom_id.id result['product_uom_qty'] = qty_uos / product_obj.uos_coeff result['th_weight'] = result['product_uom_qty'] * product_obj.weight elif uom: # whether uos is set or not default_uom = product_obj.uom_id and product_obj.uom_id.id q = product_uom_obj._compute_qty(cr, uid, uom, qty, default_uom) if product_obj.uos_id: result['product_uos'] = product_obj.uos_id.id result['product_uos_qty'] = qty * product_obj.uos_coeff else: result['product_uos'] = False result['product_uos_qty'] = qty result['th_weight'] = q * product_obj.weight # Round the quantity up if not uom2: uom2 = product_obj.uom_id # get unit price if not pricelist: warn_msg = _('You have to select a pricelist or a customer in the sales form !\n' 'Please set one before choosing a product.') warning_msgs += _("No Pricelist ! : ") + warn_msg +"\n\n" else: price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], product, qty or 1.0, partner_id, { 'uom': uom or result.get('product_uom'), 'date': date_order, })[pricelist] if price is False: warn_msg = _("Cannot find a pricelist line matching this product and quantity.\n" "You have to change either the product, the quantity or the pricelist.") warning_msgs += _("No valid pricelist line found ! :") + warn_msg +"\n\n" else: result.update({'price_unit': price}) if warning_msgs: warning = { 'title': _('Configuration Error!'), 'message' : warning_msgs } return {'value': result, 'domain': domain, 'warning': warning} def product_uom_change(self, cursor, user, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, context=None): context = context or {} lang = lang or ('lang' in context and context['lang']) if not uom: return {'value': {'price_unit': 0.0, 'product_uom' : uom or False}} return self.product_id_change(cursor, user, ids, pricelist, product, qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, context=context) def unlink(self, cr, uid, ids, context=None): if context is None: context = {} """Allows to delete sales order lines in draft,cancel states""" for rec in self.browse(cr, uid, ids, context=context): if rec.state not in ['draft', 'cancel']: raise osv.except_osv(_('Invalid Action!'), _('Cannot delete a sales order line which is in state \'%s\'.') %(rec.state,)) return super(sale_order_line, self).unlink(cr, uid, ids, context=context) class mail_compose_message(osv.Model): _inherit = 'mail.compose.message' def send_mail(self, cr, uid, ids, context=None): context = context or {} if context.get('default_model') == 'sale.order' and context.get('default_res_id') and context.get('mark_so_as_sent'): context = dict(context, mail_post_autofollow=True) self.pool.get('sale.order').signal_workflow(cr, uid, [context['default_res_id']], 'quotation_sent') return super(mail_compose_message, self).send_mail(cr, uid, ids, context=context) class account_invoice(osv.Model): _inherit = 'account.invoice' def _get_default_section_id(self, cr, uid, context=None): """ Gives default section by checking if present in the context """ section_id = self._resolve_section_id_from_context(cr, uid, context=context) or False if not section_id: section_id = self.pool.get('res.users').browse(cr, uid, uid, context).default_section_id.id or False return section_id def _resolve_section_id_from_context(self, cr, uid, context=None): """ Returns ID of section based on the value of 'section_id' context key, or None if it cannot be resolved to a single Sales Team. """ if context is None: context = {} if type(context.get('default_section_id')) in (int, long): return context.get('default_section_id') if isinstance(context.get('default_section_id'), basestring): section_ids = self.pool.get('crm.case.section').name_search(cr, uid, name=context['default_section_id'], context=context) if len(section_ids) == 1: return int(section_ids[0][0]) return None _columns = { 'section_id': fields.many2one('crm.case.section', 'Sales Team'), } _defaults = { 'section_id': lambda self, cr, uid, c=None: self._get_default_section_id(cr, uid, context=c) } def confirm_paid(self, cr, uid, ids, context=None): sale_order_obj = self.pool.get('sale.order') res = super(account_invoice, self).confirm_paid(cr, uid, ids, context=context) so_ids = sale_order_obj.search(cr, uid, [('invoice_ids', 'in', ids)], context=context) for so_id in so_ids: sale_order_obj.message_post(cr, uid, so_id, body=_("Invoice paid"), context=context) return res def unlink(self, cr, uid, ids, context=None): """ Overwrite unlink method of account invoice to send a trigger to the sale workflow upon invoice deletion """ invoice_ids = self.search(cr, uid, [('id', 'in', ids), ('state', 'in', ['draft', 'cancel'])], context=context) #if we can't cancel all invoices, do nothing if len(invoice_ids) == len(ids): #Cancel invoice(s) first before deleting them so that if any sale order is associated with them #it will trigger the workflow to put the sale order in an 'invoice exception' state for id in ids: workflow.trg_validate(uid, 'account.invoice', id, 'invoice_cancel', cr) return super(account_invoice, self).unlink(cr, uid, ids, context=context) class procurement_order(osv.osv): _inherit = 'procurement.order' _columns = { 'sale_line_id': fields.many2one('sale.order.line', string='Sale Order Line'), } def write(self, cr, uid, ids, vals, context=None): if isinstance(ids, (int, long)): ids = [ids] res = super(procurement_order, self).write(cr, uid, ids, vals, context=context) from openerp import workflow if vals.get('state') in ['done', 'cancel', 'exception']: for proc in self.browse(cr, uid, ids, context=context): if proc.sale_line_id and proc.sale_line_id.order_id: order_id = proc.sale_line_id.order_id.id if self.pool.get('sale.order').test_procurements_done(cr, uid, [order_id], context=context): workflow.trg_validate(uid, 'sale.order', order_id, 'ship_end', cr) if self.pool.get('sale.order').test_procurements_except(cr, uid, [order_id], context=context): workflow.trg_validate(uid, 'sale.order', order_id, 'ship_except', cr) return res class product_product(osv.Model): _inherit = 'product.product' def _sales_count(self, cr, uid, ids, field_name, arg, context=None): r = dict.fromkeys(ids, 0) domain = [ ('state', 'in', ['waiting_date','progress','manual', 'shipping_except', 'invoice_except', 'done']), ('product_id', 'in', ids), ] for group in self.pool['sale.report'].read_group(cr, uid, domain, ['product_id','product_uom_qty'], ['product_id'], context=context): r[group['product_id'][0]] = group['product_uom_qty'] return r def action_view_sales(self, cr, uid, ids, context=None): result = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'sale.action_order_line_product_tree', raise_if_not_found=True) result = self.pool['ir.actions.act_window'].read(cr, uid, [result], context=context)[0] result['domain'] = "[('product_id','in',[" + ','.join(map(str, ids)) + "])]" return result _columns = { 'sales_count': fields.function(_sales_count, string='# Sales', type='integer'), } class product_template(osv.Model): _inherit = 'product.template' def _sales_count(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, 0) for template in self.browse(cr, uid, ids, context=context): res[template.id] = sum([p.sales_count for p in template.product_variant_ids]) return res def action_view_sales(self, cr, uid, ids, context=None): act_obj = self.pool.get('ir.actions.act_window') mod_obj = self.pool.get('ir.model.data') product_ids = [] for template in self.browse(cr, uid, ids, context=context): product_ids += [x.id for x in template.product_variant_ids] result = mod_obj.xmlid_to_res_id(cr, uid, 'sale.action_order_line_product_tree',raise_if_not_found=True) result = act_obj.read(cr, uid, [result], context=context)[0] result['domain'] = "[('product_id','in',[" + ','.join(map(str, product_ids)) + "])]" return result _columns = { 'sales_count': fields.function(_sales_count, string='# Sales', type='integer'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
gvb/odoo
addons/sale/sale.py
Python
agpl-3.0
71,046
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi. Copyright Camptocamp SA # Financial contributors: Hasa SA, Open Net SA, # Prisme Solutions Informatique SA, Quod SA # # 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/>. # ############################################################################## import base64 import time import re from openerp.tools.translate import _ from openerp.osv.orm import TransientModel, fields from openerp.osv.osv import except_osv from openerp.tools import mod10r REF = re.compile('[^0-9]') class BvrImporterWizard(TransientModel): _name = 'bvr.import.wizard' _columns = {'file': fields.binary('BVR File')} def _reconstruct_invoice_ref(self, cursor, user, reference, context=None): """Try to get correct invoice/invoice line form ESV/BVR reference""" id_invoice = False # On fait d'abord une recherche sur toutes les factures # we now search for an invoice user_obj = self.pool['res.users'] user_current = user_obj.browse(cursor, user, user) cursor.execute("SELECT inv.id, inv.number from account_invoice " "AS inv where inv.company_id = %s and type='out_invoice'", (user_current.company_id.id,)) result_invoice = cursor.fetchall() for inv_id, inv_name in result_invoice: inv_name = REF.sub('0', str(inv_name)) if inv_name == reference: id_invoice = inv_id break if id_invoice: cursor.execute('SELECT l.id' ' FROM account_move_line l, account_invoice i' ' WHERE l.move_id = i.move_id AND l.reconcile_id is NULL ' ' AND i.id IN %s', (tuple([id_invoice]),)) inv_line = [] for id_line in cursor.fetchall(): inv_line.append(id_line[0]) return inv_line else: return [] def _parse_lines(self, cursor, uid, inlines, context=None): """Parses raw v11 line and populate records list with dict""" records = [] total_amount = 0 total_cost = 0 find_total = False for lines in inlines: if not lines: # manage new line at end of file continue (line, lines) = (lines[:128], lines[128:]) record = {} if line[0:3] in ('999', '995'): if find_total: raise except_osv(_('Error'), _('Too much total record found!')) find_total = True if lines: raise except_osv(_('Error'), _('Record found after total record!')) amount = float(line[39:49]) + (float(line[49:51]) / 100) cost = float(line[69:76]) + (float(line[76:78]) / 100) if line[2] == '5': amount *= -1 cost *= -1 if round(amount - total_amount, 2) >= 0.01 \ or round(cost - total_cost, 2) >= 0.01: raise except_osv(_('Error'), _('Total record different from the computed!')) if int(line[51:63]) != len(records): raise except_osv(_('Error'), _('Number record different from the computed!')) else: record = { 'reference': line[12:39], 'amount': float(line[39:47]) + (float(line[47:49]) / 100), 'date': time.strftime('%Y-%m-%d', time.strptime(line[65:71], '%y%m%d')), 'cost': float(line[96:98]) + (float(line[98:100]) / 100), } if record['reference'] != mod10r(record['reference'][:-1]): raise except_osv(_('Error'), _('Recursive mod10 is invalid for reference: %s') % record['reference']) if line[2] == '5': record['amount'] *= -1 record['cost'] *= -1 total_amount += record['amount'] total_cost += record['cost'] records.append(record) return records #deprecated def _create_voucher_from_record(self, cursor, uid, record, statement, line_ids, context=None): """Create a voucher with voucher line""" context.update({'move_line_ids': line_ids}) voucher_obj = self.pool.get('account.voucher') move_line_obj = self.pool.get('account.move.line') voucher_line_obj = self.pool.get('account.voucher.line') line = move_line_obj.browse(cursor, uid, line_ids[0]) partner_id = line.partner_id and line.partner_id.id or False if not partner_id: return False move_id = line.move_id.id result = voucher_obj.onchange_partner_id(cursor, uid, [], partner_id, statement.journal_id.id, abs(record['amount']), statement.currency.id, 'receipt', statement.date, context=context) voucher_res = {'type': 'receipt', 'name': record['reference'], 'partner_id': partner_id, 'journal_id': statement.journal_id.id, 'account_id': result.get('account_id', statement.journal_id.default_credit_account_id.id), 'company_id': statement.company_id.id, 'currency_id': statement.currency.id, 'date': record['date'] or time.strftime('%Y-%m-%d'), 'amount': abs(record['amount']), 'period_id': statement.period_id.id } voucher_id = voucher_obj.create(cursor, uid, voucher_res, context=context) voucher_line_dict = False if result['value']['line_cr_ids']: for line_dict in result['value']['line_cr_ids']: move_line = move_line_obj.browse(cursor, uid, line_dict['move_line_id'], context) if move_id == move_line.move_id.id: voucher_line_dict = line_dict if voucher_line_dict: voucher_line_dict.update({'voucher_id': voucher_id}) voucher_line_obj.create(cursor, uid, voucher_line_dict, context=context) return voucher_id def _get_account(self, cursor, uid, line_ids, record, context=None): """Get account from move line or from property""" property_obj = self.pool.get('ir.property') move_line_obj = self.pool.get('account.move.line') account_id = False if line_ids: for line in move_line_obj.browse(cursor, uid, line_ids, context=context): return line.account_id.id if not account_id and not line_ids: name = "property_account_receivable" if record['amount'] < 0: name = "property_account_payable" account_id = property_obj.get(cursor, uid, name, 'res.partner', context=context).id if not account_id: raise except_osv(_('Error'), _('The properties account payable account receivable are not set')) return account_id def _prepare_line_vals(self, cursor, uid, statement, record, voucher_enabled, context=None): # Remove the 11 first char because it can be adherent number # TODO check if 11 is the right number move_line_obj = self.pool.get('account.move.line') reference = record['reference'] values = {'name': '/', 'date': record['date'], 'amount': record['amount'], 'ref': reference, 'type': (record['amount'] >= 0 and 'customer') or 'supplier', 'statement_id': statement.id, } line_ids = move_line_obj.search(cursor, uid, [('ref', '=', reference), ('reconcile_id', '=', False), ('account_id.type', 'in', ['receivable', 'payable']), ('journal_id.type', '=', 'sale')], order='date desc', context=context) #for multiple payments if not line_ids: line_ids = move_line_obj.search(cursor, uid, [('transaction_ref', '=', reference), ('reconcile_id', '=', False), ('account_id.type', 'in', ['receivable', 'payable']), ('journal_id.type', '=', 'sale')], order='date desc', context=context) if not line_ids: line_ids = self._reconstruct_invoice_ref(cursor, uid, reference, None) if line_ids and voucher_enabled: values['voucher_id'] = self._create_voucher_from_record(cursor, uid, record, statement, line_ids, context=context) account_id = self._get_account(cursor, uid, line_ids, record, context=context) values['account_id'] = account_id if line_ids: line = move_line_obj.browse(cursor, uid, line_ids[0]) partner_id = line.partner_id.id values['name'] = line.invoice and (_('Inv. no ') + line.invoice.number) or values['name'] values['partner_id'] = partner_id return values def import_v11(self, cursor, uid, ids, data, context=None): """Import v11 file and transfor it into statement lines""" if context is None: context = {} module_obj = self.pool['ir.module.module'] voucher_enabled = module_obj.search(cursor, uid, [('name', '=', 'account_voucher'), ('state', '=', 'installed')]) # if module installed we check ir.config_parameter to force disable of voucher if voucher_enabled: para = self.pool['ir.config_parameter'].get_param(cursor, uid, 'l10n_ch_payment_slip_voucher_disable', default = '0') if para.lower() not in ['0', 'false']: # if voucher is disabled voucher_enabled = False statement_line_obj = self.pool.get('account.bank.statement.line') attachment_obj = self.pool.get('ir.attachment') statement_obj = self.pool.get('account.bank.statement') file = data['form']['file'] if not file: raise except_osv(_('UserError'), _('Please select a file first!')) statement_id = data['id'] lines = base64.decodestring(file).split("\n") records = self._parse_lines(cursor, uid, lines, context=context) statement = statement_obj.browse(cursor, uid, statement_id, context=context) for record in records: values = self._prepare_line_vals(cursor, uid, statement, record, voucher_enabled, context=context) statement_line_obj.create(cursor, uid, values, context=context) attachment_obj.create(cursor, uid, {'name': 'BVR %s' % time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime()), 'datas': file, 'datas_fname': 'BVR %s.txt' % time.strftime("%Y-%m-%d_%H:%M:%S", time.gmtime()), 'res_model': 'account.bank.statement', 'res_id': statement_id, }, context=context) return {} def import_bvr(self, cursor, uid, ids, context=None): data = {} if context is None: context = {} active_ids = context.get('active_ids', []) active_id = context.get('active_id', False) data['form'] = {} data['ids'] = active_ids data['id'] = active_id data['form']['file'] = '' res = self.read(cursor, uid, ids[0], ['file']) if res: data['form']['file'] = res['file'] self.import_v11(cursor, uid, ids, data, context=context) return {} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
odoousers2014/LibrERP
l10n_ch_payment_slip/wizard/bvr_import.py
Python
agpl-3.0
13,953
from facts import FactRules from sympy.core.compatibility import cmp class CycleDetected(Exception): """(internal) used to detect cycles when evaluating assumptions through prerequisites """ pass class AssumeMeths(object): """ Define default assumption methods. AssumeMeths should be used to derive Basic class only. All symbolic objects have assumption attributes that can be accessed via .is_<assumption name> attribute. Assumptions determine certain properties of symbolic objects. Assumptions can have 3 possible values: True, False, None. None is returned when it is impossible to say something about the property. For example, a Symbol is not know beforehand to be positive. By default, all symbolic values are in the largest set in the given context without specifying the property. For example, a symbol that has a property being integer, is also real, complex, etc. Here follows a list of possible assumption names: - commutative - object commutes with any other object with respect to multiplication operation. - real - object can have only values from the set of real numbers - integer - object can have only values from the set of integers - bounded - object absolute value is bounded - positive - object can have only positive values - negative - object can have only negative values - nonpositive - object can have only nonpositive values - nonnegative - object can have only nonnegative values - comparable - object.evalf() returns Number object. - irrational - object value cannot be represented exactly by Rational - unbounded - object value is arbitrarily large - infinitesimal - object value is infinitesimal Example rules: positive=T -> nonpositive=F, real=T real=T & positive=F -> nonpositive=T unbounded=F|T -> bounded=not unbounded XXX ok? irrational=T -> real=T Implementation note: assumption values are stored in ._assumption dictionary or are returned by getter methods (with property decorators) or are attributes of objects/classes. Examples: - True, when we are sure about a property. For example, when we are working only with real numbers: >>> from sympy import Symbol >>> Symbol('x', real = True) x - False - None (if you don't know if the property is True or false) """ __slots__ = ['_assumptions', # assumptions '_a_inprogress', # already-seen requests (when deducing # through prerequisites -- see CycleDetected) ] # This are the rules under which our assumptions function # # References # ---------- # # negative, -- http://en.wikipedia.org/wiki/Negative_number # nonnegative # # even, odd -- http://en.wikipedia.org/wiki/Parity_(mathematics) # imaginary -- http://en.wikipedia.org/wiki/Imaginary_number # composite -- http://en.wikipedia.org/wiki/Composite_number # finite -- http://en.wikipedia.org/wiki/Finite # infinitesimal -- http://en.wikipedia.org/wiki/Infinitesimal # irrational -- http://en.wikipedia.org/wiki/Irrational_number # ... _assume_rules = FactRules([ 'integer -> rational', 'rational -> real', 'real -> complex', 'imaginary -> complex', 'complex -> commutative', 'odd == integer & !even', 'even == integer & !odd', 'real == negative | zero | positive', 'positive -> real & !negative & !zero', 'negative -> real & !positive & !zero', 'nonpositive == real & !positive', 'nonnegative == real & !negative', 'zero -> infinitesimal & even', 'prime -> integer & positive', 'composite == integer & positive & !prime', 'irrational == real & !rational', 'imaginary -> !real', '!bounded == unbounded', 'noninteger == real & !integer', '!zero == nonzero', # XXX do we need this ? 'finite -> bounded', # XXX do we need this? 'finite -> !zero', # XXX wrong? 'infinitesimal -> !finite', # XXX is this ok? ]) _assume_defined = _assume_rules.defined_facts.copy() _assume_defined.add('comparable') _assume_defined = frozenset(_assume_defined) ################################### # positive/negative from .evalf() # ################################### # properties that indicate ordering on real axis _real_ordering = set(['negative', 'nonnegative', 'positive', 'nonpositive']) # what can be said from cmp(x.evalf(),0) # NOTE: if x.evalf() is zero we can say nothing _real_cmp0_table= { 'positive': {1: True, -1: False, 0: None}, 'negative': {1: False, -1: True, 0: None}, } # because we can say nothing if x.evalf() is zero, nonpositive is the same # as negative _real_cmp0_table['nonpositive'] = _real_cmp0_table['negative'] _real_cmp0_table['nonnegative'] = _real_cmp0_table['positive'] def __getstate__(self, cls=None): if cls is None: # This is the case for the instance that gets pickled cls = self.__class__ d = {} # Get all data that should be stored from super classes for c in cls.__bases__: if hasattr(c, "__getstate__"): d.update(c.__getstate__(self, c)) # Get all information that should be stored from cls and return the dic for name in cls.__slots__: if hasattr(self, name): d[name] = getattr(self, name) return d def __setstate__(self, d): # All values that were pickled are now assigned to a fresh instance for name, value in d.iteritems(): try: setattr(self, name, value) except: pass def _what_known_about(self, k): """tries hard to give an answer to: what is known about fact `k` NOTE: You should not use this directly -- see make__get_assumption instead This function is called when a request is made to see what a fact value is. If we are here, it means that the asked-for fact is not known, and we should try to find a way to find its value. For this we use several techniques: 1. _eval_is_<fact> ------------------ first fact-evaluation function is tried, for example _eval_is_integer 2. relations ------------ if the first step did not succeeded (no such function, or its return is None) then we try related facts. For example means rational --> integer another example is joined rule: integer & !odd --> even so in the latter case if we are looking at what 'even' value is, 'integer' and 'odd' facts will be asked. 3. evalf() for comparable ------------------------- as a last resort for comparable objects we get their numerical value -- this helps to determine facts like 'positive' and 'negative' In all cases when we settle on some fact value, it is given to _learn_new_facts to deduce all its implications, and also the result is cached in ._assumptions for later quick access. """ # 'defined' assumption if k not in self._assume_defined: raise AttributeError('undefined assumption %r' % (k)) assumptions = self._assumptions seen = self._a_inprogress #print '%s=?\t%s %s' % (name, self,seen) if k in seen: raise CycleDetected seen.append(k) try: # First try the assumption evaluation function if it exists if hasattr(self, '_eval_is_'+k): #print 'FWDREQ: %s\t%s' % (self, k) try: a = getattr(self,'_eval_is_'+k)() # no luck - e.g. is_integer -> ... -> is_integer except CycleDetected: #print 'CYC' pass else: if a is not None: self._learn_new_facts( ((k,a),) ) return a # Try assumption's prerequisites for pk in self._assume_rules.prereq.get(k,()): #print 'pk: %s' % pk if hasattr(self, '_eval_is_'+pk): # cycle if pk in seen: continue #print 'PREREQ: %s\t%s <- %s' % (self, k, pk) a = getattr(self,'is_'+pk) if a is not None: self._learn_new_facts( ((pk,a),) ) # it is possible that we either know or don't know k at # this point try: return self._assumptions[k] except KeyError: pass finally: seen.pop() # For positive/negative try to ask evalf if k in self._real_ordering: if self.is_comparable: v = self.evalf() #FIXME-py3k: this fails for complex numbers, when we define cmp #FIXME-py3k: as (a>b) - (a<b) c = cmp(v, 0) a = self._real_cmp0_table[k][c] if a is not None: self._learn_new_facts( ((k,a),) ) return a # No result -- unknown # cache it (NB ._learn_new_facts(k, None) to learn other properties, # and because assumptions may not be detached) self._learn_new_facts( ((k,None),) ) return None def _learn_new_facts(self, facts): """Learn new facts about self. ******************************************************************* * internal routine designed to be used only from assumptions core * ******************************************************************* Given new facts and already present knowledge (._assumptions) we ask inference engine to derive full set of new facts which follow from this combination. The result is stored back into ._assumptions """ # no new facts if not facts: return default_assumptions = type(self).default_assumptions base = self._assumptions # ._assumptions were shared with the class if base is default_assumptions: base = base.copy() self._assumptions = base self._assume_rules.deduce_all_facts(facts, base) else: # NOTE it modifies base inplace self._assume_rules.deduce_all_facts(facts, base) def make__get_assumption(classname, name): """Cooks function which will get named assumption e.g. class C: is_xxx = make__get_assumption('C', 'xxx') is_yyy = property( make__get_assumption('C', 'yyy')) then c = C() c.is_xxx() # note braces -- it's a function call c.is_yyy # no braces -- it's a property """ def getit(self): try: return self._assumptions[name] except KeyError: return self._what_known_about(name) getit.func_name = '%s__is_%s' % (classname, name) #print '\n\n\n%s\n' % getit #from dis import dis #dis(getit) return getit
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/sympy/core/assumptions.py
Python
agpl-3.0
12,183
# -*- coding: utf-8 -*- ############################################################################## # # Odoo Addon, Open Source Management Solution # Copyright (C) 2014-now Equitania Software GmbH(<http://www.equitania.de>). # # 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/>. # ##############################################################################
equitania/myodoo-addons-v10
eq_website_quote/__init__.py
Python
agpl-3.0
1,002
import datetime from django import template from registration.models import RegistrationProfile register = template.Library() @register.simple_tag def get_volunteer_number(): volunteers = RegistrationProfile.objects.all().count() return volunteers
koolfreak/volunteer_planner
scheduler/templatetags/number_registrations.py
Python
agpl-3.0
260
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import time from selenium.common.exceptions import NoSuchElementException, InvalidSelectorException from selenium.common.exceptions import TimeoutException POLL_FREQUENCY = 0.5 # How long to sleep in between calls to the method IGNORED_EXCEPTIONS = (NoSuchElementException,) # exceptions ignored during calls to the method class WebDriverWait(object): def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None): """Constructor, takes a WebDriver instance and timeout in seconds. :Args: - driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote) - timeout - Number of seconds before timing out - poll_frequency - sleep interval between calls By default, it is 0.5 second. - ignored_exceptions - iterable structure of exception classes ignored during calls. By default, it contains NoSuchElementException only. Example:: from selenium.webdriver.support.wait import WebDriverWait \n element = WebDriverWait(driver, 10).until(lambda x: x.find_element(By.ID, "someId")) \n is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\\ \n until_not(lambda x: x.find_element(By.ID, "someId").is_displayed()) """ self._driver = driver self._timeout = float(timeout) self._poll = poll_frequency # avoid the divide by zero if self._poll == 0: self._poll = POLL_FREQUENCY exceptions = list(IGNORED_EXCEPTIONS) if ignored_exceptions: try: exceptions.extend(iter(ignored_exceptions)) except TypeError: # ignored_exceptions is not iterable exceptions.append(ignored_exceptions) self._ignored_exceptions = tuple(exceptions) def __repr__(self): return '<{0.__module__}.{0.__name__} (session="{1}")>'.format( type(self), self._driver.session_id) def until(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value does not evaluate to ``False``. :param method: callable(WebDriver) :param message: optional message for :exc:`TimeoutException` :returns: the result of the last call to `method` :raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs """ screen = None stacktrace = None end_time = time.time() + self._timeout while True: try: value = method(self._driver) if value: return value except InvalidSelectorException as e: raise e except self._ignored_exceptions as exc: screen = getattr(exc, 'screen', None) stacktrace = getattr(exc, 'stacktrace', None) time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(message, screen, stacktrace) def until_not(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value evaluates to ``False``. :param method: callable(WebDriver) :param message: optional message for :exc:`TimeoutException` :returns: the result of the last call to `method`, or ``True`` if `method` has raised one of the ignored exceptions :raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs """ end_time = time.time() + self._timeout while True: try: value = method(self._driver) if not value: return value except InvalidSelectorException as e: raise e except self._ignored_exceptions: return True time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(message)
titusfortner/selenium
py/selenium/webdriver/support/wait.py
Python
apache-2.0
4,895
# -*- coding: utf-8 -*- ############################################################################### # # GetClicksForLink # Returns the number of clicks on a single Bitly link. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo 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 temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class GetClicksForLink(Choreography): def __init__(self, temboo_session): """ Create a new instance of the GetClicksForLink Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(GetClicksForLink, self).__init__(temboo_session, '/Library/Bitly/LinkMetrics/GetClicksForLink') def new_input_set(self): return GetClicksForLinkInputSet() def _make_result_set(self, result, path): return GetClicksForLinkResultSet(result, path) def _make_execution(self, session, exec_id, path): return GetClicksForLinkChoreographyExecution(session, exec_id, path) class GetClicksForLinkInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the GetClicksForLink Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccessToken(self, value): """ Set the value of the AccessToken input for this Choreo. ((required, string) The OAuth access token provided by Bitly.) """ super(GetClicksForLinkInputSet, self)._set_input('AccessToken', value) def set_Limit(self, value): """ Set the value of the Limit input for this Choreo. ((optional, integer) The result limit. Defaults to 100. Range is 1 to 1000.) """ super(GetClicksForLinkInputSet, self)._set_input('Limit', value) def set_Link(self, value): """ Set the value of the Link input for this Choreo. ((required, string) A Bitly link.) """ super(GetClicksForLinkInputSet, self)._set_input('Link', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that you want the response to be in. Accepted values are "json" or "xml". Defaults to "json".) """ super(GetClicksForLinkInputSet, self)._set_input('ResponseFormat', value) def set_Rollup(self, value): """ Set the value of the Rollup input for this Choreo. ((optional, boolean) Accepted values are true or false. When set to true, this returns data for multiple units rolled up to a single result instead of a separate value for each period of time.) """ super(GetClicksForLinkInputSet, self)._set_input('Rollup', value) def set_Timestamp(self, value): """ Set the value of the Timestamp input for this Choreo. ((optional, date) An epoch timestamp, indicating the most recent time for which to pull metrics.) """ super(GetClicksForLinkInputSet, self)._set_input('Timestamp', value) def set_Timezone(self, value): """ Set the value of the Timezone input for this Choreo. ((optional, string) An integer hour offset from UTC (-12..12), or a timezone string. Defaults to "America/New_York".) """ super(GetClicksForLinkInputSet, self)._set_input('Timezone', value) def set_UnitName(self, value): """ Set the value of the UnitName input for this Choreo. ((optional, string) The unit of time that corresponds to query you want to run. Accepted values are: minute, hour, day, week, month, and day. Defaults to "day".) """ super(GetClicksForLinkInputSet, self)._set_input('UnitName', value) def set_UnitValue(self, value): """ Set the value of the UnitValue input for this Choreo. ((optional, integer) An integer representing the amount of time to query for. Corresponds to the UnitName input. Defaults to -1 indicating to return all units of time.) """ super(GetClicksForLinkInputSet, self)._set_input('UnitValue', value) class GetClicksForLinkResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the GetClicksForLink Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Bitly.) """ return self._output.get('Response', None) class GetClicksForLinkChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return GetClicksForLinkResultSet(response, path)
jordanemedlock/psychtruths
temboo/core/Library/Bitly/LinkMetrics/GetClicksForLink.py
Python
apache-2.0
5,517
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. def merge(dbag, rules): for rule in rules["rules"]: source_ip = rule["source_ip_address"] destination_ip = rule["destination_ip_address"] revoke = rule["revoke"] newrule = dict() newrule["public_ip"] = source_ip newrule["internal_ip"] = destination_ip if rules["type"] == "staticnatrules": newrule["type"] = "staticnat" elif rules["type"] == "forwardrules": newrule["type"] = "forward" newrule["public_ports"] = rule["source_port_range"] newrule["internal_ports"] = rule["destination_port_range"] newrule["protocol"] = rule["protocol"] if not revoke: if rules["type"] == "staticnatrules": dbag[source_ip] = [newrule] elif rules["type"] == "forwardrules": index = -1 if source_ip in dbag.keys(): for forward in dbag[source_ip]: if ruleCompare(forward, newrule): index = dbag[source_ip].index(forward) if not index == -1: dbag[source_ip][index] = newrule else: dbag[source_ip].append(newrule) else: dbag[source_ip] = [newrule] else: if rules["type"] == "staticnatrules": if source_ip in dbag.keys(): del dbag[source_ip] elif rules["type"] == "forwardrules": if source_ip in dbag.keys(): index = -1 for forward in dbag[source_ip]: if ruleCompare(forward, newrule): index = dbag[source_ip].index(forward) print "removing index %s" % str(index) if not index == -1: del dbag[source_ip][index] return dbag # Compare function checks only the public side, those must be equal the internal details could change def ruleCompare(ruleA, ruleB): if not ruleA["type"] == ruleB["type"]: return False if ruleA["type"] == "staticnat": return ruleA["public_ip"] == ruleB["public_ip"] elif ruleA["type"] == "forward": return ruleA["public_ip"] == ruleB["public_ip"] and ruleA["public_ports"] == ruleB["public_ports"] \ and ruleA["protocol"] == ruleB["protocol"]
DaanHoogland/cloudstack
systemvm/debian/opt/cloud/bin/cs_forwardingrules.py
Python
apache-2.0
3,239
"""Allow users to set and activate scenes.""" from __future__ import annotations import logging from typing import Any, NamedTuple import voluptuous as vol from homeassistant import config as conf_util from homeassistant.components.light import ATTR_TRANSITION from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN, STATES, Scene from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_STATE, CONF_ENTITIES, CONF_ICON, CONF_ID, CONF_NAME, CONF_PLATFORM, SERVICE_RELOAD, STATE_OFF, STATE_ON, ) from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssistant, State, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import ( config_per_platform, config_validation as cv, entity_platform, ) from homeassistant.helpers.state import async_reproduce_state from homeassistant.loader import async_get_integration def _convert_states(states): """Convert state definitions to State objects.""" result = {} for entity_id, info in states.items(): entity_id = cv.entity_id(entity_id) if isinstance(info, dict): entity_attrs = info.copy() state = entity_attrs.pop(ATTR_STATE, None) attributes = entity_attrs else: state = info attributes = {} # YAML translates 'on' to a boolean # http://yaml.org/type/bool.html if isinstance(state, bool): state = STATE_ON if state else STATE_OFF elif not isinstance(state, str): raise vol.Invalid(f"State for {entity_id} should be a string") result[entity_id] = State(entity_id, state, attributes) return result def _ensure_no_intersection(value): """Validate that entities and snapshot_entities do not overlap.""" if ( CONF_SNAPSHOT not in value or CONF_ENTITIES not in value or all( entity_id not in value[CONF_SNAPSHOT] for entity_id in value[CONF_ENTITIES] ) ): return value raise vol.Invalid("entities and snapshot_entities must not overlap") CONF_SCENE_ID = "scene_id" CONF_SNAPSHOT = "snapshot_entities" DATA_PLATFORM = "homeassistant_scene" EVENT_SCENE_RELOADED = "scene_reloaded" STATES_SCHEMA = vol.All(dict, _convert_states) PLATFORM_SCHEMA = vol.Schema( { vol.Required(CONF_PLATFORM): HA_DOMAIN, vol.Required(STATES): vol.All( cv.ensure_list, [ vol.Schema( { vol.Optional(CONF_ID): cv.string, vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_ICON): cv.icon, vol.Required(CONF_ENTITIES): STATES_SCHEMA, } ) ], ), }, extra=vol.ALLOW_EXTRA, ) CREATE_SCENE_SCHEMA = vol.All( cv.has_at_least_one_key(CONF_ENTITIES, CONF_SNAPSHOT), _ensure_no_intersection, vol.Schema( { vol.Required(CONF_SCENE_ID): cv.slug, vol.Optional(CONF_ENTITIES, default={}): STATES_SCHEMA, vol.Optional(CONF_SNAPSHOT, default=[]): cv.entity_ids, } ), ) SERVICE_APPLY = "apply" SERVICE_CREATE = "create" _LOGGER = logging.getLogger(__name__) class SceneConfig(NamedTuple): """Object for storing scene config.""" id: str name: str icon: str states: dict @callback def scenes_with_entity(hass: HomeAssistant, entity_id: str) -> list[str]: """Return all scenes that reference the entity.""" if DATA_PLATFORM not in hass.data: return [] platform = hass.data[DATA_PLATFORM] return [ scene_entity.entity_id for scene_entity in platform.entities.values() if entity_id in scene_entity.scene_config.states ] @callback def entities_in_scene(hass: HomeAssistant, entity_id: str) -> list[str]: """Return all entities in a scene.""" if DATA_PLATFORM not in hass.data: return [] platform = hass.data[DATA_PLATFORM] if (entity := platform.entities.get(entity_id)) is None: return [] return list(entity.scene_config.states) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up Home Assistant scene entries.""" _process_scenes_config(hass, async_add_entities, config) # This platform can be loaded multiple times. Only first time register the service. if hass.services.has_service(SCENE_DOMAIN, SERVICE_RELOAD): return # Store platform for later. platform = hass.data[DATA_PLATFORM] = entity_platform.async_get_current_platform() async def reload_config(call): """Reload the scene config.""" try: conf = await conf_util.async_hass_config_yaml(hass) except HomeAssistantError as err: _LOGGER.error(err) return integration = await async_get_integration(hass, SCENE_DOMAIN) conf = await conf_util.async_process_component_config(hass, conf, integration) if not (conf and platform): return await platform.async_reset() # Extract only the config for the Home Assistant platform, ignore the rest. for p_type, p_config in config_per_platform(conf, SCENE_DOMAIN): if p_type != HA_DOMAIN: continue _process_scenes_config(hass, async_add_entities, p_config) hass.bus.async_fire(EVENT_SCENE_RELOADED, context=call.context) hass.helpers.service.async_register_admin_service( SCENE_DOMAIN, SERVICE_RELOAD, reload_config ) async def apply_service(call): """Apply a scene.""" reproduce_options = {} if ATTR_TRANSITION in call.data: reproduce_options[ATTR_TRANSITION] = call.data.get(ATTR_TRANSITION) await async_reproduce_state( hass, call.data[CONF_ENTITIES].values(), context=call.context, reproduce_options=reproduce_options, ) hass.services.async_register( SCENE_DOMAIN, SERVICE_APPLY, apply_service, vol.Schema( { vol.Optional(ATTR_TRANSITION): vol.All( vol.Coerce(float), vol.Clamp(min=0, max=6553) ), vol.Required(CONF_ENTITIES): STATES_SCHEMA, } ), ) async def create_service(call): """Create a scene.""" snapshot = call.data[CONF_SNAPSHOT] entities = call.data[CONF_ENTITIES] for entity_id in snapshot: if (state := hass.states.get(entity_id)) is None: _LOGGER.warning( "Entity %s does not exist and therefore cannot be snapshotted", entity_id, ) continue entities[entity_id] = State(entity_id, state.state, state.attributes) if not entities: _LOGGER.warning("Empty scenes are not allowed") return scene_config = SceneConfig(None, call.data[CONF_SCENE_ID], None, entities) entity_id = f"{SCENE_DOMAIN}.{scene_config.name}" if (old := platform.entities.get(entity_id)) is not None: if not old.from_service: _LOGGER.warning("The scene %s already exists", entity_id) return await platform.async_remove_entity(entity_id) async_add_entities([HomeAssistantScene(hass, scene_config, from_service=True)]) hass.services.async_register( SCENE_DOMAIN, SERVICE_CREATE, create_service, CREATE_SCENE_SCHEMA ) def _process_scenes_config(hass, async_add_entities, config): """Process multiple scenes and add them.""" # Check empty list if not (scene_config := config[STATES]): return async_add_entities( HomeAssistantScene( hass, SceneConfig( scene.get(CONF_ID), scene[CONF_NAME], scene.get(CONF_ICON), scene[CONF_ENTITIES], ), ) for scene in scene_config ) class HomeAssistantScene(Scene): """A scene is a group of entities and the states we want them to be.""" def __init__(self, hass, scene_config, from_service=False): """Initialize the scene.""" self.hass = hass self.scene_config = scene_config self.from_service = from_service @property def name(self): """Return the name of the scene.""" return self.scene_config.name @property def icon(self): """Return the icon of the scene.""" return self.scene_config.icon @property def unique_id(self): """Return unique ID.""" return self.scene_config.id @property def extra_state_attributes(self): """Return the scene state attributes.""" attributes = {ATTR_ENTITY_ID: list(self.scene_config.states)} if (unique_id := self.unique_id) is not None: attributes[CONF_ID] = unique_id return attributes async def async_activate(self, **kwargs: Any) -> None: """Activate scene. Try to get entities into requested state.""" await async_reproduce_state( self.hass, self.scene_config.states.values(), context=self._context, reproduce_options=kwargs, )
lukas-hetzenecker/home-assistant
homeassistant/components/homeassistant/scene.py
Python
apache-2.0
9,460
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Code for backpropagation using the tape utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.python import pywrap_tensorflow from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients from tensorflow.python.util import compat VSpace = collections.namedtuple("VSpace", [ "aggregate_fn", "num_elements_fn", "zeros_fn", "ones_fn", "zeros_like_fn", "ones_like_fn", "graph_shape_fn" ]) def imperative_grad(tape, target, sources, output_gradients=None, sources_raw=None, unconnected_gradients=UnconnectedGradients.NONE): """Computes gradients from the imperatively defined tape on top of the stack. Works by filtering the tape, computing how many downstream usages are of each tensor and entry, and repeatedly applying backward functions until we have gradients for all sources. Args: tape: the gradient tape which stores the trace. target: either a Tensor or list of Tensors to be differentiated. sources: list of Tensors for which we want gradients output_gradients: if not None, a list of gradient provided for each Target, or None if we are to use the target's computed downstream gradient. sources_raw: if not None, a list of the source python objects from which the sources were generated. Should have the same length as sources. Only needs to be populated if unconnected_gradients is 'zero'. unconnected_gradients: determines the value returned if the target and sources are unconnected. When 'none' the value returned is None wheras when 'zero' a zero tensor in the same shape as the sources is returned. Returns: the gradient wrt each of the sources. Raises: ValueError: if the arguments are invalid. RuntimeError: if something goes wrong. """ try: unconnected_gradients = UnconnectedGradients(unconnected_gradients) except ValueError: raise ValueError( "Unknown value for unconnected_gradients: %r" % unconnected_gradients) return pywrap_tensorflow.TFE_Py_TapeGradient( tape._tape, # pylint: disable=protected-access target, sources, output_gradients, sources_raw, compat.as_str(unconnected_gradients.value))
ppwwyyxx/tensorflow
tensorflow/python/eager/imperative_grad.py
Python
apache-2.0
3,071
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2013 Contributor # # 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. """ Building is a subclass of Location """ from sqlalchemy import Column, Integer, ForeignKey from aquilon.aqdb.model import Location class Building(Location): """ Building is a subtype of location """ __tablename__ = 'building' __mapper_args__ = {'polymorphic_identity' : 'building'} id = Column(Integer, ForeignKey('location.id', name='building_loc_fk', ondelete='CASCADE'), primary_key=True) building = Building.__table__ building.primary_key.name='building_pk' table = building def populate(sess, *args, **kw): if len(sess.query(Building).all()) > 0: return from aquilon.aqdb.model import City log = kw['log'] assert log, "no log in kwargs for Building.populate()" dsdb = kw['dsdb'] assert dsdb, "No dsdb in kwargs for Building.populate()" city = {} for c in sess.query(City).all(): city[c.name] = c for row in dsdb.dump('building'): try: p = city[str(row[2])] except KeyError, e: log.error(str(e)) continue a = Building(name = str(row[0]), fullname = str(row[1]), parent = city[str(row[2])]) sess.add(a) sess.commit() log.debug('created %s buildings'%(len(sess.query(Building).all())))
jrha/aquilon
upgrade/1.4.5/aquilon/aqdb/model/building.py
Python
apache-2.0
2,077
# -*- coding: utf-8 -*- import os from future.moves.urllib.parse import quote import uuid import ssl from pymongo import MongoClient import requests from django.apps import apps from addons.wiki import settings as wiki_settings from addons.wiki.exceptions import InvalidVersionError from osf.utils.permissions import ADMIN, READ, WRITE # MongoDB forbids field names that begin with "$" or contain ".". These # utilities map to and from Mongo field names. mongo_map = { '.': '__!dot!__', '$': '__!dollar!__', } def to_mongo(item): for key, value in mongo_map.items(): item = item.replace(key, value) return item def to_mongo_key(item): return to_mongo(item).strip().lower() def generate_private_uuid(node, wname): """ Generate private uuid for internal use in sharejs namespacing. Note that this will NEVER be passed to to the client or sharejs. """ private_uuid = str(uuid.uuid1()) wiki_key = to_mongo_key(wname) node.wiki_private_uuids[wiki_key] = private_uuid node.save() return private_uuid def get_sharejs_uuid(node, wname): """ Format private uuid into the form used in mongo and sharejs. This includes node's primary ID to prevent fork namespace collision """ wiki_key = to_mongo_key(wname) private_uuid = node.wiki_private_uuids.get(wiki_key) return str(uuid.uuid5( uuid.UUID(private_uuid), str(node._id) )) if private_uuid else None def delete_share_doc(node, wname): """Deletes share document and removes namespace from model.""" db = share_db() sharejs_uuid = get_sharejs_uuid(node, wname) db['docs'].remove({'_id': sharejs_uuid}) db['docs_ops'].remove({'name': sharejs_uuid}) wiki_key = to_mongo_key(wname) del node.wiki_private_uuids[wiki_key] node.save() def migrate_uuid(node, wname): """Migrates uuid to new namespace.""" db = share_db() old_sharejs_uuid = get_sharejs_uuid(node, wname) broadcast_to_sharejs('lock', old_sharejs_uuid) generate_private_uuid(node, wname) new_sharejs_uuid = get_sharejs_uuid(node, wname) doc_item = db['docs'].find_one({'_id': old_sharejs_uuid}) if doc_item: doc_item['_id'] = new_sharejs_uuid db['docs'].insert(doc_item) db['docs'].remove({'_id': old_sharejs_uuid}) ops_items = [item for item in db['docs_ops'].find({'name': old_sharejs_uuid})] if ops_items: for item in ops_items: item['_id'] = item['_id'].replace(old_sharejs_uuid, new_sharejs_uuid) item['name'] = new_sharejs_uuid db['docs_ops'].insert(ops_items) db['docs_ops'].remove({'name': old_sharejs_uuid}) write_contributors = [ user._id for user in node.contributors if node.has_permission(user, WRITE) ] broadcast_to_sharejs('unlock', old_sharejs_uuid, data=write_contributors) def share_db(): """Generate db client for sharejs db""" client = MongoClient(wiki_settings.SHAREJS_DB_URL, ssl_cert_reqs=ssl.CERT_NONE) return client[wiki_settings.SHAREJS_DB_NAME] def get_sharejs_content(node, wname): db = share_db() sharejs_uuid = get_sharejs_uuid(node, wname) doc_item = db['docs'].find_one({'_id': sharejs_uuid}) return doc_item['_data'] if doc_item else '' def broadcast_to_sharejs(action, sharejs_uuid, node=None, wiki_name='home', data=None): """ Broadcast an action to all documents connected to a wiki. Actions include 'lock', 'unlock', 'redirect', and 'delete' 'redirect' and 'delete' both require a node to be specified 'unlock' requires data to be a list of contributors with write permission """ url = 'http://{host}:{port}/{action}/{id}/'.format( host=wiki_settings.SHAREJS_HOST, port=wiki_settings.SHAREJS_PORT, action=action, id=sharejs_uuid ) if action == 'redirect' or action == 'delete': redirect_url = quote( node.web_url_for('project_wiki_view', wname=wiki_name, _guid=True), safe='', ) url = os.path.join(url, redirect_url) try: requests.post(url, json=data) except requests.ConnectionError: pass # Assume sharejs is not online def format_wiki_version(version, num_versions, allow_preview): """ :param str version: 'preview', 'current', 'previous', '1', '2', ... :param int num_versions: :param allow_preview: True if view, False if compare """ if not version: return if version.isdigit(): version = int(version) if version > num_versions or version < 1: raise InvalidVersionError elif version == num_versions: return 'current' elif version == num_versions - 1: return 'previous' elif version != 'current' and version != 'previous': if allow_preview and version == 'preview': return version raise InvalidVersionError elif version == 'previous' and num_versions == 0: raise InvalidVersionError return version def serialize_wiki_settings(user, nodes): """ Format wiki data for project settings page :param user: modular odm User object :param nodes: list of parent project nodes :return: treebeard-formatted data """ WikiPage = apps.get_model('addons_wiki.WikiPage') items = [] for node in nodes: assert node, '{} is not a valid Node.'.format(node._id) can_read = node.has_permission(user, READ) is_admin = node.has_permission(user, ADMIN) include_wiki_settings = WikiPage.objects.include_wiki_settings(node) if not include_wiki_settings: continue children = node.get_nodes(**{'is_deleted': False, 'is_node_link': False}) children_tree = [] wiki = node.get_addon('wiki') if wiki: children_tree.append({ 'select': { 'title': 'permission', 'permission': 'public' if wiki.is_publicly_editable else 'private' }, }) children_tree.extend(serialize_wiki_settings(user, children)) item = { 'node': { 'id': node._id, 'url': node.url if can_read else '', 'title': node.title if can_read else 'Private Project', 'is_public': node.is_public }, 'children': children_tree, 'kind': 'folder' if not node.parent_node or not node.parent_node.has_permission(user, READ) else 'node', 'nodeType': node.project_or_component, 'category': node.category, 'permissions': { 'view': can_read, 'admin': is_admin, }, } items.append(item) return items def serialize_wiki_widget(node): from addons.wiki.models import WikiVersion wiki = node.get_addon('wiki') wiki_version = WikiVersion.objects.get_for_node(node, 'home') # Show "Read more" link if there are multiple pages or has > 400 characters more = node.wikis.filter(deleted__isnull=True).count() >= 2 MAX_DISPLAY_LENGTH = 400 rendered_before_update = False if wiki_version and wiki_version.content: if len(wiki_version.content) > MAX_DISPLAY_LENGTH: more = True rendered_before_update = wiki_version.rendered_before_update # Content fetched and rendered by front-end wiki_html = None wiki_widget_data = { 'complete': True, 'wiki_content': wiki_html if wiki_html else None, 'wiki_content_url': node.api_url_for('wiki_page_content', wname='home'), 'rendered_before_update': rendered_before_update, 'more': more, 'include': False, } wiki_widget_data.update(wiki.config.to_json()) return wiki_widget_data
mfraezz/osf.io
addons/wiki/utils.py
Python
apache-2.0
7,955
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """This module contains AWS SNS hook""" import json import warnings from typing import Dict, Optional, Union from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook def _get_message_attribute(o): if isinstance(o, bytes): return {'DataType': 'Binary', 'BinaryValue': o} if isinstance(o, str): return {'DataType': 'String', 'StringValue': o} if isinstance(o, (int, float)): return {'DataType': 'Number', 'StringValue': str(o)} if hasattr(o, '__iter__'): return {'DataType': 'String.Array', 'StringValue': json.dumps(o)} raise TypeError( f'Values in MessageAttributes must be one of bytes, str, int, float, or iterable; got {type(o)}' ) class SnsHook(AwsBaseHook): """ Interact with Amazon Simple Notification Service. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBaseHook. .. seealso:: :class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` """ def __init__(self, *args, **kwargs): super().__init__(client_type='sns', *args, **kwargs) def publish_to_target( self, target_arn: str, message: str, subject: Optional[str] = None, message_attributes: Optional[dict] = None, ): """ Publish a message to a topic or an endpoint. :param target_arn: either a TopicArn or an EndpointArn :param message: the default message you want to send :param message: str :param subject: subject of message :param message_attributes: additional attributes to publish for message filtering. This should be a flat dict; the DataType to be sent depends on the type of the value: - bytes = Binary - str = String - int, float = Number - iterable = String.Array """ publish_kwargs: Dict[str, Union[str, dict]] = { 'TargetArn': target_arn, 'MessageStructure': 'json', 'Message': json.dumps({'default': message}), } # Construct args this way because boto3 distinguishes from missing args and those set to None if subject: publish_kwargs['Subject'] = subject if message_attributes: publish_kwargs['MessageAttributes'] = { key: _get_message_attribute(val) for key, val in message_attributes.items() } return self.get_conn().publish(**publish_kwargs) class AwsSnsHook(SnsHook): """ This hook is deprecated. Please use :class:`airflow.providers.amazon.aws.hooks.sns.SnsHook`. """ def __init__(self, *args, **kwargs): warnings.warn( "This hook is deprecated. " "Please use :class:`airflow.providers.amazon.aws.hooks.sns.SnsHook`.", DeprecationWarning, stacklevel=2, ) super().__init__(*args, **kwargs)
Acehaidrey/incubator-airflow
airflow/providers/amazon/aws/hooks/sns.py
Python
apache-2.0
3,748
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================= # pylint: disable=unused-import,g-bad-import-order """Neural network support. See the @{$python/nn} guide. @@relu @@relu6 @@crelu @@swish @@elu @@leaky_relu @@selu @@softplus @@softsign @@dropout @@bias_add @@sigmoid @@log_sigmoid @@tanh @@convolution @@conv2d @@depthwise_conv2d @@depthwise_conv2d_native @@separable_conv2d @@atrous_conv2d @@atrous_conv2d_transpose @@conv2d_transpose @@conv1d @@conv3d @@conv3d_transpose @@conv2d_backprop_filter @@conv2d_backprop_input @@conv3d_backprop_filter_v2 @@depthwise_conv2d_native_backprop_filter @@depthwise_conv2d_native_backprop_input @@avg_pool @@max_pool @@max_pool_with_argmax @@avg_pool3d @@max_pool3d @@fractional_avg_pool @@fractional_max_pool @@pool @@dilation2d @@erosion2d @@with_space_to_batch @@l2_normalize @@local_response_normalization @@sufficient_statistics @@normalize_moments @@moments @@weighted_moments @@fused_batch_norm @@batch_normalization @@batch_norm_with_global_normalization @@l2_loss @@log_poisson_loss @@sigmoid_cross_entropy_with_logits @@softmax @@log_softmax @@softmax_cross_entropy_with_logits @@sparse_softmax_cross_entropy_with_logits @@weighted_cross_entropy_with_logits @@embedding_lookup @@embedding_lookup_sparse @@dynamic_rnn @@bidirectional_dynamic_rnn @@raw_rnn @@static_rnn @@static_state_saving_rnn @@static_bidirectional_rnn @@ctc_loss @@ctc_greedy_decoder @@ctc_beam_search_decoder @@top_k @@in_top_k @@nce_loss @@sampled_softmax_loss @@uniform_candidate_sampler @@log_uniform_candidate_sampler @@learned_unigram_candidate_sampler @@fixed_unigram_candidate_sampler @@compute_accidental_hits @@quantized_conv2d @@quantized_relu_x @@quantized_max_pool @@quantized_avg_pool """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys as _sys # pylint: disable=unused-import from tensorflow.python.ops import ctc_ops as _ctc_ops from tensorflow.python.ops import embedding_ops as _embedding_ops from tensorflow.python.ops import nn_grad as _nn_grad from tensorflow.python.ops import nn_ops as _nn_ops from tensorflow.python.ops.math_ops import sigmoid from tensorflow.python.ops.math_ops import tanh # pylint: enable=unused-import from tensorflow.python.util.all_util import remove_undocumented # Bring more nn-associated functionality into this package. # go/tf-wildcard-import # pylint: disable=wildcard-import,unused-import from tensorflow.python.ops.ctc_ops import * from tensorflow.python.ops.nn_impl import * from tensorflow.python.ops.nn_ops import * from tensorflow.python.ops.candidate_sampling_ops import * from tensorflow.python.ops.embedding_ops import * from tensorflow.python.ops.rnn import * from tensorflow.python.ops import rnn_cell # pylint: enable=wildcard-import,unused-import # TODO(cwhipkey): sigmoid and tanh should not be exposed from tf.nn. _allowed_symbols = [ "zero_fraction", # documented in training.py # Modules whitelisted for reference through tf.nn. # TODO(cwhipkey): migrate callers to use the submodule directly. # Symbols whitelisted for export without documentation. # TODO(cwhipkey): review these and move to contrib or expose through # documentation. "all_candidate_sampler", # Excluded in gen_docs_combined. "lrn", # Excluded in gen_docs_combined. "relu_layer", # Excluded in gen_docs_combined. "xw_plus_b", # Excluded in gen_docs_combined. "rnn_cell", # rnn_cell is a submodule of tf.nn. ] remove_undocumented(__name__, _allowed_symbols, [_sys.modules[__name__], _ctc_ops, _nn_ops, _nn_grad])
benoitsteiner/tensorflow-opencl
tensorflow/python/ops/nn.py
Python
apache-2.0
4,256
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # 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. """This code example gets all labels. To create labels, run create_labels.py. This feature is only available to DFP premium solution networks.""" # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v201502') # Create statement to get all labels statement = dfp.FilterStatement() # Get labels by statement. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: # Display results. for label in response['results']: print ('Label with id \'%s\' and name \'%s\' was found.' % (label['id'], label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client)
wubr2000/googleads-python-lib
examples/dfp/v201502/label_service/get_all_labels.py
Python
apache-2.0
1,648
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Tests for layers.feature_column_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.contrib.layers.python.layers import feature_column_ops from tensorflow.python.ops import init_ops class TransformerTest(tf.test.TestCase): def testRealValuedColumnIsIdentityTransformation(self): real_valued = tf.contrib.layers.real_valued_column("price") features = {"price": tf.constant([[20.], [110], [-3]])} output = feature_column_ops._Transformer(features).transform(real_valued) with self.test_session(): self.assertAllEqual(output.eval(), [[20.], [110], [-3]]) def testBucketizedColumn(self): bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) # buckets 2, 3, 0 features = {"price": tf.constant([[20.], [110], [-3]])} output = feature_column_ops._Transformer(features).transform(bucket) with self.test_session(): self.assertAllEqual(output.eval(), [[2], [3], [0]]) def testBucketizedColumnWithMultiDimensions(self): bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price", 2), boundaries=[0., 10., 100.]) # buckets 2, 3, 0 features = {"price": tf.constant([[20., 110], [110., 20], [-3, -3]])} output = feature_column_ops._Transformer(features).transform(bucket) with self.test_session(): self.assertAllEqual(output.eval(), [[2, 3], [3, 2], [0, 0]]) def testCachedTransformation(self): bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) # buckets 2, 3, 0 features = {"price": tf.constant([[20.], [110], [-3]])} transformer = feature_column_ops._Transformer(features) with self.test_session() as sess: transformer.transform(bucket) num_of_ops = len(sess.graph.get_operations()) # Verify that the second call to transform the same feature # doesn't increase the number of ops. transformer.transform(bucket) self.assertEqual(num_of_ops, len(sess.graph.get_operations())) def testSparseColumnWithHashBucket(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} output = feature_column_ops._Transformer(features).transform(hashed_sparse) with self.test_session(): self.assertEqual(output.values.dtype, tf.int64) self.assertTrue(all(x < 10 and x >= 0 for x in output.values.eval())) self.assertAllEqual(output.indices.eval(), wire_tensor.indices.eval()) self.assertAllEqual(output.shape.eval(), wire_tensor.shape.eval()) def testEmbeddingColumn(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} output = feature_column_ops._Transformer(features).transform( tf.contrib.layers.embedding_column(hashed_sparse, 10)) expected = feature_column_ops._Transformer(features).transform( hashed_sparse) with self.test_session(): self.assertAllEqual(output.values.eval(), expected.values.eval()) self.assertAllEqual(output.indices.eval(), expected.indices.eval()) self.assertAllEqual(output.shape.eval(), expected.shape.eval()) def testSparseColumnWithKeys(self): keys_sparse = tf.contrib.layers.sparse_column_with_keys( "wire", ["marlo", "omar", "stringer"]) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} output = feature_column_ops._Transformer(features).transform(keys_sparse) with self.test_session(): tf.initialize_all_tables().run() self.assertEqual(output.values.dtype, tf.int64) self.assertAllEqual(output.values.eval(), [1, 2, 0]) self.assertAllEqual(output.indices.eval(), wire_tensor.indices.eval()) self.assertAllEqual(output.shape.eval(), wire_tensor.shape.eval()) def testSparseColumnWithHashBucket_IsIntegerized(self): hashed_sparse = tf.contrib.layers.sparse_column_with_integerized_feature( "wire", 10) wire_tensor = tf.SparseTensor(values=[100, 1, 25], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} output = feature_column_ops._Transformer(features).transform(hashed_sparse) with self.test_session(): self.assertEqual(output.values.dtype, tf.int32) self.assertTrue(all(x < 10 and x >= 0 for x in output.values.eval())) self.assertAllEqual(output.indices.eval(), wire_tensor.indices.eval()) self.assertAllEqual(output.shape.eval(), wire_tensor.shape.eval()) def testWeightedSparseColumn(self): ids = tf.contrib.layers.sparse_column_with_keys( "ids", ["marlo", "omar", "stringer"]) ids_tensor = tf.SparseTensor(values=["stringer", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, "weights") weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"ids": ids_tensor, "weights": weights_tensor} output = feature_column_ops._Transformer(features).transform(weighted_ids) with self.test_session(): tf.initialize_all_tables().run() self.assertAllEqual(output[0].shape.eval(), ids_tensor.shape.eval()) self.assertAllEqual(output[0].indices.eval(), ids_tensor.indices.eval()) self.assertAllEqual(output[0].values.eval(), [2, 2, 0]) self.assertAllEqual(output[1].shape.eval(), weights_tensor.shape.eval()) self.assertAllEqual(output[1].indices.eval(), weights_tensor.indices.eval()) self.assertEqual(output[1].values.dtype, tf.float32) self.assertAllEqual(output[1].values.eval(), weights_tensor.values.eval()) def testCrossColumn(self): language = tf.contrib.layers.sparse_column_with_hash_bucket( "language", hash_bucket_size=3) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) country_language = tf.contrib.layers.crossed_column( [language, country], hash_bucket_size=15) features = { "language": tf.SparseTensor(values=["english", "spanish"], indices=[[0, 0], [1, 0]], shape=[2, 1]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [1, 0]], shape=[2, 1]) } output = feature_column_ops._Transformer(features).transform( country_language) with self.test_session(): self.assertEqual(output.values.dtype, tf.int64) self.assertTrue(all(x < 15 and x >= 0 for x in output.values.eval())) def testCrossWithBucketizedColumn(self): price_bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) country_price = tf.contrib.layers.crossed_column( [country, price_bucket], hash_bucket_size=15) features = { "price": tf.constant([[20.]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [0, 1]], shape=[1, 2]) } output = feature_column_ops._Transformer(features).transform(country_price) with self.test_session(): self.assertEqual(output.values.dtype, tf.int64) self.assertTrue(all(x < 15 and x >= 0 for x in output.values.eval())) def testCrossWithMultiDimensionBucketizedColumn(self): country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) price_bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price", 2), boundaries=[0., 10., 100.]) country_price = tf.contrib.layers.crossed_column( [country, price_bucket], hash_bucket_size=1000) with tf.Graph().as_default(): features = {"price": tf.constant([[20., 210.], [110., 50.], [-3., -30.]]), "country": tf.SparseTensor(values=["US", "SV", "US"], indices=[[0, 0], [1, 0], [2, 0]], shape=[3, 2])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [country_price], num_outputs=1)) weights = column_to_variable[country_price][0] grad = tf.squeeze(tf.gradients(output, weights)[0].values) with self.test_session(): tf.initialize_all_variables().run() self.assertEqual(len(grad.eval()), 6) def testCrossWithCrossedColumn(self): price_bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) country_price = tf.contrib.layers.crossed_column( [country, price_bucket], hash_bucket_size=15) wire = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_country_price = tf.contrib.layers.crossed_column( [wire, country_price], hash_bucket_size=15) features = { "price": tf.constant([[20.]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [0, 1]], shape=[1, 2]), "wire": tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [0, 1], [0, 2]], shape=[1, 3]) } output = feature_column_ops._Transformer(features).transform( wire_country_price) with self.test_session(): self.assertEqual(output.values.dtype, tf.int64) self.assertTrue(all(x < 15 and x >= 0 for x in output.values.eval())) def testIfFeatureTableContainsTransfromationReturnIt(self): any_column = tf.contrib.layers.sparse_column_with_hash_bucket("sparse", 10) features = {any_column: "any-thing-even-not-a-tensor"} output = feature_column_ops._Transformer(features).transform(any_column) self.assertEqual(output, "any-thing-even-not-a-tensor") class InputLayerTest(tf.test.TestCase): def testRealValuedColumn(self): real_valued = tf.contrib.layers.real_valued_column("price") features = {"price": tf.constant([[20.], [110], [-3]])} output = tf.contrib.layers.input_from_feature_columns(features, [real_valued]) with self.test_session(): self.assertAllClose(output.eval(), features["price"].eval()) def testRealValuedColumnWithMultiDimensions(self): real_valued = tf.contrib.layers.real_valued_column("price", 2) features = {"price": tf.constant([[20., 10.], [110, 0.], [-3, 30]])} output = tf.contrib.layers.input_from_feature_columns(features, [real_valued]) with self.test_session(): self.assertAllClose(output.eval(), features["price"].eval()) def testBucketizedColumn(self): bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) # buckets 2, 3, 0 features = {"price": tf.constant([[20.], [110], [-3]])} output = tf.contrib.layers.input_from_feature_columns(features, [bucket]) expected = [[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0]] with self.test_session(): self.assertAllClose(output.eval(), expected) def testBucketizedColumnWithMultiDimensions(self): bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price", 2), boundaries=[0., 10., 100.]) # buckets [2, 3], [3, 2], [0, 0]. dimension = 2 features = {"price": tf.constant([[20., 200], [110, 50], [-3, -3]])} output = tf.contrib.layers.input_from_feature_columns(features, [bucket]) expected = [[0, 0, 1, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 0], [1, 0, 0, 0, 1, 0, 0, 0]] with self.test_session(): self.assertAllClose(output.eval(), expected) def testEmbeddingColumn(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} embeded_sparse = tf.contrib.layers.embedding_column(hashed_sparse, 10) output = tf.contrib.layers.input_from_feature_columns(features, [embeded_sparse]) with self.test_session(): tf.initialize_all_variables().run() self.assertAllEqual(output.eval().shape, [2, 10]) def testHashedEmbeddingColumn(self): wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo", "omar"], indices=[[0, 0], [1, 0], [1, 1], [2, 0]], shape=[3, 2]) features = {"wire": wire_tensor} # Big enough hash space so that hopefully there is no collision embedded_sparse = tf.contrib.layers.hashed_embedding_column("wire", 1000, 3) output = tf.contrib.layers.input_from_feature_columns( features, [embedded_sparse], weight_collections=["my_collection"]) weights = tf.get_collection("my_collection") grad = tf.gradients(output, weights) with self.test_session(): tf.initialize_all_variables().run() gradient_values = [] # Collect the gradient from the different partitions (one in this test) for p in range(len(grad)): gradient_values.extend(grad[p].values.eval()) gradient_values.sort() self.assertAllEqual(gradient_values, [0.5]*6 + [2]*3) def testEmbeddingColumnWithInitializer(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} init_value = 133.7 embeded_sparse = tf.contrib.layers.embedding_column( hashed_sparse, 10, initializer=tf.constant_initializer(init_value)) output = tf.contrib.layers.input_from_feature_columns(features, [embeded_sparse]) with self.test_session(): tf.initialize_all_variables().run() output_eval = output.eval() self.assertAllEqual(output_eval.shape, [2, 10]) self.assertAllClose(output_eval, np.tile(init_value, [2, 10])) def testEmbeddingColumnWithMultipleInitializers(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} embedded_sparse = tf.contrib.layers.embedding_column( hashed_sparse, 10, initializer=tf.truncated_normal_initializer(mean=42, stddev=1337)) embedded_sparse_alternate = tf.contrib.layers.embedding_column( hashed_sparse, 10, initializer=tf.truncated_normal_initializer(mean=1337, stddev=42)) # Makes sure that trying to use different initializers with the same # embedding column explicitly fails. with self.test_session(): with self.assertRaisesRegexp( ValueError, "Duplicate feature column key found for column: wire_embedding"): tf.contrib.layers.input_from_feature_columns( features, [embedded_sparse, embedded_sparse_alternate]) def testEmbeddingColumnWithWeightedSparseColumn(self): ids = tf.contrib.layers.sparse_column_with_keys( "ids", ["marlo", "omar", "stringer"]) ids_tensor = tf.SparseTensor(values=["stringer", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, "weights") weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"ids": ids_tensor, "weights": weights_tensor} embeded_sparse = tf.contrib.layers.embedding_column(weighted_ids, 10) output = tf.contrib.layers.input_from_feature_columns(features, [embeded_sparse]) with self.test_session(): tf.initialize_all_variables().run() tf.initialize_all_tables().run() self.assertAllEqual(output.eval().shape, [2, 10]) def testEmbeddingColumnWitCrossedColumn(self): a = tf.contrib.layers.sparse_column_with_hash_bucket("aaa", hash_bucket_size=100) b = tf.contrib.layers.sparse_column_with_hash_bucket("bbb", hash_bucket_size=100) crossed = tf.contrib.layers.crossed_column( set([a, b]), hash_bucket_size=10000) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"aaa": wire_tensor, "bbb": wire_tensor} embeded_sparse = tf.contrib.layers.embedding_column(crossed, 10) output = tf.contrib.layers.input_from_feature_columns(features, [embeded_sparse]) with self.test_session(): tf.initialize_all_variables().run() self.assertAllEqual(output.eval().shape, [2, 10]) def testSparseColumn(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} with self.test_session(): with self.assertRaisesRegexp( ValueError, "Error creating input layer for column: wire"): tf.initialize_all_variables().run() tf.contrib.layers.input_from_feature_columns(features, [hashed_sparse]) def testWeightedSparseColumn(self): ids = tf.contrib.layers.sparse_column_with_keys( "ids", ["marlo", "omar", "stringer"]) ids_tensor = tf.SparseTensor(values=["stringer", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, "weights") weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"ids": ids_tensor, "weights": weights_tensor} with self.test_session(): with self.assertRaisesRegexp( ValueError, "Error creating input layer for column: ids_weighted_by_weights"): tf.initialize_all_tables().run() tf.contrib.layers.input_from_feature_columns(features, [weighted_ids]) def testCrossedColumn(self): a = tf.contrib.layers.sparse_column_with_hash_bucket("aaa", hash_bucket_size=100) b = tf.contrib.layers.sparse_column_with_hash_bucket("bbb", hash_bucket_size=100) crossed = tf.contrib.layers.crossed_column( set([a, b]), hash_bucket_size=10000) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"aaa": wire_tensor, "bbb": wire_tensor} with self.test_session(): with self.assertRaisesRegexp( ValueError, "Error creating input layer for column: aaa_X_bbb"): tf.initialize_all_variables().run() tf.contrib.layers.input_from_feature_columns(features, [crossed]) def testAllColumns(self): real_valued = tf.contrib.layers.real_valued_column("income", 3) bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price", 2), boundaries=[0., 10., 100.]) hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) features = { "income": tf.constant([[20., 10, -5], [110, 0, -7], [-3, 30, 50]]), "price": tf.constant([[20., 200], [110, 2], [-20, -30]]), "wire": tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [2, 0]], shape=[3, 1]) } embeded_sparse = tf.contrib.layers.embedding_column( hashed_sparse, 10, initializer=tf.constant_initializer(133.7)) output = tf.contrib.layers.input_from_feature_columns( features, [real_valued, bucket, embeded_sparse]) with self.test_session(): tf.initialize_all_variables().run() # size of output = 3 (real_valued) + 2 * 4 (bucket) + 10 (embedding) = 21 self.assertAllEqual(output.eval().shape, [3, 21]) def testPredictionsEmbeddingColumn(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} embeded_sparse = tf.contrib.layers.embedding_column( hashed_sparse, 1, combiner="sum", initializer=init_ops.ones_initializer) output = tf.contrib.layers.input_from_feature_columns(features, [embeded_sparse]) with self.test_session(): tf.initialize_all_variables().run() # score: (number of values) self.assertAllEqual(output.eval(), [[1.], [2.]]) def testPredictionsEmbeddingColumnWithWeightedSparseColumn(self): ids = tf.contrib.layers.sparse_column_with_keys( "ids", ["marlo", "omar", "stringer"]) ids_tensor = tf.SparseTensor(values=["stringer", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, "weights") weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"ids": ids_tensor, "weights": weights_tensor} embeded_sparse = tf.contrib.layers.embedding_column( weighted_ids, 1, combiner="sum", initializer=init_ops.ones_initializer) output = tf.contrib.layers.input_from_feature_columns(features, [embeded_sparse]) with self.test_session(): tf.initialize_all_variables().run() tf.initialize_all_tables().run() # score: (sum of weights) self.assertAllEqual(output.eval(), [[10.], [50.]]) def testInputLayerWithCollections(self): real_valued = tf.contrib.layers.real_valued_column("price") bucket = tf.contrib.layers.bucketized_column(real_valued, boundaries=[0., 10., 100.]) hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) features = { "price": tf.constant([[20.], [110], [-3]]), "wire": tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [2, 0]], shape=[3, 1]) } embeded_sparse = tf.contrib.layers.embedding_column(hashed_sparse, 10) tf.contrib.layers.input_from_feature_columns( features, [real_valued, bucket, embeded_sparse], weight_collections=["my_collection"]) weights = tf.get_collection("my_collection") # one variable for embeded sparse self.assertEqual(1, len(weights)) def testInputLayerWithTrainableArg(self): real_valued = tf.contrib.layers.real_valued_column("price") bucket = tf.contrib.layers.bucketized_column(real_valued, boundaries=[0., 10., 100.]) hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) features = { "price": tf.constant([[20.], [110], [-3]]), "wire": tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [2, 0]], shape=[3, 1]) } embeded_sparse = tf.contrib.layers.embedding_column(hashed_sparse, 10) tf.contrib.layers.input_from_feature_columns( features, [real_valued, bucket, embeded_sparse], weight_collections=["my_collection"], trainable=False) # There should not be any trainable variables self.assertEqual(0, len(tf.trainable_variables())) tf.contrib.layers.input_from_feature_columns( features, [real_valued, bucket, embeded_sparse], weight_collections=["my_collection"], trainable=True) # There should one trainable variable for embeded sparse self.assertEqual(1, len(tf.trainable_variables())) class WeightedSumTest(tf.test.TestCase): def testSparseColumn(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns( features, [hashed_sparse], num_outputs=5) with self.test_session(): tf.initialize_all_variables().run() self.assertAllEqual(logits.eval().shape, [2, 5]) def testWeightedSparseColumn(self): ids = tf.contrib.layers.sparse_column_with_keys( "ids", ["marlo", "omar", "stringer"]) ids_tensor = tf.SparseTensor(values=["stringer", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) weighted_ids = tf.contrib.layers.weighted_sparse_column(ids, "weights") weights_tensor = tf.SparseTensor(values=[10.0, 20.0, 30.0], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"ids": ids_tensor, "weights": weights_tensor} logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns( features, [weighted_ids], num_outputs=5) with self.test_session(): tf.initialize_all_variables().run() tf.initialize_all_tables().run() self.assertAllEqual(logits.eval().shape, [2, 5]) def testCrossedColumn(self): a = tf.contrib.layers.sparse_column_with_hash_bucket("aaa", hash_bucket_size=100) b = tf.contrib.layers.sparse_column_with_hash_bucket("bbb", hash_bucket_size=100) crossed = tf.contrib.layers.crossed_column( set([a, b]), hash_bucket_size=10000) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"aaa": wire_tensor, "bbb": wire_tensor} logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns( features, [crossed], num_outputs=5) with self.test_session(): tf.initialize_all_variables().run() self.assertAllEqual(logits.eval().shape, [2, 5]) def testEmbeddingColumn(self): hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) wire_tensor = tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [1, 1]], shape=[2, 2]) features = {"wire": wire_tensor} embeded_sparse = tf.contrib.layers.embedding_column(hashed_sparse, 10) with self.test_session(): with self.assertRaisesRegexp( ValueError, "Error creating weighted sum for column: wire_embedding"): tf.initialize_all_variables().run() tf.contrib.layers.weighted_sum_from_feature_columns(features, [embeded_sparse], num_outputs=5) def testRealValuedColumnWithMultiDimensions(self): real_valued = tf.contrib.layers.real_valued_column("price", 2) features = {"price": tf.constant([[20., 10.], [110, 0.], [-3, 30]])} logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns( features, [real_valued], num_outputs=5) with self.test_session(): tf.initialize_all_variables().run() self.assertAllEqual(logits.eval().shape, [3, 5]) def testBucketizedColumnWithMultiDimensions(self): bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price", 2), boundaries=[0., 10., 100.]) features = {"price": tf.constant([[20., 10.], [110, 0.], [-3, 30]])} logits, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns( features, [bucket], num_outputs=5) with self.test_session(): tf.initialize_all_variables().run() self.assertAllEqual(logits.eval().shape, [3, 5]) def testAllColumns(self): real_valued = tf.contrib.layers.real_valued_column("income", 2) bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) hashed_sparse = tf.contrib.layers.sparse_column_with_hash_bucket("wire", 10) crossed = tf.contrib.layers.crossed_column([bucket, hashed_sparse], 100) features = { "income": tf.constant([[20., 10], [110, 0], [-3, 30]]), "price": tf.constant([[20.], [110], [-3]]), "wire": tf.SparseTensor(values=["omar", "stringer", "marlo"], indices=[[0, 0], [1, 0], [2, 0]], shape=[3, 1]) } output, _, _ = tf.contrib.layers.weighted_sum_from_feature_columns( features, [real_valued, bucket, hashed_sparse, crossed], num_outputs=5) with self.test_session(): tf.initialize_all_variables().run() self.assertAllEqual(output.eval().shape, [3, 5]) def testPredictions(self): language = tf.contrib.layers.sparse_column_with_keys( column_name="language", keys=["english", "finnish", "hindi"]) age = tf.contrib.layers.real_valued_column("age") with tf.Graph().as_default(): features = { "age": tf.constant([[1], [2]]), "language": tf.SparseTensor(values=["hindi", "english"], indices=[[0, 0], [1, 0]], shape=[2, 1]), } output, column_to_variable, bias = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [age, language], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() self.assertAllClose(output.eval(), [[0.], [0.]]) sess.run(bias.assign([0.1])) self.assertAllClose(output.eval(), [[0.1], [0.1]]) # score: 0.1 + age*0.1 sess.run(column_to_variable[age][0].assign([[0.2]])) self.assertAllClose(output.eval(), [[0.3], [0.5]]) # score: 0.1 + age*0.1 + language_weight[language_index] sess.run(column_to_variable[language][0].assign([[0.1], [0.3], [0.2]])) self.assertAllClose(output.eval(), [[0.5], [0.6]]) def testPredictionsWithWeightedSparseColumn(self): language = tf.contrib.layers.sparse_column_with_keys( column_name="language", keys=["english", "finnish", "hindi"]) weighted_language = tf.contrib.layers.weighted_sparse_column( sparse_id_column=language, weight_column_name="age") with tf.Graph().as_default(): features = { "language": tf.SparseTensor(values=["hindi", "english"], indices=[[0, 0], [1, 0]], shape=[2, 1]), "age": tf.SparseTensor(values=[10.0, 20.0], indices=[[0, 0], [1, 0]], shape=[2, 1]) } output, column_to_variable, bias = ( tf.contrib.layers.weighted_sum_from_feature_columns( features, [weighted_language], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() self.assertAllClose(output.eval(), [[0.], [0.]]) sess.run(bias.assign([0.1])) self.assertAllClose(output.eval(), [[0.1], [0.1]]) # score: bias + age*language_weight[index] sess.run(column_to_variable[weighted_language][0].assign( [[0.1], [0.2], [0.3]])) self.assertAllClose(output.eval(), [[3.1], [2.1]]) def testPredictionsWithMultivalentColumnButNoCross(self): language = tf.contrib.layers.sparse_column_with_keys( column_name="language", keys=["english", "turkish", "hindi"]) with tf.Graph().as_default(): features = { "language": tf.SparseTensor(values=["hindi", "english"], indices=[[0, 0], [0, 1]], shape=[1, 2]) } output, column_to_variable, bias = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [language], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() # score: 0.1 + language_weight['hindi'] + language_weight['english'] sess.run(bias.assign([0.1])) sess.run(column_to_variable[language][0].assign([[0.1], [0.3], [0.2]])) self.assertAllClose(output.eval(), [[0.4]]) def testSparseFeatureColumnWithHashedBucketSize(self): movies = tf.contrib.layers.sparse_column_with_hash_bucket( column_name="movies", hash_bucket_size=15) with tf.Graph().as_default(): features = { "movies": tf.SparseTensor( values=["matrix", "head-on", "winter sleep"], indices=[[0, 0], [0, 1], [1, 0]], shape=[2, 2]) } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [movies], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[movies][0] self.assertEqual(weights.get_shape(), (15, 1)) sess.run(weights.assign(weights + 0.4)) # score for first example = 0.4 (matrix) + 0.4 (head-on) = 0.8 # score for second example = 0.4 (winter sleep) self.assertAllClose(output.eval(), [[0.8], [0.4]]) def testCrossUsageInPredictions(self): language = tf.contrib.layers.sparse_column_with_hash_bucket( "language", hash_bucket_size=3) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) country_language = tf.contrib.layers.crossed_column( [language, country], hash_bucket_size=10) with tf.Graph().as_default(): features = { "language": tf.SparseTensor(values=["english", "spanish"], indices=[[0, 0], [1, 0]], shape=[2, 1]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [1, 0]], shape=[2, 1]) } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns( features, [country_language], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[country_language][0] sess.run(weights.assign(weights + 0.4)) self.assertAllClose(output.eval(), [[0.4], [0.4]]) def testCrossColumnByItself(self): language = tf.contrib.layers.sparse_column_with_hash_bucket( "language", hash_bucket_size=3) language_language = tf.contrib.layers.crossed_column( [language, language], hash_bucket_size=10) with tf.Graph().as_default(): features = { "language": tf.SparseTensor(values=["english", "spanish"], indices=[[0, 0], [0, 1]], shape=[1, 2]), } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns( features, [language_language], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[language_language][0] sess.run(weights.assign(weights + 0.4)) # There are two features inside language. If we cross it by itself we'll # have four crossed features. self.assertAllClose(output.eval(), [[1.6]]) def testMultivalentCrossUsageInPredictions(self): language = tf.contrib.layers.sparse_column_with_hash_bucket( "language", hash_bucket_size=3) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) country_language = tf.contrib.layers.crossed_column( [language, country], hash_bucket_size=10) with tf.Graph().as_default(): features = { "language": tf.SparseTensor(values=["english", "spanish"], indices=[[0, 0], [0, 1]], shape=[1, 2]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [0, 1]], shape=[1, 2]) } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns( features, [country_language], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[country_language][0] sess.run(weights.assign(weights + 0.4)) # There are four crosses each with 0.4 weight. # score = 0.4 + 0.4 + 0.4 + 0.4 self.assertAllClose(output.eval(), [[1.6]]) def testMultivalentCrossUsageInPredictionsWithPartition(self): # bucket size has to be big enough to allwo sharding. language = tf.contrib.layers.sparse_column_with_hash_bucket( "language", hash_bucket_size=64 << 19) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=64 << 18) country_language = tf.contrib.layers.crossed_column( [language, country], hash_bucket_size=64 << 18) with tf.Graph().as_default(): features = { "language": tf.SparseTensor(values=["english", "spanish"], indices=[[0, 0], [0, 1]], shape=[1, 2]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [0, 1]], shape=[1, 2]) } with tf.variable_op_scope( features.values(), "weighted_sum_from_feature_columns", partitioner=tf.min_max_variable_partitioner( max_partitions=10, min_slice_size=((64 << 20) - 1))) as scope: output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns( features, [country, language, country_language], num_outputs=1, scope=scope)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() self.assertEqual(2, len(column_to_variable[country])) self.assertEqual(3, len(column_to_variable[language])) self.assertEqual(2, len(column_to_variable[country_language])) weights = column_to_variable[country_language] for partition_variable in weights: sess.run(partition_variable.assign(partition_variable + 0.4)) # There are four crosses each with 0.4 weight. # score = 0.4 + 0.4 + 0.4 + 0.4 self.assertAllClose(output.eval(), [[1.6]]) def testRealValuedColumnHavingMultiDimensions(self): country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) age = tf.contrib.layers.real_valued_column("age") # The following RealValuedColumn has 3 dimensions. incomes = tf.contrib.layers.real_valued_column("incomes", 3) with tf.Graph().as_default(): features = {"age": tf.constant([[1], [1]]), "incomes": tf.constant([[100., 200., 300.], [10., 20., 30.]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [1, 0]], shape=[2, 2])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns( features, [country, age, incomes], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() incomes_weights = column_to_variable[incomes][0] sess.run(incomes_weights.assign([[0.1], [0.2], [0.3]])) self.assertAllClose(output.eval(), [[140.], [14.]]) def testMulticlassWithRealValuedColumnHavingMultiDimensions(self): country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) age = tf.contrib.layers.real_valued_column("age") # The following RealValuedColumn has 3 dimensions. incomes = tf.contrib.layers.real_valued_column("incomes", 3) with tf.Graph().as_default(): features = {"age": tf.constant([[1], [1]]), "incomes": tf.constant([[100., 200., 300.], [10., 20., 30.]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [1, 0]], shape=[2, 2])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns( features, [country, age, incomes], num_outputs=5)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() incomes_weights = column_to_variable[incomes][0] sess.run(incomes_weights.assign([[0.01, 0.1, 1., 10., 100.], [0.02, 0.2, 2., 20., 200.], [0.03, 0.3, 3., 30., 300.]])) self.assertAllClose(output.eval(), [[14., 140., 1400., 14000., 140000.], [1.4, 14., 140., 1400., 14000.]]) def testBucketizedColumn(self): bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) with tf.Graph().as_default(): # buckets 2, 3, 0 features = {"price": tf.constant([[20.], [110], [-3]])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [bucket], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() sess.run(column_to_variable[bucket][0].assign([[0.1], [0.2], [0.3], [0.4 ]])) self.assertAllClose(output.eval(), [[0.3], [0.4], [0.1]]) def testBucketizedColumnHavingMultiDimensions(self): country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price", 2), boundaries=[0., 10., 100.]) with tf.Graph().as_default(): # buckets 2, 3, 0 features = {"price": tf.constant([[20., 210], [110, 50], [-3, -30]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [1, 0]], shape=[3, 2])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [bucket, country], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() # dimension = 2, bucket_size = 4, num_classes = 1 sess.run(column_to_variable[bucket][0].assign( [[0.1], [0.2], [0.3], [0.4], [1], [2], [3], [4]])) self.assertAllClose(output.eval(), [[0.3 + 4], [0.4 + 3], [0.1 + 1]]) def testMulticlassWithBucketizedColumnHavingMultiDimensions(self): country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price", 2), boundaries=[0., 10., 100.]) with tf.Graph().as_default(): # buckets 2, 3, 0 features = {"price": tf.constant([[20., 210], [110, 50], [-3, -30]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [1, 0]], shape=[3, 2])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [bucket, country], num_outputs=5)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() # dimension = 2, bucket_size = 4, num_classes = 5 sess.run(column_to_variable[bucket][0].assign( [[0.1, 1, 10, 100, 1000], [0.2, 2, 20, 200, 2000], [0.3, 3, 30, 300, 3000], [0.4, 4, 40, 400, 4000], [5, 50, 500, 5000, 50000], [6, 60, 600, 6000, 60000], [7, 70, 700, 7000, 70000], [8, 80, 800, 8000, 80000]])) self.assertAllClose( output.eval(), [[0.3 + 8, 3 + 80, 30 + 800, 300 + 8000, 3000 + 80000], [0.4 + 7, 4 + 70, 40 + 700, 400 + 7000, 4000 + 70000], [0.1 + 5, 1 + 50, 10 + 500, 100 + 5000, 1000 + 50000]]) def testCrossWithBucketizedColumn(self): price_bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) country_price = tf.contrib.layers.crossed_column( [country, price_bucket], hash_bucket_size=10) with tf.Graph().as_default(): features = { "price": tf.constant([[20.]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [0, 1]], shape=[1, 2]) } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [country_price], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[country_price][0] sess.run(weights.assign(weights + 0.4)) # There are two crosses each with 0.4 weight. # score = 0.4 + 0.4 self.assertAllClose(output.eval(), [[0.8]]) def testCrossWithCrossedColumn(self): price_bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) language = tf.contrib.layers.sparse_column_with_hash_bucket( "language", hash_bucket_size=3) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) country_language = tf.contrib.layers.crossed_column( [language, country], hash_bucket_size=10) country_language_price = tf.contrib.layers.crossed_column( set([country_language, price_bucket]), hash_bucket_size=15) with tf.Graph().as_default(): features = { "price": tf.constant([[20.]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [0, 1]], shape=[1, 2]), "language": tf.SparseTensor(values=["english", "spanish"], indices=[[0, 0], [0, 1]], shape=[1, 2]) } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns( features, [country_language_price], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[country_language_price][0] sess.run(weights.assign(weights + 0.4)) # There are two crosses each with 0.4 weight. # score = 0.4 + 0.4 + 0.4 + 0.4 self.assertAllClose(output.eval(), [[1.6]]) def testIntegerizedColumn(self): product = tf.contrib.layers.sparse_column_with_integerized_feature( "product", bucket_size=5) with tf.Graph().as_default(): features = {"product": tf.SparseTensor(values=[0, 4, 2], indices=[[0, 0], [1, 0], [2, 0]], shape=[3, 1])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [product], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() product_weights = column_to_variable[product][0] sess.run(product_weights.assign([[0.1], [0.2], [0.3], [0.4], [0.5]])) self.assertAllClose(output.eval(), [[0.1], [0.5], [0.3]]) def testIntegerizedColumnWithInvalidId(self): product = tf.contrib.layers.sparse_column_with_integerized_feature( "product", bucket_size=5) with tf.Graph().as_default(): features = {"product": tf.SparseTensor(values=[5, 4, 7], indices=[[0, 0], [1, 0], [2, 0]], shape=[3, 1])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [product], num_outputs=1)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() product_weights = column_to_variable[product][0] sess.run(product_weights.assign([[0.1], [0.2], [0.3], [0.4], [0.5]])) self.assertAllClose(output.eval(), [[0.1], [0.5], [0.3]]) def testMulticlassWithOnlyBias(self): with tf.Graph().as_default(): features = {"age": tf.constant([[10.], [20.], [30.], [40.]])} output, _, bias = tf.contrib.layers.weighted_sum_from_feature_columns( features, [tf.contrib.layers.real_valued_column("age")], num_outputs=3) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() sess.run(bias.assign([0.1, 0.2, 0.3])) self.assertAllClose(output.eval(), [[0.1, 0.2, 0.3], [0.1, 0.2, 0.3], [0.1, 0.2, 0.3], [0.1, 0.2, 0.3]]) def testMulticlassWithRealValuedColumn(self): with tf.Graph().as_default(): column = tf.contrib.layers.real_valued_column("age") features = {"age": tf.constant([[10.], [20.], [30.], [40.]])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [column], num_outputs=3)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[column][0] self.assertEqual(weights.get_shape(), (1, 3)) sess.run(weights.assign([[0.01, 0.03, 0.05]])) self.assertAllClose(output.eval(), [[0.1, 0.3, 0.5], [0.2, 0.6, 1.0], [0.3, 0.9, 1.5], [0.4, 1.2, 2.0]]) def testMulticlassWithSparseColumn(self): with tf.Graph().as_default(): column = tf.contrib.layers.sparse_column_with_keys( column_name="language", keys=["english", "arabic", "hindi", "russian", "swahili"]) features = { "language": tf.SparseTensor( values=["hindi", "english", "arabic", "russian"], indices=[[0, 0], [1, 0], [2, 0], [3, 0]], shape=[4, 1]) } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [column], num_outputs=3)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[column][0] self.assertEqual(weights.get_shape(), (5, 3)) sess.run(weights.assign([[0.1, 0.4, 0.7], [0.2, 0.5, 0.8], [0.3, 0.6, 0.9], [0.4, 0.7, 1.0], [0.5, 0.8, 1.1]])) self.assertAllClose(output.eval(), [[0.3, 0.6, 0.9], [0.1, 0.4, 0.7], [0.2, 0.5, 0.8], [0.4, 0.7, 1.0]]) def testMulticlassWithBucketizedColumn(self): column = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 100., 500., 1000.]) with tf.Graph().as_default(): # buckets 0, 2, 1, 2 features = {"price": tf.constant([[-3], [110], [20.], [210]])} output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [column], num_outputs=3)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[column][0] self.assertEqual(weights.get_shape(), (5, 3)) sess.run(weights.assign([[0.1, 0.4, 0.7], [0.2, 0.5, 0.8], [0.3, 0.6, 0.9], [0.4, 0.7, 1.0], [0.5, 0.8, 1.1]])) self.assertAllClose(output.eval(), [[0.1, 0.4, 0.7], [0.3, 0.6, 0.9], [0.2, 0.5, 0.8], [0.3, 0.6, 0.9]]) def testMulticlassWithCrossedColumn(self): language = tf.contrib.layers.sparse_column_with_hash_bucket( "language", hash_bucket_size=3) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=2) column = tf.contrib.layers.crossed_column( {language, country}, hash_bucket_size=5) with tf.Graph().as_default(): features = { "language": tf.SparseTensor( values=["english", "spanish", "russian", "swahili"], indices=[[0, 0], [1, 0], [2, 0], [3, 0]], shape=[4, 1]), "country": tf.SparseTensor(values=["US", "SV", "RU", "KE"], indices=[[0, 0], [1, 0], [2, 0], [3, 0]], shape=[4, 1]) } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [column], num_outputs=3)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[column][0] self.assertEqual(weights.get_shape(), (5, 3)) sess.run(weights.assign([[0.1, 0.4, 0.7], [0.2, 0.5, 0.8], [0.3, 0.6, 0.9], [0.4, 0.7, 1.0], [0.5, 0.8, 1.1]])) self.assertAllClose(tf.shape(output).eval(), [4, 3]) def testMulticlassWithMultivalentColumn(self): column = tf.contrib.layers.sparse_column_with_keys( column_name="language", keys=["english", "turkish", "hindi", "russian", "swahili"]) with tf.Graph().as_default(): features = { "language": tf.SparseTensor( values=["hindi", "english", "turkish", "turkish", "english"], indices=[[0, 0], [0, 1], [1, 0], [2, 0], [3, 0]], shape=[4, 2]) } output, column_to_variable, _ = ( tf.contrib.layers.weighted_sum_from_feature_columns(features, [column], num_outputs=3)) with self.test_session() as sess: tf.initialize_all_variables().run() tf.initialize_all_tables().run() weights = column_to_variable[column][0] self.assertEqual(weights.get_shape(), (5, 3)) sess.run(weights.assign([[0.1, 0.4, 0.7], [0.2, 0.5, 0.8], [0.3, 0.6, 0.9], [0.4, 0.7, 1.0], [0.5, 0.8, 1.1]])) self.assertAllClose(output.eval(), [[0.4, 1.0, 1.6], [0.2, 0.5, 0.8], [0.2, 0.5, 0.8], [0.1, 0.4, 0.7]]) def testVariablesAddedToCollection(self): price_bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price"), boundaries=[0., 10., 100.]) country = tf.contrib.layers.sparse_column_with_hash_bucket( "country", hash_bucket_size=5) country_price = tf.contrib.layers.crossed_column( [country, price_bucket], hash_bucket_size=10) with tf.Graph().as_default(): features = { "price": tf.constant([[20.]]), "country": tf.SparseTensor(values=["US", "SV"], indices=[[0, 0], [0, 1]], shape=[1, 2]) } tf.contrib.layers.weighted_sum_from_feature_columns( features, [country_price, price_bucket], num_outputs=1, weight_collections=["my_collection"]) weights = tf.get_collection("my_collection") # 3 = bias + price_bucket + country_price self.assertEqual(3, len(weights)) class ParseExampleTest(tf.test.TestCase): def testParseExample(self): bucket = tf.contrib.layers.bucketized_column( tf.contrib.layers.real_valued_column("price", dimension=3), boundaries=[0., 10., 100.]) wire_cast = tf.contrib.layers.sparse_column_with_keys( "wire_cast", ["marlo", "omar", "stringer"]) # buckets 2, 3, 0 data = tf.train.Example(features=tf.train.Features(feature={ "price": tf.train.Feature(float_list=tf.train.FloatList(value=[20., 110, -3])), "wire_cast": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ b"stringer", b"marlo" ])), })) output = tf.contrib.layers.parse_feature_columns_from_examples( serialized=[data.SerializeToString()], feature_columns=[bucket, wire_cast]) self.assertIn(bucket, output) self.assertIn(wire_cast, output) with self.test_session(): tf.initialize_all_tables().run() self.assertAllEqual(output[bucket].eval(), [[2, 3, 0]]) self.assertAllEqual(output[wire_cast].indices.eval(), [[0, 0], [0, 1]]) self.assertAllEqual(output[wire_cast].values.eval(), [2, 0]) class InferRealValuedColumnTest(tf.test.TestCase): def testTensorInt32(self): self.assertEqual( tf.contrib.layers.infer_real_valued_columns( tf.zeros(shape=[33, 4], dtype=tf.int32)), [tf.contrib.layers.real_valued_column("", dimension=4, dtype=tf.int32)]) def testTensorInt64(self): self.assertEqual( tf.contrib.layers.infer_real_valued_columns( tf.zeros(shape=[33, 4], dtype=tf.int64)), [tf.contrib.layers.real_valued_column("", dimension=4, dtype=tf.int64)]) def testTensorFloat32(self): self.assertEqual( tf.contrib.layers.infer_real_valued_columns( tf.zeros(shape=[33, 4], dtype=tf.float32)), [tf.contrib.layers.real_valued_column( "", dimension=4, dtype=tf.float32)]) def testTensorFloat64(self): self.assertEqual( tf.contrib.layers.infer_real_valued_columns( tf.zeros(shape=[33, 4], dtype=tf.float64)), [tf.contrib.layers.real_valued_column( "", dimension=4, dtype=tf.float64)]) def testDictionary(self): self.assertItemsEqual( tf.contrib.layers.infer_real_valued_columns({ "a": tf.zeros(shape=[33, 4], dtype=tf.int32), "b": tf.zeros(shape=[3, 2], dtype=tf.float32) }), [tf.contrib.layers.real_valued_column( "a", dimension=4, dtype=tf.int32), tf.contrib.layers.real_valued_column( "b", dimension=2, dtype=tf.float32)]) def testNotGoodDtype(self): with self.assertRaises(ValueError): tf.contrib.layers.infer_real_valued_columns( tf.constant([["a"]], dtype=tf.string)) def testSparseTensor(self): with self.assertRaises(ValueError): tf.contrib.layers.infer_real_valued_columns( tf.SparseTensor(indices=[[0, 0]], values=["a"], shape=[1, 1])) if __name__ == "__main__": tf.test.main()
rew4332/tensorflow
tensorflow/contrib/layers/python/layers/feature_column_ops_test.py
Python
apache-2.0
66,277
# Copyright 2016 Google Inc. All Rights Reserved. # # 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. """Basic operations examples."""
googleads/googleads-python-lib
examples/adwords/v201809/basic_operations/__init__.py
Python
apache-2.0
631
''' Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py (Original author Wei Wu) by Antti-Pekka Hynninen Implementing the original resnet ILSVRC 2015 winning network from: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. "Deep Residual Learning for Image Recognition" ''' import mxnet as mx def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False): """Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : int Bottle neck channels factor with regard to num_filter stride : tuple Stride used in convolution dim_match : Boolean True means channel number between input and output is the same, otherwise means differ name : str Base name of the operators workspace : int Workspace used in convolution operator """ if bottle_neck: conv1 = mx.sym.Convolution(data=data, num_filter=int(num_filter*0.25), kernel=(1,1), stride=stride, pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv1') bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1') act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') conv2 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.25), kernel=(3,3), stride=(1,1), pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2') bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2') act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2') conv3 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True, workspace=workspace, name=name + '_conv3') bn3 = mx.sym.BatchNorm(data=conv3, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3') if dim_match: shortcut = data else: conv1sc = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_conv1sc') shortcut = mx.sym.BatchNorm(data=conv1sc, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc') if memonger: shortcut._set_attr(mirror_stage='True') return mx.sym.Activation(data=bn3 + shortcut, act_type='relu', name=name + '_relu3') else: conv1 = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv1') bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1') act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1') conv2 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1), no_bias=True, workspace=workspace, name=name + '_conv2') bn2 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2') if dim_match: shortcut = data else: conv1sc = mx.sym.Convolution(data=data, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True, workspace=workspace, name=name+'_conv1sc') shortcut = mx.sym.BatchNorm(data=conv1sc, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_sc') if memonger: shortcut._set_attr(mirror_stage='True') return mx.sym.Activation(data=bn2 + shortcut, act_type='relu', name=name + '_relu3') def resnet(units, num_stages, filter_list, num_classes, image_shape, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False): """Return ResNet symbol of Parameters ---------- units : list Number of units in each stage num_stages : int Number of stage filter_list : list Channel size of each stage num_classes : int Ouput size of symbol dataset : str Dataset type, only cifar10 and imagenet supports workspace : int Workspace used in convolution operator """ num_unit = len(units) assert(num_unit == num_stages) data = mx.sym.Variable(name='data') data = mx.sym.identity(data=data, name='id') (nchannel, height, width) = image_shape if height <= 32: # such as cifar10 body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(3, 3), stride=(1,1), pad=(1, 1), no_bias=True, name="conv0", workspace=workspace) # Is this BatchNorm supposed to be here? body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn0') else: # often expected to be 224 such as imagenet body = mx.sym.Convolution(data=data, num_filter=filter_list[0], kernel=(7, 7), stride=(2,2), pad=(3, 3), no_bias=True, name="conv0", workspace=workspace) body = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn0') body = mx.sym.Activation(data=body, act_type='relu', name='relu0') body = mx.symbol.Pooling(data=body, kernel=(3, 3), stride=(2,2), pad=(1,1), pool_type='max') for i in range(num_stages): body = residual_unit(body, filter_list[i+1], (1 if i==0 else 2, 1 if i==0 else 2), False, name='stage%d_unit%d' % (i + 1, 1), bottle_neck=bottle_neck, workspace=workspace, memonger=memonger) for j in range(units[i]-1): body = residual_unit(body, filter_list[i+1], (1,1), True, name='stage%d_unit%d' % (i + 1, j + 2), bottle_neck=bottle_neck, workspace=workspace, memonger=memonger) # bn1 = mx.sym.BatchNorm(data=body, fix_gamma=False, eps=2e-5, momentum=bn_mom, name='bn1') # relu1 = mx.sym.Activation(data=bn1, act_type='relu', name='relu1') # Although kernel is not used here when global_pool=True, we should put one pool1 = mx.symbol.Pooling(data=body, global_pool=True, kernel=(7, 7), pool_type='avg', name='pool1') flat = mx.symbol.Flatten(data=pool1) fc1 = mx.symbol.FullyConnected(data=flat, num_hidden=num_classes, name='fc1') return mx.symbol.SoftmaxOutput(data=fc1, name='softmax') def get_symbol(num_classes, num_layers, image_shape, conv_workspace=256, **kwargs): """ Adapted from https://github.com/tornadomeet/ResNet/blob/master/symbol_resnet.py (Original author Wei Wu) by Antti-Pekka Hynninen Implementing the original resnet ILSVRC 2015 winning network from: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun. "Deep Residual Learning for Image Recognition" """ image_shape = [int(l) for l in image_shape.split(',')] (nchannel, height, width) = image_shape if height <= 28: num_stages = 3 if (num_layers-2) % 9 == 0 and num_layers >= 164: per_unit = [(num_layers-2)//9] filter_list = [16, 64, 128, 256] bottle_neck = True elif (num_layers-2) % 6 == 0 and num_layers < 164: per_unit = [(num_layers-2)//6] filter_list = [16, 16, 32, 64] bottle_neck = False else: raise ValueError("no experiments done on num_layers {}, you can do it youself".format(num_layers)) units = per_unit * num_stages else: if num_layers >= 50: filter_list = [64, 256, 512, 1024, 2048] bottle_neck = True else: filter_list = [64, 64, 128, 256, 512] bottle_neck = False num_stages = 4 if num_layers == 18: units = [2, 2, 2, 2] elif num_layers == 34: units = [3, 4, 6, 3] elif num_layers == 50: units = [3, 4, 6, 3] elif num_layers == 101: units = [3, 4, 23, 3] elif num_layers == 152: units = [3, 8, 36, 3] elif num_layers == 200: units = [3, 24, 36, 3] elif num_layers == 269: units = [3, 30, 48, 8] else: raise ValueError("no experiments done on num_layers {}, you can do it youself".format(num_layers)) return resnet(units = units, num_stages = num_stages, filter_list = filter_list, num_classes = num_classes, image_shape = image_shape, bottle_neck = bottle_neck, workspace = conv_workspace)
coder-james/mxnet
example/image-classification/symbols/resnet-v1.py
Python
apache-2.0
8,907
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import socket import unittest import warnings from unittest import skipUnless from django.conf import settings from django.contrib.gis.geoip import HAS_GEOIP from django.contrib.gis.geos import HAS_GEOS, GEOSGeometry from django.test import ignore_warnings from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_text if HAS_GEOIP: from django.contrib.gis.geoip import GeoIP, GeoIPException from django.contrib.gis.geoip.prototypes import GeoIP_lib_version # Note: Requires use of both the GeoIP country and city datasets. # The GEOIP_DATA path should be the only setting set (the directory # should contain links or the actual database files 'GeoIP.dat' and # 'GeoLiteCity.dat'. @skipUnless( HAS_GEOIP and getattr(settings, "GEOIP_PATH", None), "GeoIP is required along with the GEOIP_PATH setting." ) @ignore_warnings(category=RemovedInDjango20Warning) class GeoIPTest(unittest.TestCase): addr = '162.242.220.127' fqdn = 'www.djangoproject.com' def _is_dns_available(self, domain): # Naive check to see if there is DNS available to use. # Used to conditionally skip fqdn geoip checks. # See #25407 for details. ErrClass = socket.error if six.PY2 else OSError try: socket.gethostbyname(domain) return True except ErrClass: return False def test01_init(self): "Testing GeoIP initialization." g1 = GeoIP() # Everything inferred from GeoIP path path = settings.GEOIP_PATH g2 = GeoIP(path, 0) # Passing in data path explicitly. g3 = GeoIP.open(path, 0) # MaxMind Python API syntax. for g in (g1, g2, g3): self.assertTrue(g._country) self.assertTrue(g._city) # Only passing in the location of one database. city = os.path.join(path, 'GeoLiteCity.dat') cntry = os.path.join(path, 'GeoIP.dat') g4 = GeoIP(city, country='') self.assertIsNone(g4._country) g5 = GeoIP(cntry, city='') self.assertIsNone(g5._city) # Improper parameters. bad_params = (23, 'foo', 15.23) for bad in bad_params: with self.assertRaises(GeoIPException): GeoIP(cache=bad) if isinstance(bad, six.string_types): e = GeoIPException else: e = TypeError with self.assertRaises(e): GeoIP(bad, 0) def test02_bad_query(self): "Testing GeoIP query parameter checking." cntry_g = GeoIP(city='<foo>') # No city database available, these calls should fail. with self.assertRaises(GeoIPException): cntry_g.city('google.com') with self.assertRaises(GeoIPException): cntry_g.coords('yahoo.com') # Non-string query should raise TypeError with self.assertRaises(TypeError): cntry_g.country_code(17) with self.assertRaises(TypeError): cntry_g.country_name(GeoIP) def test03_country(self): "Testing GeoIP country querying methods." g = GeoIP(city='<foo>') queries = [self.addr] if self._is_dns_available(self.fqdn): queries.append(self.fqdn) for query in queries: for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query), 'Failed for func %s and query %s' % (func, query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual('United States', func(query), 'Failed for func %s and query %s' % (func, query)) self.assertEqual({'country_code': 'US', 'country_name': 'United States'}, g.country(query)) @skipUnless(HAS_GEOS, "Geos is required") def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country='<foo>') queries = [self.addr] if self._is_dns_available(self.fqdn): queries.append(self.fqdn) for query in queries: # Country queries should still work. for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual('United States', func(query)) self.assertEqual({'country_code': 'US', 'country_name': 'United States'}, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual('USA', d['country_code3']) self.assertEqual('San Antonio', d['city']) self.assertEqual('TX', d['region']) self.assertEqual(210, d['area_code']) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) lon, lat = (-98, 29) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 0) self.assertAlmostEqual(lat, tup[1], 0) def test05_unicode_response(self): "Testing that GeoIP strings are properly encoded, see #16553." g = GeoIP() fqdn = "messe-duesseldorf.com" if self._is_dns_available(fqdn): d = g.city(fqdn) self.assertEqual('Düsseldorf', d['city']) d = g.country('200.26.205.1') # Some databases have only unaccented countries self.assertIn(d['country_name'], ('Curaçao', 'Curacao')) def test_deprecation_warning(self): with warnings.catch_warnings(record=True) as warns: warnings.simplefilter('always') GeoIP() self.assertEqual(len(warns), 1) msg = str(warns[0].message) self.assertIn('django.contrib.gis.geoip is deprecated', msg) def test_repr(self): path = settings.GEOIP_PATH g = GeoIP(path=path) country_path = g._country_file city_path = g._city_file if GeoIP_lib_version: expected = '<GeoIP [v%(version)s] _country_file="%(country)s", _city_file="%(city)s">' % { 'version': force_text(GeoIP_lib_version()), 'country': country_path, 'city': city_path, } else: expected = '<GeoIP _country_file="%(country)s", _city_file="%(city)s">' % { 'country': country_path, 'city': city_path, } self.assertEqual(repr(g), expected)
cloudera/hue
desktop/core/ext-py/Django-1.11.29/tests/gis_tests/test_geoip.py
Python
apache-2.0
6,866
# # Unit Tests for the colors.py functions # # Rajul Srivastava (rajul09@gmail.com) # import unittest import logging import numpy as np import ginga.colors class TestError(Exception): pass class TestColors(unittest.TestCase): def setUp(self): self.logger = logging.getLogger("TestColors") self.color_list_length = len(ginga.colors.color_dict) # Tests for the lookup_color() funtion def test_lookup_color_white_tuple(self): expected = (1.0, 1.0, 1.0) actual = ginga.colors.lookup_color("white", "tuple") assert np.allclose(expected, actual) def test_lookup_color_black_tuple(self): expected = (0.0, 0.0, 0.0) actual = ginga.colors.lookup_color("black", "tuple") assert np.allclose(expected, actual) def test_lookup_color_white_hash(self): expected = "#ffffff" actual = ginga.colors.lookup_color("white", "hash") assert expected == actual def test_lookup_color_black_black(self): expected = "#000000" actual = ginga.colors.lookup_color("black", "hash") assert expected == actual def test_lookup_color_yellow_tuple(self): expected = (1.0, 1.0, 0.0) actual = ginga.colors.lookup_color("yellow") assert np.allclose(expected, actual) def test_lookup_color_unknown(self): self.assertRaises(KeyError, ginga.colors.lookup_color, "unknown_color") def test_lookup_color_raise_exception_unknown_key(self): self.assertRaises(KeyError, ginga.colors.lookup_color, "unknown_key") def test_lookup_color_raise_exception_unknown_format(self): self.assertRaises(ValueError, ginga.colors.lookup_color, "white", "unknown_format") # Tests for the get_colors() function def test_get_colors_len(self): expected = self.color_list_length actual = len(ginga.colors.get_colors()) assert expected == actual def test_add_and_get_colors_len(self): ginga.colors.add_color("test_color_white", (0.0, 0.0, 0.0)) expected = self.color_list_length + 1 actual = len(ginga.colors.get_colors()) assert expected == actual ginga.colors.remove_color("test_color_white") # Tests for the add_color() and remove_color() function def test_add_and_remove_color_len(self): ginga.colors.add_color("test_color_white", (0.0, 0.0, 0.0)) expected = self.color_list_length + 1 actual = len(ginga.colors.color_dict) assert expected == actual expected = len(ginga.colors.color_dict) actual = len(ginga.colors.color_list) assert expected == actual ginga.colors.remove_color("test_color_white") expected = self.color_list_length actual = len(ginga.colors.color_dict) assert expected == actual expected = len(ginga.colors.color_dict) actual = len(ginga.colors.color_list) assert expected == actual def test_add_and_remove_color_rbg(self): ginga.colors.add_color("test_color_white", (0.0, 0.0, 0.0)) expected = (0.0, 0.0, 0.0) actual = ginga.colors.lookup_color("test_color_white") assert np.allclose(expected, actual) ginga.colors.remove_color("test_color_white") self.assertRaises(KeyError, ginga.colors.remove_color, "test_color_white") def test_add_color_wrong_rbg_type(self): self.assertRaises(TypeError, ginga.colors.add_color, "white", "string_wrong_format") def test_add_color_wrong_rbg_values(self): self.assertRaises(ValueError, ginga.colors.add_color, "test_color", (-1.0, 0.0, 0.0)) def test_add_color_wrong_tuple_length(self): self.assertRaises(ValueError, ginga.colors.add_color, "test_color", (0.0, 0.0)) def test_remove_color_unknown(self): self.assertRaises(KeyError, ginga.colors.remove_color, "unknown_color") # Tests for recalc_color_list() function def test_recalc_color_list(self): ginga.colors.color_dict["test_color_white"] = (0.0, 0.0, 0.0) expected = len(ginga.colors.color_dict) - 1 actual = len(ginga.colors.color_list) assert expected == actual ginga.colors.recalc_color_list() expected = len(ginga.colors.color_dict) actual = len(ginga.colors.color_list) assert expected == actual del ginga.colors.color_dict["test_color_white"] expected = len(ginga.colors.color_dict) + 1 actual = len(ginga.colors.color_list) assert expected == actual ginga.colors.recalc_color_list() expected = len(ginga.colors.color_dict) actual = len(ginga.colors.color_list) assert expected == actual # Tests for scan_rgbtxt_buf() function def test_scan_rgbtxt_buf(self): test_rgb_lines = ''' 255 255 255 white 0 0 0 black 255 0 0 red 0 255 0 green 0 0 255 blue ''' result = ginga.colors.scan_rgbtxt_buf(test_rgb_lines) assert isinstance(result, dict) expected = 5 actual = len(result) assert expected == actual expected = (1.0, 1.0, 1.0) actual = result["white"] assert np.allclose(expected, actual) def tearDown(self): pass if __name__ == '__main__': unittest.main() #END
rupak0577/ginga
ginga/tests/test_colors.py
Python
bsd-3-clause
4,797
from __future__ import division, print_function, absolute_import import sys from numpy.testing import * import numpy.linalg as linalg def random(size): return rand(*size) class TestSolve(TestCase): def bench_random(self): basic_solve = linalg.solve print() print(' Solving system of linear equations') print(' ==================================') print(' | contiguous | non-contiguous ') print('----------------------------------------------') print(' size | scipy | basic | scipy | basic ') for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print('%5s' % size, end=' ') sys.stdout.flush() a = random([size,size]) # larger diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i]) b = random([size]) print('| %6.2f ' % measure('solve(a,b)',repeat), end=' ') sys.stdout.flush() print('| %6.2f ' % measure('basic_solve(a,b)',repeat), end=' ') sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert_(not a.flags['CONTIGUOUS']) print('| %6.2f ' % measure('solve(a,b)',repeat), end=' ') sys.stdout.flush() print('| %6.2f ' % measure('basic_solve(a,b)',repeat), end=' ') sys.stdout.flush() print(' (secs for %s calls)' % (repeat)) class TestInv(TestCase): def bench_random(self): basic_inv = linalg.inv print() print(' Finding matrix inverse') print(' ==================================') print(' | contiguous | non-contiguous ') print('----------------------------------------------') print(' size | scipy | basic | scipy | basic') for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print('%5s' % size, end=' ') sys.stdout.flush() a = random([size,size]) # large diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i]) print('| %6.2f ' % measure('inv(a)',repeat), end=' ') sys.stdout.flush() print('| %6.2f ' % measure('basic_inv(a)',repeat), end=' ') sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert_(not a.flags['CONTIGUOUS']) print('| %6.2f ' % measure('inv(a)',repeat), end=' ') sys.stdout.flush() print('| %6.2f ' % measure('basic_inv(a)',repeat), end=' ') sys.stdout.flush() print(' (secs for %s calls)' % (repeat)) class TestDet(TestCase): def bench_random(self): basic_det = linalg.det print() print(' Finding matrix determinant') print(' ==================================') print(' | contiguous | non-contiguous ') print('----------------------------------------------') print(' size | scipy | basic | scipy | basic ') for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print('%5s' % size, end=' ') sys.stdout.flush() a = random([size,size]) print('| %6.2f ' % measure('det(a)',repeat), end=' ') sys.stdout.flush() print('| %6.2f ' % measure('basic_det(a)',repeat), end=' ') sys.stdout.flush() a = a[-1::-1,-1::-1] # turn into a non-contiguous array assert_(not a.flags['CONTIGUOUS']) print('| %6.2f ' % measure('det(a)',repeat), end=' ') sys.stdout.flush() print('| %6.2f ' % measure('basic_det(a)',repeat), end=' ') sys.stdout.flush() print(' (secs for %s calls)' % (repeat)) if __name__ == "__main__": run_module_suite()
sargas/scipy
scipy/linalg/benchmarks/bench_basic.py
Python
bsd-3-clause
4,065
import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.shortcuts import redirect from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date class SessionMiddleware(object): def __init__(self): engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore def process_request(self, request): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) request.session = self.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: pass else: # First check if we need to delete this cookie. # The session should be deleted only if the session is entirely empty if settings.SESSION_COOKIE_NAME in request.COOKIES and empty: response.delete_cookie(settings.SESSION_COOKIE_NAME, domain=settings.SESSION_COOKIE_DOMAIN) else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = cookie_date(expires_time) # Save the session data and refresh the client cookie. # Skip session save for 500 responses, refs #3881. if response.status_code != 500: try: request.session.save() except UpdateError: # The user is now logged out; redirecting to same # page will result in a redirect to the login page # if required. return redirect(request.path) response.set_cookie(settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None) return response
vincepandolfo/django
django/contrib/sessions/middleware.py
Python
bsd-3-clause
3,093
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import absolute_import from .build_response import BuildResponse # noqa from .pod_response import PodResponse # noqa
bfontecc007/osbs-client
osbs/build/__init__.py
Python
bsd-3-clause
314
""" ========================================================================= 2 samples permutation test on source data with spatio-temporal clustering ========================================================================= Tests if the source space data are significantly different between 2 groups of subjects (simulated here using one subject's data). The multiple comparisons problem is addressed with a cluster-level permutation test across space and time. """ # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import os.path as op import numpy as np from scipy import stats as stats import mne from mne import spatial_src_connectivity from mne.stats import spatio_temporal_cluster_test, summarize_clusters_stc from mne.datasets import sample print(__doc__) ############################################################################### # Set parameters # -------------- data_path = sample.data_path() stc_fname = data_path + '/MEG/sample/sample_audvis-meg-lh.stc' subjects_dir = data_path + '/subjects' src_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif' # Load stc to in common cortical space (fsaverage) stc = mne.read_source_estimate(stc_fname) stc.resample(50, npad='auto') # Read the source space we are morphing to src = mne.read_source_spaces(src_fname) fsave_vertices = [s['vertno'] for s in src] stc = mne.morph_data('sample', 'fsaverage', stc, grade=fsave_vertices, smooth=20, subjects_dir=subjects_dir) n_vertices_fsave, n_times = stc.data.shape tstep = stc.tstep n_subjects1, n_subjects2 = 7, 9 print('Simulating data for %d and %d subjects.' % (n_subjects1, n_subjects2)) # Let's make sure our results replicate, so set the seed. np.random.seed(0) X1 = np.random.randn(n_vertices_fsave, n_times, n_subjects1) * 10 X2 = np.random.randn(n_vertices_fsave, n_times, n_subjects2) * 10 X1[:, :, :] += stc.data[:, :, np.newaxis] # make the activity bigger for the second set of subjects X2[:, :, :] += 3 * stc.data[:, :, np.newaxis] # We want to compare the overall activity levels for each subject X1 = np.abs(X1) # only magnitude X2 = np.abs(X2) # only magnitude ############################################################################### # Compute statistic # ----------------- # # To use an algorithm optimized for spatio-temporal clustering, we # just pass the spatial connectivity matrix (instead of spatio-temporal) print('Computing connectivity.') connectivity = spatial_src_connectivity(src) # Note that X needs to be a list of multi-dimensional array of shape # samples (subjects_k) x time x space, so we permute dimensions X1 = np.transpose(X1, [2, 1, 0]) X2 = np.transpose(X2, [2, 1, 0]) X = [X1, X2] # Now let's actually do the clustering. This can take a long time... # Here we set the threshold quite high to reduce computation. p_threshold = 0.0001 f_threshold = stats.distributions.f.ppf(1. - p_threshold / 2., n_subjects1 - 1, n_subjects2 - 1) print('Clustering.') T_obs, clusters, cluster_p_values, H0 = clu =\ spatio_temporal_cluster_test(X, connectivity=connectivity, n_jobs=1, threshold=f_threshold) # Now select the clusters that are sig. at p < 0.05 (note that this value # is multiple-comparisons corrected). good_cluster_inds = np.where(cluster_p_values < 0.05)[0] ############################################################################### # Visualize the clusters # ---------------------- print('Visualizing clusters.') # Now let's build a convenient representation of each cluster, where each # cluster becomes a "time point" in the SourceEstimate fsave_vertices = [np.arange(10242), np.arange(10242)] stc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep, vertices=fsave_vertices, subject='fsaverage') # Let's actually plot the first "time point" in the SourceEstimate, which # shows all the clusters, weighted by duration subjects_dir = op.join(data_path, 'subjects') # blue blobs are for condition A != condition B brain = stc_all_cluster_vis.plot('fsaverage', hemi='both', colormap='mne', views='lateral', subjects_dir=subjects_dir, time_label='Duration significant (ms)') brain.save_image('clusters.png')
teonlamont/mne-python
tutorials/plot_stats_cluster_spatio_temporal_2samp.py
Python
bsd-3-clause
4,494
from __future__ import print_function import side_effect def useless_function(first, second): print("I have the wrong number of arguments.") def function(frame, bp_loc, dict): side_effect.bktptcmd = "function was here" def another_function(frame, bp_loc, extra_args, dict): se_value = extra_args.GetValueForKey("side_effect") se_string = se_value.GetStringValue(100) side_effect.fancy = se_string def a_third_function(frame, bp_loc, extra_args, dict): se_value = extra_args.GetValueForKey("side_effect") se_string = se_value.GetStringValue(100) side_effect.fancier = se_string def empty_extra_args(frame, bp_loc, extra_args, dict): if extra_args.IsValid(): side_effect.not_so_fancy = "Extra args should not be valid" side_effect.not_so_fancy = "Not so fancy"
endlessm/chromium-browser
third_party/llvm/lldb/test/API/functionalities/breakpoint/breakpoint_command/bktptcmd.py
Python
bsd-3-clause
812
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import logging import time from flexget import plugin from flexget.event import event from flexget.utils.log import log_once from flexget.utils.titles.movie import MovieParser from flexget.utils.titles.series import SeriesParser from .parser_common import ParseWarning log = logging.getLogger('parser_internal') class ParserInternal(object): # movie_parser API @plugin.priority(1) def parse_movie(self, data, **kwargs): log.debug('Parsing movie: `%s` kwargs: %s', data, kwargs) start = time.clock() parser = MovieParser() try: parser.parse(data) except ParseWarning as pw: log_once(pw.value, logger=log) end = time.clock() log.debug('Parsing result: %s (in %s ms)', parser, (end - start) * 1000) return parser # series_parser API @plugin.priority(1) def parse_series(self, data, **kwargs): log.debug('Parsing series: `%s` kwargs: %s', data, kwargs) start = time.clock() parser = SeriesParser(**kwargs) try: parser.parse(data) except ParseWarning as pw: log_once(pw.value, logger=log) end = time.clock() log.debug('Parsing result: %s (in %s ms)', parser, (end - start) * 1000) return parser @event('plugin.register') def register_plugin(): plugin.register(ParserInternal, 'parser_internal', interfaces=['movie_parser', 'series_parser'], api_ver=2)
qk4l/Flexget
flexget/plugins/parsers/parser_internal.py
Python
mit
1,607
import inspect from biicode.client.shell.biistream import Color class ToolCatalog(dict): def __init__(self, main_class, tools): dict.__init__(self) self.main_class = main_class # dict from tool group name to set of classes for c in tools: self[c.group] = c self.show_advanced = False def _get_doc_short(self, doc): return doc.split('\n', 1)[0] def print_help(self, out, argv): out.writeln('\nSYNOPSIS:', Color.YELLOW) out.writeln(' $ bii COMMAND [options]') out.writeln('For help about a command:', Color.YELLOW) out.writeln(' $ bii COMMAND --help') out.write('To change verbosity, use options ', Color.YELLOW) out.writeln('--quiet --verbose\n') if not argv or 'all' in argv: out.writeln('--------- Global Commands ----------', Color.YELLOW) for m in inspect.getmembers(self.main_class, predicate=inspect.ismethod): method_name = m[0] if not method_name.startswith('_'): method = m[1] if not method.__doc__.startswith(' ADVANCED'): doc = method.__doc__ out.write(' %-10s' % method_name, Color.GREEN) out.writeln(self._get_doc_short(doc)) elif self.show_advanced: doc = method.__doc__.replace(' ADVANCED', '') out.write(' %-10s' % method_name, Color.GREEN) out.writeln(self._get_doc_short(doc)) if not argv: out.writeln('\n--------- Tools ----------', Color.YELLOW) out.writeln('For help about one or more tools ("all" for all):', Color.YELLOW) out.writeln(' $ bii --help TOOL [TOOL2]\n') for group, class_ in self.iteritems(): out.write(' %-10s ' % class_.group, Color.GREEN) out.writeln(class_.__doc__) else: # Tools, as main commands for group, class_ in self.iteritems(): if group not in argv and 'all' not in argv: continue out.writeln('---------%s--------' % class_.__doc__, Color.YELLOW) for m in inspect.getmembers(class_, predicate=inspect.ismethod): method_name = m[0] method = m[1] if method.__doc__: method_doc = self._get_doc_short(method.__doc__) if not method_name.startswith('_') and not method_doc.startswith('HIDDEN'): com = '%s:%s' % (group, method_name) out.write(' %-15s ' % com, Color.GREEN) out.writeln(method_doc)
drodri/client
command/tool_catalog.py
Python
mit
2,824
""" Support for functionality to have conversations with Home Assistant. For more details about this component, please refer to the documentation at https://home-assistant.io/components/conversation/ """ import logging import re import warnings import voluptuous as vol from homeassistant import core from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON) import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['fuzzywuzzy==0.12.0'] ATTR_TEXT = 'text' DOMAIN = 'conversation' REGEX_TURN_COMMAND = re.compile(r'turn (?P<name>(?: |\w)+) (?P<command>\w+)') SERVICE_PROCESS = 'process' SERVICE_PROCESS_SCHEMA = vol.Schema({ vol.Required(ATTR_TEXT): vol.All(cv.string, vol.Lower), }) CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({}), }, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Register the process service.""" warnings.filterwarnings('ignore', module='fuzzywuzzy') from fuzzywuzzy import process as fuzzyExtract logger = logging.getLogger(__name__) def process(service): """Parse text into commands.""" text = service.data[ATTR_TEXT] match = REGEX_TURN_COMMAND.match(text) if not match: logger.error("Unable to process: %s", text) return name, command = match.groups() entities = {state.entity_id: state.name for state in hass.states.all()} entity_ids = fuzzyExtract.extractOne( name, entities, score_cutoff=65)[2] if not entity_ids: logger.error( "Could not find entity id %s from text %s", name, text) return if command == 'on': hass.services.call(core.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: entity_ids, }, blocking=True) elif command == 'off': hass.services.call(core.DOMAIN, SERVICE_TURN_OFF, { ATTR_ENTITY_ID: entity_ids, }, blocking=True) else: logger.error('Got unsupported command %s from text %s', command, text) hass.services.register( DOMAIN, SERVICE_PROCESS, process, schema=SERVICE_PROCESS_SCHEMA) return True
leoc/home-assistant
homeassistant/components/conversation.py
Python
mit
2,231
#!/usr/bin/python 'Finite difference RTM as a linear operator' import os, sys, tempfile, subprocess import rsf.prog, rsf.path # Madagascar bin directory bindir=os.path.join(rsf.prog.RSFROOT,'bin') # Madagascar DATAPATH datapath=rsf.path.datapath().rstrip('/') # Madagascar commands cp=os.path.join(bindir,'sfcp') rtm=os.path.join(bindir,'sfmpifdlsrtm') # Random files for input and output inpd,inpfile=tempfile.mkstemp(dir=datapath) outd,outfile=tempfile.mkstemp(dir=datapath) p=subprocess.Popen([cp],stdout=inpd, close_fds=True) p.wait() run='ibrun tacc_affinity %s input=%s output=%s %s' %(rtm, inpfile, outfile,' '.join(sys.argv[1:])) print run os.system(run) p=subprocess.Popen([cp],stdin=outd) p.wait
TobbeTripitaka/src
user/zhiguang/Mfdlsrtm.py
Python
gpl-2.0
715
#!/usr/bin/python3 # This script will compare the versions of ebuilds in the funtoo portage tree against # the versions of ebuilds in the target portage tree. Any higher versions in the # target Portage tree will be printed to stdout. import portage.versions import os,sys import subprocess import json from merge_utils import * dirpath = os.path.dirname(os.path.realpath(__file__)) print("List of differences between funtoo and gentoo") print("=============================================") def getKeywords(portdir, ebuild, warn): a = subprocess.getstatusoutput(dirpath + "/keywords.sh %s %s" % ( portdir, ebuild ) ) if a[0] == 0: my_set = set(a[1].split()) return (0, my_set) else: return a if len(sys.argv) != 3: print("Please specify funtoo tree as first argument, gentoo tree as second argument.") sys.exit(1) gportdir=sys.argv[2] portdir=sys.argv[1] def filterOnKeywords(portdir, ebuilds, keywords, warn=False): """ This function accepts a path to a portage tree, a list of ebuilds, and a list of keywords. It will iteratively find the "best" version in the ebuild list (the most recent), and then manually extract this ebuild's KEYWORDS using the getKeywords() function. If at least one of the keywords in "keywords" cannot be found in the ebuild's KEYWORDS, then the ebuild is removed from the return list. Think of this function as "skimming the masked cream off the top" of a particular set of ebuilds. This way our list has been filtered somewhat and we don't have gcc-6.0 in our list just because someone added it masked to the tree. It makes comparisons fairer. """ filtered = ebuilds[:] if len(ebuilds) == 0: return [] cps = portage.versions.catpkgsplit(filtered[0]) cat = cps[0] pkg = cps[1] keywords = set(keywords) while True: fbest = portage.versions.best(filtered) if fbest == "": break retval, fkeywords = getKeywords(portdir, "%s/%s/%s.ebuild" % (cat, pkg, fbest.split("/")[1] ), warn) if len(keywords & fkeywords) == 0: filtered.remove(fbest) else: break return filtered def get_cpv_in_portdir(portdir,cat,pkg): if not os.path.exists("%s/%s/%s" % (portdir, cat, pkg)): return [] if not os.path.isdir("%s/%s/%s" % (portdir, cat, pkg)): return [] files = os.listdir("%s/%s/%s" % (portdir, cat, pkg)) ebuilds = [] for file in files: if file[-7:] == ".ebuild": ebuilds.append("%s/%s" % (cat, file[:-7])) return ebuilds def version_compare(portdir,gportdir,keywords,label): print print("Package comparison for %s" % keywords) print("============================================") print("(note that package.{un}mask(s) are ignored - looking at ebuilds only)") print for cat in os.listdir(portdir): if cat == ".git": continue if not os.path.exists(gportdir+"/"+cat): continue if not os.path.isdir(gportdir+"/"+cat): continue for pkg in os.listdir(os.path.join(portdir,cat)): ebuilds = get_cpv_in_portdir(portdir,cat,pkg) gebuilds =get_cpv_in_portdir(gportdir,cat,pkg) ebuilds = filterOnKeywords(portdir, ebuilds, keywords, warn=True) if len(ebuilds) == 0: continue fbest = portage.versions.best(ebuilds) gebuilds = filterOnKeywords(gportdir, gebuilds, keywords, warn=False) if len(gebuilds) == 0: continue gbest = portage.versions.best(gebuilds) if fbest == gbest: continue # a little trickery to ignore rev differences: fps = list(portage.versions.catpkgsplit(fbest))[1:] gps = list(portage.versions.catpkgsplit(gbest))[1:] gps[-1] = "r0" fps[-1] = "r0" if gps[-2] in [ "9999", "99999", "999999", "9999999", "99999999"]: continue mycmp = portage.versions.pkgcmp(fps, gps) if mycmp == -1: json_out[label].append("%s/%s %s %s" % (cat, pkg, gbest[len(cat)+len(pkg)+2:], fbest[len(cat)+len(pkg)+2:])) print("%s (vs. %s in funtoo)" % ( gbest, fbest )) json_out={} for keyw in [ "~amd64" ]: if keyw == "~x86": label = "fcx8632" elif keyw == "~amd64": label = "fcx8664" json_out[label] = [] if keyw[0] == "~": # for unstable, add stable arch and ~* and * keywords too keyw = [ keyw, keyw[1:], "~*", "*"] else: # for stable, also consider the * keyword keyw = [ keyw, "*"] version_compare(portdir,gportdir,keyw,label) for key in json_out: json_out[key].sort() json_out[key] = ",".join(json_out[key]) jsonfile = "/home/ports/public_html/my.json" a = open(jsonfile, 'w') json.dump(json_out, a, sort_keys=True, indent=4, separators=(',',": ")) a.close() print("Wrote output to %s" % jsonfile)
Tassie-Tux/funtoo-overlay
funtoo/scripts/gentoo-compare-json.py
Python
gpl-2.0
4,518
import random import struct ######################################################################################################################## class base_primitive (object): ''' The primitive base class implements common functionality shared across most primitives. ''' def __init__ (self): self.fuzz_complete = False # this flag is raised when the mutations are exhausted. self.fuzz_library = [] # library of static fuzz heuristics to cycle through. self.fuzzable = True # flag controlling whether or not the given primitive is to be fuzzed. self.mutant_index = 0 # current mutation index into the fuzz library. self.original_value = None # original value of primitive. self.rendered = "" # rendered value of primitive. self.value = None # current value of primitive. def exhaust (self): ''' Exhaust the possible mutations for this primitive. @rtype: Integer @return: The number of mutations to reach exhaustion ''' num = self.num_mutations() - self.mutant_index self.fuzz_complete = True self.mutant_index = self.num_mutations() self.value = self.original_value return num def mutate (self): ''' Mutate the primitive by stepping through the fuzz library, return False on completion. @rtype: Boolean @return: True on success, False otherwise. ''' # if we've ran out of mutations, raise the completion flag. if self.mutant_index == self.num_mutations(): self.fuzz_complete = True # if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored. if not self.fuzzable or self.fuzz_complete: self.value = self.original_value return False # update the current value from the fuzz library. self.value = self.fuzz_library[self.mutant_index] # increment the mutation count. self.mutant_index += 1 return True def num_mutations (self): ''' Calculate and return the total number of mutations for this individual primitive. @rtype: Integer @return: Number of mutated forms this primitive can take ''' return len(self.fuzz_library) def render (self): ''' Nothing fancy on render, simply return the value. ''' self.rendered = self.value return self.rendered def reset (self): ''' Reset this primitive to the starting mutation state. ''' self.fuzz_complete = False self.mutant_index = 0 self.value = self.original_value ######################################################################################################################## class delim (base_primitive): def __init__ (self, value, fuzzable=True, name=None): ''' Represent a delimiter such as :,\r,\n, ,=,>,< etc... Mutations include repetition, substitution and exclusion. @type value: Character @param value: Original value @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' self.value = self.original_value = value self.fuzzable = fuzzable self.name = name self.s_type = "delim" # for ease of object identification self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.fuzz_library = [] # library of fuzz heuristics self.mutant_index = 0 # current mutation number # # build the library of fuzz heuristics. # # if the default delim is not blank, repeat it a bunch of times. if self.value: self.fuzz_library.append(self.value * 2) self.fuzz_library.append(self.value * 5) self.fuzz_library.append(self.value * 10) self.fuzz_library.append(self.value * 25) self.fuzz_library.append(self.value * 100) self.fuzz_library.append(self.value * 500) self.fuzz_library.append(self.value * 1000) # try ommitting the delimiter. self.fuzz_library.append("") # if the delimiter is a space, try throwing out some tabs. if self.value == " ": self.fuzz_library.append("\t") self.fuzz_library.append("\t" * 2) self.fuzz_library.append("\t" * 100) # toss in some other common delimiters: self.fuzz_library.append(" ") self.fuzz_library.append("\t") self.fuzz_library.append("\t " * 100) self.fuzz_library.append("\t\r\n" * 100) self.fuzz_library.append("!") self.fuzz_library.append("@") self.fuzz_library.append("#") self.fuzz_library.append("$") self.fuzz_library.append("%") self.fuzz_library.append("^") self.fuzz_library.append("&") self.fuzz_library.append("*") self.fuzz_library.append("(") self.fuzz_library.append(")") self.fuzz_library.append("-") self.fuzz_library.append("_") self.fuzz_library.append("+") self.fuzz_library.append("=") self.fuzz_library.append(":") self.fuzz_library.append(": " * 100) self.fuzz_library.append(":7" * 100) self.fuzz_library.append(";") self.fuzz_library.append("'") self.fuzz_library.append("\"") self.fuzz_library.append("/") self.fuzz_library.append("\\") self.fuzz_library.append("?") self.fuzz_library.append("<") self.fuzz_library.append(">") self.fuzz_library.append(".") self.fuzz_library.append(",") self.fuzz_library.append("\r") self.fuzz_library.append("\n") self.fuzz_library.append("\r\n" * 64) self.fuzz_library.append("\r\n" * 128) self.fuzz_library.append("\r\n" * 512) ######################################################################################################################## class group (base_primitive): def __init__ (self, name, values): ''' This primitive represents a list of static values, stepping through each one on mutation. You can tie a block to a group primitive to specify that the block should cycle through all possible mutations for *each* value within the group. The group primitive is useful for example for representing a list of valid opcodes. @type name: String @param name: Name of group @type values: List or raw data @param values: List of possible raw values this group can take. ''' self.name = name self.values = values self.fuzzable = True self.s_type = "group" self.value = self.values[0] self.original_value = self.values[0] self.rendered = "" self.fuzz_complete = False self.mutant_index = 0 # sanity check that values list only contains strings (or raw data) if self.values != []: for val in self.values: assert type(val) is str, "Value list may only contain strings or raw data" def mutate (self): ''' Move to the next item in the values list. @rtype: False @return: False ''' if self.mutant_index == self.num_mutations(): self.fuzz_complete = True # if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored. if not self.fuzzable or self.fuzz_complete: self.value = self.values[0] return False # step through the value list. self.value = self.values[self.mutant_index] # increment the mutation count. self.mutant_index += 1 return True def num_mutations (self): ''' Number of values in this primitive. @rtype: Integer @return: Number of values in this primitive. ''' return len(self.values) ######################################################################################################################## class random_data (base_primitive): def __init__ (self, value, min_length, max_length, max_mutations=25, fuzzable=True, step=None, name=None): ''' Generate a random chunk of data while maintaining a copy of the original. A random length range can be specified. For a static length, set min/max length to be the same. @type value: Raw @param value: Original value @type min_length: Integer @param min_length: Minimum length of random block @type max_length: Integer @param max_length: Maximum length of random block @type max_mutations: Integer @param max_mutations: (Optional, def=25) Number of mutations to make before reverting to default @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type step: Integer @param step: (Optional, def=None) If not null, step count between min and max reps, otherwise random @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' self.value = self.original_value = str(value) self.min_length = min_length self.max_length = max_length self.max_mutations = max_mutations self.fuzzable = fuzzable self.step = step self.name = name self.s_type = "random_data" # for ease of object identification self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.mutant_index = 0 # current mutation number if self.step: self.max_mutations = (self.max_length - self.min_length) / self.step + 1 def mutate (self): ''' Mutate the primitive value returning False on completion. @rtype: Boolean @return: True on success, False otherwise. ''' # if we've ran out of mutations, raise the completion flag. if self.mutant_index == self.num_mutations(): self.fuzz_complete = True # if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored. if not self.fuzzable or self.fuzz_complete: self.value = self.original_value return False # select a random length for this string. if not self.step: length = random.randint(self.min_length, self.max_length) # select a length function of the mutant index and the step. else: length = self.min_length + self.mutant_index * self.step # reset the value and generate a random string of the determined length. self.value = "" for i in xrange(length): self.value += chr(random.randint(0, 255)) # increment the mutation count. self.mutant_index += 1 return True def num_mutations (self): ''' Calculate and return the total number of mutations for this individual primitive. @rtype: Integer @return: Number of mutated forms this primitive can take ''' return self.max_mutations ######################################################################################################################## class static (base_primitive): def __init__ (self, value, name=None): ''' Primitive that contains static content. @type value: Raw @param value: Raw static data @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' self.value = self.original_value = value self.name = name self.fuzzable = False # every primitive needs this attribute. self.mutant_index = 0 self.s_type = "static" # for ease of object identification self.rendered = "" self.fuzz_complete = True def mutate (self): ''' Do nothing. @rtype: False @return: False ''' return False def num_mutations (self): ''' Return 0. @rtype: 0 @return: 0 ''' return 0 ######################################################################################################################## class string (base_primitive): # store fuzz_library as a class variable to avoid copying the ~70MB structure across each instantiated primitive. fuzz_library = [] def __init__ (self, value, size=-1, padding="\x00", encoding="ascii", fuzzable=True, max_len=0, name=None): ''' Primitive that cycles through a library of "bad" strings. The class variable 'fuzz_library' contains a list of smart fuzz values global across all instances. The 'this_library' variable contains fuzz values specific to the instantiated primitive. This allows us to avoid copying the near ~70MB fuzz_library data structure across each instantiated primitive. @type value: String @param value: Default string value @type size: Integer @param size: (Optional, def=-1) Static size of this field, leave -1 for dynamic. @type padding: Character @param padding: (Optional, def="\\x00") Value to use as padding to fill static field size. @type encoding: String @param encoding: (Optonal, def="ascii") String encoding, ex: utf_16_le for Microsoft Unicode. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type max_len: Integer @param max_len: (Optional, def=0) Maximum string length @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' self.value = self.original_value = value self.size = size self.padding = padding self.encoding = encoding self.fuzzable = fuzzable self.name = name self.s_type = "string" # for ease of object identification self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.mutant_index = 0 # current mutation number # add this specific primitives repitition values to the unique fuzz library. self.this_library = \ [ self.value * 2, self.value * 10, self.value * 100, # UTF-8 self.value * 2 + "\xfe", self.value * 10 + "\xfe", self.value * 100 + "\xfe", ] # if the fuzz library has not yet been initialized, do so with all the global values. if not self.fuzz_library: string.fuzz_library = \ [ # omission. "", # strings ripped from spike (and some others I added) "/.:/" + "A"*5000 + "\x00\x00", "/.../" + "A"*5000 + "\x00\x00", "/.../.../.../.../.../.../.../.../.../.../", "/../../../../../../../../../../../../etc/passwd", "/../../../../../../../../../../../../boot.ini", "..:..:..:..:..:..:..:..:..:..:..:..:..:", "\\\\*", "\\\\?\\", "/\\" * 5000, "/." * 5000, "!@#$%%^#$%#$@#$%$$@#$%^^**(()", "%01%02%03%04%0a%0d%0aADSF", "%01%02%03@%04%0a%0d%0aADSF", "/%00/", "%00/", "%00", "%u0000", "%\xfe\xf0%\x00\xff", "%\xfe\xf0%\x01\xff" * 20, # format strings. "%n" * 100, "%n" * 500, "\"%n\"" * 500, "%s" * 100, "%s" * 500, "\"%s\"" * 500, # command injection. "|touch /tmp/SULLEY", ";touch /tmp/SULLEY;", "|notepad", ";notepad;", "\nnotepad\n", # SQL injection. "1;SELECT%20*", "'sqlattempt1", "(sqlattempt2)", "OR%201=1", # some binary strings. "\xde\xad\xbe\xef", "\xde\xad\xbe\xef" * 10, "\xde\xad\xbe\xef" * 100, "\xde\xad\xbe\xef" * 1000, "\xde\xad\xbe\xef" * 10000, "\x00" * 1000, # miscellaneous. "\r\n" * 100, "<>" * 500, # sendmail crackaddr (http://lsd-pl.net/other/sendmail.txt) ] # add some long strings. self.add_long_strings("A") self.add_long_strings("B") self.add_long_strings("1") self.add_long_strings("2") self.add_long_strings("3") self.add_long_strings("<") self.add_long_strings(">") self.add_long_strings("'") self.add_long_strings("\"") self.add_long_strings("/") self.add_long_strings("\\") self.add_long_strings("?") self.add_long_strings("=") self.add_long_strings("a=") self.add_long_strings("&") self.add_long_strings(".") self.add_long_strings(",") self.add_long_strings("(") self.add_long_strings(")") self.add_long_strings("]") self.add_long_strings("[") self.add_long_strings("%") self.add_long_strings("*") self.add_long_strings("-") self.add_long_strings("+") self.add_long_strings("{") self.add_long_strings("}") self.add_long_strings("\x14") self.add_long_strings("\xFE") # expands to 4 characters under utf16 self.add_long_strings("\xFF") # expands to 4 characters under utf16 # add some long strings with null bytes thrown in the middle of it. for length in [128, 256, 1024, 2048, 4096, 32767, 0xFFFF]: s = "B" * length s = s[:len(s)/2] + "\x00" + s[len(s)/2:] string.fuzz_library.append(s) # if the optional file '.fuzz_strings' is found, parse each line as a new entry for the fuzz library. try: fh = open(".fuzz_strings", "r") for fuzz_string in fh.readlines(): fuzz_string = fuzz_string.rstrip("\r\n") if fuzz_string != "": string.fuzz_library.append(fuzz_string) fh.close() except: pass # delete strings which length is greater than max_len. if max_len > 0: if any(len(s) > max_len for s in self.this_library): self.this_library = list(set([s[:max_len] for s in self.this_library])) if any(len(s) > max_len for s in self.fuzz_library): self.fuzz_library = list(set([s[:max_len] for s in self.fuzz_library])) def add_long_strings (self, sequence): ''' Given a sequence, generate a number of selectively chosen strings lengths of the given sequence and add to the string heuristic library. @type sequence: String @param sequence: Sequence to repeat for creation of fuzz strings. ''' for length in [128, 255, 256, 257, 511, 512, 513, 1023, 1024, 2048, 2049, 4095, 4096, 4097, 5000, 10000, 20000, 32762, 32763, 32764, 32765, 32766, 32767, 32768, 32769, 0xFFFF-2, 0xFFFF-1, 0xFFFF, 0xFFFF+1, 0xFFFF+2, 99999, 100000, 500000, 1000000]: long_string = sequence * length string.fuzz_library.append(long_string) def mutate (self): ''' Mutate the primitive by stepping through the fuzz library extended with the "this" library, return False on completion. @rtype: Boolean @return: True on success, False otherwise. ''' # loop through the fuzz library until a suitable match is found. while 1: # if we've ran out of mutations, raise the completion flag. if self.mutant_index == self.num_mutations(): self.fuzz_complete = True # if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored. if not self.fuzzable or self.fuzz_complete: self.value = self.original_value return False # update the current value from the fuzz library. self.value = (self.fuzz_library + self.this_library)[self.mutant_index] # increment the mutation count. self.mutant_index += 1 # if the size parameter is disabled, break out of the loop right now. if self.size == -1: break # ignore library items greather then user-supplied length. # TODO: might want to make this smarter. if len(self.value) > self.size: continue # pad undersized library items. if len(self.value) < self.size: self.value = self.value + self.padding * (self.size - len(self.value)) break return True def num_mutations (self): ''' Calculate and return the total number of mutations for this individual primitive. @rtype: Integer @return: Number of mutated forms this primitive can take ''' return len(self.fuzz_library) + len(self.this_library) def render (self): ''' Render the primitive, encode the string according to the specified encoding. ''' # try to encode the string properly and fall back to the default value on failure. try: self.rendered = str(self.value).encode(self.encoding) except: self.rendered = self.value return self.rendered ######################################################################################################################## class bit_field (base_primitive): def __init__ (self, value, width, max_num=None, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None): ''' The bit field primitive represents a number of variable length and is used to define all other integer types. @type value: Integer @param value: Default integer value @type width: Integer @param width: Width of bit fields @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' assert(type(width) is int or type(value) is long) if type(value) in [int, long, list, tuple]: self.value = self.original_value = value else: raise ValueError("The supplied value must be either an Int, Long, List or Tuple.") self.width = width self.max_num = max_num self.endian = endian self.format = format self.signed = signed self.full_range = full_range self.fuzzable = fuzzable self.name = name self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.fuzz_library = [] # library of fuzz heuristics self.mutant_index = 0 # current mutation number self.cyclic_index = 0 # when cycling through non-mutating values if self.max_num == None: self.max_num = self.to_decimal("1" + "0" * width) assert(type(self.max_num) is int or type(self.max_num) is long) # build the fuzz library. if self.full_range: # add all possible values. for i in xrange(0, self.max_num): self.fuzz_library.append(i) else: if type(value) in [list, tuple]: # Use the supplied values as the fuzz library. for val in value: self.fuzz_library.append(val) else: # try only "smart" values. self.add_integer_boundaries(0) self.add_integer_boundaries(self.max_num / 2) self.add_integer_boundaries(self.max_num / 3) self.add_integer_boundaries(self.max_num / 4) self.add_integer_boundaries(self.max_num / 8) self.add_integer_boundaries(self.max_num / 16) self.add_integer_boundaries(self.max_num / 32) self.add_integer_boundaries(self.max_num) # if the optional file '.fuzz_ints' is found, parse each line as a new entry for the fuzz library. try: fh = open(".fuzz_ints", "r") for fuzz_int in fh.readlines(): # convert the line into an integer, continue on failure. try: fuzz_int = long(fuzz_int, 16) except: continue if fuzz_int < self.max_num: self.fuzz_library.append(fuzz_int) fh.close() except: pass def add_integer_boundaries (self, integer): ''' Add the supplied integer and border cases to the integer fuzz heuristics library. @type integer: Int @param integer: Integer to append to fuzz heuristics ''' for i in xrange(-10, 10): case = integer + i # ensure the border case falls within the valid range for this field. if 0 <= case < self.max_num: if case not in self.fuzz_library: self.fuzz_library.append(case) def render (self): ''' Render the primitive. ''' # # binary formatting. # if self.format == "binary": bit_stream = "" rendered = "" # pad the bit stream to the next byte boundary. if self.width % 8 == 0: bit_stream += self.to_binary() else: bit_stream = "0" * (8 - (self.width % 8)) bit_stream += self.to_binary() # convert the bit stream from a string of bits into raw bytes. for i in xrange(len(bit_stream) / 8): chunk = bit_stream[8*i:8*i+8] rendered += struct.pack("B", self.to_decimal(chunk)) # if necessary, convert the endianess of the raw bytes. if self.endian == "<": rendered = list(rendered) rendered.reverse() rendered = "".join(rendered) self.rendered = rendered # # ascii formatting. # else: # if the sign flag is raised and we are dealing with a signed integer (first bit is 1). if self.signed and self.to_binary()[0] == "1": max_num = self.to_decimal("1" + "0" * (self.width - 1)) # mask off the sign bit. val = self.value & self.to_decimal("1" * (self.width - 1)) # account for the fact that the negative scale works backwards. val = max_num - val - 1 # toss in the negative sign. self.rendered = "%d" % ~val # unsigned integer or positive signed integer. else: self.rendered = "%d" % self.value return self.rendered def to_binary (self, number=None, bit_count=None): ''' Convert a number to a binary string. @type number: Integer @param number: (Optional, def=self.value) Number to convert @type bit_count: Integer @param bit_count: (Optional, def=self.width) Width of bit string @rtype: String @return: Bit string ''' if number == None: if type(self.value) in [list, tuple]: # We have been given a list to cycle through that is not being mutated... if self.cyclic_index == len(self.value): # Reset the index. self.cyclic_index = 0 number = self.value[self.cyclic_index] self.cyclic_index += 1 else: number = self.value if bit_count == None: bit_count = self.width return "".join(map(lambda x:str((number >> x) & 1), range(bit_count -1, -1, -1))) def to_decimal (self, binary): ''' Convert a binary string to a decimal number. @type binary: String @param binary: Binary string @rtype: Integer @return: Converted bit string ''' return int(binary, 2) ######################################################################################################################## class byte (bit_field): def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None): self.s_type = "byte" if type(value) not in [int, long, list, tuple]: value = struct.unpack(endian + "B", value)[0] bit_field.__init__(self, value, 8, None, endian, format, signed, full_range, fuzzable, name) ######################################################################################################################## class word (bit_field): def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None): self.s_type = "word" if type(value) not in [int, long, list, tuple]: value = struct.unpack(endian + "H", value)[0] bit_field.__init__(self, value, 16, None, endian, format, signed, full_range, fuzzable, name) ######################################################################################################################## class dword (bit_field): def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None): self.s_type = "dword" if type(value) not in [int, long, list, tuple]: value = struct.unpack(endian + "L", value)[0] bit_field.__init__(self, value, 32, None, endian, format, signed, full_range, fuzzable, name) ######################################################################################################################## class qword (bit_field): def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None): self.s_type = "qword" if type(value) not in [int, long, list, tuple]: value = struct.unpack(endian + "Q", value)[0] bit_field.__init__(self, value, 64, None, endian, format, signed, full_range, fuzzable, name)
cirosantilli/sulley
sulley/primitives.py
Python
gpl-2.0
32,873
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2016 CERN. # # Zenodo is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Zenodo 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """Persistent identifier minters.""" from __future__ import absolute_import from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \ RecordIdentifier def zenodo_concept_recid_minter(record_uuid=None, data=None): """Mint the Concept RECID. Reserves the Concept RECID for the record. """ parent_id = RecordIdentifier.next() conceptrecid = PersistentIdentifier.create( pid_type='recid', pid_value=str(parent_id), status=PIDStatus.RESERVED, ) data['conceptrecid'] = conceptrecid.pid_value return conceptrecid def zenodo_deposit_minter(record_uuid, data): """Mint the DEPID, and reserve the Concept RECID and RECID PIDs.""" if 'conceptrecid' not in data: zenodo_concept_recid_minter(data=data) recid = zenodo_reserved_record_minter(data=data) # Create depid with same pid_value of the recid depid = PersistentIdentifier.create( 'depid', str(recid.pid_value), object_type='rec', object_uuid=record_uuid, status=PIDStatus.REGISTERED, ) data.update({ '_deposit': { 'id': depid.pid_value, 'status': 'draft', }, }) return depid def zenodo_reserved_record_minter(record_uuid=None, data=None): """Reserve a recid.""" id_ = RecordIdentifier.next() recid = PersistentIdentifier.create( 'recid', id_, status=PIDStatus.RESERVED ) data['recid'] = recid.pid_value return recid
jainaman224/zenodo
zenodo/modules/deposit/minters.py
Python
gpl-2.0
2,471
# Natural Language Toolkit: Dispersion Plots # # Copyright (C) 2001-2015 NLTK Project # Author: Steven Bird <stevenbird1@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ A utility for displaying lexical dispersion. """ def dispersion_plot(text, words, ignore_case=False, title="Lexical Dispersion Plot"): """ Generate a lexical dispersion plot. :param text: The source text :type text: list(str) or enum(str) :param words: The target words :type words: list of str :param ignore_case: flag to set if case should be ignored when searching text :type ignore_case: bool """ try: from matplotlib import pylab except ImportError: raise ValueError('The plot function requires matplotlib to be installed.' 'See http://matplotlib.org/') text = list(text) words.reverse() if ignore_case: words_to_comp = list(map(str.lower, words)) text_to_comp = list(map(str.lower, text)) else: words_to_comp = words text_to_comp = text points = [(x,y) for x in range(len(text_to_comp)) for y in range(len(words_to_comp)) if text_to_comp[x] == words_to_comp[y]] if points: x, y = list(zip(*points)) else: x = y = () pylab.plot(x, y, "b|", scalex=.1) pylab.yticks(list(range(len(words))), words, color="b") pylab.ylim(-1, len(words)) pylab.title(title) pylab.xlabel("Word Offset") pylab.show() if __name__ == '__main__': import nltk.compat from nltk.corpus import gutenberg words = ['Elinor', 'Marianne', 'Edward', 'Willoughby'] dispersion_plot(gutenberg.words('austen-sense.txt'), words)
Reagankm/KnockKnock
venv/lib/python3.4/site-packages/nltk/draw/dispersion.py
Python
gpl-2.0
1,744
#!/usr/bin/env python import sys import time from hypertable.thriftclient import * from hyperthrift.gen.ttypes import * if (len(sys.argv) < 2): print sys.argv[0], "<hql>" sys.exit(1); try: client = ThriftClient("localhost", 15867) namespace = client.open_namespace("/") res = client.hql_query(namespace, sys.argv[1]); print res client.close_namespace(namespace) except ClientException, e: print '%s' % (e.message)
hypertable/hypertable
tests/integration/thrift-table-refresh/thrift_hql.py
Python
gpl-3.0
438
""" Tests related to the cohorting feature. """ from uuid import uuid4 from .helpers import BaseDiscussionMixin from .helpers import CohortTestMixin from ..helpers import UniqueCourseTest from ...pages.lms.auto_auth import AutoAuthPage from ...fixtures.course import (CourseFixture, XBlockFixtureDesc) from ...pages.lms.discussion import (DiscussionTabSingleThreadPage, InlineDiscussionThreadPage, InlineDiscussionPage) from ...pages.lms.courseware import CoursewarePage from nose.plugins.attrib import attr class NonCohortedDiscussionTestMixin(BaseDiscussionMixin): """ Mixin for tests of discussion in non-cohorted courses. """ def setup_cohorts(self): """ No cohorts are desired for this mixin. """ pass def test_non_cohort_visibility_label(self): self.setup_thread(1) self.assertEquals(self.thread_page.get_group_visibility_label(), "This post is visible to everyone.") class CohortedDiscussionTestMixin(BaseDiscussionMixin, CohortTestMixin): """ Mixin for tests of discussion in cohorted courses. """ def setup_cohorts(self): """ Sets up the course to use cohorting with a single defined cohort group. """ self.setup_cohort_config(self.course_fixture) self.cohort_1_name = "Cohort Group 1" self.cohort_1_id = self.add_manual_cohort(self.course_fixture, self.cohort_1_name) def test_cohort_visibility_label(self): # Must be moderator to view content in a cohort other than your own AutoAuthPage(self.browser, course_id=self.course_id, roles="Moderator").visit() self.thread_id = self.setup_thread(1, group_id=self.cohort_1_id) self.assertEquals( self.thread_page.get_group_visibility_label(), "This post is visible only to {}.".format(self.cohort_1_name) ) # Disable cohorts and verify that the post now shows as visible to everyone. self.disable_cohorting(self.course_fixture) self.refresh_thread_page(self.thread_id) self.assertEquals(self.thread_page.get_group_visibility_label(), "This post is visible to everyone.") class DiscussionTabSingleThreadTest(UniqueCourseTest): """ Tests for the discussion page displaying a single thread. """ def setUp(self): super(DiscussionTabSingleThreadTest, self).setUp() self.discussion_id = "test_discussion_{}".format(uuid4().hex) # Create a course to register for self.course_fixture = CourseFixture(**self.course_info).install() self.setup_cohorts() AutoAuthPage(self.browser, course_id=self.course_id).visit() def setup_thread_page(self, thread_id): self.thread_page = DiscussionTabSingleThreadPage(self.browser, self.course_id, thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.visit() # pylint: disable=unused-argument def refresh_thread_page(self, thread_id): self.browser.refresh() self.thread_page.wait_for_page() @attr('shard_1') class CohortedDiscussionTabSingleThreadTest(DiscussionTabSingleThreadTest, CohortedDiscussionTestMixin): """ Tests for the discussion page displaying a single cohorted thread. """ # Actual test method(s) defined in CohortedDiscussionTestMixin. pass @attr('shard_1') class NonCohortedDiscussionTabSingleThreadTest(DiscussionTabSingleThreadTest, NonCohortedDiscussionTestMixin): """ Tests for the discussion page displaying a single non-cohorted thread. """ # Actual test method(s) defined in NonCohortedDiscussionTestMixin. pass class InlineDiscussionTest(UniqueCourseTest): """ Tests for inline discussions """ def setUp(self): super(InlineDiscussionTest, self).setUp() self.discussion_id = "test_discussion_{}".format(uuid4().hex) self.course_fixture = CourseFixture(**self.course_info).add_children( XBlockFixtureDesc("chapter", "Test Section").add_children( XBlockFixtureDesc("sequential", "Test Subsection").add_children( XBlockFixtureDesc("vertical", "Test Unit").add_children( XBlockFixtureDesc( "discussion", "Test Discussion", metadata={"discussion_id": self.discussion_id} ) ) ) ) ).install() self.setup_cohorts() self.user_id = AutoAuthPage(self.browser, course_id=self.course_id).visit().get_user_id() def setup_thread_page(self, thread_id): CoursewarePage(self.browser, self.course_id).visit() self.show_thread(thread_id) def show_thread(self, thread_id): discussion_page = InlineDiscussionPage(self.browser, self.discussion_id) discussion_page.expand_discussion() self.assertEqual(discussion_page.get_num_displayed_threads(), 1) self.thread_page = InlineDiscussionThreadPage(self.browser, thread_id) # pylint: disable=attribute-defined-outside-init self.thread_page.expand() def refresh_thread_page(self, thread_id): self.browser.refresh() self.show_thread(thread_id) @attr('shard_1') class CohortedInlineDiscussionTest(InlineDiscussionTest, CohortedDiscussionTestMixin): """ Tests for cohorted inline discussions. """ # Actual test method(s) defined in CohortedDiscussionTestMixin. pass @attr('shard_1') class NonCohortedInlineDiscussionTest(InlineDiscussionTest, NonCohortedDiscussionTestMixin): """ Tests for non-cohorted inline discussions. """ # Actual test method(s) defined in NonCohortedDiscussionTestMixin. pass
UQ-UQx/edx-platform_lti
common/test/acceptance/tests/discussion/test_cohorts.py
Python
agpl-3.0
5,771
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PerlFontTtf(PerlPackage): """Perl module for TrueType Font hacking""" homepage = "http://search.cpan.org/~bhallissy/Font-TTF-1.06/lib/Font/TTF.pm" url = "http://search.cpan.org/CPAN/authors/id/B/BH/BHALLISSY/Font-TTF-1.06.tar.gz" version('1.06', '241b59310ad4450e6e050d5e790f1b21')
krafczyk/spack
var/spack/repos/builtin/packages/perl-font-ttf/package.py
Python
lgpl-2.1
1,568
def pow(a, b, mod): res = 1 while b > 0: if b & 1 != 0: res = res * a % mod a = a * a % mod b >>= 1 return res print(1024 == pow(2, 10, 1000000007))
animesh0353/codelibrary
python/pow.py
Python
unlicense
198
from nose.tools import * # flake8: noqa from django.db.models import Q from tests.base import AdminTestCase from osf_tests.factories import SubjectFactory from osf.models import Subject from osf.models.preprint_provider import rules_to_subjects from admin.base.utils import get_subject_rules import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) class TestSubjectRules(AdminTestCase): def setUp(self): super(TestSubjectRules, self).setUp() self.parent_one = SubjectFactory() # 0 self.parent_two = SubjectFactory() # 1 self.child_one_1 = SubjectFactory(parent=self.parent_one) # 2 self.child_one_2 = SubjectFactory(parent=self.parent_one) # 3 self.grandchild_one_1 = SubjectFactory(parent=self.child_one_1) # 4 self.grandchild_one_2 = SubjectFactory(parent=self.child_one_1) # 5 self.child_two_1 = SubjectFactory(parent=self.parent_two) # 6 self.child_two_2 = SubjectFactory(parent=self.parent_two) # 7 def test_error_when_child_called_without_parent(self): subjects_selected = [self.child_one_1] with self.assertRaises(AttributeError): get_subject_rules(subjects_selected) def test_just_toplevel_subject(self): subjects_selected = [self.parent_one] rules_returned = get_subject_rules(subjects_selected) rules_ideal = [[[self.parent_one._id], False]] self.assertItemsEqual(rules_returned, rules_ideal) def test_two_toplevel_subjects(self): subjects_selected = [ self.parent_one, self.parent_two ] rules_returned = get_subject_rules(subjects_selected) rules_ideal = [ [[self.parent_one._id], False], [[self.parent_two._id], False] ] self.assertItemsEqual(rules_returned, rules_ideal) def test_one_child(self): subjects_selected = [ self.parent_one, self.child_one_1 ] rules_returned = get_subject_rules(subjects_selected) rules_ideal = [[[self.parent_one._id, self.child_one_1._id], False]] self.assertItemsEqual(rules_returned, rules_ideal) def test_one_child_all_grandchildren(self): subjects_selected = [ self.parent_one, self.child_one_1, self.grandchild_one_1, self.grandchild_one_2, ] rules_returned = get_subject_rules(subjects_selected) rules_ideal = [[[self.parent_one._id, self.child_one_1._id], True]] self.assertItemsEqual(rules_returned, rules_ideal) def test_all_children_all_grandchildren(self): subjects_selected = [ self.parent_one, self.child_one_1, self.grandchild_one_1, self.grandchild_one_2, self.child_one_2 ] rules_returned = get_subject_rules(subjects_selected) rules_ideal = [[[self.parent_one._id], True]] self.assertItemsEqual(rules_returned, rules_ideal) def test_one_child_with_one_grandchild(self): subjects_selected = [ self.parent_one, self.child_one_1, self.grandchild_one_1 ] rules_returned = get_subject_rules(subjects_selected) rules_ideal = [ [[self.parent_one._id, self.child_one_1._id, self.grandchild_one_1._id], False] ] self.assertItemsEqual(rules_returned, rules_ideal) def test_rules_to_subjects(self): rules = [ [[self.parent_one._id, self.child_one_1._id], False] ] subject_queryset_ideal = Subject.objects.filter(Q(id=self.parent_one.id) | Q(id=self.child_one_1.id)) returned_subjects = rules_to_subjects(rules) self.assertItemsEqual(subject_queryset_ideal, returned_subjects)
aaxelb/osf.io
admin_tests/base/test_utils.py
Python
apache-2.0
3,856
# Copyright 2008-2014 Nokia Solutions and Networks # # 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 robot.utils import elapsed_time_to_string, html_escape, normalize from .tags import TagPatterns class Stat(object): """Generic statistic object used for storing all the statistic values.""" def __init__(self, name): #: Human readable identifier of the object these statistics #: belong to. Either `All Tests` or `Critical Tests` for #: :class:`~robot.model.totalstatistics.TotalStatistics`, #: long name of the suite for #: :class:`~robot.model.suitestatistics.SuiteStatistics` #: or name of the tag for #: :class:`~robot.model.tagstatistics.TagStatistics` self.name = name #: Number of passed tests. self.passed = 0 #: Number of failed tests. self.failed = 0 #: Number of milliseconds it took to execute. self.elapsed = 0 self._norm_name = normalize(name, ignore='_') def get_attributes(self, include_label=False, include_elapsed=False, exclude_empty=False, values_as_strings=False, html_escape=False): attrs = {'pass': self.passed, 'fail': self.failed} attrs.update(self._get_custom_attrs()) if include_label: attrs['label'] = self.name if include_elapsed: attrs['elapsed'] = elapsed_time_to_string(self.elapsed, include_millis=False) if exclude_empty: attrs = dict((k, v) for k, v in attrs.items() if v != '') if values_as_strings: attrs = dict((k, unicode(v)) for k, v in attrs.items()) if html_escape: attrs = dict((k, self._html_escape(v)) for k, v in attrs.items()) return attrs def _get_custom_attrs(self): return {} def _html_escape(self, item): return html_escape(item) if isinstance(item, basestring) else item @property def total(self): return self.passed + self.failed def add_test(self, test): self._update_stats(test) self._update_elapsed(test) def _update_stats(self, test): if test.passed: self.passed += 1 else: self.failed += 1 def _update_elapsed(self, test): self.elapsed += test.elapsedtime def __cmp__(self, other): return cmp(self._norm_name, other._norm_name) def __nonzero__(self): return not self.failed def visit(self, visitor): visitor.visit_stat(self) class TotalStat(Stat): """Stores statistic values for a test run.""" #: Always string `total` type = 'total' class SuiteStat(Stat): """Stores statistics values for a single suite.""" #: Always string `suite` type = 'suite' def __init__(self, suite): Stat.__init__(self, suite.longname) #: Identifier of the suite, e.g. `s1-s2`. self.id = suite.id #: Number of milliseconds it took to execute this suite, #: including sub-suites. self.elapsed = suite.elapsedtime self._name = suite.name def _get_custom_attrs(self): return {'id': self.id, 'name': self._name} def _update_elapsed(self, test): pass def add_stat(self, other): self.passed += other.passed self.failed += other.failed class TagStat(Stat): """Stores statistic values for a single tag.""" #: Always string `tag`. type = 'tag' def __init__(self, name, doc='', links=None, critical=False, non_critical=False, combined=''): Stat.__init__(self, name) #: Documentation of tag as a string. self.doc = doc #: List of tuples in which the first value is the link URL and #: the second is the link title. An empty list by default. self.links = links or [] #: ``True`` if tag is considered critical, ``False`` otherwise. self.critical = critical #: ``True`` if tag is considered non-critical, ``False`` otherwise. self.non_critical = non_critical #: Pattern as a string if the tag is combined, #: an empty string otherwise. self.combined = combined @property def info(self): """Returns additional information of the tag statistics are about. Either `critical`, `non-critical`, `combined` or an empty string. """ if self.critical: return 'critical' if self.non_critical: return 'non-critical' if self.combined: return 'combined' return '' def _get_custom_attrs(self): return {'doc': self.doc, 'links': self._get_links_as_string(), 'info': self.info, 'combined': self.combined} def _get_links_as_string(self): return ':::'.join('%s:%s' % (title, url) for url, title in self.links) def __cmp__(self, other): return cmp(other.critical, self.critical) \ or cmp(other.non_critical, self.non_critical) \ or cmp(bool(other.combined), bool(self.combined)) \ or Stat.__cmp__(self, other) class CombinedTagStat(TagStat): def __init__(self, pattern, name=None, doc='', links=None): TagStat.__init__(self, name or pattern, doc, links, combined=pattern) self._matcher = TagPatterns(pattern) def match(self, tags): return self._matcher.match(tags)
eric-stanley/robotframework
src/robot/model/stats.py
Python
apache-2.0
6,017
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from textwrap import dedent from mock import MagicMock from pants.backend.codegen.targets.java_thrift_library import JavaThriftLibrary from pants.backend.jvm.targets.java_library import JavaLibrary from pants.backend.jvm.targets.scala_library import ScalaLibrary from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.build_graph.address import Address from pants.build_graph.build_file_aliases import BuildFileAliases from pants.goal.context import Context from pants.util.dirutil import safe_rmtree from pants_test.tasks.task_test_base import TaskTestBase from twitter.common.collections import OrderedSet from pants.contrib.scrooge.tasks.scrooge_gen import ScroogeGen # TODO (tdesai) Issue-240: Use JvmToolTaskTestBase for ScroogeGenTest class ScroogeGenTest(TaskTestBase): @classmethod def task_type(cls): return ScroogeGen @property def alias_groups(self): return BuildFileAliases(targets={'java_thrift_library': JavaThriftLibrary}) def setUp(self): super(ScroogeGenTest, self).setUp() self.task_outdir = os.path.join(self.build_root, 'scrooge', 'gen-java') def tearDown(self): super(ScroogeGenTest, self).tearDown() safe_rmtree(self.task_outdir) def test_validate_compiler_configs(self): # Set synthetic defaults for the global scope. self.set_options_for_scope('thrift-defaults', compiler='unchecked', language='uniform', rpc_style='async') self.add_to_build_file('test_validate', dedent(''' java_thrift_library(name='one', sources=[], dependencies=[], ) ''')) self.add_to_build_file('test_validate', dedent(''' java_thrift_library(name='two', sources=[], dependencies=[':one'], ) ''')) self.add_to_build_file('test_validate', dedent(''' java_thrift_library(name='three', sources=[], dependencies=[':one'], rpc_style='finagle', ) ''')) target = self.target('test_validate:one') context = self.context(target_roots=[target]) task = self.create_task(context) task._validate_compiler_configs([self.target('test_validate:one')]) task._validate_compiler_configs([self.target('test_validate:two')]) with self.assertRaises(TaskError): task._validate_compiler_configs([self.target('test_validate:three')]) def test_scala(self): build_string = ''' java_thrift_library(name='a', sources=['a.thrift'], dependencies=[], compiler='scrooge', language='scala', rpc_style='finagle' ) ''' sources = [os.path.join(self.task_outdir, 'org/pantsbuild/example/Example.scala')] self._test_help(build_string, ScalaLibrary, sources) def test_android(self): build_string = ''' java_thrift_library(name='a', sources=['a.thrift'], dependencies=[], compiler='scrooge', language='android', rpc_style='finagle' ) ''' sources = [os.path.join(self.task_outdir, 'org/pantsbuild/android_example/Example.java')] self._test_help(build_string, JavaLibrary, sources) def _test_help(self, build_string, library_type, sources): contents = dedent('''#@namespace android org.pantsbuild.android_example namespace java org.pantsbuild.example struct Example { 1: optional i64 number } ''') self.create_file(relpath='test_smoke/a.thrift', contents=contents) self.add_to_build_file('test_smoke', dedent(build_string)) target = self.target('test_smoke:a') context = self.context(target_roots=[target]) task = self.create_task(context) task._declares_service = lambda source: False task._outdir = MagicMock() task._outdir.return_value = self.task_outdir task.gen = MagicMock() task.gen.return_value = {'test_smoke/a.thrift': sources} saved_add_new_target = Context.add_new_target try: mock = MagicMock() Context.add_new_target = mock task.execute() self.assertEquals(1, mock.call_count) _, call_kwargs = mock.call_args self.assertEquals(call_kwargs['target_type'], library_type) self.assertEquals(call_kwargs['dependencies'], OrderedSet()) self.assertEquals(call_kwargs['provides'], None) self.assertEquals(call_kwargs['sources'], []) self.assertEquals(call_kwargs['derived_from'], target) finally: Context.add_new_target = saved_add_new_target
jtrobec/pants
contrib/scrooge/tests/python/pants_test/contrib/scrooge/tasks/test_scrooge_gen.py
Python
apache-2.0
4,867
from django.conf.urls import url from dojo.engagement import views urlpatterns = [ # engagements and calendar url(r'^calendar$', views.engagement_calendar, name='calendar'), url(r'^calendar/engagements$', views.engagement_calendar, name='engagement_calendar'), url(r'^engagement$', views.engagement, name='engagement'), url(r'^engagement/new$', views.new_engagement, name='new_eng'), url(r'^engagement/(?P<eid>\d+)$', views.view_engagement, name='view_engagement'), url(r'^engagement/(?P<eid>\d+)/ics$', views.engagement_ics, name='engagement_ics'), url(r'^engagement/(?P<eid>\d+)/edit$', views.edit_engagement, name='edit_engagement'), url(r'^engagement/(?P<eid>\d+)/delete$', views.delete_engagement, name='delete_engagement'), url(r'^engagement/(?P<eid>\d+)/add_tests$', views.add_tests, name='add_tests'), url(r'^engagement/(?P<eid>\d+)/import_scan_results$', views.import_scan_results, name='import_scan_results'), url(r'^engagement/(?P<eid>\d+)/close$', views.close_eng, name='close_engagement'), url(r'^engagement/(?P<eid>\d+)/reopen$', views.reopen_eng, name='reopen_engagement'), url(r'^engagement/(?P<eid>\d+)/complete_checklist$', views.complete_checklist, name='complete_checklist'), url(r'^engagement/(?P<eid>\d+)/upload_risk_acceptance$', views.upload_risk, name='upload_risk_acceptance$'), url(r'^engagement/(?P<eid>\d+)/risk_approval/(?P<raid>\d+)$', views.view_risk, name='view_risk'), url(r'^engagement/(?P<eid>\d+)/risk_approval/(?P<raid>\d+)/delete$', views.delete_risk, name='delete_risk'), url(r'^engagement/(?P<eid>\d+)/risk_approval/(?P<raid>\d+)/download$', views.download_risk, name='download_risk'), url(r'^engagement/(?P<eid>\d+)/threatmodel$', views.view_threatmodel, name='view_threatmodel'), url(r'^engagement/(?P<eid>\d+)/threatmodel/upload$', views.upload_threatmodel, name='upload_threatmodel'), ]
Prakhash/security-tools
external/django-DefectDojo-1.2.1/dojo/engagement/urls.py
Python
apache-2.0
2,035
# -*- coding: utf-8 -*- ############################################################################### # # DeleteWaterLog # Deletes a specified water log entry. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo 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 temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class DeleteWaterLog(Choreography): def __init__(self, temboo_session): """ Create a new instance of the DeleteWaterLog Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(DeleteWaterLog, self).__init__(temboo_session, '/Library/Fitbit/Foods/DeleteWaterLog') def new_input_set(self): return DeleteWaterLogInputSet() def _make_result_set(self, result, path): return DeleteWaterLogResultSet(result, path) def _make_execution(self, session, exec_id, path): return DeleteWaterLogChoreographyExecution(session, exec_id, path) class DeleteWaterLogInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the DeleteWaterLog Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccessTokenSecret(self, value): """ Set the value of the AccessTokenSecret input for this Choreo. ((required, string) The Access Token Secret retrieved during the OAuth process.) """ super(DeleteWaterLogInputSet, self)._set_input('AccessTokenSecret', value) def set_AccessToken(self, value): """ Set the value of the AccessToken input for this Choreo. ((required, string) The Access Token retrieved during the OAuth process.) """ super(DeleteWaterLogInputSet, self)._set_input('AccessToken', value) def set_ConsumerKey(self, value): """ Set the value of the ConsumerKey input for this Choreo. ((required, string) The Consumer Key provided by Fitbit.) """ super(DeleteWaterLogInputSet, self)._set_input('ConsumerKey', value) def set_ConsumerSecret(self, value): """ Set the value of the ConsumerSecret input for this Choreo. ((required, string) The Consumer Secret provided by Fitbit.) """ super(DeleteWaterLogInputSet, self)._set_input('ConsumerSecret', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that you want the response to be in: xml or json. Defaults to json.) """ super(DeleteWaterLogInputSet, self)._set_input('ResponseFormat', value) def set_UserID(self, value): """ Set the value of the UserID input for this Choreo. ((optional, string) The user's encoded id. Defaults to "-" (dash) which will return data for the user associated with the token credentials provided.) """ super(DeleteWaterLogInputSet, self)._set_input('UserID', value) def set_WaterLogID(self, value): """ Set the value of the WaterLogID input for this Choreo. ((required, integer) The id of the water log you want to delete. The Id is returned in the LogWater response.) """ super(DeleteWaterLogInputSet, self)._set_input('WaterLogID', value) class DeleteWaterLogResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the DeleteWaterLog Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Fitbit.) """ return self._output.get('Response', None) class DeleteWaterLogChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return DeleteWaterLogResultSet(response, path)
jordanemedlock/psychtruths
temboo/core/Library/Fitbit/Foods/DeleteWaterLog.py
Python
apache-2.0
4,732
# 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 django.utils.translation import ugettext_lazy as _ # The slug of the panel group to be added to HORIZON_CONFIG. Required. PANEL_GROUP = 'database' # The display name of the PANEL_GROUP. Required. PANEL_GROUP_NAME = _('Database') # The slug of the dashboard the PANEL_GROUP associated with. Required. PANEL_GROUP_DASHBOARD = 'project'
dklyle/trove-dashboard
trove_dashboard/enabled/_1710_database_panel_group.py
Python
apache-2.0
913
"""Produce contact map for Figure 5D from the PySB publication""" from __future__ import print_function import pysb.integrate import pysb.util import numpy as np import scipy.optimize import scipy.interpolate import matplotlib.pyplot as plt import os import sys import inspect from earm.lopez_embedded import model # List of model observables and corresponding data file columns for # point-by-point fitting obs_names = ['mBid', 'cPARP'] data_names = ['norm_ICRP', 'norm_ECRP'] var_names = ['nrm_var_ICRP', 'nrm_var_ECRP'] # Load experimental data file data_path = os.path.join(os.path.dirname(__file__), 'fig6_data.csv') exp_data = np.genfromtxt(data_path, delimiter=',', names=True) # Model observable corresponding to the IMS-RP reporter (MOMP timing) momp_obs = 'aSmac' # Mean and variance of Td (delay time) and Ts (switching time) of MOMP, and # yfinal (the last value of the IMS-RP trajectory) momp_data = np.array([9810.0, 180.0, 1.0]) momp_var = np.array([7245000.0, 3600.0, 1e-9]) # Build time points for the integrator, using the same time scale as the # experimental data but with greater resolution to help the integrator converge. ntimes = len(exp_data['Time']) # Factor by which to increase time resolution tmul = 10 # Do the sampling such that the original experimental timepoints can be # extracted with a slice expression instead of requiring interpolation. tspan = np.linspace(exp_data['Time'][0], exp_data['Time'][-1], (ntimes-1) * tmul + 1) # Initialize solver object solver = pysb.integrate.Solver(model, tspan, rtol=1e-5, atol=1e-5) # Get parameters for rates only rate_params = model.parameters_rules() # Build a boolean mask for those params against the entire param list rate_mask = np.array([p in rate_params for p in model.parameters]) # Build vector of nominal parameter values from the model nominal_values = np.array([p.value for p in model.parameters]) # Set the radius of a hypercube bounding the search space bounds_radius = 2 def objective_func(x, rate_mask, lb, ub): caller_frame, _, _, caller_func, _, _ = inspect.stack()[1] if caller_func in {'anneal', '_minimize_anneal'}: caller_locals = caller_frame.f_locals if caller_locals['n'] == 1: print(caller_locals['best_state'].cost, caller_locals['current_state'].cost) # Apply hard bounds if np.any((x < lb) | (x > ub)): print("bounds-check failed") return np.inf # Simulate model with rates taken from x (which is log transformed) param_values = np.array([p.value for p in model.parameters]) param_values[rate_mask] = 10 ** x solver.run(param_values) # Calculate error for point-by-point trajectory comparisons e1 = 0 for obs_name, data_name, var_name in zip(obs_names, data_names, var_names): # Get model observable trajectory (this is the slice expression # mentioned above in the comment for tspan) ysim = solver.yobs[obs_name][::tmul] # Normalize it to 0-1 ysim_norm = ysim / np.nanmax(ysim) # Get experimental measurement and variance ydata = exp_data[data_name] yvar = exp_data[var_name] # Compute error between simulation and experiment (chi-squared) e1 += np.sum((ydata - ysim_norm) ** 2 / (2 * yvar)) / len(ydata) # Calculate error for Td, Ts, and final value for IMS-RP reporter # ===== # Normalize trajectory ysim_momp = solver.yobs[momp_obs] ysim_momp_norm = ysim_momp / np.nanmax(ysim_momp) # Build a spline to interpolate it st, sc, sk = scipy.interpolate.splrep(solver.tspan, ysim_momp_norm) # Use root-finding to find the point where trajectory reaches 10% and 90% t10 = scipy.interpolate.sproot((st, sc-0.10, sk))[0] t90 = scipy.interpolate.sproot((st, sc-0.90, sk))[0] # Calculate Td as the mean of these times td = (t10 + t90) / 2 # Calculate Ts as their difference ts = t90 - t10 # Get yfinal, the last element from the trajectory yfinal = ysim_momp_norm[-1] # Build a vector of the 3 variables to fit momp_sim = [td, ts, yfinal] # Perform chi-squared calculation against mean and variance vectors e2 = np.sum((momp_data - momp_sim) ** 2 / (2 * momp_var)) / 3 # Calculate error for final cPARP value (ensure all PARP is cleaved) cparp_final = model.parameters['PARP_0'].value cparp_final_var = .01 cparp_final_sim = solver.yobs['cPARP'][-1] e3 = (cparp_final - cparp_final_sim) ** 2 / (2 * cparp_final_var) error = e1 + e2 + e3 return error def estimate(start_values=None): """Estimate parameter values by fitting to data. Parameters ========== parameter_values : numpy array of floats, optional Starting parameter values. Taken from model's nominal parameter values if not specified. Returns ======= numpy array of floats, containing fitted parameter values. """ # Set starting position to nominal parameter values if not specified if start_values is None: start_values = nominal_values else: assert start_values.shape == nominal_values.shape # Log-transform the starting position x0 = np.log10(start_values[rate_mask]) # Displacement size for annealing moves dx = .02 # The default 'fast' annealing schedule uses the 'lower' and 'upper' # arguments in a somewhat counterintuitive way. See # http://projects.scipy.org/scipy/ticket/1126 for more information. This is # how to get the search to start at x0 and use a displacement on the order # of dx (note that this will affect the T0 estimation which *does* expect # lower and upper to be the absolute expected bounds on x). lower = x0 - dx / 2 upper = x0 + dx / 2 # Log-transform the rate parameter values xnominal = np.log10(nominal_values[rate_mask]) # Hard lower and upper bounds on x lb = xnominal - bounds_radius ub = xnominal + bounds_radius # Perform the annealing args = [rate_mask, lb, ub] (xmin, Jmin, Tfinal, feval, iters, accept, retval) = \ scipy.optimize.anneal(objective_func, x0, full_output=True, maxiter=4000, quench=0.5, lower=lower, upper=upper, args=args) # Construct vector with resulting parameter values (un-log-transformed) params_estimated = start_values.copy() params_estimated[rate_mask] = 10 ** xmin # Display annealing results for v in ('xmin', 'Jmin', 'Tfinal', 'feval', 'iters', 'accept', 'retval'): print("%s: %s" % (v, locals()[v])) return params_estimated def display(params_estimated): # Simulate model with nominal parameters and construct a matrix of the # trajectories of the observables of interest, normalized to 0-1. solver.run() obs_names_disp = ['mBid', 'aSmac', 'cPARP'] obs_totals = [model.parameters[n].value for n in ('Bid_0', 'Smac_0', 'PARP_0')] sim_obs = solver.yobs[obs_names_disp].view(float).reshape(len(solver.yobs), -1) sim_obs_norm = (sim_obs / obs_totals).T # Do the same with the estimated parameters solver.run(params_estimated) sim_est_obs = solver.yobs[obs_names_disp].view(float).reshape(len(solver.yobs), -1) sim_est_obs_norm = (sim_est_obs / obs_totals).T # Plot data with simulation trajectories both before and after fitting color_data = '#C0C0C0' color_orig = '#FAAA6A' color_est = '#83C98E' plt.subplot(311) plt.errorbar(exp_data['Time'], exp_data['norm_ICRP'], yerr=exp_data['nrm_var_ICRP']**0.5, c=color_data, linewidth=2, elinewidth=0.5) plt.plot(solver.tspan, sim_obs_norm[0], color_orig, linewidth=2) plt.plot(solver.tspan, sim_est_obs_norm[0], color_est, linewidth=2) plt.ylabel('Fraction of\ncleaved IC-RP/Bid', multialignment='center') plt.axis([0, 20000, -0.2, 1.2]) plt.subplot(312) plt.vlines(momp_data[0], -0.2, 1.2, color=color_data, linewidth=2) plt.plot(solver.tspan, sim_obs_norm[1], color_orig, linewidth=2) plt.plot(solver.tspan, sim_est_obs_norm[1], color_est, linewidth=2) plt.ylabel('Td / Fraction of\nreleased Smac', multialignment='center') plt.axis([0, 20000, -0.2, 1.2]) plt.subplot(313) plt.errorbar(exp_data['Time'], exp_data['norm_ECRP'], yerr=exp_data['nrm_var_ECRP']**0.5, c=color_data, linewidth=2, elinewidth=0.5) plt.plot(solver.tspan, sim_obs_norm[2], color_orig, linewidth=2) plt.plot(solver.tspan, sim_est_obs_norm[2], color_est, linewidth=2) plt.ylabel('Fraction of\ncleaved EC-RP/PARP', multialignment='center') plt.xlabel('Time (s)') plt.axis([0, 20000, -0.2, 1.2]) plt.show() if __name__ == '__main__': params_estimated = None try: earm_path = sys.modules['earm'].__path__[0] fit_file = os.path.join(earm_path, '..', 'EARM_2_0_M1a_fitted_params.txt') params_estimated = np.genfromtxt(fit_file)[:,1].copy() except IOError: pass if params_estimated is None: np.random.seed(1) params_estimated = estimate() display(params_estimated)
LoLab-VU/pysb
pysb/examples/paper_figures/fig6.py
Python
bsd-2-clause
9,204
import mock from django_images.models import Thumbnail from taggit.models import Tag from tastypie.exceptions import Unauthorized from tastypie.test import ResourceTestCase from .helpers import ImageFactory, PinFactory, UserFactory from ..models import Pin, Image from ...users.models import User __all__ = ['ImageResourceTest', 'PinResourceTest'] def filter_generator_for(size): def wrapped_func(obj): return Thumbnail.objects.get_or_create_at_size(obj.pk, size) return wrapped_func def mock_requests_get(url): response = mock.Mock(content=open('logo.png', 'rb').read()) return response class ImageResourceTest(ResourceTestCase): def test_post_create_unsupported(self): """Make sure that new images can't be created using API""" response = self.api_client.post('/api/v1/image/', format='json', data={}) self.assertHttpUnauthorized(response) def test_list_detail(self): image = ImageFactory() thumbnail = filter_generator_for('thumbnail')(image) standard = filter_generator_for('standard')(image) square = filter_generator_for('square')(image) response = self.api_client.get('/api/v1/image/', format='json') self.assertDictEqual(self.deserialize(response)['objects'][0], { u'image': unicode(image.image.url), u'height': image.height, u'width': image.width, u'standard': { u'image': unicode(standard.image.url), u'width': standard.width, u'height': standard.height, }, u'thumbnail': { u'image': unicode(thumbnail.image.url), u'width': thumbnail.width, u'height': thumbnail.height, }, u'square': { u'image': unicode(square.image.url), u'width': square.width, u'height': square.height, }, }) class PinResourceTest(ResourceTestCase): def setUp(self): super(PinResourceTest, self).setUp() self.user = UserFactory(password='password') self.api_client.client.login(username=self.user.username, password='password') @mock.patch('requests.get', mock_requests_get) def test_post_create_url(self): url = 'http://testserver/mocked/logo.png' post_data = { 'submitter': '/api/v1/user/{}/'.format(self.user.pk), 'url': url, 'description': 'That\'s an Apple!' } response = self.api_client.post('/api/v1/pin/', data=post_data) self.assertHttpCreated(response) self.assertEqual(Pin.objects.count(), 1) self.assertEqual(Image.objects.count(), 1) # submitter is optional, current user will be used by default post_data = { 'url': url, 'description': 'That\'s an Apple!', 'origin': None } response = self.api_client.post('/api/v1/pin/', data=post_data) self.assertHttpCreated(response) @mock.patch('requests.get', mock_requests_get) def test_post_create_url_with_empty_tags(self): url = 'http://testserver/mocked/logo.png' post_data = { 'submitter': '/api/v1/user/{}/'.format(self.user.pk), 'url': url, 'description': 'That\'s an Apple!', 'tags': [] } response = self.api_client.post('/api/v1/pin/', data=post_data) self.assertHttpCreated(response) self.assertEqual(Pin.objects.count(), 1) self.assertEqual(Image.objects.count(), 1) pin = Pin.objects.get(url=url) self.assertEqual(pin.tags.count(), 0) @mock.patch('requests.get', mock_requests_get) def test_post_create_url_unauthorized(self): url = 'http://testserver/mocked/logo.png' post_data = { 'submitter': '/api/v1/user/2/', 'url': url, 'description': 'That\'s an Apple!', 'tags': [] } with self.assertRaises(Unauthorized): response = self.api_client.post('/api/v1/pin/', data=post_data) self.assertEqual(Pin.objects.count(), 0) self.assertEqual(Image.objects.count(), 0) @mock.patch('requests.get', mock_requests_get) def test_post_create_url_with_empty_origin(self): url = 'http://testserver/mocked/logo.png' post_data = { 'submitter': '/api/v1/user/{}/'.format(self.user.pk), 'url': url, 'description': 'That\'s an Apple!', 'origin': None } response = self.api_client.post('/api/v1/pin/', data=post_data) self.assertHttpCreated(response) self.assertEqual(Pin.objects.count(), 1) self.assertEqual(Image.objects.count(), 1) self.assertEqual(Pin.objects.get(url=url).origin, None) @mock.patch('requests.get', mock_requests_get) def test_post_create_url_with_origin(self): origin = 'http://testserver/mocked/' url = origin + 'logo.png' post_data = { 'submitter': '/api/v1/user/{}/'.format(self.user.pk), 'url': url, 'description': 'That\'s an Apple!', 'origin': origin } response = self.api_client.post('/api/v1/pin/', data=post_data) self.assertHttpCreated(response) self.assertEqual(Pin.objects.count(), 1) self.assertEqual(Image.objects.count(), 1) self.assertEqual(Pin.objects.get(url=url).origin, origin) def test_post_create_obj(self): image = ImageFactory() post_data = { 'submitter': '/api/v1/user/{}/'.format(self.user.pk), 'image': '/api/v1/image/{}/'.format(image.pk), 'description': 'That\'s something else (probably a CC logo)!', 'tags': ['random', 'tags'], } response = self.api_client.post('/api/v1/pin/', data=post_data) self.assertEqual( self.deserialize(response)['description'], 'That\'s something else (probably a CC logo)!' ) self.assertHttpCreated(response) # A number of Image objects should stay the same as we are using an existing image self.assertEqual(Image.objects.count(), 1) self.assertEqual(Pin.objects.count(), 1) self.assertEquals(Tag.objects.count(), 2) def test_put_detail_unauthenticated(self): self.api_client.client.logout() uri = '/api/v1/pin/{}/'.format(PinFactory().pk) response = self.api_client.put(uri, format='json', data={}) self.assertHttpUnauthorized(response) def test_put_detail_unauthorized(self): uri = '/api/v1/pin/{}/'.format(PinFactory(submitter=self.user).pk) user = UserFactory(password='password') self.api_client.client.login(username=user.username, password='password') response = self.api_client.put(uri, format='json', data={}) self.assertHttpUnauthorized(response) def test_put_detail(self): pin = PinFactory(submitter=self.user) uri = '/api/v1/pin/{}/'.format(pin.pk) new = {'description': 'Updated description'} response = self.api_client.put(uri, format='json', data=new) self.assertHttpAccepted(response) self.assertEqual(Pin.objects.count(), 1) self.assertEqual(Pin.objects.get(pk=pin.pk).description, new['description']) def test_delete_detail_unauthenticated(self): uri = '/api/v1/pin/{}/'.format(PinFactory(submitter=self.user).pk) self.api_client.client.logout() self.assertHttpUnauthorized(self.api_client.delete(uri)) def test_delete_detail_unauthorized(self): uri = '/api/v1/pin/{}/'.format(PinFactory(submitter=self.user).pk) User.objects.create_user('test', 'test@example.com', 'test') self.api_client.client.login(username='test', password='test') self.assertHttpUnauthorized(self.api_client.delete(uri)) def test_delete_detail(self): uri = '/api/v1/pin/{}/'.format(PinFactory(submitter=self.user).pk) self.assertHttpAccepted(self.api_client.delete(uri)) self.assertEqual(Pin.objects.count(), 0) def test_get_list_json_ordered(self): _, pin = PinFactory(), PinFactory() response = self.api_client.get('/api/v1/pin/', format='json', data={'order_by': '-id'}) self.assertValidJSONResponse(response) self.assertEqual(self.deserialize(response)['objects'][0]['id'], pin.id) def test_get_list_json_filtered_by_tags(self): pin = PinFactory() response = self.api_client.get('/api/v1/pin/', format='json', data={'tag': pin.tags.all()[0]}) self.assertValidJSONResponse(response) self.assertEqual(self.deserialize(response)['objects'][0]['id'], pin.pk) def test_get_list_json_filtered_by_submitter(self): pin = PinFactory(submitter=self.user) response = self.api_client.get('/api/v1/pin/', format='json', data={'submitter__username': self.user.username}) self.assertValidJSONResponse(response) self.assertEqual(self.deserialize(response)['objects'][0]['id'], pin.pk) def test_get_list_json(self): image = ImageFactory() pin = PinFactory(**{ 'submitter': self.user, 'image': image, 'url': 'http://testserver/mocked/logo.png', 'description': u'Mocked Description', 'origin': None }) standard = filter_generator_for('standard')(image) thumbnail = filter_generator_for('thumbnail')(image) square = filter_generator_for('square')(image) response = self.api_client.get('/api/v1/pin/', format='json') self.assertValidJSONResponse(response) self.assertDictEqual(self.deserialize(response)['objects'][0], { u'id': pin.id, u'submitter': { u'username': unicode(self.user.username), u'gravatar': unicode(self.user.gravatar) }, u'image': { u'image': unicode(image.image.url), u'width': image.width, u'height': image.height, u'standard': { u'image': unicode(standard.image.url), u'width': standard.width, u'height': standard.height, }, u'thumbnail': { u'image': unicode(thumbnail.image.url), u'width': thumbnail.width, u'height': thumbnail.height, }, u'square': { u'image': unicode(square.image.url), u'width': square.width, u'height': square.height, }, }, u'url': pin.url, u'origin': pin.origin, u'description': pin.description, u'tags': [tag.name for tag in pin.tags.all()] })
supervacuo/pinry
pinry/core/tests/api.py
Python
bsd-2-clause
10,976
from django.conf import settings from django.contrib import admin if 'django.contrib.auth' in settings.INSTALLED_APPS: from tastypie.models import ApiKey class ApiKeyInline(admin.StackedInline): model = ApiKey extra = 0 ABSTRACT_APIKEY = getattr(settings, 'TASTYPIE_ABSTRACT_APIKEY', False) if ABSTRACT_APIKEY and not isinstance(ABSTRACT_APIKEY, bool): raise TypeError("'TASTYPIE_ABSTRACT_APIKEY' must be either 'True' " "or 'False'.") if not ABSTRACT_APIKEY: admin.site.register(ApiKey)
rtucker-mozilla/WhistlePig
vendor-local/lib/python/tastypie/admin.py
Python
bsd-3-clause
582
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: <Enthought pyface code editor> #------------------------------------------------------------------------------ import math from pyface.qt import QtCore, QtGui class GutterWidget(QtGui.QWidget): min_width = 5 background_color = QtGui.QColor(220, 220, 220) def sizeHint(self): return QtCore.QSize(self.min_width, 0) def paintEvent(self, event): """ Paint the line numbers. """ painter = QtGui.QPainter(self) painter.fillRect(event.rect(), QtCore.Qt.lightGray) def wheelEvent(self, event): """ Delegate mouse wheel events to parent for seamless scrolling. """ self.parent().wheelEvent(event) class StatusGutterWidget(GutterWidget): """ Draws status markers """ def __init__(self, *args, **kw): super(StatusGutterWidget, self).__init__(*args, **kw) self.error_lines = [] self.warn_lines = [] self.info_lines = [] def sizeHint(self): return QtCore.QSize(10, 0) def paintEvent(self, event): """ Paint the line numbers. """ painter = QtGui.QPainter(self) painter.fillRect(event.rect(), self.background_color) cw = self.parent() pixels_per_block = self.height()/float(cw.blockCount()) for line in self.info_lines: painter.fillRect(QtCore.QRect(0, line*pixels_per_block, self.width(), 3), QtCore.Qt.green) for line in self.warn_lines: painter.fillRect(QtCore.QRect(0, line*pixels_per_block, self.width(), 3), QtCore.Qt.yellow) for line in self.error_lines: painter.fillRect(QtCore.QRect(0, line*pixels_per_block, self.width(), 3), QtCore.Qt.red) class LineNumberWidget(GutterWidget): """ Draw line numbers. """ min_char_width = 4 def fontMetrics(self): # QWidget's fontMetrics method does not provide an up to date # font metrics, just one corresponding to the initial font return QtGui.QFontMetrics(self.font) def set_font(self, font): self.font = font def digits_width(self): nlines = max(1, self.parent().blockCount()) ndigits = max(self.min_char_width, int(math.floor(math.log10(nlines) + 1))) width = max(self.fontMetrics().width(u'0' * ndigits) + 3, self.min_width) return width def sizeHint(self): return QtCore.QSize(self.digits_width(), 0) def paintEvent(self, event): """ Paint the line numbers. """ painter = QtGui.QPainter(self) painter.setFont(self.font) painter.fillRect(event.rect(), self.background_color) cw = self.parent() block = cw.firstVisibleBlock() blocknum = block.blockNumber() top = cw.blockBoundingGeometry(block).translated( cw.contentOffset()).top() bottom = top + int(cw.blockBoundingRect(block).height()) while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): painter.setPen(QtCore.Qt.black) painter.drawText(0, top, self.width() - 2, self.fontMetrics().height(), QtCore.Qt.AlignRight, str(blocknum + 1)) block = block.next() top = bottom bottom = top + int(cw.blockBoundingRect(block).height()) blocknum += 1
pankajp/pyface
pyface/ui/qt4/code_editor/gutters.py
Python
bsd-3-clause
3,820
# -*- coding: utf-8 -*- """ tests.basic ~~~~~~~~~~~~~~~~~~~~~ The basic functionality. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import pytest import re import uuid import time import flask import pickle from datetime import datetime from threading import Thread from flask._compat import text_type from werkzeug.exceptions import BadRequest, NotFound, Forbidden from werkzeug.http import parse_date from werkzeug.routing import BuildError import werkzeug.serving def test_options_work(): app = flask.Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return 'Hello World' rv = app.test_client().open('/', method='OPTIONS') assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] assert rv.data == b'' def test_options_on_multiple_rules(): app = flask.Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return 'Hello World' @app.route('/', methods=['PUT']) def index_put(): return 'Aha!' rv = app.test_client().open('/', method='OPTIONS') assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] def test_options_handling_disabled(): app = flask.Flask(__name__) def index(): return 'Hello World!' index.provide_automatic_options = False app.route('/')(index) rv = app.test_client().open('/', method='OPTIONS') assert rv.status_code == 405 app = flask.Flask(__name__) def index2(): return 'Hello World!' index2.provide_automatic_options = True app.route('/', methods=['OPTIONS'])(index2) rv = app.test_client().open('/', method='OPTIONS') assert sorted(rv.allow) == ['OPTIONS'] def test_request_dispatching(): app = flask.Flask(__name__) @app.route('/') def index(): return flask.request.method @app.route('/more', methods=['GET', 'POST']) def more(): return flask.request.method c = app.test_client() assert c.get('/').data == b'GET' rv = c.post('/') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS'] rv = c.head('/') assert rv.status_code == 200 assert not rv.data # head truncates assert c.post('/more').data == b'POST' assert c.get('/more').data == b'GET' rv = c.delete('/more') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] def test_disallow_string_for_allowed_methods(): app = flask.Flask(__name__) with pytest.raises(TypeError): @app.route('/', methods='GET POST') def index(): return "Hey" def test_url_mapping(): app = flask.Flask(__name__) random_uuid4 = "7eb41166-9ebf-4d26-b771-ea3f54f8b383" def index(): return flask.request.method def more(): return flask.request.method def options(): return random_uuid4 app.add_url_rule('/', 'index', index) app.add_url_rule('/more', 'more', more, methods=['GET', 'POST']) # Issue 1288: Test that automatic options are not added when non-uppercase 'options' in methods app.add_url_rule('/options', 'options', options, methods=['options']) c = app.test_client() assert c.get('/').data == b'GET' rv = c.post('/') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS'] rv = c.head('/') assert rv.status_code == 200 assert not rv.data # head truncates assert c.post('/more').data == b'POST' assert c.get('/more').data == b'GET' rv = c.delete('/more') assert rv.status_code == 405 assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] rv = c.open('/options', method='OPTIONS') assert rv.status_code == 200 assert random_uuid4 in rv.data.decode("utf-8") def test_werkzeug_routing(): from werkzeug.routing import Submount, Rule app = flask.Flask(__name__) app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) def bar(): return 'bar' def index(): return 'index' app.view_functions['bar'] = bar app.view_functions['index'] = index c = app.test_client() assert c.get('/foo/').data == b'index' assert c.get('/foo/bar').data == b'bar' def test_endpoint_decorator(): from werkzeug.routing import Submount, Rule app = flask.Flask(__name__) app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) @app.endpoint('bar') def bar(): return 'bar' @app.endpoint('index') def index(): return 'index' c = app.test_client() assert c.get('/foo/').data == b'index' assert c.get('/foo/bar').data == b'bar' def test_session(): app = flask.Flask(__name__) app.secret_key = 'testkey' @app.route('/set', methods=['POST']) def set(): flask.session['value'] = flask.request.form['value'] return 'value set' @app.route('/get') def get(): return flask.session['value'] c = app.test_client() assert c.post('/set', data={'value': '42'}).data == b'value set' assert c.get('/get').data == b'42' def test_session_using_server_name(): app = flask.Flask(__name__) app.config.update( SECRET_KEY='foo', SERVER_NAME='example.com' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com/') assert 'domain=.example.com' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower() def test_session_using_server_name_and_port(): app = flask.Flask(__name__) app.config.update( SECRET_KEY='foo', SERVER_NAME='example.com:8080' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') assert 'domain=.example.com' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower() def test_session_using_server_name_port_and_path(): app = flask.Flask(__name__) app.config.update( SECRET_KEY='foo', SERVER_NAME='example.com:8080', APPLICATION_ROOT='/foo' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/foo') assert 'domain=example.com' in rv.headers['set-cookie'].lower() assert 'path=/foo' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower() def test_session_using_application_root(): class PrefixPathMiddleware(object): def __init__(self, app, prefix): self.app = app self.prefix = prefix def __call__(self, environ, start_response): environ['SCRIPT_NAME'] = self.prefix return self.app(environ, start_response) app = flask.Flask(__name__) app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar') app.config.update( SECRET_KEY='foo', APPLICATION_ROOT='/bar' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') assert 'path=/bar' in rv.headers['set-cookie'].lower() def test_session_using_session_settings(): app = flask.Flask(__name__) app.config.update( SECRET_KEY='foo', SERVER_NAME='www.example.com:8080', APPLICATION_ROOT='/test', SESSION_COOKIE_DOMAIN='.example.com', SESSION_COOKIE_HTTPONLY=False, SESSION_COOKIE_SECURE=True, SESSION_COOKIE_PATH='/' ) @app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://www.example.com:8080/test/') cookie = rv.headers['set-cookie'].lower() assert 'domain=.example.com' in cookie assert 'path=/' in cookie assert 'secure' in cookie assert 'httponly' not in cookie def test_missing_session(): app = flask.Flask(__name__) def expect_exception(f, *args, **kwargs): try: f(*args, **kwargs) except RuntimeError as e: assert e.args and 'session is unavailable' in e.args[0] else: assert False, 'expected exception' with app.test_request_context(): assert flask.session.get('missing_key') is None expect_exception(flask.session.__setitem__, 'foo', 42) expect_exception(flask.session.pop, 'foo') def test_session_expiration(): permanent = True app = flask.Flask(__name__) app.secret_key = 'testkey' @app.route('/') def index(): flask.session['test'] = 42 flask.session.permanent = permanent return '' @app.route('/test') def test(): return text_type(flask.session.permanent) client = app.test_client() rv = client.get('/') assert 'set-cookie' in rv.headers match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie']) expires = parse_date(match.group()) expected = datetime.utcnow() + app.permanent_session_lifetime assert expires.year == expected.year assert expires.month == expected.month assert expires.day == expected.day rv = client.get('/test') assert rv.data == b'True' permanent = False rv = app.test_client().get('/') assert 'set-cookie' in rv.headers match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) assert match is None def test_session_stored_last(): app = flask.Flask(__name__) app.secret_key = 'development-key' app.testing = True @app.after_request def modify_session(response): flask.session['foo'] = 42 return response @app.route('/') def dump_session_contents(): return repr(flask.session.get('foo')) c = app.test_client() assert c.get('/').data == b'None' assert c.get('/').data == b'42' def test_session_special_types(): app = flask.Flask(__name__) app.secret_key = 'development-key' app.testing = True now = datetime.utcnow().replace(microsecond=0) the_uuid = uuid.uuid4() @app.after_request def modify_session(response): flask.session['m'] = flask.Markup('Hello!') flask.session['u'] = the_uuid flask.session['dt'] = now flask.session['b'] = b'\xff' flask.session['t'] = (1, 2, 3) return response @app.route('/') def dump_session_contents(): return pickle.dumps(dict(flask.session)) c = app.test_client() c.get('/') rv = pickle.loads(c.get('/').data) assert rv['m'] == flask.Markup('Hello!') assert type(rv['m']) == flask.Markup assert rv['dt'] == now assert rv['u'] == the_uuid assert rv['b'] == b'\xff' assert type(rv['b']) == bytes assert rv['t'] == (1, 2, 3) def test_session_cookie_setting(): app = flask.Flask(__name__) app.testing = True app.secret_key = 'dev key' is_permanent = True @app.route('/bump') def bump(): rv = flask.session['foo'] = flask.session.get('foo', 0) + 1 flask.session.permanent = is_permanent return str(rv) @app.route('/read') def read(): return str(flask.session.get('foo', 0)) def run_test(expect_header): with app.test_client() as c: assert c.get('/bump').data == b'1' assert c.get('/bump').data == b'2' assert c.get('/bump').data == b'3' rv = c.get('/read') set_cookie = rv.headers.get('set-cookie') assert (set_cookie is not None) == expect_header assert rv.data == b'3' is_permanent = True app.config['SESSION_REFRESH_EACH_REQUEST'] = True run_test(expect_header=True) is_permanent = True app.config['SESSION_REFRESH_EACH_REQUEST'] = False run_test(expect_header=False) is_permanent = False app.config['SESSION_REFRESH_EACH_REQUEST'] = True run_test(expect_header=False) is_permanent = False app.config['SESSION_REFRESH_EACH_REQUEST'] = False run_test(expect_header=False) def test_flashes(): app = flask.Flask(__name__) app.secret_key = 'testkey' with app.test_request_context(): assert not flask.session.modified flask.flash('Zap') flask.session.modified = False flask.flash('Zip') assert flask.session.modified assert list(flask.get_flashed_messages()) == ['Zap', 'Zip'] def test_extended_flashing(): # Be sure app.testing=True below, else tests can fail silently. # # Specifically, if app.testing is not set to True, the AssertionErrors # in the view functions will cause a 500 response to the test client # instead of propagating exceptions. app = flask.Flask(__name__) app.secret_key = 'testkey' app.testing = True @app.route('/') def index(): flask.flash(u'Hello World') flask.flash(u'Hello World', 'error') flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning') return '' @app.route('/test/') def test(): messages = flask.get_flashed_messages() assert list(messages) == [ u'Hello World', u'Hello World', flask.Markup(u'<em>Testing</em>') ] return '' @app.route('/test_with_categories/') def test_with_categories(): messages = flask.get_flashed_messages(with_categories=True) assert len(messages) == 3 assert list(messages) == [ ('message', u'Hello World'), ('error', u'Hello World'), ('warning', flask.Markup(u'<em>Testing</em>')) ] return '' @app.route('/test_filter/') def test_filter(): messages = flask.get_flashed_messages( category_filter=['message'], with_categories=True) assert list(messages) == [('message', u'Hello World')] return '' @app.route('/test_filters/') def test_filters(): messages = flask.get_flashed_messages( category_filter=['message', 'warning'], with_categories=True) assert list(messages) == [ ('message', u'Hello World'), ('warning', flask.Markup(u'<em>Testing</em>')) ] return '' @app.route('/test_filters_without_returning_categories/') def test_filters2(): messages = flask.get_flashed_messages( category_filter=['message', 'warning']) assert len(messages) == 2 assert messages[0] == u'Hello World' assert messages[1] == flask.Markup(u'<em>Testing</em>') return '' # Create new test client on each test to clean flashed messages. c = app.test_client() c.get('/') c.get('/test/') c = app.test_client() c.get('/') c.get('/test_with_categories/') c = app.test_client() c.get('/') c.get('/test_filter/') c = app.test_client() c.get('/') c.get('/test_filters/') c = app.test_client() c.get('/') c.get('/test_filters_without_returning_categories/') def test_request_processing(): app = flask.Flask(__name__) evts = [] @app.before_request def before_request(): evts.append('before') @app.after_request def after_request(response): response.data += b'|after' evts.append('after') return response @app.route('/') def index(): assert 'before' in evts assert 'after' not in evts return 'request' assert 'after' not in evts rv = app.test_client().get('/').data assert 'after' in evts assert rv == b'request|after' def test_request_preprocessing_early_return(): app = flask.Flask(__name__) evts = [] @app.before_request def before_request1(): evts.append(1) @app.before_request def before_request2(): evts.append(2) return "hello" @app.before_request def before_request3(): evts.append(3) return "bye" @app.route('/') def index(): evts.append('index') return "damnit" rv = app.test_client().get('/').data.strip() assert rv == b'hello' assert evts == [1, 2] def test_after_request_processing(): app = flask.Flask(__name__) app.testing = True @app.route('/') def index(): @flask.after_this_request def foo(response): response.headers['X-Foo'] = 'a header' return response return 'Test' c = app.test_client() resp = c.get('/') assert resp.status_code == 200 assert resp.headers['X-Foo'] == 'a header' def test_teardown_request_handler(): called = [] app = flask.Flask(__name__) @app.teardown_request def teardown_request(exc): called.append(True) return "Ignored" @app.route('/') def root(): return "Response" rv = app.test_client().get('/') assert rv.status_code == 200 assert b'Response' in rv.data assert len(called) == 1 def test_teardown_request_handler_debug_mode(): called = [] app = flask.Flask(__name__) app.testing = True @app.teardown_request def teardown_request(exc): called.append(True) return "Ignored" @app.route('/') def root(): return "Response" rv = app.test_client().get('/') assert rv.status_code == 200 assert b'Response' in rv.data assert len(called) == 1 def test_teardown_request_handler_error(): called = [] app = flask.Flask(__name__) app.config['LOGGER_HANDLER_POLICY'] = 'never' @app.teardown_request def teardown_request1(exc): assert type(exc) == ZeroDivisionError called.append(True) # This raises a new error and blows away sys.exc_info(), so we can # test that all teardown_requests get passed the same original # exception. try: raise TypeError() except: pass @app.teardown_request def teardown_request2(exc): assert type(exc) == ZeroDivisionError called.append(True) # This raises a new error and blows away sys.exc_info(), so we can # test that all teardown_requests get passed the same original # exception. try: raise TypeError() except: pass @app.route('/') def fails(): 1 // 0 rv = app.test_client().get('/') assert rv.status_code == 500 assert b'Internal Server Error' in rv.data assert len(called) == 2 def test_before_after_request_order(): called = [] app = flask.Flask(__name__) @app.before_request def before1(): called.append(1) @app.before_request def before2(): called.append(2) @app.after_request def after1(response): called.append(4) return response @app.after_request def after2(response): called.append(3) return response @app.teardown_request def finish1(exc): called.append(6) @app.teardown_request def finish2(exc): called.append(5) @app.route('/') def index(): return '42' rv = app.test_client().get('/') assert rv.data == b'42' assert called == [1, 2, 3, 4, 5, 6] def test_error_handling(): app = flask.Flask(__name__) app.config['LOGGER_HANDLER_POLICY'] = 'never' @app.errorhandler(404) def not_found(e): return 'not found', 404 @app.errorhandler(500) def internal_server_error(e): return 'internal server error', 500 @app.errorhandler(Forbidden) def forbidden(e): return 'forbidden', 403 @app.route('/') def index(): flask.abort(404) @app.route('/error') def error(): 1 // 0 @app.route('/forbidden') def error2(): flask.abort(403) c = app.test_client() rv = c.get('/') assert rv.status_code == 404 assert rv.data == b'not found' rv = c.get('/error') assert rv.status_code == 500 assert b'internal server error' == rv.data rv = c.get('/forbidden') assert rv.status_code == 403 assert b'forbidden' == rv.data def test_before_request_and_routing_errors(): app = flask.Flask(__name__) @app.before_request def attach_something(): flask.g.something = 'value' @app.errorhandler(404) def return_something(error): return flask.g.something, 404 rv = app.test_client().get('/') assert rv.status_code == 404 assert rv.data == b'value' def test_user_error_handling(): class MyException(Exception): pass app = flask.Flask(__name__) @app.errorhandler(MyException) def handle_my_exception(e): assert isinstance(e, MyException) return '42' @app.route('/') def index(): raise MyException() c = app.test_client() assert c.get('/').data == b'42' def test_http_error_subclass_handling(): class ForbiddenSubclass(Forbidden): pass app = flask.Flask(__name__) @app.errorhandler(ForbiddenSubclass) def handle_forbidden_subclass(e): assert isinstance(e, ForbiddenSubclass) return 'banana' @app.errorhandler(403) def handle_forbidden_subclass(e): assert not isinstance(e, ForbiddenSubclass) assert isinstance(e, Forbidden) return 'apple' @app.route('/1') def index1(): raise ForbiddenSubclass() @app.route('/2') def index2(): flask.abort(403) @app.route('/3') def index3(): raise Forbidden() c = app.test_client() assert c.get('/1').data == b'banana' assert c.get('/2').data == b'apple' assert c.get('/3').data == b'apple' def test_trapping_of_bad_request_key_errors(): app = flask.Flask(__name__) app.testing = True @app.route('/fail') def fail(): flask.request.form['missing_key'] c = app.test_client() assert c.get('/fail').status_code == 400 app.config['TRAP_BAD_REQUEST_ERRORS'] = True c = app.test_client() try: c.get('/fail') except KeyError as e: assert isinstance(e, BadRequest) else: assert False, 'Expected exception' def test_trapping_of_all_http_exceptions(): app = flask.Flask(__name__) app.testing = True app.config['TRAP_HTTP_EXCEPTIONS'] = True @app.route('/fail') def fail(): flask.abort(404) c = app.test_client() with pytest.raises(NotFound): c.get('/fail') def test_enctype_debug_helper(): from flask.debughelpers import DebugFilesKeyError app = flask.Flask(__name__) app.debug = True @app.route('/fail', methods=['POST']) def index(): return flask.request.files['foo'].filename # with statement is important because we leave an exception on the # stack otherwise and we want to ensure that this is not the case # to not negatively affect other tests. with app.test_client() as c: try: c.post('/fail', data={'foo': 'index.txt'}) except DebugFilesKeyError as e: assert 'no file contents were transmitted' in str(e) assert 'This was submitted: "index.txt"' in str(e) else: assert False, 'Expected exception' def test_response_creation(): app = flask.Flask(__name__) @app.route('/unicode') def from_unicode(): return u'Hällo Wörld' @app.route('/string') def from_string(): return u'Hällo Wörld'.encode('utf-8') @app.route('/args') def from_tuple(): return 'Meh', 400, { 'X-Foo': 'Testing', 'Content-Type': 'text/plain; charset=utf-8' } @app.route('/two_args') def from_two_args_tuple(): return 'Hello', { 'X-Foo': 'Test', 'Content-Type': 'text/plain; charset=utf-8' } @app.route('/args_status') def from_status_tuple(): return 'Hi, status!', 400 @app.route('/args_header') def from_response_instance_status_tuple(): return flask.Response('Hello world', 404), { "X-Foo": "Bar", "X-Bar": "Foo" } c = app.test_client() assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8') assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8') rv = c.get('/args') assert rv.data == b'Meh' assert rv.headers['X-Foo'] == 'Testing' assert rv.status_code == 400 assert rv.mimetype == 'text/plain' rv2 = c.get('/two_args') assert rv2.data == b'Hello' assert rv2.headers['X-Foo'] == 'Test' assert rv2.status_code == 200 assert rv2.mimetype == 'text/plain' rv3 = c.get('/args_status') assert rv3.data == b'Hi, status!' assert rv3.status_code == 400 assert rv3.mimetype == 'text/html' rv4 = c.get('/args_header') assert rv4.data == b'Hello world' assert rv4.headers['X-Foo'] == 'Bar' assert rv4.headers['X-Bar'] == 'Foo' assert rv4.status_code == 404 def test_make_response(): app = flask.Flask(__name__) with app.test_request_context(): rv = flask.make_response() assert rv.status_code == 200 assert rv.data == b'' assert rv.mimetype == 'text/html' rv = flask.make_response('Awesome') assert rv.status_code == 200 assert rv.data == b'Awesome' assert rv.mimetype == 'text/html' rv = flask.make_response('W00t', 404) assert rv.status_code == 404 assert rv.data == b'W00t' assert rv.mimetype == 'text/html' def test_make_response_with_response_instance(): app = flask.Flask(__name__) with app.test_request_context(): rv = flask.make_response( flask.jsonify({'msg': 'W00t'}), 400) assert rv.status_code == 400 assert rv.data == b'{\n "msg": "W00t"\n}\n' assert rv.mimetype == 'application/json' rv = flask.make_response( flask.Response(''), 400) assert rv.status_code == 400 assert rv.data == b'' assert rv.mimetype == 'text/html' rv = flask.make_response( flask.Response('', headers={'Content-Type': 'text/html'}), 400, [('X-Foo', 'bar')]) assert rv.status_code == 400 assert rv.headers['Content-Type'] == 'text/html' assert rv.headers['X-Foo'] == 'bar' def test_jsonify_no_prettyprint(): app = flask.Flask(__name__) app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False}) with app.test_request_context(): compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}\n' uncompressed_msg = { "msg": { "submsg": "W00t" }, "msg2": "foobar" } rv = flask.make_response( flask.jsonify(uncompressed_msg), 200) assert rv.data == compressed_msg def test_jsonify_prettyprint(): app = flask.Flask(__name__) app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True}) with app.test_request_context(): compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"} pretty_response =\ b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}\n' rv = flask.make_response( flask.jsonify(compressed_msg), 200) assert rv.data == pretty_response def test_url_generation(): app = flask.Flask(__name__) @app.route('/hello/<name>', methods=['POST']) def hello(): pass with app.test_request_context(): assert flask.url_for('hello', name='test x') == '/hello/test%20x' assert flask.url_for('hello', name='test x', _external=True) == \ 'http://localhost/hello/test%20x' def test_build_error_handler(): app = flask.Flask(__name__) # Test base case, a URL which results in a BuildError. with app.test_request_context(): pytest.raises(BuildError, flask.url_for, 'spam') # Verify the error is re-raised if not the current exception. try: with app.test_request_context(): flask.url_for('spam') except BuildError as err: error = err try: raise RuntimeError('Test case where BuildError is not current.') except RuntimeError: pytest.raises( BuildError, app.handle_url_build_error, error, 'spam', {}) # Test a custom handler. def handler(error, endpoint, values): # Just a test. return '/test_handler/' app.url_build_error_handlers.append(handler) with app.test_request_context(): assert flask.url_for('spam') == '/test_handler/' def test_custom_converters(): from werkzeug.routing import BaseConverter class ListConverter(BaseConverter): def to_python(self, value): return value.split(',') def to_url(self, value): base_to_url = super(ListConverter, self).to_url return ','.join(base_to_url(x) for x in value) app = flask.Flask(__name__) app.url_map.converters['list'] = ListConverter @app.route('/<list:args>') def index(args): return '|'.join(args) c = app.test_client() assert c.get('/1,2,3').data == b'1|2|3' def test_static_files(): app = flask.Flask(__name__) app.testing = True rv = app.test_client().get('/static/index.html') assert rv.status_code == 200 assert rv.data.strip() == b'<h1>Hello World!</h1>' with app.test_request_context(): assert flask.url_for('static', filename='index.html') == \ '/static/index.html' rv.close() def test_none_response(): app = flask.Flask(__name__) app.testing = True @app.route('/') def test(): return None try: app.test_client().get('/') except ValueError as e: assert str(e) == 'View function did not return a response' pass else: assert "Expected ValueError" def test_request_locals(): assert repr(flask.g) == '<LocalProxy unbound>' assert not flask.g def test_test_app_proper_environ(): app = flask.Flask(__name__) app.config.update( SERVER_NAME='localhost.localdomain:5000' ) @app.route('/') def index(): return 'Foo' @app.route('/', subdomain='foo') def subdomain(): return 'Foo SubDomain' rv = app.test_client().get('/') assert rv.data == b'Foo' rv = app.test_client().get('/', 'http://localhost.localdomain:5000') assert rv.data == b'Foo' rv = app.test_client().get('/', 'https://localhost.localdomain:5000') assert rv.data == b'Foo' app.config.update(SERVER_NAME='localhost.localdomain') rv = app.test_client().get('/', 'https://localhost.localdomain') assert rv.data == b'Foo' try: app.config.update(SERVER_NAME='localhost.localdomain:443') rv = app.test_client().get('/', 'https://localhost.localdomain') # Werkzeug 0.8 assert rv.status_code == 404 except ValueError as e: # Werkzeug 0.7 assert str(e) == ( "the server name provided " "('localhost.localdomain:443') does not match the " "server name from the WSGI environment ('localhost.localdomain')" ) try: app.config.update(SERVER_NAME='localhost.localdomain') rv = app.test_client().get('/', 'http://foo.localhost') # Werkzeug 0.8 assert rv.status_code == 404 except ValueError as e: # Werkzeug 0.7 assert str(e) == ( "the server name provided " "('localhost.localdomain') does not match the " "server name from the WSGI environment ('foo.localhost')" ) rv = app.test_client().get('/', 'http://foo.localhost.localdomain') assert rv.data == b'Foo SubDomain' def test_exception_propagation(): def apprunner(config_key): app = flask.Flask(__name__) app.config['LOGGER_HANDLER_POLICY'] = 'never' @app.route('/') def index(): 1 // 0 c = app.test_client() if config_key is not None: app.config[config_key] = True try: c.get('/') except Exception: pass else: assert False, 'expected exception' else: assert c.get('/').status_code == 500 # we have to run this test in an isolated thread because if the # debug flag is set to true and an exception happens the context is # not torn down. This causes other tests that run after this fail # when they expect no exception on the stack. for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None: t = Thread(target=apprunner, args=(config_key,)) t.start() t.join() def test_max_content_length(): app = flask.Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 64 @app.before_request def always_first(): flask.request.form['myfile'] assert False @app.route('/accept', methods=['POST']) def accept_file(): flask.request.form['myfile'] assert False @app.errorhandler(413) def catcher(error): return '42' c = app.test_client() rv = c.post('/accept', data={'myfile': 'foo' * 100}) assert rv.data == b'42' def test_url_processors(): app = flask.Flask(__name__) @app.url_defaults def add_language_code(endpoint, values): if flask.g.lang_code is not None and \ app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): values.setdefault('lang_code', flask.g.lang_code) @app.url_value_preprocessor def pull_lang_code(endpoint, values): flask.g.lang_code = values.pop('lang_code', None) @app.route('/<lang_code>/') def index(): return flask.url_for('about') @app.route('/<lang_code>/about') def about(): return flask.url_for('something_else') @app.route('/foo') def something_else(): return flask.url_for('about', lang_code='en') c = app.test_client() assert c.get('/de/').data == b'/de/about' assert c.get('/de/about').data == b'/foo' assert c.get('/foo').data == b'/en/about' def test_inject_blueprint_url_defaults(): app = flask.Flask(__name__) bp = flask.Blueprint('foo.bar.baz', __name__, template_folder='template') @bp.url_defaults def bp_defaults(endpoint, values): values['page'] = 'login' @bp.route('/<page>') def view(page): pass app.register_blueprint(bp) values = dict() app.inject_url_defaults('foo.bar.baz.view', values) expected = dict(page='login') assert values == expected with app.test_request_context('/somepage'): url = flask.url_for('foo.bar.baz.view') expected = '/login' assert url == expected def test_nonascii_pathinfo(): app = flask.Flask(__name__) app.testing = True @app.route(u'/киртест') def index(): return 'Hello World!' c = app.test_client() rv = c.get(u'/киртест') assert rv.data == b'Hello World!' def test_debug_mode_complains_after_first_request(): app = flask.Flask(__name__) app.debug = True @app.route('/') def index(): return 'Awesome' assert not app.got_first_request assert app.test_client().get('/').data == b'Awesome' try: @app.route('/foo') def broken(): return 'Meh' except AssertionError as e: assert 'A setup function was called' in str(e) else: assert False, 'Expected exception' app.debug = False @app.route('/foo') def working(): return 'Meh' assert app.test_client().get('/foo').data == b'Meh' assert app.got_first_request def test_before_first_request_functions(): got = [] app = flask.Flask(__name__) @app.before_first_request def foo(): got.append(42) c = app.test_client() c.get('/') assert got == [42] c.get('/') assert got == [42] assert app.got_first_request def test_before_first_request_functions_concurrent(): got = [] app = flask.Flask(__name__) @app.before_first_request def foo(): time.sleep(0.2) got.append(42) c = app.test_client() def get_and_assert(): c.get("/") assert got == [42] t = Thread(target=get_and_assert) t.start() get_and_assert() t.join() assert app.got_first_request def test_routing_redirect_debugging(): app = flask.Flask(__name__) app.debug = True @app.route('/foo/', methods=['GET', 'POST']) def foo(): return 'success' with app.test_client() as c: try: c.post('/foo', data={}) except AssertionError as e: assert 'http://localhost/foo/' in str(e) assert ('Make sure to directly send ' 'your POST-request to this URL') in str(e) else: assert False, 'Expected exception' rv = c.get('/foo', data={}, follow_redirects=True) assert rv.data == b'success' app.debug = False with app.test_client() as c: rv = c.post('/foo', data={}, follow_redirects=True) assert rv.data == b'success' def test_route_decorator_custom_endpoint(): app = flask.Flask(__name__) app.debug = True @app.route('/foo/') def foo(): return flask.request.endpoint @app.route('/bar/', endpoint='bar') def for_bar(): return flask.request.endpoint @app.route('/bar/123', endpoint='123') def for_bar_foo(): return flask.request.endpoint with app.test_request_context(): assert flask.url_for('foo') == '/foo/' assert flask.url_for('bar') == '/bar/' assert flask.url_for('123') == '/bar/123' c = app.test_client() assert c.get('/foo/').data == b'foo' assert c.get('/bar/').data == b'bar' assert c.get('/bar/123').data == b'123' def test_preserve_only_once(): app = flask.Flask(__name__) app.debug = True @app.route('/fail') def fail_func(): 1 // 0 c = app.test_client() for x in range(3): with pytest.raises(ZeroDivisionError): c.get('/fail') assert flask._request_ctx_stack.top is not None assert flask._app_ctx_stack.top is not None # implicit appctx disappears too flask._request_ctx_stack.top.pop() assert flask._request_ctx_stack.top is None assert flask._app_ctx_stack.top is None def test_preserve_remembers_exception(): app = flask.Flask(__name__) app.debug = True errors = [] @app.route('/fail') def fail_func(): 1 // 0 @app.route('/success') def success_func(): return 'Okay' @app.teardown_request def teardown_handler(exc): errors.append(exc) c = app.test_client() # After this failure we did not yet call the teardown handler with pytest.raises(ZeroDivisionError): c.get('/fail') assert errors == [] # But this request triggers it, and it's an error c.get('/success') assert len(errors) == 2 assert isinstance(errors[0], ZeroDivisionError) # At this point another request does nothing. c.get('/success') assert len(errors) == 3 assert errors[1] is None def test_get_method_on_g(): app = flask.Flask(__name__) app.testing = True with app.app_context(): assert flask.g.get('x') is None assert flask.g.get('x', 11) == 11 flask.g.x = 42 assert flask.g.get('x') == 42 assert flask.g.x == 42 def test_g_iteration_protocol(): app = flask.Flask(__name__) app.testing = True with app.app_context(): flask.g.foo = 23 flask.g.bar = 42 assert 'foo' in flask.g assert 'foos' not in flask.g assert sorted(flask.g) == ['bar', 'foo'] def test_subdomain_basic_support(): app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'localhost' @app.route('/') def normal_index(): return 'normal index' @app.route('/', subdomain='test') def test_index(): return 'test index' c = app.test_client() rv = c.get('/', 'http://localhost/') assert rv.data == b'normal index' rv = c.get('/', 'http://test.localhost/') assert rv.data == b'test index' def test_subdomain_matching(): app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'localhost' @app.route('/', subdomain='<user>') def index(user): return 'index for %s' % user c = app.test_client() rv = c.get('/', 'http://mitsuhiko.localhost/') assert rv.data == b'index for mitsuhiko' def test_subdomain_matching_with_ports(): app = flask.Flask(__name__) app.config['SERVER_NAME'] = 'localhost:3000' @app.route('/', subdomain='<user>') def index(user): return 'index for %s' % user c = app.test_client() rv = c.get('/', 'http://mitsuhiko.localhost:3000/') assert rv.data == b'index for mitsuhiko' def test_multi_route_rules(): app = flask.Flask(__name__) @app.route('/') @app.route('/<test>/') def index(test='a'): return test rv = app.test_client().open('/') assert rv.data == b'a' rv = app.test_client().open('/b/') assert rv.data == b'b' def test_multi_route_class_views(): class View(object): def __init__(self, app): app.add_url_rule('/', 'index', self.index) app.add_url_rule('/<test>/', 'index', self.index) def index(self, test='a'): return test app = flask.Flask(__name__) _ = View(app) rv = app.test_client().open('/') assert rv.data == b'a' rv = app.test_client().open('/b/') assert rv.data == b'b' def test_run_defaults(monkeypatch): rv = {} # Mocks werkzeug.serving.run_simple method def run_simple_mock(*args, **kwargs): rv['result'] = 'running...' app = flask.Flask(__name__) monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock) app.run() assert rv['result'] == 'running...' def test_run_server_port(monkeypatch): rv = {} # Mocks werkzeug.serving.run_simple method def run_simple_mock(hostname, port, application, *args, **kwargs): rv['result'] = 'running on %s:%s ...' % (hostname, port) app = flask.Flask(__name__) monkeypatch.setattr(werkzeug.serving, 'run_simple', run_simple_mock) hostname, port = 'localhost', 8000 app.run(hostname, port, debug=True) assert rv['result'] == 'running on %s:%s ...' % (hostname, port)
tangfeng1/flask
tests/test_basic.py
Python
bsd-3-clause
42,900
#File to read the data from mysql and push into CSV. # Python imports import datetime as dt import csv import copy import os import pickle # 3rd party imports import numpy as np import matplotlib.pyplot as plt import pandas as pd # QSTK imports from QSTK.qstkutil import qsdateutil as du import QSTK.qstkutil.DataEvolved as de def get_data(ls_symbols, ls_keys): ''' @summary: Gets a data chunk for backtesting @param dt_start: Start time @param dt_end: End time @param ls_symbols: symbols to use @note: More data will be pulled from before and after the limits to ensure valid data on the start/enddates which requires lookback/forward @return: data dictionry ''' print "Getting Data from MySQL" # Modify dates to ensure enough data for all features dt_start = dt.datetime(2005,1,1) dt_end = dt.datetime(2012, 8, 31) ldt_timestamps = du.getNYSEdays( dt_start, dt_end, dt.timedelta(hours=16) ) c_da = de.DataAccess('mysql') ldf_data = c_da.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) return d_data def read_symbols(s_symbols_file): ls_symbols=[] file = open(s_symbols_file, 'r') for f in file.readlines(): j = f[:-1] ls_symbols.append(j) file.close() return ls_symbols def csv_sym(sym, d_data, ls_keys, s_directory): bool_first_iter = True for key in ls_keys: if bool_first_iter == True: df_sym = d_data[key].reindex(columns = [sym]) df_sym = df_sym.rename(columns = {sym : key}) bool_first_iter = False else: df_temp = d_data[key].reindex(columns = [sym]) df_temp = df_temp.rename(columns = {sym : key}) df_sym = df_sym.join(df_temp, how= 'outer') symfilename = sym.split('-')[0] sym_file = open(s_directory + symfilename + '.csv', 'w') sym_file.write("Date,Open,High,Low,Close,Volume,Adj Close \n") ldt_timestamps = list(df_sym.index) ldt_timestamps.reverse() for date in ldt_timestamps: date_to_csv = '{:%Y-%m-%d}'.format(date) string_to_csv = date_to_csv for key in ls_keys: string_to_csv = string_to_csv + ',' + str(df_sym[key][date]) string_to_csv = string_to_csv + '\n' sym_file.write(string_to_csv) def main(s_directory, s_symbols_file): #ls_symbols = read_symbols(s_symbols_file) ls_symbols = ['ACS-201002','BDK-201003','BJS-201004','BSC-201108','CCT-201111','EQ-200907','JAVA-201002','NCC-200901','NOVL-201104','PBG-201003','PTV-201011','ROH-200904','SGP-200911','SII-201008','WB-200901','WYE-200910','XTO-201006'] ls_keys = ['actual_open', 'actual_high', 'actual_low', 'actual_close', 'volume', 'close'] d_data = get_data(ls_symbols, ls_keys) # print d_data print "Creating CSV files now" for sym in ls_symbols: print sym csv_sym(sym,d_data, ls_keys, s_directory) print "Created all CSV files" if __name__ == '__main__' : s_directory = 'MLTData/' s_directory = os.environ['QSDATA'] + '/Yahoo/' s_symbols_file1 = 'MLTData/sp5002012.txt' s_symbols_file2 = 'MLTData/index.txt' s_symbols_file3 = 'MLTData/sp5002008.txt' main(s_directory, s_symbols_file3)
wogsland/QSTK
build/lib.linux-x86_64-2.7/Bin/Data_CSV.py
Python
bsd-3-clause
3,301
import unittest from scrabble import score class WordTest(unittest.TestCase): def test_invalid_word_scores_zero(self): self.assertEqual(0, score('')) self.assertEqual(0, score(' \t\n')) self.assertEqual(0, score('hous3')) self.assertEqual(0, score('wo rd')) def test_scores_very_short_word(self): self.assertEqual(1, score('a')) def test_scores_other_very_short_word(self): self.assertEqual(4, score('f')) def test_simple_word_scores_the_number_of_letters(self): self.assertEqual(6, score("street")) def test_complicated_word_scores_more(self): self.assertEqual(22, score("quirky")) def test_scores_are_case_insensitive(self): self.assertEqual(41, score("OxyphenButazone")) if __name__ == '__main__': unittest.main()
wobh/xpython
scrabble-score/scrabble_score_test.py
Python
mit
826
from django.conf.urls import patterns, url from polls import views urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'), )
kwailamchan/programming-languages
python/django/polls/pollsite/polls/urls.py
Python
mit
374
# Copyright 2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 __all__ = ['ArgumentParser'] try: from argparse import ArgumentParser except ImportError: # Compatibility with Python 2.6 and 3.1 from optparse import OptionGroup, OptionParser from portage.localization import _ class ArgumentParser(object): def __init__(self, **kwargs): add_help = kwargs.pop("add_help", None) if add_help is not None: kwargs["add_help_option"] = add_help parser = OptionParser(**kwargs) self._parser = parser self.add_argument = parser.add_option self.print_help = parser.print_help self.error = parser.error def add_argument_group(self, title=None, **kwargs): optiongroup = OptionGroup(self._parser, title, **kwargs) self._parser.add_option_group(optiongroup) return _ArgumentGroup(optiongroup) def parse_known_args(self, args=None, namespace=None): return self._parser.parse_args(args, namespace) def parse_args(self, args=None, namespace=None): args, argv = self.parse_known_args(args, namespace) if argv: msg = _('unrecognized arguments: %s') self.error(msg % ' '.join(argv)) return args class _ArgumentGroup(object): def __init__(self, optiongroup): self.add_argument = optiongroup.add_option
nullishzero/Portage
pym/portage/util/_argparse.py
Python
gpl-2.0
1,300
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Component tests for VPC network functionality - Port Forwarding Rules. """ from nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase from marvin.lib.base import (stopRouter, startRouter, Account, VpcOffering, VPC, ServiceOffering, NATRule, NetworkACL, PublicIPAddress, NetworkOffering, Network, VirtualMachine, LoadBalancerRule) from marvin.lib.common import (get_domain, get_zone, get_template, list_routers) from marvin.lib.utils import cleanup_resources import socket import time import sys class Services: """Test VPC network services - Port Forwarding Rules Test Data Class. """ def __init__(self): self.services = { "account": { "email": "test@test.com", "firstname": "Test", "lastname": "User", "username": "test", # Random characters are appended for unique # username "password": "password", }, "host1": None, "host2": None, "service_offering": { "name": "Tiny Instance", "displaytext": "Tiny Instance", "cpunumber": 1, "cpuspeed": 100, "memory": 128, }, "network_offering": { "name": 'VPC Network offering', "displaytext": 'VPC Network off', "guestiptype": 'Isolated', "supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL', "traffictype": 'GUEST', "availability": 'Optional', "useVpc": 'on', "serviceProviderList": { "Vpn": 'VpcVirtualRouter', "Dhcp": 'VpcVirtualRouter', "Dns": 'VpcVirtualRouter', "SourceNat": 'VpcVirtualRouter', "PortForwarding": 'VpcVirtualRouter', "Lb": 'VpcVirtualRouter', "UserData": 'VpcVirtualRouter', "StaticNat": 'VpcVirtualRouter', "NetworkACL": 'VpcVirtualRouter' }, }, "network_offering_no_lb": { "name": 'VPC Network offering', "displaytext": 'VPC Network off', "guestiptype": 'Isolated', "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,UserData,StaticNat,NetworkACL', "traffictype": 'GUEST', "availability": 'Optional', "useVpc": 'on', "serviceProviderList": { "Dhcp": 'VpcVirtualRouter', "Dns": 'VpcVirtualRouter', "SourceNat": 'VpcVirtualRouter', "PortForwarding": 'VpcVirtualRouter', "UserData": 'VpcVirtualRouter', "StaticNat": 'VpcVirtualRouter', "NetworkACL": 'VpcVirtualRouter' }, }, "vpc_offering": { "name": 'VPC off', "displaytext": 'VPC off', "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat', }, "vpc": { "name": "TestVPC", "displaytext": "TestVPC", "cidr": '10.0.0.1/24' }, "network": { "name": "Test Network", "displaytext": "Test Network", "netmask": '255.255.255.0' }, "lbrule": { "name": "SSH", "alg": "leastconn", # Algorithm used for load balancing "privateport": 22, "publicport": 2222, "openfirewall": False, "startport": 22, "endport": 2222, "protocol": "TCP", "cidrlist": '0.0.0.0/0', }, "lbrule_http": { "name": "HTTP", "alg": "leastconn", # Algorithm used for load balancing "privateport": 80, "publicport": 8888, "openfirewall": False, "startport": 80, "endport": 8888, "protocol": "TCP", "cidrlist": '0.0.0.0/0', }, "natrule": { "privateport": 22, "publicport": 22, "startport": 22, "endport": 22, "protocol": "TCP", "cidrlist": '0.0.0.0/0', }, "http_rule": { "privateport": 80, "publicport": 80, "startport": 80, "endport": 80, "cidrlist": '0.0.0.0/0', "protocol": "TCP" }, "virtual_machine": { "displayname": "Test VM", "username": "root", "password": "password", "ssh_port": 22, # "hypervisor": 'XenServer', # Hypervisor type should be same as # hypervisor type of cluster "privateport": 22, "publicport": 22, "protocol": 'TCP', }, "ostype": 'CentOS 5.3 (64-bit)', "timeout": 10, } class TestVPCNetworkPFRules(cloudstackTestCase): @classmethod def setUpClass(cls): # We want to fail quicker if it's failure socket.setdefaulttimeout(60) cls.testClient = super(TestVPCNetworkPFRules, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = Services().services # Get Zone, Domain and templates cls.domain = get_domain(cls.api_client) cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests()) cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["virtual_machine"]["template"] = cls.template.id cls.service_offering = ServiceOffering.create( cls.api_client, cls.services["service_offering"] ) cls._cleanup = [cls.service_offering] return @classmethod def tearDownClass(cls): try: #Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.account = Account.create( self.apiclient, self.services["account"], admin=True, domainid=self.domain.id ) self.cleanup = [self.account] self.debug("Creating a VPC offering..") self.vpc_off = VpcOffering.create( self.apiclient, self.services["vpc_offering"] ) self.debug("Enabling the VPC offering created") self.vpc_off.update(self.apiclient, state='Enabled') self.debug("Creating a VPC network in the account: %s" % self.account.name) self.services["vpc"]["cidr"] = '10.1.1.1/16' self.vpc = VPC.create( self.apiclient, self.services["vpc"], vpcofferingid=self.vpc_off.id, zoneid=self.zone.id, account=self.account.name, domainid=self.account.domainid ) return def tearDown(self): try: #Clean up, terminate the created network offerings cleanup_resources(self.apiclient, self.cleanup) except Exception as e: self.debug("Warning: Exception during cleanup : %s" % e) return def get_vpcrouter(self): routers = list_routers(self.apiclient, account=self.account.name, domainid=self.account.domainid, ) self.assertEqual(isinstance(routers, list), True, "Check for list routers response return valid data" ) self.assertNotEqual(len(routers), 0, "Check list router response" ) router = routers[0] return router def stop_vpcrouter(self): router = self.get_vpcrouter() self.debug("Stopping router ID: %s" % router.id) cmd = stopRouter.stopRouterCmd() cmd.id = router.id self.apiclient.stopRouter(cmd) routers = list_routers(self.apiclient, account=self.account.name, domainid=self.account.domainid, ) self.assertEqual(isinstance(routers, list), True, "Check for list routers response return valid data" ) router = routers[0] self.assertEqual(router.state, 'Stopped', "Check list router response for router state" ) return router def start_vpcrouter(self, router): # Start the VPC Router self.debug("Starting router ID: %s" % router.id) cmd = startRouter.startRouterCmd() cmd.id = router.id self.apiclient.startRouter(cmd) routers = list_routers(self.apiclient, account=self.account.name, domainid=self.account.domainid, zoneid=self.zone.id ) self.assertEqual(isinstance(routers, list), True, "Check for list routers response return valid data" ) router = routers[0] self.assertEqual(router.state, 'Running', "Check list router response for router state" ) def check_ssh_into_vm(self, vm, public_ip, testnegative=False): self.debug("Checking if we can SSH into VM=%s on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress)) try: vm.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress) if not testnegative: self.debug("SSH into VM=%s on public_ip=%s is successfully" % (vm.name, public_ip.ipaddress.ipaddress)) else: self.fail("SSH into VM=%s on public_ip=%s is successfully" % (vm.name, public_ip.ipaddress.ipaddress)) except: if not testnegative: self.fail("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress)) else: self.debug("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress)) def check_wget_from_vm(self, vm, public_ip, network=None, testnegative=False, isVmAccessible=True): import urllib self.debug("Checking if we can wget from a VM=%s http server on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress)) try: if not isVmAccessible: self.create_natrule(vm, public_ip, network) self.setup_webserver(vm) urllib.urlretrieve("http://%s/test.html" % public_ip.ipaddress.ipaddress, filename="test.html") if not testnegative: self.debug("Successesfull to wget from VM=%s http server on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress)) else: self.fail("Successesfull to wget from VM=%s http server on public_ip=%s" % (vm.name, public_ip.ipaddress.ipaddress)) except Exception as e: if not testnegative: self.fail("Failed to wget from VM=%s http server on public_ip=%s: %s" % (vm.name, public_ip.ipaddress.ipaddress, e)) else: self.debug("Failed to wget from VM=%s http server on public_ip=%s: %s" % (vm.name, public_ip.ipaddress.ipaddress, e)) def setup_webserver(self, vm): # Start httpd service on VM first sshClient = vm.get_ssh_client() # Test to see if we are on a tiny linux box (using busybox) res = str(sshClient.execute("busybox")).lower() if "hexdump" in res: self.setup_busybox(sshClient) else: self.setup_apache(sshClient) def setup_busybox(self, sshClient): """ Create a dummy test.html file and fire up the busybox web server """ sshClient.execute('echo test > test.html') sshClient.execute("/usr/sbin/httpd") self.debug("Setup webserver using busybox") def setup_apache(self, sshClient): sshClient.execute("service httpd start") time.sleep(5) ssh_response = str(sshClient.execute("service httpd status")).lower() self.debug("httpd service status is: %s" % ssh_response) if "httpd: unrecognized service" in ssh_response or "inactive" in ssh_response: ssh_res = sshClient.execute("yum install httpd -y") if "Complete!" not in ssh_res: raise Exception("Failed to install http server") sshClient.execute("service httpd start") time.sleep(5) ssh_response = str(sshClient.execute("service httpd status")).lower() if not "running" in ssh_response: raise Exception("Failed to start httpd service") self.debug("Setup webserver using apache") def create_natrule(self, vm, public_ip, network, services=None): self.debug("Creating NAT rule in network for vm with public IP") if not services: services = self.services["natrule"] nat_rule = NATRule.create(self.apiclient, vm, services, ipaddressid=public_ip.ipaddress.id, openfirewall=False, networkid=network.id, vpcid=self.vpc.id ) self.debug("Adding NetworkACL rules to make NAT rule accessible") nwacl_nat = NetworkACL.create(self.apiclient, networkid=network.id, services=services, traffictype='Ingress' ) self.debug('nwacl_nat=%s' % nwacl_nat.__dict__) return nat_rule def acquire_publicip(self, network): self.debug("Associating public IP for network: %s" % network.name) public_ip = PublicIPAddress.create(self.apiclient, accountid=self.account.name, zoneid=self.zone.id, domainid=self.account.domainid, networkid=network.id, vpcid=self.vpc.id ) self.debug("Associated %s with network %s" % (public_ip.ipaddress.ipaddress, network.id )) return public_ip def create_vpc(self, cidr='10.1.2.1/16'): self.debug("Creating a VPC offering..") self.services["vpc_offering"]["name"] = self.services["vpc_offering"]["name"] + str(cidr) vpc_off = VpcOffering.create( self.apiclient, self.services["vpc_offering"] ) self._cleanup.append(vpc_off) self.debug("Enabling the VPC offering created") vpc_off.update(self.apiclient, state='Enabled') self.debug("Creating a VPC network in the account: %s" % self.account.name) self.services["vpc"]["cidr"] = cidr vpc = VPC.create( self.apiclient, self.services["vpc"], vpcofferingid=vpc_off.id, zoneid=self.zone.id, account=self.account.name, domainid=self.account.domainid ) return vpc def create_network(self, net_offerring, gateway='10.1.1.1',vpc=None): try: self.debug('Create NetworkOffering') net_offerring["name"] = "NET_OFF-" + str(gateway) nw_off = NetworkOffering.create(self.apiclient, net_offerring, conservemode=False ) # Enable Network offering nw_off.update(self.apiclient, state='Enabled') self._cleanup.append(nw_off) self.debug('Created and Enabled NetworkOffering') self.services["network"]["name"] = "NETWORK-" + str(gateway) self.debug('Adding Network=%s' % self.services["network"]) obj_network = Network.create(self.apiclient, self.services["network"], accountid=self.account.name, domainid=self.account.domainid, networkofferingid=nw_off.id, zoneid=self.zone.id, gateway=gateway, vpcid=vpc.id if vpc else self.vpc.id ) self.debug("Created network with ID: %s" % obj_network.id) return obj_network except Exception, e: self.fail('Unable to create a Network with offering=%s because of %s ' % (net_offerring, e)) def deployvm_in_network(self, network, host_id=None): try: self.debug('Creating VM in network=%s' % network.name) vm = VirtualMachine.create( self.apiclient, self.services["virtual_machine"], accountid=self.account.name, domainid=self.account.domainid, serviceofferingid=self.service_offering.id, networkids=[str(network.id)], hostid=host_id ) self.debug('Created VM=%s in network=%s' % (vm.id, network.name)) return vm except: self.fail('Unable to create VM in a Network=%s' % network.name) def create_lbrule(self, public_ip, network, vmarray, services=None): self.debug("Creating LB rule for IP address: %s" % public_ip.ipaddress.ipaddress) objservices = None if services: objservices = services else: objservices = self.services["lbrule"] lb_rule = LoadBalancerRule.create( self.apiclient, objservices, ipaddressid=public_ip.ipaddress.id, accountid=self.account.name, networkid=network.id, vpcid=self.vpc.id, domainid=self.account.domainid ) self.debug("Adding virtual machines %s and %s to LB rule" % (vmarray)) lb_rule.assign(self.apiclient, vmarray) return lb_rule def open_egress_to_world(self, network): self.debug("Adding Egress rules to network %s and %s to allow access to internet" % (network.name,self.services["http_rule"])) nwacl_internet_1 = NetworkACL.create( self.apiclient, networkid=network.id, services=self.services["http_rule"], traffictype='Ingress' ) return nwacl_internet_1 @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_01_network_services_VPC_StopCreatePF(self): """ Test : Create VPC PF rules on acquired public ip when VpcVirtualRouter is stopped """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Deploy vm1 in network1. # 5. Stop the VPC Virtual Router. # 6. Use the Create PF rule for vm in network1. # 7. Start VPC Virtual Router. # 8. Successfully ssh into the Guest VM using the PF rule network_1 = self.create_network(self.services["network_offering"]) vm_1 = self.deployvm_in_network(network_1) public_ip_1 = self.acquire_publicip(network_1) #ensure vm is accessible over public ip nat_rule = self.create_natrule(vm_1, public_ip_1, network_1) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) #remove the nat rule nat_rule.delete(self.apiclient) router = self.stop_vpcrouter() #recreate nat rule self.create_natrule(vm_1, public_ip_1, network_1) self.start_vpcrouter(router) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_02_network_services_VPC_CreatePF(self): """ Test Create VPC PF rules on acquired public ip when VpcVirtualRouter is Running """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Deploy vm1 in network1. # 5. Use the Create PF rule for vm in network1. # 6. Successfully ssh into the Guest VM using the PF rule network_1 = self.create_network(self.services["network_offering"]) vm_1 = self.deployvm_in_network(network_1) public_ip_1 = self.acquire_publicip(network_1) self.create_natrule( vm_1, public_ip_1, network_1) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_03_network_services_VPC_StopCreateMultiplePF(self): """ Test Create multiple VPC PF rules on acquired public ip in diff't networks when VpcVirtualRouter is stopped """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Add network2(10.1.2.1/24) using N01 to this VPC. # 5. Deploy vm1 in network1. # 6. Deploy vm2 in network2. # 7. Stop the VPC Virtual Router. # 8. Use the Create PF rule for vm1 in network1. # 9. Use the Create PF rule for vm2 in network2. # 10. Start VPC Virtual Router. # 11. Successfully ssh into the Guest VM1 and VM2 using the PF rule network_1 = self.create_network(self.services["network_offering_no_lb"]) network_2 = self.create_network(self.services["network_offering_no_lb"], '10.1.2.1') vm_1 = self.deployvm_in_network(network_1) vm_2 = self.deployvm_in_network(network_2) # wait until VM is up before stop the VR time.sleep(120) public_ip_1 = self.acquire_publicip(network_1) public_ip_2 = self.acquire_publicip(network_2) router = self.stop_vpcrouter() self.create_natrule(vm_1, public_ip_1, network_1) self.create_natrule(vm_2, public_ip_2, network_2) self.start_vpcrouter(router) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=False) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_04_network_services_VPC_CreateMultiplePF(self): """ Test Create multiple VPC PF rules on acquired public ip in diff't networks when VpcVirtualRouter is running """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Add network2(10.1.2.1/24) using N01 to this VPC. # 5. Deploy vm1 in network1. # 6. Deploy vm2 in network2. # 7. Use the Create PF rule for vm1 in network1. # 8. Use the Create PF rule for vm2 in network2. # 9. Successfully ssh into the Guest VM1 and VM2 using the PF rule network_1 = self.create_network(self.services["network_offering"]) network_2 = self.create_network(self.services["network_offering_no_lb"], '10.1.2.1') vm_1 = self.deployvm_in_network(network_1) vm_2 = self.deployvm_in_network(network_2) public_ip_1 = self.acquire_publicip(network_1) public_ip_2 = self.acquire_publicip(network_2) self.create_natrule(vm_1, public_ip_1, network_1) self.create_natrule(vm_2, public_ip_2, network_2) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=False) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_05_network_services_VPC_StopDeletePF(self): """ Test delete a PF rule in VPC when VpcVirtualRouter is Stopped """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Deploy vm1 in network1. # 5. Use the Create PF rule for vm in network1. # 6. Successfully ssh into the Guest VM using the PF rule. # 7. Successfully wget a file on http server of VM1. # 8. Stop the VPC Virtual Router. # 9. Delete internet PF rule # 10. Start VPC Virtual Router. # 11. wget a file present on http server of VM1 should fail network_1 = self.create_network(self.services["network_offering"]) vm_1 = self.deployvm_in_network(network_1) public_ip_1 = self.acquire_publicip(network_1) self.create_natrule(vm_1, public_ip_1, network_1) http_rule = self.create_natrule(vm_1, public_ip_1, network_1, self.services["http_rule"]) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=False) router = self.stop_vpcrouter() http_rule.delete(self.apiclient) self.start_vpcrouter(router) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=True) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_06_network_services_VPC_DeletePF(self): """ Test delete a PF rule in VPC when VpcVirtualRouter is Running """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Deploy vm1 in network1. # 5. Use the Create PF rule for vm in network1. # 6. Successfully ssh into the Guest VM using the PF rule. # 7. Successfully wget a file on http server of VM1. # 9. Delete internet PF rule # 10. wget a file present on http server of VM1 should fail network_1 = self.create_network(self.services["network_offering"]) vm_1 = self.deployvm_in_network(network_1) public_ip_1 = self.acquire_publicip(network_1) self.create_natrule(vm_1, public_ip_1, network_1) http_rule=self.create_natrule(vm_1, public_ip_1, network_1, self.services["http_rule"]) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=False) http_rule.delete(self.apiclient) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=True) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_07_network_services_VPC_StopDeleteAllPF(self): """ Test delete all PF rules in VPC when VpcVirtualRouter is Stopped """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Deploy vm1 in network1. # 5. Use the Create PF rule for vm in network1. # 6. Successfully ssh into the Guest VM using the PF rule. # 7. Successfully wget a file on http server of VM1. # 8. Stop the VPC Virtual Router. # 9. Delete all PF rule # 10. Start VPC Virtual Router. # 11. wget a file present on http server of VM1 should fail # 12. ssh into Guest VM using the PF rule should fail network_1 = self.create_network(self.services["network_offering"]) vm_1 = self.deployvm_in_network(network_1) public_ip_1 = self.acquire_publicip(network_1) nat_rule = self.create_natrule(vm_1, public_ip_1, network_1) http_rule = self.create_natrule(vm_1, public_ip_1, network_1, self.services["http_rule"]) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=False) router = self.stop_vpcrouter() http_rule.delete(self.apiclient) nat_rule.delete(self.apiclient) self.start_vpcrouter(router) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=True) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=True, isVmAccessible=False, network=network_1) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_08_network_services_VPC_DeleteAllPF(self): """ Test delete all PF rules in VPC when VpcVirtualRouter is Running """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16 # 2. Create a Network offering - NO1 with all supported services # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Deploy vm1 in network1. # 5. Use the Create PF rule for vm in network1. # 6. Successfully ssh into the Guest VM using the PF rule. # 7. Successfully wget a file on http server of VM1. # 8. Delete all PF rule # 9. wget a file present on http server of VM1 should fail # 10. ssh into Guest VM using the PF rule should fail network_1 = self.create_network(self.services["network_offering"]) vm_1 = self.deployvm_in_network(network_1) public_ip_1 = self.acquire_publicip(network_1) nat_rule = self.create_natrule(vm_1, public_ip_1, network_1) http_rule = self.create_natrule(vm_1, public_ip_1, network_1, self.services["http_rule"]) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=False) http_rule.delete(self.apiclient) nat_rule.delete(self.apiclient) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=True) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=True, isVmAccessible=False, network=network_1) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_09_network_services_VPC_StopDeleteAllMultiplePF(self): """ Test delete all PF rules in VPC across multiple networks when VpcVirtualRouter is Stopped """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16. # 2. Create a Network offering - NO1 with all supported services. # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Add network2(10.1.2.1/24) using N01 to this VPC. # 5. Deploy vm1 and vm2 in network1. # 6. Deploy vm3 and vm4 in network2. # 7. Use the Create PF rule ssh and http for vm1 and vm2 in network1. # 8. Use the Create PF rule ssh and http for vm3 and vm4 in network2. # 9. Successfully ssh into the Guest vm1, vm2, vm3 and vm4 using the PF rule. # 10. Succesfully wget a file from http server present on vm1, vm2, vm3 and vm4. # 11. Stop VPC Virtual Router. # 12. Delete all PF rultes for vm1, vm2, vm3 and vm4. # 12. Start VPC Virtual Router. # 13. Fail to ssh and http to vm1, vm2, vm3 and vm4. network_1 = self.create_network(self.services["network_offering"]) network_2 = self.create_network(self.services["network_offering_no_lb"], '10.1.2.1') vm_1 = self.deployvm_in_network(network_1) vm_2 = self.deployvm_in_network(network_1) vm_3 = self.deployvm_in_network(network_2) vm_4 = self.deployvm_in_network(network_2) public_ip_1 = self.acquire_publicip(network_1) public_ip_2 = self.acquire_publicip(network_1) nat_rule1 = self.create_natrule(vm_1, public_ip_1, network_1) nat_rule2 = self.create_natrule(vm_2, public_ip_2, network_1) http_rule1 = self.create_natrule(vm_1, public_ip_1, network_1, self.services["http_rule"]) http_rule2 = self.create_natrule(vm_2, public_ip_2, network_1, self.services["http_rule"]) public_ip_3 = self.acquire_publicip(network_2) public_ip_4 = self.acquire_publicip(network_2) nat_rule3 = self.create_natrule(vm_3, public_ip_3, network_2) nat_rule4 = self.create_natrule(vm_4, public_ip_4, network_2) http_rule3 = self.create_natrule(vm_3, public_ip_3, network_2, self.services["http_rule"]) http_rule4 = self.create_natrule(vm_4, public_ip_4, network_2, self.services["http_rule"]) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=False) self.check_ssh_into_vm(vm_3, public_ip_3, testnegative=False) self.check_ssh_into_vm(vm_4, public_ip_4, testnegative=False) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=False) self.check_wget_from_vm(vm_2, public_ip_2, testnegative=False) self.check_wget_from_vm(vm_3, public_ip_3, testnegative=False) self.check_wget_from_vm(vm_4, public_ip_4, testnegative=False) router = self.stop_vpcrouter() nat_rule1.delete(self.apiclient) nat_rule2.delete(self.apiclient) nat_rule3.delete(self.apiclient) nat_rule4.delete(self.apiclient) http_rule1.delete(self.apiclient) http_rule2.delete(self.apiclient) http_rule3.delete(self.apiclient) http_rule4.delete(self.apiclient) self.start_vpcrouter(router) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=True) self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=True) self.check_ssh_into_vm(vm_3, public_ip_3, testnegative=True) self.check_ssh_into_vm(vm_4, public_ip_4, testnegative=True) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=True, isVmAccessible=False, network=network_1) self.check_wget_from_vm(vm_2, public_ip_2, testnegative=True, isVmAccessible=False, network=network_1) self.check_wget_from_vm(vm_3, public_ip_3, testnegative=True, isVmAccessible=False, network=network_2) self.check_wget_from_vm(vm_4, public_ip_4, testnegative=True, isVmAccessible=False, network=network_2) return @attr(tags=["advanced", "intervlan"], required_hardware="true") def test_10_network_services_VPC_DeleteAllMultiplePF(self): """ Test delete all PF rules in VPC across multiple networks when VpcVirtualRouter is Running """ # Validate the following # 1. Create a VPC with cidr - 10.1.1.1/16. # 2. Create a Network offering - NO1 with all supported services. # 3. Add network1(10.1.1.1/24) using N01 to this VPC. # 4. Add network2(10.1.2.1/24) using N01 to this VPC. # 5. Deploy vm1 and vm2 in network1. # 6. Deploy vm3 and vm4 in network2. # 7. Use the Create PF rule ssh and http for vm1 and vm2 in network1. # 8. Use the Create PF rule ssh and http for vm3 and vm4 in network2. # 9. Successfully ssh into the Guest vm1, vm2, vm3 and vm4 using the PF rule. # 10. Succesfully wget a file from http server present on vm1, vm2, vm3 and vm4. # 12. Delete all PF rultes for vm1, vm2, vm3 and vm4. # 13. Fail to ssh and http to vm1, vm2, vm3 and vm4. network_1 = self.create_network(self.services["network_offering"]) network_2 = self.create_network(self.services["network_offering_no_lb"], '10.1.2.1') vm_1 = self.deployvm_in_network(network_1) vm_2 = self.deployvm_in_network(network_1) vm_3 = self.deployvm_in_network(network_2) vm_4 = self.deployvm_in_network(network_2) public_ip_1 = self.acquire_publicip(network_1) public_ip_2 = self.acquire_publicip(network_1) nat_rule1 = self.create_natrule(vm_1, public_ip_1, network_1) nat_rule2 = self.create_natrule(vm_2, public_ip_2, network_1) http_rule1 = self.create_natrule(vm_1, public_ip_1, network_1, self.services["http_rule"]) http_rule2 = self.create_natrule(vm_2, public_ip_2, network_1, self.services["http_rule"]) public_ip_3 = self.acquire_publicip(network_2) public_ip_4 = self.acquire_publicip(network_2) nat_rule3 = self.create_natrule(vm_3, public_ip_3, network_2) nat_rule4 = self.create_natrule(vm_4, public_ip_4, network_2) http_rule3 = self.create_natrule(vm_3, public_ip_3, network_2, self.services["http_rule"]) http_rule4 = self.create_natrule(vm_4, public_ip_4, network_2, self.services["http_rule"]) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=False) self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=False) self.check_ssh_into_vm(vm_3, public_ip_3, testnegative=False) self.check_ssh_into_vm(vm_4, public_ip_4, testnegative=False) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=False) self.check_wget_from_vm(vm_2, public_ip_2, testnegative=False) self.check_wget_from_vm(vm_3, public_ip_3, testnegative=False) self.check_wget_from_vm(vm_4, public_ip_4, testnegative=False) nat_rule1.delete(self.apiclient) nat_rule2.delete(self.apiclient) nat_rule3.delete(self.apiclient) nat_rule4.delete(self.apiclient) http_rule1.delete(self.apiclient) http_rule2.delete(self.apiclient) http_rule3.delete(self.apiclient) http_rule4.delete(self.apiclient) self.check_ssh_into_vm(vm_1, public_ip_1, testnegative=True) self.check_ssh_into_vm(vm_2, public_ip_2, testnegative=True) self.check_ssh_into_vm(vm_3, public_ip_3, testnegative=True) self.check_ssh_into_vm(vm_4, public_ip_4, testnegative=True) self.check_wget_from_vm(vm_1, public_ip_1, testnegative=True, isVmAccessible=False, network=network_1) self.check_wget_from_vm(vm_2, public_ip_2, testnegative=True, isVmAccessible=False, network=network_1) self.check_wget_from_vm(vm_3, public_ip_3, testnegative=True, isVmAccessible=False, network=network_2) self.check_wget_from_vm(vm_4, public_ip_4, testnegative=True, isVmAccessible=False, network=network_2) return
ikoula/cloudstack
test/integration/component/test_vpc_network_pfrules.py
Python
gpl-2.0
43,341
#!/usr/bin/env python ''' Copyright (C) 2007 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ''' # local library import inkex import simplepath import simpletransform import cubicsuperpath inkex.localize() class Extrude(inkex.Effect): def __init__(self): inkex.Effect.__init__(self) opts = [('-m', '--mode', 'string', 'mode', 'Lines', 'Join paths with lines or polygons'), ] for o in opts: self.OptionParser.add_option(o[0], o[1], action="store", type=o[2], dest=o[3], default=o[4], help=o[5]) def effect(self): paths = [] for id, node in self.selected.iteritems(): if node.tag == '{http://www.w3.org/2000/svg}path': paths.append(node) if len(paths) < 2: inkex.errormsg(_('Need at least 2 paths selected')) return pts = [cubicsuperpath.parsePath(paths[i].get('d')) for i in range(len(paths))] for i in range(len(paths)): if 'transform' in paths[i].keys(): trans = paths[i].get('transform') trans = simpletransform.parseTransform(trans) simpletransform.applyTransformToPath(trans, pts[i]) for n1 in range(0, len(paths)): for n2 in range(n1 + 1, len(paths)): verts = [] for i in range(0, min(map(len, pts))): comp = [] for j in range(0, min(len(pts[n1][i]), len(pts[n2][i]))): comp.append([pts[n1][i][j][1][-2:], pts[n2][i][j][1][-2:]]) verts.append(comp) if self.options.mode.lower() == 'lines': line = [] for comp in verts: for n,v in enumerate(comp): line += [('M', v[0])] line += [('L', v[1])] ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path') paths[0].xpath('..')[0].append(ele) ele.set('d', simplepath.formatPath(line)) ele.set('style', 'fill:none;stroke:#000000;stroke-opacity:1;stroke-width:1;') elif self.options.mode.lower() == 'polygons': g = inkex.etree.Element('{http://www.w3.org/2000/svg}g') g.set('style', 'fill:#000000;stroke:#000000;fill-opacity:0.3;stroke-width:2;stroke-opacity:0.6;') paths[0].xpath('..')[0].append(g) for comp in verts: for n,v in enumerate(comp): nn = n+1 if nn == len(comp): nn = 0 line = [] line += [('M', comp[n][0])] line += [('L', comp[n][1])] line += [('L', comp[nn][1])] line += [('L', comp[nn][0])] line += [('L', comp[n][0])] ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path') g.append(ele) ele.set('d', simplepath.formatPath(line)) if __name__ == '__main__': #pragma: no cover e = Extrude() e.affect()
piksels-and-lines-orchestra/inkscape
share/extensions/extrude.py
Python
gpl-2.0
3,989
#!/usr/bin/env python from ecl.summary import EclSum OIL_PRICES = { "2010-01-01": 78.33, "2010-02-01": 76.39, "2010-03-01": 81.20, "2010-04-01": 84.29, "2010-05-01": 73.74, "2010-06-01": 75.34, "2010-07-01": 76.32, "2010-08-01": 76.60, "2010-09-01": 75.24, "2010-10-01": 81.89, "2010-11-01": 84.25, "2010-12-01": 89.15, "2011-01-01": 89.17, "2011-02-01": 88.58, "2011-03-01": 102.86, "2011-04-01": 109.53, "2011-05-01": 100.90, "2011-06-01": 96.26, "2011-07-01": 97.30, "2011-08-01": 86.33, "2011-09-01": 85.52, "2011-10-01": 86.32, "2011-11-01": 97.16, "2011-12-01": 98.56, "2012-01-01": 100.27, "2012-02-01": 102.20, "2012-03-01": 106.16, "2012-04-01": 103.32, "2012-05-01": 94.65, "2012-06-01": 82.30, "2012-07-01": 87.90, "2012-08-01": 94.13, "2012-09-01": 94.51, "2012-10-01": 89.49, "2012-11-01": 86.53, "2012-12-01": 87.86, "2013-01-01": 94.76, "2013-02-01": 95.31, "2013-03-01": 92.94, "2013-04-01": 92.02, "2013-05-01": 94.51, "2013-06-01": 95.77, "2013-07-01": 104.67, "2013-08-01": 106.57, "2013-09-01": 106.29, "2013-10-01": 100.54, "2013-11-01": 93.86, "2013-12-01": 97.63, "2014-01-01": 94.62, "2014-02-01": 100.82, "2014-03-01": 100.80, "2014-04-01": 102.07, "2014-05-01": 102.18, "2014-06-01": 105.79, "2014-07-01": 103.59, "2014-08-01": 96.54, "2014-09-01": 93.21, "2014-10-01": 84.40, "2014-11-01": 75.79, "2014-12-01": 59.29, "2015-01-01": 47.22, "2015-02-01": 50.58, "2015-03-01": 47.82, "2015-04-01": 54.45, "2015-05-01": 59.27, "2015-06-01": 59.82, "2015-07-01": 50.90, "2015-08-01": 42.87, "2015-09-01": 45.48, } if __name__ == "__main__": ecl_sum = EclSum("SNAKE_OIL_FIELD") start_time = ecl_sum.getStartTime() date_ranges = ecl_sum.timeRange(start_time, interval="1M") production_sums = ecl_sum.blockedProduction("FOPT", date_ranges) npv = 0.0 for index in range(0, len(date_ranges) - 1): date = date_ranges[index + 1] # end of period production_sum = production_sums[index] oil_price = OIL_PRICES[date.date().strftime("%Y-%m-%d")] production_value = oil_price * production_sum npv += production_value with open("snake_oil_npv.txt", "w") as output_file: output_file.write("NPV %s\n" % npv) if npv < 80000: rating = "POOR" elif 80000 <= npv < 100000: rating = "AVERAGE" elif 100000 <= npv < 120000: rating = "GOOD" else: rating = "EXCELLENT" output_file.write("RATING %s\n" % rating)
joakim-hove/ert
test-data/local/snake_oil_structure/snake_oil/jobs/snake_oil_npv.py
Python
gpl-3.0
2,757
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Follow' db.create_table('actstream_follow', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), ('content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'])), ('object_id', self.gf('django.db.models.fields.PositiveIntegerField')()), )) db.send_create_signal('actstream', ['Follow']) # Adding unique constraint on 'Follow', fields ['user', 'content_type', 'object_id'] db.create_unique('actstream_follow', ['user_id', 'content_type_id', 'object_id']) # Adding model 'Action' db.create_table('actstream_action', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('actor_content_type', self.gf('django.db.models.fields.related.ForeignKey')(related_name='actor', to=orm['contenttypes.ContentType'])), ('actor_object_id', self.gf('django.db.models.fields.PositiveIntegerField')()), ('verb', self.gf('django.db.models.fields.CharField')(max_length=255)), ('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('target_content_type', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='target', null=True, to=orm['contenttypes.ContentType'])), ('target_object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)), ('action_object_content_type', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='action_object', null=True, to=orm['contenttypes.ContentType'])), ('action_object_object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)), ('timestamp', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('public', self.gf('django.db.models.fields.BooleanField')(default=True)), )) db.send_create_signal('actstream', ['Action']) def backwards(self, orm): # Removing unique constraint on 'Follow', fields ['user', 'content_type', 'object_id'] db.delete_unique('actstream_follow', ['user_id', 'content_type_id', 'object_id']) # Deleting model 'Follow' db.delete_table('actstream_follow') # Deleting model 'Action' db.delete_table('actstream_action') models = { 'actstream.action': { 'Meta': {'object_name': 'Action'}, 'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'action_object_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': "orm['contenttypes.ContentType']"}), 'actor_object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'target_object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'actstream.follow': { 'Meta': {'unique_together': "(('user', 'content_type', 'object_id'),)", 'object_name': 'Follow'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['actstream']
hzlf/openbroadcast
website/apps/actstream/migrations/0001_initial.py
Python
gpl-3.0
7,890
import unittest from datetime import datetime from flask import url_for from app import current_app as app from app.helpers.data import save_to_db from app.models.call_for_papers import CallForPaper from tests.unittests.object_mother import ObjectMother from tests.unittests.utils import OpenEventTestCase class TestGuestEventPage(OpenEventTestCase): def test_published_event_view(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' save_to_db(event, "Event Saved") rv = self.app.get(url_for('event_detail.display_event_detail_home', identifier=event.identifier), follow_redirects=True) self.assertTrue("Open Event" in rv.data, msg=rv.data) def test_published_event_view_coc(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' event.code_of_conduct = 'Test Code of Conduct' save_to_db(event, "Event Saved") rv = self.app.get(url_for('event_detail.display_event_coc', identifier=event.identifier), follow_redirects=True) self.assertTrue("Code of Conduct" in rv.data, msg=rv.data) def test_unpublished_event_view_coc(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' save_to_db(event, "Event Saved") rv = self.app.get(url_for('event_detail.display_event_coc', identifier=event.identifier), follow_redirects=True) self.assertEqual(rv.status_code, 404) def test_unpublished_event_view_attempt(self): with app.test_request_context(): event = ObjectMother.get_event() save_to_db(event, "Event Saved") rv = self.app.get(url_for('event_detail.display_event_detail_home', identifier=event.identifier), follow_redirects=True) self.assertEqual(rv.status_code, 404) def test_soft_deleted_event_view_attempt(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' event.in_trash = True save_to_db(event, "Event Saved") rv = self.app.get(url_for('event_detail.display_event_detail_home', identifier=event.identifier), follow_redirects=True) self.assertEqual(rv.status_code, 404) def test_published_event_sessions_view(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' save_to_db(event, "Event Saved") track = ObjectMother.get_track() track.event_id = event.id save_to_db(track, "Track Saved") speaker = ObjectMother.get_speaker() speaker.event_id = event.id save_to_db(speaker, "Speaker Saved") session = ObjectMother.get_session() session.event_id = event.id session.speakers = [speaker] session.state = 'accepted' save_to_db(session, "Session Saved") rv = self.app.get(url_for('event_detail.display_event_sessions', identifier=event.identifier), follow_redirects=True) self.assertTrue("Sessions" in rv.data, msg=rv.data) def test_published_event_schedule_view(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' event.schedule_published_on = datetime.now() save_to_db(event, "Event Saved") track = ObjectMother.get_track() track.event_id = event.id save_to_db(track, "Track Saved") speaker = ObjectMother.get_speaker() speaker.event_id = event.id save_to_db(speaker, "Speaker Saved") microlocation = ObjectMother.get_microlocation() save_to_db(microlocation, "Microlocation Saved") session = ObjectMother.get_session() session.event_id = event.id session.state = 'accepted' session.microlocation_id = microlocation.id session.speakers = [speaker] save_to_db(session, "Session Saved") rv = self.app.get(url_for('event_detail.display_event_schedule', identifier=event.identifier), follow_redirects=True) self.assertTrue("Schedule" in rv.data, msg=rv.data) def test_published_event_unpublished_schedule_view_attempt(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' save_to_db(event, "Event Saved") track = ObjectMother.get_track() track.event_id = event.id save_to_db(track, "Track Saved") speaker = ObjectMother.get_speaker() speaker.event_id = event.id save_to_db(speaker, "Speaker Saved") microlocation = ObjectMother.get_microlocation() save_to_db(microlocation, "Microlocation Saved") session = ObjectMother.get_session() session.event_id = event.id session.microlocation_id = microlocation.id session.speakers = [speaker] session.state = 'accepted' save_to_db(session, "Session Saved") rv = self.app.get(url_for('event_detail.display_event_schedule', identifier=event.identifier), follow_redirects=True) self.assertEqual(rv.status_code, 404) def test_published_event_cfs_view(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' save_to_db(event, "Event Saved") custom_form = ObjectMother.get_custom_form() custom_form.event_id = event.id save_to_db(custom_form, "Custom form saved") call_for_papers = CallForPaper(announcement="Announce", start_date=datetime(2003, 8, 4, 12, 30, 45), end_date=datetime(2004, 8, 4, 12, 30, 45), event_id=event.id) save_to_db(call_for_papers, "Call for papers saved") rv = self.app.get(url_for('event_detail.display_event_cfs', identifier=event.identifier), follow_redirects=True) self.assertTrue("Closed" in rv.data, msg=rv.data) def test_published_event_cfs_view_attempt(self): with app.test_request_context(): event = ObjectMother.get_event() event.state = 'Published' save_to_db(event, "Event Saved") rv = self.app.get(url_for('event_detail.display_event_cfs', identifier=event.identifier), follow_redirects=True) self.assertEqual(rv.status_code, 404) if __name__ == '__main__': unittest.main()
Achint08/open-event-orga-server
tests/unittests/views/guest/test_guest_event_page.py
Python
gpl-3.0
7,240
# Copyright 2014 Google Inc. All Rights Reserved. """Commands for reading and manipulating snapshots.""" from googlecloudsdk.calliope import base class Snapshots(base.Group): """List, describe, and delete Google Compute Engine snapshots.""" Snapshots.detailed_help = { 'brief': 'List, describe, and delete Google Compute Engine snapshots', }
harshilasu/LinkurApp
y/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/snapshots/__init__.py
Python
gpl-3.0
353
from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env log = CPLog(__name__) class Automation(Plugin): def __init__(self): addEvent('app.load', self.setCrons) if not Env.get('dev'): addEvent('app.load', self.addMovies) addEvent('setting.save.automation.hour.after', self.setCrons) def setCrons(self): fireEvent('schedule.interval', 'automation.add_movies', self.addMovies, hours = self.conf('hour', default = 12)) def addMovies(self): movies = fireEvent('automation.get_movies', merge = True) movie_ids = [] for imdb_id in movies: prop_name = 'automation.added.%s' % imdb_id added = Env.prop(prop_name, default = False) if not added: added_movie = fireEvent('movie.add', params = {'identifier': imdb_id}, force_readd = False, search_after = False, update_library = True, single = True) if added_movie: movie_ids.append(added_movie['id']) Env.prop(prop_name, True) for movie_id in movie_ids: movie_dict = fireEvent('movie.get', movie_id, single = True) fireEvent('searcher.single', movie_dict)
coolbombom/CouchPotatoServer
couchpotato/core/plugins/automation/main.py
Python
gpl-3.0
1,352
import unittest from PySide.QtCore import QSizeF from PySide.QtGui import QGraphicsProxyWidget, QSizePolicy, QPushButton, QGraphicsScene, QGraphicsView from helper import TimedQApplication def createItem(minimum, preferred, maximum, name): w = QGraphicsProxyWidget() w.setWidget(QPushButton(name)) w.setMinimumSize(minimum) w.setPreferredSize(preferred) w.setMaximumSize(maximum) w.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) return w class TestBug972 (TimedQApplication): # Test if the function QGraphicsProxyWidget.setWidget have the correct behavior def testIt(self): scene = QGraphicsScene() minSize = QSizeF(30, 100) prefSize = QSizeF(210, 100) maxSize = QSizeF(300, 100) a = createItem(minSize, prefSize, maxSize, "A") b = createItem(minSize, prefSize, maxSize, "B") c = createItem(minSize, prefSize, maxSize, "C") d = createItem(minSize, prefSize, maxSize, "D") view = QGraphicsView(scene) view.show() self.app.exec_() if __name__ == "__main__": unittest.main()
M4rtinK/pyside-android
tests/QtGui/bug_972.py
Python
lgpl-2.1
1,124
# Copyright (c) 2018 Kevin Weiss, for HAW Hamburg <kevin.weiss@haw-hamburg.de> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. """@package PyToAPI This module handles parsing of information from RIOT periph_uart test. """ try: from riot_pal import DutShell except ImportError: raise ImportError('Cannot find riot_pal, try "pip install riot_pal"') class PeriphUartIf(DutShell): """Interface to the node with periph_uart firmware.""" def uart_init(self, dev, baud): """Initialize DUT's UART.""" return self.send_cmd("init {} {}".format(dev, baud)) def uart_mode(self, dev, data_bits, parity, stop_bits): """Setup databits, parity and stopbits.""" return self.send_cmd( "mode {} {} {} {}".format(dev, data_bits, parity, stop_bits)) def uart_send_string(self, dev, test_string): """Send data via DUT's UART.""" return self.send_cmd("send {} {}".format(dev, test_string))
lazytech-org/RIOT
tests/periph_uart/tests/periph_uart_if.py
Python
lgpl-2.1
1,079
import pilasengine # Permite que este ejemplo funcion incluso si no has instalado pilas. import sys sys.path.insert(0, "..") pilas = pilasengine.iniciar() mono = pilas.actores.Mono(y=-100) def cuando_cambia_escala(valor): mono.escala = valor * 2 deslizador_escala = pilas.interfaz.Deslizador(y=50) deslizador_escala.conectar(cuando_cambia_escala) def cuando_cambia_rotacion(valor): mono.rotacion = valor * 360 deslizador_rotacion = pilas.interfaz.Deslizador(y=100) deslizador_rotacion.conectar(cuando_cambia_rotacion) def cuando_cambia_posicion(valor): # Obtiene valores entre -200 y 400 mono.x = -200 + 400 * valor print valor deslizador_posicion = pilas.interfaz.Deslizador(y=150) deslizador_posicion.conectar(cuando_cambia_posicion) pilas.avisar("Usa el deslizador para modificar al mono.") pilas.ejecutar()
fsalamero/pilas
pilasengine/ejemplos/ejemplos_a_revisar/deslizador.py
Python
lgpl-3.0
842
tutorial_tests = """ Let's try a simple generator: >>> def f(): ... yield 1 ... yield 2 >>> for i in f(): ... print(i) 1 2 >>> g = f() >>> next(g) 1 >>> next(g) 2 "Falling off the end" stops the generator: >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in g StopIteration "return" also stops the generator: >>> def f(): ... yield 1 ... return ... yield 2 # never reached ... >>> g = f() >>> next(g) 1 >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in f StopIteration >>> next(g) # once stopped, can't be resumed Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration "raise StopIteration" stops the generator too: >>> def f(): ... yield 1 ... raise StopIteration ... yield 2 # never reached ... >>> g = f() >>> next(g) 1 >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration However, they are not exactly equivalent: >>> def g1(): ... try: ... return ... except: ... yield 1 ... >>> list(g1()) [] >>> def g2(): ... try: ... raise StopIteration ... except: ... yield 42 >>> print(list(g2())) [42] This may be surprising at first: >>> def g3(): ... try: ... return ... finally: ... yield 1 ... >>> list(g3()) [1] Let's create an alternate range() function implemented as a generator: >>> def yrange(n): ... for i in range(n): ... yield i ... >>> list(yrange(5)) [0, 1, 2, 3, 4] Generators always return to the most recent caller: >>> def creator(): ... r = yrange(5) ... print("creator", next(r)) ... return r ... >>> def caller(): ... r = creator() ... for i in r: ... print("caller", i) ... >>> caller() creator 0 caller 1 caller 2 caller 3 caller 4 Generators can call other generators: >>> def zrange(n): ... for i in yrange(n): ... yield i ... >>> list(zrange(5)) [0, 1, 2, 3, 4] """ # The examples from PEP 255. pep_tests = """ Specification: Yield Restriction: A generator cannot be resumed while it is actively running: >>> def g(): ... i = next(me) ... yield i >>> me = g() >>> next(me) Traceback (most recent call last): ... File "<string>", line 2, in g ValueError: generator already executing Specification: Return Note that return isn't always equivalent to raising StopIteration: the difference lies in how enclosing try/except constructs are treated. For example, >>> def f1(): ... try: ... return ... except: ... yield 1 >>> print(list(f1())) [] because, as in any function, return simply exits, but >>> def f2(): ... try: ... raise StopIteration ... except: ... yield 42 >>> print(list(f2())) [42] because StopIteration is captured by a bare "except", as is any exception. Specification: Generators and Exception Propagation >>> def f(): ... return 1//0 >>> def g(): ... yield f() # the zero division exception propagates ... yield 42 # and we'll never get here >>> k = g() >>> next(k) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in g File "<stdin>", line 2, in f ZeroDivisionError: integer division or modulo by zero >>> next(k) # and the generator cannot be resumed Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration >>> Specification: Try/Except/Finally >>> def f(): ... try: ... yield 1 ... try: ... yield 2 ... 1//0 ... yield 3 # never get here ... except ZeroDivisionError: ... yield 4 ... yield 5 ... raise ... except: ... yield 6 ... yield 7 # the "raise" above stops this ... except: ... yield 8 ... yield 9 ... try: ... x = 12 ... finally: ... yield 10 ... yield 11 >>> print(list(f())) [1, 2, 4, 5, 8, 9, 10, 11] >>> Guido's binary tree example. >>> # A binary tree class. >>> class Tree: ... ... def __init__(self, label, left=None, right=None): ... self.label = label ... self.left = left ... self.right = right ... ... def __repr__(self, level=0, indent=" "): ... s = level*indent + repr(self.label) ... if self.left: ... s = s + "\\n" + self.left.__repr__(level+1, indent) ... if self.right: ... s = s + "\\n" + self.right.__repr__(level+1, indent) ... return s ... ... def __iter__(self): ... return inorder(self) >>> # Create a Tree from a list. >>> def tree(list): ... n = len(list) ... if n == 0: ... return [] ... i = n // 2 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:])) >>> # Show it off: create a tree. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # A recursive generator that generates Tree labels in in-order. >>> def inorder(t): ... if t: ... for x in inorder(t.left): ... yield x ... yield t.label ... for x in inorder(t.right): ... yield x >>> # Show it off: create a tree. >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ") >>> # Print the nodes of the tree in in-order. >>> for x in t: ... print(' '+x, end='') A B C D E F G H I J K L M N O P Q R S T U V W X Y Z >>> # A non-recursive generator. >>> def inorder(node): ... stack = [] ... while node: ... while node.left: ... stack.append(node) ... node = node.left ... yield node.label ... while not node.right: ... try: ... node = stack.pop() ... except IndexError: ... return ... yield node.label ... node = node.right >>> # Exercise the non-recursive generator. >>> for x in t: ... print(' '+x, end='') A B C D E F G H I J K L M N O P Q R S T U V W X Y Z """ # Examples from Iterator-List and Python-Dev and c.l.py. email_tests = """ The difference between yielding None and returning it. >>> def g(): ... for i in range(3): ... yield None ... yield None ... return >>> list(g()) [None, None, None, None] Ensure that explicitly raising StopIteration acts like any other exception in try/except, not like a return. >>> def g(): ... yield 1 ... try: ... raise StopIteration ... except: ... yield 2 ... yield 3 >>> list(g()) [1, 2, 3] Next one was posted to c.l.py. >>> def gcomb(x, k): ... "Generate all combinations of k elements from list x." ... ... if k > len(x): ... return ... if k == 0: ... yield [] ... else: ... first, rest = x[0], x[1:] ... # A combination does or doesn't contain first. ... # If it does, the remainder is a k-1 comb of rest. ... for c in gcomb(rest, k-1): ... c.insert(0, first) ... yield c ... # If it doesn't contain first, it's a k comb of rest. ... for c in gcomb(rest, k): ... yield c >>> seq = list(range(1, 5)) >>> for k in range(len(seq) + 2): ... print("%d-combs of %s:" % (k, seq)) ... for c in gcomb(seq, k): ... print(" ", c) 0-combs of [1, 2, 3, 4]: [] 1-combs of [1, 2, 3, 4]: [1] [2] [3] [4] 2-combs of [1, 2, 3, 4]: [1, 2] [1, 3] [1, 4] [2, 3] [2, 4] [3, 4] 3-combs of [1, 2, 3, 4]: [1, 2, 3] [1, 2, 4] [1, 3, 4] [2, 3, 4] 4-combs of [1, 2, 3, 4]: [1, 2, 3, 4] 5-combs of [1, 2, 3, 4]: From the Iterators list, about the types of these things. >>> def g(): ... yield 1 ... >>> type(g) <class 'function'> >>> i = g() >>> type(i) <class 'generator'> >>> [s for s in dir(i) if not s.startswith('_')] ['close', 'gi_code', 'gi_frame', 'gi_running', 'send', 'throw'] >>> from test.support import HAVE_DOCSTRINGS >>> print(i.__next__.__doc__ if HAVE_DOCSTRINGS else 'x.__next__() <==> next(x)') x.__next__() <==> next(x) >>> iter(i) is i True >>> import types >>> isinstance(i, types.GeneratorType) True And more, added later. >>> i.gi_running 0 >>> type(i.gi_frame) <class 'frame'> >>> i.gi_running = 42 Traceback (most recent call last): ... AttributeError: readonly attribute >>> def g(): ... yield me.gi_running >>> me = g() >>> me.gi_running 0 >>> next(me) 1 >>> me.gi_running 0 A clever union-find implementation from c.l.py, due to David Eppstein. Sent: Friday, June 29, 2001 12:16 PM To: python-list@python.org Subject: Re: PEP 255: Simple Generators >>> class disjointSet: ... def __init__(self, name): ... self.name = name ... self.parent = None ... self.generator = self.generate() ... ... def generate(self): ... while not self.parent: ... yield self ... for x in self.parent.generator: ... yield x ... ... def find(self): ... return next(self.generator) ... ... def union(self, parent): ... if self.parent: ... raise ValueError("Sorry, I'm not a root!") ... self.parent = parent ... ... def __str__(self): ... return self.name >>> names = "ABCDEFGHIJKLM" >>> sets = [disjointSet(name) for name in names] >>> roots = sets[:] >>> import random >>> gen = random.Random(42) >>> while 1: ... for s in sets: ... print(" %s->%s" % (s, s.find()), end='') ... print() ... if len(roots) > 1: ... s1 = gen.choice(roots) ... roots.remove(s1) ... s2 = gen.choice(roots) ... s1.union(s2) ... print("merged", s1, "into", s2) ... else: ... break A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M merged K into B A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->B L->L M->M merged A into F A->F B->B C->C D->D E->E F->F G->G H->H I->I J->J K->B L->L M->M merged E into F A->F B->B C->C D->D E->F F->F G->G H->H I->I J->J K->B L->L M->M merged D into C A->F B->B C->C D->C E->F F->F G->G H->H I->I J->J K->B L->L M->M merged M into C A->F B->B C->C D->C E->F F->F G->G H->H I->I J->J K->B L->L M->C merged J into B A->F B->B C->C D->C E->F F->F G->G H->H I->I J->B K->B L->L M->C merged B into C A->F B->C C->C D->C E->F F->F G->G H->H I->I J->C K->C L->L M->C merged F into G A->G B->C C->C D->C E->G F->G G->G H->H I->I J->C K->C L->L M->C merged L into C A->G B->C C->C D->C E->G F->G G->G H->H I->I J->C K->C L->C M->C merged G into I A->I B->C C->C D->C E->I F->I G->I H->H I->I J->C K->C L->C M->C merged I into H A->H B->C C->C D->C E->H F->H G->H H->H I->H J->C K->C L->C M->C merged C into H A->H B->H C->H D->H E->H F->H G->H H->H I->H J->H K->H L->H M->H """ # Emacs turd ' # Fun tests (for sufficiently warped notions of "fun"). fun_tests = """ Build up to a recursive Sieve of Eratosthenes generator. >>> def firstn(g, n): ... return [next(g) for i in range(n)] >>> def intsfrom(i): ... while 1: ... yield i ... i += 1 >>> firstn(intsfrom(5), 7) [5, 6, 7, 8, 9, 10, 11] >>> def exclude_multiples(n, ints): ... for i in ints: ... if i % n: ... yield i >>> firstn(exclude_multiples(3, intsfrom(1)), 6) [1, 2, 4, 5, 7, 8] >>> def sieve(ints): ... prime = next(ints) ... yield prime ... not_divisible_by_prime = exclude_multiples(prime, ints) ... for p in sieve(not_divisible_by_prime): ... yield p >>> primes = sieve(intsfrom(2)) >>> firstn(primes, 20) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71] Another famous problem: generate all integers of the form 2**i * 3**j * 5**k in increasing order, where i,j,k >= 0. Trickier than it may look at first! Try writing it without generators, and correctly, and without generating 3 internal results for each result output. >>> def times(n, g): ... for i in g: ... yield n * i >>> firstn(times(10, intsfrom(1)), 10) [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] >>> def merge(g, h): ... ng = next(g) ... nh = next(h) ... while 1: ... if ng < nh: ... yield ng ... ng = next(g) ... elif ng > nh: ... yield nh ... nh = next(h) ... else: ... yield ng ... ng = next(g) ... nh = next(h) The following works, but is doing a whale of a lot of redundant work -- it's not clear how to get the internal uses of m235 to share a single generator. Note that me_times2 (etc) each need to see every element in the result sequence. So this is an example where lazy lists are more natural (you can look at the head of a lazy list any number of times). >>> def m235(): ... yield 1 ... me_times2 = times(2, m235()) ... me_times3 = times(3, m235()) ... me_times5 = times(5, m235()) ... for i in merge(merge(me_times2, ... me_times3), ... me_times5): ... yield i Don't print "too many" of these -- the implementation above is extremely inefficient: each call of m235() leads to 3 recursive calls, and in turn each of those 3 more, and so on, and so on, until we've descended enough levels to satisfy the print stmts. Very odd: when I printed 5 lines of results below, this managed to screw up Win98's malloc in "the usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting address space, and it *looked* like a very slow leak. >>> result = m235() >>> for i in range(3): ... print(firstn(result, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] Heh. Here's one way to get a shared list, complete with an excruciating namespace renaming trick. The *pretty* part is that the times() and merge() functions can be reused as-is, because they only assume their stream arguments are iterable -- a LazyList is the same as a generator to times(). >>> class LazyList: ... def __init__(self, g): ... self.sofar = [] ... self.fetch = g.__next__ ... ... def __getitem__(self, i): ... sofar, fetch = self.sofar, self.fetch ... while i >= len(sofar): ... sofar.append(fetch()) ... return sofar[i] >>> def m235(): ... yield 1 ... # Gack: m235 below actually refers to a LazyList. ... me_times2 = times(2, m235) ... me_times3 = times(3, m235) ... me_times5 = times(5, m235) ... for i in merge(merge(me_times2, ... me_times3), ... me_times5): ... yield i Print as many of these as you like -- *this* implementation is memory- efficient. >>> m235 = LazyList(m235()) >>> for i in range(5): ... print([m235[j] for j in range(15*i, 15*(i+1))]) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384] [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675] Ye olde Fibonacci generator, LazyList style. >>> def fibgen(a, b): ... ... def sum(g, h): ... while 1: ... yield next(g) + next(h) ... ... def tail(g): ... next(g) # throw first away ... for x in g: ... yield x ... ... yield a ... yield b ... for s in sum(iter(fib), ... tail(iter(fib))): ... yield s >>> fib = LazyList(fibgen(1, 2)) >>> firstn(iter(fib), 17) [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584] Running after your tail with itertools.tee (new in version 2.4) The algorithms "m235" (Hamming) and Fibonacci presented above are both examples of a whole family of FP (functional programming) algorithms where a function produces and returns a list while the production algorithm suppose the list as already produced by recursively calling itself. For these algorithms to work, they must: - produce at least a first element without presupposing the existence of the rest of the list - produce their elements in a lazy manner To work efficiently, the beginning of the list must not be recomputed over and over again. This is ensured in most FP languages as a built-in feature. In python, we have to explicitly maintain a list of already computed results and abandon genuine recursivity. This is what had been attempted above with the LazyList class. One problem with that class is that it keeps a list of all of the generated results and therefore continually grows. This partially defeats the goal of the generator concept, viz. produce the results only as needed instead of producing them all and thereby wasting memory. Thanks to itertools.tee, it is now clear "how to get the internal uses of m235 to share a single generator". >>> from itertools import tee >>> def m235(): ... def _m235(): ... yield 1 ... for n in merge(times(2, m2), ... merge(times(3, m3), ... times(5, m5))): ... yield n ... m1 = _m235() ... m2, m3, m5, mRes = tee(m1, 4) ... return mRes >>> it = m235() >>> for i in range(5): ... print(firstn(it, 15)) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80] [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192] [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384] [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675] The "tee" function does just what we want. It internally keeps a generated result for as long as it has not been "consumed" from all of the duplicated iterators, whereupon it is deleted. You can therefore print the hamming sequence during hours without increasing memory usage, or very little. The beauty of it is that recursive running-after-their-tail FP algorithms are quite straightforwardly expressed with this Python idiom. Ye olde Fibonacci generator, tee style. >>> def fib(): ... ... def _isum(g, h): ... while 1: ... yield next(g) + next(h) ... ... def _fib(): ... yield 1 ... yield 2 ... next(fibTail) # throw first away ... for res in _isum(fibHead, fibTail): ... yield res ... ... realfib = _fib() ... fibHead, fibTail, fibRes = tee(realfib, 3) ... return fibRes >>> firstn(fib(), 17) [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584] """ # syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0 # hackery. syntax_tests = """ >>> def f(): ... return 22 ... yield 1 Traceback (most recent call last): .. SyntaxError: 'return' with argument inside generator >>> def f(): ... yield 1 ... return 22 Traceback (most recent call last): .. SyntaxError: 'return' with argument inside generator "return None" is not the same as "return" in a generator: >>> def f(): ... yield 1 ... return None Traceback (most recent call last): .. SyntaxError: 'return' with argument inside generator These are fine: >>> def f(): ... yield 1 ... return >>> def f(): ... try: ... yield 1 ... finally: ... pass >>> def f(): ... try: ... try: ... 1//0 ... except ZeroDivisionError: ... yield 666 ... except: ... pass ... finally: ... pass >>> def f(): ... try: ... try: ... yield 12 ... 1//0 ... except ZeroDivisionError: ... yield 666 ... except: ... try: ... x = 12 ... finally: ... yield 12 ... except: ... return >>> list(f()) [12, 666] >>> def f(): ... yield >>> type(f()) <class 'generator'> >>> def f(): ... if 0: ... yield >>> type(f()) <class 'generator'> >>> def f(): ... if 0: ... yield 1 >>> type(f()) <class 'generator'> >>> def f(): ... if "": ... yield None >>> type(f()) <class 'generator'> >>> def f(): ... return ... try: ... if x==4: ... pass ... elif 0: ... try: ... 1//0 ... except SyntaxError: ... pass ... else: ... if 0: ... while 12: ... x += 1 ... yield 2 # don't blink ... f(a, b, c, d, e) ... else: ... pass ... except: ... x = 1 ... return >>> type(f()) <class 'generator'> >>> def f(): ... if 0: ... def g(): ... yield 1 ... >>> type(f()) <class 'NoneType'> >>> def f(): ... if 0: ... class C: ... def __init__(self): ... yield 1 ... def f(self): ... yield 2 >>> type(f()) <class 'NoneType'> >>> def f(): ... if 0: ... return ... if 0: ... yield 2 >>> type(f()) <class 'generator'> >>> def f(): ... if 0: ... lambda x: x # shouldn't trigger here ... return # or here ... def f(i): ... return 2*i # or here ... if 0: ... return 3 # but *this* sucks (line 8) ... if 0: ... yield 2 # because it's a generator (line 10) Traceback (most recent call last): SyntaxError: 'return' with argument inside generator This one caused a crash (see SF bug 567538): >>> def f(): ... for i in range(3): ... try: ... continue ... finally: ... yield i ... >>> g = f() >>> print(next(g)) 0 >>> print(next(g)) 1 >>> print(next(g)) 2 >>> print(next(g)) Traceback (most recent call last): StopIteration Test the gi_code attribute >>> def f(): ... yield 5 ... >>> g = f() >>> g.gi_code is f.__code__ True >>> next(g) 5 >>> next(g) Traceback (most recent call last): StopIteration >>> g.gi_code is f.__code__ True Test the __name__ attribute and the repr() >>> def f(): ... yield 5 ... >>> g = f() >>> g.__name__ 'f' >>> repr(g) # doctest: +ELLIPSIS '<generator object f at ...>' Lambdas shouldn't have their usual return behavior. >>> x = lambda: (yield 1) >>> list(x()) [1] >>> x = lambda: ((yield 1), (yield 2)) >>> list(x()) [1, 2] """ # conjoin is a simple backtracking generator, named in honor of Icon's # "conjunction" control structure. Pass a list of no-argument functions # that return iterable objects. Easiest to explain by example: assume the # function list [x, y, z] is passed. Then conjoin acts like: # # def g(): # values = [None] * 3 # for values[0] in x(): # for values[1] in y(): # for values[2] in z(): # yield values # # So some 3-lists of values *may* be generated, each time we successfully # get into the innermost loop. If an iterator fails (is exhausted) before # then, it "backtracks" to get the next value from the nearest enclosing # iterator (the one "to the left"), and starts all over again at the next # slot (pumps a fresh iterator). Of course this is most useful when the # iterators have side-effects, so that which values *can* be generated at # each slot depend on the values iterated at previous slots. def simple_conjoin(gs): values = [None] * len(gs) def gen(i): if i >= len(gs): yield values else: for values[i] in gs[i](): for x in gen(i+1): yield x for x in gen(0): yield x # That works fine, but recursing a level and checking i against len(gs) for # each item produced is inefficient. By doing manual loop unrolling across # generator boundaries, it's possible to eliminate most of that overhead. # This isn't worth the bother *in general* for generators, but conjoin() is # a core building block for some CPU-intensive generator applications. def conjoin(gs): n = len(gs) values = [None] * n # Do one loop nest at time recursively, until the # of loop nests # remaining is divisible by 3. def gen(i): if i >= n: yield values elif (n-i) % 3: ip1 = i+1 for values[i] in gs[i](): for x in gen(ip1): yield x else: for x in _gen3(i): yield x # Do three loop nests at a time, recursing only if at least three more # remain. Don't call directly: this is an internal optimization for # gen's use. def _gen3(i): assert i < n and (n-i) % 3 == 0 ip1, ip2, ip3 = i+1, i+2, i+3 g, g1, g2 = gs[i : ip3] if ip3 >= n: # These are the last three, so we can yield values directly. for values[i] in g(): for values[ip1] in g1(): for values[ip2] in g2(): yield values else: # At least 6 loop nests remain; peel off 3 and recurse for the # rest. for values[i] in g(): for values[ip1] in g1(): for values[ip2] in g2(): for x in _gen3(ip3): yield x for x in gen(0): yield x # And one more approach: For backtracking apps like the Knight's Tour # solver below, the number of backtracking levels can be enormous (one # level per square, for the Knight's Tour, so that e.g. a 100x100 board # needs 10,000 levels). In such cases Python is likely to run out of # stack space due to recursion. So here's a recursion-free version of # conjoin too. # NOTE WELL: This allows large problems to be solved with only trivial # demands on stack space. Without explicitly resumable generators, this is # much harder to achieve. OTOH, this is much slower (up to a factor of 2) # than the fancy unrolled recursive conjoin. def flat_conjoin(gs): # rename to conjoin to run tests with this instead n = len(gs) values = [None] * n iters = [None] * n _StopIteration = StopIteration # make local because caught a *lot* i = 0 while 1: # Descend. try: while i < n: it = iters[i] = gs[i]().__next__ values[i] = it() i += 1 except _StopIteration: pass else: assert i == n yield values # Backtrack until an older iterator can be resumed. i -= 1 while i >= 0: try: values[i] = iters[i]() # Success! Start fresh at next level. i += 1 break except _StopIteration: # Continue backtracking. i -= 1 else: assert i < 0 break # A conjoin-based N-Queens solver. class Queens: def __init__(self, n): self.n = n rangen = range(n) # Assign a unique int to each column and diagonal. # columns: n of those, range(n). # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0- # based. # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along # each, smallest i+j is 0, largest is 2n-2. # For each square, compute a bit vector of the columns and # diagonals it covers, and for each row compute a function that # generates the possiblities for the columns in that row. self.rowgenerators = [] for i in rangen: rowuses = [(1 << j) | # column ordinal (1 << (n + i-j + n-1)) | # NW-SE ordinal (1 << (n + 2*n-1 + i+j)) # NE-SW ordinal for j in rangen] def rowgen(rowuses=rowuses): for j in rangen: uses = rowuses[j] if uses & self.used == 0: self.used |= uses yield j self.used &= ~uses self.rowgenerators.append(rowgen) # Generate solutions. def solve(self): self.used = 0 for row2col in conjoin(self.rowgenerators): yield row2col def printsolution(self, row2col): n = self.n assert n == len(row2col) sep = "+" + "-+" * n print(sep) for i in range(n): squares = [" " for j in range(n)] squares[row2col[i]] = "Q" print("|" + "|".join(squares) + "|") print(sep) # A conjoin-based Knight's Tour solver. This is pretty sophisticated # (e.g., when used with flat_conjoin above, and passing hard=1 to the # constructor, a 200x200 Knight's Tour was found quickly -- note that we're # creating 10s of thousands of generators then!), and is lengthy. class Knights: def __init__(self, m, n, hard=0): self.m, self.n = m, n # solve() will set up succs[i] to be a list of square #i's # successors. succs = self.succs = [] # Remove i0 from each of its successor's successor lists, i.e. # successors can't go back to i0 again. Return 0 if we can # detect this makes a solution impossible, else return 1. def remove_from_successors(i0, len=len): # If we remove all exits from a free square, we're dead: # even if we move to it next, we can't leave it again. # If we create a square with one exit, we must visit it next; # else somebody else will have to visit it, and since there's # only one adjacent, there won't be a way to leave it again. # Finelly, if we create more than one free square with a # single exit, we can only move to one of them next, leaving # the other one a dead end. ne0 = ne1 = 0 for i in succs[i0]: s = succs[i] s.remove(i0) e = len(s) if e == 0: ne0 += 1 elif e == 1: ne1 += 1 return ne0 == 0 and ne1 < 2 # Put i0 back in each of its successor's successor lists. def add_to_successors(i0): for i in succs[i0]: succs[i].append(i0) # Generate the first move. def first(): if m < 1 or n < 1: return # Since we're looking for a cycle, it doesn't matter where we # start. Starting in a corner makes the 2nd move easy. corner = self.coords2index(0, 0) remove_from_successors(corner) self.lastij = corner yield corner add_to_successors(corner) # Generate the second moves. def second(): corner = self.coords2index(0, 0) assert self.lastij == corner # i.e., we started in the corner if m < 3 or n < 3: return assert len(succs[corner]) == 2 assert self.coords2index(1, 2) in succs[corner] assert self.coords2index(2, 1) in succs[corner] # Only two choices. Whichever we pick, the other must be the # square picked on move m*n, as it's the only way to get back # to (0, 0). Save its index in self.final so that moves before # the last know it must be kept free. for i, j in (1, 2), (2, 1): this = self.coords2index(i, j) final = self.coords2index(3-i, 3-j) self.final = final remove_from_successors(this) succs[final].append(corner) self.lastij = this yield this succs[final].remove(corner) add_to_successors(this) # Generate moves 3 thru m*n-1. def advance(len=len): # If some successor has only one exit, must take it. # Else favor successors with fewer exits. candidates = [] for i in succs[self.lastij]: e = len(succs[i]) assert e > 0, "else remove_from_successors() pruning flawed" if e == 1: candidates = [(e, i)] break candidates.append((e, i)) else: candidates.sort() for e, i in candidates: if i != self.final: if remove_from_successors(i): self.lastij = i yield i add_to_successors(i) # Generate moves 3 thru m*n-1. Alternative version using a # stronger (but more expensive) heuristic to order successors. # Since the # of backtracking levels is m*n, a poor move early on # can take eons to undo. Smallest square board for which this # matters a lot is 52x52. def advance_hard(vmid=(m-1)/2.0, hmid=(n-1)/2.0, len=len): # If some successor has only one exit, must take it. # Else favor successors with fewer exits. # Break ties via max distance from board centerpoint (favor # corners and edges whenever possible). candidates = [] for i in succs[self.lastij]: e = len(succs[i]) assert e > 0, "else remove_from_successors() pruning flawed" if e == 1: candidates = [(e, 0, i)] break i1, j1 = self.index2coords(i) d = (i1 - vmid)**2 + (j1 - hmid)**2 candidates.append((e, -d, i)) else: candidates.sort() for e, d, i in candidates: if i != self.final: if remove_from_successors(i): self.lastij = i yield i add_to_successors(i) # Generate the last move. def last(): assert self.final in succs[self.lastij] yield self.final if m*n < 4: self.squaregenerators = [first] else: self.squaregenerators = [first, second] + \ [hard and advance_hard or advance] * (m*n - 3) + \ [last] def coords2index(self, i, j): assert 0 <= i < self.m assert 0 <= j < self.n return i * self.n + j def index2coords(self, index): assert 0 <= index < self.m * self.n return divmod(index, self.n) def _init_board(self): succs = self.succs del succs[:] m, n = self.m, self.n c2i = self.coords2index offsets = [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)] rangen = range(n) for i in range(m): for j in rangen: s = [c2i(i+io, j+jo) for io, jo in offsets if 0 <= i+io < m and 0 <= j+jo < n] succs.append(s) # Generate solutions. def solve(self): self._init_board() for x in conjoin(self.squaregenerators): yield x def printsolution(self, x): m, n = self.m, self.n assert len(x) == m*n w = len(str(m*n)) format = "%" + str(w) + "d" squares = [[None] * n for i in range(m)] k = 1 for i in x: i1, j1 = self.index2coords(i) squares[i1][j1] = format % k k += 1 sep = "+" + ("-" * w + "+") * n print(sep) for i in range(m): row = squares[i] print("|" + "|".join(row) + "|") print(sep) conjoin_tests = """ Generate the 3-bit binary numbers in order. This illustrates dumbest- possible use of conjoin, just to generate the full cross-product. >>> for c in conjoin([lambda: iter((0, 1))] * 3): ... print(c) [0, 0, 0] [0, 0, 1] [0, 1, 0] [0, 1, 1] [1, 0, 0] [1, 0, 1] [1, 1, 0] [1, 1, 1] For efficiency in typical backtracking apps, conjoin() yields the same list object each time. So if you want to save away a full account of its generated sequence, you need to copy its results. >>> def gencopy(iterator): ... for x in iterator: ... yield x[:] >>> for n in range(10): ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n))) ... print(n, len(all), all[0] == [0] * n, all[-1] == [1] * n) 0 1 True True 1 2 True True 2 4 True True 3 8 True True 4 16 True True 5 32 True True 6 64 True True 7 128 True True 8 256 True True 9 512 True True And run an 8-queens solver. >>> q = Queens(8) >>> LIMIT = 2 >>> count = 0 >>> for row2col in q.solve(): ... count += 1 ... if count <= LIMIT: ... print("Solution", count) ... q.printsolution(row2col) Solution 1 +-+-+-+-+-+-+-+-+ |Q| | | | | | | | +-+-+-+-+-+-+-+-+ | | | | |Q| | | | +-+-+-+-+-+-+-+-+ | | | | | | | |Q| +-+-+-+-+-+-+-+-+ | | | | | |Q| | | +-+-+-+-+-+-+-+-+ | | |Q| | | | | | +-+-+-+-+-+-+-+-+ | | | | | | |Q| | +-+-+-+-+-+-+-+-+ | |Q| | | | | | | +-+-+-+-+-+-+-+-+ | | | |Q| | | | | +-+-+-+-+-+-+-+-+ Solution 2 +-+-+-+-+-+-+-+-+ |Q| | | | | | | | +-+-+-+-+-+-+-+-+ | | | | | |Q| | | +-+-+-+-+-+-+-+-+ | | | | | | | |Q| +-+-+-+-+-+-+-+-+ | | |Q| | | | | | +-+-+-+-+-+-+-+-+ | | | | | | |Q| | +-+-+-+-+-+-+-+-+ | | | |Q| | | | | +-+-+-+-+-+-+-+-+ | |Q| | | | | | | +-+-+-+-+-+-+-+-+ | | | | |Q| | | | +-+-+-+-+-+-+-+-+ >>> print(count, "solutions in all.") 92 solutions in all. And run a Knight's Tour on a 10x10 board. Note that there are about 20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion. >>> k = Knights(10, 10) >>> LIMIT = 2 >>> count = 0 >>> for x in k.solve(): ... count += 1 ... if count <= LIMIT: ... print("Solution", count) ... k.printsolution(x) ... else: ... break Solution 1 +---+---+---+---+---+---+---+---+---+---+ | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8| +---+---+---+---+---+---+---+---+---+---+ | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11| +---+---+---+---+---+---+---+---+---+---+ | 59|100| 73| 36| 41| 56| 39| 32| 9| 6| +---+---+---+---+---+---+---+---+---+---+ | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31| +---+---+---+---+---+---+---+---+---+---+ | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50| +---+---+---+---+---+---+---+---+---+---+ | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13| +---+---+---+---+---+---+---+---+---+---+ | 87| 98| 91| 80| 77| 84| 53| 46| 65| 44| +---+---+---+---+---+---+---+---+---+---+ | 90| 23| 88| 95| 70| 79| 68| 83| 14| 17| +---+---+---+---+---+---+---+---+---+---+ | 97| 92| 21| 78| 81| 94| 19| 16| 45| 66| +---+---+---+---+---+---+---+---+---+---+ | 22| 89| 96| 93| 20| 69| 82| 67| 18| 15| +---+---+---+---+---+---+---+---+---+---+ Solution 2 +---+---+---+---+---+---+---+---+---+---+ | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8| +---+---+---+---+---+---+---+---+---+---+ | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11| +---+---+---+---+---+---+---+---+---+---+ | 59|100| 73| 36| 41| 56| 39| 32| 9| 6| +---+---+---+---+---+---+---+---+---+---+ | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31| +---+---+---+---+---+---+---+---+---+---+ | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50| +---+---+---+---+---+---+---+---+---+---+ | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13| +---+---+---+---+---+---+---+---+---+---+ | 87| 98| 89| 80| 77| 84| 53| 46| 65| 44| +---+---+---+---+---+---+---+---+---+---+ | 90| 23| 92| 95| 70| 79| 68| 83| 14| 17| +---+---+---+---+---+---+---+---+---+---+ | 97| 88| 21| 78| 81| 94| 19| 16| 45| 66| +---+---+---+---+---+---+---+---+---+---+ | 22| 91| 96| 93| 20| 69| 82| 67| 18| 15| +---+---+---+---+---+---+---+---+---+---+ """ weakref_tests = """\ Generators are weakly referencable: >>> import weakref >>> def gen(): ... yield 'foo!' ... >>> wr = weakref.ref(gen) >>> wr() is gen True >>> p = weakref.proxy(gen) Generator-iterators are weakly referencable as well: >>> gi = gen() >>> wr = weakref.ref(gi) >>> wr() is gi True >>> p = weakref.proxy(gi) >>> list(p) ['foo!'] """ coroutine_tests = """\ Sending a value into a started generator: >>> def f(): ... print((yield 1)) ... yield 2 >>> g = f() >>> next(g) 1 >>> g.send(42) 42 2 Sending a value into a new generator produces a TypeError: >>> f().send("foo") Traceback (most recent call last): ... TypeError: can't send non-None value to a just-started generator Yield by itself yields None: >>> def f(): yield >>> list(f()) [None] An obscene abuse of a yield expression within a generator expression: >>> list((yield 21) for i in range(4)) [21, None, 21, None, 21, None, 21, None] And a more sane, but still weird usage: >>> def f(): list(i for i in [(yield 26)]) >>> type(f()) <class 'generator'> A yield expression with augmented assignment. >>> def coroutine(seq): ... count = 0 ... while count < 200: ... count += yield ... seq.append(count) >>> seq = [] >>> c = coroutine(seq) >>> next(c) >>> print(seq) [] >>> c.send(10) >>> print(seq) [10] >>> c.send(10) >>> print(seq) [10, 20] >>> c.send(10) >>> print(seq) [10, 20, 30] Check some syntax errors for yield expressions: >>> f=lambda: (yield 1),(yield 2) Traceback (most recent call last): ... SyntaxError: 'yield' outside function >>> def f(): return lambda x=(yield): 1 Traceback (most recent call last): ... SyntaxError: 'return' with argument inside generator >>> def f(): x = yield = y Traceback (most recent call last): ... SyntaxError: assignment to yield expression not possible >>> def f(): (yield bar) = y Traceback (most recent call last): ... SyntaxError: can't assign to yield expression >>> def f(): (yield bar) += y Traceback (most recent call last): ... SyntaxError: can't assign to yield expression Now check some throw() conditions: >>> def f(): ... while True: ... try: ... print((yield)) ... except ValueError as v: ... print("caught ValueError (%s)" % (v)) >>> import sys >>> g = f() >>> next(g) >>> g.throw(ValueError) # type only caught ValueError () >>> g.throw(ValueError("xyz")) # value only caught ValueError (xyz) >>> g.throw(ValueError, ValueError(1)) # value+matching type caught ValueError (1) >>> g.throw(ValueError, TypeError(1)) # mismatched type, rewrapped caught ValueError (1) >>> g.throw(ValueError, ValueError(1), None) # explicit None traceback caught ValueError (1) >>> g.throw(ValueError(1), "foo") # bad args Traceback (most recent call last): ... TypeError: instance exception may not have a separate value >>> g.throw(ValueError, "foo", 23) # bad args Traceback (most recent call last): ... TypeError: throw() third argument must be a traceback object >>> g.throw("abc") Traceback (most recent call last): ... TypeError: exceptions must be classes or instances deriving from BaseException, not str >>> g.throw(0) Traceback (most recent call last): ... TypeError: exceptions must be classes or instances deriving from BaseException, not int >>> g.throw(list) Traceback (most recent call last): ... TypeError: exceptions must be classes or instances deriving from BaseException, not type >>> def throw(g,exc): ... try: ... raise exc ... except: ... g.throw(*sys.exc_info()) >>> throw(g,ValueError) # do it with traceback included caught ValueError () >>> g.send(1) 1 >>> throw(g,TypeError) # terminate the generator Traceback (most recent call last): ... TypeError >>> print(g.gi_frame) None >>> g.send(2) Traceback (most recent call last): ... StopIteration >>> g.throw(ValueError,6) # throw on closed generator Traceback (most recent call last): ... ValueError: 6 >>> f().throw(ValueError,7) # throw on just-opened generator Traceback (most recent call last): ... ValueError: 7 Plain "raise" inside a generator should preserve the traceback (#13188). The traceback should have 3 levels: - g.throw() - f() - 1/0 >>> def f(): ... try: ... yield ... except: ... raise >>> g = f() >>> try: ... 1/0 ... except ZeroDivisionError as v: ... try: ... g.throw(v) ... except Exception as w: ... tb = w.__traceback__ >>> levels = 0 >>> while tb: ... levels += 1 ... tb = tb.tb_next >>> levels 3 Now let's try closing a generator: >>> def f(): ... try: yield ... except GeneratorExit: ... print("exiting") >>> g = f() >>> next(g) >>> g.close() exiting >>> g.close() # should be no-op now >>> f().close() # close on just-opened generator should be fine >>> def f(): yield # an even simpler generator >>> f().close() # close before opening >>> g = f() >>> next(g) >>> g.close() # close normally And finalization: >>> def f(): ... try: yield ... finally: ... print("exiting") >>> g = f() >>> next(g) >>> del g exiting GeneratorExit is not caught by except Exception: >>> def f(): ... try: yield ... except Exception: ... print('except') ... finally: ... print('finally') >>> g = f() >>> next(g) >>> del g finally Now let's try some ill-behaved generators: >>> def f(): ... try: yield ... except GeneratorExit: ... yield "foo!" >>> g = f() >>> next(g) >>> g.close() Traceback (most recent call last): ... RuntimeError: generator ignored GeneratorExit >>> g.close() Our ill-behaved code should be invoked during GC: >>> import sys, io >>> old, sys.stderr = sys.stderr, io.StringIO() >>> g = f() >>> next(g) >>> del g >>> sys.stderr.getvalue().startswith( ... "Exception RuntimeError: 'generator ignored GeneratorExit' in " ... ) True >>> sys.stderr = old And errors thrown during closing should propagate: >>> def f(): ... try: yield ... except GeneratorExit: ... raise TypeError("fie!") >>> g = f() >>> next(g) >>> g.close() Traceback (most recent call last): ... TypeError: fie! Ensure that various yield expression constructs make their enclosing function a generator: >>> def f(): x += yield >>> type(f()) <class 'generator'> >>> def f(): x = yield >>> type(f()) <class 'generator'> >>> def f(): lambda x=(yield): 1 >>> type(f()) <class 'generator'> >>> def f(): x=(i for i in (yield) if (yield)) >>> type(f()) <class 'generator'> >>> def f(d): d[(yield "a")] = d[(yield "b")] = 27 >>> data = [1,2] >>> g = f(data) >>> type(g) <class 'generator'> >>> g.send(None) 'a' >>> data [1, 2] >>> g.send(0) 'b' >>> data [27, 2] >>> try: g.send(1) ... except StopIteration: pass >>> data [27, 27] """ refleaks_tests = """ Prior to adding cycle-GC support to itertools.tee, this code would leak references. We add it to the standard suite so the routine refleak-tests would trigger if it starts being uncleanable again. >>> import itertools >>> def leak(): ... class gen: ... def __iter__(self): ... return self ... def __next__(self): ... return self.item ... g = gen() ... head, tail = itertools.tee(g) ... g.item = head ... return head >>> it = leak() Make sure to also test the involvement of the tee-internal teedataobject, which stores returned items. >>> item = next(it) This test leaked at one point due to generator finalization/destruction. It was copied from Lib/test/leakers/test_generator_cycle.py before the file was removed. >>> def leak(): ... def gen(): ... while True: ... yield g ... g = gen() >>> leak() This test isn't really generator related, but rather exception-in-cleanup related. The coroutine tests (above) just happen to cause an exception in the generator's __del__ (tp_del) method. We can also test for this explicitly, without generators. We do have to redirect stderr to avoid printing warnings and to doublecheck that we actually tested what we wanted to test. >>> import sys, io >>> old = sys.stderr >>> try: ... sys.stderr = io.StringIO() ... class Leaker: ... def __del__(self): ... raise RuntimeError ... ... l = Leaker() ... del l ... err = sys.stderr.getvalue().strip() ... err.startswith( ... "Exception RuntimeError: RuntimeError() in <" ... ) ... err.endswith("> ignored") ... len(err.splitlines()) ... finally: ... sys.stderr = old True True 1 These refleak tests should perhaps be in a testfile of their own, test_generators just happened to be the test that drew these out. """ __test__ = {"tut": tutorial_tests, "pep": pep_tests, "email": email_tests, "fun": fun_tests, "syntax": syntax_tests, "conjoin": conjoin_tests, "weakref": weakref_tests, "coroutine": coroutine_tests, "refleaks": refleaks_tests, } # Magic test name that regrtest.py invokes *after* importing this module. # This worms around a bootstrap problem. # Note that doctest and regrtest both look in sys.argv for a "-v" argument, # so this works as expected in both ways of running regrtest. def test_main(verbose=None): from test import support, test_generators support.run_doctest(test_generators, verbose) # This part isn't needed for regrtest, but for running the test directly. if __name__ == "__main__": test_main(1)
cnsoft/kbengine-cocos2dx
kbe/src/lib/python/Lib/test/test_generators.py
Python
lgpl-3.0
50,722
''' Analysis plugin for supporting WorkspaceEmulators during analysis pass. Finds and connects Switch Cases, most specifically from Microsoft. ''' import envi import envi.archs.i386 as e_i386 import vivisect import vivisect.analysis.generic.codeblocks as vagc def analyzeJmp(amod, emu, op, starteip): ''' Top level logic ''' test, ctx = testSwitch(emu.vw, op, starteip, emu) if test: output = makeSwitch(emu.vw, starteip, ctx['offarraybase'], ctx['indiroffbase']) def testSwitch(vw, op, vajmp, emu=None): ''' identifies and enumerates microsoft's switch-case methods. ''' if not (op.iflags & envi.IF_BRANCH): # vw.verbprint( "indirect branch is not correct type") return False,None backone = vw.getLocation(vajmp-1) if backone == None: #vw.verbprint( "previous instruction isn't defined") return False,None backtwo = vw.getLocation(backone[0]-1) if backtwo == None: #vw.verbprint( "two previous instruction isn't defined") return False,None filename = vw.getMemoryMap(vajmp)[3] imagebase = vw.getFileMeta(filename, 'imagebase') op1 = vw.parseOpcode(backone[0]) if op1.mnem != 'add': #vw.verbprint( "previous instruction isn't an 'add'") return False,None baseoper = op1.opers[1] if not isinstance(baseoper, e_i386.i386RegOper): #vw.verbprint( "baseoper is not an i386RegOper: %s" % repr(baseoper)) return False,None # this is a weak analysis failure, but a powerful confirmation. if emu != None: regbase = op1.getOperValue(1, emu) if regbase != imagebase: vw.verbprint( "reg != imagebase") return False,None # now check the instruction before that op2 = vw.parseOpcode(backtwo[0]) if op2.mnem != 'mov': vw.verbprint( "2nd previous instruction isn't an 'mov'") return False,None arrayoper = op2.opers[1] if not (isinstance(arrayoper, e_i386.i386SibOper) and arrayoper.scale == 4): vw.verbprint( "arrayoper is not an i386SibOper of size 4: %s" % repr(baseoper)) return False,None ao_reg = arrayoper.reg & e_i386.RMETA_NMASK if ao_reg != baseoper.reg: vw.verbprint( "arrayoper.reg != baseoper.reg: %s != %s" % (ao_reg, baseoper.reg)) return False,None offarraybase = arrayoper.disp #initial check of the array. should point to the next va. we'll scrape it up later offarrayfirst = vw.readMemValue(offarraybase+imagebase, 4) if offarrayfirst+imagebase != vajmp+2: vw.verbprint( "first ref is not the va after the jmp: %x != %x" % (offarrayfirst+imagebase, vajmp+2)) indiroffbase = None # now check for the byte array before that backthree = vw.getLocation(backtwo[0]-1) # this one is optional. first two are not. if backthree != None: op = vw.parseOpcode(backthree[0]) if op.mnem == 'movzx' and isinstance(op.opers[1], e_i386.i386SibOper) and \ op.opers[1].scale == 1: vw.verbprint( "this is a double deref (hitting a byte array offset into the offset-array)") indiroffbase = op.opers[1].disp return True, {'indiroffbase':indiroffbase, 'offarraybase':offarraybase, } def makeSwitch(vw, vajmp, offarraybase, indiroffbase=None): ''' Makes the changes to the Workspace for the given jmp location. Handles naming for all cases because naming wants to indicate larger context. (future)If indiroffbase is not None, the indirection "database" is analyzed for naming ''' filename = vw.getMemoryMap(vajmp)[3] imagebase = vw.getFileMeta(filename, 'imagebase') # we have identified this is a switch case vw.verbprint( "FOUND MS SWITCH CASE SPRAY at 0x%x" % vajmp) # roll through the offset array until imagebase+offset is not a valid pointer, points to non-op locations or splits instructions count = 0 tracker = [] ptr = offarraybase while True: off = vw.readMemValue(ptr+imagebase, 4) ova = imagebase + off tgtva = makeSwitchCase(vw, vajmp, ova) if not tgtva: break tracker.append((count, tgtva)) count += 1 ptr += 4 # FIXME: this doesn't take into account two-level derefs (indiroffbase) naming = {} for idx,va in tracker: lst = naming.get(va) if lst == None: lst = [] naming[va] = lst lst.append("%xh" % idx) #TODO: analyze indiroffbase to determine case information for va, opts in naming.items(): options = "_".join(opts) name = "switch_case_%s_%.8x" % (options, va) vw.makeName(va, name) #TODO: analyze which paths handle which cases, name accordingly #TODO: determine good hint for symbolik constraints funcva = vw.getFunction(vajmp) vw.makeName(vajmp, "jmp_switch_%.8x" % vajmp) vagc.analyzeFunction(vw, funcva) return tracker def makeSwitchCase(vw, vaSwitch, vaCase): ''' Handle minutia of each case, specifically, checking for validity and making Xref and making code (if necessary) ''' if not vw.isValidPointer(vaCase): return False loc = vw.getLocation(vaCase) if loc != None: if loc[0] != vaCase: return False if loc[vivisect.L_LTYPE] != vivisect.LOC_OP: return False else: vw.makeCode(vaCase) #if we reach here, we're going to assume the location is valid. vw.verbprint( "0x%x MS Switch Case Spray: emu.getBranchNode( emu.curpath , 0x%x )" % (vaSwitch, vaCase)) vw.addXref(vaSwitch, vaCase, vivisect.REF_CODE) return vaCase if globals().get('vw'): verbose = vw.verbose vw.verbose = True vw.vprint("Starting...") findSwitchCase(vw) vw.vprint("Done") vw.verbose = verbose
imjonsnooow/vivisect
vivisect/analysis/generic/switchcase.py
Python
apache-2.0
5,920
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # 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. import json from six.moves.urllib import parse as urllib from tempest_lib import exceptions as lib_exc from tempest.api_schema.response.compute.v2_1 import images as schema from tempest.common import service_client from tempest.common import waiters class ImagesClient(service_client.ServiceClient): def create_image(self, server_id, name, meta=None): """Creates an image of the original server.""" post_body = { 'createImage': { 'name': name, } } if meta is not None: post_body['createImage']['metadata'] = meta post_body = json.dumps(post_body) resp, body = self.post('servers/%s/action' % server_id, post_body) self.validate_response(schema.create_image, resp, body) return service_client.ResponseBody(resp, body) def list_images(self, detail=False, **params): """Returns a list of all images filtered by any parameters.""" url = 'images' _schema = schema.list_images if detail: url += '/detail' _schema = schema.list_images_details if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) self.validate_response(_schema, resp, body) return service_client.ResponseBodyList(resp, body['images']) def show_image(self, image_id): """Returns the details of a single image.""" resp, body = self.get("images/%s" % image_id) self.expected_success(200, resp.status) body = json.loads(body) self.validate_response(schema.get_image, resp, body) return service_client.ResponseBody(resp, body['image']) def delete_image(self, image_id): """Deletes the provided image.""" resp, body = self.delete("images/%s" % image_id) self.validate_response(schema.delete, resp, body) return service_client.ResponseBody(resp, body) def wait_for_image_status(self, image_id, status): """Waits for an image to reach a given status.""" waiters.wait_for_image_status(self, image_id, status) def list_image_metadata(self, image_id): """Lists all metadata items for an image.""" resp, body = self.get("images/%s/metadata" % image_id) body = json.loads(body) self.validate_response(schema.image_metadata, resp, body) return service_client.ResponseBody(resp, body['metadata']) def set_image_metadata(self, image_id, meta): """Sets the metadata for an image.""" post_body = json.dumps({'metadata': meta}) resp, body = self.put('images/%s/metadata' % image_id, post_body) body = json.loads(body) self.validate_response(schema.image_metadata, resp, body) return service_client.ResponseBody(resp, body['metadata']) def update_image_metadata(self, image_id, meta): """Updates the metadata for an image.""" post_body = json.dumps({'metadata': meta}) resp, body = self.post('images/%s/metadata' % image_id, post_body) body = json.loads(body) self.validate_response(schema.image_metadata, resp, body) return service_client.ResponseBody(resp, body['metadata']) def show_image_metadata_item(self, image_id, key): """Returns the value for a specific image metadata key.""" resp, body = self.get("images/%s/metadata/%s" % (image_id, key)) body = json.loads(body) self.validate_response(schema.image_meta_item, resp, body) return service_client.ResponseBody(resp, body['meta']) def set_image_metadata_item(self, image_id, key, meta): """Sets the value for a specific image metadata key.""" post_body = json.dumps({'meta': meta}) resp, body = self.put('images/%s/metadata/%s' % (image_id, key), post_body) body = json.loads(body) self.validate_response(schema.image_meta_item, resp, body) return service_client.ResponseBody(resp, body['meta']) def delete_image_metadata_item(self, image_id, key): """Deletes a single image metadata key/value pair.""" resp, body = self.delete("images/%s/metadata/%s" % (image_id, key)) self.validate_response(schema.delete, resp, body) return service_client.ResponseBody(resp, body) def is_resource_deleted(self, id): try: self.show_image(id) except lib_exc.NotFound: return True return False @property def resource_type(self): """Returns the primary type of resource this client works with.""" return 'image'
roopali8/tempest
tempest/services/compute/json/images_client.py
Python
apache-2.0
5,390
"""Tests for acme.challenges.""" import unittest import mock import OpenSSL import requests from six.moves.urllib import parse as urllib_parse # pylint: disable=import-error from acme import errors from acme import jose from acme import test_util CERT = test_util.load_comparable_cert('cert.pem') KEY = jose.JWKRSA(key=test_util.load_rsa_private_key('rsa512_key.pem')) class ChallengeTest(unittest.TestCase): def test_from_json_unrecognized(self): from acme.challenges import Challenge from acme.challenges import UnrecognizedChallenge chall = UnrecognizedChallenge({"type": "foo"}) # pylint: disable=no-member self.assertEqual(chall, Challenge.from_json(chall.jobj)) class UnrecognizedChallengeTest(unittest.TestCase): def setUp(self): from acme.challenges import UnrecognizedChallenge self.jobj = {"type": "foo"} self.chall = UnrecognizedChallenge(self.jobj) def test_to_partial_json(self): self.assertEqual(self.jobj, self.chall.to_partial_json()) def test_from_json(self): from acme.challenges import UnrecognizedChallenge self.assertEqual( self.chall, UnrecognizedChallenge.from_json(self.jobj)) class KeyAuthorizationChallengeResponseTest(unittest.TestCase): def setUp(self): def _encode(name): assert name == "token" return "foo" self.chall = mock.Mock() self.chall.encode.side_effect = _encode def test_verify_ok(self): from acme.challenges import KeyAuthorizationChallengeResponse response = KeyAuthorizationChallengeResponse( key_authorization='foo.oKGqedy-b-acd5eoybm2f-NVFxvyOoET5CNy3xnv8WY') self.assertTrue(response.verify(self.chall, KEY.public_key())) def test_verify_wrong_token(self): from acme.challenges import KeyAuthorizationChallengeResponse response = KeyAuthorizationChallengeResponse( key_authorization='bar.oKGqedy-b-acd5eoybm2f-NVFxvyOoET5CNy3xnv8WY') self.assertFalse(response.verify(self.chall, KEY.public_key())) def test_verify_wrong_thumbprint(self): from acme.challenges import KeyAuthorizationChallengeResponse response = KeyAuthorizationChallengeResponse( key_authorization='foo.oKGqedy-b-acd5eoybm2f-NVFxv') self.assertFalse(response.verify(self.chall, KEY.public_key())) def test_verify_wrong_form(self): from acme.challenges import KeyAuthorizationChallengeResponse response = KeyAuthorizationChallengeResponse( key_authorization='.foo.oKGqedy-b-acd5eoybm2f-' 'NVFxvyOoET5CNy3xnv8WY') self.assertFalse(response.verify(self.chall, KEY.public_key())) class HTTP01ResponseTest(unittest.TestCase): # pylint: disable=too-many-instance-attributes def setUp(self): from acme.challenges import HTTP01Response self.msg = HTTP01Response(key_authorization=u'foo') self.jmsg = { 'resource': 'challenge', 'type': 'http-01', 'keyAuthorization': u'foo', } from acme.challenges import HTTP01 self.chall = HTTP01(token=(b'x' * 16)) self.response = self.chall.response(KEY) def test_to_partial_json(self): self.assertEqual(self.jmsg, self.msg.to_partial_json()) def test_from_json(self): from acme.challenges import HTTP01Response self.assertEqual( self.msg, HTTP01Response.from_json(self.jmsg)) def test_from_json_hashable(self): from acme.challenges import HTTP01Response hash(HTTP01Response.from_json(self.jmsg)) def test_simple_verify_bad_key_authorization(self): key2 = jose.JWKRSA.load(test_util.load_vector('rsa256_key.pem')) self.response.simple_verify(self.chall, "local", key2.public_key()) @mock.patch("acme.challenges.requests.get") def test_simple_verify_good_validation(self, mock_get): validation = self.chall.validation(KEY) mock_get.return_value = mock.MagicMock(text=validation) self.assertTrue(self.response.simple_verify( self.chall, "local", KEY.public_key())) mock_get.assert_called_once_with(self.chall.uri("local")) @mock.patch("acme.challenges.requests.get") def test_simple_verify_bad_validation(self, mock_get): mock_get.return_value = mock.MagicMock(text="!") self.assertFalse(self.response.simple_verify( self.chall, "local", KEY.public_key())) @mock.patch("acme.challenges.requests.get") def test_simple_verify_whitespace_validation(self, mock_get): from acme.challenges import HTTP01Response mock_get.return_value = mock.MagicMock( text=(self.chall.validation(KEY) + HTTP01Response.WHITESPACE_CUTSET)) self.assertTrue(self.response.simple_verify( self.chall, "local", KEY.public_key())) mock_get.assert_called_once_with(self.chall.uri("local")) @mock.patch("acme.challenges.requests.get") def test_simple_verify_connection_error(self, mock_get): mock_get.side_effect = requests.exceptions.RequestException self.assertFalse(self.response.simple_verify( self.chall, "local", KEY.public_key())) @mock.patch("acme.challenges.requests.get") def test_simple_verify_port(self, mock_get): self.response.simple_verify( self.chall, domain="local", account_public_key=KEY.public_key(), port=8080) self.assertEqual("local:8080", urllib_parse.urlparse( mock_get.mock_calls[0][1][0]).netloc) class HTTP01Test(unittest.TestCase): def setUp(self): from acme.challenges import HTTP01 self.msg = HTTP01( token=jose.decode_b64jose( 'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ+PCt92wr+oA')) self.jmsg = { 'type': 'http-01', 'token': 'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA', } def test_path(self): self.assertEqual(self.msg.path, '/.well-known/acme-challenge/' 'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA') def test_uri(self): self.assertEqual( 'http://example.com/.well-known/acme-challenge/' 'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA', self.msg.uri('example.com')) def test_to_partial_json(self): self.assertEqual(self.jmsg, self.msg.to_partial_json()) def test_from_json(self): from acme.challenges import HTTP01 self.assertEqual(self.msg, HTTP01.from_json(self.jmsg)) def test_from_json_hashable(self): from acme.challenges import HTTP01 hash(HTTP01.from_json(self.jmsg)) def test_good_token(self): self.assertTrue(self.msg.good_token) self.assertFalse( self.msg.update(token=b'..').good_token) class TLSSNI01ResponseTest(unittest.TestCase): # pylint: disable=too-many-instance-attributes def setUp(self): from acme.challenges import TLSSNI01 self.chall = TLSSNI01( token=jose.b64decode(b'a82d5ff8ef740d12881f6d3c2277ab2e')) self.response = self.chall.response(KEY) self.jmsg = { 'resource': 'challenge', 'type': 'tls-sni-01', 'keyAuthorization': self.response.key_authorization, } # pylint: disable=invalid-name label1 = b'dc38d9c3fa1a4fdcc3a5501f2d38583f' label2 = b'b7793728f084394f2a1afd459556bb5c' self.z = label1 + label2 self.z_domain = label1 + b'.' + label2 + b'.acme.invalid' self.domain = 'foo.com' def test_z_and_domain(self): self.assertEqual(self.z, self.response.z) self.assertEqual(self.z_domain, self.response.z_domain) def test_to_partial_json(self): self.assertEqual(self.jmsg, self.response.to_partial_json()) def test_from_json(self): from acme.challenges import TLSSNI01Response self.assertEqual(self.response, TLSSNI01Response.from_json(self.jmsg)) def test_from_json_hashable(self): from acme.challenges import TLSSNI01Response hash(TLSSNI01Response.from_json(self.jmsg)) @mock.patch('acme.challenges.socket.gethostbyname') @mock.patch('acme.challenges.crypto_util.probe_sni') def test_probe_cert(self, mock_probe_sni, mock_gethostbyname): mock_gethostbyname.return_value = '127.0.0.1' self.response.probe_cert('foo.com') mock_gethostbyname.assert_called_once_with('foo.com') mock_probe_sni.assert_called_once_with( host='127.0.0.1', port=self.response.PORT, name=self.z_domain) self.response.probe_cert('foo.com', host='8.8.8.8') mock_probe_sni.assert_called_with( host='8.8.8.8', port=mock.ANY, name=mock.ANY) self.response.probe_cert('foo.com', port=1234) mock_probe_sni.assert_called_with( host=mock.ANY, port=1234, name=mock.ANY) self.response.probe_cert('foo.com', bar='baz') mock_probe_sni.assert_called_with( host=mock.ANY, port=mock.ANY, name=mock.ANY, bar='baz') self.response.probe_cert('foo.com', name=b'xxx') mock_probe_sni.assert_called_with( host=mock.ANY, port=mock.ANY, name=self.z_domain) def test_gen_verify_cert(self): key1 = test_util.load_pyopenssl_private_key('rsa512_key.pem') cert, key2 = self.response.gen_cert(key1) self.assertEqual(key1, key2) self.assertTrue(self.response.verify_cert(cert)) def test_gen_verify_cert_gen_key(self): cert, key = self.response.gen_cert() self.assertTrue(isinstance(key, OpenSSL.crypto.PKey)) self.assertTrue(self.response.verify_cert(cert)) def test_verify_bad_cert(self): self.assertFalse(self.response.verify_cert( test_util.load_cert('cert.pem'))) def test_simple_verify_bad_key_authorization(self): key2 = jose.JWKRSA.load(test_util.load_vector('rsa256_key.pem')) self.response.simple_verify(self.chall, "local", key2.public_key()) @mock.patch('acme.challenges.TLSSNI01Response.verify_cert', autospec=True) def test_simple_verify(self, mock_verify_cert): mock_verify_cert.return_value = mock.sentinel.verification self.assertEqual( mock.sentinel.verification, self.response.simple_verify( self.chall, self.domain, KEY.public_key(), cert=mock.sentinel.cert)) mock_verify_cert.assert_called_once_with( self.response, mock.sentinel.cert) @mock.patch('acme.challenges.TLSSNI01Response.probe_cert') def test_simple_verify_false_on_probe_error(self, mock_probe_cert): mock_probe_cert.side_effect = errors.Error self.assertFalse(self.response.simple_verify( self.chall, self.domain, KEY.public_key())) class TLSSNI01Test(unittest.TestCase): def setUp(self): from acme.challenges import TLSSNI01 self.msg = TLSSNI01( token=jose.b64decode('a82d5ff8ef740d12881f6d3c2277ab2e')) self.jmsg = { 'type': 'tls-sni-01', 'token': 'a82d5ff8ef740d12881f6d3c2277ab2e', } def test_to_partial_json(self): self.assertEqual(self.jmsg, self.msg.to_partial_json()) def test_from_json(self): from acme.challenges import TLSSNI01 self.assertEqual(self.msg, TLSSNI01.from_json(self.jmsg)) def test_from_json_hashable(self): from acme.challenges import TLSSNI01 hash(TLSSNI01.from_json(self.jmsg)) def test_from_json_invalid_token_length(self): from acme.challenges import TLSSNI01 self.jmsg['token'] = jose.encode_b64jose(b'abcd') self.assertRaises( jose.DeserializationError, TLSSNI01.from_json, self.jmsg) @mock.patch('acme.challenges.TLSSNI01Response.gen_cert') def test_validation(self, mock_gen_cert): mock_gen_cert.return_value = ('cert', 'key') self.assertEqual(('cert', 'key'), self.msg.validation( KEY, cert_key=mock.sentinel.cert_key)) mock_gen_cert.assert_called_once_with(key=mock.sentinel.cert_key) class DNSTest(unittest.TestCase): def setUp(self): from acme.challenges import DNS self.msg = DNS(token=jose.b64decode( b'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA')) self.jmsg = { 'type': 'dns', 'token': 'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA', } def test_to_partial_json(self): self.assertEqual(self.jmsg, self.msg.to_partial_json()) def test_from_json(self): from acme.challenges import DNS self.assertEqual(self.msg, DNS.from_json(self.jmsg)) def test_from_json_hashable(self): from acme.challenges import DNS hash(DNS.from_json(self.jmsg)) def test_gen_check_validation(self): self.assertTrue(self.msg.check_validation( self.msg.gen_validation(KEY), KEY.public_key())) def test_gen_check_validation_wrong_key(self): key2 = jose.JWKRSA.load(test_util.load_vector('rsa1024_key.pem')) self.assertFalse(self.msg.check_validation( self.msg.gen_validation(KEY), key2.public_key())) def test_check_validation_wrong_payload(self): validations = tuple( jose.JWS.sign(payload=payload, alg=jose.RS256, key=KEY) for payload in (b'', b'{}') ) for validation in validations: self.assertFalse(self.msg.check_validation( validation, KEY.public_key())) def test_check_validation_wrong_fields(self): bad_validation = jose.JWS.sign( payload=self.msg.update( token=b'x' * 20).json_dumps().encode('utf-8'), alg=jose.RS256, key=KEY) self.assertFalse(self.msg.check_validation( bad_validation, KEY.public_key())) def test_gen_response(self): with mock.patch('acme.challenges.DNS.gen_validation') as mock_gen: mock_gen.return_value = mock.sentinel.validation response = self.msg.gen_response(KEY) from acme.challenges import DNSResponse self.assertTrue(isinstance(response, DNSResponse)) self.assertEqual(response.validation, mock.sentinel.validation) def test_validation_domain_name(self): self.assertEqual( '_acme-challenge.le.wtf', self.msg.validation_domain_name('le.wtf')) class DNSResponseTest(unittest.TestCase): def setUp(self): from acme.challenges import DNS self.chall = DNS(token=jose.b64decode( b"evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA")) self.validation = jose.JWS.sign( payload=self.chall.json_dumps(sort_keys=True).encode(), key=KEY, alg=jose.RS256) from acme.challenges import DNSResponse self.msg = DNSResponse(validation=self.validation) self.jmsg_to = { 'resource': 'challenge', 'type': 'dns', 'validation': self.validation, } self.jmsg_from = { 'resource': 'challenge', 'type': 'dns', 'validation': self.validation.to_json(), } def test_to_partial_json(self): self.assertEqual(self.jmsg_to, self.msg.to_partial_json()) def test_from_json(self): from acme.challenges import DNSResponse self.assertEqual(self.msg, DNSResponse.from_json(self.jmsg_from)) def test_from_json_hashable(self): from acme.challenges import DNSResponse hash(DNSResponse.from_json(self.jmsg_from)) def test_check_validation(self): self.assertTrue( self.msg.check_validation(self.chall, KEY.public_key())) if __name__ == '__main__': unittest.main() # pragma: no cover
mitnk/letsencrypt
acme/acme/challenges_test.py
Python
apache-2.0
15,928
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Datasets for random number generators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.util import random_seed from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import gen_dataset_ops from tensorflow.python.util.tf_export import tf_export @tf_export("data.experimental.RandomDataset") class RandomDataset(dataset_ops.DatasetSource): """A `Dataset` of pseudorandom values.""" def __init__(self, seed=None): """A `Dataset` of pseudorandom values.""" super(RandomDataset, self).__init__() self._seed, self._seed2 = random_seed.get_seed(seed) def _as_variant_tensor(self): return gen_dataset_ops.random_dataset( seed=self._seed, seed2=self._seed2, **dataset_ops.flat_structure(self)) @property def output_classes(self): return ops.Tensor @property def output_shapes(self): return tensor_shape.scalar() @property def output_types(self): return dtypes.int64
alshedivat/tensorflow
tensorflow/python/data/experimental/ops/random_ops.py
Python
apache-2.0
1,886
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # 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 tempest_lib.common.utils import data_utils from testtools import matchers from tempest.api.compute import base from tempest import config from tempest import test CONF = config.CONF class VolumesGetTestJSON(base.BaseV2ComputeTest): @classmethod def skip_checks(cls): super(VolumesGetTestJSON, cls).skip_checks() if not CONF.service_available.cinder: skip_msg = ("%s skipped as Cinder is not available" % cls.__name__) raise cls.skipException(skip_msg) @classmethod def setup_clients(cls): super(VolumesGetTestJSON, cls).setup_clients() cls.client = cls.volumes_extensions_client @test.idempotent_id('f10f25eb-9775-4d9d-9cbe-1cf54dae9d5f') def test_volume_create_get_delete(self): # CREATE, GET, DELETE Volume volume = None v_name = data_utils.rand_name('Volume') metadata = {'Type': 'work'} # Create volume volume = self.client.create_volume(display_name=v_name, metadata=metadata) self.addCleanup(self.delete_volume, volume['id']) self.assertIn('id', volume) self.assertIn('displayName', volume) self.assertEqual(volume['displayName'], v_name, "The created volume name is not equal " "to the requested name") self.assertTrue(volume['id'] is not None, "Field volume id is empty or not found.") # Wait for Volume status to become ACTIVE self.client.wait_for_volume_status(volume['id'], 'available') # GET Volume fetched_volume = self.client.show_volume(volume['id']) # Verification of details of fetched Volume self.assertEqual(v_name, fetched_volume['displayName'], 'The fetched Volume is different ' 'from the created Volume') self.assertEqual(volume['id'], fetched_volume['id'], 'The fetched Volume is different ' 'from the created Volume') self.assertThat(fetched_volume['metadata'].items(), matchers.ContainsAll(metadata.items()), 'The fetched Volume metadata misses data ' 'from the created Volume')
akash1808/tempest
tempest/api/compute/volumes/test_volumes_get.py
Python
apache-2.0
3,025
from __future__ import division, print_function, absolute_import import numpy import pandas from numpy.random.mtrand import RandomState from sklearn.metrics.pairwise import pairwise_distances from hep_ml import commonutils from hep_ml.commonutils import weighted_quantile, build_normalizer, \ compute_cut_for_efficiency, generate_sample, compute_knn_indices_of_signal, \ compute_knn_indices_of_same_class def test_splitting(n_rows=10, n_columns=8): column_names = ['col' + str(i) for i in range(n_columns)] signal_df = pandas.DataFrame(numpy.ones([n_rows, n_columns]), columns=column_names) bg_df = pandas.DataFrame(numpy.zeros([n_rows, n_columns]), columns=column_names) common_X = pandas.concat([signal_df, bg_df], ignore_index=True) common_y = numpy.concatenate([numpy.ones(len(signal_df)), numpy.zeros(len(bg_df))]) trainX, testX, trainY, testY = commonutils.train_test_split(common_X, common_y) for (index, row), label in zip(trainX.iterrows(), trainY): assert numpy.all(row == label), 'wrong data partition' for (index, row), label in zip(testX.iterrows(), testY): assert numpy.all(row == label), 'wrong data partition' assert (trainX.columns == column_names).all(), 'new column names!' assert (testX.columns == column_names).all(), 'new column names!' assert len(trainX) + len(testX) == len(common_X), 'new size is strange' def check_weighted_percentile(size=100, q_size=20): random = RandomState() array = random.permutation(size) quantiles = random.uniform(size=q_size) q_permutation = random.permutation(q_size) result1 = weighted_quantile(array, quantiles)[q_permutation] result2 = weighted_quantile(array, quantiles[q_permutation]) result3 = weighted_quantile(array[random.permutation(size)], quantiles[q_permutation]) assert numpy.all(result1 == result2) and numpy.all(result1 == result3), 'breaks on permutations' # checks that order is kept quantiles = numpy.linspace(0, 1, size * 3) x = weighted_quantile(array, quantiles, sample_weight=random.exponential(size=size)) assert numpy.all(x == numpy.sort(x)), "doesn't preserve order" array = numpy.array([0, 1, 2, 5]) # comparing with simple percentiles for x in random.uniform(size=10): assert numpy.abs(numpy.percentile(array, x * 100) - weighted_quantile(array, x, old_style=True)) < 1e-7, \ "doesn't coincide with numpy.percentile" def test_weighted_percentile(): check_weighted_percentile(RandomState().randint(4, 40), RandomState().randint(4, 40)) check_weighted_percentile(100, 20) check_weighted_percentile(20, 100) def test_build_normalizer(checks=10): predictions = numpy.array(RandomState().normal(size=2000)) result = build_normalizer(predictions)(predictions) assert numpy.all(result[numpy.argsort(predictions)] == sorted(result)) assert numpy.all(result >= 0) and numpy.all(result <= 1) percentiles = [100 * (i + 1.) / (checks + 1.) for i in range(checks)] assert numpy.all(abs(numpy.percentile(result, percentiles) - numpy.array(percentiles) / 100.) < 0.01) # testing with weights predictions = numpy.exp(predictions / 2) weighted_normalizer = build_normalizer(predictions, sample_weight=predictions) result = weighted_normalizer(predictions) assert numpy.all(result[numpy.argsort(predictions)] == sorted(result)) assert numpy.all(result >= 0) and numpy.all(result <= 1 + 1e-7) predictions = numpy.sort(predictions) result = weighted_normalizer(predictions) result2 = numpy.cumsum(predictions) / numpy.sum(predictions) assert numpy.all(numpy.abs(result - result2) < 0.005) def test_compute_cut(): random = RandomState() predictions = random.permutation(100) labels = numpy.ones(100) for eff in [0.1, 0.5, 0.75, 0.99]: cut = compute_cut_for_efficiency(eff, labels, predictions) assert numpy.sum(predictions > cut) / len(predictions) == eff, 'the cut was set wrongly' weights = numpy.array(random.exponential(size=100)) for eff in random.uniform(size=100): cut = compute_cut_for_efficiency(eff, labels, predictions, sample_weight=weights) lower = numpy.sum(weights[predictions > cut + 1]) / numpy.sum(weights) upper = numpy.sum(weights[predictions > cut - 1]) / numpy.sum(weights) assert lower < eff < upper, 'the cut was set wrongly' def test_compute_knn_indices(n_events=100): X, y = generate_sample(n_events, 10, distance=.5) is_signal = y > 0.5 signal_indices = numpy.where(is_signal)[0] uniform_columns = X.columns[:1] knn_indices = compute_knn_indices_of_signal(X[uniform_columns], is_signal, 10) distances = pairwise_distances(X[uniform_columns]) for i, neighbours in enumerate(knn_indices): assert numpy.all(is_signal[neighbours]), "returned indices are not signal" not_neighbours = [x for x in signal_indices if not x in neighbours] min_dist = numpy.min(distances[i, not_neighbours]) max_dist = numpy.max(distances[i, neighbours]) assert min_dist >= max_dist, "distances are set wrongly!" knn_all_indices = compute_knn_indices_of_same_class(X[uniform_columns], is_signal, 10) for i, neighbours in enumerate(knn_all_indices): assert numpy.all(is_signal[neighbours] == is_signal[i]), "returned indices are not signal/bg"
anaderi/hep_ml
tests/test_commonutils.py
Python
apache-2.0
5,407
"""Routines to help recognizing sound files. Function whathdr() recognizes various types of sound file headers. It understands almost all headers that SOX can decode. The return tuple contains the following items, in this order: - file type (as SOX understands it) - sampling rate (0 if unknown or hard to decode) - number of channels (0 if unknown or hard to decode) - number of frames in the file (-1 if unknown or hard to decode) - number of bits/sample, or 'U' for U-LAW, or 'A' for A-LAW If the file doesn't have a recognizable type, it returns None. If the file can't be opened, OSError is raised. To compute the total time, divide the number of frames by the sampling rate (a frame contains a sample for each channel). Function what() calls whathdr(). (It used to also use some heuristics for raw data, but this doesn't work very well.) Finally, the function test() is a simple main program that calls what() for all files mentioned on the argument list. For directory arguments it calls what() for all files in that directory. Default argument is "." (testing all files in the current directory). The option -r tells it to recurse down directories found inside explicitly given directories. """ # The file structure is top-down except that the test program and its # subroutine come last. __all__ = ['what', 'whathdr'] from collections import namedtuple SndHeaders = namedtuple('SndHeaders', 'filetype framerate nchannels nframes sampwidth') SndHeaders.filetype.__doc__ = ("""The value for type indicates the data type and will be one of the strings 'aifc', 'aiff', 'au','hcom', 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', or 'ul'.""") SndHeaders.framerate.__doc__ = ("""The sampling_rate will be either the actual value or 0 if unknown or difficult to decode.""") SndHeaders.nchannels.__doc__ = ("""The number of channels or 0 if it cannot be determined or if the value is difficult to decode.""") SndHeaders.nframes.__doc__ = ("""The value for frames will be either the number of frames or -1.""") SndHeaders.sampwidth.__doc__ = ("""Either the sample size in bits or 'A' for A-LAW or 'U' for u-LAW.""") def what(filename): """Guess the type of a sound file.""" res = whathdr(filename) return res def whathdr(filename): """Recognize sound headers.""" with open(filename, 'rb') as f: h = f.read(512) for tf in tests: res = tf(h, f) if res: return SndHeaders(*res) return None #-----------------------------------# # Subroutines per sound header type # #-----------------------------------# tests = [] def test_aifc(h, f): import aifc if not h.startswith(b'FORM'): return None if h[8:12] == b'AIFC': fmt = 'aifc' elif h[8:12] == b'AIFF': fmt = 'aiff' else: return None f.seek(0) try: a = aifc.open(f, 'r') except (EOFError, aifc.Error): return None return (fmt, a.getframerate(), a.getnchannels(), a.getnframes(), 8 * a.getsampwidth()) tests.append(test_aifc) def test_au(h, f): if h.startswith(b'.snd'): func = get_long_be elif h[:4] in (b'\0ds.', b'dns.'): func = get_long_le else: return None filetype = 'au' hdr_size = func(h[4:8]) data_size = func(h[8:12]) encoding = func(h[12:16]) rate = func(h[16:20]) nchannels = func(h[20:24]) sample_size = 1 # default if encoding == 1: sample_bits = 'U' elif encoding == 2: sample_bits = 8 elif encoding == 3: sample_bits = 16 sample_size = 2 else: sample_bits = '?' frame_size = sample_size * nchannels if frame_size: nframe = data_size / frame_size else: nframe = -1 return filetype, rate, nchannels, nframe, sample_bits tests.append(test_au) def test_hcom(h, f): if h[65:69] != b'FSSD' or h[128:132] != b'HCOM': return None divisor = get_long_be(h[144:148]) if divisor: rate = 22050 / divisor else: rate = 0 return 'hcom', rate, 1, -1, 8 tests.append(test_hcom) def test_voc(h, f): if not h.startswith(b'Creative Voice File\032'): return None sbseek = get_short_le(h[20:22]) rate = 0 if 0 <= sbseek < 500 and h[sbseek] == 1: ratecode = 256 - h[sbseek+4] if ratecode: rate = int(1000000.0 / ratecode) return 'voc', rate, 1, -1, 8 tests.append(test_voc) def test_wav(h, f): import wave # 'RIFF' <len> 'WAVE' 'fmt ' <len> if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ': return None f.seek(0) try: w = wave.openfp(f, 'r') except (EOFError, wave.Error): return None return ('wav', w.getframerate(), w.getnchannels(), w.getnframes(), 8*w.getsampwidth()) tests.append(test_wav) def test_8svx(h, f): if not h.startswith(b'FORM') or h[8:12] != b'8SVX': return None # Should decode it to get #channels -- assume always 1 return '8svx', 0, 1, 0, 8 tests.append(test_8svx) def test_sndt(h, f): if h.startswith(b'SOUND'): nsamples = get_long_le(h[8:12]) rate = get_short_le(h[20:22]) return 'sndt', rate, 1, nsamples, 8 tests.append(test_sndt) def test_sndr(h, f): if h.startswith(b'\0\0'): rate = get_short_le(h[2:4]) if 4000 <= rate <= 25000: return 'sndr', rate, 1, -1, 8 tests.append(test_sndr) #-------------------------------------------# # Subroutines to extract numbers from bytes # #-------------------------------------------# def get_long_be(b): return (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3] def get_long_le(b): return (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0] def get_short_be(b): return (b[0] << 8) | b[1] def get_short_le(b): return (b[1] << 8) | b[0] #--------------------# # Small test program # #--------------------# def test(): import sys recursive = 0 if sys.argv[1:] and sys.argv[1] == '-r': del sys.argv[1:2] recursive = 1 try: if sys.argv[1:]: testall(sys.argv[1:], recursive, 1) else: testall(['.'], recursive, 1) except KeyboardInterrupt: sys.stderr.write('\n[Interrupted]\n') sys.exit(1) def testall(list, recursive, toplevel): import sys import os for filename in list: if os.path.isdir(filename): print(filename + '/:', end=' ') if recursive or toplevel: print('recursing down:') import glob names = glob.glob(os.path.join(filename, '*')) testall(names, recursive, 0) else: print('*** directory (use -r) ***') else: print(filename + ':', end=' ') sys.stdout.flush() try: print(what(filename)) except OSError: print('*** not found ***') if __name__ == '__main__': test()
yotchang4s/cafebabepy
src/main/python/sndhdr.py
Python
bsd-3-clause
7,088
# pylint:disable-msg=R0201 """docstring""" __revision__ = '' class Interface: """base class for interfaces""" class IMachin(Interface): """docstring""" def truc(self): """docstring""" def troc(self, argument): """docstring""" class Correct1: """docstring""" __implements__ = IMachin def __init__(self): pass def truc(self): """docstring""" pass def troc(self, argument): """docstring""" pass class Correct2: """docstring""" __implements__ = (IMachin,) def __init__(self): pass def truc(self): """docstring""" pass def troc(self, argument): """docstring""" print argument class MissingMethod: """docstring""" __implements__ = IMachin, def __init__(self): pass def troc(self, argument): """docstring""" print argument def other(self): """docstring""" class BadArgument: """docstring""" __implements__ = (IMachin,) def __init__(self): pass def truc(self): """docstring""" pass def troc(self): """docstring""" pass class InterfaceCantBeFound: """docstring""" __implements__ = undefined def __init__(self): """only to make pylint happier""" def please(self): """public method 1/2""" def besilent(self): """public method 2/2""" class InterfaceCanNowBeFound: """docstring""" __implements__ = BadArgument.__implements__ + Correct2.__implements__ def __init__(self): """only to make pylint happier""" def please(self): """public method 1/2""" def besilent(self): """public method 2/2"""
dbbhattacharya/kitsune
vendor/packages/pylint/test/input/func_interfaces.py
Python
bsd-3-clause
1,802
#!/usr/bin/python # Author: Jon Trulson <jtrulson@ics.com> # Copyright (c) 2016 Intel Corporation. # # 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 __future__ import print_function import time, sys, signal, atexit from upm import pyupm_bmx055 as sensorObj def main(): # Instantiate a BMX055 instance using default i2c bus and address sensor = sensorObj.BMX055() ## Exit handlers ## # This function stops python from printing a stacktrace when you hit control-C def SIGINTHandler(signum, frame): raise SystemExit # This function lets you run code on exit def exitHandler(): print("Exiting") sys.exit(0) # Register exit handlers atexit.register(exitHandler) signal.signal(signal.SIGINT, SIGINTHandler) x = sensorObj.new_floatp() y = sensorObj.new_floatp() z = sensorObj.new_floatp() # now output data every 250 milliseconds while (1): sensor.update() sensor.getAccelerometer(x, y, z) print("Accelerometer x:", sensorObj.floatp_value(x), end=' ') print(" y:", sensorObj.floatp_value(y), end=' ') print(" z:", sensorObj.floatp_value(z), end=' ') print(" g") sensor.getGyroscope(x, y, z) print("Gyroscope x:", sensorObj.floatp_value(x), end=' ') print(" y:", sensorObj.floatp_value(y), end=' ') print(" z:", sensorObj.floatp_value(z), end=' ') print(" degrees/s") sensor.getMagnetometer(x, y, z) print("Magnetometer x:", sensorObj.floatp_value(x), end=' ') print(" y:", sensorObj.floatp_value(y), end=' ') print(" z:", sensorObj.floatp_value(z), end=' ') print(" uT") print() time.sleep(.250) if __name__ == '__main__': main()
whbruce/upm
examples/python/bmx055.py
Python
mit
2,781
"""Test that `yield` or `yield from` can't be used inside an async function.""" # pylint: disable=missing-docstring, unused-variable async def good_coro(): def _inner(): yield 42 yield from [1, 2, 3] async def bad_coro(): yield 42 yield from [1, 2, 3] # [yield-inside-async-function]
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/y/yield_inside_async_function_py36.py
Python
mit
327
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals def connect_sqs(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """Return async connection to Amazon SQS.""" from .sqs.connection import AsyncSQSConnection return AsyncSQSConnection( aws_access_key_id, aws_secret_access_key, **kwargs )
ammarkhann/FinalSeniorCode
lib/python2.7/site-packages/kombu/async/aws/__init__.py
Python
mit
358
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ This file implements the CLA Classifier region. See the comments in the class definition of CLAClassifierRegion for a description. """ from PyRegion import PyRegion from nupic.algorithms.cla_classifier_factory import CLAClassifierFactory ############################################################################### class CLAClassifierRegion(PyRegion): """ CLAClassifierRegion implements a CLA specific classifier that accepts a binary input from the level below (the "activationPattern") and information from the sensor and encoders (the "classification") describing the input to the system at that time step. When learning, for every bit in activation pattern, it records a history of the classification each time that bit was active. The history is bounded by a maximum allowed age so that old entries are thrown away. For inference, it takes an ensemble approach. For every active bit in the activationPattern, it looks up the most likely classification(s) from the history stored for that bit and then votes across these to get the resulting classification(s). The caller can choose to tell the region that the classifications for iteration N+K should be aligned with the activationPattern for iteration N. This results in the classifier producing predictions for K steps in advance. Any number of different K's can be specified, allowing the classifier to learn and infer multi-step predictions for a number of steps in advance. """ ############################################################################### @classmethod def getSpec(cls): ns = dict( description=CLAClassifierRegion.__doc__, singleNodeOnly=True, # The inputs and outputs are not used in this region because they are # either sparse vectors or dictionaries and hence don't fit the "vector # of real" input/output pattern. # There is a custom compute() function provided that accepts the # inputs and outputs. inputs=dict( categoryIn=dict( description='Category of the input sample', dataType='Real32', count=1, required=True, regionLevel=True, isDefaultInput=False, requireSplitterMap=False), bottomUpIn=dict( description='Belief values over children\'s groups', dataType='Real32', count=0, required=True, regionLevel=False, isDefaultInput=True, requireSplitterMap=False), ), outputs=dict(), parameters=dict( learningMode=dict( description='Boolean (0/1) indicating whether or not a region ' 'is in learning mode.', dataType='UInt32', count=1, constraints='bool', defaultValue=1, accessMode='ReadWrite'), inferenceMode=dict( description='Boolean (0/1) indicating whether or not a region ' 'is in inference mode.', dataType='UInt32', count=1, constraints='bool', defaultValue=0, accessMode='ReadWrite'), steps=dict( description='Comma separated list of the desired steps of ' 'prediction that the classifier should learn', dataType="Byte", count=0, constraints='', defaultValue='1', accessMode='Create'), alpha=dict( description='The alpha used to compute running averages of the ' 'bucket duty cycles for each activation pattern bit. A lower ' 'alpha results in longer term memory', dataType="Real32", count=1, constraints='', defaultValue=0.001, accessMode='Create'), implementation=dict( description='The classifier implementation to use.', accessMode='ReadWrite', dataType='Byte', count=0, constraints='enum: py, cpp'), clVerbosity=dict( description='An integer that controls the verbosity level, ' '0 means no verbose output, increasing integers ' 'provide more verbosity.', dataType='UInt32', count=1, constraints='', defaultValue=0 , accessMode='ReadWrite'), ), commands=dict() ) return ns ############################################################################### def __init__(self, steps='1', alpha=0.001, clVerbosity=0, implementation=None, ): # Convert the steps designation to a list self.steps = steps self.stepsList = eval("[%s]" % (steps)) self.alpha = alpha self.verbosity = clVerbosity # Initialize internal structures self._claClassifier = CLAClassifierFactory.create( steps=self.stepsList, alpha=self.alpha, verbosity=self.verbosity, implementation=implementation, ) self.learningMode = True self.inferenceMode = False self._initEphemerals() ############################################################################### def _initEphemerals(self): pass ############################################################################### def initialize(self, dims, splitterMaps): pass ############################################################################### def clear(self): self._claClassifier.clear() ############################################################################### def getParameter(self, name, index=-1): """ Get the value of the parameter. @param name -- the name of the parameter to retrieve, as defined by the Node Spec. """ # If any spec parameter name is the same as an attribute, this call # will get it automatically, e.g. self.learningMode return PyRegion.getParameter(self, name, index) ############################################################################### def setParameter(self, name, index, value): """ Set the value of the parameter. @param name -- the name of the parameter to update, as defined by the Node Spec. @param value -- the value to which the parameter is to be set. """ if name == "learningMode": self.learningMode = bool(int(value)) elif name == "inferenceMode": self.inferenceMode = bool(int(value)) else: return PyRegion.setParameter(self, name, index, value) ############################################################################### def reset(self): pass ############################################################################### def compute(self, inputs, outputs): """ Process one input sample. This method is called by the runtime engine. We don't use this method in this region because the inputs and outputs don't fit the standard "vector of reals" used by the engine. Instead, call the customCompute() method directly """ pass ############################################################################### def customCompute(self, recordNum, patternNZ, classification): """ Process one input sample. This method is called by outer loop code outside the nupic-engine. We use this instead of the nupic engine compute() because our inputs and outputs aren't fixed size vectors of reals. Parameters: -------------------------------------------------------------------- patternNZ: list of the active indices from the output below classification: dict of the classification information: bucketIdx: index of the encoder bucket actValue: actual value going into the encoder retval: dict containing inference results, one entry for each step in self.steps. The key is the number of steps, the value is an array containing the relative likelihood for each bucketIdx starting from bucketIdx 0. for example: {1 : [0.1, 0.3, 0.2, 0.7] 4 : [0.2, 0.4, 0.3, 0.5]} """ return self._claClassifier.compute( recordNum=recordNum, patternNZ=patternNZ, classification=classification, learn = self.learningMode, infer = self.inferenceMode) ############################################################################### if __name__=='__main__': from nupic.engine import Network n = Network() classifier = n.addRegion( 'classifier', 'py.CLAClassifierRegion', '{ steps: "1,2", maxAge: 1000}' )
tomsilver/nupic
nupic/regions/CLAClassifierRegion.py
Python
gpl-3.0
9,996
from nose.tools import * # noqa import mock from boto.s3.connection import * # noqa from tests.base import OsfTestCase, get_default_metaschema from tests.factories import ProjectFactory from framework.auth import Auth from website.addons.base.testing import models from website.addons.s3.model import S3NodeSettings from website.addons.s3.tests.factories import ( S3UserSettingsFactory, S3NodeSettingsFactory, S3AccountFactory ) class TestUserSettings(models.OAuthAddonUserSettingTestSuiteMixin, OsfTestCase): short_name = 's3' full_name = 'Amazon S3' ExternalAccountFactory = S3AccountFactory class TestNodeSettings(models.OAuthAddonNodeSettingsTestSuiteMixin, OsfTestCase): short_name = 's3' full_name = 'Amazon S3' ExternalAccountFactory = S3AccountFactory NodeSettingsFactory = S3NodeSettingsFactory NodeSettingsClass = S3NodeSettings UserSettingsFactory = S3UserSettingsFactory def test_registration_settings(self): registration = ProjectFactory() clone, message = self.node_settings.after_register( self.node, registration, self.user, ) assert_is_none(clone) def test_before_register_no_settings(self): self.node_settings.user_settings = None message = self.node_settings.before_register(self.node, self.user) assert_false(message) def test_before_register_no_auth(self): self.node_settings.external_account = None message = self.node_settings.before_register(self.node, self.user) assert_false(message) def test_before_register_settings_and_auth(self): message = self.node_settings.before_register(self.node, self.user) assert_true(message) @mock.patch('website.archiver.tasks.archive') def test_does_not_get_copied_to_registrations(self, mock_archive): registration = self.node.register_node( schema=get_default_metaschema(), auth=Auth(user=self.user), data='hodor', ) assert_false(registration.has_addon('s3')) ## Overrides ## def test_serialize_credentials(self): self.user_settings.external_accounts[0].oauth_key = 'key-11' self.user_settings.external_accounts[0].oauth_secret = 'secret-15' self.user_settings.save() credentials = self.node_settings.serialize_waterbutler_credentials() expected = {'access_key': self.node_settings.external_account.oauth_key, 'secret_key': self.node_settings.external_account.oauth_secret} assert_equal(credentials, expected) @mock.patch('website.addons.s3.model.bucket_exists') @mock.patch('website.addons.s3.model.get_bucket_location_or_error') def test_set_folder(self, mock_location, mock_exists): mock_exists.return_value = True mock_location.return_value = '' folder_id = '1234567890' self.node_settings.set_folder(folder_id, auth=Auth(self.user)) self.node_settings.save() # Bucket was set assert_equal(self.node_settings.folder_id, folder_id) # Log was saved last_log = self.node.logs[-1] assert_equal(last_log.action, '{0}_bucket_linked'.format(self.short_name)) def test_serialize_settings(self): settings = self.node_settings.serialize_waterbutler_settings() expected = {'bucket': self.node_settings.folder_id, 'encrypt_uploads': self.node_settings.encrypt_uploads} assert_equal(settings, expected)
rdhyee/osf.io
website/addons/s3/tests/test_model.py
Python
apache-2.0
3,529
"""Support for Nanoleaf Lights.""" import logging import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_TRANSITION, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_TRANSITION, Light) from homeassistant.const import CONF_HOST, CONF_NAME, CONF_TOKEN import homeassistant.helpers.config_validation as cv from homeassistant.util import color as color_util from homeassistant.util.color import \ color_temperature_mired_to_kelvin as mired_to_kelvin from homeassistant.util.json import load_json, save_json _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'Nanoleaf' DATA_NANOLEAF = 'nanoleaf' CONFIG_FILE = '.nanoleaf.conf' ICON = 'mdi:triangle-outline' SUPPORT_NANOLEAF = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT | SUPPORT_COLOR | SUPPORT_TRANSITION) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_TOKEN): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Nanoleaf light.""" from pynanoleaf import Nanoleaf, Unavailable if DATA_NANOLEAF not in hass.data: hass.data[DATA_NANOLEAF] = dict() token = '' if discovery_info is not None: host = discovery_info['host'] name = discovery_info['hostname'] # if device already exists via config, skip discovery setup if host in hass.data[DATA_NANOLEAF]: return _LOGGER.info("Discovered a new Nanoleaf: %s", discovery_info) conf = load_json(hass.config.path(CONFIG_FILE)) if conf.get(host, {}).get('token'): token = conf[host]['token'] else: host = config[CONF_HOST] name = config[CONF_NAME] token = config[CONF_TOKEN] nanoleaf_light = Nanoleaf(host) if not token: token = nanoleaf_light.request_token() if not token: _LOGGER.error("Could not generate the auth token, did you press " "and hold the power button on %s" "for 5-7 seconds?", name) return conf = load_json(hass.config.path(CONFIG_FILE)) conf[host] = {'token': token} save_json(hass.config.path(CONFIG_FILE), conf) nanoleaf_light.token = token try: nanoleaf_light.available except Unavailable: _LOGGER.error( "Could not connect to Nanoleaf Light: %s on %s", name, host) return hass.data[DATA_NANOLEAF][host] = nanoleaf_light add_entities([NanoleafLight(nanoleaf_light, name)], True) class NanoleafLight(Light): """Representation of a Nanoleaf Light.""" def __init__(self, light, name): """Initialize an Nanoleaf light.""" self._available = True self._brightness = None self._color_temp = None self._effect = None self._effects_list = None self._light = light self._name = name self._hs_color = None self._state = None @property def available(self): """Return availability.""" return self._available @property def brightness(self): """Return the brightness of the light.""" if self._brightness is not None: return int(self._brightness * 2.55) return None @property def color_temp(self): """Return the current color temperature.""" if self._color_temp is not None: return color_util.color_temperature_kelvin_to_mired( self._color_temp) return None @property def effect(self): """Return the current effect.""" return self._effect @property def effect_list(self): """Return the list of supported effects.""" return self._effects_list @property def min_mireds(self): """Return the coldest color_temp that this light supports.""" return 154 @property def max_mireds(self): """Return the warmest color_temp that this light supports.""" return 833 @property def name(self): """Return the display name of this light.""" return self._name @property def icon(self): """Return the icon to use in the frontend, if any.""" return ICON @property def is_on(self): """Return true if light is on.""" return self._state @property def hs_color(self): """Return the color in HS.""" return self._hs_color @property def supported_features(self): """Flag supported features.""" return SUPPORT_NANOLEAF def turn_on(self, **kwargs): """Instruct the light to turn on.""" brightness = kwargs.get(ATTR_BRIGHTNESS) hs_color = kwargs.get(ATTR_HS_COLOR) color_temp_mired = kwargs.get(ATTR_COLOR_TEMP) effect = kwargs.get(ATTR_EFFECT) transition = kwargs.get(ATTR_TRANSITION) if hs_color: hue, saturation = hs_color self._light.hue = int(hue) self._light.saturation = int(saturation) if color_temp_mired: self._light.color_temperature = mired_to_kelvin(color_temp_mired) if transition: if brightness: # tune to the required brightness in n seconds self._light.brightness_transition( int(brightness / 2.55), int(transition)) else: # If brightness is not specified, assume full brightness self._light.brightness_transition(100, int(transition)) else: # If no transition is occurring, turn on the light self._light.on = True if brightness: self._light.brightness = int(brightness / 2.55) if effect: self._light.effect = effect def turn_off(self, **kwargs): """Instruct the light to turn off.""" transition = kwargs.get(ATTR_TRANSITION) if transition: self._light.brightness_transition(0, int(transition)) else: self._light.on = False def update(self): """Fetch new state data for this light.""" from pynanoleaf import Unavailable try: self._available = self._light.available self._brightness = self._light.brightness self._color_temp = self._light.color_temperature self._effect = self._light.effect self._effects_list = self._light.effects self._hs_color = self._light.hue, self._light.saturation self._state = self._light.on except Unavailable as err: _LOGGER.error("Could not update status for %s (%s)", self.name, err) self._available = False
MartinHjelmare/home-assistant
homeassistant/components/nanoleaf/light.py
Python
apache-2.0
6,951
from __future__ import absolute_import from __future__ import print_function import filecmp import os import ujson from django.core import mail from django.http import HttpResponse from django.test import override_settings from mock import patch from typing import Any, Dict, List from zerver.lib.actions import do_change_stream_invite_only from zerver.models import get_realm, get_stream, get_user_profile_by_email, \ Realm, Stream, UserProfile from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import ( avatar_disk_path, get_test_image_file, tornado_redirected_to_list, ) class BotTest(ZulipTestCase): def assert_num_bots_equal(self, count): # type: (int) -> None result = self.client_get("/json/bots") self.assert_json_success(result) json = ujson.loads(result.content) self.assertEqual(count, len(json['bots'])) def create_bot(self, **extras): # type: (**Any) -> Dict[str, Any] bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } bot_info.update(extras) result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) return ujson.loads(result.content) def test_bot_domain(self): # type: () -> None self.login("hamlet@zulip.com") self.create_bot() self.assertTrue(UserProfile.objects.filter(email='hambot-bot@zulip.testserver').exists()) # The other cases are hard to test directly, since we don't allow creating bots from # the wrong subdomain, and because 'testserver.example.com' is not a valid domain for the bot's email. # So we just test the Raelm.get_bot_domain function. realm = get_realm('zulip') with self.settings(REALMS_HAVE_SUBDOMAINS=True): self.assertEqual(realm.get_bot_domain(), 'zulip.testserver') Realm.objects.exclude(string_id='zulip').update(deactivated=True) self.assertEqual(realm.get_bot_domain(), 'testserver') def deactivate_bot(self): # type: () -> None result = self.client_delete("/json/bots/hambot-bot@zulip.testserver") self.assert_json_success(result) def test_add_bot_with_bad_username(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) bot_info = dict( full_name='', short_name='', ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Bad name or username') self.assert_num_bots_equal(0) def test_add_bot(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) events = [] # type: List[Dict[str, Any]] with tornado_redirected_to_list(events): result = self.create_bot() self.assert_num_bots_equal(1) bot = get_user_profile_by_email('hambot-bot@zulip.testserver') event = [e for e in events if e['event']['type'] == 'realm_bot'][0] self.assertEqual( dict( type='realm_bot', op='add', bot=dict(email='hambot-bot@zulip.testserver', user_id=bot.id, full_name='The Bot of Hamlet', is_active=True, api_key=result['api_key'], avatar_url=result['avatar_url'], default_sending_stream=None, default_events_register_stream=None, default_all_public_streams=False, owner='hamlet@zulip.com') ), event['event'] ) users_result = self.client_get('/json/users') members = ujson.loads(users_result.content)['members'] bots = [m for m in members if m['email'] == 'hambot-bot@zulip.testserver'] self.assertEqual(len(bots), 1) bot = bots[0] self.assertEqual(bot['bot_owner'], 'hamlet@zulip.com') self.assertEqual(bot['user_id'], get_user_profile_by_email('hambot-bot@zulip.testserver').id) def test_add_bot_with_username_in_use(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) result = self.create_bot() self.assert_num_bots_equal(1) bot_info = dict( full_name='Duplicate', short_name='hambot', ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'Username already in use') def test_add_bot_with_user_avatar(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) with get_test_image_file('img.png') as fp: self.create_bot(file=fp) profile = get_user_profile_by_email('hambot-bot@zulip.testserver') # Make sure that avatar image that we've uploaded is same with avatar image in the server self.assertTrue(filecmp.cmp(fp.name, os.path.splitext(avatar_disk_path(profile))[0] + ".original")) self.assert_num_bots_equal(1) self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_USER) self.assertTrue(os.path.exists(avatar_disk_path(profile))) def test_add_bot_with_too_many_files(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) with get_test_image_file('img.png') as fp1, \ get_test_image_file('img.gif') as fp2: bot_info = dict( full_name='whatever', short_name='whatever', file1=fp1, file2=fp2, ) result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, 'You may only upload one file at a time') self.assert_num_bots_equal(0) def test_add_bot_with_default_sending_stream(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) result = self.create_bot(default_sending_stream='Denmark') self.assert_num_bots_equal(1) self.assertEqual(result['default_sending_stream'], 'Denmark') profile = get_user_profile_by_email('hambot-bot@zulip.testserver') self.assertEqual(profile.default_sending_stream.name, 'Denmark') def test_add_bot_with_default_sending_stream_not_subscribed(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) result = self.create_bot(default_sending_stream='Rome') self.assert_num_bots_equal(1) self.assertEqual(result['default_sending_stream'], 'Rome') profile = get_user_profile_by_email('hambot-bot@zulip.testserver') self.assertEqual(profile.default_sending_stream.name, 'Rome') def test_bot_add_subscription(self): # type: () -> None """ Calling POST /json/users/me/subscriptions should successfully add streams, and a stream to the list of subscriptions and confirm the right number of events are generated. When 'principals' has a bot, no notification message event or invitation email is sent when add_subscriptions_backend is called in the above api call. """ self.login("hamlet@zulip.com") # Normal user i.e. not a bot. request_data = { 'principals': '["iago@zulip.com"]' } events = [] # type: List[Dict[str, Any]] with tornado_redirected_to_list(events): result = self.common_subscribe_to_streams("hamlet@zulip.com", ['Rome'], request_data) self.assert_json_success(result) msg_event = [e for e in events if e['event']['type'] == 'message'] self.assert_length(msg_event, 1) # Notification message event is sent. # Create a bot. self.assert_num_bots_equal(0) result = self.create_bot() self.assert_num_bots_equal(1) # A bot bot_request_data = { 'principals': '["hambot-bot@zulip.testserver"]' } events_bot = [] # type: List[Dict[str, Any]] with tornado_redirected_to_list(events_bot): result = self.common_subscribe_to_streams("hamlet@zulip.com", ['Rome'], bot_request_data) self.assert_json_success(result) # No notification message event or invitation email is sent because of bot. msg_event = [e for e in events_bot if e['event']['type'] == 'message'] self.assert_length(msg_event, 0) self.assertEqual(len(events_bot), len(events) - 1) # Test runner automatically redirects all sent email to a dummy 'outbox'. self.assertEqual(len(mail.outbox), 0) def test_add_bot_with_default_sending_stream_private_allowed(self): # type: () -> None self.login("hamlet@zulip.com") user_profile = get_user_profile_by_email("hamlet@zulip.com") stream = get_stream("Denmark", user_profile.realm) self.subscribe_to_stream(user_profile.email, stream.name) do_change_stream_invite_only(stream, True) self.assert_num_bots_equal(0) events = [] # type: List[Dict[str, Any]] with tornado_redirected_to_list(events): result = self.create_bot(default_sending_stream='Denmark') self.assert_num_bots_equal(1) self.assertEqual(result['default_sending_stream'], 'Denmark') profile = get_user_profile_by_email('hambot-bot@zulip.testserver') self.assertEqual(profile.default_sending_stream.name, 'Denmark') event = [e for e in events if e['event']['type'] == 'realm_bot'][0] self.assertEqual( dict( type='realm_bot', op='add', bot=dict(email='hambot-bot@zulip.testserver', user_id=profile.id, full_name='The Bot of Hamlet', is_active=True, api_key=result['api_key'], avatar_url=result['avatar_url'], default_sending_stream='Denmark', default_events_register_stream=None, default_all_public_streams=False, owner='hamlet@zulip.com') ), event['event'] ) self.assertEqual(event['users'], (user_profile.id,)) def test_add_bot_with_default_sending_stream_private_denied(self): # type: () -> None self.login("hamlet@zulip.com") user_profile = get_user_profile_by_email("hamlet@zulip.com") stream = get_stream("Denmark", user_profile.realm) self.unsubscribe_from_stream("hamlet@zulip.com", "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', 'default_sending_stream': 'Denmark', } result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, "Invalid stream name 'Denmark'") def test_add_bot_with_default_events_register_stream(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) result = self.create_bot(default_events_register_stream='Denmark') self.assert_num_bots_equal(1) self.assertEqual(result['default_events_register_stream'], 'Denmark') profile = get_user_profile_by_email('hambot-bot@zulip.testserver') self.assertEqual(profile.default_events_register_stream.name, 'Denmark') def test_add_bot_with_default_events_register_stream_private_allowed(self): # type: () -> None self.login("hamlet@zulip.com") user_profile = get_user_profile_by_email("hamlet@zulip.com") stream = self.subscribe_to_stream(user_profile.email, 'Denmark') do_change_stream_invite_only(stream, True) self.assert_num_bots_equal(0) events = [] # type: List[Dict[str, Any]] with tornado_redirected_to_list(events): result = self.create_bot(default_events_register_stream='Denmark') self.assert_num_bots_equal(1) self.assertEqual(result['default_events_register_stream'], 'Denmark') bot_profile = get_user_profile_by_email('hambot-bot@zulip.testserver') self.assertEqual(bot_profile.default_events_register_stream.name, 'Denmark') event = [e for e in events if e['event']['type'] == 'realm_bot'][0] self.assertEqual( dict( type='realm_bot', op='add', bot=dict(email='hambot-bot@zulip.testserver', full_name='The Bot of Hamlet', user_id=bot_profile.id, is_active=True, api_key=result['api_key'], avatar_url=result['avatar_url'], default_sending_stream=None, default_events_register_stream='Denmark', default_all_public_streams=False, owner='hamlet@zulip.com') ), event['event'] ) self.assertEqual(event['users'], (user_profile.id,)) def test_add_bot_with_default_events_register_stream_private_denied(self): # type: () -> None self.login("hamlet@zulip.com") user_profile = get_user_profile_by_email("hamlet@zulip.com") stream = get_stream("Denmark", user_profile.realm) self.unsubscribe_from_stream("hamlet@zulip.com", "Denmark") do_change_stream_invite_only(stream, True) self.assert_num_bots_equal(0) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', 'default_events_register_stream': 'Denmark', } result = self.client_post("/json/bots", bot_info) self.assert_json_error(result, "Invalid stream name 'Denmark'") def test_add_bot_with_default_all_public_streams(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) result = self.create_bot(default_all_public_streams=ujson.dumps(True)) self.assert_num_bots_equal(1) self.assertTrue(result['default_all_public_streams']) profile = get_user_profile_by_email('hambot-bot@zulip.testserver') self.assertEqual(profile.default_all_public_streams, True) def test_deactivate_bot(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) self.deactivate_bot() # You can deactivate the same bot twice. self.deactivate_bot() self.assert_num_bots_equal(0) def test_deactivate_bogus_bot(self): # type: () -> None """Deleting a bogus bot will succeed silently.""" self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) result = self.client_delete("/json/bots/bogus-bot@zulip.com") self.assert_json_error(result, 'No such bot') self.assert_num_bots_equal(1) def test_bot_deactivation_attacks(self): # type: () -> None """You cannot deactivate somebody else's bot.""" self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) # Have Othello try to deactivate both Hamlet and # Hamlet's bot. self.login("othello@zulip.com") # Can not deactivate a user as a bot result = self.client_delete("/json/bots/hamlet@zulip.com") self.assert_json_error(result, 'No such bot') result = self.client_delete("/json/bots/hambot-bot@zulip.testserver") self.assert_json_error(result, 'Insufficient permission') # But we don't actually deactivate the other person's bot. self.login("hamlet@zulip.com") self.assert_num_bots_equal(1) # Can not deactivate a bot as a user result = self.client_delete("/json/users/hambot-bot@zulip.testserver") self.assert_json_error(result, 'No such user') self.assert_num_bots_equal(1) def test_bot_permissions(self): # type: () -> None self.login("hamlet@zulip.com") self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) # Have Othello try to mess with Hamlet's bots. self.login("othello@zulip.com") result = self.client_post("/json/bots/hambot-bot@zulip.testserver/api_key/regenerate") self.assert_json_error(result, 'Insufficient permission') bot_info = { 'full_name': 'Fred', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_error(result, 'Insufficient permission') def get_bot(self): # type: () -> Dict[str, Any] result = self.client_get("/json/bots") bots = ujson.loads(result.content)['bots'] return bots[0] def test_update_api_key(self): # type: () -> None self.login("hamlet@zulip.com") self.create_bot() bot = self.get_bot() old_api_key = bot['api_key'] result = self.client_post('/json/bots/hambot-bot@zulip.testserver/api_key/regenerate') self.assert_json_success(result) new_api_key = ujson.loads(result.content)['api_key'] self.assertNotEqual(old_api_key, new_api_key) bot = self.get_bot() self.assertEqual(new_api_key, bot['api_key']) def test_update_api_key_for_invalid_user(self): # type: () -> None self.login("hamlet@zulip.com") result = self.client_post('/json/bots/nonexistentuser@zulip.com/api_key/regenerate') self.assert_json_error(result, 'No such user') def test_patch_bot_full_name(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'full_name': 'Fred', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) full_name = ujson.loads(result.content)['full_name'] self.assertEqual('Fred', full_name) bot = self.get_bot() self.assertEqual('Fred', bot['full_name']) def test_patch_bot_owner(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'bot_owner': 'othello@zulip.com', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) # Test bot's owner has been changed successfully. bot_owner = ujson.loads(result.content)['bot_owner'] self.assertEqual(bot_owner, 'othello@zulip.com') self.login('othello@zulip.com') bot = self.get_bot() self.assertEqual('The Bot of Hamlet', bot['full_name']) @override_settings(LOCAL_UPLOADS_DIR='var/bot_avatar') def test_patch_bot_avatar(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) profile = get_user_profile_by_email('hambot-bot@zulip.testserver') self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR) # Try error case first (too many files): with get_test_image_file('img.png') as fp1, \ get_test_image_file('img.gif') as fp2: result = self.client_patch_multipart( '/json/bots/hambot-bot@zulip.testserver', dict(file1=fp1, file2=fp2)) self.assert_json_error(result, 'You may only upload one file at a time') profile = get_user_profile_by_email("hambot-bot@zulip.testserver") self.assertEqual(profile.avatar_version, 1) # HAPPY PATH with get_test_image_file('img.png') as fp: result = self.client_patch_multipart( '/json/bots/hambot-bot@zulip.testserver', dict(file=fp)) profile = get_user_profile_by_email('hambot-bot@zulip.testserver') self.assertEqual(profile.avatar_version, 2) # Make sure that avatar image that we've uploaded is same with avatar image in the server self.assertTrue(filecmp.cmp(fp.name, os.path.splitext(avatar_disk_path(profile))[0] + ".original")) self.assert_json_success(result) self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_USER) self.assertTrue(os.path.exists(avatar_disk_path(profile))) def test_patch_bot_to_stream(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'Denmark', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_sending_stream = ujson.loads(result.content)['default_sending_stream'] self.assertEqual('Denmark', default_sending_stream) bot = self.get_bot() self.assertEqual('Denmark', bot['default_sending_stream']) def test_patch_bot_to_stream_not_subscribed(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'Rome', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_sending_stream = ujson.loads(result.content)['default_sending_stream'] self.assertEqual('Rome', default_sending_stream) bot = self.get_bot() self.assertEqual('Rome', bot['default_sending_stream']) def test_patch_bot_to_stream_none(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': '', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_sending_stream = get_user_profile_by_email( "hambot-bot@zulip.testserver").default_sending_stream self.assertEqual(None, default_sending_stream) bot = self.get_bot() self.assertEqual(None, bot['default_sending_stream']) def test_patch_bot_to_stream_private_allowed(self): # type: () -> None self.login("hamlet@zulip.com") user_profile = get_user_profile_by_email("hamlet@zulip.com") stream = self.subscribe_to_stream(user_profile.email, "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'Denmark', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_sending_stream = ujson.loads(result.content)['default_sending_stream'] self.assertEqual('Denmark', default_sending_stream) bot = self.get_bot() self.assertEqual('Denmark', bot['default_sending_stream']) def test_patch_bot_to_stream_private_denied(self): # type: () -> None self.login("hamlet@zulip.com") user_profile = get_user_profile_by_email("hamlet@zulip.com") stream = get_stream("Denmark", user_profile.realm) self.unsubscribe_from_stream("hamlet@zulip.com", "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'Denmark', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_error(result, "Invalid stream name 'Denmark'") def test_patch_bot_to_stream_not_found(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_sending_stream': 'missing', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_error(result, "Invalid stream name 'missing'") def test_patch_bot_events_register_stream(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': 'Denmark', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_events_register_stream = ujson.loads(result.content)['default_events_register_stream'] self.assertEqual('Denmark', default_events_register_stream) bot = self.get_bot() self.assertEqual('Denmark', bot['default_events_register_stream']) def test_patch_bot_events_register_stream_allowed(self): # type: () -> None self.login("hamlet@zulip.com") user_profile = get_user_profile_by_email("hamlet@zulip.com") stream = self.subscribe_to_stream(user_profile.email, "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': 'Denmark', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_events_register_stream = ujson.loads(result.content)['default_events_register_stream'] self.assertEqual('Denmark', default_events_register_stream) bot = self.get_bot() self.assertEqual('Denmark', bot['default_events_register_stream']) def test_patch_bot_events_register_stream_denied(self): # type: () -> None self.login("hamlet@zulip.com") user_profile = get_user_profile_by_email("hamlet@zulip.com") stream = get_stream("Denmark", user_profile.realm) self.unsubscribe_from_stream("hamlet@zulip.com", "Denmark") do_change_stream_invite_only(stream, True) bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': 'Denmark', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_error(result, "Invalid stream name 'Denmark'") def test_patch_bot_events_register_stream_none(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': '', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_events_register_stream = get_user_profile_by_email( "hambot-bot@zulip.testserver").default_events_register_stream self.assertEqual(None, default_events_register_stream) bot = self.get_bot() self.assertEqual(None, bot['default_events_register_stream']) def test_patch_bot_events_register_stream_not_found(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_events_register_stream': 'missing', } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_error(result, "Invalid stream name 'missing'") def test_patch_bot_default_all_public_streams_true(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_all_public_streams': ujson.dumps(True), } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_events_register_stream = ujson.loads(result.content)['default_all_public_streams'] self.assertEqual(default_events_register_stream, True) bot = self.get_bot() self.assertEqual(bot['default_all_public_streams'], True) def test_patch_bot_default_all_public_streams_false(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'default_all_public_streams': ujson.dumps(False), } result = self.client_patch("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) default_events_register_stream = ujson.loads(result.content)['default_all_public_streams'] self.assertEqual(default_events_register_stream, False) bot = self.get_bot() self.assertEqual(bot['default_all_public_streams'], False) def test_patch_bot_via_post(self): # type: () -> None self.login("hamlet@zulip.com") bot_info = { 'full_name': 'The Bot of Hamlet', 'short_name': 'hambot', } result = self.client_post("/json/bots", bot_info) self.assert_json_success(result) bot_info = { 'full_name': 'Fred', 'method': 'PATCH' } result = self.client_post("/json/bots/hambot-bot@zulip.testserver", bot_info) self.assert_json_success(result) full_name = ujson.loads(result.content)['full_name'] self.assertEqual('Fred', full_name) bot = self.get_bot() self.assertEqual('Fred', bot['full_name']) def test_patch_bogus_bot(self): # type: () -> None """Deleting a bogus bot will succeed silently.""" self.login("hamlet@zulip.com") self.create_bot() bot_info = { 'full_name': 'Fred', } result = self.client_patch("/json/bots/nonexistent-bot@zulip.com", bot_info) self.assert_json_error(result, 'No such user') self.assert_num_bots_equal(1)
dawran6/zulip
zerver/tests/test_bots.py
Python
apache-2.0
33,314
from typing import Optional, Set, Text import re # Match multi-word string between @** ** or match any one-word # sequences after @ find_mentions = r'(?<![^\s\'\"\(,:<])@(\*\*[^\*]+\*\*|all|everyone)' user_group_mentions = r'(?<![^\s\'\"\(,:<])@(\*[^\*]+\*)' wildcards = ['all', 'everyone'] def user_mention_matches_wildcard(mention: Text) -> bool: return mention in wildcards def extract_name(s: Text) -> Optional[Text]: if s.startswith("**") and s.endswith("**"): name = s[2:-2] if name in wildcards: return None return name # We don't care about @all or @everyone return None def possible_mentions(content: Text) -> Set[Text]: matches = re.findall(find_mentions, content) names_with_none = (extract_name(match) for match in matches) names = {name for name in names_with_none if name} return names def extract_user_group(matched_text: Text) -> Text: return matched_text[1:-1] def possible_user_group_mentions(content: Text) -> Set[Text]: matches = re.findall(user_group_mentions, content) return {extract_user_group(match) for match in matches}
mahim97/zulip
zerver/lib/mention.py
Python
apache-2.0
1,137
from __future__ import unicode_literals from django.contrib.syndication.views import Feed from django.contrib.sites.models import get_current_site from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django_images.models import Thumbnail from taggit.models import Tag from .models import Pin def filter_generator_for(size): def wrapped_func(obj): return Thumbnail.objects.get_or_create_at_size(obj.pk, size) return wrapped_func class LatestPins(Feed): title = 'Latest Pins' link = '/' description = 'The latest pins from around the internet.' domain_name = None item_enclosure_mime_type = 'image/jpeg' def get_object(self, request): """ Doing this as a fix for Django's not including the domain name in enclosure urls. """ try: request_type = 'http' if request.is_secure(): request_type = 'https' self.domain_name = ''.join([request_type, '://', get_current_site(request).domain]) except: pass def items(self): return Pin.objects.order_by('-published')[:15] def item_pubdate(self, item): return item.published def item_link(self, item): return item.url def item_title(self, item): return item.url def item_description(self, item): tags = ', '.join(tag.name for tag in item.tags.all()) return ''.join(['Description: ', item.description or 'None', ' | Tags: ', tags or 'None']) def item_enclosure_url(self, item): slug = unicode(filter_generator_for('standard')(item.image).image.url) return self.domain_name + slug def item_enclosure_length(self, item): return filter_generator_for('standard')(item.image).image.size class LatestUserPins(Feed): description = 'The latest pins from around the internet.' domain_name = None item_enclosure_mime_type = 'image/jpeg' def get_object(self, request, user): """ Doing this as a fix for Django's not including the domain name in enclosure urls. """ request_type = 'http' if request.is_secure(): request_type = 'https' self.domain_name = ''.join([request_type, '://', get_current_site(request).domain]) return get_object_or_404(User, username=user) def title(self, obj): return 'Latest Pins from ' + obj.username def link(self, obj): return '/pins/user/' + obj.username + '/' def items(self, obj): return Pin.objects.filter(submitter=obj).order_by('-published')[:15] def item_pubdate(self, item): return item.published def item_link(self, item): return item.url def item_title(self, item): return item.url def item_description(self, item): tags = ', '.join(tag.name for tag in item.tags.all()) return ''.join(['Description: ', item.description or 'None', ' | Tags: ', tags or 'None']) def item_enclosure_url(self, item): slug = unicode(filter_generator_for('standard')(item.image).image.url) return self.domain_name + slug def item_enclosure_length(self, item): return filter_generator_for('standard')(item.image).image.size class LatestTagPins(Feed): link = '/' description = 'The latest pins from around the internet.' domain_name = None item_enclosure_mime_type = 'image/jpeg' def get_object(self, request, tag): """ Doing this as a fix for Django's not including the domain name in enclosure urls. """ request_type = 'http' if request.is_secure(): request_type = 'https' self.domain_name = ''.join([request_type, '://', get_current_site(request).domain]) return get_object_or_404(Tag, name=tag) def title(self, obj): return 'Latest Pins in ' + obj.name def link(self, obj): return '/pins/tag/' + obj.name + '/' def items(self, obj): return Pin.objects.filter(tags=obj).order_by('-published')[:15] def item_pubdate(self, item): return item.published def item_link(self, item): return item.url def item_title(self, item): return item.url def item_description(self, item): tags = ', '.join(tag.name for tag in item.tags.all()) return ''.join(['Description: ', item.description or 'None', ' | Tags: ', tags or 'None']) def item_enclosure_url(self, item): slug = unicode(filter_generator_for('standard')(item.image).image.url) return self.domain_name + slug def item_enclosure_length(self, item): return filter_generator_for('standard')(item.image).image.size
supervacuo/pinry
pinry/core/feeds.py
Python
bsd-2-clause
4,918
# Authors: Nicolas Goix <nicolas.goix@telecom-paristech.fr> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD 3 clause from __future__ import division import numpy as np import scipy as sp from warnings import warn from scipy.sparse import issparse import numbers from ..externals import six from ..tree import ExtraTreeRegressor from ..utils import check_random_state, check_array from .bagging import BaseBagging __all__ = ["IsolationForest"] INTEGER_TYPES = (numbers.Integral, np.integer) class IsolationForest(BaseBagging): """Isolation Forest Algorithm Return the anomaly score of each sample using the IsolationForest algorithm The IsolationForest 'isolates' observations by randomly selecting a feature and then randomly selecting a split value between the maximum and minimum values of the selected feature. Since recursive partitioning can be represented by a tree structure, the number of splittings required to isolate a sample is equivalent to the path length from the root node to the terminating node. This path length, averaged over a forest of such random trees, is a measure of normality and our decision function. Random partitioning produces noticeably shorter paths for anomalies. Hence, when a forest of random trees collectively produce shorter path lengths for particular samples, they are highly likely to be anomalies. Read more in the :ref:`User Guide <isolation_forest>`. .. versionadded:: 0.18 Parameters ---------- n_estimators : int, optional (default=100) The number of base estimators in the ensemble. max_samples : int or float, optional (default="auto") The number of samples to draw from X to train each base estimator. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. - If "auto", then `max_samples=min(256, n_samples)`. If max_samples is larger than the number of samples provided, all samples will be used for all trees (no sampling). contamination : float in (0., 0.5), optional (default=0.1) The amount of contamination of the data set, i.e. the proportion of outliers in the data set. Used when fitting to define the threshold on the decision function. max_features : int or float, optional (default=1.0) The number of features to draw from X to train each base estimator. - If int, then draw `max_features` features. - If float, then draw `max_features * X.shape[1]` features. bootstrap : boolean, optional (default=False) If True, individual trees are fit on random subsets of the training data sampled with replacement. If False, sampling without replacement is performed. n_jobs : integer, optional (default=1) The number of jobs to run in parallel for both `fit` and `predict`. If -1, then the number of jobs is set to the number of cores. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. verbose : int, optional (default=0) Controls the verbosity of the tree building process. Attributes ---------- estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. estimators_samples_ : list of arrays The subset of drawn samples (i.e., the in-bag samples) for each base estimator. max_samples_ : integer The actual number of samples References ---------- .. [1] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. "Isolation forest." Data Mining, 2008. ICDM'08. Eighth IEEE International Conference on. .. [2] Liu, Fei Tony, Ting, Kai Ming and Zhou, Zhi-Hua. "Isolation-based anomaly detection." ACM Transactions on Knowledge Discovery from Data (TKDD) 6.1 (2012): 3. """ def __init__(self, n_estimators=100, max_samples="auto", contamination=0.1, max_features=1., bootstrap=False, n_jobs=1, random_state=None, verbose=0): super(IsolationForest, self).__init__( base_estimator=ExtraTreeRegressor( max_features=1, splitter='random', random_state=random_state), # here above max_features has no links with self.max_features bootstrap=bootstrap, bootstrap_features=False, n_estimators=n_estimators, max_samples=max_samples, max_features=max_features, n_jobs=n_jobs, random_state=random_state, verbose=verbose) self.contamination = contamination def _set_oob_score(self, X, y): raise NotImplementedError("OOB score not supported by iforest") def fit(self, X, y=None, sample_weight=None): """Fit estimator. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csc_matrix`` for maximum efficiency. Returns ------- self : object Returns self. """ # ensure_2d=False because there are actually unit test checking we fail # for 1d. X = check_array(X, accept_sparse=['csc'], ensure_2d=False) if issparse(X): # Pre-sort indices to avoid that each individual tree of the # ensemble sorts the indices. X.sort_indices() rnd = check_random_state(self.random_state) y = rnd.uniform(size=X.shape[0]) # ensure that max_sample is in [1, n_samples]: n_samples = X.shape[0] if isinstance(self.max_samples, six.string_types): if self.max_samples == 'auto': max_samples = min(256, n_samples) else: raise ValueError('max_samples (%s) is not supported.' 'Valid choices are: "auto", int or' 'float' % self.max_samples) elif isinstance(self.max_samples, INTEGER_TYPES): if self.max_samples > n_samples: warn("max_samples (%s) is greater than the " "total number of samples (%s). max_samples " "will be set to n_samples for estimation." % (self.max_samples, n_samples)) max_samples = n_samples else: max_samples = self.max_samples else: # float if not (0. < self.max_samples <= 1.): raise ValueError("max_samples must be in (0, 1], got %r" % self.max_samples) max_samples = int(self.max_samples * X.shape[0]) self.max_samples_ = max_samples max_depth = int(np.ceil(np.log2(max(max_samples, 2)))) super(IsolationForest, self)._fit(X, y, max_samples, max_depth=max_depth, sample_weight=sample_weight) self.threshold_ = -sp.stats.scoreatpercentile( -self.decision_function(X), 100. * (1. - self.contamination)) return self def predict(self, X): """Predict if a particular sample is an outlier or not. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Returns ------- is_inlier : array, shape (n_samples,) For each observations, tells whether or not (+1 or -1) it should be considered as an inlier according to the fitted model. """ X = check_array(X, accept_sparse='csr') is_inlier = np.ones(X.shape[0], dtype=int) is_inlier[self.decision_function(X) <= self.threshold_] = -1 return is_inlier def decision_function(self, X): """Average anomaly score of X of the base classifiers. The anomaly score of an input sample is computed as the mean anomaly score of the trees in the forest. The measure of normality of an observation given a tree is the depth of the leaf containing this observation, which is equivalent to the number of splittings required to isolate this point. In case of several observations n_left in the leaf, the average path length of a n_left samples isolation tree is added. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns ------- scores : array of shape (n_samples,) The anomaly score of the input samples. The lower, the more abnormal. """ # code structure from ForestClassifier/predict_proba # Check data X = self.estimators_[0]._validate_X_predict(X, check_input=True) n_samples = X.shape[0] n_samples_leaf = np.zeros((n_samples, self.n_estimators), order="f") depths = np.zeros((n_samples, self.n_estimators), order="f") for i, tree in enumerate(self.estimators_): leaves_index = tree.apply(X) node_indicator = tree.decision_path(X) n_samples_leaf[:, i] = tree.tree_.n_node_samples[leaves_index] depths[:, i] = np.asarray(node_indicator.sum(axis=1)).reshape(-1) - 1 depths += _average_path_length(n_samples_leaf) scores = 2 ** (-depths.mean(axis=1) / _average_path_length(self.max_samples_)) # Take the opposite of the scores as bigger is better (here less # abnormal) and add 0.5 (this value plays a special role as described # in the original paper) to give a sense to scores = 0: return 0.5 - scores def _average_path_length(n_samples_leaf): """ The average path length in a n_samples iTree, which is equal to the average path length of an unsuccessful BST search since the latter has the same structure as an isolation tree. Parameters ---------- n_samples_leaf : array-like of shape (n_samples, n_estimators), or int. The number of training samples in each test sample leaf, for each estimators. Returns ------- average_path_length : array, same shape as n_samples_leaf """ if isinstance(n_samples_leaf, INTEGER_TYPES): if n_samples_leaf <= 1: return 1. else: return 2. * (np.log(n_samples_leaf) + 0.5772156649) - 2. * ( n_samples_leaf - 1.) / n_samples_leaf else: n_samples_leaf_shape = n_samples_leaf.shape n_samples_leaf = n_samples_leaf.reshape((1, -1)) average_path_length = np.zeros(n_samples_leaf.shape) mask = (n_samples_leaf <= 1) not_mask = np.logical_not(mask) average_path_length[mask] = 1. average_path_length[not_mask] = 2. * ( np.log(n_samples_leaf[not_mask]) + 0.5772156649) - 2. * ( n_samples_leaf[not_mask] - 1.) / n_samples_leaf[not_mask] return average_path_length.reshape(n_samples_leaf_shape)
waterponey/scikit-learn
sklearn/ensemble/iforest.py
Python
bsd-3-clause
11,906
from __future__ import unicode_literals import codecs import os import shutil import tempfile import unittest from admin_scripts.tests import AdminScriptTestCase from django.conf import settings from django.contrib.staticfiles import storage from django.contrib.staticfiles.management.commands import collectstatic from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command from django.test import override_settings from django.test.utils import extend_sys_path from django.utils import six from django.utils._os import symlinks_supported from django.utils.encoding import force_text from django.utils.functional import empty from .cases import CollectionTestCase, StaticFilesTestCase, TestDefaults from .settings import TEST_ROOT, TEST_SETTINGS from .storage import DummyStorage class TestNoFilesCreated(object): def test_no_files_created(self): """ Make sure no files were create in the destination directory. """ self.assertEqual(os.listdir(settings.STATIC_ROOT), []) class TestFindStatic(TestDefaults, CollectionTestCase): """ Test ``findstatic`` management command. """ def _get_file(self, filepath): path = call_command('findstatic', filepath, all=False, verbosity=0, stdout=six.StringIO()) with codecs.open(force_text(path), "r", "utf-8") as f: return f.read() def test_all_files(self): """ Test that findstatic returns all candidate files if run without --first and -v1. """ result = call_command('findstatic', 'test/file.txt', verbosity=1, stdout=six.StringIO()) lines = [l.strip() for l in result.split('\n')] self.assertEqual(len(lines), 3) # three because there is also the "Found <file> here" line self.assertIn('project', force_text(lines[1])) self.assertIn('apps', force_text(lines[2])) def test_all_files_less_verbose(self): """ Test that findstatic returns all candidate files if run without --first and -v0. """ result = call_command('findstatic', 'test/file.txt', verbosity=0, stdout=six.StringIO()) lines = [l.strip() for l in result.split('\n')] self.assertEqual(len(lines), 2) self.assertIn('project', force_text(lines[0])) self.assertIn('apps', force_text(lines[1])) def test_all_files_more_verbose(self): """ Test that findstatic returns all candidate files if run without --first and -v2. Also, test that findstatic returns the searched locations with -v2. """ result = call_command('findstatic', 'test/file.txt', verbosity=2, stdout=six.StringIO()) lines = [l.strip() for l in result.split('\n')] self.assertIn('project', force_text(lines[1])) self.assertIn('apps', force_text(lines[2])) self.assertIn("Looking in the following locations:", force_text(lines[3])) searched_locations = ', '.join(force_text(x) for x in lines[4:]) # AppDirectoriesFinder searched locations self.assertIn(os.path.join('staticfiles_tests', 'apps', 'test', 'static'), searched_locations) self.assertIn(os.path.join('staticfiles_tests', 'apps', 'no_label', 'static'), searched_locations) # FileSystemFinder searched locations self.assertIn(TEST_SETTINGS['STATICFILES_DIRS'][1][1], searched_locations) self.assertIn(TEST_SETTINGS['STATICFILES_DIRS'][0], searched_locations) # DefaultStorageFinder searched locations self.assertIn( os.path.join('staticfiles_tests', 'project', 'site_media', 'media'), searched_locations ) class TestConfiguration(StaticFilesTestCase): def test_location_empty(self): msg = 'without having set the STATIC_ROOT setting to a filesystem path' err = six.StringIO() for root in ['', None]: with override_settings(STATIC_ROOT=root): with self.assertRaisesMessage(ImproperlyConfigured, msg): call_command('collectstatic', interactive=False, verbosity=0, stderr=err) def test_local_storage_detection_helper(self): staticfiles_storage = storage.staticfiles_storage try: storage.staticfiles_storage._wrapped = empty with self.settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage'): command = collectstatic.Command() self.assertTrue(command.is_local_storage()) storage.staticfiles_storage._wrapped = empty with self.settings(STATICFILES_STORAGE='staticfiles_tests.storage.DummyStorage'): command = collectstatic.Command() self.assertFalse(command.is_local_storage()) collectstatic.staticfiles_storage = storage.FileSystemStorage() command = collectstatic.Command() self.assertTrue(command.is_local_storage()) collectstatic.staticfiles_storage = DummyStorage() command = collectstatic.Command() self.assertFalse(command.is_local_storage()) finally: staticfiles_storage._wrapped = empty collectstatic.staticfiles_storage = staticfiles_storage storage.staticfiles_storage = staticfiles_storage class TestCollectionHelpSubcommand(AdminScriptTestCase): @override_settings(STATIC_ROOT=None) def test_missing_settings_dont_prevent_help(self): """ Even if the STATIC_ROOT setting is not set, one can still call the `manage.py help collectstatic` command. """ self.write_settings('settings.py', apps=['django.contrib.staticfiles']) out, err = self.run_manage(['help', 'collectstatic']) self.assertNoOutput(err) class TestCollection(TestDefaults, CollectionTestCase): """ Test ``collectstatic`` management command. """ def test_ignore(self): """ Test that -i patterns are ignored. """ self.assertFileNotFound('test/test.ignoreme') def test_common_ignore_patterns(self): """ Common ignore patterns (*~, .*, CVS) are ignored. """ self.assertFileNotFound('test/.hidden') self.assertFileNotFound('test/backup~') self.assertFileNotFound('test/CVS') class TestCollectionClear(CollectionTestCase): """ Test the ``--clear`` option of the ``collectstatic`` management command. """ def run_collectstatic(self, **kwargs): clear_filepath = os.path.join(settings.STATIC_ROOT, 'cleared.txt') with open(clear_filepath, 'w') as f: f.write('should be cleared') super(TestCollectionClear, self).run_collectstatic(clear=True) def test_cleared_not_found(self): self.assertFileNotFound('cleared.txt') def test_dir_not_exists(self, **kwargs): shutil.rmtree(six.text_type(settings.STATIC_ROOT)) super(TestCollectionClear, self).run_collectstatic(clear=True) @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.PathNotImplementedStorage') def test_handle_path_notimplemented(self): self.run_collectstatic() self.assertFileNotFound('cleared.txt') class TestCollectionExcludeNoDefaultIgnore(TestDefaults, CollectionTestCase): """ Test ``--exclude-dirs`` and ``--no-default-ignore`` options of the ``collectstatic`` management command. """ def run_collectstatic(self): super(TestCollectionExcludeNoDefaultIgnore, self).run_collectstatic( use_default_ignore_patterns=False) def test_no_common_ignore_patterns(self): """ With --no-default-ignore, common ignore patterns (*~, .*, CVS) are not ignored. """ self.assertFileContains('test/.hidden', 'should be ignored') self.assertFileContains('test/backup~', 'should be ignored') self.assertFileContains('test/CVS', 'should be ignored') class TestCollectionDryRun(TestNoFilesCreated, CollectionTestCase): """ Test ``--dry-run`` option for ``collectstatic`` management command. """ def run_collectstatic(self): super(TestCollectionDryRun, self).run_collectstatic(dry_run=True) class TestCollectionFilesOverride(CollectionTestCase): """ Test overriding duplicated files by ``collectstatic`` management command. Check for proper handling of apps order in installed apps even if file modification dates are in different order: 'staticfiles_test_app', 'staticfiles_tests.apps.no_label', """ def setUp(self): self.temp_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.temp_dir) # get modification and access times for no_label/static/file2.txt self.orig_path = os.path.join(TEST_ROOT, 'apps', 'no_label', 'static', 'file2.txt') self.orig_mtime = os.path.getmtime(self.orig_path) self.orig_atime = os.path.getatime(self.orig_path) # prepare duplicate of file2.txt from a temporary app # this file will have modification time older than no_label/static/file2.txt # anyway it should be taken to STATIC_ROOT because the temporary app is before # 'no_label' app in installed apps self.temp_app_path = os.path.join(self.temp_dir, 'staticfiles_test_app') self.testfile_path = os.path.join(self.temp_app_path, 'static', 'file2.txt') os.makedirs(self.temp_app_path) with open(os.path.join(self.temp_app_path, '__init__.py'), 'w+'): pass os.makedirs(os.path.dirname(self.testfile_path)) with open(self.testfile_path, 'w+') as f: f.write('duplicate of file2.txt') os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1)) self.settings_with_test_app = self.modify_settings( INSTALLED_APPS={'prepend': 'staticfiles_test_app'}) with extend_sys_path(self.temp_dir): self.settings_with_test_app.enable() super(TestCollectionFilesOverride, self).setUp() def tearDown(self): super(TestCollectionFilesOverride, self).tearDown() self.settings_with_test_app.disable() def test_ordering_override(self): """ Test if collectstatic takes files in proper order """ self.assertFileContains('file2.txt', 'duplicate of file2.txt') # run collectstatic again self.run_collectstatic() self.assertFileContains('file2.txt', 'duplicate of file2.txt') # The collectstatic test suite already has conflicting files since both # project/test/file.txt and apps/test/static/test/file.txt are collected. To # properly test for the warning not happening unless we tell it to explicitly, # we remove the project directory and will add back a conflicting file later. @override_settings(STATICFILES_DIRS=[]) class TestCollectionOverwriteWarning(CollectionTestCase): """ Test warning in ``collectstatic`` output when a file is skipped because a previous file was already written to the same path. """ # If this string is in the collectstatic output, it means the warning we're # looking for was emitted. warning_string = 'Found another file' def _collectstatic_output(self, **kwargs): """ Run collectstatic, and capture and return the output. We want to run the command at highest verbosity, which is why we can't just call e.g. BaseCollectionTestCase.run_collectstatic() """ out = six.StringIO() call_command('collectstatic', interactive=False, verbosity=3, stdout=out, **kwargs) return force_text(out.getvalue()) def test_no_warning(self): """ There isn't a warning if there isn't a duplicate destination. """ output = self._collectstatic_output(clear=True) self.assertNotIn(self.warning_string, output) def test_warning(self): """ There is a warning when there are duplicate destinations. """ static_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, static_dir) duplicate = os.path.join(static_dir, 'test', 'file.txt') os.mkdir(os.path.dirname(duplicate)) with open(duplicate, 'w+') as f: f.write('duplicate of file.txt') with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True) self.assertIn(self.warning_string, output) os.remove(duplicate) # Make sure the warning went away again. with self.settings(STATICFILES_DIRS=[static_dir]): output = self._collectstatic_output(clear=True) self.assertNotIn(self.warning_string, output) @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.DummyStorage') class TestCollectionNonLocalStorage(TestNoFilesCreated, CollectionTestCase): """ Tests for #15035 """ pass @unittest.skipUnless(symlinks_supported(), "Must be able to symlink to run this test.") class TestCollectionLinks(TestDefaults, CollectionTestCase): """ Test ``--link`` option for ``collectstatic`` management command. Note that by inheriting ``TestDefaults`` we repeat all the standard file resolving tests here, to make sure using ``--link`` does not change the file-selection semantics. """ def run_collectstatic(self, clear=False): super(TestCollectionLinks, self).run_collectstatic(link=True, clear=clear) def test_links_created(self): """ With ``--link``, symbolic links are created. """ self.assertTrue(os.path.islink(os.path.join(settings.STATIC_ROOT, 'test.txt'))) def test_broken_symlink(self): """ Test broken symlink gets deleted. """ path = os.path.join(settings.STATIC_ROOT, 'test.txt') os.unlink(path) self.run_collectstatic() self.assertTrue(os.path.islink(path)) def test_clear_broken_symlink(self): """ With ``--clear``, broken symbolic links are deleted. """ nonexistent_file_path = os.path.join(settings.STATIC_ROOT, 'nonexistent.txt') broken_symlink_path = os.path.join(settings.STATIC_ROOT, 'symlink.txt') os.symlink(nonexistent_file_path, broken_symlink_path) self.run_collectstatic(clear=True) self.assertFalse(os.path.lexists(broken_symlink_path))
indevgr/django
tests/staticfiles_tests/test_management.py
Python
bsd-3-clause
14,449
from doit.action import CmdAction def task_hello(): """hello cmd """ def create_cmd_string(): return "echo hi" return { 'actions': [CmdAction(create_cmd_string)], 'verbosity': 2, }
wangpanjun/doit
doc/tutorial/cmd_from_callable.py
Python
mit
228
from app.config.cplog import CPLog from app.lib.provider.movie.base import movieBase from imdb import IMDb from urllib import quote_plus from urllib2 import URLError import cherrypy import os import urllib2 log = CPLog(__name__) class theMovieDb(movieBase): """Api for theMovieDb""" apiUrl = 'http://api.themoviedb.org/2.1' imageUrl = 'http://hwcdn.themoviedb.org' def __init__(self, config): log.info('Using TheMovieDb provider.') self.config = config def conf(self, option): return self.config.get('TheMovieDB', option) def find(self, q, limit = 8, alternative = True): ''' Find movie by name ''' if self.isDisabled(): return False log.debug('TheMovieDB - Searching for movie: %s' % q) url = "%s/%s/en/xml/%s/%s" % (self.apiUrl, 'Movie.search', self.conf('key'), quote_plus(self.toSearchString(q))) try: log.info('Searching: %s' % url) data = urllib2.urlopen(url, timeout = self.timeout) return self.parseXML(data, limit, alternative = alternative) except: return [] def findById(self, id): ''' Find movie by TheMovieDB ID ''' if self.isDisabled(): return False xml = self.getXML(id) if xml: results = self.parseXML(xml, limit = 8) return results.pop(0) else: return False def findByImdbId(self, id): ''' Find movie by IMDB ID ''' if self.isDisabled(): return False url = "%s/%s/en/xml/%s/%s" % (self.apiUrl, 'Movie.imdbLookup', self.conf('key'), id) try: data = urllib2.urlopen(url, timeout = self.timeout) except (IOError, URLError): log.error('Failed to open %s.' % url) return [] results = self.parseXML(data, limit = 8, alternative = False) if results: return results.pop(0) else: return [] def parseXML(self, data, limit, alternative = True): if data: log.debug('TheMovieDB - Parsing RSS') try: xml = self.getItems(data, 'movies/movie') results = [] nr = 0 for movie in xml: id = int(self.gettextelement(movie, "id")) name = self.gettextelement(movie, "name") imdb = self.gettextelement(movie, "imdb_id") year = str(self.gettextelement(movie, "released"))[:4] # 1900 is the same as None if year == '1900': year = 'None' # do some IMDB searching if needed if year == 'None': i = IMDb('mobile') if imdb: log.info('Found movie, but with no date, getting data from %s.' % imdb) r = i.get_movie(imdb.replace('tt', '')) year = r.get('year', None) else: log.info('Found movie, but with no date, searching IMDB.') r = i.search_movie(name) if len(r) > 0: imdb = 'tt' + r[0].movieID year = r[0].get('year', None) results.append(self.fillFeedItem(id, name, imdb, year)) alternativeName = self.gettextelement(movie, "alternative_name") if alternativeName and alternative: if alternativeName.lower() != name.lower() and alternativeName.lower() != 'none' and alternativeName != None: results.append(self.fillFeedItem(id, alternativeName, imdb, year)) nr += 1 if nr == limit: break log.info('TheMovieDB - Found: %s' % results) return results except SyntaxError: log.error('TheMovieDB - Failed to parse XML response from TheMovieDb') return False def getXML(self, id): if self.isDisabled(): return False try: url = "%s/%s/en/xml/%s/%s" % (self.apiUrl, 'Movie.getInfo', self.conf('key'), id) data = urllib2.urlopen(url, timeout = self.timeout) except: data = False return data def saveImage(self, url, destination): if url[:7] != 'http://': url = self.imageUrl + url # Make dir imageCache = os.path.join(cherrypy.config.get('cachePath'), 'images') if not os.path.isdir(imageCache): os.mkdir(imageCache) # Return old imageFile = os.path.join(imageCache, destination) if not os.path.isfile(imageFile): try: data = urllib2.urlopen(url, timeout = 10) # Write file with open(imageFile, 'wb') as f: f.write(data.read()) except (IOError, URLError): log.error('Failed get thumb %s.' % url) return False return 'cache/images/' + destination def fillFeedItem(self, id, name, imdb, year): item = self.feedItem() item.id = id item.name = self.toSaveString(name) item.imdb = imdb item.year = year return item def isDisabled(self): if self.conf('key') == '': log.error('TheMovieDB - No API key provided for TheMovieDB') True else: False def findReleaseDate(self, movie): pass
lechat/CouchPotato
app/lib/provider/movie/sources/theMovieDb.py
Python
gpl-3.0
5,746
# Gnome15 - Suite of tools for the Logitech G series keyboards and headsets # Copyright (C) 2010 Brett Smith <tanktarta@blueyonder.co.uk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gnome15.g15locale as g15locale _ = g15locale.get_translation("sysmon", modfile = __file__).ugettext import gnome15.util.g15convert as g15convert import gnome15.util.g15uigconf as g15uigconf import gnome15.util.g15gconf as g15gconf import gnome15.util.g15cairo as g15cairo import gnome15.util.g15icontools as g15icontools import gnome15.g15driver as g15driver import gnome15.g15plugin as g15plugin import time import logging logger=logging.getLogger(__name__) try: import gtop except Exception as e: logger.debug("Could not import gtop. Falling back to g15top", exc_info = e) # API compatible work around for Ubuntu 12.10 import gnome15.g15top as gtop import gtk import os import sys import socket id = "sysmon" name = _("System Monitor") description = _("Display CPU, Memory, and Network statistics. Either a summary of each system's stats is displayed, or \ you may cycle through the CPU and Network interfaces.") author = "Brett Smith <tanktarta@blueyonder.co.uk>" copyright = _("Copyright (C)2010 Brett Smith") site = "http://www.gnome15.org" default_enabled = True has_preferences = True actions={ g15driver.PREVIOUS_SELECTION : _("Toggle Monitored CPU"), g15driver.NEXT_SELECTION : _("Toggle Monitored Network\nInterface") } unsupported_models = [ g15driver.MODEL_G110, g15driver.MODEL_G11, g15driver.MODEL_G930, g15driver.MODEL_G35 ] # Various constants GRAPH_SIZE = 50 CPU_ICONS = [ "utilities-system-monitor","gnome-cpu-frequency-applet", "computer" ] ''' This plugin displays system statistics ''' def create(gconf_key, gconf_client, screen): return G15SysMon(gconf_key, gconf_client, screen) def show_preferences(parent, driver, gconf_client, gconf_key): widget_tree = gtk.Builder() widget_tree.add_from_file(os.path.join(os.path.dirname(__file__), "sysmon.ui")) dialog = widget_tree.get_object("SysmonDialog") dialog.set_transient_for(parent) g15uigconf.configure_checkbox_from_gconf(gconf_client, gconf_key + "/show_cpu_on_panel", "ShowCPUUsageOnPanel", True, widget_tree) dialog.run() dialog.hide() class Net(): def __init__(self, net_no, name): self.net_no = net_no self.name = name self.recv_bps = 0.0 self.send_bps = 0.0 self.last_net_list = None self.max_send = 0.0001 self.max_recv = 0.0001 self.send_history = [0] * GRAPH_SIZE self.recv_history = [0] * GRAPH_SIZE self.last_net_list = None self.last_time = 0 def new_data(self, this_net_list): now = time.time() ''' Net ''' self.recv_bps = 0.0 self.send_bps = 0.0 if self.last_net_list != None: time_taken = now - self.last_time if self.net_no == 0: this_total = self._get_net_total(this_net_list) last_total = self._get_net_total(self.last_net_list) else: this_total = self._get_net(this_net_list[self.name]) last_total = self._get_net(self.last_net_list[self.name]) # How many bps self.recv_bps = (this_total[0] - last_total[0]) / time_taken self.send_bps = (this_total[1] - last_total[1]) / time_taken # Adjust the maximums if necessary if self.recv_bps > self.max_recv: self.max_recv = self.recv_bps if self.send_bps > self.max_send: self.max_send = self.send_bps # History self.send_history.append(self.recv_bps) while len(self.send_history) > GRAPH_SIZE: del self.send_history[0] self.recv_history.append(self.send_bps) while len(self.recv_history) > GRAPH_SIZE: del self.recv_history[0] self.last_net_list = this_net_list self.last_time = now def _get_net(self, card): totals = (card[0], card[1]) return totals def _get_net_total(self, net_list): totals = (0, 0) for l in net_list: card = net_list[l] totals = (totals[0] + card[0], totals[1]) totals = (totals[0], totals[1] + card[1]) return totals class CPU(): def __init__(self, number): self.number = number self.name = "cpu%d" % number if number >= 0 else "cpu" self.history = [0] * GRAPH_SIZE self.value = 0 self.times = None self.last_times = None def new_times(self, time_list): if self.last_times is not None: working_list = list(time_list) ''' Work out the number of time units the CPU has spent on each task type since the last time we checked ''' for i in range(len(self.last_times)): working_list[i] -= self.last_times[i] self.pc = self.get_pc(working_list) else: self.pc = 0 self.last_times = time_list # Update the history and trim it to the graph data size self.history.append(self.pc) while len(self.history) > GRAPH_SIZE: del self.history[0] def get_pc(self, times): sum_l = sum(times) val = times[len(times)- 1] if sum_l > 0: return 100 - (val * 100.00 / sum_l) return 0 class G15SysMon(g15plugin.G15RefreshingPlugin): """ Plugin implementation """ def __init__(self, gconf_key, gconf_client, screen): g15plugin.G15RefreshingPlugin.__init__(self, gconf_client, gconf_key, screen, CPU_ICONS, id, name) self.only_refresh_when_visible = False def activate(self): self._net_icon = g15icontools.get_icon_path([ "network-transmit-receive", "gnome-fs-network", "network-server" ], self.screen.height) self._cpu_icon = g15icontools.get_icon_path( CPU_ICONS, self.screen.height) self._mem_icon = g15icontools.get_icon_path( [ "media-memory", "media-flash" ], self.screen.height) self._thumb_icon = g15cairo.load_surface_from_file(self._cpu_icon) self.variant = 0 self.graphs = {} self.last_time_list = None self.last_times_list = [] self.last_time = 0 # CPU self.selected_cpu = None self.cpu_no = 0 self.cpu_data = [] selected_cpu_name = self.gconf_client.get_string(self.gconf_key + "/cpu") cpus = gtop.cpu().cpus for i in range(-1, len(cpus)): cpu = CPU(i) self.cpu_data.append(cpu) if cpu.name == selected_cpu_name: self.selected_cpu = cpu if self.selected_cpu is None: self.selected_cpu = self.cpu_data[0] # Net self.selected_net = None _, self.net_list = self._get_net_stats() net_name = self.gconf_client.get_string(self.gconf_key + "/net") self.net_data = [] for idx, n in enumerate(self.net_list): net = Net(idx, n) self.net_data.append(net) if net.name == net_name: self.selected_net = net if self.selected_net is None and len(self.net_data) > 0: self.selected_net = self.net_data[0] # Memory self.max_total_mem = 0 self.total = 1.0 self.cached = 0 self.free = 0 self.used = 0 self.cached_history = [0] * GRAPH_SIZE self.used_history = [0] * GRAPH_SIZE g15plugin.G15RefreshingPlugin.activate(self) self._set_panel() self.watch(["show_cpu_on_panel","theme"], self._config_changed) self.screen.key_handler.action_listeners.append(self) # Start refreshing self.do_refresh() def reload_theme(self): g15plugin.G15RefreshingPlugin.reload_theme(self) self._set_panel() def deactivate(self): g15plugin.G15RefreshingPlugin.deactivate(self) self.screen.key_handler.action_listeners.remove(self) def action_performed(self, binding): if self.page and self.page.is_visible(): if binding.action == g15driver.PREVIOUS_SELECTION: idx = self.cpu_data.index(self.selected_cpu) idx += 1 if idx >= len(self.cpu_data): idx = 0 self.gconf_client.set_string(self.gconf_key + "/cpu", self.cpu_data[idx].name) self.selected_cpu = self.cpu_data[idx] self.do_refresh() return True elif binding.action == g15driver.NEXT_SELECTION: if self.selected_net is not None: idx = self.net_data.index(self.selected_net) idx += 1 if idx >= len(self.net_data): idx = 0 self.gconf_client.set_string(self.gconf_key + "/net", self.net_data[idx].name) self.selected_net = self.net_data[idx] self.do_refresh() return True def refresh(self): # Memory mem = self._get_mem_info() now = time.time() ''' CPU ''' for c in self.cpu_data: c.new_times(self._get_time_list(c)) ''' Net ''' # Current net status this_net_list, self.net_list = self._get_net_stats() for n in self.net_data: n.new_data(this_net_list) ''' Memory ''' self.total = float(mem.total) self.max_total_mem = max(self.max_total_mem, self.total) self.free = float(mem.free) self.used = self.total - self.free self.cached = float(mem.cached) self.noncached = self.total - self.free - self.cached self.used_history.append(self.used + self.cached) while len(self.used_history) > GRAPH_SIZE: del self.used_history[0] self.cached_history.append(self.cached) while len(self.cached_history) > GRAPH_SIZE: del self.cached_history[0] self.last_time = now ''' Private ''' def _config_changed(self, client, connection_id, entry, args): self.reload_theme() self._reschedule_refresh() def _set_panel(self, client = None, connection_id = None, entry = None, args = None): self.page.panel_painter = self._paint_panel if g15gconf.get_bool_or_default(self.gconf_client, self.gconf_key + "/show_cpu_on_panel", True) else None def _refresh(self): if self.page is not None: if self.screen.is_visible(self.page): self.refresh() self.screen.redraw(self.page) elif self.page.panel_painter is not None: self.refresh() self.screen.redraw(redraw_content = False) self._schedule_refresh() def get_theme_properties(self): properties = {} properties["cpu_pc"] = "%3d" % self.selected_cpu.pc properties["mem_total"] = "%f" % ( self.total / 1024 ) properties["mem_free_k"] = "%f" % ( self.free / 1024 ) properties["mem_used_k"] = "%f" % ( self.used / 1024 ) properties["mem_cached_k"] = "%f" % ( self.cached / 1024 ) properties["mem_noncached_k"] = "%f" % ( self.noncached / 1024 ) properties["mem_total_mb"] = "%.2f" % ( self.total / 1024 / 1024 ) properties["mem_free_mb"] = "%.2f" % ( self.free / 1024 / 1024 ) properties["mem_used_mb"] = "%.2f" % ( self.used / 1024 / 1024 ) properties["mem_cached_mb" ] = "%3d" % ( self.cached / 1024 / 1024 ) properties["mem_noncached_mb" ] = "%3d" % ( self.noncached / 1024 / 1024 ) properties["mem_total_gb"] = "%.1f" % ( self.total / 1024 / 1024 / 1024 ) properties["mem_free_gb"] = "%.1f" % ( self.free / 1024 / 1024 / 1024 ) properties["mem_used_gb"] = "%.1f" % ( self.used / 1024 / 1024 / 1024 ) properties["mem_cached_gb" ] = "%.1f" % ( self.cached / 1024 / 1024 / 1024 ) properties["mem_noncached_gb"] = "%.1f" % ( self.noncached / 1024 / 1024 / 1024 ) properties["mem_used_pc"] = int(self.used * 100.0 / self.total) properties["mem_cached_pc"] = int(self.cached * 100.0 / self.total) properties["mem_noncached_pc"] = int(self.noncached * 100.0 / self.total) if self.selected_net is not None: properties["net_recv_pc"] = int(self.selected_net.recv_bps * 100.0 / self.selected_net.max_recv) properties["net_send_pc"] = int(self.selected_net.send_bps * 100.0 / self.selected_net.max_send) properties["net_recv_mbps"] = "%.2f" % (self.selected_net.recv_bps / 1024 / 1024) properties["net_send_mbps"] = "%.2f" % (self.selected_net.send_bps / 1024 / 1024) properties["net_no"] = self.selected_net.name.upper() idx = self.net_data.index(self.selected_net) properties["next_net_no"] = self.net_list[idx + 1].upper() if idx < ( len(self.net_list) - 1) else self.net_list[0].upper() else: for c in ["net_recv_pc","net_send_pc","net_recv_mbps","net_send_mbps"]: properties[c] = "" # TODO we should ship some more appropriate default icons properties["net_icon"] = self._net_icon properties["cpu_icon"] = self._cpu_icon properties["mem_icon"] = self._mem_icon try : properties["info"] = socket.gethostname() except Exception as e: logger.debug("Could not get hostname. Falling back to 'System'", exc_info = e) properties["info"] = "System" properties["cpu_no"] = self.selected_cpu.name.upper() idx = self.cpu_data.index(self.selected_cpu) properties["next_cpu_no"] = self.cpu_data[idx + 1].name.upper() if idx < ( len(self.cpu_data) - 1) else self.cpu_data[0].name.upper() return properties def _paint_thumbnail(self, canvas, allocated_size, horizontal): if self.page != None and self._thumb_icon != None and self.screen.driver.get_bpp() == 16: return g15cairo.paint_thumbnail_image(allocated_size, self._thumb_icon, canvas) def _paint_panel(self, canvas, allocated_size, horizontal): if self.page != None and self.screen.driver.get_bpp() == 16: canvas.save() no_cpus = len(self.cpu_data) - 1 if no_cpus < 2: bar_width = 16 elif no_cpus < 3: bar_width = 8 elif no_cpus < 5: bar_width = 6 elif no_cpus < 9: bar_width = 4 else: bar_width = 2 total_width = ( bar_width + 1 ) * no_cpus available_height = allocated_size - 4 r, g, b = self.screen.driver.get_color_as_ratios(g15driver.HINT_FOREGROUND, (0,0,0)) canvas.set_line_width(1.0) canvas.set_source_rgba(r, g, b, 0.3) canvas.rectangle(0, 0, total_width + 4, allocated_size ) canvas.stroke() canvas.set_source_rgb(*self.screen.driver.get_color_as_ratios(g15driver.HINT_HIGHLIGHT, (0,0,0))) canvas.translate(2, 0) for i in self.cpu_data: if i.number >= 0: bar_height = float(available_height) * ( float(i.pc) / 100.0 ) canvas.rectangle(0, available_height - bar_height + 2, bar_width, bar_height ) canvas.fill() canvas.translate(bar_width + 1, 0) canvas.restore() return 4 + total_width def _get_net_stats(self): ifs = { } nets = gtop.netlist() for net in nets: netload = gtop.netload(net) ifs[net] = [ netload.bytes_in, netload.bytes_out ] nets.insert(0, "Net") return ifs, nets def _get_time_list(self, cpu): ''' Returns a 4 element list containing the amount of time the CPU has spent performing the different types of work 0 user 1 nice 2 system 3 idle Values are in USER_HZ or Jiffies ''' if cpu.number == -1: cpu_times = gtop.cpu() else: cpu_times = gtop.cpu().cpus[cpu.number] return [cpu_times.user, cpu_times.nice, cpu_times.sys, cpu_times.idle] def _get_mem_info(self): return gtop.mem()
achilleas-k/gnome15
src/plugins/sysmon/sysmon.py
Python
gpl-3.0
18,178
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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.osv import fields, osv class account_chart(osv.osv_memory): """ For Chart of Accounts """ _name = "account.chart" _description = "Account chart" _columns = { 'fiscalyear': fields.many2one('account.fiscalyear', \ 'Fiscal year', \ help='Keep empty for all open fiscal years'), 'period_from': fields.many2one('account.period', 'Start period'), 'period_to': fields.many2one('account.period', 'End period'), 'target_move': fields.selection([('posted', 'All Posted Entries'), ('all', 'All Entries'), ], 'Target Moves', required=True), } def _get_fiscalyear(self, cr, uid, context=None): """Return default Fiscalyear value""" return self.pool.get('account.fiscalyear').find(cr, uid, context=context) def onchange_fiscalyear(self, cr, uid, ids, fiscalyear_id=False, context=None): res = {} if fiscalyear_id: start_period = end_period = False cr.execute(''' SELECT * FROM (SELECT p.id FROM account_period p LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id) WHERE f.id = %s ORDER BY p.date_start ASC, p.special DESC LIMIT 1) AS period_start UNION ALL SELECT * FROM (SELECT p.id FROM account_period p LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id) WHERE f.id = %s AND p.date_start < NOW() ORDER BY p.date_stop DESC LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id)) periods = [i[0] for i in cr.fetchall()] if periods: start_period = periods[0] if len(periods) > 1: end_period = periods[1] res['value'] = {'period_from': start_period, 'period_to': end_period} else: res['value'] = {'period_from': False, 'period_to': False} return res def account_chart_open_window(self, cr, uid, ids, context=None): """ Opens chart of Accounts @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of account chart’s IDs @return: dictionary of Open account chart window on given fiscalyear and all Entries or posted entries """ mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') period_obj = self.pool.get('account.period') fy_obj = self.pool.get('account.fiscalyear') if context is None: context = {} data = self.read(cr, uid, ids, context=context)[0] result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_tree') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] fiscalyear_id = data.get('fiscalyear', False) and data['fiscalyear'][0] or False result['periods'] = [] if data['period_from'] and data['period_to']: period_from = data.get('period_from', False) and data['period_from'][0] or False period_to = data.get('period_to', False) and data['period_to'][0] or False result['periods'] = period_obj.build_ctx_periods(cr, uid, period_from, period_to) result['context'] = str({'fiscalyear': fiscalyear_id, 'periods': result['periods'], \ 'state': data['target_move']}) if fiscalyear_id: result['name'] += ':' + fy_obj.read(cr, uid, [fiscalyear_id], context=context)[0]['code'] return result _defaults = { 'target_move': 'posted', 'fiscalyear': _get_fiscalyear, }
addition-it-solutions/project-all
addons/account/wizard/account_chart.py
Python
agpl-3.0
5,123
""" Specific overrides to the base prod settings to make development easier. """ from os.path import abspath, dirname, join from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import # Don't use S3 in devstack, fall back to filesystem del DEFAULT_FILE_STORAGE MEDIA_ROOT = "/edx/var/edxapp/uploads" DEBUG = True USE_I18N = True TEMPLATE_DEBUG = True SITE_NAME = 'localhost:8000' PLATFORM_NAME = ENV_TOKENS.get('PLATFORM_NAME', 'Devstack') # By default don't use a worker, execute tasks as if they were local functions CELERY_ALWAYS_EAGER = True HTTPS = 'off' ################################ LOGGERS ###################################### # Silence noisy logs import logging LOG_OVERRIDES = [ ('track.contexts', logging.CRITICAL), ('track.middleware', logging.CRITICAL), ('dd.dogapi', logging.CRITICAL), ('django_comment_client.utils', logging.CRITICAL), ] for log_name, log_level in LOG_OVERRIDES: logging.getLogger(log_name).setLevel(log_level) ################################ EMAIL ######################################## EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' FEATURES['ENABLE_INSTRUCTOR_EMAIL'] = True # Enable email for all Studio courses FEATURES['REQUIRE_COURSE_EMAIL_AUTH'] = False # Give all courses email (don't require django-admin perms) ########################## ANALYTICS TESTING ######################## ANALYTICS_SERVER_URL = "http://127.0.0.1:9000/" ANALYTICS_API_KEY = "" # Set this to the dashboard URL in order to display the link from the # dashboard to the Analytics Dashboard. ANALYTICS_DASHBOARD_URL = None ################################ DEBUG TOOLBAR ################################ INSTALLED_APPS += ('debug_toolbar', 'debug_toolbar_mongo') MIDDLEWARE_CLASSES += ( 'django_comment_client.utils.QueryCountDebugMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_PANELS = ( 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar_mongo.panel.MongoDebugPanel', # ProfilingPanel has been intentionally removed for default devstack.py # runtimes for performance reasons. If you wish to re-enable it in your # local development environment, please create a new settings file # that imports and extends devstack.py. ) DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': 'lms.envs.devstack.should_show_debug_toolbar' } def should_show_debug_toolbar(_): return True # We always want the toolbar on devstack regardless of IP, auth, etc. ########################### PIPELINE ################################# # Skip packaging and optimization in development PIPELINE_ENABLED = False STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage' # Revert to the default set of finders as we don't want the production pipeline STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] # Disable JavaScript compression in development PIPELINE_JS_COMPRESSOR = None # Whether to run django-require in debug mode. REQUIRE_DEBUG = DEBUG PIPELINE_SASS_ARGUMENTS = '--debug-info --require {proj_dir}/static/sass/bourbon/lib/bourbon.rb'.format(proj_dir=PROJECT_ROOT) ########################### VERIFIED CERTIFICATES ################################# FEATURES['AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'] = True FEATURES['ENABLE_PAYMENT_FAKE'] = True CC_PROCESSOR_NAME = 'CyberSource2' CC_PROCESSOR = { 'CyberSource2': { "PURCHASE_ENDPOINT": '/shoppingcart/payment_fake/', "SECRET_KEY": 'abcd123', "ACCESS_KEY": 'abcd123', "PROFILE_ID": 'edx', } } ########################### External REST APIs ################################# FEATURES['ENABLE_OAUTH2_PROVIDER'] = True OAUTH_OIDC_ISSUER = 'http://127.0.0.1:8000/oauth2' FEATURES['ENABLE_MOBILE_REST_API'] = True FEATURES['ENABLE_VIDEO_ABSTRACTION_LAYER_API'] = True ########################## SECURITY ####################### FEATURES['ENFORCE_PASSWORD_POLICY'] = False FEATURES['ENABLE_MAX_FAILED_LOGIN_ATTEMPTS'] = False FEATURES['SQUELCH_PII_IN_LOGS'] = False FEATURES['PREVENT_CONCURRENT_LOGINS'] = False FEATURES['ADVANCED_SECURITY'] = False PASSWORD_MIN_LENGTH = None PASSWORD_COMPLEXITY = {} ########################### Milestones ################################# FEATURES['MILESTONES_APP'] = True ########################### Milestones ################################# FEATURES['ORGANIZATIONS_APP'] = True ########################### Entrance Exams ################################# FEATURES['ENTRANCE_EXAMS'] = True ################################ COURSE LICENSES ################################ FEATURES['LICENSING'] = True ########################## Courseware Search ####################### FEATURES['ENABLE_COURSEWARE_SEARCH'] = True SEARCH_ENGINE = "search.elastic.ElasticSearchEngine" ########################## Dashboard Search ####################### FEATURES['ENABLE_DASHBOARD_SEARCH'] = True ########################## Certificates Web/HTML View ####################### FEATURES['CERTIFICATES_HTML_VIEW'] = True ########################## Course Discovery ####################### from django.utils.translation import ugettext as _ LANGUAGE_MAP = {'terms': {lang: display for lang, display in ALL_LANGUAGES}, 'name': _('Language')} COURSE_DISCOVERY_MEANINGS = { 'org': { 'name': _('Organization'), }, 'modes': { 'name': _('Course Type'), 'terms': { 'honor': _('Honor'), 'verified': _('Verified'), }, }, 'language': LANGUAGE_MAP, } FEATURES['ENABLE_COURSE_DISCOVERY'] = True # Setting for overriding default filtering facets for Course discovery # COURSE_DISCOVERY_FILTERS = ["org", "language", "modes"] FEATURES['COURSES_ARE_BROWSEABLE'] = True HOMEPAGE_COURSE_MAX = 9 # Software secure fake page feature flag FEATURES['ENABLE_SOFTWARE_SECURE_FAKE'] = True # Setting for the testing of Software Secure Result Callback VERIFY_STUDENT["SOFTWARE_SECURE"] = { "API_ACCESS_KEY": "BBBBBBBBBBBBBBBBBBBB", "API_SECRET_KEY": "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC", } # Skip enrollment start date filtering SEARCH_SKIP_ENROLLMENT_START_DATE_FILTERING = True ########################## Shopping cart ########################## FEATURES['ENABLE_SHOPPING_CART'] = True FEATURES['STORE_BILLING_INFO'] = True FEATURES['ENABLE_PAID_COURSE_REGISTRATION'] = True FEATURES['ENABLE_COSMETIC_DISPLAY_PRICE'] = True ########################## Third Party Auth ####################### if FEATURES.get('ENABLE_THIRD_PARTY_AUTH') and 'third_party_auth.dummy.DummyBackend' not in AUTHENTICATION_BACKENDS: AUTHENTICATION_BACKENDS = ['third_party_auth.dummy.DummyBackend'] + list(AUTHENTICATION_BACKENDS) ############## ECOMMERCE API CONFIGURATION SETTINGS ############### ECOMMERCE_PUBLIC_URL_ROOT = "http://localhost:8002" ###################### Cross-domain requests ###################### FEATURES['ENABLE_CORS_HEADERS'] = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = () CORS_ORIGIN_ALLOW_ALL = True ##################################################################### # See if the developer has any local overrides. if os.path.isfile(join(dirname(abspath(__file__)), 'private.py')): from .private import * # pylint: disable=import-error,wildcard-import ##################################################################### # Lastly, run any migrations, if needed. MODULESTORE = convert_module_store_setting_if_needed(MODULESTORE) SECRET_KEY = '85920908f28904ed733fe576320db18cabd7b6cd'
ahmadiga/min_edx
lms/envs/devstack.py
Python
agpl-3.0
7,967
#!/usr/bin/python # # Copyright 2014 Microsoft Corporation # # 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 redhatPatching import redhatPatching class centosPatching(redhatPatching): def __init__(self, hutil): super(centosPatching,self).__init__(hutil)
soumyanishan/azure-linux-extensions
OSPatching/patch/centosPatching.py
Python
apache-2.0
770
"""The Energy integration.""" from __future__ import annotations from homeassistant.components import frontend from homeassistant.core import HomeAssistant from homeassistant.helpers import discovery from homeassistant.helpers.typing import ConfigType from . import websocket_api from .const import DOMAIN from .data import async_get_manager async def is_configured(hass: HomeAssistant) -> bool: """Return a boolean to indicate if energy is configured.""" manager = await async_get_manager(hass) if manager.data is None: return False return bool(manager.data != manager.default_preferences()) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up Energy.""" websocket_api.async_setup(hass) frontend.async_register_built_in_panel(hass, DOMAIN, DOMAIN, "mdi:lightning-bolt") hass.async_create_task( discovery.async_load_platform(hass, "sensor", DOMAIN, {}, config) ) hass.data[DOMAIN] = { "cost_sensors": {}, } return True
jawilson/home-assistant
homeassistant/components/energy/__init__.py
Python
apache-2.0
1,029
# Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Reference implementation for health checking in gRPC Python.""" import threading import grpc from grpc_health.v1 import health_pb2 class HealthServicer(health_pb2.HealthServicer): """Servicer handling RPCs for service statuses.""" def __init__(self): self._server_status_lock = threading.Lock() self._server_status = {} def Check(self, request, context): with self._server_status_lock: status = self._server_status.get(request.service) if status is None: context.set_code(grpc.StatusCode.NOT_FOUND) return health_pb2.HealthCheckResponse() else: return health_pb2.HealthCheckResponse(status=status) def set(self, service, status): """Sets the status of a service. Args: service: string, the name of the service. NOTE, '' must be set. status: HealthCheckResponse.status enum value indicating the status of the service """ with self._server_status_lock: self._server_status[service] = status
grani/grpc
src/python/grpcio_health_checking/grpc_health/v1/health.py
Python
bsd-3-clause
2,629
# Copyright (c) 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from absl import app from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait import test_util # Detect if history deletion is enabled or disabled and print the result. # The way to check is: # - visit chrome://history; # - get the first history item; # - check the checkbox. If history deletion is disabled, then the check # box has attribute 'disabled'; # TODO(crbug.com/986444): move those helper methods into test_util.py once def getElementFromShadowRoot(driver, element, selector): if element is None: return None else: return driver.execute_script( "return arguments[0].shadowRoot.querySelector(arguments[1])", element, selector) def main(argv): driver = test_util.create_chrome_webdriver() try: driver.get('http://www.google.com') driver.get('chrome://history') # wait for page to be loaded wait = WebDriverWait(driver, 10) wait.until( expected_conditions.visibility_of_element_located((By.TAG_NAME, 'history-app'))) history_app = driver.find_element_by_css_selector("history-app") histroy_list = getElementFromShadowRoot(driver, history_app, "history-list") # get the checkbox of the first history item histroy_item = getElementFromShadowRoot(driver, histroy_list, 'history-item') checkbox = getElementFromShadowRoot(driver, histroy_item, '#main-container cr-checkbox') disabled = checkbox.get_attribute('disabled') if disabled == 'true': print('DISABLED') else: print('ENABLED') finally: driver.quit() if __name__ == '__main__': app.run(main)
ric2b/Vivaldi-browser
chromium/chrome/test/enterprise/e2e/policy/allow_deleting_browser_history/allow_deleting_browser_history_webdriver_test.py
Python
bsd-3-clause
1,991
import unittest, StringIO, robotparser from test import test_support from urllib2 import urlopen, HTTPError class RobotTestCase(unittest.TestCase): def __init__(self, index, parser, url, good, agent): unittest.TestCase.__init__(self) if good: self.str = "RobotTest(%d, good, %s)" % (index, url) else: self.str = "RobotTest(%d, bad, %s)" % (index, url) self.parser = parser self.url = url self.good = good self.agent = agent def runTest(self): if isinstance(self.url, tuple): agent, url = self.url else: url = self.url agent = self.agent if self.good: self.assertTrue(self.parser.can_fetch(agent, url)) else: self.assertFalse(self.parser.can_fetch(agent, url)) def __str__(self): return self.str tests = unittest.TestSuite() def RobotTest(index, robots_txt, good_urls, bad_urls, agent="test_robotparser"): lines = StringIO.StringIO(robots_txt).readlines() parser = robotparser.RobotFileParser() parser.parse(lines) for url in good_urls: tests.addTest(RobotTestCase(index, parser, url, 1, agent)) for url in bad_urls: tests.addTest(RobotTestCase(index, parser, url, 0, agent)) # Examples from http://www.robotstxt.org/wc/norobots.html (fetched 2002) # 1. doc = """ User-agent: * Disallow: /cyberworld/map/ # This is an infinite virtual URL space Disallow: /tmp/ # these will soon disappear Disallow: /foo.html """ good = ['/','/test.html'] bad = ['/cyberworld/map/index.html','/tmp/xxx','/foo.html'] RobotTest(1, doc, good, bad) # 2. doc = """ # robots.txt for http://www.example.com/ User-agent: * Disallow: /cyberworld/map/ # This is an infinite virtual URL space # Cybermapper knows where to go. User-agent: cybermapper Disallow: """ good = ['/','/test.html',('cybermapper','/cyberworld/map/index.html')] bad = ['/cyberworld/map/index.html'] RobotTest(2, doc, good, bad) # 3. doc = """ # go away User-agent: * Disallow: / """ good = [] bad = ['/cyberworld/map/index.html','/','/tmp/'] RobotTest(3, doc, good, bad) # Examples from http://www.robotstxt.org/wc/norobots-rfc.html (fetched 2002) # 4. doc = """ User-agent: figtree Disallow: /tmp Disallow: /a%3cd.html Disallow: /a%2fb.html Disallow: /%7ejoe/index.html """ good = [] # XFAIL '/a/b.html' bad = ['/tmp','/tmp.html','/tmp/a.html', '/a%3cd.html','/a%3Cd.html','/a%2fb.html', '/~joe/index.html' ] RobotTest(4, doc, good, bad, 'figtree') RobotTest(5, doc, good, bad, 'FigTree Robot libwww-perl/5.04') # 6. doc = """ User-agent: * Disallow: /tmp/ Disallow: /a%3Cd.html Disallow: /a/b.html Disallow: /%7ejoe/index.html """ good = ['/tmp',] # XFAIL: '/a%2fb.html' bad = ['/tmp/','/tmp/a.html', '/a%3cd.html','/a%3Cd.html',"/a/b.html", '/%7Ejoe/index.html'] RobotTest(6, doc, good, bad) # From bug report #523041 # 7. doc = """ User-Agent: * Disallow: /. """ good = ['/foo.html'] bad = [] # Bug report says "/" should be denied, but that is not in the RFC RobotTest(7, doc, good, bad) # From Google: http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=40364 # 8. doc = """ User-agent: Googlebot Allow: /folder1/myfile.html Disallow: /folder1/ """ good = ['/folder1/myfile.html'] bad = ['/folder1/anotherfile.html'] RobotTest(8, doc, good, bad, agent="Googlebot") # 9. This file is incorrect because "Googlebot" is a substring of # "Googlebot-Mobile", so test 10 works just like test 9. doc = """ User-agent: Googlebot Disallow: / User-agent: Googlebot-Mobile Allow: / """ good = [] bad = ['/something.jpg'] RobotTest(9, doc, good, bad, agent="Googlebot") good = [] bad = ['/something.jpg'] RobotTest(10, doc, good, bad, agent="Googlebot-Mobile") # 11. Get the order correct. doc = """ User-agent: Googlebot-Mobile Allow: / User-agent: Googlebot Disallow: / """ good = [] bad = ['/something.jpg'] RobotTest(11, doc, good, bad, agent="Googlebot") good = ['/something.jpg'] bad = [] RobotTest(12, doc, good, bad, agent="Googlebot-Mobile") # 13. Google also got the order wrong in #8. You need to specify the # URLs from more specific to more general. doc = """ User-agent: Googlebot Allow: /folder1/myfile.html Disallow: /folder1/ """ good = ['/folder1/myfile.html'] bad = ['/folder1/anotherfile.html'] RobotTest(13, doc, good, bad, agent="googlebot") # 14. For issue #6325 (query string support) doc = """ User-agent: * Disallow: /some/path?name=value """ good = ['/some/path'] bad = ['/some/path?name=value'] RobotTest(14, doc, good, bad) # 15. For issue #4108 (obey first * entry) doc = """ User-agent: * Disallow: /some/path User-agent: * Disallow: /another/path """ good = ['/another/path'] bad = ['/some/path'] RobotTest(15, doc, good, bad) # 16. Empty query (issue #17403). Normalizing the url first. doc = """ User-agent: * Allow: /some/path? Disallow: /another/path? """ good = ['/some/path?'] bad = ['/another/path?'] RobotTest(16, doc, good, bad) class NetworkTestCase(unittest.TestCase): def testPasswordProtectedSite(self): test_support.requires('network') with test_support.transient_internet('mueblesmoraleda.com'): url = 'http://mueblesmoraleda.com' robots_url = url + "/robots.txt" # First check the URL is usable for our purposes, since the # test site is a bit flaky. try: urlopen(robots_url) except HTTPError as e: if e.code not in {401, 403}: self.skipTest( "%r should return a 401 or 403 HTTP error, not %r" % (robots_url, e.code)) else: self.skipTest( "%r should return a 401 or 403 HTTP error, not succeed" % (robots_url)) parser = robotparser.RobotFileParser() parser.set_url(url) try: parser.read() except IOError: self.skipTest('%s is unavailable' % url) self.assertEqual(parser.can_fetch("*", robots_url), False) def testPythonOrg(self): test_support.requires('network') with test_support.transient_internet('www.python.org'): parser = robotparser.RobotFileParser( "http://www.python.org/robots.txt") parser.read() self.assertTrue( parser.can_fetch("*", "http://www.python.org/robots.txt")) def test_main(): test_support.run_unittest(tests) test_support.run_unittest(NetworkTestCase) if __name__=='__main__': test_support.verbose = 1 test_main()
ianyh/heroku-buildpack-python-opencv
vendor/.heroku/lib/python2.7/test/test_robotparser.py
Python
mit
6,753
"""SCons.Tool.gfortran Tool-specific initialization for gfortran, the GNU Fortran 95/Fortran 2003 compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # 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. # __revision__ = "src/engine/SCons/Tool/gfortran.py 2014/09/27 12:51:43 garyo" import SCons.Util import fortran def generate(env): """Add Builders and construction variables for gfortran to an Environment.""" fortran.generate(env) for dialect in ['F77', 'F90', 'FORTRAN', 'F95', 'F03']: env['%s' % dialect] = 'gfortran' env['SH%s' % dialect] = '$%s' % dialect if env['PLATFORM'] in ['cygwin', 'win32']: env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS' % dialect) else: env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect) env['INC%sPREFIX' % dialect] = "-I" env['INC%sSUFFIX' % dialect] = "" def exists(env): return env.Detect('gfortran') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
stonekyx/binary
vendor/scons-local-2.3.4/SCons/Tool/gfortran.py
Python
gpl-3.0
2,256
import os.path, string, posix, pyvms # # IDIR = ['swig_root:[source.swig]', 'swig_root:[source.doh.include]', 'swig_root:[source.include]', 'swig_root:[source.preprocessor]'] def new_file(fg, dirname): global IDIR fn = 'swig_root:[vms.scripts]compil_' + os.path.basename(dirname) + '.com' print >> fg, '$ @' + fn f = open(fn, 'w') print >> f, '$!' print >> f, '$! Generated by genbuild.py' print >> f, '$!' print >> f, '$ libname = "swig_root:[vms.o_alpha]swig.olb"' print >> f, '$' print >> f, '$ set default', pyvms.crtl_to_vms(dirname)[0][0] print >> f, '$' print >> f, "$ idir := ", IDIR[0] for i in range(1, len(IDIR)): print >> f, '$ idir = idir + ",' + IDIR[i] + '"' print >> f, '$' print >> f, "$ iflags = \"/include=(''idir', sys$disk:[])\"" print >> f, '$ oflags = \"/object=swig_root:[vms.o_alpha]' print >> f, "$ cflags = \"''oflags'''iflags'''dflags'\"" print >> f, "$ cxxflags = \"''oflags'''iflags'''dflags'\"" print >> f, '$' return f def end_file(f): print >>f,"""$ exit $! $! $MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES $ V = 'F$Verify(0) $! P1 = What we are trying to make $! P2 = Command to make it $! P3 = Source file $! P4 - P8 What it depends on $ $ modname = f$parse(p3,,,"name") $ set noon $ set message/nofacility/noident/noseverity/notext $ libr/lis=swig_root:[vms]swiglib.tmp/full/width=132/only='modname' 'libname' $ set message/facility/ident/severity/text $ on error then exit $ open/read swigtmp swig_root:[vms]swiglib.tmp $! skip header $ read swigtmp r $ read swigtmp r $ read swigtmp r $ read swigtmp r $ read swigtmp r $ read swigtmp r $ read swigtmp r $ read swigtmp r $ read swigtmp r $! $ $ read/end=module_not_found swigtmp r $ modfound = 1 $ Time = f$cvtime(f$extract(49, 20, r)) $ goto end_search_module $ module_not_found: $ modfound = 0 $ $ end_search_module: $ close swigtmp $ delete swig_root:[vms]swiglib.tmp;* $ $ if modfound .eq. 0 then $ goto Makeit $ $! Time = F$CvTime(F$File(P1,"RDT")) $arg=3 $Loop: $ Argument = P'arg $ If Argument .Eqs. "" Then Goto Exit $ El=0 $Loop2: $ File = F$Element(El," ",Argument) $ If File .Eqs. " " Then Goto Endl $ AFile = "" $Loop3: $ OFile = AFile $ AFile = F$Search(File) $ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl $ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit $ Goto Loop3 $NextEL: $ El = El + 1 $ Goto Loop2 $EndL: $ arg=arg+1 $ If arg .Le. 8 Then Goto Loop $ Goto Exit $ $Makeit: $ VV=F$VERIFY(1) $ 'P2' 'P3' $ VV='F$Verify(VV) $Exit: $ If V Then Set Verify $ENDSUBROUTINE""" def listRep(args, dirname, filenames): fg = args[0] first = 1 for fn in filenames: if fn[-2:] == '.c': if first: first = 0 fc = new_file(fg, dirname) cstr = "\"cc ''cflags'\" " line = "$ call make swig_root:[vms.o_alpha]" line += fn[:-1] + 'obj -' print >> fc, line line = "\t" + cstr + fn print >> fc, line elif fn[-4:] == '.cxx': if first: first = 0 fc = new_file(fg, dirname) cstr = "\"cxx ''cxxflags'\" " line = "$ call make swig_root:[vms.o_alpha]" line += fn[:-3] + 'obj -' print >> fc, line line = "\t" + cstr + fn print >> fc, line if first == 0: end_file(fc) fc.close() # def genbuild(f, dir): os.path.walk(dir, listRep, (f,)) cmd = 'set default swig_root:[vms]' # f = open('swig_root:[vms.scripts]build_all.com','w') print >> f, '$!' print >> f, '$! Generated by genbuild.py' print >> f, '$!' print >> f, '$ set default swig_root:[vms]' print >> f, '$' print >> f, '$ @swig_root:[vms]build_init' # genbuild(f, '/swig_root/source') print >> f, '$' print >> f, '$ set default swig_root:[vms]' print >> f, '$' print >> f, '$ @swig_root:[vms]build_end' f.close
DGA-MI-SSI/YaCo
deps/swig-3.0.7/vms/genbuild.py
Python
gpl-3.0
4,052
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Plugin's Base Class """ import sys import cli from cli.docopt import docopt PLUGIN_NAME = "base-plugin" PLUGIN_CLASS = "PluginBase" VERSION = "Mesos Plugin Base 1.0" SHORT_HELP = "This is the base plugin from which all other plugins inherit." USAGE = \ """ {short_help} Usage: mesos {plugin} (-h | --help) mesos {plugin} --version mesos {plugin} <command> (-h | --help) mesos {plugin} [options] <command> [<args>...] Options: -h --help Show this screen. --version Show version info. Commands: {commands} """ SUBCOMMAND_USAGE = \ """{short_help} Usage: mesos {plugin} {command} (-h | --help) mesos {plugin} {command} --version mesos {plugin} {command} [options] {arguments} Options: {flags} Description: {long_help} """ class PluginBase(): """ Base class from which all CLI plugins should inherit. """ # pylint: disable=too-few-public-methods COMMANDS = {} def __setup__(self, command, argv): pass def __module_reference__(self): return sys.modules[self.__module__] def __init__(self, settings, config): # pylint: disable=invalid-name self.PLUGIN_NAME = PLUGIN_NAME self.PLUGIN_CLASS = PLUGIN_CLASS self.VERSION = VERSION self.SHORT_HELP = SHORT_HELP self.USAGE = USAGE module = self.__module_reference__() if hasattr(module, "PLUGIN_NAME"): self.PLUGIN_NAME = getattr(module, "PLUGIN_NAME") if hasattr(module, "PLUGIN_CLASS"): self.PLUGIN_CLASS = getattr(module, "PLUGIN_CLASS") if hasattr(module, "VERSION"): self.VERSION = getattr(module, "VERSION") if hasattr(module, "SHORT_HELP"): self.SHORT_HELP = getattr(module, "SHORT_HELP") if hasattr(module, "USAGE"): self.USAGE = getattr(module, "USAGE") self.settings = settings self.config = config def __autocomplete__(self, command, current_word, argv): # pylint: disable=unused-variable,unused-argument, # attribute-defined-outside-init return ("default", []) def __autocomplete_base__(self, current_word, argv): option = "default" # <command> comp_words = list(self.COMMANDS.keys()) comp_words = cli.util.completions(comp_words, current_word, argv) if comp_words is not None: return (option, comp_words) # <args>... comp_words = self.__autocomplete__(argv[0], current_word, argv[1:]) # In general, we expect a tuple to be returned from __autocomplete__, # with the first element being a valid autocomplete option, and the # second being a list of completion words. However, in the common # case we usually use the default option, so it's OK for a plugin to # just return a list. We will add the "default" option for them. if isinstance(comp_words, tuple): option, comp_words = comp_words return (option, comp_words) def main(self, argv): """ Main method takes argument from top level mesos and parses them to call the appropriate method. """ command_strings = cli.util.format_commands_help(self.COMMANDS) usage = self.USAGE.format( plugin=self.PLUGIN_NAME, short_help=self.SHORT_HELP, commands=command_strings) arguments = docopt( usage, argv=argv, version=self.VERSION, program="mesos " + self.PLUGIN_NAME, options_first=True) cmd = arguments["<command>"] argv = arguments["<args>"] if cmd in self.COMMANDS.keys(): if "external" not in self.COMMANDS[cmd]: argument_format, short_help, long_help, flag_format = \ cli.util.format_subcommands_help(self.COMMANDS[cmd]) usage = SUBCOMMAND_USAGE.format( plugin=self.PLUGIN_NAME, command=cmd, arguments=argument_format, flags=flag_format, short_help=short_help, long_help=long_help) arguments = docopt( usage, argv=argv, program="mesos " + self.PLUGIN_NAME + " " + cmd, version=self.VERSION, options_first=True) if "alias" in self.COMMANDS[cmd]: cmd = self.COMMANDS[cmd]["alias"] self.__setup__(cmd, argv) return getattr(self, cmd.replace("-", "_"))(arguments) return self.main(["--help"])
reneploetz/mesos
src/python/cli_new/lib/cli/plugins/base.py
Python
apache-2.0
5,461
# Copyright (c) 2012-2016 Seafile Ltd. from django.contrib import admin # Register your models here.
miurahr/seahub
seahub/role_permissions/admin.py
Python
apache-2.0
102
# Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import threading import time import unittest from grpc import _grpcio_metadata from grpc._adapter import _types from grpc._adapter import _low from tests.unit import test_common def wait_for_events(completion_queues, deadline): """ Args: completion_queues: list of completion queues to wait for events on deadline: absolute deadline to wait until Returns: a sequence of events of length len(completion_queues). """ results = [None] * len(completion_queues) lock = threading.Lock() threads = [] def set_ith_result(i, completion_queue): result = completion_queue.next(deadline) with lock: results[i] = result for i, completion_queue in enumerate(completion_queues): thread = threading.Thread(target=set_ith_result, args=[i, completion_queue]) thread.start() threads.append(thread) for thread in threads: thread.join() return results class InsecureServerInsecureClient(unittest.TestCase): def setUp(self): self.server_completion_queue = _low.CompletionQueue() self.server = _low.Server(self.server_completion_queue, []) self.port = self.server.add_http2_port('[::]:0') self.client_completion_queue = _low.CompletionQueue() self.client_channel = _low.Channel('localhost:%d'%self.port, []) self.server.start() def tearDown(self): self.server.shutdown() del self.client_channel self.client_completion_queue.shutdown() while (self.client_completion_queue.next(float('+inf')).type != _types.EventType.QUEUE_SHUTDOWN): pass self.server_completion_queue.shutdown() while (self.server_completion_queue.next(float('+inf')).type != _types.EventType.QUEUE_SHUTDOWN): pass del self.client_completion_queue del self.server_completion_queue del self.server def testEcho(self): deadline = time.time() + 5 event_time_tolerance = 2 deadline_tolerance = 0.25 client_metadata_ascii_key = 'key' client_metadata_ascii_value = 'val' client_metadata_bin_key = 'key-bin' client_metadata_bin_value = b'\0'*1000 server_initial_metadata_key = 'init_me_me_me' server_initial_metadata_value = 'whodawha?' server_trailing_metadata_key = 'california_is_in_a_drought' server_trailing_metadata_value = 'zomg it is' server_status_code = _types.StatusCode.OK server_status_details = 'our work is never over' request = 'blarghaflargh' response = 'his name is robert paulson' method = 'twinkies' host = 'hostess' server_request_tag = object() request_call_result = self.server.request_call(self.server_completion_queue, server_request_tag) self.assertEqual(_types.CallError.OK, request_call_result) client_call_tag = object() client_call = self.client_channel.create_call( self.client_completion_queue, method, host, deadline) client_initial_metadata = [ (client_metadata_ascii_key, client_metadata_ascii_value), (client_metadata_bin_key, client_metadata_bin_value) ] client_start_batch_result = client_call.start_batch([ _types.OpArgs.send_initial_metadata(client_initial_metadata), _types.OpArgs.send_message(request, 0), _types.OpArgs.send_close_from_client(), _types.OpArgs.recv_initial_metadata(), _types.OpArgs.recv_message(), _types.OpArgs.recv_status_on_client() ], client_call_tag) self.assertEqual(_types.CallError.OK, client_start_batch_result) client_no_event, request_event, = wait_for_events( [self.client_completion_queue, self.server_completion_queue], time.time() + event_time_tolerance) self.assertEqual(client_no_event, None) self.assertEqual(_types.EventType.OP_COMPLETE, request_event.type) self.assertIsInstance(request_event.call, _low.Call) self.assertIs(server_request_tag, request_event.tag) self.assertEqual(1, len(request_event.results)) received_initial_metadata = request_event.results[0].initial_metadata # Check that our metadata were transmitted self.assertTrue(test_common.metadata_transmitted(client_initial_metadata, received_initial_metadata)) # Check that Python's user agent string is a part of the full user agent # string received_initial_metadata_dict = dict(received_initial_metadata) self.assertIn('user-agent', received_initial_metadata_dict) self.assertIn('Python-gRPC-{}'.format(_grpcio_metadata.__version__), received_initial_metadata_dict['user-agent']) self.assertEqual(method, request_event.call_details.method) self.assertEqual(host, request_event.call_details.host) self.assertLess(abs(deadline - request_event.call_details.deadline), deadline_tolerance) # Check that the channel is connected, and that both it and the call have # the proper target and peer; do this after the first flurry of messages to # avoid the possibility that connection was delayed by the core until the # first message was sent. self.assertEqual(_types.ConnectivityState.READY, self.client_channel.check_connectivity_state(False)) self.assertIsNotNone(self.client_channel.target()) self.assertIsNotNone(client_call.peer()) server_call_tag = object() server_call = request_event.call server_initial_metadata = [ (server_initial_metadata_key, server_initial_metadata_value) ] server_trailing_metadata = [ (server_trailing_metadata_key, server_trailing_metadata_value) ] server_start_batch_result = server_call.start_batch([ _types.OpArgs.send_initial_metadata(server_initial_metadata), _types.OpArgs.recv_message(), _types.OpArgs.send_message(response, 0), _types.OpArgs.recv_close_on_server(), _types.OpArgs.send_status_from_server( server_trailing_metadata, server_status_code, server_status_details) ], server_call_tag) self.assertEqual(_types.CallError.OK, server_start_batch_result) client_event, server_event, = wait_for_events( [self.client_completion_queue, self.server_completion_queue], time.time() + event_time_tolerance) self.assertEqual(6, len(client_event.results)) found_client_op_types = set() for client_result in client_event.results: # we expect each op type to be unique self.assertNotIn(client_result.type, found_client_op_types) found_client_op_types.add(client_result.type) if client_result.type == _types.OpType.RECV_INITIAL_METADATA: self.assertTrue( test_common.metadata_transmitted(server_initial_metadata, client_result.initial_metadata)) elif client_result.type == _types.OpType.RECV_MESSAGE: self.assertEqual(response, client_result.message) elif client_result.type == _types.OpType.RECV_STATUS_ON_CLIENT: self.assertTrue( test_common.metadata_transmitted(server_trailing_metadata, client_result.trailing_metadata)) self.assertEqual(server_status_details, client_result.status.details) self.assertEqual(server_status_code, client_result.status.code) self.assertEqual(set([ _types.OpType.SEND_INITIAL_METADATA, _types.OpType.SEND_MESSAGE, _types.OpType.SEND_CLOSE_FROM_CLIENT, _types.OpType.RECV_INITIAL_METADATA, _types.OpType.RECV_MESSAGE, _types.OpType.RECV_STATUS_ON_CLIENT ]), found_client_op_types) self.assertEqual(5, len(server_event.results)) found_server_op_types = set() for server_result in server_event.results: self.assertNotIn(client_result.type, found_server_op_types) found_server_op_types.add(server_result.type) if server_result.type == _types.OpType.RECV_MESSAGE: self.assertEqual(request, server_result.message) elif server_result.type == _types.OpType.RECV_CLOSE_ON_SERVER: self.assertFalse(server_result.cancelled) self.assertEqual(set([ _types.OpType.SEND_INITIAL_METADATA, _types.OpType.RECV_MESSAGE, _types.OpType.SEND_MESSAGE, _types.OpType.RECV_CLOSE_ON_SERVER, _types.OpType.SEND_STATUS_FROM_SERVER ]), found_server_op_types) del client_call del server_call class HangingServerShutdown(unittest.TestCase): def setUp(self): self.server_completion_queue = _low.CompletionQueue() self.server = _low.Server(self.server_completion_queue, []) self.port = self.server.add_http2_port('[::]:0') self.client_completion_queue = _low.CompletionQueue() self.client_channel = _low.Channel('localhost:%d'%self.port, []) self.server.start() def tearDown(self): self.server.shutdown() del self.client_channel self.client_completion_queue.shutdown() self.server_completion_queue.shutdown() while True: client_event, server_event = wait_for_events( [self.client_completion_queue, self.server_completion_queue], float("+inf")) if (client_event.type == _types.EventType.QUEUE_SHUTDOWN and server_event.type == _types.EventType.QUEUE_SHUTDOWN): break del self.client_completion_queue del self.server_completion_queue del self.server def testHangingServerCall(self): deadline = time.time() + 5 deadline_tolerance = 0.25 event_time_tolerance = 2 cancel_all_calls_time_tolerance = 0.5 request = 'blarghaflargh' method = 'twinkies' host = 'hostess' server_request_tag = object() request_call_result = self.server.request_call(self.server_completion_queue, server_request_tag) client_call_tag = object() client_call = self.client_channel.create_call(self.client_completion_queue, method, host, deadline) client_start_batch_result = client_call.start_batch([ _types.OpArgs.send_initial_metadata([]), _types.OpArgs.send_message(request, 0), _types.OpArgs.send_close_from_client(), _types.OpArgs.recv_initial_metadata(), _types.OpArgs.recv_message(), _types.OpArgs.recv_status_on_client() ], client_call_tag) client_no_event, request_event, = wait_for_events( [self.client_completion_queue, self.server_completion_queue], time.time() + event_time_tolerance) # Now try to shutdown the server and expect that we see server shutdown # almost immediately after calling cancel_all_calls. # First attempt to cancel all calls before shutting down, and expect # our state machine to catch the erroneous API use. with self.assertRaises(RuntimeError): self.server.cancel_all_calls() shutdown_tag = object() self.server.shutdown(shutdown_tag) pre_cancel_timestamp = time.time() self.server.cancel_all_calls() finish_shutdown_timestamp = None client_call_event, server_shutdown_event = wait_for_events( [self.client_completion_queue, self.server_completion_queue], time.time() + event_time_tolerance) self.assertIs(shutdown_tag, server_shutdown_event.tag) self.assertGreater(pre_cancel_timestamp + cancel_all_calls_time_tolerance, time.time()) del client_call if __name__ == '__main__': unittest.main(verbosity=2)
shishaochen/TensorFlow-0.8-Win
third_party/grpc/src/python/grpcio/tests/unit/_adapter/_low_test.py
Python
apache-2.0
13,085
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import os import platform import shutil import subprocess import sys import tempfile import unittest import zipfile from telemetry.util import cloud_storage from telemetry.util import find_dependencies class FindDependenciesTest(unittest.TestCase): @unittest.skipUnless( cloud_storage.SupportsProdaccess( os.path.realpath(cloud_storage.FindGsutil())), 'Could not find a depot_tools installation with gsutil.') def testGsutil(self): parser = optparse.OptionParser() find_dependencies.FindDependenciesCommand.AddCommandLineArgs(parser) options, _ = parser.parse_args([]) try: temp_dir = tempfile.mkdtemp() zip_path = os.path.join(temp_dir, 'gsutil.zip') options.zip = zip_path find_dependencies.ZipDependencies([], set(), options) if platform.system() == 'Windows': with zipfile.ZipFile(zip_path, 'r') as zip_file: zip_file.extractall(temp_dir) else: # Use unzip instead of Python zipfile to preserve file permissions. with open(os.devnull, 'w') as dev_null: subprocess.call(['unzip', zip_path], cwd=temp_dir, stdout=dev_null) third_party_path = os.path.join(temp_dir, 'telemetry', 'src', 'tools', 'telemetry', 'third_party') # __init__.py is in Chromium src, but we didn't include any repo files. open(os.path.join(third_party_path, '__init__.py'), 'a').close() gsutil_path = os.path.join(third_party_path, 'gsutil', 'gsutil') self.assertTrue(os.access(gsutil_path, os.X_OK)) with open(os.devnull, 'w') as dev_null: # gsutil with no args should print usage and exit with exit code 0. gsutil_command = [sys.executable, gsutil_path] self.assertEqual(subprocess.call(gsutil_command, stdout=dev_null), 0) # gsutil config should wait for the user and not exit with exit code 1. #gsutil_command = [sys.executable, gsutil_path, 'config', # '-o', os.path.join(temp_dir, 'config_file')] #gsutil_process = subprocess.Popen(gsutil_command, stdout=dev_null) #try: # util.WaitFor(gsutil_process.poll, timeout=0.5) # self.assertEqual(gsutil_process.returncode, 0, # msg='gsutil config failed.') #except exceptions.TimeoutException: # gsutil_process.terminate() # gsutil_process.wait() finally: shutil.rmtree(temp_dir)
guorendong/iridium-browser-ubuntu
tools/telemetry/telemetry/util/find_dependencies_unittest.py
Python
bsd-3-clause
2,648
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from .code_generator_info import CodeGeneratorInfo from .composition_parts import WithCodeGeneratorInfo from .composition_parts import WithComponent from .composition_parts import WithDebugInfo from .composition_parts import WithIdentifier from .ir_map import IRMap from .make_copy import make_copy class Typedef(WithIdentifier, WithCodeGeneratorInfo, WithComponent, WithDebugInfo): """https://webidl.spec.whatwg.org/#idl-typedefs""" class IR(IRMap.IR, WithCodeGeneratorInfo, WithComponent, WithDebugInfo): def __init__(self, identifier, idl_type, code_generator_info=None, component=None, debug_info=None): IRMap.IR.__init__( self, identifier=identifier, kind=IRMap.IR.Kind.TYPEDEF) WithCodeGeneratorInfo.__init__(self, code_generator_info) WithComponent.__init__(self, component) WithDebugInfo.__init__(self, debug_info) self.idl_type = idl_type def __init__(self, ir): assert isinstance(ir, Typedef.IR) ir = make_copy(ir) WithIdentifier.__init__(self, ir) WithCodeGeneratorInfo.__init__(self, ir, readonly=True) WithComponent.__init__(self, ir, readonly=True) WithDebugInfo.__init__(self, ir) self._idl_type = ir.idl_type @property def idl_type(self): """Returns the typedef'ed type.""" return self._idl_type
chromium/chromium
third_party/blink/renderer/bindings/scripts/web_idl/typedef.py
Python
bsd-3-clause
1,678
import json from django.conf import settings from django.contrib.messages.storage.base import BaseStorage, Message from django.http import SimpleCookie from django.utils.crypto import salted_hmac, constant_time_compare from django.utils.safestring import SafeData, mark_safe from django.utils import six class MessageEncoder(json.JSONEncoder): """ Compactly serializes instances of the ``Message`` class as JSON. """ message_key = '__json_message' def default(self, obj): if isinstance(obj, Message): # Using 0/1 here instead of False/True to produce more compact json is_safedata = 1 if isinstance(obj.message, SafeData) else 0 message = [self.message_key, is_safedata, obj.level, obj.message] if obj.extra_tags: message.append(obj.extra_tags) return message return super(MessageEncoder, self).default(obj) class MessageDecoder(json.JSONDecoder): """ Decodes JSON that includes serialized ``Message`` instances. """ def process_messages(self, obj): if isinstance(obj, list) and obj: if obj[0] == MessageEncoder.message_key: if len(obj) == 3: # Compatibility with previously-encoded messages return Message(*obj[1:]) if obj[1]: obj[3] = mark_safe(obj[3]) return Message(*obj[2:]) return [self.process_messages(item) for item in obj] if isinstance(obj, dict): return {key: self.process_messages(value) for key, value in six.iteritems(obj)} return obj def decode(self, s, **kwargs): decoded = super(MessageDecoder, self).decode(s, **kwargs) return self.process_messages(decoded) class CookieStorage(BaseStorage): """ Stores messages in a cookie. """ cookie_name = 'messages' # uwsgi's default configuration enforces a maximum size of 4kb for all the # HTTP headers. In order to leave some room for other cookies and headers, # restrict the session cookie to 1/2 of 4kb. See #18781. max_cookie_size = 2048 not_finished = '__messagesnotfinished__' def _get(self, *args, **kwargs): """ Retrieves a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage. """ data = self.request.COOKIES.get(self.cookie_name) messages = self._decode(data) all_retrieved = not (messages and messages[-1] == self.not_finished) if messages and not all_retrieved: # remove the sentinel value messages.pop() return messages, all_retrieved def _update_cookie(self, encoded_data, response): """ Either sets the cookie with the encoded data if there is any data to store, or deletes the cookie. """ if encoded_data: response.set_cookie(self.cookie_name, encoded_data, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None) else: response.delete_cookie(self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN) def _store(self, messages, response, remove_oldest=True, *args, **kwargs): """ Stores the messages to a cookie, returning a list of any messages which could not be stored. If the encoded data is larger than ``max_cookie_size``, removes messages until the data fits (these are the messages which are returned), and add the not_finished sentinel value to indicate as much. """ unstored_messages = [] encoded_data = self._encode(messages) if self.max_cookie_size: # data is going to be stored eventually by SimpleCookie, which # adds its own overhead, which we must account for. cookie = SimpleCookie() # create outside the loop def stored_length(val): return len(cookie.value_encode(val)[1]) while encoded_data and stored_length(encoded_data) > self.max_cookie_size: if remove_oldest: unstored_messages.append(messages.pop(0)) else: unstored_messages.insert(0, messages.pop()) encoded_data = self._encode(messages + [self.not_finished], encode_empty=unstored_messages) self._update_cookie(encoded_data, response) return unstored_messages def _hash(self, value): """ Creates an HMAC/SHA1 hash based on the value and the project setting's SECRET_KEY, modified to make it unique for the present purpose. """ key_salt = 'django.contrib.messages' return salted_hmac(key_salt, value).hexdigest() def _encode(self, messages, encode_empty=False): """ Returns an encoded version of the messages list which can be stored as plain text. Since the data will be retrieved from the client-side, the encoded data also contains a hash to ensure that the data was not tampered with. """ if messages or encode_empty: encoder = MessageEncoder(separators=(',', ':')) value = encoder.encode(messages) return '%s$%s' % (self._hash(value), value) def _decode(self, data): """ Safely decodes an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, ``None`` is returned. """ if not data: return None bits = data.split('$', 1) if len(bits) == 2: hash, value = bits if constant_time_compare(hash, self._hash(value)): try: # If we get here (and the JSON decode works), everything is # good. In any other case, drop back and return None. return json.loads(value, cls=MessageDecoder) except ValueError: pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None
doismellburning/django
django/contrib/messages/storage/cookie.py
Python
bsd-3-clause
6,545