file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
Line.ts
import { Attribute, Class } from '../decorators'; import { Element } from '../models'; import { Point } from './Point'; @Class('Line', Element) export class Line extends Element { private _from = new Point(); private _to = new Point(); @Attribute({ type: Point }) get from(): Point { return this._from; } set
(value: Point) { this._from = value; } @Attribute({ type: Point }) get to(): Point { return this._to; } set to(value: Point) { this._to = value; } get dx(): number { return this._to.x - this._from.x; } get x1(): number { return this._from.x; } get y1(): number { return this._from.y; } get x2(): number { return this._to.x; } get y2(): number { return this._to.y; } get dy(): number { return this._to.y - this._from.y; } get angle(): number { return Math.atan2(this.dy, this.dx); } get length(): number { return Math.hypot(this.dx, this.dy); } constructor(x1?: number, y1?: number, x2?: number, y2?: number) { super(); if (typeof x1 === 'number' && typeof y1 === 'number' && typeof x2 === 'number' && typeof y2 === 'number') { this._from = new Point(x1, y1); this._to = new Point(x2, y2); } } static fromCoordinates({ x1, y1, x2, y2 }: { x1: number, y1: number, x2: number, y2: number }): Line { const result = new Line(); result.from.x = x1; result.from.y = y1; result.to.x = x2; result.to.y = y2; return result; } static fromTwoPoints(p1: Point, p2: Point): Line { const result = new Line(); result.from = p1; result.to = p2; return result; } /** * Returns the line's coordinates */ getCoordinates(): { x1: number, y1: number, x2: number, y2: number } { const [x1, y1] = this._from.getTuple(); const [x2, y2] = this._to.getTuple(); return { x1, y1, x2, y2 }; } /** * Calculates the distance if a point to this line */ calculateDistanceToPoint(point: Point): number { const { length, x1, y1, x2, y2, dx, dy } = this; if (Math.hypot(point.x - x1, point.y - y1) > length || Math.hypot(point.x - x2, point.y - y2) > length) return Infinity; return Math.abs(dy * point.x - dx * point.y + x2 * y1 - y2 * x1) / length; } /** * Calculates a point on the line. * Offset 0 is the starting point, offset 1 is the ending point. * * @param offset * @param inPixels If true, the offset is given in pixels * @returns a new point instance */ calculatePointBetween(offset: number, inPixels: boolean = false): Point { const { _from, dx, dy } = this; if (inPixels) offset /= this.length; return new Point(_from.x + dx * offset, _from.y + dy * offset); } }
from
identifier_name
views.py
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.route('/register/', methods=['GET', 'POST']) def register():
@app.route('/add/<modelname>/', methods=['GET', 'POST']) def add(modelname): kwargs = listAndEdit(modelname) return render_template('editpage.html', **kwargs) @app.route('/add/<modelname>/to/<foreign_table>/<foreign_key>', methods=['GET', 'POST']) def addto(modelname, foreign_table, foreign_key): kwargs = listAndEdit(modelname, action = 'AddTo', foreign_table = foreign_table, foreign_key = foreign_key) return render_template('editpage.html', **kwargs) @app.route('/edit/<modelname>/<entryid>', methods=['GET', 'POST']) def edit(modelname, entryid): kwargs = listAndEdit(modelname, entryid) #print kwargs return render_template('editpage.html', **kwargs) def saveFormsToModels(form): # needs the form fields to be named modelname_fieldname editedModels = {} foreignKeys = [] for formfield in form.data: if formfield in ['csrf_token']: continue try: modelname, field = formfield.split('_') except: continue value = form[formfield].data try: functionName, foreignKeyName = value.split('_') if functionName == 'ForeignKey': foreignKeys.append( dict( modelname = modelname, field = field, foreignKeyName = foreignKeyName, ) ) continue except: pass try: setattr(editedModels[modelname], field, value) except: editedModels[modelname] = models.ALL_MODELS_DICT[modelname]() setattr(editedModels[modelname], field, value) for model in editedModels: editedModels[model].save() for key in foreignKeys: setattr( editedModels[key['modelname']], key['field'], editedModels[key['foreignKeyName']]) print 'start' print 'Set attr: {}, {}, {}'.format( editedModels[key['modelname']], key['field'], editedModels[key['foreignKeyName']]) for model in editedModels: editedModels[model].save() def getFields(model, exclude=['id']): foreignKeys = {x.column : x.dest_table for x in models.db.get_foreign_keys(model.__name__)} #fields = [(x, type(model._meta.fields[x]).__name__, foreignKeys) for x in model._meta.sorted_field_names if not x in exclude] #print foreignKeys fields = [] for field in model._meta.sorted_field_names: if not field in exclude: fieldtype = type(model._meta.fields[field]).__name__ foreignFieldName = '{}_id'.format(field) if foreignFieldName in foreignKeys: foreignKeyModelName = foreignKeys[foreignFieldName].title() else: foreignKeyModelName = False fields.append( (field, fieldtype, foreignKeyModelName)) #print "Field: {}\nType: {}\nModelname: {}\n".format(field, fieldtype, foreignKeyModelName) return fields def getRelatedModels(entry): entries = {} models = [] try: for query, fk in reversed(list(entry.dependencies())): #for x in dir(fk): #print x for x in fk.model_class.select().where(query): #print 'here:' #print x modelname = fk.model_class.__name__ try: entries[modelname].append(x) except: models.append(modelname) entries[modelname] = [] entries[modelname].append(x) #entries.append((fk.model_class.__name__, x)) except: pass return (models, entries) def listAndEdit(modelname, entryid = 0, entries = False, action = False, **kwargs): try: model = models.ALL_MODELS_DICT[modelname] except KeyError: abort(404) if not entries: entries = model.select() modelForm = model_form(model) fields = getFields(model) try: entry = model.get(id=int(entryid)) dependencies = getRelatedModels(entry) except: entry = model() dependencies = False form = modelForm(obj = entry) if request.method == 'POST': if request.form['submit'] == 'Save': form = modelForm(request.values, obj = entry) if form.validate(): form.populate_obj(entry) entry.save() if action == 'AddTo': addForeignKey(model, entry, kwargs['foreign_table'], kwargs['foreign_key']) redirect(url_for('edit', modelname = model, entryid = kwargs['foreign_key'])) flash('Your entry has been saved') print 'saved' elif request.form['submit'] == 'Delete': try: model.get(model.id == int(entryid)).delete_instance(recursive = True) #redirect(url_for('add', modelname = modelname)) except: pass finally: entry = model() form = modelForm(obj = entry) kwargs = dict( links = [x.__name__ for x in models.ALL_MODELS], header = model.__name__, form=form, entry=entry, entries=entries, fields = fields, dependencies = dependencies, ) return kwargs def addForeignKey(model, entry, foreign_table, foreign_key): foreignModel = models.ALL_MODELS_DICT[foreign_table] foreignItem = foreignModel.get(foreignModel.id == int(foreign_key)) foreignFieldName = model.__name__.lower() print "entry = {}".format(foreignModel) print "item = {}".format(foreignItem) print "fieldName = {}".format(foreignFieldName) print "id = {}".format(entry.id) setattr(foreignItem, foreignFieldName, entry.id) foreignItem.save() @app.route('/favicon.ico') def favicon(): return send_from_directory( os.path.join(app.root_path, 'static'), 'favicon.png', mimetype='image/vnd.microsoft.icon')
Form = forms.ManualRegisterForm(request.values) if request.method == 'POST': if Form.submit.data: saveFormsToModels(Form) return redirect(url_for('register')) return render_template('frontpage.html', form = Form, )
identifier_body
views.py
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.route('/register/', methods=['GET', 'POST']) def register(): Form = forms.ManualRegisterForm(request.values) if request.method == 'POST': if Form.submit.data: saveFormsToModels(Form) return redirect(url_for('register')) return render_template('frontpage.html', form = Form, ) @app.route('/add/<modelname>/', methods=['GET', 'POST']) def add(modelname): kwargs = listAndEdit(modelname) return render_template('editpage.html', **kwargs) @app.route('/add/<modelname>/to/<foreign_table>/<foreign_key>', methods=['GET', 'POST']) def addto(modelname, foreign_table, foreign_key): kwargs = listAndEdit(modelname, action = 'AddTo', foreign_table = foreign_table, foreign_key = foreign_key) return render_template('editpage.html', **kwargs) @app.route('/edit/<modelname>/<entryid>', methods=['GET', 'POST']) def edit(modelname, entryid): kwargs = listAndEdit(modelname, entryid) #print kwargs return render_template('editpage.html', **kwargs) def saveFormsToModels(form): # needs the form fields to be named modelname_fieldname editedModels = {} foreignKeys = [] for formfield in form.data: if formfield in ['csrf_token']: continue try: modelname, field = formfield.split('_') except: continue value = form[formfield].data try: functionName, foreignKeyName = value.split('_') if functionName == 'ForeignKey': foreignKeys.append( dict( modelname = modelname, field = field, foreignKeyName = foreignKeyName, ) ) continue except: pass try: setattr(editedModels[modelname], field, value) except: editedModels[modelname] = models.ALL_MODELS_DICT[modelname]() setattr(editedModels[modelname], field, value) for model in editedModels: editedModels[model].save() for key in foreignKeys: setattr( editedModels[key['modelname']], key['field'], editedModels[key['foreignKeyName']]) print 'start' print 'Set attr: {}, {}, {}'.format( editedModels[key['modelname']], key['field'], editedModels[key['foreignKeyName']]) for model in editedModels:
def getFields(model, exclude=['id']): foreignKeys = {x.column : x.dest_table for x in models.db.get_foreign_keys(model.__name__)} #fields = [(x, type(model._meta.fields[x]).__name__, foreignKeys) for x in model._meta.sorted_field_names if not x in exclude] #print foreignKeys fields = [] for field in model._meta.sorted_field_names: if not field in exclude: fieldtype = type(model._meta.fields[field]).__name__ foreignFieldName = '{}_id'.format(field) if foreignFieldName in foreignKeys: foreignKeyModelName = foreignKeys[foreignFieldName].title() else: foreignKeyModelName = False fields.append( (field, fieldtype, foreignKeyModelName)) #print "Field: {}\nType: {}\nModelname: {}\n".format(field, fieldtype, foreignKeyModelName) return fields def getRelatedModels(entry): entries = {} models = [] try: for query, fk in reversed(list(entry.dependencies())): #for x in dir(fk): #print x for x in fk.model_class.select().where(query): #print 'here:' #print x modelname = fk.model_class.__name__ try: entries[modelname].append(x) except: models.append(modelname) entries[modelname] = [] entries[modelname].append(x) #entries.append((fk.model_class.__name__, x)) except: pass return (models, entries) def listAndEdit(modelname, entryid = 0, entries = False, action = False, **kwargs): try: model = models.ALL_MODELS_DICT[modelname] except KeyError: abort(404) if not entries: entries = model.select() modelForm = model_form(model) fields = getFields(model) try: entry = model.get(id=int(entryid)) dependencies = getRelatedModels(entry) except: entry = model() dependencies = False form = modelForm(obj = entry) if request.method == 'POST': if request.form['submit'] == 'Save': form = modelForm(request.values, obj = entry) if form.validate(): form.populate_obj(entry) entry.save() if action == 'AddTo': addForeignKey(model, entry, kwargs['foreign_table'], kwargs['foreign_key']) redirect(url_for('edit', modelname = model, entryid = kwargs['foreign_key'])) flash('Your entry has been saved') print 'saved' elif request.form['submit'] == 'Delete': try: model.get(model.id == int(entryid)).delete_instance(recursive = True) #redirect(url_for('add', modelname = modelname)) except: pass finally: entry = model() form = modelForm(obj = entry) kwargs = dict( links = [x.__name__ for x in models.ALL_MODELS], header = model.__name__, form=form, entry=entry, entries=entries, fields = fields, dependencies = dependencies, ) return kwargs def addForeignKey(model, entry, foreign_table, foreign_key): foreignModel = models.ALL_MODELS_DICT[foreign_table] foreignItem = foreignModel.get(foreignModel.id == int(foreign_key)) foreignFieldName = model.__name__.lower() print "entry = {}".format(foreignModel) print "item = {}".format(foreignItem) print "fieldName = {}".format(foreignFieldName) print "id = {}".format(entry.id) setattr(foreignItem, foreignFieldName, entry.id) foreignItem.save() @app.route('/favicon.ico') def favicon(): return send_from_directory( os.path.join(app.root_path, 'static'), 'favicon.png', mimetype='image/vnd.microsoft.icon')
editedModels[model].save()
conditional_block
views.py
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.route('/register/', methods=['GET', 'POST']) def register(): Form = forms.ManualRegisterForm(request.values) if request.method == 'POST': if Form.submit.data: saveFormsToModels(Form) return redirect(url_for('register')) return render_template('frontpage.html', form = Form, ) @app.route('/add/<modelname>/', methods=['GET', 'POST']) def add(modelname): kwargs = listAndEdit(modelname) return render_template('editpage.html', **kwargs) @app.route('/add/<modelname>/to/<foreign_table>/<foreign_key>', methods=['GET', 'POST']) def addto(modelname, foreign_table, foreign_key): kwargs = listAndEdit(modelname, action = 'AddTo', foreign_table = foreign_table, foreign_key = foreign_key) return render_template('editpage.html', **kwargs) @app.route('/edit/<modelname>/<entryid>', methods=['GET', 'POST']) def edit(modelname, entryid): kwargs = listAndEdit(modelname, entryid) #print kwargs return render_template('editpage.html', **kwargs) def saveFormsToModels(form): # needs the form fields to be named modelname_fieldname editedModels = {} foreignKeys = [] for formfield in form.data: if formfield in ['csrf_token']: continue try: modelname, field = formfield.split('_') except: continue value = form[formfield].data try: functionName, foreignKeyName = value.split('_') if functionName == 'ForeignKey': foreignKeys.append( dict( modelname = modelname, field = field, foreignKeyName = foreignKeyName, ) ) continue except: pass try: setattr(editedModels[modelname], field, value) except: editedModels[modelname] = models.ALL_MODELS_DICT[modelname]() setattr(editedModels[modelname], field, value) for model in editedModels: editedModels[model].save() for key in foreignKeys: setattr( editedModels[key['modelname']], key['field'], editedModels[key['foreignKeyName']]) print 'start' print 'Set attr: {}, {}, {}'.format( editedModels[key['modelname']], key['field'], editedModels[key['foreignKeyName']]) for model in editedModels: editedModels[model].save() def getFields(model, exclude=['id']): foreignKeys = {x.column : x.dest_table for x in models.db.get_foreign_keys(model.__name__)} #fields = [(x, type(model._meta.fields[x]).__name__, foreignKeys) for x in model._meta.sorted_field_names if not x in exclude] #print foreignKeys fields = [] for field in model._meta.sorted_field_names: if not field in exclude: fieldtype = type(model._meta.fields[field]).__name__ foreignFieldName = '{}_id'.format(field) if foreignFieldName in foreignKeys: foreignKeyModelName = foreignKeys[foreignFieldName].title() else: foreignKeyModelName = False fields.append( (field, fieldtype, foreignKeyModelName)) #print "Field: {}\nType: {}\nModelname: {}\n".format(field, fieldtype, foreignKeyModelName) return fields def getRelatedModels(entry): entries = {} models = [] try: for query, fk in reversed(list(entry.dependencies())): #for x in dir(fk): #print x for x in fk.model_class.select().where(query): #print 'here:' #print x modelname = fk.model_class.__name__ try: entries[modelname].append(x) except: models.append(modelname) entries[modelname] = [] entries[modelname].append(x) #entries.append((fk.model_class.__name__, x)) except: pass return (models, entries) def listAndEdit(modelname, entryid = 0, entries = False, action = False, **kwargs): try: model = models.ALL_MODELS_DICT[modelname] except KeyError: abort(404) if not entries: entries = model.select() modelForm = model_form(model) fields = getFields(model) try: entry = model.get(id=int(entryid)) dependencies = getRelatedModels(entry) except: entry = model() dependencies = False form = modelForm(obj = entry) if request.method == 'POST': if request.form['submit'] == 'Save': form = modelForm(request.values, obj = entry) if form.validate(): form.populate_obj(entry) entry.save() if action == 'AddTo': addForeignKey(model, entry, kwargs['foreign_table'], kwargs['foreign_key']) redirect(url_for('edit', modelname = model, entryid = kwargs['foreign_key'])) flash('Your entry has been saved') print 'saved' elif request.form['submit'] == 'Delete':
except: pass finally: entry = model() form = modelForm(obj = entry) kwargs = dict( links = [x.__name__ for x in models.ALL_MODELS], header = model.__name__, form=form, entry=entry, entries=entries, fields = fields, dependencies = dependencies, ) return kwargs def addForeignKey(model, entry, foreign_table, foreign_key): foreignModel = models.ALL_MODELS_DICT[foreign_table] foreignItem = foreignModel.get(foreignModel.id == int(foreign_key)) foreignFieldName = model.__name__.lower() print "entry = {}".format(foreignModel) print "item = {}".format(foreignItem) print "fieldName = {}".format(foreignFieldName) print "id = {}".format(entry.id) setattr(foreignItem, foreignFieldName, entry.id) foreignItem.save() @app.route('/favicon.ico') def favicon(): return send_from_directory( os.path.join(app.root_path, 'static'), 'favicon.png', mimetype='image/vnd.microsoft.icon')
try: model.get(model.id == int(entryid)).delete_instance(recursive = True) #redirect(url_for('add', modelname = modelname))
random_line_split
views.py
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.route('/register/', methods=['GET', 'POST']) def register(): Form = forms.ManualRegisterForm(request.values) if request.method == 'POST': if Form.submit.data: saveFormsToModels(Form) return redirect(url_for('register')) return render_template('frontpage.html', form = Form, ) @app.route('/add/<modelname>/', methods=['GET', 'POST']) def add(modelname): kwargs = listAndEdit(modelname) return render_template('editpage.html', **kwargs) @app.route('/add/<modelname>/to/<foreign_table>/<foreign_key>', methods=['GET', 'POST']) def addto(modelname, foreign_table, foreign_key): kwargs = listAndEdit(modelname, action = 'AddTo', foreign_table = foreign_table, foreign_key = foreign_key) return render_template('editpage.html', **kwargs) @app.route('/edit/<modelname>/<entryid>', methods=['GET', 'POST']) def edit(modelname, entryid): kwargs = listAndEdit(modelname, entryid) #print kwargs return render_template('editpage.html', **kwargs) def saveFormsToModels(form): # needs the form fields to be named modelname_fieldname editedModels = {} foreignKeys = [] for formfield in form.data: if formfield in ['csrf_token']: continue try: modelname, field = formfield.split('_') except: continue value = form[formfield].data try: functionName, foreignKeyName = value.split('_') if functionName == 'ForeignKey': foreignKeys.append( dict( modelname = modelname, field = field, foreignKeyName = foreignKeyName, ) ) continue except: pass try: setattr(editedModels[modelname], field, value) except: editedModels[modelname] = models.ALL_MODELS_DICT[modelname]() setattr(editedModels[modelname], field, value) for model in editedModels: editedModels[model].save() for key in foreignKeys: setattr( editedModels[key['modelname']], key['field'], editedModels[key['foreignKeyName']]) print 'start' print 'Set attr: {}, {}, {}'.format( editedModels[key['modelname']], key['field'], editedModels[key['foreignKeyName']]) for model in editedModels: editedModels[model].save() def getFields(model, exclude=['id']): foreignKeys = {x.column : x.dest_table for x in models.db.get_foreign_keys(model.__name__)} #fields = [(x, type(model._meta.fields[x]).__name__, foreignKeys) for x in model._meta.sorted_field_names if not x in exclude] #print foreignKeys fields = [] for field in model._meta.sorted_field_names: if not field in exclude: fieldtype = type(model._meta.fields[field]).__name__ foreignFieldName = '{}_id'.format(field) if foreignFieldName in foreignKeys: foreignKeyModelName = foreignKeys[foreignFieldName].title() else: foreignKeyModelName = False fields.append( (field, fieldtype, foreignKeyModelName)) #print "Field: {}\nType: {}\nModelname: {}\n".format(field, fieldtype, foreignKeyModelName) return fields def
(entry): entries = {} models = [] try: for query, fk in reversed(list(entry.dependencies())): #for x in dir(fk): #print x for x in fk.model_class.select().where(query): #print 'here:' #print x modelname = fk.model_class.__name__ try: entries[modelname].append(x) except: models.append(modelname) entries[modelname] = [] entries[modelname].append(x) #entries.append((fk.model_class.__name__, x)) except: pass return (models, entries) def listAndEdit(modelname, entryid = 0, entries = False, action = False, **kwargs): try: model = models.ALL_MODELS_DICT[modelname] except KeyError: abort(404) if not entries: entries = model.select() modelForm = model_form(model) fields = getFields(model) try: entry = model.get(id=int(entryid)) dependencies = getRelatedModels(entry) except: entry = model() dependencies = False form = modelForm(obj = entry) if request.method == 'POST': if request.form['submit'] == 'Save': form = modelForm(request.values, obj = entry) if form.validate(): form.populate_obj(entry) entry.save() if action == 'AddTo': addForeignKey(model, entry, kwargs['foreign_table'], kwargs['foreign_key']) redirect(url_for('edit', modelname = model, entryid = kwargs['foreign_key'])) flash('Your entry has been saved') print 'saved' elif request.form['submit'] == 'Delete': try: model.get(model.id == int(entryid)).delete_instance(recursive = True) #redirect(url_for('add', modelname = modelname)) except: pass finally: entry = model() form = modelForm(obj = entry) kwargs = dict( links = [x.__name__ for x in models.ALL_MODELS], header = model.__name__, form=form, entry=entry, entries=entries, fields = fields, dependencies = dependencies, ) return kwargs def addForeignKey(model, entry, foreign_table, foreign_key): foreignModel = models.ALL_MODELS_DICT[foreign_table] foreignItem = foreignModel.get(foreignModel.id == int(foreign_key)) foreignFieldName = model.__name__.lower() print "entry = {}".format(foreignModel) print "item = {}".format(foreignItem) print "fieldName = {}".format(foreignFieldName) print "id = {}".format(entry.id) setattr(foreignItem, foreignFieldName, entry.id) foreignItem.save() @app.route('/favicon.ico') def favicon(): return send_from_directory( os.path.join(app.root_path, 'static'), 'favicon.png', mimetype='image/vnd.microsoft.icon')
getRelatedModels
identifier_name
project_map.js
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="text"]').focusin(function(ev){ if ($(this).attr('value')=="Location, latitude or longitude") { $(this).attr('value',''); } }); $('div.outer_map form input[type="text"]').focusout(function(ev){ if ($(this).attr('value')=="") { $(this).attr('value','Location, latitude or longitude'); } }); $('a#add_location_map').click(function(ev){ ev.preventDefault(); ev.stopPropagation(); markers_position = []; var position = $(this).offset(); $('div.map_window').css('top',position.top-310+'px'); $('div.map_window').css('left',position.left-140+'px'); $('div.map_window').fadeIn(function(){ var myOptions = { zoom: 1, center: new google.maps.LatLng(30, 0), disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map"),myOptions); var image = new google.maps.MarkerImage('/images/backoffice/projects/project_marker.png',new google.maps.Size(34, 42),new google.maps.Point(0,0), new google.maps.Point(17, 42)); google.maps.event.addListener(map,"click",function(event){ var marker = new google.maps.Marker({position: event.latLng, map:map, icon:image}); markers_position.push(event.latLng); }); $('#project_coordinates li input').each(function(){ var point = $(this).attr('value').replace(/\(/,'').replace(/\)/,'').split(', '); var position = new google.maps.LatLng(point[0],point[1]); var marker = new google.maps.Marker({position: position, map:map, icon:image}); markers_position.push(position); }); }); $(window).resize(function() { var position = $('a#add_location_map').position(); $('div.map_window').css('top',position.top+'px'); $('div.map_window').css('left',position.left+'px'); }); }); $('a.close').live('click', function(){ var li = $(this).closest('li') var point = li.children('input').attr('value'); li.remove(); for(var i=0;i<markers_position.length;i++){
} } $(window).unbind('resize'); $('div.map_window').fadeOut(); return false; }); $('a.save').click(function(e){ $('#project_coordinates li').each(function(){ $(this).remove(); }); for(var i=0;i<markers_position.length;i++){ $('#project_coordinates').append('<li><p>'+markers_position[i]+'</p><input type="hidden" name="project[points][]" value="'+markers_position[i]+'" /><a href="javascript:void(null)" class="close"></a></li>'); } $(window).unbind('resize'); $('div.map_window').fadeOut(); }); }); function searchPlace() { var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds); } }); }
if (point == markers_position[i]) { markers_position.splice(i);
random_line_split
project_map.js
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="text"]').focusin(function(ev){ if ($(this).attr('value')=="Location, latitude or longitude") { $(this).attr('value',''); } }); $('div.outer_map form input[type="text"]').focusout(function(ev){ if ($(this).attr('value')=="") { $(this).attr('value','Location, latitude or longitude'); } }); $('a#add_location_map').click(function(ev){ ev.preventDefault(); ev.stopPropagation(); markers_position = []; var position = $(this).offset(); $('div.map_window').css('top',position.top-310+'px'); $('div.map_window').css('left',position.left-140+'px'); $('div.map_window').fadeIn(function(){ var myOptions = { zoom: 1, center: new google.maps.LatLng(30, 0), disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map"),myOptions); var image = new google.maps.MarkerImage('/images/backoffice/projects/project_marker.png',new google.maps.Size(34, 42),new google.maps.Point(0,0), new google.maps.Point(17, 42)); google.maps.event.addListener(map,"click",function(event){ var marker = new google.maps.Marker({position: event.latLng, map:map, icon:image}); markers_position.push(event.latLng); }); $('#project_coordinates li input').each(function(){ var point = $(this).attr('value').replace(/\(/,'').replace(/\)/,'').split(', '); var position = new google.maps.LatLng(point[0],point[1]); var marker = new google.maps.Marker({position: position, map:map, icon:image}); markers_position.push(position); }); }); $(window).resize(function() { var position = $('a#add_location_map').position(); $('div.map_window').css('top',position.top+'px'); $('div.map_window').css('left',position.left+'px'); }); }); $('a.close').live('click', function(){ var li = $(this).closest('li') var point = li.children('input').attr('value'); li.remove(); for(var i=0;i<markers_position.length;i++){ if (point == markers_position[i]) { markers_position.splice(i); } } $(window).unbind('resize'); $('div.map_window').fadeOut(); return false; }); $('a.save').click(function(e){ $('#project_coordinates li').each(function(){ $(this).remove(); }); for(var i=0;i<markers_position.length;i++){ $('#project_coordinates').append('<li><p>'+markers_position[i]+'</p><input type="hidden" name="project[points][]" value="'+markers_position[i]+'" /><a href="javascript:void(null)" class="close"></a></li>'); } $(window).unbind('resize'); $('div.map_window').fadeOut(); }); }); function searchPlace()
{ var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds); } }); }
identifier_body
project_map.js
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="text"]').focusin(function(ev){ if ($(this).attr('value')=="Location, latitude or longitude") { $(this).attr('value',''); } }); $('div.outer_map form input[type="text"]').focusout(function(ev){ if ($(this).attr('value')=="") { $(this).attr('value','Location, latitude or longitude'); } }); $('a#add_location_map').click(function(ev){ ev.preventDefault(); ev.stopPropagation(); markers_position = []; var position = $(this).offset(); $('div.map_window').css('top',position.top-310+'px'); $('div.map_window').css('left',position.left-140+'px'); $('div.map_window').fadeIn(function(){ var myOptions = { zoom: 1, center: new google.maps.LatLng(30, 0), disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map"),myOptions); var image = new google.maps.MarkerImage('/images/backoffice/projects/project_marker.png',new google.maps.Size(34, 42),new google.maps.Point(0,0), new google.maps.Point(17, 42)); google.maps.event.addListener(map,"click",function(event){ var marker = new google.maps.Marker({position: event.latLng, map:map, icon:image}); markers_position.push(event.latLng); }); $('#project_coordinates li input').each(function(){ var point = $(this).attr('value').replace(/\(/,'').replace(/\)/,'').split(', '); var position = new google.maps.LatLng(point[0],point[1]); var marker = new google.maps.Marker({position: position, map:map, icon:image}); markers_position.push(position); }); }); $(window).resize(function() { var position = $('a#add_location_map').position(); $('div.map_window').css('top',position.top+'px'); $('div.map_window').css('left',position.left+'px'); }); }); $('a.close').live('click', function(){ var li = $(this).closest('li') var point = li.children('input').attr('value'); li.remove(); for(var i=0;i<markers_position.length;i++){ if (point == markers_position[i]) { markers_position.splice(i); } } $(window).unbind('resize'); $('div.map_window').fadeOut(); return false; }); $('a.save').click(function(e){ $('#project_coordinates li').each(function(){ $(this).remove(); }); for(var i=0;i<markers_position.length;i++){ $('#project_coordinates').append('<li><p>'+markers_position[i]+'</p><input type="hidden" name="project[points][]" value="'+markers_position[i]+'" /><a href="javascript:void(null)" class="close"></a></li>'); } $(window).unbind('resize'); $('div.map_window').fadeOut(); }); }); function
() { var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds); } }); }
searchPlace
identifier_name
project_map.js
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="text"]').focusin(function(ev){ if ($(this).attr('value')=="Location, latitude or longitude") { $(this).attr('value',''); } }); $('div.outer_map form input[type="text"]').focusout(function(ev){ if ($(this).attr('value')=="") { $(this).attr('value','Location, latitude or longitude'); } }); $('a#add_location_map').click(function(ev){ ev.preventDefault(); ev.stopPropagation(); markers_position = []; var position = $(this).offset(); $('div.map_window').css('top',position.top-310+'px'); $('div.map_window').css('left',position.left-140+'px'); $('div.map_window').fadeIn(function(){ var myOptions = { zoom: 1, center: new google.maps.LatLng(30, 0), disableDefaultUI: true, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map"),myOptions); var image = new google.maps.MarkerImage('/images/backoffice/projects/project_marker.png',new google.maps.Size(34, 42),new google.maps.Point(0,0), new google.maps.Point(17, 42)); google.maps.event.addListener(map,"click",function(event){ var marker = new google.maps.Marker({position: event.latLng, map:map, icon:image}); markers_position.push(event.latLng); }); $('#project_coordinates li input').each(function(){ var point = $(this).attr('value').replace(/\(/,'').replace(/\)/,'').split(', '); var position = new google.maps.LatLng(point[0],point[1]); var marker = new google.maps.Marker({position: position, map:map, icon:image}); markers_position.push(position); }); }); $(window).resize(function() { var position = $('a#add_location_map').position(); $('div.map_window').css('top',position.top+'px'); $('div.map_window').css('left',position.left+'px'); }); }); $('a.close').live('click', function(){ var li = $(this).closest('li') var point = li.children('input').attr('value'); li.remove(); for(var i=0;i<markers_position.length;i++){ if (point == markers_position[i]) { markers_position.splice(i); } } $(window).unbind('resize'); $('div.map_window').fadeOut(); return false; }); $('a.save').click(function(e){ $('#project_coordinates li').each(function(){ $(this).remove(); }); for(var i=0;i<markers_position.length;i++)
$(window).unbind('resize'); $('div.map_window').fadeOut(); }); }); function searchPlace() { var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds); } }); }
{ $('#project_coordinates').append('<li><p>'+markers_position[i]+'</p><input type="hidden" name="project[points][]" value="'+markers_position[i]+'" /><a href="javascript:void(null)" class="close"></a></li>'); }
conditional_block
usbiodef.rs
// Copyright © 2016 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! Common header file for all USB IOCTLs defined for //! the core stack. We define them in this single header file //! so that we can maintain backward compatibilty with older //! versions of the stack. use shared::guiddef::GUID; use shared::minwindef::ULONG; use um::winioctl::{FILE_ANY_ACCESS, FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, METHOD_NEITHER}; use um::winnt::PVOID; pub const USB_SUBMIT_URB: ULONG = 0; pub const USB_RESET_PORT: ULONG = 1; pub const USB_GET_ROOTHUB_PDO: ULONG = 3; pub const USB_GET_PORT_STATUS: ULONG = 4; pub const USB_ENABLE_PORT: ULONG = 5; pub const USB_GET_HUB_COUNT: ULONG = 6; pub const USB_CYCLE_PORT: ULONG = 7; pub const USB_GET_HUB_NAME: ULONG = 8; pub const USB_IDLE_NOTIFICATION: ULONG = 9; pub const USB_RECORD_FAILURE: ULONG = 10; pub const USB_GET_BUS_INFO: ULONG = 264; pub const USB_GET_CONTROLLER_NAME: ULONG = 265; pub const USB_GET_BUSGUID_INFO: ULONG = 266; pub const USB_GET_PARENT_HUB_INFO: ULONG = 267; pub const USB_GET_DEVICE_HANDLE: ULONG = 268;
pub const USB_GET_DEVICE_HANDLE_EX: ULONG = 269; pub const USB_GET_TT_DEVICE_HANDLE: ULONG = 270; pub const USB_GET_TOPOLOGY_ADDRESS: ULONG = 271; pub const USB_IDLE_NOTIFICATION_EX: ULONG = 272; pub const USB_REQ_GLOBAL_SUSPEND: ULONG = 273; pub const USB_REQ_GLOBAL_RESUME: ULONG = 274; pub const USB_GET_HUB_CONFIG_INFO: ULONG = 275; pub const USB_FAIL_GET_STATUS: ULONG = 280; pub const USB_REGISTER_COMPOSITE_DEVICE: ULONG = 0; pub const USB_UNREGISTER_COMPOSITE_DEVICE: ULONG = 1; pub const USB_REQUEST_REMOTE_WAKE_NOTIFICATION: ULONG = 2; pub const HCD_GET_STATS_1: ULONG = 255; pub const HCD_DIAGNOSTIC_MODE_ON: ULONG = 256; pub const HCD_DIAGNOSTIC_MODE_OFF: ULONG = 257; pub const HCD_GET_ROOT_HUB_NAME: ULONG = 258; pub const HCD_GET_DRIVERKEY_NAME: ULONG = 265; pub const HCD_GET_STATS_2: ULONG = 266; pub const HCD_DISABLE_PORT: ULONG = 268; pub const HCD_ENABLE_PORT: ULONG = 269; pub const HCD_USER_REQUEST: ULONG = 270; pub const HCD_TRACE_READ_REQUEST: ULONG = 275; pub const USB_GET_NODE_INFORMATION: ULONG = 258; pub const USB_GET_NODE_CONNECTION_INFORMATION: ULONG = 259; pub const USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION: ULONG = 260; pub const USB_GET_NODE_CONNECTION_NAME: ULONG = 261; pub const USB_DIAG_IGNORE_HUBS_ON: ULONG = 262; pub const USB_DIAG_IGNORE_HUBS_OFF: ULONG = 263; pub const USB_GET_NODE_CONNECTION_DRIVERKEY_NAME: ULONG = 264; pub const USB_GET_HUB_CAPABILITIES: ULONG = 271; pub const USB_GET_NODE_CONNECTION_ATTRIBUTES: ULONG = 272; pub const USB_HUB_CYCLE_PORT: ULONG = 273; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX: ULONG = 274; pub const USB_RESET_HUB: ULONG = 275; pub const USB_GET_HUB_CAPABILITIES_EX: ULONG = 276; pub const USB_GET_HUB_INFORMATION_EX: ULONG = 277; pub const USB_GET_PORT_CONNECTOR_PROPERTIES: ULONG = 278; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX_V2: ULONG = 279; DEFINE_GUID!{GUID_DEVINTERFACE_USB_HUB, 0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8} DEFINE_GUID!{GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} DEFINE_GUID!{GUID_DEVINTERFACE_USB_HOST_CONTROLLER, 0x3abf6f2d, 0x71c4, 0x462a, 0x8a, 0x92, 0x1e, 0x68, 0x61, 0xe6, 0xaf, 0x27} DEFINE_GUID!{GUID_USB_WMI_STD_DATA, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_STD_NOTIFICATION, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_DEVICE_PERF_INFO, 0x66c1aa3c, 0x499f, 0x49a0, 0xa9, 0xa5, 0x61, 0xe2, 0x35, 0x9f, 0x64, 0x7} DEFINE_GUID!{GUID_USB_WMI_NODE_INFO, 0x9c179357, 0xdc7a, 0x4f41, 0xb6, 0x6b, 0x32, 0x3b, 0x9d, 0xdc, 0xb5, 0xb1} DEFINE_GUID!{GUID_USB_WMI_TRACING, 0x3a61881b, 0xb4e6, 0x4bf9, 0xae, 0xf, 0x3c, 0xd8, 0xf3, 0x94, 0xe5, 0x2f} DEFINE_GUID!{GUID_USB_TRANSFER_TRACING, 0x681eb8aa, 0x403d, 0x452c, 0x9f, 0x8a, 0xf0, 0x61, 0x6f, 0xac, 0x95, 0x40} DEFINE_GUID!{GUID_USB_PERFORMANCE_TRACING, 0xd5de77a6, 0x6ae9, 0x425c, 0xb1, 0xe2, 0xf5, 0x61, 0x5f, 0xd3, 0x48, 0xa9} DEFINE_GUID!{GUID_USB_WMI_SURPRISE_REMOVAL_NOTIFICATION, 0x9bbbf831, 0xa2f2, 0x43b4, 0x96, 0xd1, 0x86, 0x94, 0x4b, 0x59, 0x14, 0xb3} pub const GUID_CLASS_USBHUB: GUID = GUID_DEVINTERFACE_USB_HUB; pub const GUID_CLASS_USB_DEVICE: GUID = GUID_DEVINTERFACE_USB_DEVICE; pub const GUID_CLASS_USB_HOST_CONTROLLER: GUID = GUID_DEVINTERFACE_USB_HOST_CONTROLLER; pub const FILE_DEVICE_USB: ULONG = FILE_DEVICE_UNKNOWN; #[inline] pub fn USB_CTL(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_NEITHER, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL_BUFFERED(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } // No calling convention was specified in the code FN!{stdcall USB_IDLE_CALLBACK( Context: PVOID, ) -> ()} STRUCT!{struct USB_IDLE_CALLBACK_INFO { IdleCallback: USB_IDLE_CALLBACK, IdleContext: PVOID, }} pub type PUSB_IDLE_CALLBACK_INFO = *mut USB_IDLE_CALLBACK_INFO;
random_line_split
usbiodef.rs
// Copyright © 2016 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! Common header file for all USB IOCTLs defined for //! the core stack. We define them in this single header file //! so that we can maintain backward compatibilty with older //! versions of the stack. use shared::guiddef::GUID; use shared::minwindef::ULONG; use um::winioctl::{FILE_ANY_ACCESS, FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, METHOD_NEITHER}; use um::winnt::PVOID; pub const USB_SUBMIT_URB: ULONG = 0; pub const USB_RESET_PORT: ULONG = 1; pub const USB_GET_ROOTHUB_PDO: ULONG = 3; pub const USB_GET_PORT_STATUS: ULONG = 4; pub const USB_ENABLE_PORT: ULONG = 5; pub const USB_GET_HUB_COUNT: ULONG = 6; pub const USB_CYCLE_PORT: ULONG = 7; pub const USB_GET_HUB_NAME: ULONG = 8; pub const USB_IDLE_NOTIFICATION: ULONG = 9; pub const USB_RECORD_FAILURE: ULONG = 10; pub const USB_GET_BUS_INFO: ULONG = 264; pub const USB_GET_CONTROLLER_NAME: ULONG = 265; pub const USB_GET_BUSGUID_INFO: ULONG = 266; pub const USB_GET_PARENT_HUB_INFO: ULONG = 267; pub const USB_GET_DEVICE_HANDLE: ULONG = 268; pub const USB_GET_DEVICE_HANDLE_EX: ULONG = 269; pub const USB_GET_TT_DEVICE_HANDLE: ULONG = 270; pub const USB_GET_TOPOLOGY_ADDRESS: ULONG = 271; pub const USB_IDLE_NOTIFICATION_EX: ULONG = 272; pub const USB_REQ_GLOBAL_SUSPEND: ULONG = 273; pub const USB_REQ_GLOBAL_RESUME: ULONG = 274; pub const USB_GET_HUB_CONFIG_INFO: ULONG = 275; pub const USB_FAIL_GET_STATUS: ULONG = 280; pub const USB_REGISTER_COMPOSITE_DEVICE: ULONG = 0; pub const USB_UNREGISTER_COMPOSITE_DEVICE: ULONG = 1; pub const USB_REQUEST_REMOTE_WAKE_NOTIFICATION: ULONG = 2; pub const HCD_GET_STATS_1: ULONG = 255; pub const HCD_DIAGNOSTIC_MODE_ON: ULONG = 256; pub const HCD_DIAGNOSTIC_MODE_OFF: ULONG = 257; pub const HCD_GET_ROOT_HUB_NAME: ULONG = 258; pub const HCD_GET_DRIVERKEY_NAME: ULONG = 265; pub const HCD_GET_STATS_2: ULONG = 266; pub const HCD_DISABLE_PORT: ULONG = 268; pub const HCD_ENABLE_PORT: ULONG = 269; pub const HCD_USER_REQUEST: ULONG = 270; pub const HCD_TRACE_READ_REQUEST: ULONG = 275; pub const USB_GET_NODE_INFORMATION: ULONG = 258; pub const USB_GET_NODE_CONNECTION_INFORMATION: ULONG = 259; pub const USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION: ULONG = 260; pub const USB_GET_NODE_CONNECTION_NAME: ULONG = 261; pub const USB_DIAG_IGNORE_HUBS_ON: ULONG = 262; pub const USB_DIAG_IGNORE_HUBS_OFF: ULONG = 263; pub const USB_GET_NODE_CONNECTION_DRIVERKEY_NAME: ULONG = 264; pub const USB_GET_HUB_CAPABILITIES: ULONG = 271; pub const USB_GET_NODE_CONNECTION_ATTRIBUTES: ULONG = 272; pub const USB_HUB_CYCLE_PORT: ULONG = 273; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX: ULONG = 274; pub const USB_RESET_HUB: ULONG = 275; pub const USB_GET_HUB_CAPABILITIES_EX: ULONG = 276; pub const USB_GET_HUB_INFORMATION_EX: ULONG = 277; pub const USB_GET_PORT_CONNECTOR_PROPERTIES: ULONG = 278; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX_V2: ULONG = 279; DEFINE_GUID!{GUID_DEVINTERFACE_USB_HUB, 0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8} DEFINE_GUID!{GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} DEFINE_GUID!{GUID_DEVINTERFACE_USB_HOST_CONTROLLER, 0x3abf6f2d, 0x71c4, 0x462a, 0x8a, 0x92, 0x1e, 0x68, 0x61, 0xe6, 0xaf, 0x27} DEFINE_GUID!{GUID_USB_WMI_STD_DATA, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_STD_NOTIFICATION, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_DEVICE_PERF_INFO, 0x66c1aa3c, 0x499f, 0x49a0, 0xa9, 0xa5, 0x61, 0xe2, 0x35, 0x9f, 0x64, 0x7} DEFINE_GUID!{GUID_USB_WMI_NODE_INFO, 0x9c179357, 0xdc7a, 0x4f41, 0xb6, 0x6b, 0x32, 0x3b, 0x9d, 0xdc, 0xb5, 0xb1} DEFINE_GUID!{GUID_USB_WMI_TRACING, 0x3a61881b, 0xb4e6, 0x4bf9, 0xae, 0xf, 0x3c, 0xd8, 0xf3, 0x94, 0xe5, 0x2f} DEFINE_GUID!{GUID_USB_TRANSFER_TRACING, 0x681eb8aa, 0x403d, 0x452c, 0x9f, 0x8a, 0xf0, 0x61, 0x6f, 0xac, 0x95, 0x40} DEFINE_GUID!{GUID_USB_PERFORMANCE_TRACING, 0xd5de77a6, 0x6ae9, 0x425c, 0xb1, 0xe2, 0xf5, 0x61, 0x5f, 0xd3, 0x48, 0xa9} DEFINE_GUID!{GUID_USB_WMI_SURPRISE_REMOVAL_NOTIFICATION, 0x9bbbf831, 0xa2f2, 0x43b4, 0x96, 0xd1, 0x86, 0x94, 0x4b, 0x59, 0x14, 0xb3} pub const GUID_CLASS_USBHUB: GUID = GUID_DEVINTERFACE_USB_HUB; pub const GUID_CLASS_USB_DEVICE: GUID = GUID_DEVINTERFACE_USB_DEVICE; pub const GUID_CLASS_USB_HOST_CONTROLLER: GUID = GUID_DEVINTERFACE_USB_HOST_CONTROLLER; pub const FILE_DEVICE_USB: ULONG = FILE_DEVICE_UNKNOWN; #[inline] pub fn USB_CTL(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } #[inline] pub fn U
id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_NEITHER, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL_BUFFERED(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } // No calling convention was specified in the code FN!{stdcall USB_IDLE_CALLBACK( Context: PVOID, ) -> ()} STRUCT!{struct USB_IDLE_CALLBACK_INFO { IdleCallback: USB_IDLE_CALLBACK, IdleContext: PVOID, }} pub type PUSB_IDLE_CALLBACK_INFO = *mut USB_IDLE_CALLBACK_INFO;
SB_KERNEL_CTL(
identifier_name
usbiodef.rs
// Copyright © 2016 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms //! Common header file for all USB IOCTLs defined for //! the core stack. We define them in this single header file //! so that we can maintain backward compatibilty with older //! versions of the stack. use shared::guiddef::GUID; use shared::minwindef::ULONG; use um::winioctl::{FILE_ANY_ACCESS, FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, METHOD_NEITHER}; use um::winnt::PVOID; pub const USB_SUBMIT_URB: ULONG = 0; pub const USB_RESET_PORT: ULONG = 1; pub const USB_GET_ROOTHUB_PDO: ULONG = 3; pub const USB_GET_PORT_STATUS: ULONG = 4; pub const USB_ENABLE_PORT: ULONG = 5; pub const USB_GET_HUB_COUNT: ULONG = 6; pub const USB_CYCLE_PORT: ULONG = 7; pub const USB_GET_HUB_NAME: ULONG = 8; pub const USB_IDLE_NOTIFICATION: ULONG = 9; pub const USB_RECORD_FAILURE: ULONG = 10; pub const USB_GET_BUS_INFO: ULONG = 264; pub const USB_GET_CONTROLLER_NAME: ULONG = 265; pub const USB_GET_BUSGUID_INFO: ULONG = 266; pub const USB_GET_PARENT_HUB_INFO: ULONG = 267; pub const USB_GET_DEVICE_HANDLE: ULONG = 268; pub const USB_GET_DEVICE_HANDLE_EX: ULONG = 269; pub const USB_GET_TT_DEVICE_HANDLE: ULONG = 270; pub const USB_GET_TOPOLOGY_ADDRESS: ULONG = 271; pub const USB_IDLE_NOTIFICATION_EX: ULONG = 272; pub const USB_REQ_GLOBAL_SUSPEND: ULONG = 273; pub const USB_REQ_GLOBAL_RESUME: ULONG = 274; pub const USB_GET_HUB_CONFIG_INFO: ULONG = 275; pub const USB_FAIL_GET_STATUS: ULONG = 280; pub const USB_REGISTER_COMPOSITE_DEVICE: ULONG = 0; pub const USB_UNREGISTER_COMPOSITE_DEVICE: ULONG = 1; pub const USB_REQUEST_REMOTE_WAKE_NOTIFICATION: ULONG = 2; pub const HCD_GET_STATS_1: ULONG = 255; pub const HCD_DIAGNOSTIC_MODE_ON: ULONG = 256; pub const HCD_DIAGNOSTIC_MODE_OFF: ULONG = 257; pub const HCD_GET_ROOT_HUB_NAME: ULONG = 258; pub const HCD_GET_DRIVERKEY_NAME: ULONG = 265; pub const HCD_GET_STATS_2: ULONG = 266; pub const HCD_DISABLE_PORT: ULONG = 268; pub const HCD_ENABLE_PORT: ULONG = 269; pub const HCD_USER_REQUEST: ULONG = 270; pub const HCD_TRACE_READ_REQUEST: ULONG = 275; pub const USB_GET_NODE_INFORMATION: ULONG = 258; pub const USB_GET_NODE_CONNECTION_INFORMATION: ULONG = 259; pub const USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION: ULONG = 260; pub const USB_GET_NODE_CONNECTION_NAME: ULONG = 261; pub const USB_DIAG_IGNORE_HUBS_ON: ULONG = 262; pub const USB_DIAG_IGNORE_HUBS_OFF: ULONG = 263; pub const USB_GET_NODE_CONNECTION_DRIVERKEY_NAME: ULONG = 264; pub const USB_GET_HUB_CAPABILITIES: ULONG = 271; pub const USB_GET_NODE_CONNECTION_ATTRIBUTES: ULONG = 272; pub const USB_HUB_CYCLE_PORT: ULONG = 273; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX: ULONG = 274; pub const USB_RESET_HUB: ULONG = 275; pub const USB_GET_HUB_CAPABILITIES_EX: ULONG = 276; pub const USB_GET_HUB_INFORMATION_EX: ULONG = 277; pub const USB_GET_PORT_CONNECTOR_PROPERTIES: ULONG = 278; pub const USB_GET_NODE_CONNECTION_INFORMATION_EX_V2: ULONG = 279; DEFINE_GUID!{GUID_DEVINTERFACE_USB_HUB, 0xf18a0e88, 0xc30c, 0x11d0, 0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8} DEFINE_GUID!{GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} DEFINE_GUID!{GUID_DEVINTERFACE_USB_HOST_CONTROLLER, 0x3abf6f2d, 0x71c4, 0x462a, 0x8a, 0x92, 0x1e, 0x68, 0x61, 0xe6, 0xaf, 0x27} DEFINE_GUID!{GUID_USB_WMI_STD_DATA, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_STD_NOTIFICATION, 0x4E623B20, 0xCB14, 0x11D1, 0xB3, 0x31, 0x00, 0xA0, 0xC9, 0x59, 0xBB, 0xD2} DEFINE_GUID!{GUID_USB_WMI_DEVICE_PERF_INFO, 0x66c1aa3c, 0x499f, 0x49a0, 0xa9, 0xa5, 0x61, 0xe2, 0x35, 0x9f, 0x64, 0x7} DEFINE_GUID!{GUID_USB_WMI_NODE_INFO, 0x9c179357, 0xdc7a, 0x4f41, 0xb6, 0x6b, 0x32, 0x3b, 0x9d, 0xdc, 0xb5, 0xb1} DEFINE_GUID!{GUID_USB_WMI_TRACING, 0x3a61881b, 0xb4e6, 0x4bf9, 0xae, 0xf, 0x3c, 0xd8, 0xf3, 0x94, 0xe5, 0x2f} DEFINE_GUID!{GUID_USB_TRANSFER_TRACING, 0x681eb8aa, 0x403d, 0x452c, 0x9f, 0x8a, 0xf0, 0x61, 0x6f, 0xac, 0x95, 0x40} DEFINE_GUID!{GUID_USB_PERFORMANCE_TRACING, 0xd5de77a6, 0x6ae9, 0x425c, 0xb1, 0xe2, 0xf5, 0x61, 0x5f, 0xd3, 0x48, 0xa9} DEFINE_GUID!{GUID_USB_WMI_SURPRISE_REMOVAL_NOTIFICATION, 0x9bbbf831, 0xa2f2, 0x43b4, 0x96, 0xd1, 0x86, 0x94, 0x4b, 0x59, 0x14, 0xb3} pub const GUID_CLASS_USBHUB: GUID = GUID_DEVINTERFACE_USB_HUB; pub const GUID_CLASS_USB_DEVICE: GUID = GUID_DEVINTERFACE_USB_DEVICE; pub const GUID_CLASS_USB_HOST_CONTROLLER: GUID = GUID_DEVINTERFACE_USB_HOST_CONTROLLER; pub const FILE_DEVICE_USB: ULONG = FILE_DEVICE_UNKNOWN; #[inline] pub fn USB_CTL(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL(id: ULONG) -> ULONG {
#[inline] pub fn USB_KERNEL_CTL_BUFFERED(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } // No calling convention was specified in the code FN!{stdcall USB_IDLE_CALLBACK( Context: PVOID, ) -> ()} STRUCT!{struct USB_IDLE_CALLBACK_INFO { IdleCallback: USB_IDLE_CALLBACK, IdleContext: PVOID, }} pub type PUSB_IDLE_CALLBACK_INFO = *mut USB_IDLE_CALLBACK_INFO;
CTL_CODE!(FILE_DEVICE_USB, id, METHOD_NEITHER, FILE_ANY_ACCESS) }
identifier_body
web.py
import busbus from busbus.entity import BaseEntityJSONEncoder from busbus.provider import ProviderBase from busbus.queryable import Queryable import cherrypy import collections import itertools import types def json_handler(*args, **kwargs): value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) return BaseEntityJSONEncoder().encode(value).encode('utf-8') cherrypy.config['tools.json_out.handler'] = json_handler EXPAND_TYPES = { 'providers': ProviderBase, 'agencies': busbus.Agency, 'stops': busbus.Stop, 'routes': busbus.Route, 'arrivals': busbus.Arrival, } def unexpand_init(result, to_expand): return ({attr: unexpand(value, to_expand) for attr, value in dict(obj).items()} for obj in result) def unexpand(obj, to_expand): for name, cls in EXPAND_TYPES.items(): if isinstance(obj, cls): if name not in to_expand: return {'id': obj.id} else: return {attr: unexpand(value, to_expand) for attr, value in dict(obj).items()} if isinstance(obj, dict): return {attr: unexpand(value, to_expand) for attr, value in obj.items()} if isinstance(obj, (list, tuple, collections.Iterator)): return (unexpand(value, to_expand) for value in obj) return obj class APIError(Exception): def __init__(self, msg, error_code=500): self.msg = msg self.error_code = error_code class EndpointNotFoundError(APIError): def __init__(self, entity, action=None): super(EndpointNotFoundError, self).__init__( 'Endpoint /{0} not found'.format( entity + '/' + action if action else entity), 404) class Engine(busbus.Engine): def __init__(self, *args, **kwargs): # perhaps fix this to use a decorator somehow? self._entity_actions = { ('stops', 'find'): (self.stops_find, 'stops'), ('routes', 'directions'): (self.routes_directions, 'directions'), } super(Engine, self).__init__(*args, **kwargs) @cherrypy.popargs('entity', 'action') @cherrypy.expose @cherrypy.tools.json_out() def default(self, entity=None, action=None, **kwargs): if entity is None: return self.help() response = { 'request': { 'status': 'ok', 'entity': entity, 'params': kwargs, } } try: to_expand = (kwargs.pop('_expand').split(',') if '_expand' in kwargs else []) if to_expand: response['request']['expand'] = to_expand limit = kwargs.pop('_limit', None) if limit: try: limit = int(limit) if limit <= 0: raise ValueError() except ValueError: raise APIError('_limit must be a positive integer', 422) response['request']['limit'] = limit if 'realtime' in kwargs: if kwargs['realtime'] in ('y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON'): kwargs['realtime'] = True elif kwargs['realtime'] in ('n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF'): kwargs['realtime'] = False else: raise APIError('realtime is not a boolean', 422) if action: response['request']['action'] = action if (entity, action) in self._entity_actions: func, entity = self._entity_actions[(entity, action)] result = func(**kwargs) else: raise EndpointNotFoundError(entity, action) else: if 'provider.id' in kwargs: provider_id = kwargs.pop('provider.id') if provider_id in self._providers: provider = self._providers[provider_id] entity_func = getattr(provider, entity, None) else: entity_func = Queryable(()) else: entity_func = getattr(self, entity, None) if entity_func is not None: result = entity_func.where(**kwargs) else: raise EndpointNotFoundError(entity) if limit: result = itertools.islice(result, limit) response[entity] = unexpand_init(result, to_expand) except APIError as exc: response['request']['status'] = 'error' response['error'] = exc.msg cherrypy.response.status = exc.error_code return response def help(self): return { 'request': { 'status': 'help', }, '_entities': EXPAND_TYPES.keys(), '_actions': self._entity_actions.keys(), } def stops_find(self, **kwargs): expected = ('latitude', 'longitude', 'distance') if all(x in kwargs for x in expected): for x in expected: kwargs[x] = float(kwargs[x]) latlon = (kwargs['latitude'], kwargs['longitude']) return super(Engine, self).stops.where( lambda s: s.distance_to(latlon) <= kwargs['distance']) else:
def routes_directions(self, **kwargs): expected = ('route.id', 'provider.id') missing = [x for x in expected if x not in kwargs] if missing: raise APIError('missing attributes: ' + ','.join(missing), 422) provider = self._providers[kwargs['provider.id']] route = provider.get(busbus.Route, kwargs['route.id']) return route.directions
raise APIError('missing attributes: ' + ','.join( x for x in expected if x not in kwargs), 422)
conditional_block
web.py
import busbus from busbus.entity import BaseEntityJSONEncoder from busbus.provider import ProviderBase from busbus.queryable import Queryable import cherrypy import collections import itertools import types def json_handler(*args, **kwargs): value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) return BaseEntityJSONEncoder().encode(value).encode('utf-8') cherrypy.config['tools.json_out.handler'] = json_handler EXPAND_TYPES = { 'providers': ProviderBase, 'agencies': busbus.Agency, 'stops': busbus.Stop, 'routes': busbus.Route, 'arrivals': busbus.Arrival, } def unexpand_init(result, to_expand): return ({attr: unexpand(value, to_expand) for attr, value in dict(obj).items()} for obj in result) def unexpand(obj, to_expand): for name, cls in EXPAND_TYPES.items(): if isinstance(obj, cls): if name not in to_expand: return {'id': obj.id} else: return {attr: unexpand(value, to_expand) for attr, value in dict(obj).items()} if isinstance(obj, dict): return {attr: unexpand(value, to_expand) for attr, value in obj.items()} if isinstance(obj, (list, tuple, collections.Iterator)): return (unexpand(value, to_expand) for value in obj) return obj class APIError(Exception): def __init__(self, msg, error_code=500): self.msg = msg self.error_code = error_code class EndpointNotFoundError(APIError): def __init__(self, entity, action=None): super(EndpointNotFoundError, self).__init__( 'Endpoint /{0} not found'.format( entity + '/' + action if action else entity), 404) class Engine(busbus.Engine): def __init__(self, *args, **kwargs): # perhaps fix this to use a decorator somehow? self._entity_actions = { ('stops', 'find'): (self.stops_find, 'stops'), ('routes', 'directions'): (self.routes_directions, 'directions'), } super(Engine, self).__init__(*args, **kwargs) @cherrypy.popargs('entity', 'action') @cherrypy.expose @cherrypy.tools.json_out() def default(self, entity=None, action=None, **kwargs):
def help(self): return { 'request': { 'status': 'help', }, '_entities': EXPAND_TYPES.keys(), '_actions': self._entity_actions.keys(), } def stops_find(self, **kwargs): expected = ('latitude', 'longitude', 'distance') if all(x in kwargs for x in expected): for x in expected: kwargs[x] = float(kwargs[x]) latlon = (kwargs['latitude'], kwargs['longitude']) return super(Engine, self).stops.where( lambda s: s.distance_to(latlon) <= kwargs['distance']) else: raise APIError('missing attributes: ' + ','.join( x for x in expected if x not in kwargs), 422) def routes_directions(self, **kwargs): expected = ('route.id', 'provider.id') missing = [x for x in expected if x not in kwargs] if missing: raise APIError('missing attributes: ' + ','.join(missing), 422) provider = self._providers[kwargs['provider.id']] route = provider.get(busbus.Route, kwargs['route.id']) return route.directions
if entity is None: return self.help() response = { 'request': { 'status': 'ok', 'entity': entity, 'params': kwargs, } } try: to_expand = (kwargs.pop('_expand').split(',') if '_expand' in kwargs else []) if to_expand: response['request']['expand'] = to_expand limit = kwargs.pop('_limit', None) if limit: try: limit = int(limit) if limit <= 0: raise ValueError() except ValueError: raise APIError('_limit must be a positive integer', 422) response['request']['limit'] = limit if 'realtime' in kwargs: if kwargs['realtime'] in ('y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON'): kwargs['realtime'] = True elif kwargs['realtime'] in ('n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF'): kwargs['realtime'] = False else: raise APIError('realtime is not a boolean', 422) if action: response['request']['action'] = action if (entity, action) in self._entity_actions: func, entity = self._entity_actions[(entity, action)] result = func(**kwargs) else: raise EndpointNotFoundError(entity, action) else: if 'provider.id' in kwargs: provider_id = kwargs.pop('provider.id') if provider_id in self._providers: provider = self._providers[provider_id] entity_func = getattr(provider, entity, None) else: entity_func = Queryable(()) else: entity_func = getattr(self, entity, None) if entity_func is not None: result = entity_func.where(**kwargs) else: raise EndpointNotFoundError(entity) if limit: result = itertools.islice(result, limit) response[entity] = unexpand_init(result, to_expand) except APIError as exc: response['request']['status'] = 'error' response['error'] = exc.msg cherrypy.response.status = exc.error_code return response
identifier_body
web.py
import busbus from busbus.entity import BaseEntityJSONEncoder from busbus.provider import ProviderBase from busbus.queryable import Queryable import cherrypy import collections import itertools import types def json_handler(*args, **kwargs): value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) return BaseEntityJSONEncoder().encode(value).encode('utf-8') cherrypy.config['tools.json_out.handler'] = json_handler EXPAND_TYPES = { 'providers': ProviderBase, 'agencies': busbus.Agency, 'stops': busbus.Stop, 'routes': busbus.Route, 'arrivals': busbus.Arrival, } def unexpand_init(result, to_expand): return ({attr: unexpand(value, to_expand) for attr, value in dict(obj).items()} for obj in result) def unexpand(obj, to_expand): for name, cls in EXPAND_TYPES.items(): if isinstance(obj, cls): if name not in to_expand: return {'id': obj.id} else: return {attr: unexpand(value, to_expand) for attr, value in dict(obj).items()} if isinstance(obj, dict): return {attr: unexpand(value, to_expand) for attr, value in obj.items()} if isinstance(obj, (list, tuple, collections.Iterator)): return (unexpand(value, to_expand) for value in obj) return obj class APIError(Exception): def __init__(self, msg, error_code=500): self.msg = msg self.error_code = error_code class EndpointNotFoundError(APIError): def __init__(self, entity, action=None): super(EndpointNotFoundError, self).__init__( 'Endpoint /{0} not found'.format( entity + '/' + action if action else entity), 404) class Engine(busbus.Engine): def __init__(self, *args, **kwargs): # perhaps fix this to use a decorator somehow? self._entity_actions = { ('stops', 'find'): (self.stops_find, 'stops'), ('routes', 'directions'): (self.routes_directions, 'directions'), } super(Engine, self).__init__(*args, **kwargs) @cherrypy.popargs('entity', 'action') @cherrypy.expose @cherrypy.tools.json_out() def default(self, entity=None, action=None, **kwargs): if entity is None: return self.help() response = { 'request': { 'status': 'ok', 'entity': entity, 'params': kwargs, } } try: to_expand = (kwargs.pop('_expand').split(',') if '_expand' in kwargs else []) if to_expand: response['request']['expand'] = to_expand limit = kwargs.pop('_limit', None) if limit: try: limit = int(limit) if limit <= 0: raise ValueError() except ValueError: raise APIError('_limit must be a positive integer', 422) response['request']['limit'] = limit if 'realtime' in kwargs: if kwargs['realtime'] in ('y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON'): kwargs['realtime'] = True elif kwargs['realtime'] in ('n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF'): kwargs['realtime'] = False else: raise APIError('realtime is not a boolean', 422) if action:
response['request']['action'] = action if (entity, action) in self._entity_actions: func, entity = self._entity_actions[(entity, action)] result = func(**kwargs) else: raise EndpointNotFoundError(entity, action) else: if 'provider.id' in kwargs: provider_id = kwargs.pop('provider.id') if provider_id in self._providers: provider = self._providers[provider_id] entity_func = getattr(provider, entity, None) else: entity_func = Queryable(()) else: entity_func = getattr(self, entity, None) if entity_func is not None: result = entity_func.where(**kwargs) else: raise EndpointNotFoundError(entity) if limit: result = itertools.islice(result, limit) response[entity] = unexpand_init(result, to_expand) except APIError as exc: response['request']['status'] = 'error' response['error'] = exc.msg cherrypy.response.status = exc.error_code return response def help(self): return { 'request': { 'status': 'help', }, '_entities': EXPAND_TYPES.keys(), '_actions': self._entity_actions.keys(), } def stops_find(self, **kwargs): expected = ('latitude', 'longitude', 'distance') if all(x in kwargs for x in expected): for x in expected: kwargs[x] = float(kwargs[x]) latlon = (kwargs['latitude'], kwargs['longitude']) return super(Engine, self).stops.where( lambda s: s.distance_to(latlon) <= kwargs['distance']) else: raise APIError('missing attributes: ' + ','.join( x for x in expected if x not in kwargs), 422) def routes_directions(self, **kwargs): expected = ('route.id', 'provider.id') missing = [x for x in expected if x not in kwargs] if missing: raise APIError('missing attributes: ' + ','.join(missing), 422) provider = self._providers[kwargs['provider.id']] route = provider.get(busbus.Route, kwargs['route.id']) return route.directions
random_line_split
web.py
import busbus from busbus.entity import BaseEntityJSONEncoder from busbus.provider import ProviderBase from busbus.queryable import Queryable import cherrypy import collections import itertools import types def json_handler(*args, **kwargs): value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) return BaseEntityJSONEncoder().encode(value).encode('utf-8') cherrypy.config['tools.json_out.handler'] = json_handler EXPAND_TYPES = { 'providers': ProviderBase, 'agencies': busbus.Agency, 'stops': busbus.Stop, 'routes': busbus.Route, 'arrivals': busbus.Arrival, } def unexpand_init(result, to_expand): return ({attr: unexpand(value, to_expand) for attr, value in dict(obj).items()} for obj in result) def unexpand(obj, to_expand): for name, cls in EXPAND_TYPES.items(): if isinstance(obj, cls): if name not in to_expand: return {'id': obj.id} else: return {attr: unexpand(value, to_expand) for attr, value in dict(obj).items()} if isinstance(obj, dict): return {attr: unexpand(value, to_expand) for attr, value in obj.items()} if isinstance(obj, (list, tuple, collections.Iterator)): return (unexpand(value, to_expand) for value in obj) return obj class APIError(Exception): def __init__(self, msg, error_code=500): self.msg = msg self.error_code = error_code class EndpointNotFoundError(APIError): def __init__(self, entity, action=None): super(EndpointNotFoundError, self).__init__( 'Endpoint /{0} not found'.format( entity + '/' + action if action else entity), 404) class Engine(busbus.Engine): def __init__(self, *args, **kwargs): # perhaps fix this to use a decorator somehow? self._entity_actions = { ('stops', 'find'): (self.stops_find, 'stops'), ('routes', 'directions'): (self.routes_directions, 'directions'), } super(Engine, self).__init__(*args, **kwargs) @cherrypy.popargs('entity', 'action') @cherrypy.expose @cherrypy.tools.json_out() def default(self, entity=None, action=None, **kwargs): if entity is None: return self.help() response = { 'request': { 'status': 'ok', 'entity': entity, 'params': kwargs, } } try: to_expand = (kwargs.pop('_expand').split(',') if '_expand' in kwargs else []) if to_expand: response['request']['expand'] = to_expand limit = kwargs.pop('_limit', None) if limit: try: limit = int(limit) if limit <= 0: raise ValueError() except ValueError: raise APIError('_limit must be a positive integer', 422) response['request']['limit'] = limit if 'realtime' in kwargs: if kwargs['realtime'] in ('y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON'): kwargs['realtime'] = True elif kwargs['realtime'] in ('n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF'): kwargs['realtime'] = False else: raise APIError('realtime is not a boolean', 422) if action: response['request']['action'] = action if (entity, action) in self._entity_actions: func, entity = self._entity_actions[(entity, action)] result = func(**kwargs) else: raise EndpointNotFoundError(entity, action) else: if 'provider.id' in kwargs: provider_id = kwargs.pop('provider.id') if provider_id in self._providers: provider = self._providers[provider_id] entity_func = getattr(provider, entity, None) else: entity_func = Queryable(()) else: entity_func = getattr(self, entity, None) if entity_func is not None: result = entity_func.where(**kwargs) else: raise EndpointNotFoundError(entity) if limit: result = itertools.islice(result, limit) response[entity] = unexpand_init(result, to_expand) except APIError as exc: response['request']['status'] = 'error' response['error'] = exc.msg cherrypy.response.status = exc.error_code return response def help(self): return { 'request': { 'status': 'help', }, '_entities': EXPAND_TYPES.keys(), '_actions': self._entity_actions.keys(), } def stops_find(self, **kwargs): expected = ('latitude', 'longitude', 'distance') if all(x in kwargs for x in expected): for x in expected: kwargs[x] = float(kwargs[x]) latlon = (kwargs['latitude'], kwargs['longitude']) return super(Engine, self).stops.where( lambda s: s.distance_to(latlon) <= kwargs['distance']) else: raise APIError('missing attributes: ' + ','.join( x for x in expected if x not in kwargs), 422) def
(self, **kwargs): expected = ('route.id', 'provider.id') missing = [x for x in expected if x not in kwargs] if missing: raise APIError('missing attributes: ' + ','.join(missing), 422) provider = self._providers[kwargs['provider.id']] route = provider.get(busbus.Route, kwargs['route.id']) return route.directions
routes_directions
identifier_name
macros.rs
// Bloom // // HTTP REST API caching middleware // Copyright: 2017, Valerian Saliou <valerian@valeriansaliou.name> // License: Mozilla Public License v2.0 (MPL v2.0) macro_rules! get_cache_store_client_try { ($pool:expr, $error:expr, $client:ident $code:block) => { // In the event of a Redis failure, 'try_get' allows a full pass-through to be performed, \ // thus ensuring service continuity with degraded performance. If 'get' was used there, \ // performing as many pool 'get' as the pool size would incur a synchronous locking, \ // which would wait forever until the Redis connection is restored (this is dangerous). match $pool.try_get() { Some(mut $client) => $code, None => { error!("failed getting a cache store client from pool (try mode)"); Err($error) } } }; } macro_rules! get_cache_store_client_wait { ($pool:expr, $error:expr, $client:ident $code:block) => { // 'get' is used as an alternative to 'try_get', when there is no choice but to ensure \
// an operation succeeds (eg. for cache purges). match $pool.get() { Ok(mut $client) => $code, Err(err) => { error!( "failed getting a cache store client from pool (wait mode), because: {}", err ); Err($error) } } }; }
random_line_split
empty_paragraph_end.py
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension):
def start_program(self, program): self.program = program def end_program(self, _): self.program = None def start_section(self, section): last_paragraph = section.get_children()[-1] if 'paragraph' == last_paragraph.get_kind(): children = last_paragraph.get_children() if len(children) > 1: # violation test_ko2 self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) elif len(children) == 1: kind = children[0].get_kind() if kind not in ['exit', 'stop_run', 'goback']: self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) else: # violation test_ko1 self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position())
def __init__(self): self.program = None
random_line_split
empty_paragraph_end.py
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension): def __init__(self): self.program = None def start_program(self, program): self.program = program def
(self, _): self.program = None def start_section(self, section): last_paragraph = section.get_children()[-1] if 'paragraph' == last_paragraph.get_kind(): children = last_paragraph.get_children() if len(children) > 1: # violation test_ko2 self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) elif len(children) == 1: kind = children[0].get_kind() if kind not in ['exit', 'stop_run', 'goback']: self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) else: # violation test_ko1 self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position())
end_program
identifier_name
empty_paragraph_end.py
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension):
def __init__(self): self.program = None def start_program(self, program): self.program = program def end_program(self, _): self.program = None def start_section(self, section): last_paragraph = section.get_children()[-1] if 'paragraph' == last_paragraph.get_kind(): children = last_paragraph.get_children() if len(children) > 1: # violation test_ko2 self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) elif len(children) == 1: kind = children[0].get_kind() if kind not in ['exit', 'stop_run', 'goback']: self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) else: # violation test_ko1 self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position())
identifier_body
empty_paragraph_end.py
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension): def __init__(self): self.program = None def start_program(self, program): self.program = program def end_program(self, _): self.program = None def start_section(self, section): last_paragraph = section.get_children()[-1] if 'paragraph' == last_paragraph.get_kind(): children = last_paragraph.get_children() if len(children) > 1: # violation test_ko2
elif len(children) == 1: kind = children[0].get_kind() if kind not in ['exit', 'stop_run', 'goback']: self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) else: # violation test_ko1 self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position())
self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position())
conditional_block
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func; match init_func() { ErrorCode::Success => { debug!("Plugin has been loaded: {:?}", library); } _ => { error!("Plugin has not been loaded: {:?}", library); std::process::exit(123); } } } else
} } else { error!("Plugin not found: {:?}", library); std::process::exit(123); } }); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "android"))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::Library::new(library) }
{ error!("Init function not found: {:?}", initializer); std::process::exit(123); }
conditional_block
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func; match init_func() { ErrorCode::Success => { debug!("Plugin has been loaded: {:?}", library); } _ => { error!("Plugin has not been loaded: {:?}", library); std::process::exit(123); } } } else { error!("Init function not found: {:?}", initializer); std::process::exit(123); }
}); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "android"))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::Library::new(library) }
} } else { error!("Plugin not found: {:?}", library); std::process::exit(123); }
random_line_split
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn
(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func; match init_func() { ErrorCode::Success => { debug!("Plugin has been loaded: {:?}", library); } _ => { error!("Plugin has not been loaded: {:?}", library); std::process::exit(123); } } } else { error!("Init function not found: {:?}", initializer); std::process::exit(123); } } } else { error!("Plugin not found: {:?}", library); std::process::exit(123); } }); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "android"))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::Library::new(library) }
init_plugin
identifier_name
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { let init_func: libloading::Symbol<unsafe extern fn() -> ErrorCode> = init_func; match init_func() { ErrorCode::Success => { debug!("Plugin has been loaded: {:?}", library); } _ => { error!("Plugin has not been loaded: {:?}", library); std::process::exit(123); } } } else { error!("Init function not found: {:?}", initializer); std::process::exit(123); } } } else { error!("Plugin not found: {:?}", library); std::process::exit(123); } }); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "android"))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library>
{ libloading::Library::new(library) }
identifier_body
index.js
"use strict"; var ArrayCollection_1 = require('./ArrayCollection'); exports.ArrayCollection = ArrayCollection_1.ArrayCollection; var ArrayList_1 = require('./ArrayList'); exports.ArrayList = ArrayList_1.ArrayList; var SequenceBase_1 = require('./SequenceBase'); exports.SequenceBase = SequenceBase_1.SequenceBase; var Buckets_1 = require('./Buckets'); exports.Buckets = Buckets_1.Buckets; var Collection_1 = require('./Collection'); exports.Collection = Collection_1.Collection; var Dictionary_1 = require('./Dictionary'); exports.Dictionary = Dictionary_1.Dictionary; exports.Pair = Dictionary_1.Pair; var Hash_1 = require('./Hash'); exports.HashFunc = Hash_1.HashFunc; exports.DefaultHashFunc = Hash_1.DefaultHashFunc; var HashSet_1 = require('./HashSet'); exports.HashSet = HashSet_1.HashSet;
var Iterable_1 = require('./Iterable'); exports.Iterable = Iterable_1.Iterable; var LinkedList_1 = require('./LinkedList'); exports.LinkedList = LinkedList_1.LinkedList; var Native_1 = require('./Native'); exports.NativeIndex = Native_1.NativeIndex; exports.NativeMap = Native_1.NativeMap; var Sequence_1 = require('./Sequence'); exports.Sequence = Sequence_1.Sequence; var Stack_1 = require('./Stack'); exports.Stack = Stack_1.Stack; var Util_1 = require('./Util'); exports.Util = Util_1.Util; //# sourceMappingURL=index.js.map
random_line_split
CppFiles.py
#!/usr/bin/env python # # @file CppFiles.py # @brief class for generating cpp files # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK) # and the University of Heidelberg (Germany), with support from the National # Institutes of Health (USA) under grant R01GM070923. All rights reserved. # # 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. # # Neither the name of the California Institute of Technology (Caltech), nor # of the European Bioinformatics Institute (EMBL-EBI), nor of the University # of Heidelberg, nor the names of any contributors, may be used to endorse # or promote products derived from this software without specific prior # written permission. # ------------------------------------------------------------------------ --> import copy from . import CppHeaderFile from . import CppCodeFile from util import strFunctions, query, global_variables class CppFiles(): """Class for all Cpp files""" def __init__(self, class_object, verbose=False): #Class_object info about sbml model # members from object self.class_object = class_object self.class_object['is_list_of'] = False self.class_object['sid_refs'] = \ query.get_sid_refs(class_object['attribs']) self.class_object['unit_sid_refs'] = \ query.get_sid_refs(class_object['attribs'], unit=True) self.verbose = verbose def write_files(self): self.write_header(self.class_object) self.write_code(self.class_object) if self.class_object['hasListOf']: lo_working_class = self.create_list_of_description() self.write_header(lo_working_class) self.write_code(lo_working_class) def write_header(self, class_desc): fileout = CppHeaderFile.CppHeaderFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def write_code(self, class_desc): fileout = CppCodeFile.CppCodeFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def
(self): # default list of name lo_name = strFunctions.list_of_name(self.class_object['name']) # check that we have not specified this should be different if 'lo_class_name' in self.class_object and \ len(self.class_object['lo_class_name']) > 0: lo_name = self.class_object['lo_class_name'] descrip = copy.deepcopy(self.class_object) descrip['is_list_of'] = True descrip['attribs'] = self.class_object['lo_attribs'] descrip['child_base_class'] = self.class_object['baseClass'] if global_variables.is_package: descrip['baseClass'] = 'ListOf' else: descrip['baseClass'] = strFunctions.prefix_name('ListOf') descrip['list_of_name'] = lo_name descrip['lo_child'] = self.class_object['name'] descrip['name'] = lo_name return descrip def test_func(self): self.write_files()
create_list_of_description
identifier_name
CppFiles.py
#!/usr/bin/env python # # @file CppFiles.py # @brief class for generating cpp files # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK) # and the University of Heidelberg (Germany), with support from the National # Institutes of Health (USA) under grant R01GM070923. All rights reserved. # # 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. # # Neither the name of the California Institute of Technology (Caltech), nor # of the European Bioinformatics Institute (EMBL-EBI), nor of the University # of Heidelberg, nor the names of any contributors, may be used to endorse # or promote products derived from this software without specific prior # written permission. # ------------------------------------------------------------------------ --> import copy from . import CppHeaderFile from . import CppCodeFile from util import strFunctions, query, global_variables class CppFiles(): """Class for all Cpp files""" def __init__(self, class_object, verbose=False): #Class_object info about sbml model # members from object self.class_object = class_object self.class_object['is_list_of'] = False self.class_object['sid_refs'] = \ query.get_sid_refs(class_object['attribs']) self.class_object['unit_sid_refs'] = \ query.get_sid_refs(class_object['attribs'], unit=True) self.verbose = verbose def write_files(self):
def write_header(self, class_desc): fileout = CppHeaderFile.CppHeaderFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def write_code(self, class_desc): fileout = CppCodeFile.CppCodeFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def create_list_of_description(self): # default list of name lo_name = strFunctions.list_of_name(self.class_object['name']) # check that we have not specified this should be different if 'lo_class_name' in self.class_object and \ len(self.class_object['lo_class_name']) > 0: lo_name = self.class_object['lo_class_name'] descrip = copy.deepcopy(self.class_object) descrip['is_list_of'] = True descrip['attribs'] = self.class_object['lo_attribs'] descrip['child_base_class'] = self.class_object['baseClass'] if global_variables.is_package: descrip['baseClass'] = 'ListOf' else: descrip['baseClass'] = strFunctions.prefix_name('ListOf') descrip['list_of_name'] = lo_name descrip['lo_child'] = self.class_object['name'] descrip['name'] = lo_name return descrip def test_func(self): self.write_files()
self.write_header(self.class_object) self.write_code(self.class_object) if self.class_object['hasListOf']: lo_working_class = self.create_list_of_description() self.write_header(lo_working_class) self.write_code(lo_working_class)
identifier_body
CppFiles.py
#!/usr/bin/env python # # @file CppFiles.py # @brief class for generating cpp files # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK) # and the University of Heidelberg (Germany), with support from the National # Institutes of Health (USA) under grant R01GM070923. All rights reserved. # # 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. # # Neither the name of the California Institute of Technology (Caltech), nor # of the European Bioinformatics Institute (EMBL-EBI), nor of the University # of Heidelberg, nor the names of any contributors, may be used to endorse # or promote products derived from this software without specific prior # written permission. # ------------------------------------------------------------------------ --> import copy from . import CppHeaderFile from . import CppCodeFile from util import strFunctions, query, global_variables class CppFiles(): """Class for all Cpp files""" def __init__(self, class_object, verbose=False): #Class_object info about sbml model # members from object self.class_object = class_object self.class_object['is_list_of'] = False self.class_object['sid_refs'] = \ query.get_sid_refs(class_object['attribs']) self.class_object['unit_sid_refs'] = \ query.get_sid_refs(class_object['attribs'], unit=True) self.verbose = verbose def write_files(self): self.write_header(self.class_object) self.write_code(self.class_object) if self.class_object['hasListOf']: lo_working_class = self.create_list_of_description() self.write_header(lo_working_class) self.write_code(lo_working_class) def write_header(self, class_desc): fileout = CppHeaderFile.CppHeaderFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def write_code(self, class_desc): fileout = CppCodeFile.CppCodeFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def create_list_of_description(self): # default list of name lo_name = strFunctions.list_of_name(self.class_object['name']) # check that we have not specified this should be different if 'lo_class_name' in self.class_object and \ len(self.class_object['lo_class_name']) > 0: lo_name = self.class_object['lo_class_name'] descrip = copy.deepcopy(self.class_object) descrip['is_list_of'] = True descrip['attribs'] = self.class_object['lo_attribs'] descrip['child_base_class'] = self.class_object['baseClass'] if global_variables.is_package:
else: descrip['baseClass'] = strFunctions.prefix_name('ListOf') descrip['list_of_name'] = lo_name descrip['lo_child'] = self.class_object['name'] descrip['name'] = lo_name return descrip def test_func(self): self.write_files()
descrip['baseClass'] = 'ListOf'
conditional_block
CppFiles.py
#!/usr/bin/env python # # @file CppFiles.py # @brief class for generating cpp files # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK) # and the University of Heidelberg (Germany), with support from the National # Institutes of Health (USA) under grant R01GM070923. All rights reserved. # # 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. # # Neither the name of the California Institute of Technology (Caltech), nor # of the European Bioinformatics Institute (EMBL-EBI), nor of the University # of Heidelberg, nor the names of any contributors, may be used to endorse # or promote products derived from this software without specific prior # written permission. # ------------------------------------------------------------------------ --> import copy from . import CppHeaderFile from . import CppCodeFile from util import strFunctions, query, global_variables class CppFiles(): """Class for all Cpp files""" def __init__(self, class_object, verbose=False): #Class_object info about sbml model # members from object self.class_object = class_object self.class_object['is_list_of'] = False self.class_object['sid_refs'] = \ query.get_sid_refs(class_object['attribs']) self.class_object['unit_sid_refs'] = \ query.get_sid_refs(class_object['attribs'], unit=True) self.verbose = verbose def write_files(self): self.write_header(self.class_object) self.write_code(self.class_object) if self.class_object['hasListOf']: lo_working_class = self.create_list_of_description() self.write_header(lo_working_class) self.write_code(lo_working_class) def write_header(self, class_desc): fileout = CppHeaderFile.CppHeaderFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def write_code(self, class_desc): fileout = CppCodeFile.CppCodeFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def create_list_of_description(self): # default list of name lo_name = strFunctions.list_of_name(self.class_object['name']) # check that we have not specified this should be different if 'lo_class_name' in self.class_object and \ len(self.class_object['lo_class_name']) > 0: lo_name = self.class_object['lo_class_name'] descrip = copy.deepcopy(self.class_object) descrip['is_list_of'] = True descrip['attribs'] = self.class_object['lo_attribs'] descrip['child_base_class'] = self.class_object['baseClass'] if global_variables.is_package: descrip['baseClass'] = 'ListOf' else: descrip['baseClass'] = strFunctions.prefix_name('ListOf') descrip['list_of_name'] = lo_name descrip['lo_child'] = self.class_object['name'] descrip['name'] = lo_name return descrip def test_func(self): self.write_files()
random_line_split
hooks.py
import os import sys import re from bento.compat \ import \ inspect as compat_inspect from bento.commands.core \ import \ command SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]") __HOOK_REGISTRY = {} __PRE_HOOK_REGISTRY = {} __POST_HOOK_REGISTRY = {} __COMMANDS_OVERRIDE = {} __INIT_FUNCS = {} def add_to_registry(func, category): global __HOOK_REGISTRY if not category in __HOOK_REGISTRY:
else: __HOOK_REGISTRY[category].append(func) def override_command(command, func): global __COMMANDS_OVERRIDE local_dir = os.path.dirname(compat_inspect.stack()[2][1]) if __COMMANDS_OVERRIDE.has_key(command): __COMMANDS_OVERRIDE[command].append((func, local_dir)) else: __COMMANDS_OVERRIDE[command] = [(func, local_dir)] def add_to_pre_registry(func, cmd_name): global __PRE_HOOK_REGISTRY if not cmd_name in __PRE_HOOK_REGISTRY: __PRE_HOOK_REGISTRY[cmd_name] = [func] else: __PRE_HOOK_REGISTRY[cmd_name].append(func) def add_to_post_registry(func, cmd_name): global __POST_HOOK_REGISTRY if not cmd_name in __POST_HOOK_REGISTRY: __POST_HOOK_REGISTRY[cmd_name] = [func] else: __POST_HOOK_REGISTRY[cmd_name].append(func) def get_registry_categories(): global __HOOK_REGISTRY return __HOOK_REGISTRY.keys() def get_registry_category(categorie): global __HOOK_REGISTRY return __HOOK_REGISTRY[categorie] def get_pre_hooks(cmd_name): global __PRE_HOOK_REGISTRY return __PRE_HOOK_REGISTRY.get(cmd_name, []) def get_post_hooks(cmd_name): global __POST_HOOK_REGISTRY return __POST_HOOK_REGISTRY.get(cmd_name, []) def get_command_override(cmd_name): global __COMMANDS_OVERRIDE return __COMMANDS_OVERRIDE.get(cmd_name, []) def _make_hook_decorator(command_name, kind): name = "%s_%s" % (kind, command_name) help_bypass = False def decorator(f): local_dir = os.path.dirname(compat_inspect.stack()[1][1]) add_to_registry((f, local_dir, help_bypass), name) if kind == "post": add_to_post_registry((f, local_dir, help_bypass), command_name) elif kind == "pre": add_to_pre_registry((f, local_dir, help_bypass), command_name) else: raise ValueError("invalid hook kind %s" % kind) return f return decorator post_configure = _make_hook_decorator("configure", "post") pre_configure = _make_hook_decorator("configure", "pre") post_build = _make_hook_decorator("build", "post") pre_build = _make_hook_decorator("build", "pre") post_sdist = _make_hook_decorator("sdist", "post") pre_sdist = _make_hook_decorator("sdist", "pre") def override(f): override_command(f.__name__, f) def options(f): __INIT_FUNCS["options"] = f return lambda context: f(context) def startup(f): __INIT_FUNCS["startup"] = f return lambda context: f(context) def shutdown(f): __INIT_FUNCS["shutdown"] = f return lambda context: f(context) def dummy_startup(ctx): pass def dummy_options(ctx): pass def dummy_shutdown(): pass def create_hook_module(target): import imp safe_name = SAFE_MODULE_NAME.sub("_", target, len(target)) module_name = "bento_hook_%s" % safe_name main_file = os.path.abspath(target) module = imp.new_module(module_name) module.__file__ = main_file code = open(main_file).read() sys.path.insert(0, os.path.dirname(main_file)) try: exec(compile(code, main_file, 'exec'), module.__dict__) sys.modules[module_name] = module finally: sys.path.pop(0) module.root_path = main_file if not "startup" in __INIT_FUNCS: module.startup = dummy_startup if not "options" in __INIT_FUNCS: module.options = dummy_options if not "shutdown" in __INIT_FUNCS: module.shutdown = dummy_shutdown return module
__HOOK_REGISTRY[category] = [func]
conditional_block
hooks.py
import os import sys import re from bento.compat \ import \ inspect as compat_inspect from bento.commands.core \ import \ command SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]") __HOOK_REGISTRY = {} __PRE_HOOK_REGISTRY = {} __POST_HOOK_REGISTRY = {} __COMMANDS_OVERRIDE = {} __INIT_FUNCS = {} def add_to_registry(func, category): global __HOOK_REGISTRY if not category in __HOOK_REGISTRY: __HOOK_REGISTRY[category] = [func] else: __HOOK_REGISTRY[category].append(func) def override_command(command, func): global __COMMANDS_OVERRIDE local_dir = os.path.dirname(compat_inspect.stack()[2][1]) if __COMMANDS_OVERRIDE.has_key(command): __COMMANDS_OVERRIDE[command].append((func, local_dir)) else: __COMMANDS_OVERRIDE[command] = [(func, local_dir)] def add_to_pre_registry(func, cmd_name): global __PRE_HOOK_REGISTRY if not cmd_name in __PRE_HOOK_REGISTRY: __PRE_HOOK_REGISTRY[cmd_name] = [func] else: __PRE_HOOK_REGISTRY[cmd_name].append(func) def add_to_post_registry(func, cmd_name): global __POST_HOOK_REGISTRY if not cmd_name in __POST_HOOK_REGISTRY: __POST_HOOK_REGISTRY[cmd_name] = [func] else: __POST_HOOK_REGISTRY[cmd_name].append(func) def get_registry_categories(): global __HOOK_REGISTRY return __HOOK_REGISTRY.keys() def get_registry_category(categorie): global __HOOK_REGISTRY return __HOOK_REGISTRY[categorie] def get_pre_hooks(cmd_name): global __PRE_HOOK_REGISTRY return __PRE_HOOK_REGISTRY.get(cmd_name, []) def
(cmd_name): global __POST_HOOK_REGISTRY return __POST_HOOK_REGISTRY.get(cmd_name, []) def get_command_override(cmd_name): global __COMMANDS_OVERRIDE return __COMMANDS_OVERRIDE.get(cmd_name, []) def _make_hook_decorator(command_name, kind): name = "%s_%s" % (kind, command_name) help_bypass = False def decorator(f): local_dir = os.path.dirname(compat_inspect.stack()[1][1]) add_to_registry((f, local_dir, help_bypass), name) if kind == "post": add_to_post_registry((f, local_dir, help_bypass), command_name) elif kind == "pre": add_to_pre_registry((f, local_dir, help_bypass), command_name) else: raise ValueError("invalid hook kind %s" % kind) return f return decorator post_configure = _make_hook_decorator("configure", "post") pre_configure = _make_hook_decorator("configure", "pre") post_build = _make_hook_decorator("build", "post") pre_build = _make_hook_decorator("build", "pre") post_sdist = _make_hook_decorator("sdist", "post") pre_sdist = _make_hook_decorator("sdist", "pre") def override(f): override_command(f.__name__, f) def options(f): __INIT_FUNCS["options"] = f return lambda context: f(context) def startup(f): __INIT_FUNCS["startup"] = f return lambda context: f(context) def shutdown(f): __INIT_FUNCS["shutdown"] = f return lambda context: f(context) def dummy_startup(ctx): pass def dummy_options(ctx): pass def dummy_shutdown(): pass def create_hook_module(target): import imp safe_name = SAFE_MODULE_NAME.sub("_", target, len(target)) module_name = "bento_hook_%s" % safe_name main_file = os.path.abspath(target) module = imp.new_module(module_name) module.__file__ = main_file code = open(main_file).read() sys.path.insert(0, os.path.dirname(main_file)) try: exec(compile(code, main_file, 'exec'), module.__dict__) sys.modules[module_name] = module finally: sys.path.pop(0) module.root_path = main_file if not "startup" in __INIT_FUNCS: module.startup = dummy_startup if not "options" in __INIT_FUNCS: module.options = dummy_options if not "shutdown" in __INIT_FUNCS: module.shutdown = dummy_shutdown return module
get_post_hooks
identifier_name
hooks.py
import os import sys import re from bento.compat \ import \ inspect as compat_inspect from bento.commands.core \ import \ command SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]") __HOOK_REGISTRY = {} __PRE_HOOK_REGISTRY = {} __POST_HOOK_REGISTRY = {} __COMMANDS_OVERRIDE = {} __INIT_FUNCS = {} def add_to_registry(func, category): global __HOOK_REGISTRY if not category in __HOOK_REGISTRY: __HOOK_REGISTRY[category] = [func] else: __HOOK_REGISTRY[category].append(func) def override_command(command, func): global __COMMANDS_OVERRIDE local_dir = os.path.dirname(compat_inspect.stack()[2][1]) if __COMMANDS_OVERRIDE.has_key(command): __COMMANDS_OVERRIDE[command].append((func, local_dir)) else: __COMMANDS_OVERRIDE[command] = [(func, local_dir)] def add_to_pre_registry(func, cmd_name): global __PRE_HOOK_REGISTRY if not cmd_name in __PRE_HOOK_REGISTRY: __PRE_HOOK_REGISTRY[cmd_name] = [func] else: __PRE_HOOK_REGISTRY[cmd_name].append(func) def add_to_post_registry(func, cmd_name): global __POST_HOOK_REGISTRY
else: __POST_HOOK_REGISTRY[cmd_name].append(func) def get_registry_categories(): global __HOOK_REGISTRY return __HOOK_REGISTRY.keys() def get_registry_category(categorie): global __HOOK_REGISTRY return __HOOK_REGISTRY[categorie] def get_pre_hooks(cmd_name): global __PRE_HOOK_REGISTRY return __PRE_HOOK_REGISTRY.get(cmd_name, []) def get_post_hooks(cmd_name): global __POST_HOOK_REGISTRY return __POST_HOOK_REGISTRY.get(cmd_name, []) def get_command_override(cmd_name): global __COMMANDS_OVERRIDE return __COMMANDS_OVERRIDE.get(cmd_name, []) def _make_hook_decorator(command_name, kind): name = "%s_%s" % (kind, command_name) help_bypass = False def decorator(f): local_dir = os.path.dirname(compat_inspect.stack()[1][1]) add_to_registry((f, local_dir, help_bypass), name) if kind == "post": add_to_post_registry((f, local_dir, help_bypass), command_name) elif kind == "pre": add_to_pre_registry((f, local_dir, help_bypass), command_name) else: raise ValueError("invalid hook kind %s" % kind) return f return decorator post_configure = _make_hook_decorator("configure", "post") pre_configure = _make_hook_decorator("configure", "pre") post_build = _make_hook_decorator("build", "post") pre_build = _make_hook_decorator("build", "pre") post_sdist = _make_hook_decorator("sdist", "post") pre_sdist = _make_hook_decorator("sdist", "pre") def override(f): override_command(f.__name__, f) def options(f): __INIT_FUNCS["options"] = f return lambda context: f(context) def startup(f): __INIT_FUNCS["startup"] = f return lambda context: f(context) def shutdown(f): __INIT_FUNCS["shutdown"] = f return lambda context: f(context) def dummy_startup(ctx): pass def dummy_options(ctx): pass def dummy_shutdown(): pass def create_hook_module(target): import imp safe_name = SAFE_MODULE_NAME.sub("_", target, len(target)) module_name = "bento_hook_%s" % safe_name main_file = os.path.abspath(target) module = imp.new_module(module_name) module.__file__ = main_file code = open(main_file).read() sys.path.insert(0, os.path.dirname(main_file)) try: exec(compile(code, main_file, 'exec'), module.__dict__) sys.modules[module_name] = module finally: sys.path.pop(0) module.root_path = main_file if not "startup" in __INIT_FUNCS: module.startup = dummy_startup if not "options" in __INIT_FUNCS: module.options = dummy_options if not "shutdown" in __INIT_FUNCS: module.shutdown = dummy_shutdown return module
if not cmd_name in __POST_HOOK_REGISTRY: __POST_HOOK_REGISTRY[cmd_name] = [func]
random_line_split
hooks.py
import os import sys import re from bento.compat \ import \ inspect as compat_inspect from bento.commands.core \ import \ command SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]") __HOOK_REGISTRY = {} __PRE_HOOK_REGISTRY = {} __POST_HOOK_REGISTRY = {} __COMMANDS_OVERRIDE = {} __INIT_FUNCS = {} def add_to_registry(func, category): global __HOOK_REGISTRY if not category in __HOOK_REGISTRY: __HOOK_REGISTRY[category] = [func] else: __HOOK_REGISTRY[category].append(func) def override_command(command, func): global __COMMANDS_OVERRIDE local_dir = os.path.dirname(compat_inspect.stack()[2][1]) if __COMMANDS_OVERRIDE.has_key(command): __COMMANDS_OVERRIDE[command].append((func, local_dir)) else: __COMMANDS_OVERRIDE[command] = [(func, local_dir)] def add_to_pre_registry(func, cmd_name): global __PRE_HOOK_REGISTRY if not cmd_name in __PRE_HOOK_REGISTRY: __PRE_HOOK_REGISTRY[cmd_name] = [func] else: __PRE_HOOK_REGISTRY[cmd_name].append(func) def add_to_post_registry(func, cmd_name):
def get_registry_categories(): global __HOOK_REGISTRY return __HOOK_REGISTRY.keys() def get_registry_category(categorie): global __HOOK_REGISTRY return __HOOK_REGISTRY[categorie] def get_pre_hooks(cmd_name): global __PRE_HOOK_REGISTRY return __PRE_HOOK_REGISTRY.get(cmd_name, []) def get_post_hooks(cmd_name): global __POST_HOOK_REGISTRY return __POST_HOOK_REGISTRY.get(cmd_name, []) def get_command_override(cmd_name): global __COMMANDS_OVERRIDE return __COMMANDS_OVERRIDE.get(cmd_name, []) def _make_hook_decorator(command_name, kind): name = "%s_%s" % (kind, command_name) help_bypass = False def decorator(f): local_dir = os.path.dirname(compat_inspect.stack()[1][1]) add_to_registry((f, local_dir, help_bypass), name) if kind == "post": add_to_post_registry((f, local_dir, help_bypass), command_name) elif kind == "pre": add_to_pre_registry((f, local_dir, help_bypass), command_name) else: raise ValueError("invalid hook kind %s" % kind) return f return decorator post_configure = _make_hook_decorator("configure", "post") pre_configure = _make_hook_decorator("configure", "pre") post_build = _make_hook_decorator("build", "post") pre_build = _make_hook_decorator("build", "pre") post_sdist = _make_hook_decorator("sdist", "post") pre_sdist = _make_hook_decorator("sdist", "pre") def override(f): override_command(f.__name__, f) def options(f): __INIT_FUNCS["options"] = f return lambda context: f(context) def startup(f): __INIT_FUNCS["startup"] = f return lambda context: f(context) def shutdown(f): __INIT_FUNCS["shutdown"] = f return lambda context: f(context) def dummy_startup(ctx): pass def dummy_options(ctx): pass def dummy_shutdown(): pass def create_hook_module(target): import imp safe_name = SAFE_MODULE_NAME.sub("_", target, len(target)) module_name = "bento_hook_%s" % safe_name main_file = os.path.abspath(target) module = imp.new_module(module_name) module.__file__ = main_file code = open(main_file).read() sys.path.insert(0, os.path.dirname(main_file)) try: exec(compile(code, main_file, 'exec'), module.__dict__) sys.modules[module_name] = module finally: sys.path.pop(0) module.root_path = main_file if not "startup" in __INIT_FUNCS: module.startup = dummy_startup if not "options" in __INIT_FUNCS: module.options = dummy_options if not "shutdown" in __INIT_FUNCS: module.shutdown = dummy_shutdown return module
global __POST_HOOK_REGISTRY if not cmd_name in __POST_HOOK_REGISTRY: __POST_HOOK_REGISTRY[cmd_name] = [func] else: __POST_HOOK_REGISTRY[cmd_name].append(func)
identifier_body
NearbyGalleryCard.tsx
import { ContextModule } from "@artsy/cohesion" import { Box, BoxProps, ResponsiveBox, Image, Flex, Text } from "@artsy/palette" import { capitalize, compact, uniq } from "lodash" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import { RouterLink } from "v2/System/Router/RouterLink" import { FollowProfileButtonFragmentContainer } from "v2/Components/FollowButton/FollowProfileButton" import { NearbyGalleryCard_partner } from "v2/__generated__/NearbyGalleryCard_partner.graphql" interface NearbyGalleryCardProps extends BoxProps { partner: NearbyGalleryCard_partner city?: string | null } function normalizeCityName(city: string) { return capitalize(city.trim()) } function getLocation(cities: Array<string>, preferredCity?: string | null) { let location if (cities.length > 0)
return location } const NearbyGalleryCard: React.FC<NearbyGalleryCardProps> = ({ partner, city, ...rest }) => { const { user } = useSystemContext() if (!partner) { return null } const { name, slug, profile, type, locationsConnection } = partner const canFollow = type !== "Auction House" const image = partner?.profile?.image?.cropped const partnerHref = `/partner/${slug}` const cities = uniq( compact( locationsConnection?.edges?.map(location => location?.node?.city ? normalizeCityName(location?.node?.city) : location?.node?.displayCountry ) ) ) const location = getLocation(cities, city) return ( <Box {...rest}> <ResponsiveBox bg="black10" aspectHeight={3} aspectWidth={4} maxWidth="100%" > <RouterLink to={partnerHref}> {image && ( <Image lazyLoad src={image.src} srcSet={image.srcSet} width="100%" height="100%" /> )} </RouterLink> </ResponsiveBox> <Flex justifyContent="space-between" mt={1}> <Box> <RouterLink noUnderline to={partnerHref}> <Text variant="subtitle">{name}</Text> {location && <Text color="black60">{location}</Text>} </RouterLink> </Box> {canFollow && !!profile && ( <FollowProfileButtonFragmentContainer profile={profile} user={user} contextModule={ContextModule.partnerHeader} buttonProps={{ size: "small", variant: "secondaryOutline", }} /> )} </Flex> </Box> ) } export const NearbyGalleryCardFragmentContainer = createFragmentContainer( NearbyGalleryCard, { partner: graphql` fragment NearbyGalleryCard_partner on Partner { name slug type profile { image { cropped(height: 300, width: 400, version: "wide") { src srcSet } } ...FollowProfileButton_profile } locationsConnection(first: 20) { edges { node { city displayCountry } } } } `, } )
{ const normalizedPreferredCity = preferredCity && normalizeCityName(preferredCity) if (cities.some(c => c === normalizedPreferredCity)) { location = normalizedPreferredCity } else { location = cities[0] } if (cities.length > 1) { location += ` & ${cities.length - 1} other location` if (cities.length > 2) { location += "s" } } }
conditional_block
NearbyGalleryCard.tsx
import { ContextModule } from "@artsy/cohesion" import { Box, BoxProps, ResponsiveBox, Image, Flex, Text } from "@artsy/palette" import { capitalize, compact, uniq } from "lodash" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import { RouterLink } from "v2/System/Router/RouterLink" import { FollowProfileButtonFragmentContainer } from "v2/Components/FollowButton/FollowProfileButton" import { NearbyGalleryCard_partner } from "v2/__generated__/NearbyGalleryCard_partner.graphql" interface NearbyGalleryCardProps extends BoxProps { partner: NearbyGalleryCard_partner city?: string | null } function normalizeCityName(city: string) { return capitalize(city.trim()) } function getLocation(cities: Array<string>, preferredCity?: string | null)
const NearbyGalleryCard: React.FC<NearbyGalleryCardProps> = ({ partner, city, ...rest }) => { const { user } = useSystemContext() if (!partner) { return null } const { name, slug, profile, type, locationsConnection } = partner const canFollow = type !== "Auction House" const image = partner?.profile?.image?.cropped const partnerHref = `/partner/${slug}` const cities = uniq( compact( locationsConnection?.edges?.map(location => location?.node?.city ? normalizeCityName(location?.node?.city) : location?.node?.displayCountry ) ) ) const location = getLocation(cities, city) return ( <Box {...rest}> <ResponsiveBox bg="black10" aspectHeight={3} aspectWidth={4} maxWidth="100%" > <RouterLink to={partnerHref}> {image && ( <Image lazyLoad src={image.src} srcSet={image.srcSet} width="100%" height="100%" /> )} </RouterLink> </ResponsiveBox> <Flex justifyContent="space-between" mt={1}> <Box> <RouterLink noUnderline to={partnerHref}> <Text variant="subtitle">{name}</Text> {location && <Text color="black60">{location}</Text>} </RouterLink> </Box> {canFollow && !!profile && ( <FollowProfileButtonFragmentContainer profile={profile} user={user} contextModule={ContextModule.partnerHeader} buttonProps={{ size: "small", variant: "secondaryOutline", }} /> )} </Flex> </Box> ) } export const NearbyGalleryCardFragmentContainer = createFragmentContainer( NearbyGalleryCard, { partner: graphql` fragment NearbyGalleryCard_partner on Partner { name slug type profile { image { cropped(height: 300, width: 400, version: "wide") { src srcSet } } ...FollowProfileButton_profile } locationsConnection(first: 20) { edges { node { city displayCountry } } } } `, } )
{ let location if (cities.length > 0) { const normalizedPreferredCity = preferredCity && normalizeCityName(preferredCity) if (cities.some(c => c === normalizedPreferredCity)) { location = normalizedPreferredCity } else { location = cities[0] } if (cities.length > 1) { location += ` & ${cities.length - 1} other location` if (cities.length > 2) { location += "s" } } } return location }
identifier_body
NearbyGalleryCard.tsx
import { ContextModule } from "@artsy/cohesion" import { Box, BoxProps, ResponsiveBox, Image, Flex, Text } from "@artsy/palette" import { capitalize, compact, uniq } from "lodash" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import { RouterLink } from "v2/System/Router/RouterLink" import { FollowProfileButtonFragmentContainer } from "v2/Components/FollowButton/FollowProfileButton" import { NearbyGalleryCard_partner } from "v2/__generated__/NearbyGalleryCard_partner.graphql" interface NearbyGalleryCardProps extends BoxProps { partner: NearbyGalleryCard_partner city?: string | null } function normalizeCityName(city: string) { return capitalize(city.trim()) } function
(cities: Array<string>, preferredCity?: string | null) { let location if (cities.length > 0) { const normalizedPreferredCity = preferredCity && normalizeCityName(preferredCity) if (cities.some(c => c === normalizedPreferredCity)) { location = normalizedPreferredCity } else { location = cities[0] } if (cities.length > 1) { location += ` & ${cities.length - 1} other location` if (cities.length > 2) { location += "s" } } } return location } const NearbyGalleryCard: React.FC<NearbyGalleryCardProps> = ({ partner, city, ...rest }) => { const { user } = useSystemContext() if (!partner) { return null } const { name, slug, profile, type, locationsConnection } = partner const canFollow = type !== "Auction House" const image = partner?.profile?.image?.cropped const partnerHref = `/partner/${slug}` const cities = uniq( compact( locationsConnection?.edges?.map(location => location?.node?.city ? normalizeCityName(location?.node?.city) : location?.node?.displayCountry ) ) ) const location = getLocation(cities, city) return ( <Box {...rest}> <ResponsiveBox bg="black10" aspectHeight={3} aspectWidth={4} maxWidth="100%" > <RouterLink to={partnerHref}> {image && ( <Image lazyLoad src={image.src} srcSet={image.srcSet} width="100%" height="100%" /> )} </RouterLink> </ResponsiveBox> <Flex justifyContent="space-between" mt={1}> <Box> <RouterLink noUnderline to={partnerHref}> <Text variant="subtitle">{name}</Text> {location && <Text color="black60">{location}</Text>} </RouterLink> </Box> {canFollow && !!profile && ( <FollowProfileButtonFragmentContainer profile={profile} user={user} contextModule={ContextModule.partnerHeader} buttonProps={{ size: "small", variant: "secondaryOutline", }} /> )} </Flex> </Box> ) } export const NearbyGalleryCardFragmentContainer = createFragmentContainer( NearbyGalleryCard, { partner: graphql` fragment NearbyGalleryCard_partner on Partner { name slug type profile { image { cropped(height: 300, width: 400, version: "wide") { src srcSet } } ...FollowProfileButton_profile } locationsConnection(first: 20) { edges { node { city displayCountry } } } } `, } )
getLocation
identifier_name
NearbyGalleryCard.tsx
import { ContextModule } from "@artsy/cohesion" import { Box, BoxProps, ResponsiveBox, Image, Flex, Text } from "@artsy/palette" import { capitalize, compact, uniq } from "lodash" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import { RouterLink } from "v2/System/Router/RouterLink" import { FollowProfileButtonFragmentContainer } from "v2/Components/FollowButton/FollowProfileButton" import { NearbyGalleryCard_partner } from "v2/__generated__/NearbyGalleryCard_partner.graphql" interface NearbyGalleryCardProps extends BoxProps { partner: NearbyGalleryCard_partner
} function getLocation(cities: Array<string>, preferredCity?: string | null) { let location if (cities.length > 0) { const normalizedPreferredCity = preferredCity && normalizeCityName(preferredCity) if (cities.some(c => c === normalizedPreferredCity)) { location = normalizedPreferredCity } else { location = cities[0] } if (cities.length > 1) { location += ` & ${cities.length - 1} other location` if (cities.length > 2) { location += "s" } } } return location } const NearbyGalleryCard: React.FC<NearbyGalleryCardProps> = ({ partner, city, ...rest }) => { const { user } = useSystemContext() if (!partner) { return null } const { name, slug, profile, type, locationsConnection } = partner const canFollow = type !== "Auction House" const image = partner?.profile?.image?.cropped const partnerHref = `/partner/${slug}` const cities = uniq( compact( locationsConnection?.edges?.map(location => location?.node?.city ? normalizeCityName(location?.node?.city) : location?.node?.displayCountry ) ) ) const location = getLocation(cities, city) return ( <Box {...rest}> <ResponsiveBox bg="black10" aspectHeight={3} aspectWidth={4} maxWidth="100%" > <RouterLink to={partnerHref}> {image && ( <Image lazyLoad src={image.src} srcSet={image.srcSet} width="100%" height="100%" /> )} </RouterLink> </ResponsiveBox> <Flex justifyContent="space-between" mt={1}> <Box> <RouterLink noUnderline to={partnerHref}> <Text variant="subtitle">{name}</Text> {location && <Text color="black60">{location}</Text>} </RouterLink> </Box> {canFollow && !!profile && ( <FollowProfileButtonFragmentContainer profile={profile} user={user} contextModule={ContextModule.partnerHeader} buttonProps={{ size: "small", variant: "secondaryOutline", }} /> )} </Flex> </Box> ) } export const NearbyGalleryCardFragmentContainer = createFragmentContainer( NearbyGalleryCard, { partner: graphql` fragment NearbyGalleryCard_partner on Partner { name slug type profile { image { cropped(height: 300, width: 400, version: "wide") { src srcSet } } ...FollowProfileButton_profile } locationsConnection(first: 20) { edges { node { city displayCountry } } } } `, } )
city?: string | null } function normalizeCityName(city: string) { return capitalize(city.trim())
random_line_split
playerwrapper.js
var PlayerWrapper = function() { this.underlyingPlayer = 'aurora'; this.aurora = {}; this.sm2 = {}; this.duration = 0; this.volume = 100; return this; }; PlayerWrapper.prototype = _.extend({}, OC.Backbone.Events); PlayerWrapper.prototype.play = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.play('ownCloudSound'); break; case 'aurora': this.aurora.play(); break; } }; PlayerWrapper.prototype.stop = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.stop('ownCloudSound'); this.sm2.destroySound('ownCloudSound'); break; case 'aurora': if(this.aurora.asset !== undefined) { // check if player's constructor has been called, // if so, stop() will be available this.aurora.stop(); } break; } }; PlayerWrapper.prototype.togglePlayback = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.togglePause('ownCloudSound'); break; case 'aurora': this.aurora.togglePlayback(); break; } }; PlayerWrapper.prototype.seekingSupported = function() { // Seeking is not implemented in aurora/flac.js and does not work on all // files with aurora/mp3.js. Hence, we disable seeking with aurora. return this.underlyingPlayer == 'sm2'; }; PlayerWrapper.prototype.pause = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.pause('ownCloudSound'); break; case 'aurora': this.aurora.pause(); break; } }; PlayerWrapper.prototype.seek = function(percentage) { if (this.seekingSupported()) { console.log('seek to '+percentage); switch(this.underlyingPlayer) { case 'sm2': this.sm2.setPosition('ownCloudSound', percentage * this.duration); break; case 'aurora': this.aurora.seek(percentage * this.duration); break; } } else { console.log('seeking is not supported for this file'); } }; PlayerWrapper.prototype.setVolume = function(percentage) { this.volume = percentage; switch(this.underlyingPlayer) { case 'sm2': this.sm2.setVolume('ownCloudSound', this.volume); break; case 'aurora': this.aurora.volume = this.volume; break; } }; PlayerWrapper.prototype.fromURL = function(typeAndURL) { var self = this; var url = typeAndURL['url']; var type = typeAndURL['type']; if (soundManager.canPlayURL(url)) { this.underlyingPlayer = 'sm2'; } else { this.underlyingPlayer = 'aurora'; } console.log('Using ' + this.underlyingPlayer + ' for type ' + type + ' URL ' + url); switch(this.underlyingPlayer) { case 'sm2': this.sm2 = soundManager.setup({ html5PollingInterval: 200 }); this.sm2.html5Only = true; this.sm2.createSound({ id: 'ownCloudSound', url: url, whileplaying: function() { self.trigger('progress', this.position); }, whileloading: function() { self.duration = this.durationEstimate; self.trigger('duration', this.durationEstimate); // The buffer may contain holes after seeking but just ignore those.
}, onfinish: function() { self.trigger('end'); }, onload: function(success) { if (success) { self.trigger('ready'); } else { console.log('SM2: sound load error'); } } }); break; case 'aurora': this.aurora = AV.Player.fromURL(url); this.aurora.asset.source.chunkSize=524288; this.aurora.on('buffer', function(percent) { self.trigger('buffer', percent); }); this.aurora.on('progress', function(currentTime) {//currentTime is in msec self.trigger('progress', currentTime); }); this.aurora.on('ready', function() { self.trigger('ready'); }); this.aurora.on('end', function() { self.trigger('end'); }); this.aurora.on('duration', function(msecs) { self.duration = msecs; self.trigger('duration', msecs); }); break; } // Set the current volume to the newly created player instance this.setVolume(this.volume); }; PlayerWrapper.prototype.setVolume = function(vol) { console.log("setVolume not implemented");// TODO };
// Show the buffering status according the last buffered position. var bufCount = this.buffered.length; var bufEnd = (bufCount > 0) ? this.buffered[bufCount-1].end : 0; self.trigger('buffer', bufEnd / this.durationEstimate * 100);
random_line_split
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>, Vec<u8>>, Coordinate) { let (min, max) = min_max(&list); let diff = max - min; let add = Coordinate::new(-min.x, -min.y); let image = gen_canvas(diff.x as u32, diff.y as u32); (image, add) } /** Finds the min and max of a list and returns (min, max). the min and max use the size of the Draw trait to enlarge the are the min, max occupy. */ fn min_max<T: Location + Draw + MinMax>(list: &[T]) -> (Coordinate, Coordinate) { let mut size: i16 = consts::DEFAULT_SIZE as i16; let mut min = coordinate!(); let mut max = coordinate!(); for item in list { size = cmp::max(size, item.size() as i16); let (imin, imax) = item.min_max(); max.x = cmp::max(max.x, imax.x); min.x = cmp::min(min.x, imin.x); max.y = cmp::max(max.y, imax.y); min.y = cmp::min(min.y, imin.y); } let size = coordinate!(size / 4); (min - size, max + size) } /** Generates a canvas from the image crate. */ fn gen_canvas(w: u32, h: u32) -> image::ImageBuffer<Rgba<u8>, Vec<u8>>
#[cfg(test)] mod tests { use super::*; #[test] fn test_gen_canvas() { let image = gen_canvas(50, 50); assert_eq!(image.width(), 50); assert_eq!(image.height(), 50); } #[test] fn test_gen_canvas_2() { let image = gen_canvas(0, 0); assert_eq!(image.width(), 0); assert_eq!(image.height(), 0); } #[test] fn test_min_max() { let nodes = Node::from_list(&[(-50, 50), (50, -50), (0, 25), (25, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-55, -55)); assert_eq!(max, Coordinate::new(55, 55)); } #[test] fn test_min_max_2() { let nodes = Node::from_list(&[(-9999, 50), (50, -50), (0, 25), (9999, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-10004, -55)); assert_eq!(max, Coordinate::new(10004, 55)); } }
{ image::DynamicImage::new_rgba8(w, h).to_rgba() }
identifier_body
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>, Vec<u8>>, Coordinate) { let (min, max) = min_max(&list); let diff = max - min; let add = Coordinate::new(-min.x, -min.y); let image = gen_canvas(diff.x as u32, diff.y as u32); (image, add) } /** Finds the min and max of a list and returns (min, max). the min and max use the size of the Draw trait to enlarge the are the min, max occupy. */ fn
<T: Location + Draw + MinMax>(list: &[T]) -> (Coordinate, Coordinate) { let mut size: i16 = consts::DEFAULT_SIZE as i16; let mut min = coordinate!(); let mut max = coordinate!(); for item in list { size = cmp::max(size, item.size() as i16); let (imin, imax) = item.min_max(); max.x = cmp::max(max.x, imax.x); min.x = cmp::min(min.x, imin.x); max.y = cmp::max(max.y, imax.y); min.y = cmp::min(min.y, imin.y); } let size = coordinate!(size / 4); (min - size, max + size) } /** Generates a canvas from the image crate. */ fn gen_canvas(w: u32, h: u32) -> image::ImageBuffer<Rgba<u8>, Vec<u8>> { image::DynamicImage::new_rgba8(w, h).to_rgba() } #[cfg(test)] mod tests { use super::*; #[test] fn test_gen_canvas() { let image = gen_canvas(50, 50); assert_eq!(image.width(), 50); assert_eq!(image.height(), 50); } #[test] fn test_gen_canvas_2() { let image = gen_canvas(0, 0); assert_eq!(image.width(), 0); assert_eq!(image.height(), 0); } #[test] fn test_min_max() { let nodes = Node::from_list(&[(-50, 50), (50, -50), (0, 25), (25, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-55, -55)); assert_eq!(max, Coordinate::new(55, 55)); } #[test] fn test_min_max_2() { let nodes = Node::from_list(&[(-9999, 50), (50, -50), (0, 25), (9999, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-10004, -55)); assert_eq!(max, Coordinate::new(10004, 55)); } }
min_max
identifier_name
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>, Vec<u8>>, Coordinate) { let (min, max) = min_max(&list); let diff = max - min; let add = Coordinate::new(-min.x, -min.y); let image = gen_canvas(diff.x as u32, diff.y as u32); (image, add) } /** Finds the min and max of a list and returns (min, max). the min and max use the size of the Draw trait to enlarge the are the min, max occupy. */ fn min_max<T: Location + Draw + MinMax>(list: &[T]) -> (Coordinate, Coordinate) { let mut size: i16 = consts::DEFAULT_SIZE as i16; let mut min = coordinate!(); let mut max = coordinate!(); for item in list { size = cmp::max(size, item.size() as i16); let (imin, imax) = item.min_max(); max.x = cmp::max(max.x, imax.x); min.x = cmp::min(min.x, imin.x); max.y = cmp::max(max.y, imax.y); min.y = cmp::min(min.y, imin.y); } let size = coordinate!(size / 4); (min - size, max + size) } /** Generates a canvas from the image crate. */ fn gen_canvas(w: u32, h: u32) -> image::ImageBuffer<Rgba<u8>, Vec<u8>> { image::DynamicImage::new_rgba8(w, h).to_rgba() } #[cfg(test)] mod tests { use super::*; #[test]
fn test_gen_canvas() { let image = gen_canvas(50, 50); assert_eq!(image.width(), 50); assert_eq!(image.height(), 50); } #[test] fn test_gen_canvas_2() { let image = gen_canvas(0, 0); assert_eq!(image.width(), 0); assert_eq!(image.height(), 0); } #[test] fn test_min_max() { let nodes = Node::from_list(&[(-50, 50), (50, -50), (0, 25), (25, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-55, -55)); assert_eq!(max, Coordinate::new(55, 55)); } #[test] fn test_min_max_2() { let nodes = Node::from_list(&[(-9999, 50), (50, -50), (0, 25), (9999, 0)]); let (min, max) = min_max(&nodes); assert_eq!(min, Coordinate::new(-10004, -55)); assert_eq!(max, Coordinate::new(10004, 55)); } }
random_line_split
__init__.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Mixins to add common attributes and relationships. Note, all model classes must also inherit from ``db.Model``. For example: color color .. class Market(BusinessObject, db.Model): __tablename__ = 'markets' """ # pylint: disable=no-self-argument # All declared_attr properties that are class level as per sqlalchemy # documentatio, are reported as false positives by pylint. from logging import getLogger from uuid import uuid1 import datetime from sqlalchemy import event from sqlalchemy import orm from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.session import Session from ggrc import builder from ggrc import db from ggrc.models import reflection from ggrc.models.deferred import deferred from ggrc.models.inflector import ModelInflectorDescriptor from ggrc.models.reflection import AttributeInfo from ggrc.models.mixins.customattributable import CustomAttributable from ggrc.models.mixins.notifiable import Notifiable from ggrc.utils import create_stub from ggrc.fulltext import attributes # pylint: disable=invalid-name logger = getLogger(__name__) class Identifiable(object): """A model with an ``id`` property that is the primary key.""" id = db.Column(db.Integer, primary_key=True) # noqa # REST properties _publish_attrs = ['id', 'type'] _update_attrs = [] _inflector = ModelInflectorDescriptor() @builder.simple_property def type(self): return self.__class__.__name__ @classmethod def eager_query(cls): mapper_class = cls._sa_class_manager.mapper.base_mapper.class_ return db.session.query(cls).options( db.Load(mapper_class).undefer_group( mapper_class.__name__ + '_complete'), ) @classmethod def eager_inclusions(cls, query, include_links): """Load related items listed in include_links eagerly.""" options = [] for include_link in include_links: inclusion_class = getattr(cls, include_link).property.mapper.class_ options.append( orm.subqueryload(include_link) .undefer_group(inclusion_class.__name__ + '_complete')) return query.options(*options) @declared_attr def __table_args__(cls): extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args') table_args = [] table_dict = {} for table_arg in extra_table_args: if callable(table_arg): table_arg = table_arg() if isinstance(table_arg, (list, tuple, set)): if isinstance(table_arg[-1], (dict,)): table_dict.update(table_arg[-1]) table_args.extend(table_arg[:-1]) else: table_args.extend(table_arg) elif isinstance(table_arg, (dict,)):
else: table_args.append(table_arg) if len(table_dict) > 0: table_args.append(table_dict) return tuple(table_args,) class ChangeTracked(object): """A model with fields to tracked the last user to modify the model, the creation time of the model, and the last time the model was updated. """ @declared_attr def modified_by_id(cls): """Id of user who did the last modification of the object.""" return deferred(db.Column(db.Integer), cls.__name__) @declared_attr def created_at(cls): """Date of creation. Set to current time on object creation.""" column = db.Column( db.DateTime, nullable=False, default=db.text('current_timestamp'), ) return deferred(column, cls.__name__) @declared_attr def updated_at(cls): """Date of last update. Set to current time on object creation/update.""" column = db.Column( db.DateTime, nullable=False, default=db.text('current_timestamp'), onupdate=db.text('current_timestamp'), ) return deferred(column, cls.__name__) @declared_attr def modified_by(cls): """Relationship to user referenced by modified_by_id.""" return db.relationship( 'Person', primaryjoin='{0}.modified_by_id == Person.id'.format(cls.__name__), foreign_keys='{0}.modified_by_id'.format(cls.__name__), uselist=False, ) @staticmethod def _extra_table_args(model): """Apply extra table args (like indexes) to model definition.""" return ( db.Index('ix_{}_updated_at'.format(model.__tablename__), 'updated_at'), ) # TODO Add a transaction id, this will be handy for generating etags # and for tracking the changes made to several resources together. # transaction_id = db.Column(db.Integer) # REST properties _publish_attrs = [ 'modified_by', 'created_at', 'updated_at', ] _fulltext_attrs = [ attributes.DatetimeFullTextAttr('created_at', 'created_at'), attributes.DatetimeFullTextAttr('updated_at', 'updated_at'), attributes.FullTextAttr("modified_by", "modified_by", ["name", "email"]), ] _update_attrs = [] _aliases = { "updated_at": { "display_name": "Last Updated", "filter_only": True, }, "created_at": { "display_name": "Created Date", "filter_only": True, }, } @classmethod def indexed_query(cls): return super(ChangeTracked, cls).indexed_query().options( orm.Load(cls).load_only("created_at", "updated_at"), orm.Load(cls).joinedload( "modified_by" ).load_only( "name", "email", "id" ), ) class Titled(object): """Mixin that defines `title` field. Strips title on update and defines optional UNIQUE constraint on it. """ @validates('title') def validate_title(self, key, value): """Validates and cleans Title that has leading/trailing spaces""" # pylint: disable=unused-argument,no-self-use return value if value is None else value.strip() @declared_attr def title(cls): return deferred(db.Column(db.String, nullable=False), cls.__name__) @classmethod def indexed_query(cls): return super(Titled, cls).indexed_query().options( orm.Load(cls).load_only("title"), ) @staticmethod def _extra_table_args(model): """If model._title_uniqueness is set, apply UNIQUE constraint to title.""" if getattr(model, '_title_uniqueness', True): return ( db.UniqueConstraint( 'title', name='uq_t_{}'.format(model.__tablename__)), ) return () # REST properties _publish_attrs = ['title'] _fulltext_attrs = ['title'] _sanitize_html = ['title'] _aliases = {"title": "Title"} class Described(object): """Mixin that defines `description` field.""" @declared_attr def description(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['description'] _fulltext_attrs = ['description'] _sanitize_html = ['description'] _aliases = {"description": "Description"} @classmethod def indexed_query(cls): return super(Described, cls).indexed_query().options( orm.Load(cls).load_only("description"), ) class Noted(object): """Mixin that defines `notes` field.""" @declared_attr def notes(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['notes'] _fulltext_attrs = ['notes'] _sanitize_html = ['notes'] _aliases = {"notes": "Notes"} @classmethod def indexed_query(cls): return super(Noted, cls).indexed_query().options( orm.Load(cls).load_only("notes"), ) class Hyperlinked(object): """Mixin that defines `url` and `reference_url` fields.""" @declared_attr def url(cls): return deferred(db.Column(db.String), cls.__name__) @declared_attr def reference_url(cls): return deferred(db.Column(db.String), cls.__name__) # REST properties _publish_attrs = ['url', 'reference_url'] _aliases = { "url": "Url", "reference_url": "Reference URL", } _fulltext_attrs = [ 'url', 'reference_url', ] @classmethod def indexed_query(cls): return super(Hyperlinked, cls).indexed_query().options( orm.Load(cls).load_only("url", "reference_url"), ) class Hierarchical(object): """Mixin that defines `parent` and `child` fields to organize hierarchy.""" @declared_attr def parent_id(cls): return deferred(db.Column( db.Integer, db.ForeignKey('{0}.id'.format(cls.__tablename__))), cls.__name__) @declared_attr def children(cls): return db.relationship( cls.__name__, backref=db.backref( 'parent', remote_side='{0}.id'.format(cls.__name__)), ) # REST properties _publish_attrs = [ 'children', 'parent', ] _fulltext_attrs = [ 'children', 'parent', ] @classmethod def indexed_query(cls): return super(Hierarchical, cls).indexed_query().options( orm.Load(cls).subqueryload("children"), orm.Load(cls).joinedload("parent"), ) @classmethod def eager_query(cls): query = super(Hierarchical, cls).eager_query() return query.options( orm.subqueryload('children'), # orm.joinedload('parent'), ) class Timeboxed(object): """Mixin that defines `start_date` and `end_date` fields.""" @declared_attr def start_date(cls): return deferred(db.Column(db.Date), cls.__name__) @declared_attr def end_date(cls): return deferred(db.Column(db.Date), cls.__name__) # REST properties _publish_attrs = ['start_date', 'end_date'] _aliases = { "start_date": "Effective Date", "end_date": "Stop Date", } _fulltext_attrs = [ attributes.DateFullTextAttr('start_date', 'start_date'), attributes.DateFullTextAttr('end_date', 'end_date'), ] @classmethod def indexed_query(cls): return super(Timeboxed, cls).indexed_query().options( orm.Load(cls).load_only("start_date", "end_date"), ) class Stateful(object): """Mixin that defines `status` field and status validation logic. TODO: unify with Statusable. """ @declared_attr def status(cls): return deferred(db.Column( db.String, default=cls.default_status, nullable=False), cls.__name__) _publish_attrs = ['status'] _fulltext_attrs = ['status'] _aliases = { "status": { "display_name": "State", "mandatory": False } } @classmethod def default_status(cls): return cls.valid_statuses()[0] @classmethod def valid_statuses(cls): return cls.VALID_STATES @validates('status') def validate_status(self, key, value): """Use default status if value is None, check that it is in valid set.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since there are other mixins that want to touch 'status'. if hasattr(super(Stateful, self), "validate_status"): value = super(Stateful, self).validate_status(key, value) if value is None: value = self.default_status() if value not in self.valid_statuses(): message = u"Invalid state '{}'".format(value) raise ValueError(message) return value @classmethod def indexed_query(cls): return super(Stateful, cls).indexed_query().options( orm.Load(cls).load_only("status"), ) class FinishedDate(object): """Adds 'Finished Date' which is set when status is set to a finished state. Requires Stateful to be mixed in as well. """ NOT_DONE_STATES = None DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def finished_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) _publish_attrs = [ reflection.PublishOnly('finished_date') ] _aliases = { "finished_date": "Finished Date" } _fulltext_attrs = [ attributes.DatetimeFullTextAttr('finished_date', 'finished_date'), ] @validates('status') def validate_status(self, key, value): """Update finished_date given the right status change.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since 'status' is not defined here. if hasattr(super(FinishedDate, self), "validate_status"): value = super(FinishedDate, self).validate_status(key, value) # pylint: disable=unsupported-membership-test # short circuit if (value in self.DONE_STATES and (self.NOT_DONE_STATES is None or self.status in self.NOT_DONE_STATES)): self.finished_date = datetime.datetime.now() elif ((self.NOT_DONE_STATES is None or value in self.NOT_DONE_STATES) and self.status in self.DONE_STATES): self.finished_date = None return value @classmethod def indexed_query(cls): return super(FinishedDate, cls).indexed_query().options( orm.Load(cls).load_only("finished_date"), ) class VerifiedDate(object): """Adds 'Verified Date' which is set when status is set to 'Verified'. When object is verified the status is overridden to 'Final' and the information about verification exposed as the 'verified' boolean. Requires Stateful to be mixed in as well. """ VERIFIED_STATES = {u"Verified"} DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def verified_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) @hybrid_property def verified(self): return self.verified_date != None # noqa _publish_attrs = [ reflection.PublishOnly('verified'), reflection.PublishOnly('verified_date'), ] _aliases = { "verified_date": "Verified Date" } _fulltext_attrs = [ attributes.DatetimeFullTextAttr("verified_date", "verified_date"), "verified", ] @classmethod def indexed_query(cls): return super(VerifiedDate, cls).indexed_query().options( orm.Load(cls).load_only("verified_date"), ) @validates('status') def validate_status(self, key, value): """Update verified_date on status change, make verified status final.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since 'status' is not defined here. if hasattr(super(VerifiedDate, self), "validate_status"): value = super(VerifiedDate, self).validate_status(key, value) if (value in self.VERIFIED_STATES and self.status not in self.VERIFIED_STATES): self.verified_date = datetime.datetime.now() value = self.FINAL_STATE elif (value not in self.VERIFIED_STATES and value not in self.DONE_STATES and (self.status in self.VERIFIED_STATES or self.status in self.DONE_STATES)): self.verified_date = None return value class ContextRBAC(object): """Defines `context` relationship for Context-based access control.""" @declared_attr def context_id(cls): return db.Column(db.Integer, db.ForeignKey('contexts.id')) @declared_attr def context(cls): return db.relationship('Context', uselist=False) @staticmethod def _extra_table_args(model): return ( db.Index('fk_{}_contexts'.format(model.__tablename__), 'context_id'), ) _publish_attrs = ['context'] @classmethod def indexed_query(cls): return super(ContextRBAC, cls).indexed_query().options( orm.Load(cls).load_only("context_id"), ) # @classmethod # def eager_query(cls): # from sqlalchemy import orm # query = super(ContextRBAC, cls).eager_query() # return query.options( # orm.subqueryload('context')) def is_attr_of_type(object_, attr_name, mapped_class): """Check if relationship property points to mapped_class""" cls = object_.__class__ if isinstance(attr_name, basestring): if hasattr(cls, attr_name): cls_attr = getattr(cls, attr_name) if (hasattr(cls_attr, "property") and isinstance(cls_attr.property, orm.properties.RelationshipProperty) and cls_attr.property.mapper.class_ == mapped_class): return True return False class Base(ChangeTracked, ContextRBAC, Identifiable): """Several of the models use the same mixins. This class covers that common case. """ _people_log_mappings = [ "principal_assessor_id", "secondary_assessor_id", "contact_id", "secondary_contact_id", "modified_by_id", "attribute_object_id", # used for person mapping CA ] @staticmethod def _person_stub(id_): return { 'type': u"Person", 'id': id_, 'context_id': None, 'href': u"/api/people/{}".format(id_), } def log_json_base(self): """Get a dict with attributes of self that is easy to serialize to json. This method lists only first-class attributes. """ res = {} for column in self.__table__.columns: try: res[column.name] = getattr(self, column.name) except AttributeError: pass res["display_name"] = self.display_name return res def log_json(self): """Get a dict with attributes and related objects of self. This method converts additionally person-mapping attributes and owners to person stubs. """ from ggrc import models res = self.log_json_base() for attr in self._people_log_mappings: if hasattr(self, attr): value = getattr(self, attr) # hardcoded [:-3] is used to strip "_id" suffix res[attr[:-3]] = self._person_stub(value) if value else None if hasattr(self, "owners"): res["owners"] = [ self._person_stub(owner.id) for owner in self.owners if owner ] for attr_name in AttributeInfo.gather_publish_attrs(self.__class__): if is_attr_of_type(self, attr_name, models.Option): attr = getattr(self, attr_name) if attr: stub = create_stub(attr) stub["title"] = attr.title else: stub = None res[attr_name] = stub return res @builder.simple_property def display_name(self): try: return self._display_name() except: # pylint: disable=bare-except logger.warning("display_name error in %s", type(self), exc_info=True) return "" def _display_name(self): return getattr(self, "title", None) or getattr(self, "name", "") def copy_into(self, target_object, columns, **kwargs): """Copy current object values into a target object. Copy all values listed in columns from current class to target class and use kwargs as defaults with precedence. Note that this is a shallow copy and any mutable values will be shared between current and target objects. Args: target_object: object to which we want to copy current values. This function will mutate the target_object parameter if it is set. columns: list with all attribute names that we want to set in the target_object. kwargs: additional default values. Returns: target_object with all values listed in columns set. """ target = target_object or type(self)() columns = set(columns).union(kwargs.keys()) for name in columns: if name in kwargs: value = kwargs[name] else: value = getattr(self, name) setattr(target, name, value) return target CACHED_ATTRIBUTE_MAP = None @classmethod def attributes_map(cls): if cls.CACHED_ATTRIBUTE_MAP: return cls.CACHED_ATTRIBUTE_MAP aliases = AttributeInfo.gather_aliases(cls) cls.CACHED_ATTRIBUTE_MAP = {} for key, value in aliases.items(): if isinstance(value, dict): name = value["display_name"] filter_by = None if value.get("filter_by"): filter_by = getattr(cls, value["filter_by"], None) else: name = value filter_by = None if not name: continue tmp = getattr(cls, "PROPERTY_TEMPLATE", "{}") name = tmp.format(name) key = tmp.format(key) cls.CACHED_ATTRIBUTE_MAP[name.lower()] = (key.lower(), filter_by) return cls.CACHED_ATTRIBUTE_MAP class Slugged(Base): """Several classes make use of the common mixins and additional are "slugged" and have additional fields related to their publishing in the system. """ @declared_attr def slug(cls): return deferred(db.Column(db.String, nullable=False), cls.__name__) @staticmethod def _extra_table_args(model): if getattr(model, '_slug_uniqueness', True): return ( db.UniqueConstraint('slug', name='uq_{}'.format(model.__tablename__)), ) return () # REST properties _publish_attrs = ['slug'] _fulltext_attrs = ['slug'] _sanitize_html = ['slug'] _aliases = { "slug": { "display_name": "Code", "description": ("Must be unique. Can be left empty for " "auto generation. If updating or deleting, " "code is required"), } } @classmethod def indexed_query(cls): return super(Slugged, cls).indexed_query().options( orm.Load(cls).load_only("slug"), ) @classmethod def generate_slug_for(cls, obj): _id = getattr(obj, 'id', uuid1()) obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id) # We need to make sure the generated slug is not already present in the # database. If it is, we increment the id until we find a slug that is # unique. # A better approach would be to query the database for slug uniqueness # only if the there was a conflict, but because we can't easily catch a # session rollback at this point we are sticking with a # suboptimal solution for now. INCREMENT = 1000 while cls.query.filter(cls.slug == obj.slug).count(): _id += INCREMENT obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id) @classmethod def generate_slug_prefix_for(cls, obj): return obj.__class__.__name__.upper() @classmethod def ensure_slug_before_flush(cls, session, flush_context, instances): """Set the slug to a default string so we don't run afoul of the NOT NULL constraint. """ # pylint: disable=unused-argument for o in session.new: if isinstance(o, Slugged) and (o.slug is None or o.slug == ''): o.slug = str(uuid1()) o._replace_slug = True @classmethod def ensure_slug_after_flush_postexec(cls, session, flush_context): """Replace the placeholder slug with a real slug that will be set on the next flush/commit. """ # pylint: disable=unused-argument for o in session.identity_map.values(): if isinstance(o, Slugged) and hasattr(o, '_replace_slug'): o.generate_slug_for(o) delattr(o, '_replace_slug') event.listen(Session, 'before_flush', Slugged.ensure_slug_before_flush) event.listen( Session, 'after_flush_postexec', Slugged.ensure_slug_after_flush_postexec) class WithContact(object): """Mixin that defines `contact` and `secondary_contact` fields.""" @declared_attr def contact_id(cls): return deferred( db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__) @declared_attr def secondary_contact_id(cls): return deferred( db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__) @declared_attr def contact(cls): return db.relationship( 'Person', uselist=False, foreign_keys='{}.contact_id'.format(cls.__name__)) @declared_attr def secondary_contact(cls): return db.relationship( 'Person', uselist=False, foreign_keys='{}.secondary_contact_id'.format(cls.__name__)) @staticmethod def _extra_table_args(model): return ( db.Index('fk_{}_contact'.format(model.__tablename__), 'contact_id'), db.Index('fk_{}_secondary_contact'.format( model.__tablename__), 'secondary_contact_id'), ) _publish_attrs = ['contact', 'secondary_contact'] _fulltext_attrs = [ attributes.FullTextAttr( "contact", "contact", ["name", "email"] ), attributes.FullTextAttr( 'secondary_contact', 'secondary_contact', ["name", "email"]), ] @classmethod def indexed_query(cls): return super(WithContact, cls).indexed_query().options( orm.Load(cls).joinedload( "contact" ).load_only( "name", "email", "id" ), orm.Load(cls).joinedload( "secondary_contact" ).load_only( "name", "email", "id" ), ) _aliases = { "contact": "Primary Contact", "secondary_contact": "Secondary Contact", } class BusinessObject(Stateful, Noted, Described, Hyperlinked, Titled, Slugged): """Mixin that groups most commonly-used mixins into one.""" VALID_STATES = ( 'Draft', 'Active', 'Deprecated' ) _aliases = { "status": { "display_name": "State", "mandatory": False, "description": "Options are:\n{}".format('\n'.join(VALID_STATES)) } } # This class is just a marker interface/mixin to indicate that a model type # supports custom attributes. class TestPlanned(object): """Mixin that defines `test_plan` field.""" @declared_attr def test_plan(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['test_plan'] _fulltext_attrs = ['test_plan'] _sanitize_html = ['test_plan'] _aliases = {"test_plan": "Test Plan"} @classmethod def indexed_query(cls): return super(TestPlanned, cls).indexed_query().options( orm.Load(cls).load_only("test_plan"), ) __all__ = [ "Base", "BusinessObject", "ChangeTracked", "ContextRBAC", "CustomAttributable", "Described", "FinishedDate", "Hierarchical", "Hyperlinked", "Identifiable", "Noted", "Notifiable", "Slugged", "Stateful", "TestPlanned", "Timeboxed", "Titled", "VerifiedDate", "WithContact", ]
table_dict.update(table_arg)
conditional_block
__init__.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Mixins to add common attributes and relationships. Note, all model classes must also inherit from ``db.Model``. For example: color color .. class Market(BusinessObject, db.Model): __tablename__ = 'markets' """ # pylint: disable=no-self-argument # All declared_attr properties that are class level as per sqlalchemy # documentatio, are reported as false positives by pylint. from logging import getLogger
from sqlalchemy import event from sqlalchemy import orm from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.session import Session from ggrc import builder from ggrc import db from ggrc.models import reflection from ggrc.models.deferred import deferred from ggrc.models.inflector import ModelInflectorDescriptor from ggrc.models.reflection import AttributeInfo from ggrc.models.mixins.customattributable import CustomAttributable from ggrc.models.mixins.notifiable import Notifiable from ggrc.utils import create_stub from ggrc.fulltext import attributes # pylint: disable=invalid-name logger = getLogger(__name__) class Identifiable(object): """A model with an ``id`` property that is the primary key.""" id = db.Column(db.Integer, primary_key=True) # noqa # REST properties _publish_attrs = ['id', 'type'] _update_attrs = [] _inflector = ModelInflectorDescriptor() @builder.simple_property def type(self): return self.__class__.__name__ @classmethod def eager_query(cls): mapper_class = cls._sa_class_manager.mapper.base_mapper.class_ return db.session.query(cls).options( db.Load(mapper_class).undefer_group( mapper_class.__name__ + '_complete'), ) @classmethod def eager_inclusions(cls, query, include_links): """Load related items listed in include_links eagerly.""" options = [] for include_link in include_links: inclusion_class = getattr(cls, include_link).property.mapper.class_ options.append( orm.subqueryload(include_link) .undefer_group(inclusion_class.__name__ + '_complete')) return query.options(*options) @declared_attr def __table_args__(cls): extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args') table_args = [] table_dict = {} for table_arg in extra_table_args: if callable(table_arg): table_arg = table_arg() if isinstance(table_arg, (list, tuple, set)): if isinstance(table_arg[-1], (dict,)): table_dict.update(table_arg[-1]) table_args.extend(table_arg[:-1]) else: table_args.extend(table_arg) elif isinstance(table_arg, (dict,)): table_dict.update(table_arg) else: table_args.append(table_arg) if len(table_dict) > 0: table_args.append(table_dict) return tuple(table_args,) class ChangeTracked(object): """A model with fields to tracked the last user to modify the model, the creation time of the model, and the last time the model was updated. """ @declared_attr def modified_by_id(cls): """Id of user who did the last modification of the object.""" return deferred(db.Column(db.Integer), cls.__name__) @declared_attr def created_at(cls): """Date of creation. Set to current time on object creation.""" column = db.Column( db.DateTime, nullable=False, default=db.text('current_timestamp'), ) return deferred(column, cls.__name__) @declared_attr def updated_at(cls): """Date of last update. Set to current time on object creation/update.""" column = db.Column( db.DateTime, nullable=False, default=db.text('current_timestamp'), onupdate=db.text('current_timestamp'), ) return deferred(column, cls.__name__) @declared_attr def modified_by(cls): """Relationship to user referenced by modified_by_id.""" return db.relationship( 'Person', primaryjoin='{0}.modified_by_id == Person.id'.format(cls.__name__), foreign_keys='{0}.modified_by_id'.format(cls.__name__), uselist=False, ) @staticmethod def _extra_table_args(model): """Apply extra table args (like indexes) to model definition.""" return ( db.Index('ix_{}_updated_at'.format(model.__tablename__), 'updated_at'), ) # TODO Add a transaction id, this will be handy for generating etags # and for tracking the changes made to several resources together. # transaction_id = db.Column(db.Integer) # REST properties _publish_attrs = [ 'modified_by', 'created_at', 'updated_at', ] _fulltext_attrs = [ attributes.DatetimeFullTextAttr('created_at', 'created_at'), attributes.DatetimeFullTextAttr('updated_at', 'updated_at'), attributes.FullTextAttr("modified_by", "modified_by", ["name", "email"]), ] _update_attrs = [] _aliases = { "updated_at": { "display_name": "Last Updated", "filter_only": True, }, "created_at": { "display_name": "Created Date", "filter_only": True, }, } @classmethod def indexed_query(cls): return super(ChangeTracked, cls).indexed_query().options( orm.Load(cls).load_only("created_at", "updated_at"), orm.Load(cls).joinedload( "modified_by" ).load_only( "name", "email", "id" ), ) class Titled(object): """Mixin that defines `title` field. Strips title on update and defines optional UNIQUE constraint on it. """ @validates('title') def validate_title(self, key, value): """Validates and cleans Title that has leading/trailing spaces""" # pylint: disable=unused-argument,no-self-use return value if value is None else value.strip() @declared_attr def title(cls): return deferred(db.Column(db.String, nullable=False), cls.__name__) @classmethod def indexed_query(cls): return super(Titled, cls).indexed_query().options( orm.Load(cls).load_only("title"), ) @staticmethod def _extra_table_args(model): """If model._title_uniqueness is set, apply UNIQUE constraint to title.""" if getattr(model, '_title_uniqueness', True): return ( db.UniqueConstraint( 'title', name='uq_t_{}'.format(model.__tablename__)), ) return () # REST properties _publish_attrs = ['title'] _fulltext_attrs = ['title'] _sanitize_html = ['title'] _aliases = {"title": "Title"} class Described(object): """Mixin that defines `description` field.""" @declared_attr def description(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['description'] _fulltext_attrs = ['description'] _sanitize_html = ['description'] _aliases = {"description": "Description"} @classmethod def indexed_query(cls): return super(Described, cls).indexed_query().options( orm.Load(cls).load_only("description"), ) class Noted(object): """Mixin that defines `notes` field.""" @declared_attr def notes(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['notes'] _fulltext_attrs = ['notes'] _sanitize_html = ['notes'] _aliases = {"notes": "Notes"} @classmethod def indexed_query(cls): return super(Noted, cls).indexed_query().options( orm.Load(cls).load_only("notes"), ) class Hyperlinked(object): """Mixin that defines `url` and `reference_url` fields.""" @declared_attr def url(cls): return deferred(db.Column(db.String), cls.__name__) @declared_attr def reference_url(cls): return deferred(db.Column(db.String), cls.__name__) # REST properties _publish_attrs = ['url', 'reference_url'] _aliases = { "url": "Url", "reference_url": "Reference URL", } _fulltext_attrs = [ 'url', 'reference_url', ] @classmethod def indexed_query(cls): return super(Hyperlinked, cls).indexed_query().options( orm.Load(cls).load_only("url", "reference_url"), ) class Hierarchical(object): """Mixin that defines `parent` and `child` fields to organize hierarchy.""" @declared_attr def parent_id(cls): return deferred(db.Column( db.Integer, db.ForeignKey('{0}.id'.format(cls.__tablename__))), cls.__name__) @declared_attr def children(cls): return db.relationship( cls.__name__, backref=db.backref( 'parent', remote_side='{0}.id'.format(cls.__name__)), ) # REST properties _publish_attrs = [ 'children', 'parent', ] _fulltext_attrs = [ 'children', 'parent', ] @classmethod def indexed_query(cls): return super(Hierarchical, cls).indexed_query().options( orm.Load(cls).subqueryload("children"), orm.Load(cls).joinedload("parent"), ) @classmethod def eager_query(cls): query = super(Hierarchical, cls).eager_query() return query.options( orm.subqueryload('children'), # orm.joinedload('parent'), ) class Timeboxed(object): """Mixin that defines `start_date` and `end_date` fields.""" @declared_attr def start_date(cls): return deferred(db.Column(db.Date), cls.__name__) @declared_attr def end_date(cls): return deferred(db.Column(db.Date), cls.__name__) # REST properties _publish_attrs = ['start_date', 'end_date'] _aliases = { "start_date": "Effective Date", "end_date": "Stop Date", } _fulltext_attrs = [ attributes.DateFullTextAttr('start_date', 'start_date'), attributes.DateFullTextAttr('end_date', 'end_date'), ] @classmethod def indexed_query(cls): return super(Timeboxed, cls).indexed_query().options( orm.Load(cls).load_only("start_date", "end_date"), ) class Stateful(object): """Mixin that defines `status` field and status validation logic. TODO: unify with Statusable. """ @declared_attr def status(cls): return deferred(db.Column( db.String, default=cls.default_status, nullable=False), cls.__name__) _publish_attrs = ['status'] _fulltext_attrs = ['status'] _aliases = { "status": { "display_name": "State", "mandatory": False } } @classmethod def default_status(cls): return cls.valid_statuses()[0] @classmethod def valid_statuses(cls): return cls.VALID_STATES @validates('status') def validate_status(self, key, value): """Use default status if value is None, check that it is in valid set.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since there are other mixins that want to touch 'status'. if hasattr(super(Stateful, self), "validate_status"): value = super(Stateful, self).validate_status(key, value) if value is None: value = self.default_status() if value not in self.valid_statuses(): message = u"Invalid state '{}'".format(value) raise ValueError(message) return value @classmethod def indexed_query(cls): return super(Stateful, cls).indexed_query().options( orm.Load(cls).load_only("status"), ) class FinishedDate(object): """Adds 'Finished Date' which is set when status is set to a finished state. Requires Stateful to be mixed in as well. """ NOT_DONE_STATES = None DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def finished_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) _publish_attrs = [ reflection.PublishOnly('finished_date') ] _aliases = { "finished_date": "Finished Date" } _fulltext_attrs = [ attributes.DatetimeFullTextAttr('finished_date', 'finished_date'), ] @validates('status') def validate_status(self, key, value): """Update finished_date given the right status change.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since 'status' is not defined here. if hasattr(super(FinishedDate, self), "validate_status"): value = super(FinishedDate, self).validate_status(key, value) # pylint: disable=unsupported-membership-test # short circuit if (value in self.DONE_STATES and (self.NOT_DONE_STATES is None or self.status in self.NOT_DONE_STATES)): self.finished_date = datetime.datetime.now() elif ((self.NOT_DONE_STATES is None or value in self.NOT_DONE_STATES) and self.status in self.DONE_STATES): self.finished_date = None return value @classmethod def indexed_query(cls): return super(FinishedDate, cls).indexed_query().options( orm.Load(cls).load_only("finished_date"), ) class VerifiedDate(object): """Adds 'Verified Date' which is set when status is set to 'Verified'. When object is verified the status is overridden to 'Final' and the information about verification exposed as the 'verified' boolean. Requires Stateful to be mixed in as well. """ VERIFIED_STATES = {u"Verified"} DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def verified_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) @hybrid_property def verified(self): return self.verified_date != None # noqa _publish_attrs = [ reflection.PublishOnly('verified'), reflection.PublishOnly('verified_date'), ] _aliases = { "verified_date": "Verified Date" } _fulltext_attrs = [ attributes.DatetimeFullTextAttr("verified_date", "verified_date"), "verified", ] @classmethod def indexed_query(cls): return super(VerifiedDate, cls).indexed_query().options( orm.Load(cls).load_only("verified_date"), ) @validates('status') def validate_status(self, key, value): """Update verified_date on status change, make verified status final.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since 'status' is not defined here. if hasattr(super(VerifiedDate, self), "validate_status"): value = super(VerifiedDate, self).validate_status(key, value) if (value in self.VERIFIED_STATES and self.status not in self.VERIFIED_STATES): self.verified_date = datetime.datetime.now() value = self.FINAL_STATE elif (value not in self.VERIFIED_STATES and value not in self.DONE_STATES and (self.status in self.VERIFIED_STATES or self.status in self.DONE_STATES)): self.verified_date = None return value class ContextRBAC(object): """Defines `context` relationship for Context-based access control.""" @declared_attr def context_id(cls): return db.Column(db.Integer, db.ForeignKey('contexts.id')) @declared_attr def context(cls): return db.relationship('Context', uselist=False) @staticmethod def _extra_table_args(model): return ( db.Index('fk_{}_contexts'.format(model.__tablename__), 'context_id'), ) _publish_attrs = ['context'] @classmethod def indexed_query(cls): return super(ContextRBAC, cls).indexed_query().options( orm.Load(cls).load_only("context_id"), ) # @classmethod # def eager_query(cls): # from sqlalchemy import orm # query = super(ContextRBAC, cls).eager_query() # return query.options( # orm.subqueryload('context')) def is_attr_of_type(object_, attr_name, mapped_class): """Check if relationship property points to mapped_class""" cls = object_.__class__ if isinstance(attr_name, basestring): if hasattr(cls, attr_name): cls_attr = getattr(cls, attr_name) if (hasattr(cls_attr, "property") and isinstance(cls_attr.property, orm.properties.RelationshipProperty) and cls_attr.property.mapper.class_ == mapped_class): return True return False class Base(ChangeTracked, ContextRBAC, Identifiable): """Several of the models use the same mixins. This class covers that common case. """ _people_log_mappings = [ "principal_assessor_id", "secondary_assessor_id", "contact_id", "secondary_contact_id", "modified_by_id", "attribute_object_id", # used for person mapping CA ] @staticmethod def _person_stub(id_): return { 'type': u"Person", 'id': id_, 'context_id': None, 'href': u"/api/people/{}".format(id_), } def log_json_base(self): """Get a dict with attributes of self that is easy to serialize to json. This method lists only first-class attributes. """ res = {} for column in self.__table__.columns: try: res[column.name] = getattr(self, column.name) except AttributeError: pass res["display_name"] = self.display_name return res def log_json(self): """Get a dict with attributes and related objects of self. This method converts additionally person-mapping attributes and owners to person stubs. """ from ggrc import models res = self.log_json_base() for attr in self._people_log_mappings: if hasattr(self, attr): value = getattr(self, attr) # hardcoded [:-3] is used to strip "_id" suffix res[attr[:-3]] = self._person_stub(value) if value else None if hasattr(self, "owners"): res["owners"] = [ self._person_stub(owner.id) for owner in self.owners if owner ] for attr_name in AttributeInfo.gather_publish_attrs(self.__class__): if is_attr_of_type(self, attr_name, models.Option): attr = getattr(self, attr_name) if attr: stub = create_stub(attr) stub["title"] = attr.title else: stub = None res[attr_name] = stub return res @builder.simple_property def display_name(self): try: return self._display_name() except: # pylint: disable=bare-except logger.warning("display_name error in %s", type(self), exc_info=True) return "" def _display_name(self): return getattr(self, "title", None) or getattr(self, "name", "") def copy_into(self, target_object, columns, **kwargs): """Copy current object values into a target object. Copy all values listed in columns from current class to target class and use kwargs as defaults with precedence. Note that this is a shallow copy and any mutable values will be shared between current and target objects. Args: target_object: object to which we want to copy current values. This function will mutate the target_object parameter if it is set. columns: list with all attribute names that we want to set in the target_object. kwargs: additional default values. Returns: target_object with all values listed in columns set. """ target = target_object or type(self)() columns = set(columns).union(kwargs.keys()) for name in columns: if name in kwargs: value = kwargs[name] else: value = getattr(self, name) setattr(target, name, value) return target CACHED_ATTRIBUTE_MAP = None @classmethod def attributes_map(cls): if cls.CACHED_ATTRIBUTE_MAP: return cls.CACHED_ATTRIBUTE_MAP aliases = AttributeInfo.gather_aliases(cls) cls.CACHED_ATTRIBUTE_MAP = {} for key, value in aliases.items(): if isinstance(value, dict): name = value["display_name"] filter_by = None if value.get("filter_by"): filter_by = getattr(cls, value["filter_by"], None) else: name = value filter_by = None if not name: continue tmp = getattr(cls, "PROPERTY_TEMPLATE", "{}") name = tmp.format(name) key = tmp.format(key) cls.CACHED_ATTRIBUTE_MAP[name.lower()] = (key.lower(), filter_by) return cls.CACHED_ATTRIBUTE_MAP class Slugged(Base): """Several classes make use of the common mixins and additional are "slugged" and have additional fields related to their publishing in the system. """ @declared_attr def slug(cls): return deferred(db.Column(db.String, nullable=False), cls.__name__) @staticmethod def _extra_table_args(model): if getattr(model, '_slug_uniqueness', True): return ( db.UniqueConstraint('slug', name='uq_{}'.format(model.__tablename__)), ) return () # REST properties _publish_attrs = ['slug'] _fulltext_attrs = ['slug'] _sanitize_html = ['slug'] _aliases = { "slug": { "display_name": "Code", "description": ("Must be unique. Can be left empty for " "auto generation. If updating or deleting, " "code is required"), } } @classmethod def indexed_query(cls): return super(Slugged, cls).indexed_query().options( orm.Load(cls).load_only("slug"), ) @classmethod def generate_slug_for(cls, obj): _id = getattr(obj, 'id', uuid1()) obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id) # We need to make sure the generated slug is not already present in the # database. If it is, we increment the id until we find a slug that is # unique. # A better approach would be to query the database for slug uniqueness # only if the there was a conflict, but because we can't easily catch a # session rollback at this point we are sticking with a # suboptimal solution for now. INCREMENT = 1000 while cls.query.filter(cls.slug == obj.slug).count(): _id += INCREMENT obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id) @classmethod def generate_slug_prefix_for(cls, obj): return obj.__class__.__name__.upper() @classmethod def ensure_slug_before_flush(cls, session, flush_context, instances): """Set the slug to a default string so we don't run afoul of the NOT NULL constraint. """ # pylint: disable=unused-argument for o in session.new: if isinstance(o, Slugged) and (o.slug is None or o.slug == ''): o.slug = str(uuid1()) o._replace_slug = True @classmethod def ensure_slug_after_flush_postexec(cls, session, flush_context): """Replace the placeholder slug with a real slug that will be set on the next flush/commit. """ # pylint: disable=unused-argument for o in session.identity_map.values(): if isinstance(o, Slugged) and hasattr(o, '_replace_slug'): o.generate_slug_for(o) delattr(o, '_replace_slug') event.listen(Session, 'before_flush', Slugged.ensure_slug_before_flush) event.listen( Session, 'after_flush_postexec', Slugged.ensure_slug_after_flush_postexec) class WithContact(object): """Mixin that defines `contact` and `secondary_contact` fields.""" @declared_attr def contact_id(cls): return deferred( db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__) @declared_attr def secondary_contact_id(cls): return deferred( db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__) @declared_attr def contact(cls): return db.relationship( 'Person', uselist=False, foreign_keys='{}.contact_id'.format(cls.__name__)) @declared_attr def secondary_contact(cls): return db.relationship( 'Person', uselist=False, foreign_keys='{}.secondary_contact_id'.format(cls.__name__)) @staticmethod def _extra_table_args(model): return ( db.Index('fk_{}_contact'.format(model.__tablename__), 'contact_id'), db.Index('fk_{}_secondary_contact'.format( model.__tablename__), 'secondary_contact_id'), ) _publish_attrs = ['contact', 'secondary_contact'] _fulltext_attrs = [ attributes.FullTextAttr( "contact", "contact", ["name", "email"] ), attributes.FullTextAttr( 'secondary_contact', 'secondary_contact', ["name", "email"]), ] @classmethod def indexed_query(cls): return super(WithContact, cls).indexed_query().options( orm.Load(cls).joinedload( "contact" ).load_only( "name", "email", "id" ), orm.Load(cls).joinedload( "secondary_contact" ).load_only( "name", "email", "id" ), ) _aliases = { "contact": "Primary Contact", "secondary_contact": "Secondary Contact", } class BusinessObject(Stateful, Noted, Described, Hyperlinked, Titled, Slugged): """Mixin that groups most commonly-used mixins into one.""" VALID_STATES = ( 'Draft', 'Active', 'Deprecated' ) _aliases = { "status": { "display_name": "State", "mandatory": False, "description": "Options are:\n{}".format('\n'.join(VALID_STATES)) } } # This class is just a marker interface/mixin to indicate that a model type # supports custom attributes. class TestPlanned(object): """Mixin that defines `test_plan` field.""" @declared_attr def test_plan(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['test_plan'] _fulltext_attrs = ['test_plan'] _sanitize_html = ['test_plan'] _aliases = {"test_plan": "Test Plan"} @classmethod def indexed_query(cls): return super(TestPlanned, cls).indexed_query().options( orm.Load(cls).load_only("test_plan"), ) __all__ = [ "Base", "BusinessObject", "ChangeTracked", "ContextRBAC", "CustomAttributable", "Described", "FinishedDate", "Hierarchical", "Hyperlinked", "Identifiable", "Noted", "Notifiable", "Slugged", "Stateful", "TestPlanned", "Timeboxed", "Titled", "VerifiedDate", "WithContact", ]
from uuid import uuid1 import datetime
random_line_split
__init__.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Mixins to add common attributes and relationships. Note, all model classes must also inherit from ``db.Model``. For example: color color .. class Market(BusinessObject, db.Model): __tablename__ = 'markets' """ # pylint: disable=no-self-argument # All declared_attr properties that are class level as per sqlalchemy # documentatio, are reported as false positives by pylint. from logging import getLogger from uuid import uuid1 import datetime from sqlalchemy import event from sqlalchemy import orm from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.session import Session from ggrc import builder from ggrc import db from ggrc.models import reflection from ggrc.models.deferred import deferred from ggrc.models.inflector import ModelInflectorDescriptor from ggrc.models.reflection import AttributeInfo from ggrc.models.mixins.customattributable import CustomAttributable from ggrc.models.mixins.notifiable import Notifiable from ggrc.utils import create_stub from ggrc.fulltext import attributes # pylint: disable=invalid-name logger = getLogger(__name__) class Identifiable(object): """A model with an ``id`` property that is the primary key.""" id = db.Column(db.Integer, primary_key=True) # noqa # REST properties _publish_attrs = ['id', 'type'] _update_attrs = [] _inflector = ModelInflectorDescriptor() @builder.simple_property def type(self): return self.__class__.__name__ @classmethod def eager_query(cls): mapper_class = cls._sa_class_manager.mapper.base_mapper.class_ return db.session.query(cls).options( db.Load(mapper_class).undefer_group( mapper_class.__name__ + '_complete'), ) @classmethod def eager_inclusions(cls, query, include_links): """Load related items listed in include_links eagerly.""" options = [] for include_link in include_links: inclusion_class = getattr(cls, include_link).property.mapper.class_ options.append( orm.subqueryload(include_link) .undefer_group(inclusion_class.__name__ + '_complete')) return query.options(*options) @declared_attr def __table_args__(cls): extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args') table_args = [] table_dict = {} for table_arg in extra_table_args: if callable(table_arg): table_arg = table_arg() if isinstance(table_arg, (list, tuple, set)): if isinstance(table_arg[-1], (dict,)): table_dict.update(table_arg[-1]) table_args.extend(table_arg[:-1]) else: table_args.extend(table_arg) elif isinstance(table_arg, (dict,)): table_dict.update(table_arg) else: table_args.append(table_arg) if len(table_dict) > 0: table_args.append(table_dict) return tuple(table_args,) class ChangeTracked(object): """A model with fields to tracked the last user to modify the model, the creation time of the model, and the last time the model was updated. """ @declared_attr def modified_by_id(cls): """Id of user who did the last modification of the object.""" return deferred(db.Column(db.Integer), cls.__name__) @declared_attr def created_at(cls): """Date of creation. Set to current time on object creation.""" column = db.Column( db.DateTime, nullable=False, default=db.text('current_timestamp'), ) return deferred(column, cls.__name__) @declared_attr def updated_at(cls): """Date of last update. Set to current time on object creation/update.""" column = db.Column( db.DateTime, nullable=False, default=db.text('current_timestamp'), onupdate=db.text('current_timestamp'), ) return deferred(column, cls.__name__) @declared_attr def modified_by(cls): """Relationship to user referenced by modified_by_id.""" return db.relationship( 'Person', primaryjoin='{0}.modified_by_id == Person.id'.format(cls.__name__), foreign_keys='{0}.modified_by_id'.format(cls.__name__), uselist=False, ) @staticmethod def _extra_table_args(model): """Apply extra table args (like indexes) to model definition.""" return ( db.Index('ix_{}_updated_at'.format(model.__tablename__), 'updated_at'), ) # TODO Add a transaction id, this will be handy for generating etags # and for tracking the changes made to several resources together. # transaction_id = db.Column(db.Integer) # REST properties _publish_attrs = [ 'modified_by', 'created_at', 'updated_at', ] _fulltext_attrs = [ attributes.DatetimeFullTextAttr('created_at', 'created_at'), attributes.DatetimeFullTextAttr('updated_at', 'updated_at'), attributes.FullTextAttr("modified_by", "modified_by", ["name", "email"]), ] _update_attrs = [] _aliases = { "updated_at": { "display_name": "Last Updated", "filter_only": True, }, "created_at": { "display_name": "Created Date", "filter_only": True, }, } @classmethod def indexed_query(cls): return super(ChangeTracked, cls).indexed_query().options( orm.Load(cls).load_only("created_at", "updated_at"), orm.Load(cls).joinedload( "modified_by" ).load_only( "name", "email", "id" ), ) class Titled(object): """Mixin that defines `title` field. Strips title on update and defines optional UNIQUE constraint on it. """ @validates('title') def validate_title(self, key, value): """Validates and cleans Title that has leading/trailing spaces""" # pylint: disable=unused-argument,no-self-use return value if value is None else value.strip() @declared_attr def title(cls): return deferred(db.Column(db.String, nullable=False), cls.__name__) @classmethod def indexed_query(cls): return super(Titled, cls).indexed_query().options( orm.Load(cls).load_only("title"), ) @staticmethod def _extra_table_args(model): """If model._title_uniqueness is set, apply UNIQUE constraint to title.""" if getattr(model, '_title_uniqueness', True): return ( db.UniqueConstraint( 'title', name='uq_t_{}'.format(model.__tablename__)), ) return () # REST properties _publish_attrs = ['title'] _fulltext_attrs = ['title'] _sanitize_html = ['title'] _aliases = {"title": "Title"} class Described(object): """Mixin that defines `description` field.""" @declared_attr def description(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['description'] _fulltext_attrs = ['description'] _sanitize_html = ['description'] _aliases = {"description": "Description"} @classmethod def indexed_query(cls): return super(Described, cls).indexed_query().options( orm.Load(cls).load_only("description"), ) class Noted(object): """Mixin that defines `notes` field.""" @declared_attr def notes(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['notes'] _fulltext_attrs = ['notes'] _sanitize_html = ['notes'] _aliases = {"notes": "Notes"} @classmethod def indexed_query(cls): return super(Noted, cls).indexed_query().options( orm.Load(cls).load_only("notes"), ) class Hyperlinked(object): """Mixin that defines `url` and `reference_url` fields.""" @declared_attr def url(cls): return deferred(db.Column(db.String), cls.__name__) @declared_attr def reference_url(cls): return deferred(db.Column(db.String), cls.__name__) # REST properties _publish_attrs = ['url', 'reference_url'] _aliases = { "url": "Url", "reference_url": "Reference URL", } _fulltext_attrs = [ 'url', 'reference_url', ] @classmethod def indexed_query(cls):
class Hierarchical(object): """Mixin that defines `parent` and `child` fields to organize hierarchy.""" @declared_attr def parent_id(cls): return deferred(db.Column( db.Integer, db.ForeignKey('{0}.id'.format(cls.__tablename__))), cls.__name__) @declared_attr def children(cls): return db.relationship( cls.__name__, backref=db.backref( 'parent', remote_side='{0}.id'.format(cls.__name__)), ) # REST properties _publish_attrs = [ 'children', 'parent', ] _fulltext_attrs = [ 'children', 'parent', ] @classmethod def indexed_query(cls): return super(Hierarchical, cls).indexed_query().options( orm.Load(cls).subqueryload("children"), orm.Load(cls).joinedload("parent"), ) @classmethod def eager_query(cls): query = super(Hierarchical, cls).eager_query() return query.options( orm.subqueryload('children'), # orm.joinedload('parent'), ) class Timeboxed(object): """Mixin that defines `start_date` and `end_date` fields.""" @declared_attr def start_date(cls): return deferred(db.Column(db.Date), cls.__name__) @declared_attr def end_date(cls): return deferred(db.Column(db.Date), cls.__name__) # REST properties _publish_attrs = ['start_date', 'end_date'] _aliases = { "start_date": "Effective Date", "end_date": "Stop Date", } _fulltext_attrs = [ attributes.DateFullTextAttr('start_date', 'start_date'), attributes.DateFullTextAttr('end_date', 'end_date'), ] @classmethod def indexed_query(cls): return super(Timeboxed, cls).indexed_query().options( orm.Load(cls).load_only("start_date", "end_date"), ) class Stateful(object): """Mixin that defines `status` field and status validation logic. TODO: unify with Statusable. """ @declared_attr def status(cls): return deferred(db.Column( db.String, default=cls.default_status, nullable=False), cls.__name__) _publish_attrs = ['status'] _fulltext_attrs = ['status'] _aliases = { "status": { "display_name": "State", "mandatory": False } } @classmethod def default_status(cls): return cls.valid_statuses()[0] @classmethod def valid_statuses(cls): return cls.VALID_STATES @validates('status') def validate_status(self, key, value): """Use default status if value is None, check that it is in valid set.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since there are other mixins that want to touch 'status'. if hasattr(super(Stateful, self), "validate_status"): value = super(Stateful, self).validate_status(key, value) if value is None: value = self.default_status() if value not in self.valid_statuses(): message = u"Invalid state '{}'".format(value) raise ValueError(message) return value @classmethod def indexed_query(cls): return super(Stateful, cls).indexed_query().options( orm.Load(cls).load_only("status"), ) class FinishedDate(object): """Adds 'Finished Date' which is set when status is set to a finished state. Requires Stateful to be mixed in as well. """ NOT_DONE_STATES = None DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def finished_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) _publish_attrs = [ reflection.PublishOnly('finished_date') ] _aliases = { "finished_date": "Finished Date" } _fulltext_attrs = [ attributes.DatetimeFullTextAttr('finished_date', 'finished_date'), ] @validates('status') def validate_status(self, key, value): """Update finished_date given the right status change.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since 'status' is not defined here. if hasattr(super(FinishedDate, self), "validate_status"): value = super(FinishedDate, self).validate_status(key, value) # pylint: disable=unsupported-membership-test # short circuit if (value in self.DONE_STATES and (self.NOT_DONE_STATES is None or self.status in self.NOT_DONE_STATES)): self.finished_date = datetime.datetime.now() elif ((self.NOT_DONE_STATES is None or value in self.NOT_DONE_STATES) and self.status in self.DONE_STATES): self.finished_date = None return value @classmethod def indexed_query(cls): return super(FinishedDate, cls).indexed_query().options( orm.Load(cls).load_only("finished_date"), ) class VerifiedDate(object): """Adds 'Verified Date' which is set when status is set to 'Verified'. When object is verified the status is overridden to 'Final' and the information about verification exposed as the 'verified' boolean. Requires Stateful to be mixed in as well. """ VERIFIED_STATES = {u"Verified"} DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def verified_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) @hybrid_property def verified(self): return self.verified_date != None # noqa _publish_attrs = [ reflection.PublishOnly('verified'), reflection.PublishOnly('verified_date'), ] _aliases = { "verified_date": "Verified Date" } _fulltext_attrs = [ attributes.DatetimeFullTextAttr("verified_date", "verified_date"), "verified", ] @classmethod def indexed_query(cls): return super(VerifiedDate, cls).indexed_query().options( orm.Load(cls).load_only("verified_date"), ) @validates('status') def validate_status(self, key, value): """Update verified_date on status change, make verified status final.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since 'status' is not defined here. if hasattr(super(VerifiedDate, self), "validate_status"): value = super(VerifiedDate, self).validate_status(key, value) if (value in self.VERIFIED_STATES and self.status not in self.VERIFIED_STATES): self.verified_date = datetime.datetime.now() value = self.FINAL_STATE elif (value not in self.VERIFIED_STATES and value not in self.DONE_STATES and (self.status in self.VERIFIED_STATES or self.status in self.DONE_STATES)): self.verified_date = None return value class ContextRBAC(object): """Defines `context` relationship for Context-based access control.""" @declared_attr def context_id(cls): return db.Column(db.Integer, db.ForeignKey('contexts.id')) @declared_attr def context(cls): return db.relationship('Context', uselist=False) @staticmethod def _extra_table_args(model): return ( db.Index('fk_{}_contexts'.format(model.__tablename__), 'context_id'), ) _publish_attrs = ['context'] @classmethod def indexed_query(cls): return super(ContextRBAC, cls).indexed_query().options( orm.Load(cls).load_only("context_id"), ) # @classmethod # def eager_query(cls): # from sqlalchemy import orm # query = super(ContextRBAC, cls).eager_query() # return query.options( # orm.subqueryload('context')) def is_attr_of_type(object_, attr_name, mapped_class): """Check if relationship property points to mapped_class""" cls = object_.__class__ if isinstance(attr_name, basestring): if hasattr(cls, attr_name): cls_attr = getattr(cls, attr_name) if (hasattr(cls_attr, "property") and isinstance(cls_attr.property, orm.properties.RelationshipProperty) and cls_attr.property.mapper.class_ == mapped_class): return True return False class Base(ChangeTracked, ContextRBAC, Identifiable): """Several of the models use the same mixins. This class covers that common case. """ _people_log_mappings = [ "principal_assessor_id", "secondary_assessor_id", "contact_id", "secondary_contact_id", "modified_by_id", "attribute_object_id", # used for person mapping CA ] @staticmethod def _person_stub(id_): return { 'type': u"Person", 'id': id_, 'context_id': None, 'href': u"/api/people/{}".format(id_), } def log_json_base(self): """Get a dict with attributes of self that is easy to serialize to json. This method lists only first-class attributes. """ res = {} for column in self.__table__.columns: try: res[column.name] = getattr(self, column.name) except AttributeError: pass res["display_name"] = self.display_name return res def log_json(self): """Get a dict with attributes and related objects of self. This method converts additionally person-mapping attributes and owners to person stubs. """ from ggrc import models res = self.log_json_base() for attr in self._people_log_mappings: if hasattr(self, attr): value = getattr(self, attr) # hardcoded [:-3] is used to strip "_id" suffix res[attr[:-3]] = self._person_stub(value) if value else None if hasattr(self, "owners"): res["owners"] = [ self._person_stub(owner.id) for owner in self.owners if owner ] for attr_name in AttributeInfo.gather_publish_attrs(self.__class__): if is_attr_of_type(self, attr_name, models.Option): attr = getattr(self, attr_name) if attr: stub = create_stub(attr) stub["title"] = attr.title else: stub = None res[attr_name] = stub return res @builder.simple_property def display_name(self): try: return self._display_name() except: # pylint: disable=bare-except logger.warning("display_name error in %s", type(self), exc_info=True) return "" def _display_name(self): return getattr(self, "title", None) or getattr(self, "name", "") def copy_into(self, target_object, columns, **kwargs): """Copy current object values into a target object. Copy all values listed in columns from current class to target class and use kwargs as defaults with precedence. Note that this is a shallow copy and any mutable values will be shared between current and target objects. Args: target_object: object to which we want to copy current values. This function will mutate the target_object parameter if it is set. columns: list with all attribute names that we want to set in the target_object. kwargs: additional default values. Returns: target_object with all values listed in columns set. """ target = target_object or type(self)() columns = set(columns).union(kwargs.keys()) for name in columns: if name in kwargs: value = kwargs[name] else: value = getattr(self, name) setattr(target, name, value) return target CACHED_ATTRIBUTE_MAP = None @classmethod def attributes_map(cls): if cls.CACHED_ATTRIBUTE_MAP: return cls.CACHED_ATTRIBUTE_MAP aliases = AttributeInfo.gather_aliases(cls) cls.CACHED_ATTRIBUTE_MAP = {} for key, value in aliases.items(): if isinstance(value, dict): name = value["display_name"] filter_by = None if value.get("filter_by"): filter_by = getattr(cls, value["filter_by"], None) else: name = value filter_by = None if not name: continue tmp = getattr(cls, "PROPERTY_TEMPLATE", "{}") name = tmp.format(name) key = tmp.format(key) cls.CACHED_ATTRIBUTE_MAP[name.lower()] = (key.lower(), filter_by) return cls.CACHED_ATTRIBUTE_MAP class Slugged(Base): """Several classes make use of the common mixins and additional are "slugged" and have additional fields related to their publishing in the system. """ @declared_attr def slug(cls): return deferred(db.Column(db.String, nullable=False), cls.__name__) @staticmethod def _extra_table_args(model): if getattr(model, '_slug_uniqueness', True): return ( db.UniqueConstraint('slug', name='uq_{}'.format(model.__tablename__)), ) return () # REST properties _publish_attrs = ['slug'] _fulltext_attrs = ['slug'] _sanitize_html = ['slug'] _aliases = { "slug": { "display_name": "Code", "description": ("Must be unique. Can be left empty for " "auto generation. If updating or deleting, " "code is required"), } } @classmethod def indexed_query(cls): return super(Slugged, cls).indexed_query().options( orm.Load(cls).load_only("slug"), ) @classmethod def generate_slug_for(cls, obj): _id = getattr(obj, 'id', uuid1()) obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id) # We need to make sure the generated slug is not already present in the # database. If it is, we increment the id until we find a slug that is # unique. # A better approach would be to query the database for slug uniqueness # only if the there was a conflict, but because we can't easily catch a # session rollback at this point we are sticking with a # suboptimal solution for now. INCREMENT = 1000 while cls.query.filter(cls.slug == obj.slug).count(): _id += INCREMENT obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id) @classmethod def generate_slug_prefix_for(cls, obj): return obj.__class__.__name__.upper() @classmethod def ensure_slug_before_flush(cls, session, flush_context, instances): """Set the slug to a default string so we don't run afoul of the NOT NULL constraint. """ # pylint: disable=unused-argument for o in session.new: if isinstance(o, Slugged) and (o.slug is None or o.slug == ''): o.slug = str(uuid1()) o._replace_slug = True @classmethod def ensure_slug_after_flush_postexec(cls, session, flush_context): """Replace the placeholder slug with a real slug that will be set on the next flush/commit. """ # pylint: disable=unused-argument for o in session.identity_map.values(): if isinstance(o, Slugged) and hasattr(o, '_replace_slug'): o.generate_slug_for(o) delattr(o, '_replace_slug') event.listen(Session, 'before_flush', Slugged.ensure_slug_before_flush) event.listen( Session, 'after_flush_postexec', Slugged.ensure_slug_after_flush_postexec) class WithContact(object): """Mixin that defines `contact` and `secondary_contact` fields.""" @declared_attr def contact_id(cls): return deferred( db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__) @declared_attr def secondary_contact_id(cls): return deferred( db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__) @declared_attr def contact(cls): return db.relationship( 'Person', uselist=False, foreign_keys='{}.contact_id'.format(cls.__name__)) @declared_attr def secondary_contact(cls): return db.relationship( 'Person', uselist=False, foreign_keys='{}.secondary_contact_id'.format(cls.__name__)) @staticmethod def _extra_table_args(model): return ( db.Index('fk_{}_contact'.format(model.__tablename__), 'contact_id'), db.Index('fk_{}_secondary_contact'.format( model.__tablename__), 'secondary_contact_id'), ) _publish_attrs = ['contact', 'secondary_contact'] _fulltext_attrs = [ attributes.FullTextAttr( "contact", "contact", ["name", "email"] ), attributes.FullTextAttr( 'secondary_contact', 'secondary_contact', ["name", "email"]), ] @classmethod def indexed_query(cls): return super(WithContact, cls).indexed_query().options( orm.Load(cls).joinedload( "contact" ).load_only( "name", "email", "id" ), orm.Load(cls).joinedload( "secondary_contact" ).load_only( "name", "email", "id" ), ) _aliases = { "contact": "Primary Contact", "secondary_contact": "Secondary Contact", } class BusinessObject(Stateful, Noted, Described, Hyperlinked, Titled, Slugged): """Mixin that groups most commonly-used mixins into one.""" VALID_STATES = ( 'Draft', 'Active', 'Deprecated' ) _aliases = { "status": { "display_name": "State", "mandatory": False, "description": "Options are:\n{}".format('\n'.join(VALID_STATES)) } } # This class is just a marker interface/mixin to indicate that a model type # supports custom attributes. class TestPlanned(object): """Mixin that defines `test_plan` field.""" @declared_attr def test_plan(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['test_plan'] _fulltext_attrs = ['test_plan'] _sanitize_html = ['test_plan'] _aliases = {"test_plan": "Test Plan"} @classmethod def indexed_query(cls): return super(TestPlanned, cls).indexed_query().options( orm.Load(cls).load_only("test_plan"), ) __all__ = [ "Base", "BusinessObject", "ChangeTracked", "ContextRBAC", "CustomAttributable", "Described", "FinishedDate", "Hierarchical", "Hyperlinked", "Identifiable", "Noted", "Notifiable", "Slugged", "Stateful", "TestPlanned", "Timeboxed", "Titled", "VerifiedDate", "WithContact", ]
return super(Hyperlinked, cls).indexed_query().options( orm.Load(cls).load_only("url", "reference_url"), )
identifier_body
__init__.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Mixins to add common attributes and relationships. Note, all model classes must also inherit from ``db.Model``. For example: color color .. class Market(BusinessObject, db.Model): __tablename__ = 'markets' """ # pylint: disable=no-self-argument # All declared_attr properties that are class level as per sqlalchemy # documentatio, are reported as false positives by pylint. from logging import getLogger from uuid import uuid1 import datetime from sqlalchemy import event from sqlalchemy import orm from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.session import Session from ggrc import builder from ggrc import db from ggrc.models import reflection from ggrc.models.deferred import deferred from ggrc.models.inflector import ModelInflectorDescriptor from ggrc.models.reflection import AttributeInfo from ggrc.models.mixins.customattributable import CustomAttributable from ggrc.models.mixins.notifiable import Notifiable from ggrc.utils import create_stub from ggrc.fulltext import attributes # pylint: disable=invalid-name logger = getLogger(__name__) class Identifiable(object): """A model with an ``id`` property that is the primary key.""" id = db.Column(db.Integer, primary_key=True) # noqa # REST properties _publish_attrs = ['id', 'type'] _update_attrs = [] _inflector = ModelInflectorDescriptor() @builder.simple_property def type(self): return self.__class__.__name__ @classmethod def eager_query(cls): mapper_class = cls._sa_class_manager.mapper.base_mapper.class_ return db.session.query(cls).options( db.Load(mapper_class).undefer_group( mapper_class.__name__ + '_complete'), ) @classmethod def eager_inclusions(cls, query, include_links): """Load related items listed in include_links eagerly.""" options = [] for include_link in include_links: inclusion_class = getattr(cls, include_link).property.mapper.class_ options.append( orm.subqueryload(include_link) .undefer_group(inclusion_class.__name__ + '_complete')) return query.options(*options) @declared_attr def __table_args__(cls): extra_table_args = AttributeInfo.gather_attrs(cls, '_extra_table_args') table_args = [] table_dict = {} for table_arg in extra_table_args: if callable(table_arg): table_arg = table_arg() if isinstance(table_arg, (list, tuple, set)): if isinstance(table_arg[-1], (dict,)): table_dict.update(table_arg[-1]) table_args.extend(table_arg[:-1]) else: table_args.extend(table_arg) elif isinstance(table_arg, (dict,)): table_dict.update(table_arg) else: table_args.append(table_arg) if len(table_dict) > 0: table_args.append(table_dict) return tuple(table_args,) class ChangeTracked(object): """A model with fields to tracked the last user to modify the model, the creation time of the model, and the last time the model was updated. """ @declared_attr def modified_by_id(cls): """Id of user who did the last modification of the object.""" return deferred(db.Column(db.Integer), cls.__name__) @declared_attr def created_at(cls): """Date of creation. Set to current time on object creation.""" column = db.Column( db.DateTime, nullable=False, default=db.text('current_timestamp'), ) return deferred(column, cls.__name__) @declared_attr def updated_at(cls): """Date of last update. Set to current time on object creation/update.""" column = db.Column( db.DateTime, nullable=False, default=db.text('current_timestamp'), onupdate=db.text('current_timestamp'), ) return deferred(column, cls.__name__) @declared_attr def modified_by(cls): """Relationship to user referenced by modified_by_id.""" return db.relationship( 'Person', primaryjoin='{0}.modified_by_id == Person.id'.format(cls.__name__), foreign_keys='{0}.modified_by_id'.format(cls.__name__), uselist=False, ) @staticmethod def _extra_table_args(model): """Apply extra table args (like indexes) to model definition.""" return ( db.Index('ix_{}_updated_at'.format(model.__tablename__), 'updated_at'), ) # TODO Add a transaction id, this will be handy for generating etags # and for tracking the changes made to several resources together. # transaction_id = db.Column(db.Integer) # REST properties _publish_attrs = [ 'modified_by', 'created_at', 'updated_at', ] _fulltext_attrs = [ attributes.DatetimeFullTextAttr('created_at', 'created_at'), attributes.DatetimeFullTextAttr('updated_at', 'updated_at'), attributes.FullTextAttr("modified_by", "modified_by", ["name", "email"]), ] _update_attrs = [] _aliases = { "updated_at": { "display_name": "Last Updated", "filter_only": True, }, "created_at": { "display_name": "Created Date", "filter_only": True, }, } @classmethod def indexed_query(cls): return super(ChangeTracked, cls).indexed_query().options( orm.Load(cls).load_only("created_at", "updated_at"), orm.Load(cls).joinedload( "modified_by" ).load_only( "name", "email", "id" ), ) class Titled(object): """Mixin that defines `title` field. Strips title on update and defines optional UNIQUE constraint on it. """ @validates('title') def validate_title(self, key, value): """Validates and cleans Title that has leading/trailing spaces""" # pylint: disable=unused-argument,no-self-use return value if value is None else value.strip() @declared_attr def title(cls): return deferred(db.Column(db.String, nullable=False), cls.__name__) @classmethod def indexed_query(cls): return super(Titled, cls).indexed_query().options( orm.Load(cls).load_only("title"), ) @staticmethod def _extra_table_args(model): """If model._title_uniqueness is set, apply UNIQUE constraint to title.""" if getattr(model, '_title_uniqueness', True): return ( db.UniqueConstraint( 'title', name='uq_t_{}'.format(model.__tablename__)), ) return () # REST properties _publish_attrs = ['title'] _fulltext_attrs = ['title'] _sanitize_html = ['title'] _aliases = {"title": "Title"} class Described(object): """Mixin that defines `description` field.""" @declared_attr def description(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['description'] _fulltext_attrs = ['description'] _sanitize_html = ['description'] _aliases = {"description": "Description"} @classmethod def indexed_query(cls): return super(Described, cls).indexed_query().options( orm.Load(cls).load_only("description"), ) class Noted(object): """Mixin that defines `notes` field.""" @declared_attr def notes(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['notes'] _fulltext_attrs = ['notes'] _sanitize_html = ['notes'] _aliases = {"notes": "Notes"} @classmethod def indexed_query(cls): return super(Noted, cls).indexed_query().options( orm.Load(cls).load_only("notes"), ) class Hyperlinked(object): """Mixin that defines `url` and `reference_url` fields.""" @declared_attr def url(cls): return deferred(db.Column(db.String), cls.__name__) @declared_attr def reference_url(cls): return deferred(db.Column(db.String), cls.__name__) # REST properties _publish_attrs = ['url', 'reference_url'] _aliases = { "url": "Url", "reference_url": "Reference URL", } _fulltext_attrs = [ 'url', 'reference_url', ] @classmethod def indexed_query(cls): return super(Hyperlinked, cls).indexed_query().options( orm.Load(cls).load_only("url", "reference_url"), ) class Hierarchical(object): """Mixin that defines `parent` and `child` fields to organize hierarchy.""" @declared_attr def parent_id(cls): return deferred(db.Column( db.Integer, db.ForeignKey('{0}.id'.format(cls.__tablename__))), cls.__name__) @declared_attr def children(cls): return db.relationship( cls.__name__, backref=db.backref( 'parent', remote_side='{0}.id'.format(cls.__name__)), ) # REST properties _publish_attrs = [ 'children', 'parent', ] _fulltext_attrs = [ 'children', 'parent', ] @classmethod def indexed_query(cls): return super(Hierarchical, cls).indexed_query().options( orm.Load(cls).subqueryload("children"), orm.Load(cls).joinedload("parent"), ) @classmethod def eager_query(cls): query = super(Hierarchical, cls).eager_query() return query.options( orm.subqueryload('children'), # orm.joinedload('parent'), ) class Timeboxed(object): """Mixin that defines `start_date` and `end_date` fields.""" @declared_attr def start_date(cls): return deferred(db.Column(db.Date), cls.__name__) @declared_attr def end_date(cls): return deferred(db.Column(db.Date), cls.__name__) # REST properties _publish_attrs = ['start_date', 'end_date'] _aliases = { "start_date": "Effective Date", "end_date": "Stop Date", } _fulltext_attrs = [ attributes.DateFullTextAttr('start_date', 'start_date'), attributes.DateFullTextAttr('end_date', 'end_date'), ] @classmethod def indexed_query(cls): return super(Timeboxed, cls).indexed_query().options( orm.Load(cls).load_only("start_date", "end_date"), ) class Stateful(object): """Mixin that defines `status` field and status validation logic. TODO: unify with Statusable. """ @declared_attr def status(cls): return deferred(db.Column( db.String, default=cls.default_status, nullable=False), cls.__name__) _publish_attrs = ['status'] _fulltext_attrs = ['status'] _aliases = { "status": { "display_name": "State", "mandatory": False } } @classmethod def default_status(cls): return cls.valid_statuses()[0] @classmethod def valid_statuses(cls): return cls.VALID_STATES @validates('status') def validate_status(self, key, value): """Use default status if value is None, check that it is in valid set.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since there are other mixins that want to touch 'status'. if hasattr(super(Stateful, self), "validate_status"): value = super(Stateful, self).validate_status(key, value) if value is None: value = self.default_status() if value not in self.valid_statuses(): message = u"Invalid state '{}'".format(value) raise ValueError(message) return value @classmethod def indexed_query(cls): return super(Stateful, cls).indexed_query().options( orm.Load(cls).load_only("status"), ) class FinishedDate(object): """Adds 'Finished Date' which is set when status is set to a finished state. Requires Stateful to be mixed in as well. """ NOT_DONE_STATES = None DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def finished_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) _publish_attrs = [ reflection.PublishOnly('finished_date') ] _aliases = { "finished_date": "Finished Date" } _fulltext_attrs = [ attributes.DatetimeFullTextAttr('finished_date', 'finished_date'), ] @validates('status') def validate_status(self, key, value): """Update finished_date given the right status change.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since 'status' is not defined here. if hasattr(super(FinishedDate, self), "validate_status"): value = super(FinishedDate, self).validate_status(key, value) # pylint: disable=unsupported-membership-test # short circuit if (value in self.DONE_STATES and (self.NOT_DONE_STATES is None or self.status in self.NOT_DONE_STATES)): self.finished_date = datetime.datetime.now() elif ((self.NOT_DONE_STATES is None or value in self.NOT_DONE_STATES) and self.status in self.DONE_STATES): self.finished_date = None return value @classmethod def indexed_query(cls): return super(FinishedDate, cls).indexed_query().options( orm.Load(cls).load_only("finished_date"), ) class VerifiedDate(object): """Adds 'Verified Date' which is set when status is set to 'Verified'. When object is verified the status is overridden to 'Final' and the information about verification exposed as the 'verified' boolean. Requires Stateful to be mixed in as well. """ VERIFIED_STATES = {u"Verified"} DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def verified_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) @hybrid_property def verified(self): return self.verified_date != None # noqa _publish_attrs = [ reflection.PublishOnly('verified'), reflection.PublishOnly('verified_date'), ] _aliases = { "verified_date": "Verified Date" } _fulltext_attrs = [ attributes.DatetimeFullTextAttr("verified_date", "verified_date"), "verified", ] @classmethod def indexed_query(cls): return super(VerifiedDate, cls).indexed_query().options( orm.Load(cls).load_only("verified_date"), ) @validates('status') def validate_status(self, key, value): """Update verified_date on status change, make verified status final.""" # Sqlalchemy only uses one validator per status (not necessarily the # first) and ignores others. This enables cooperation between validators # since 'status' is not defined here. if hasattr(super(VerifiedDate, self), "validate_status"): value = super(VerifiedDate, self).validate_status(key, value) if (value in self.VERIFIED_STATES and self.status not in self.VERIFIED_STATES): self.verified_date = datetime.datetime.now() value = self.FINAL_STATE elif (value not in self.VERIFIED_STATES and value not in self.DONE_STATES and (self.status in self.VERIFIED_STATES or self.status in self.DONE_STATES)): self.verified_date = None return value class ContextRBAC(object): """Defines `context` relationship for Context-based access control.""" @declared_attr def context_id(cls): return db.Column(db.Integer, db.ForeignKey('contexts.id')) @declared_attr def context(cls): return db.relationship('Context', uselist=False) @staticmethod def _extra_table_args(model): return ( db.Index('fk_{}_contexts'.format(model.__tablename__), 'context_id'), ) _publish_attrs = ['context'] @classmethod def indexed_query(cls): return super(ContextRBAC, cls).indexed_query().options( orm.Load(cls).load_only("context_id"), ) # @classmethod # def eager_query(cls): # from sqlalchemy import orm # query = super(ContextRBAC, cls).eager_query() # return query.options( # orm.subqueryload('context')) def is_attr_of_type(object_, attr_name, mapped_class): """Check if relationship property points to mapped_class""" cls = object_.__class__ if isinstance(attr_name, basestring): if hasattr(cls, attr_name): cls_attr = getattr(cls, attr_name) if (hasattr(cls_attr, "property") and isinstance(cls_attr.property, orm.properties.RelationshipProperty) and cls_attr.property.mapper.class_ == mapped_class): return True return False class Base(ChangeTracked, ContextRBAC, Identifiable): """Several of the models use the same mixins. This class covers that common case. """ _people_log_mappings = [ "principal_assessor_id", "secondary_assessor_id", "contact_id", "secondary_contact_id", "modified_by_id", "attribute_object_id", # used for person mapping CA ] @staticmethod def _person_stub(id_): return { 'type': u"Person", 'id': id_, 'context_id': None, 'href': u"/api/people/{}".format(id_), } def log_json_base(self): """Get a dict with attributes of self that is easy to serialize to json. This method lists only first-class attributes. """ res = {} for column in self.__table__.columns: try: res[column.name] = getattr(self, column.name) except AttributeError: pass res["display_name"] = self.display_name return res def log_json(self): """Get a dict with attributes and related objects of self. This method converts additionally person-mapping attributes and owners to person stubs. """ from ggrc import models res = self.log_json_base() for attr in self._people_log_mappings: if hasattr(self, attr): value = getattr(self, attr) # hardcoded [:-3] is used to strip "_id" suffix res[attr[:-3]] = self._person_stub(value) if value else None if hasattr(self, "owners"): res["owners"] = [ self._person_stub(owner.id) for owner in self.owners if owner ] for attr_name in AttributeInfo.gather_publish_attrs(self.__class__): if is_attr_of_type(self, attr_name, models.Option): attr = getattr(self, attr_name) if attr: stub = create_stub(attr) stub["title"] = attr.title else: stub = None res[attr_name] = stub return res @builder.simple_property def display_name(self): try: return self._display_name() except: # pylint: disable=bare-except logger.warning("display_name error in %s", type(self), exc_info=True) return "" def _display_name(self): return getattr(self, "title", None) or getattr(self, "name", "") def copy_into(self, target_object, columns, **kwargs): """Copy current object values into a target object. Copy all values listed in columns from current class to target class and use kwargs as defaults with precedence. Note that this is a shallow copy and any mutable values will be shared between current and target objects. Args: target_object: object to which we want to copy current values. This function will mutate the target_object parameter if it is set. columns: list with all attribute names that we want to set in the target_object. kwargs: additional default values. Returns: target_object with all values listed in columns set. """ target = target_object or type(self)() columns = set(columns).union(kwargs.keys()) for name in columns: if name in kwargs: value = kwargs[name] else: value = getattr(self, name) setattr(target, name, value) return target CACHED_ATTRIBUTE_MAP = None @classmethod def attributes_map(cls): if cls.CACHED_ATTRIBUTE_MAP: return cls.CACHED_ATTRIBUTE_MAP aliases = AttributeInfo.gather_aliases(cls) cls.CACHED_ATTRIBUTE_MAP = {} for key, value in aliases.items(): if isinstance(value, dict): name = value["display_name"] filter_by = None if value.get("filter_by"): filter_by = getattr(cls, value["filter_by"], None) else: name = value filter_by = None if not name: continue tmp = getattr(cls, "PROPERTY_TEMPLATE", "{}") name = tmp.format(name) key = tmp.format(key) cls.CACHED_ATTRIBUTE_MAP[name.lower()] = (key.lower(), filter_by) return cls.CACHED_ATTRIBUTE_MAP class Slugged(Base): """Several classes make use of the common mixins and additional are "slugged" and have additional fields related to their publishing in the system. """ @declared_attr def slug(cls): return deferred(db.Column(db.String, nullable=False), cls.__name__) @staticmethod def _extra_table_args(model): if getattr(model, '_slug_uniqueness', True): return ( db.UniqueConstraint('slug', name='uq_{}'.format(model.__tablename__)), ) return () # REST properties _publish_attrs = ['slug'] _fulltext_attrs = ['slug'] _sanitize_html = ['slug'] _aliases = { "slug": { "display_name": "Code", "description": ("Must be unique. Can be left empty for " "auto generation. If updating or deleting, " "code is required"), } } @classmethod def indexed_query(cls): return super(Slugged, cls).indexed_query().options( orm.Load(cls).load_only("slug"), ) @classmethod def generate_slug_for(cls, obj): _id = getattr(obj, 'id', uuid1()) obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id) # We need to make sure the generated slug is not already present in the # database. If it is, we increment the id until we find a slug that is # unique. # A better approach would be to query the database for slug uniqueness # only if the there was a conflict, but because we can't easily catch a # session rollback at this point we are sticking with a # suboptimal solution for now. INCREMENT = 1000 while cls.query.filter(cls.slug == obj.slug).count(): _id += INCREMENT obj.slug = "{0}-{1}".format(cls.generate_slug_prefix_for(obj), _id) @classmethod def
(cls, obj): return obj.__class__.__name__.upper() @classmethod def ensure_slug_before_flush(cls, session, flush_context, instances): """Set the slug to a default string so we don't run afoul of the NOT NULL constraint. """ # pylint: disable=unused-argument for o in session.new: if isinstance(o, Slugged) and (o.slug is None or o.slug == ''): o.slug = str(uuid1()) o._replace_slug = True @classmethod def ensure_slug_after_flush_postexec(cls, session, flush_context): """Replace the placeholder slug with a real slug that will be set on the next flush/commit. """ # pylint: disable=unused-argument for o in session.identity_map.values(): if isinstance(o, Slugged) and hasattr(o, '_replace_slug'): o.generate_slug_for(o) delattr(o, '_replace_slug') event.listen(Session, 'before_flush', Slugged.ensure_slug_before_flush) event.listen( Session, 'after_flush_postexec', Slugged.ensure_slug_after_flush_postexec) class WithContact(object): """Mixin that defines `contact` and `secondary_contact` fields.""" @declared_attr def contact_id(cls): return deferred( db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__) @declared_attr def secondary_contact_id(cls): return deferred( db.Column(db.Integer, db.ForeignKey('people.id')), cls.__name__) @declared_attr def contact(cls): return db.relationship( 'Person', uselist=False, foreign_keys='{}.contact_id'.format(cls.__name__)) @declared_attr def secondary_contact(cls): return db.relationship( 'Person', uselist=False, foreign_keys='{}.secondary_contact_id'.format(cls.__name__)) @staticmethod def _extra_table_args(model): return ( db.Index('fk_{}_contact'.format(model.__tablename__), 'contact_id'), db.Index('fk_{}_secondary_contact'.format( model.__tablename__), 'secondary_contact_id'), ) _publish_attrs = ['contact', 'secondary_contact'] _fulltext_attrs = [ attributes.FullTextAttr( "contact", "contact", ["name", "email"] ), attributes.FullTextAttr( 'secondary_contact', 'secondary_contact', ["name", "email"]), ] @classmethod def indexed_query(cls): return super(WithContact, cls).indexed_query().options( orm.Load(cls).joinedload( "contact" ).load_only( "name", "email", "id" ), orm.Load(cls).joinedload( "secondary_contact" ).load_only( "name", "email", "id" ), ) _aliases = { "contact": "Primary Contact", "secondary_contact": "Secondary Contact", } class BusinessObject(Stateful, Noted, Described, Hyperlinked, Titled, Slugged): """Mixin that groups most commonly-used mixins into one.""" VALID_STATES = ( 'Draft', 'Active', 'Deprecated' ) _aliases = { "status": { "display_name": "State", "mandatory": False, "description": "Options are:\n{}".format('\n'.join(VALID_STATES)) } } # This class is just a marker interface/mixin to indicate that a model type # supports custom attributes. class TestPlanned(object): """Mixin that defines `test_plan` field.""" @declared_attr def test_plan(cls): return deferred(db.Column(db.Text), cls.__name__) # REST properties _publish_attrs = ['test_plan'] _fulltext_attrs = ['test_plan'] _sanitize_html = ['test_plan'] _aliases = {"test_plan": "Test Plan"} @classmethod def indexed_query(cls): return super(TestPlanned, cls).indexed_query().options( orm.Load(cls).load_only("test_plan"), ) __all__ = [ "Base", "BusinessObject", "ChangeTracked", "ContextRBAC", "CustomAttributable", "Described", "FinishedDate", "Hierarchical", "Hyperlinked", "Identifiable", "Noted", "Notifiable", "Slugged", "Stateful", "TestPlanned", "Timeboxed", "Titled", "VerifiedDate", "WithContact", ]
generate_slug_prefix_for
identifier_name
pcValidation.js
/* * 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. */ import angular from 'angular'; export class IgniteFormField { static animName = 'ignite-form-field__error-blink'; static eventName = 'webkitAnimationEnd oAnimationEnd msAnimationEnd animationend'; static $inject = ['$element', '$scope']; constructor($element, $scope) { Object.assign(this, {$element}); this.$scope = $scope; } $postLink() { this.onAnimEnd = () => this.$element.removeClass(IgniteFormField.animName); this.$element.on(IgniteFormField.eventName, this.onAnimEnd); } $onDestroy() { this.$element.off(IgniteFormField.eventName, this.onAnimEnd); this.$element = this.onAnimEnd = null; } notifyAboutError() { if (this.$element) this.$element.addClass(IgniteFormField.animName); } /** * Exposes control in $scope * @param {ng.INgModelController} control */ exposeControl(control, name = '$input') { this.$scope[name] = control; this.$scope.$on('$destroy', () => this.$scope[name] = null); } } export default angular.module('ignite-console.page-configure.validation', []) .directive('pcNotInCollection', function() { class Controller { /** @type {ng.INgModelController} */ ngModel; /** @type {Array} */ items; $onInit() { this.ngModel.$validators.notInCollection = (item) => { if (!this.items) return true; return !this.items.includes(item); }; } $onChanges() { this.ngModel.$validate(); } } return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: { items: '<pcNotInCollection' } }; }) .directive('pcInCollection', function() { class Controller { /** @type {ng.INgModelController} */ ngModel; /** @type {Array} */ items; /** @type {string} */ pluck; $onInit() { this.ngModel.$validators.inCollection = (item) => { if (!this.items) return false; const items = this.pluck ? this.items.map((i) => i[this.pluck]) : this.items; return Array.isArray(item) ? item.every((i) => items.includes(i)) : items.includes(item); }; } $onChanges()
} return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: { items: '<pcInCollection', pluck: '@?pcInCollectionPluck' } }; }) .directive('pcPowerOfTwo', function() { class Controller { /** @type {ng.INgModelController} */ ngModel; $onInit() { this.ngModel.$validators.powerOfTwo = (value) => { return !value || ((value & -value) === value); }; } } return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: true }; }) .directive('bsCollapseTarget', function() { return { require: { bsCollapse: '^^bsCollapse' }, bindToController: true, controller: ['$element', '$scope', function($element, $scope) { this.open = function() { const index = this.bsCollapse.$targets.indexOf($element); const isActive = this.bsCollapse.$targets.$active.includes(index); if (!isActive) this.bsCollapse.$setActive(index); }; this.$onDestroy = () => this.open = $element = null; }] }; }) .directive('ngModel', ['$timeout', function($timeout) { return { require: ['ngModel', '?^^bsCollapseTarget', '?^^igniteFormField', '?^^panelCollapsible'], link(scope, el, attr, [ngModel, bsCollapseTarget, igniteFormField, panelCollapsible]) { const off = scope.$on('$showValidationError', (e, target) => { if (target !== ngModel) return; ngModel.$setTouched(); bsCollapseTarget && bsCollapseTarget.open(); panelCollapsible && panelCollapsible.open(); $timeout(() => { if (el[0].scrollIntoViewIfNeeded) el[0].scrollIntoViewIfNeeded(); else el[0].scrollIntoView(); if (!attr.bsSelect) $timeout(() => el[0].focus()); igniteFormField && igniteFormField.notifyAboutError(); }); }); } }; }]) .directive('igniteFormField', function() { return { restrict: 'C', controller: IgniteFormField, scope: true }; }) .directive('isValidJavaIdentifier', ['IgniteLegacyUtils', function(LegacyUtils) { return { link(scope, el, attr, ngModel) { ngModel.$validators.isValidJavaIdentifier = (value) => LegacyUtils.VALID_JAVA_IDENTIFIER.test(value); }, require: 'ngModel' }; }]) .directive('notJavaReservedWord', ['IgniteLegacyUtils', function(LegacyUtils) { return { link(scope, el, attr, ngModel) { ngModel.$validators.notJavaReservedWord = (value) => !LegacyUtils.JAVA_KEYWORDS.includes(value); }, require: 'ngModel' }; }]);
{ this.ngModel.$validate(); }
identifier_body
pcValidation.js
/* * 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. */ import angular from 'angular'; export class IgniteFormField { static animName = 'ignite-form-field__error-blink'; static eventName = 'webkitAnimationEnd oAnimationEnd msAnimationEnd animationend'; static $inject = ['$element', '$scope']; constructor($element, $scope) { Object.assign(this, {$element}); this.$scope = $scope; } $postLink() { this.onAnimEnd = () => this.$element.removeClass(IgniteFormField.animName); this.$element.on(IgniteFormField.eventName, this.onAnimEnd); } $onDestroy() { this.$element.off(IgniteFormField.eventName, this.onAnimEnd); this.$element = this.onAnimEnd = null; } notifyAboutError() { if (this.$element) this.$element.addClass(IgniteFormField.animName); } /** * Exposes control in $scope * @param {ng.INgModelController} control */ exposeControl(control, name = '$input') { this.$scope[name] = control; this.$scope.$on('$destroy', () => this.$scope[name] = null); } } export default angular.module('ignite-console.page-configure.validation', []) .directive('pcNotInCollection', function() {
/** @type {ng.INgModelController} */ ngModel; /** @type {Array} */ items; $onInit() { this.ngModel.$validators.notInCollection = (item) => { if (!this.items) return true; return !this.items.includes(item); }; } $onChanges() { this.ngModel.$validate(); } } return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: { items: '<pcNotInCollection' } }; }) .directive('pcInCollection', function() { class Controller { /** @type {ng.INgModelController} */ ngModel; /** @type {Array} */ items; /** @type {string} */ pluck; $onInit() { this.ngModel.$validators.inCollection = (item) => { if (!this.items) return false; const items = this.pluck ? this.items.map((i) => i[this.pluck]) : this.items; return Array.isArray(item) ? item.every((i) => items.includes(i)) : items.includes(item); }; } $onChanges() { this.ngModel.$validate(); } } return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: { items: '<pcInCollection', pluck: '@?pcInCollectionPluck' } }; }) .directive('pcPowerOfTwo', function() { class Controller { /** @type {ng.INgModelController} */ ngModel; $onInit() { this.ngModel.$validators.powerOfTwo = (value) => { return !value || ((value & -value) === value); }; } } return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: true }; }) .directive('bsCollapseTarget', function() { return { require: { bsCollapse: '^^bsCollapse' }, bindToController: true, controller: ['$element', '$scope', function($element, $scope) { this.open = function() { const index = this.bsCollapse.$targets.indexOf($element); const isActive = this.bsCollapse.$targets.$active.includes(index); if (!isActive) this.bsCollapse.$setActive(index); }; this.$onDestroy = () => this.open = $element = null; }] }; }) .directive('ngModel', ['$timeout', function($timeout) { return { require: ['ngModel', '?^^bsCollapseTarget', '?^^igniteFormField', '?^^panelCollapsible'], link(scope, el, attr, [ngModel, bsCollapseTarget, igniteFormField, panelCollapsible]) { const off = scope.$on('$showValidationError', (e, target) => { if (target !== ngModel) return; ngModel.$setTouched(); bsCollapseTarget && bsCollapseTarget.open(); panelCollapsible && panelCollapsible.open(); $timeout(() => { if (el[0].scrollIntoViewIfNeeded) el[0].scrollIntoViewIfNeeded(); else el[0].scrollIntoView(); if (!attr.bsSelect) $timeout(() => el[0].focus()); igniteFormField && igniteFormField.notifyAboutError(); }); }); } }; }]) .directive('igniteFormField', function() { return { restrict: 'C', controller: IgniteFormField, scope: true }; }) .directive('isValidJavaIdentifier', ['IgniteLegacyUtils', function(LegacyUtils) { return { link(scope, el, attr, ngModel) { ngModel.$validators.isValidJavaIdentifier = (value) => LegacyUtils.VALID_JAVA_IDENTIFIER.test(value); }, require: 'ngModel' }; }]) .directive('notJavaReservedWord', ['IgniteLegacyUtils', function(LegacyUtils) { return { link(scope, el, attr, ngModel) { ngModel.$validators.notJavaReservedWord = (value) => !LegacyUtils.JAVA_KEYWORDS.includes(value); }, require: 'ngModel' }; }]);
class Controller {
random_line_split
pcValidation.js
/* * 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. */ import angular from 'angular'; export class
{ static animName = 'ignite-form-field__error-blink'; static eventName = 'webkitAnimationEnd oAnimationEnd msAnimationEnd animationend'; static $inject = ['$element', '$scope']; constructor($element, $scope) { Object.assign(this, {$element}); this.$scope = $scope; } $postLink() { this.onAnimEnd = () => this.$element.removeClass(IgniteFormField.animName); this.$element.on(IgniteFormField.eventName, this.onAnimEnd); } $onDestroy() { this.$element.off(IgniteFormField.eventName, this.onAnimEnd); this.$element = this.onAnimEnd = null; } notifyAboutError() { if (this.$element) this.$element.addClass(IgniteFormField.animName); } /** * Exposes control in $scope * @param {ng.INgModelController} control */ exposeControl(control, name = '$input') { this.$scope[name] = control; this.$scope.$on('$destroy', () => this.$scope[name] = null); } } export default angular.module('ignite-console.page-configure.validation', []) .directive('pcNotInCollection', function() { class Controller { /** @type {ng.INgModelController} */ ngModel; /** @type {Array} */ items; $onInit() { this.ngModel.$validators.notInCollection = (item) => { if (!this.items) return true; return !this.items.includes(item); }; } $onChanges() { this.ngModel.$validate(); } } return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: { items: '<pcNotInCollection' } }; }) .directive('pcInCollection', function() { class Controller { /** @type {ng.INgModelController} */ ngModel; /** @type {Array} */ items; /** @type {string} */ pluck; $onInit() { this.ngModel.$validators.inCollection = (item) => { if (!this.items) return false; const items = this.pluck ? this.items.map((i) => i[this.pluck]) : this.items; return Array.isArray(item) ? item.every((i) => items.includes(i)) : items.includes(item); }; } $onChanges() { this.ngModel.$validate(); } } return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: { items: '<pcInCollection', pluck: '@?pcInCollectionPluck' } }; }) .directive('pcPowerOfTwo', function() { class Controller { /** @type {ng.INgModelController} */ ngModel; $onInit() { this.ngModel.$validators.powerOfTwo = (value) => { return !value || ((value & -value) === value); }; } } return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: true }; }) .directive('bsCollapseTarget', function() { return { require: { bsCollapse: '^^bsCollapse' }, bindToController: true, controller: ['$element', '$scope', function($element, $scope) { this.open = function() { const index = this.bsCollapse.$targets.indexOf($element); const isActive = this.bsCollapse.$targets.$active.includes(index); if (!isActive) this.bsCollapse.$setActive(index); }; this.$onDestroy = () => this.open = $element = null; }] }; }) .directive('ngModel', ['$timeout', function($timeout) { return { require: ['ngModel', '?^^bsCollapseTarget', '?^^igniteFormField', '?^^panelCollapsible'], link(scope, el, attr, [ngModel, bsCollapseTarget, igniteFormField, panelCollapsible]) { const off = scope.$on('$showValidationError', (e, target) => { if (target !== ngModel) return; ngModel.$setTouched(); bsCollapseTarget && bsCollapseTarget.open(); panelCollapsible && panelCollapsible.open(); $timeout(() => { if (el[0].scrollIntoViewIfNeeded) el[0].scrollIntoViewIfNeeded(); else el[0].scrollIntoView(); if (!attr.bsSelect) $timeout(() => el[0].focus()); igniteFormField && igniteFormField.notifyAboutError(); }); }); } }; }]) .directive('igniteFormField', function() { return { restrict: 'C', controller: IgniteFormField, scope: true }; }) .directive('isValidJavaIdentifier', ['IgniteLegacyUtils', function(LegacyUtils) { return { link(scope, el, attr, ngModel) { ngModel.$validators.isValidJavaIdentifier = (value) => LegacyUtils.VALID_JAVA_IDENTIFIER.test(value); }, require: 'ngModel' }; }]) .directive('notJavaReservedWord', ['IgniteLegacyUtils', function(LegacyUtils) { return { link(scope, el, attr, ngModel) { ngModel.$validators.notJavaReservedWord = (value) => !LegacyUtils.JAVA_KEYWORDS.includes(value); }, require: 'ngModel' }; }]);
IgniteFormField
identifier_name
EnterLeaveEventPlugin.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {accumulateEnterLeaveDispatches} from 'events/EventPropagators'; import { TOP_MOUSE_OUT, TOP_MOUSE_OVER, TOP_POINTER_OUT, TOP_POINTER_OVER, } from './DOMTopLevelEventTypes'; import SyntheticMouseEvent from './SyntheticMouseEvent'; import SyntheticPointerEvent from './SyntheticPointerEvent'; import { getClosestInstanceFromNode, getNodeFromInstance, } from '../client/ReactDOMComponentTree'; const eventTypes = { mouseEnter: { registrationName: 'onMouseEnter', dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER], }, mouseLeave: { registrationName: 'onMouseLeave', dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER], }, pointerEnter: { registrationName: 'onPointerEnter', dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER], }, pointerLeave: { registrationName: 'onPointerLeave', dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER], }, }; const EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function( topLevelType, targetInst, nativeEvent, nativeEventTarget, ) { const isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER; const isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT; if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (!isOutEvent && !isOverEvent) { // Must not be a mouse or pointer in or out - ignoring. return null; } let win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. const doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } let from; let to; if (isOutEvent) { from = targetInst; const related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } let eventInterface, leaveEventType, enterEventType, eventTypePrefix; if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) { eventInterface = SyntheticMouseEvent; leaveEventType = eventTypes.mouseLeave; enterEventType = eventTypes.mouseEnter; eventTypePrefix = 'mouse'; } else if ( topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER ) { eventInterface = SyntheticPointerEvent; leaveEventType = eventTypes.pointerLeave; enterEventType = eventTypes.pointerEnter; eventTypePrefix = 'pointer'; } const fromNode = from == null ? win : getNodeFromInstance(from); const toNode = to == null ? win : getNodeFromInstance(to); const leave = eventInterface.getPooled( leaveEventType, from, nativeEvent, nativeEventTarget, ); leave.type = eventTypePrefix + 'leave'; leave.target = fromNode; leave.relatedTarget = toNode; const enter = eventInterface.getPooled( enterEventType, to, nativeEvent,
nativeEventTarget, ); enter.type = eventTypePrefix + 'enter'; enter.target = toNode; enter.relatedTarget = fromNode; accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; }, }; export default EnterLeaveEventPlugin;
random_line_split
EnterLeaveEventPlugin.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {accumulateEnterLeaveDispatches} from 'events/EventPropagators'; import { TOP_MOUSE_OUT, TOP_MOUSE_OVER, TOP_POINTER_OUT, TOP_POINTER_OVER, } from './DOMTopLevelEventTypes'; import SyntheticMouseEvent from './SyntheticMouseEvent'; import SyntheticPointerEvent from './SyntheticPointerEvent'; import { getClosestInstanceFromNode, getNodeFromInstance, } from '../client/ReactDOMComponentTree'; const eventTypes = { mouseEnter: { registrationName: 'onMouseEnter', dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER], }, mouseLeave: { registrationName: 'onMouseLeave', dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER], }, pointerEnter: { registrationName: 'onPointerEnter', dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER], }, pointerLeave: { registrationName: 'onPointerLeave', dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER], }, }; const EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function( topLevelType, targetInst, nativeEvent, nativeEventTarget, ) { const isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER; const isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT; if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (!isOutEvent && !isOverEvent) { // Must not be a mouse or pointer in or out - ignoring. return null; } let win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. const doc = nativeEventTarget.ownerDocument; if (doc)
else { win = window; } } let from; let to; if (isOutEvent) { from = targetInst; const related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } let eventInterface, leaveEventType, enterEventType, eventTypePrefix; if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) { eventInterface = SyntheticMouseEvent; leaveEventType = eventTypes.mouseLeave; enterEventType = eventTypes.mouseEnter; eventTypePrefix = 'mouse'; } else if ( topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER ) { eventInterface = SyntheticPointerEvent; leaveEventType = eventTypes.pointerLeave; enterEventType = eventTypes.pointerEnter; eventTypePrefix = 'pointer'; } const fromNode = from == null ? win : getNodeFromInstance(from); const toNode = to == null ? win : getNodeFromInstance(to); const leave = eventInterface.getPooled( leaveEventType, from, nativeEvent, nativeEventTarget, ); leave.type = eventTypePrefix + 'leave'; leave.target = fromNode; leave.relatedTarget = toNode; const enter = eventInterface.getPooled( enterEventType, to, nativeEvent, nativeEventTarget, ); enter.type = eventTypePrefix + 'enter'; enter.target = toNode; enter.relatedTarget = fromNode; accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; }, }; export default EnterLeaveEventPlugin;
{ win = doc.defaultView || doc.parentWindow; }
conditional_block
vega.schema.ts
import type { AggregateOp, BandScale, BaseScale, BinOrdinalScale, ColorValueRef, Compare as VgCompare, ExprRef as VgExprRef, GeoShapeTransform as VgGeoShapeTransform, IdentityScale, LayoutAlign, LinearScale, LogScale, Mark, MarkConfig, NumericValueRef, OrdinalScale, PointScale, PowScale, ProjectionType, QuantileScale, QuantizeScale, RangeBand, RangeRaw, RangeScheme, ScaleData, ScaleDataRef, ScaledValueRef, ScaleMultiDataRef, ScaleMultiFieldsRef, SequentialScale, SignalRef, SortField as VgSortField, SqrtScale, SymLogScale, ThresholdScale, TimeInterval, TimeIntervalStep, TimeScale, Title as VgTitle, Transforms as VgTransform, UnionSortField as VgUnionSortField } from 'vega'; import {isArray} from 'vega-util'; import {Value} from './channeldef'; import {ExprRef} from './expr'; import {SortOrder} from './sort'; import {Dict, Flag, keys} from './util'; export type {VgSortField, VgUnionSortField, VgCompare, VgTitle, LayoutAlign, ProjectionType, VgExprRef}; // TODO: make recursive (e.g. with https://stackoverflow.com/a/64900252/214950 but needs https://github.com/vega/ts-json-schema-generator/issues/568) export type MappedExclude<T, E> = { [P in keyof T]: Exclude<T[P], E>; }; export type MapExcludeAndKeepSignalAs<T, E, S extends ExprRef | SignalRef> = { [P in keyof T]: SignalRef extends T[P] ? Exclude<T[P], E> | S : Exclude<T[P], E>; }; // Remove ValueRefs from mapped types export type MappedExcludeValueRef<T> = MappedExclude<T, ScaledValueRef<any> | NumericValueRef | ColorValueRef>; export type MapExcludeValueRefAndReplaceSignalWith<T, S extends ExprRef | SignalRef> = MapExcludeAndKeepSignalAs< T, ScaledValueRef<any> | NumericValueRef | ColorValueRef, S >; export interface VgData { name: string; source?: string; values?: any; format?: { type?: string; parse?: string | Dict<unknown>; property?: string; feature?: string; mesh?: string; }; url?: string; transform?: VgTransform[]; } export type VgScaleDataRefWithSort = ScaleDataRef & { sort?: VgSortField; }; export function isSignalRef(o: any): o is SignalRef { return o && !!o['signal']; } // TODO: add type of value (Make it VgValueRef<V extends ValueOrGradient> {value?:V ...}) export interface VgValueRef { value?: Value<never>; // value should never be a signal so we use never field?: | string | { datum?: string; group?: string; parent?: string; }; signal?: string; scale?: string; // TODO: object mult?: number; offset?: number | VgValueRef; band?: boolean | number | VgValueRef; test?: string; } // TODO: add vg prefix export type VgScaleMultiDataRefWithSort = ScaleMultiDataRef & { fields: (any[] | VgScaleDataRefWithSort | SignalRef)[]; sort?: VgUnionSortField; }; export type VgMultiFieldsRefWithSort = ScaleMultiFieldsRef & { sort?: VgUnionSortField; }; export type VgRange = RangeScheme | ScaleData | RangeBand | RangeRaw; export function isVgRangeStep(range: VgRange): range is VgRangeStep { return !!range['step']; } export interface VgRangeStep { step: number | SignalRef; } // Domains that are not a union of domains export type VgNonUnionDomain = (null | string | number | boolean | SignalRef)[] | VgScaleDataRefWithSort | SignalRef; export type VgDomain = BaseScale['domain']; export type VgMarkGroup = any; /** * A combined type for any Vega scales that Vega-Lite can generate */ export type VgScale = Pick<BaseScale, 'type'> & { range?: RangeScheme | RangeBand | ScaleData; // different Vega scales have conflicting range, need to union them here nice?: boolean | number | TimeInterval | TimeIntervalStep | SignalRef; // different Vega scales have conflicting range, need to union them here zero?: boolean | SignalRef; // LogScale only allow false, making the intersection type overly strict } & Omit< // Continuous Omit<LinearScale, 'type'> & Omit<LogScale, 'type'> & Omit<SymLogScale, 'type'> & Omit<Partial<PowScale>, 'type'> & // use partial so exponent is not required Omit<SqrtScale, 'type'> & Omit<IdentityScale, 'type'> & Omit<TimeScale, 'type'> & // Discretizing Omit<QuantileScale, 'type'> & Omit<QuantizeScale, 'type'> & Omit<ThresholdScale, 'type'> & Omit<BinOrdinalScale, 'type'> & // Sequential Omit<SequentialScale, 'type'> & // Discrete Omit<BandScale, 'type'> & Omit<PointScale, 'type'> & Omit<OrdinalScale, 'type'>, 'range' | 'nice' | 'zero' >; export interface RowCol<T> { row?: T; column?: T; } export interface VgLayout { center?: boolean | RowCol<boolean>; padding?: number | RowCol<number>; headerBand?: number | RowCol<number>; footerBand?: number | RowCol<number>; titleAnchor?: 'start' | 'end' | RowCol<'start' | 'end'>; offset?: | number | { rowHeader?: number; rowFooter?: number; rowTitle?: number; columnHeader?: number; columnFooter?: number; columnTitle?: number; }; bounds?: 'full' | 'flush'; columns?: number | {signal: string}; align?: LayoutAlign | RowCol<LayoutAlign>; } export function isDataRefUnionedDomain(domain: VgDomain): domain is VgScaleMultiDataRefWithSort { if (!isArray(domain)) { return 'fields' in domain && !('data' in domain); } return false; } export function isFieldRefUnionDomain(domain: VgDomain): domain is VgMultiFieldsRefWithSort { if (!isArray(domain)) { return 'fields' in domain && 'data' in domain; } return false; } export function isDataRefDomain(domain: VgDomain | any): domain is VgScaleDataRefWithSort { if (!isArray(domain)) { return 'field' in domain && 'data' in domain; } return false; } export type VgEncodeChannel = | 'x' | 'x2' | 'xc' | 'width' | 'y' | 'y2' | 'yc' | 'height' | 'opacity' | 'fill' | 'fillOpacity' | 'stroke' | 'strokeWidth' | 'strokeCap' | 'strokeOpacity' | 'strokeDash' | 'strokeDashOffset' | 'strokeMiterLimit' | 'strokeJoin' | 'strokeOffset' | 'strokeForeground' | 'cursor' | 'clip' | 'size' | 'shape' | 'path' | 'innerRadius' | 'outerRadius' | 'startAngle' | 'endAngle' | 'interpolate' | 'tension' | 'orient' | 'url' | 'align' | 'baseline' | 'text' | 'dir' | 'ellipsis' | 'limit' | 'dx' | 'dy' | 'radius' | 'theta' | 'angle' | 'font' | 'fontSize' | 'fontWeight' | 'fontStyle' | 'tooltip' | 'href' | 'cursor' | 'defined' | 'cornerRadius' | 'cornerRadiusTopLeft' | 'cornerRadiusTopRight' | 'cornerRadiusBottomRight' | 'cornerRadiusBottomLeft' | 'scaleX' | 'scaleY'; export type VgEncodeEntry = Partial<Record<VgEncodeChannel, VgValueRef | (VgValueRef & {test?: string})[]>>; // TODO: make export interface VgEncodeEntry { // x?: VgValueRef<number> // y?: VgValueRef<number> // ... // color?: VgValueRef<string> // ... // } export type VgPostEncodingTransform = VgGeoShapeTransform; const VG_MARK_CONFIG_INDEX: Flag<keyof MarkConfig> = { aria: 1, description: 1, ariaRole: 1, ariaRoleDescription: 1, blend: 1, opacity: 1, fill: 1, fillOpacity: 1, stroke: 1, strokeCap: 1, strokeWidth: 1, strokeOpacity: 1, strokeDash: 1, strokeDashOffset: 1, strokeJoin: 1, strokeOffset: 1, strokeMiterLimit: 1, startAngle: 1, endAngle: 1, padAngle: 1, innerRadius: 1, outerRadius: 1, size: 1, shape: 1, interpolate: 1, tension: 1, orient: 1, align: 1, baseline: 1, text: 1, dir: 1, dx: 1, dy: 1, ellipsis: 1, limit: 1, radius: 1, theta: 1, angle: 1, font: 1, fontSize: 1, fontWeight: 1, fontStyle: 1, lineBreak: 1, lineHeight: 1, cursor: 1, href: 1, tooltip: 1, cornerRadius: 1, cornerRadiusTopLeft: 1, cornerRadiusTopRight: 1, cornerRadiusBottomLeft: 1, cornerRadiusBottomRight: 1, aspect: 1, width: 1, height: 1, url: 1, smooth: 1 // commented below are vg channel that do not have mark config. // x: 1, // y: 1, // x2: 1, // y2: 1,
// path: 1, // url: 1, }; export const VG_MARK_CONFIGS = keys(VG_MARK_CONFIG_INDEX); export const VG_MARK_INDEX: Flag<Mark['type']> = { arc: 1, area: 1, group: 1, image: 1, line: 1, path: 1, rect: 1, rule: 1, shape: 1, symbol: 1, text: 1, trail: 1 }; // Vega's cornerRadius channels. export const VG_CORNERRADIUS_CHANNELS = [ 'cornerRadius', 'cornerRadiusTopLeft', 'cornerRadiusTopRight', 'cornerRadiusBottomLeft', 'cornerRadiusBottomRight' ] as const; export interface VgComparator { field?: string | string[]; order?: SortOrder | SortOrder[]; } export interface VgJoinAggregateTransform { type: 'joinaggregate'; as?: string[]; ops?: AggregateOp[]; fields?: string[]; groupby?: string[]; }
// xc'|'yc' // clip: 1,
random_line_split
vega.schema.ts
import type { AggregateOp, BandScale, BaseScale, BinOrdinalScale, ColorValueRef, Compare as VgCompare, ExprRef as VgExprRef, GeoShapeTransform as VgGeoShapeTransform, IdentityScale, LayoutAlign, LinearScale, LogScale, Mark, MarkConfig, NumericValueRef, OrdinalScale, PointScale, PowScale, ProjectionType, QuantileScale, QuantizeScale, RangeBand, RangeRaw, RangeScheme, ScaleData, ScaleDataRef, ScaledValueRef, ScaleMultiDataRef, ScaleMultiFieldsRef, SequentialScale, SignalRef, SortField as VgSortField, SqrtScale, SymLogScale, ThresholdScale, TimeInterval, TimeIntervalStep, TimeScale, Title as VgTitle, Transforms as VgTransform, UnionSortField as VgUnionSortField } from 'vega'; import {isArray} from 'vega-util'; import {Value} from './channeldef'; import {ExprRef} from './expr'; import {SortOrder} from './sort'; import {Dict, Flag, keys} from './util'; export type {VgSortField, VgUnionSortField, VgCompare, VgTitle, LayoutAlign, ProjectionType, VgExprRef}; // TODO: make recursive (e.g. with https://stackoverflow.com/a/64900252/214950 but needs https://github.com/vega/ts-json-schema-generator/issues/568) export type MappedExclude<T, E> = { [P in keyof T]: Exclude<T[P], E>; }; export type MapExcludeAndKeepSignalAs<T, E, S extends ExprRef | SignalRef> = { [P in keyof T]: SignalRef extends T[P] ? Exclude<T[P], E> | S : Exclude<T[P], E>; }; // Remove ValueRefs from mapped types export type MappedExcludeValueRef<T> = MappedExclude<T, ScaledValueRef<any> | NumericValueRef | ColorValueRef>; export type MapExcludeValueRefAndReplaceSignalWith<T, S extends ExprRef | SignalRef> = MapExcludeAndKeepSignalAs< T, ScaledValueRef<any> | NumericValueRef | ColorValueRef, S >; export interface VgData { name: string; source?: string; values?: any; format?: { type?: string; parse?: string | Dict<unknown>; property?: string; feature?: string; mesh?: string; }; url?: string; transform?: VgTransform[]; } export type VgScaleDataRefWithSort = ScaleDataRef & { sort?: VgSortField; }; export function isSignalRef(o: any): o is SignalRef { return o && !!o['signal']; } // TODO: add type of value (Make it VgValueRef<V extends ValueOrGradient> {value?:V ...}) export interface VgValueRef { value?: Value<never>; // value should never be a signal so we use never field?: | string | { datum?: string; group?: string; parent?: string; }; signal?: string; scale?: string; // TODO: object mult?: number; offset?: number | VgValueRef; band?: boolean | number | VgValueRef; test?: string; } // TODO: add vg prefix export type VgScaleMultiDataRefWithSort = ScaleMultiDataRef & { fields: (any[] | VgScaleDataRefWithSort | SignalRef)[]; sort?: VgUnionSortField; }; export type VgMultiFieldsRefWithSort = ScaleMultiFieldsRef & { sort?: VgUnionSortField; }; export type VgRange = RangeScheme | ScaleData | RangeBand | RangeRaw; export function isVgRangeStep(range: VgRange): range is VgRangeStep { return !!range['step']; } export interface VgRangeStep { step: number | SignalRef; } // Domains that are not a union of domains export type VgNonUnionDomain = (null | string | number | boolean | SignalRef)[] | VgScaleDataRefWithSort | SignalRef; export type VgDomain = BaseScale['domain']; export type VgMarkGroup = any; /** * A combined type for any Vega scales that Vega-Lite can generate */ export type VgScale = Pick<BaseScale, 'type'> & { range?: RangeScheme | RangeBand | ScaleData; // different Vega scales have conflicting range, need to union them here nice?: boolean | number | TimeInterval | TimeIntervalStep | SignalRef; // different Vega scales have conflicting range, need to union them here zero?: boolean | SignalRef; // LogScale only allow false, making the intersection type overly strict } & Omit< // Continuous Omit<LinearScale, 'type'> & Omit<LogScale, 'type'> & Omit<SymLogScale, 'type'> & Omit<Partial<PowScale>, 'type'> & // use partial so exponent is not required Omit<SqrtScale, 'type'> & Omit<IdentityScale, 'type'> & Omit<TimeScale, 'type'> & // Discretizing Omit<QuantileScale, 'type'> & Omit<QuantizeScale, 'type'> & Omit<ThresholdScale, 'type'> & Omit<BinOrdinalScale, 'type'> & // Sequential Omit<SequentialScale, 'type'> & // Discrete Omit<BandScale, 'type'> & Omit<PointScale, 'type'> & Omit<OrdinalScale, 'type'>, 'range' | 'nice' | 'zero' >; export interface RowCol<T> { row?: T; column?: T; } export interface VgLayout { center?: boolean | RowCol<boolean>; padding?: number | RowCol<number>; headerBand?: number | RowCol<number>; footerBand?: number | RowCol<number>; titleAnchor?: 'start' | 'end' | RowCol<'start' | 'end'>; offset?: | number | { rowHeader?: number; rowFooter?: number; rowTitle?: number; columnHeader?: number; columnFooter?: number; columnTitle?: number; }; bounds?: 'full' | 'flush'; columns?: number | {signal: string}; align?: LayoutAlign | RowCol<LayoutAlign>; } export function isDataRefUnionedDomain(domain: VgDomain): domain is VgScaleMultiDataRefWithSort { if (!isArray(domain))
return false; } export function isFieldRefUnionDomain(domain: VgDomain): domain is VgMultiFieldsRefWithSort { if (!isArray(domain)) { return 'fields' in domain && 'data' in domain; } return false; } export function isDataRefDomain(domain: VgDomain | any): domain is VgScaleDataRefWithSort { if (!isArray(domain)) { return 'field' in domain && 'data' in domain; } return false; } export type VgEncodeChannel = | 'x' | 'x2' | 'xc' | 'width' | 'y' | 'y2' | 'yc' | 'height' | 'opacity' | 'fill' | 'fillOpacity' | 'stroke' | 'strokeWidth' | 'strokeCap' | 'strokeOpacity' | 'strokeDash' | 'strokeDashOffset' | 'strokeMiterLimit' | 'strokeJoin' | 'strokeOffset' | 'strokeForeground' | 'cursor' | 'clip' | 'size' | 'shape' | 'path' | 'innerRadius' | 'outerRadius' | 'startAngle' | 'endAngle' | 'interpolate' | 'tension' | 'orient' | 'url' | 'align' | 'baseline' | 'text' | 'dir' | 'ellipsis' | 'limit' | 'dx' | 'dy' | 'radius' | 'theta' | 'angle' | 'font' | 'fontSize' | 'fontWeight' | 'fontStyle' | 'tooltip' | 'href' | 'cursor' | 'defined' | 'cornerRadius' | 'cornerRadiusTopLeft' | 'cornerRadiusTopRight' | 'cornerRadiusBottomRight' | 'cornerRadiusBottomLeft' | 'scaleX' | 'scaleY'; export type VgEncodeEntry = Partial<Record<VgEncodeChannel, VgValueRef | (VgValueRef & {test?: string})[]>>; // TODO: make export interface VgEncodeEntry { // x?: VgValueRef<number> // y?: VgValueRef<number> // ... // color?: VgValueRef<string> // ... // } export type VgPostEncodingTransform = VgGeoShapeTransform; const VG_MARK_CONFIG_INDEX: Flag<keyof MarkConfig> = { aria: 1, description: 1, ariaRole: 1, ariaRoleDescription: 1, blend: 1, opacity: 1, fill: 1, fillOpacity: 1, stroke: 1, strokeCap: 1, strokeWidth: 1, strokeOpacity: 1, strokeDash: 1, strokeDashOffset: 1, strokeJoin: 1, strokeOffset: 1, strokeMiterLimit: 1, startAngle: 1, endAngle: 1, padAngle: 1, innerRadius: 1, outerRadius: 1, size: 1, shape: 1, interpolate: 1, tension: 1, orient: 1, align: 1, baseline: 1, text: 1, dir: 1, dx: 1, dy: 1, ellipsis: 1, limit: 1, radius: 1, theta: 1, angle: 1, font: 1, fontSize: 1, fontWeight: 1, fontStyle: 1, lineBreak: 1, lineHeight: 1, cursor: 1, href: 1, tooltip: 1, cornerRadius: 1, cornerRadiusTopLeft: 1, cornerRadiusTopRight: 1, cornerRadiusBottomLeft: 1, cornerRadiusBottomRight: 1, aspect: 1, width: 1, height: 1, url: 1, smooth: 1 // commented below are vg channel that do not have mark config. // x: 1, // y: 1, // x2: 1, // y2: 1, // xc'|'yc' // clip: 1, // path: 1, // url: 1, }; export const VG_MARK_CONFIGS = keys(VG_MARK_CONFIG_INDEX); export const VG_MARK_INDEX: Flag<Mark['type']> = { arc: 1, area: 1, group: 1, image: 1, line: 1, path: 1, rect: 1, rule: 1, shape: 1, symbol: 1, text: 1, trail: 1 }; // Vega's cornerRadius channels. export const VG_CORNERRADIUS_CHANNELS = [ 'cornerRadius', 'cornerRadiusTopLeft', 'cornerRadiusTopRight', 'cornerRadiusBottomLeft', 'cornerRadiusBottomRight' ] as const; export interface VgComparator { field?: string | string[]; order?: SortOrder | SortOrder[]; } export interface VgJoinAggregateTransform { type: 'joinaggregate'; as?: string[]; ops?: AggregateOp[]; fields?: string[]; groupby?: string[]; }
{ return 'fields' in domain && !('data' in domain); }
conditional_block
vega.schema.ts
import type { AggregateOp, BandScale, BaseScale, BinOrdinalScale, ColorValueRef, Compare as VgCompare, ExprRef as VgExprRef, GeoShapeTransform as VgGeoShapeTransform, IdentityScale, LayoutAlign, LinearScale, LogScale, Mark, MarkConfig, NumericValueRef, OrdinalScale, PointScale, PowScale, ProjectionType, QuantileScale, QuantizeScale, RangeBand, RangeRaw, RangeScheme, ScaleData, ScaleDataRef, ScaledValueRef, ScaleMultiDataRef, ScaleMultiFieldsRef, SequentialScale, SignalRef, SortField as VgSortField, SqrtScale, SymLogScale, ThresholdScale, TimeInterval, TimeIntervalStep, TimeScale, Title as VgTitle, Transforms as VgTransform, UnionSortField as VgUnionSortField } from 'vega'; import {isArray} from 'vega-util'; import {Value} from './channeldef'; import {ExprRef} from './expr'; import {SortOrder} from './sort'; import {Dict, Flag, keys} from './util'; export type {VgSortField, VgUnionSortField, VgCompare, VgTitle, LayoutAlign, ProjectionType, VgExprRef}; // TODO: make recursive (e.g. with https://stackoverflow.com/a/64900252/214950 but needs https://github.com/vega/ts-json-schema-generator/issues/568) export type MappedExclude<T, E> = { [P in keyof T]: Exclude<T[P], E>; }; export type MapExcludeAndKeepSignalAs<T, E, S extends ExprRef | SignalRef> = { [P in keyof T]: SignalRef extends T[P] ? Exclude<T[P], E> | S : Exclude<T[P], E>; }; // Remove ValueRefs from mapped types export type MappedExcludeValueRef<T> = MappedExclude<T, ScaledValueRef<any> | NumericValueRef | ColorValueRef>; export type MapExcludeValueRefAndReplaceSignalWith<T, S extends ExprRef | SignalRef> = MapExcludeAndKeepSignalAs< T, ScaledValueRef<any> | NumericValueRef | ColorValueRef, S >; export interface VgData { name: string; source?: string; values?: any; format?: { type?: string; parse?: string | Dict<unknown>; property?: string; feature?: string; mesh?: string; }; url?: string; transform?: VgTransform[]; } export type VgScaleDataRefWithSort = ScaleDataRef & { sort?: VgSortField; }; export function isSignalRef(o: any): o is SignalRef { return o && !!o['signal']; } // TODO: add type of value (Make it VgValueRef<V extends ValueOrGradient> {value?:V ...}) export interface VgValueRef { value?: Value<never>; // value should never be a signal so we use never field?: | string | { datum?: string; group?: string; parent?: string; }; signal?: string; scale?: string; // TODO: object mult?: number; offset?: number | VgValueRef; band?: boolean | number | VgValueRef; test?: string; } // TODO: add vg prefix export type VgScaleMultiDataRefWithSort = ScaleMultiDataRef & { fields: (any[] | VgScaleDataRefWithSort | SignalRef)[]; sort?: VgUnionSortField; }; export type VgMultiFieldsRefWithSort = ScaleMultiFieldsRef & { sort?: VgUnionSortField; }; export type VgRange = RangeScheme | ScaleData | RangeBand | RangeRaw; export function
(range: VgRange): range is VgRangeStep { return !!range['step']; } export interface VgRangeStep { step: number | SignalRef; } // Domains that are not a union of domains export type VgNonUnionDomain = (null | string | number | boolean | SignalRef)[] | VgScaleDataRefWithSort | SignalRef; export type VgDomain = BaseScale['domain']; export type VgMarkGroup = any; /** * A combined type for any Vega scales that Vega-Lite can generate */ export type VgScale = Pick<BaseScale, 'type'> & { range?: RangeScheme | RangeBand | ScaleData; // different Vega scales have conflicting range, need to union them here nice?: boolean | number | TimeInterval | TimeIntervalStep | SignalRef; // different Vega scales have conflicting range, need to union them here zero?: boolean | SignalRef; // LogScale only allow false, making the intersection type overly strict } & Omit< // Continuous Omit<LinearScale, 'type'> & Omit<LogScale, 'type'> & Omit<SymLogScale, 'type'> & Omit<Partial<PowScale>, 'type'> & // use partial so exponent is not required Omit<SqrtScale, 'type'> & Omit<IdentityScale, 'type'> & Omit<TimeScale, 'type'> & // Discretizing Omit<QuantileScale, 'type'> & Omit<QuantizeScale, 'type'> & Omit<ThresholdScale, 'type'> & Omit<BinOrdinalScale, 'type'> & // Sequential Omit<SequentialScale, 'type'> & // Discrete Omit<BandScale, 'type'> & Omit<PointScale, 'type'> & Omit<OrdinalScale, 'type'>, 'range' | 'nice' | 'zero' >; export interface RowCol<T> { row?: T; column?: T; } export interface VgLayout { center?: boolean | RowCol<boolean>; padding?: number | RowCol<number>; headerBand?: number | RowCol<number>; footerBand?: number | RowCol<number>; titleAnchor?: 'start' | 'end' | RowCol<'start' | 'end'>; offset?: | number | { rowHeader?: number; rowFooter?: number; rowTitle?: number; columnHeader?: number; columnFooter?: number; columnTitle?: number; }; bounds?: 'full' | 'flush'; columns?: number | {signal: string}; align?: LayoutAlign | RowCol<LayoutAlign>; } export function isDataRefUnionedDomain(domain: VgDomain): domain is VgScaleMultiDataRefWithSort { if (!isArray(domain)) { return 'fields' in domain && !('data' in domain); } return false; } export function isFieldRefUnionDomain(domain: VgDomain): domain is VgMultiFieldsRefWithSort { if (!isArray(domain)) { return 'fields' in domain && 'data' in domain; } return false; } export function isDataRefDomain(domain: VgDomain | any): domain is VgScaleDataRefWithSort { if (!isArray(domain)) { return 'field' in domain && 'data' in domain; } return false; } export type VgEncodeChannel = | 'x' | 'x2' | 'xc' | 'width' | 'y' | 'y2' | 'yc' | 'height' | 'opacity' | 'fill' | 'fillOpacity' | 'stroke' | 'strokeWidth' | 'strokeCap' | 'strokeOpacity' | 'strokeDash' | 'strokeDashOffset' | 'strokeMiterLimit' | 'strokeJoin' | 'strokeOffset' | 'strokeForeground' | 'cursor' | 'clip' | 'size' | 'shape' | 'path' | 'innerRadius' | 'outerRadius' | 'startAngle' | 'endAngle' | 'interpolate' | 'tension' | 'orient' | 'url' | 'align' | 'baseline' | 'text' | 'dir' | 'ellipsis' | 'limit' | 'dx' | 'dy' | 'radius' | 'theta' | 'angle' | 'font' | 'fontSize' | 'fontWeight' | 'fontStyle' | 'tooltip' | 'href' | 'cursor' | 'defined' | 'cornerRadius' | 'cornerRadiusTopLeft' | 'cornerRadiusTopRight' | 'cornerRadiusBottomRight' | 'cornerRadiusBottomLeft' | 'scaleX' | 'scaleY'; export type VgEncodeEntry = Partial<Record<VgEncodeChannel, VgValueRef | (VgValueRef & {test?: string})[]>>; // TODO: make export interface VgEncodeEntry { // x?: VgValueRef<number> // y?: VgValueRef<number> // ... // color?: VgValueRef<string> // ... // } export type VgPostEncodingTransform = VgGeoShapeTransform; const VG_MARK_CONFIG_INDEX: Flag<keyof MarkConfig> = { aria: 1, description: 1, ariaRole: 1, ariaRoleDescription: 1, blend: 1, opacity: 1, fill: 1, fillOpacity: 1, stroke: 1, strokeCap: 1, strokeWidth: 1, strokeOpacity: 1, strokeDash: 1, strokeDashOffset: 1, strokeJoin: 1, strokeOffset: 1, strokeMiterLimit: 1, startAngle: 1, endAngle: 1, padAngle: 1, innerRadius: 1, outerRadius: 1, size: 1, shape: 1, interpolate: 1, tension: 1, orient: 1, align: 1, baseline: 1, text: 1, dir: 1, dx: 1, dy: 1, ellipsis: 1, limit: 1, radius: 1, theta: 1, angle: 1, font: 1, fontSize: 1, fontWeight: 1, fontStyle: 1, lineBreak: 1, lineHeight: 1, cursor: 1, href: 1, tooltip: 1, cornerRadius: 1, cornerRadiusTopLeft: 1, cornerRadiusTopRight: 1, cornerRadiusBottomLeft: 1, cornerRadiusBottomRight: 1, aspect: 1, width: 1, height: 1, url: 1, smooth: 1 // commented below are vg channel that do not have mark config. // x: 1, // y: 1, // x2: 1, // y2: 1, // xc'|'yc' // clip: 1, // path: 1, // url: 1, }; export const VG_MARK_CONFIGS = keys(VG_MARK_CONFIG_INDEX); export const VG_MARK_INDEX: Flag<Mark['type']> = { arc: 1, area: 1, group: 1, image: 1, line: 1, path: 1, rect: 1, rule: 1, shape: 1, symbol: 1, text: 1, trail: 1 }; // Vega's cornerRadius channels. export const VG_CORNERRADIUS_CHANNELS = [ 'cornerRadius', 'cornerRadiusTopLeft', 'cornerRadiusTopRight', 'cornerRadiusBottomLeft', 'cornerRadiusBottomRight' ] as const; export interface VgComparator { field?: string | string[]; order?: SortOrder | SortOrder[]; } export interface VgJoinAggregateTransform { type: 'joinaggregate'; as?: string[]; ops?: AggregateOp[]; fields?: string[]; groupby?: string[]; }
isVgRangeStep
identifier_name
vega.schema.ts
import type { AggregateOp, BandScale, BaseScale, BinOrdinalScale, ColorValueRef, Compare as VgCompare, ExprRef as VgExprRef, GeoShapeTransform as VgGeoShapeTransform, IdentityScale, LayoutAlign, LinearScale, LogScale, Mark, MarkConfig, NumericValueRef, OrdinalScale, PointScale, PowScale, ProjectionType, QuantileScale, QuantizeScale, RangeBand, RangeRaw, RangeScheme, ScaleData, ScaleDataRef, ScaledValueRef, ScaleMultiDataRef, ScaleMultiFieldsRef, SequentialScale, SignalRef, SortField as VgSortField, SqrtScale, SymLogScale, ThresholdScale, TimeInterval, TimeIntervalStep, TimeScale, Title as VgTitle, Transforms as VgTransform, UnionSortField as VgUnionSortField } from 'vega'; import {isArray} from 'vega-util'; import {Value} from './channeldef'; import {ExprRef} from './expr'; import {SortOrder} from './sort'; import {Dict, Flag, keys} from './util'; export type {VgSortField, VgUnionSortField, VgCompare, VgTitle, LayoutAlign, ProjectionType, VgExprRef}; // TODO: make recursive (e.g. with https://stackoverflow.com/a/64900252/214950 but needs https://github.com/vega/ts-json-schema-generator/issues/568) export type MappedExclude<T, E> = { [P in keyof T]: Exclude<T[P], E>; }; export type MapExcludeAndKeepSignalAs<T, E, S extends ExprRef | SignalRef> = { [P in keyof T]: SignalRef extends T[P] ? Exclude<T[P], E> | S : Exclude<T[P], E>; }; // Remove ValueRefs from mapped types export type MappedExcludeValueRef<T> = MappedExclude<T, ScaledValueRef<any> | NumericValueRef | ColorValueRef>; export type MapExcludeValueRefAndReplaceSignalWith<T, S extends ExprRef | SignalRef> = MapExcludeAndKeepSignalAs< T, ScaledValueRef<any> | NumericValueRef | ColorValueRef, S >; export interface VgData { name: string; source?: string; values?: any; format?: { type?: string; parse?: string | Dict<unknown>; property?: string; feature?: string; mesh?: string; }; url?: string; transform?: VgTransform[]; } export type VgScaleDataRefWithSort = ScaleDataRef & { sort?: VgSortField; }; export function isSignalRef(o: any): o is SignalRef { return o && !!o['signal']; } // TODO: add type of value (Make it VgValueRef<V extends ValueOrGradient> {value?:V ...}) export interface VgValueRef { value?: Value<never>; // value should never be a signal so we use never field?: | string | { datum?: string; group?: string; parent?: string; }; signal?: string; scale?: string; // TODO: object mult?: number; offset?: number | VgValueRef; band?: boolean | number | VgValueRef; test?: string; } // TODO: add vg prefix export type VgScaleMultiDataRefWithSort = ScaleMultiDataRef & { fields: (any[] | VgScaleDataRefWithSort | SignalRef)[]; sort?: VgUnionSortField; }; export type VgMultiFieldsRefWithSort = ScaleMultiFieldsRef & { sort?: VgUnionSortField; }; export type VgRange = RangeScheme | ScaleData | RangeBand | RangeRaw; export function isVgRangeStep(range: VgRange): range is VgRangeStep { return !!range['step']; } export interface VgRangeStep { step: number | SignalRef; } // Domains that are not a union of domains export type VgNonUnionDomain = (null | string | number | boolean | SignalRef)[] | VgScaleDataRefWithSort | SignalRef; export type VgDomain = BaseScale['domain']; export type VgMarkGroup = any; /** * A combined type for any Vega scales that Vega-Lite can generate */ export type VgScale = Pick<BaseScale, 'type'> & { range?: RangeScheme | RangeBand | ScaleData; // different Vega scales have conflicting range, need to union them here nice?: boolean | number | TimeInterval | TimeIntervalStep | SignalRef; // different Vega scales have conflicting range, need to union them here zero?: boolean | SignalRef; // LogScale only allow false, making the intersection type overly strict } & Omit< // Continuous Omit<LinearScale, 'type'> & Omit<LogScale, 'type'> & Omit<SymLogScale, 'type'> & Omit<Partial<PowScale>, 'type'> & // use partial so exponent is not required Omit<SqrtScale, 'type'> & Omit<IdentityScale, 'type'> & Omit<TimeScale, 'type'> & // Discretizing Omit<QuantileScale, 'type'> & Omit<QuantizeScale, 'type'> & Omit<ThresholdScale, 'type'> & Omit<BinOrdinalScale, 'type'> & // Sequential Omit<SequentialScale, 'type'> & // Discrete Omit<BandScale, 'type'> & Omit<PointScale, 'type'> & Omit<OrdinalScale, 'type'>, 'range' | 'nice' | 'zero' >; export interface RowCol<T> { row?: T; column?: T; } export interface VgLayout { center?: boolean | RowCol<boolean>; padding?: number | RowCol<number>; headerBand?: number | RowCol<number>; footerBand?: number | RowCol<number>; titleAnchor?: 'start' | 'end' | RowCol<'start' | 'end'>; offset?: | number | { rowHeader?: number; rowFooter?: number; rowTitle?: number; columnHeader?: number; columnFooter?: number; columnTitle?: number; }; bounds?: 'full' | 'flush'; columns?: number | {signal: string}; align?: LayoutAlign | RowCol<LayoutAlign>; } export function isDataRefUnionedDomain(domain: VgDomain): domain is VgScaleMultiDataRefWithSort { if (!isArray(domain)) { return 'fields' in domain && !('data' in domain); } return false; } export function isFieldRefUnionDomain(domain: VgDomain): domain is VgMultiFieldsRefWithSort { if (!isArray(domain)) { return 'fields' in domain && 'data' in domain; } return false; } export function isDataRefDomain(domain: VgDomain | any): domain is VgScaleDataRefWithSort
export type VgEncodeChannel = | 'x' | 'x2' | 'xc' | 'width' | 'y' | 'y2' | 'yc' | 'height' | 'opacity' | 'fill' | 'fillOpacity' | 'stroke' | 'strokeWidth' | 'strokeCap' | 'strokeOpacity' | 'strokeDash' | 'strokeDashOffset' | 'strokeMiterLimit' | 'strokeJoin' | 'strokeOffset' | 'strokeForeground' | 'cursor' | 'clip' | 'size' | 'shape' | 'path' | 'innerRadius' | 'outerRadius' | 'startAngle' | 'endAngle' | 'interpolate' | 'tension' | 'orient' | 'url' | 'align' | 'baseline' | 'text' | 'dir' | 'ellipsis' | 'limit' | 'dx' | 'dy' | 'radius' | 'theta' | 'angle' | 'font' | 'fontSize' | 'fontWeight' | 'fontStyle' | 'tooltip' | 'href' | 'cursor' | 'defined' | 'cornerRadius' | 'cornerRadiusTopLeft' | 'cornerRadiusTopRight' | 'cornerRadiusBottomRight' | 'cornerRadiusBottomLeft' | 'scaleX' | 'scaleY'; export type VgEncodeEntry = Partial<Record<VgEncodeChannel, VgValueRef | (VgValueRef & {test?: string})[]>>; // TODO: make export interface VgEncodeEntry { // x?: VgValueRef<number> // y?: VgValueRef<number> // ... // color?: VgValueRef<string> // ... // } export type VgPostEncodingTransform = VgGeoShapeTransform; const VG_MARK_CONFIG_INDEX: Flag<keyof MarkConfig> = { aria: 1, description: 1, ariaRole: 1, ariaRoleDescription: 1, blend: 1, opacity: 1, fill: 1, fillOpacity: 1, stroke: 1, strokeCap: 1, strokeWidth: 1, strokeOpacity: 1, strokeDash: 1, strokeDashOffset: 1, strokeJoin: 1, strokeOffset: 1, strokeMiterLimit: 1, startAngle: 1, endAngle: 1, padAngle: 1, innerRadius: 1, outerRadius: 1, size: 1, shape: 1, interpolate: 1, tension: 1, orient: 1, align: 1, baseline: 1, text: 1, dir: 1, dx: 1, dy: 1, ellipsis: 1, limit: 1, radius: 1, theta: 1, angle: 1, font: 1, fontSize: 1, fontWeight: 1, fontStyle: 1, lineBreak: 1, lineHeight: 1, cursor: 1, href: 1, tooltip: 1, cornerRadius: 1, cornerRadiusTopLeft: 1, cornerRadiusTopRight: 1, cornerRadiusBottomLeft: 1, cornerRadiusBottomRight: 1, aspect: 1, width: 1, height: 1, url: 1, smooth: 1 // commented below are vg channel that do not have mark config. // x: 1, // y: 1, // x2: 1, // y2: 1, // xc'|'yc' // clip: 1, // path: 1, // url: 1, }; export const VG_MARK_CONFIGS = keys(VG_MARK_CONFIG_INDEX); export const VG_MARK_INDEX: Flag<Mark['type']> = { arc: 1, area: 1, group: 1, image: 1, line: 1, path: 1, rect: 1, rule: 1, shape: 1, symbol: 1, text: 1, trail: 1 }; // Vega's cornerRadius channels. export const VG_CORNERRADIUS_CHANNELS = [ 'cornerRadius', 'cornerRadiusTopLeft', 'cornerRadiusTopRight', 'cornerRadiusBottomLeft', 'cornerRadiusBottomRight' ] as const; export interface VgComparator { field?: string | string[]; order?: SortOrder | SortOrder[]; } export interface VgJoinAggregateTransform { type: 'joinaggregate'; as?: string[]; ops?: AggregateOp[]; fields?: string[]; groupby?: string[]; }
{ if (!isArray(domain)) { return 'field' in domain && 'data' in domain; } return false; }
identifier_body
ScrKeyboard.py
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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. # # Please read the COPYING file. # import gettext _ = gettext.translation('yali', fallback=True).ugettext from PyQt5.Qt import QWidget, pyqtSignal, QVariant import yali.util import yali.localedata import yali.postinstall import yali.context as ctx from yali.gui import ScreenWidget from yali.gui.Ui.keyboardwidget import Ui_KeyboardWidget ## # Keyboard setup screen class Widget(QWidget, ScreenWidget): name = "keyboardSetup" def
(self): QWidget.__init__(self) self.ui = Ui_KeyboardWidget() self.ui.setupUi(self) index = 0 # comboBox.addItem doesn't increase the currentIndex self.default_layout_index = None locales = sorted([(country, data) for country, data in yali.localedata.locales.items()]) for country, data in locales: if data["xkbvariant"]: i = 0 for variant in data["xkbvariant"]: _d = dict(data) _d["xkbvariant"] = variant[0] _d["name"] = variant[1] _d["consolekeymap"] = data["consolekeymap"][i] self.ui.keyboard_list.addItem(_d["name"], QVariant(_d)) i += 1 else: self.ui.keyboard_list.addItem(data["name"], QVariant(data)) if ctx.consts.lang == country: if ctx.consts.lang == "tr": self.default_layout_index = index + 1 else: self.default_layout_index = index index += 1 self.ui.keyboard_list.setCurrentIndex(self.default_layout_index) self.ui.keyboard_list.currentIndexChanged[int].connect(self.slotLayoutChanged) def shown(self): self.slotLayoutChanged() def slotLayoutChanged(self): index = self.ui.keyboard_list.currentIndex() keymap = self.ui.keyboard_list.itemData(index)#.toMap() # Gökmen's converter keymap = dict(map(lambda x: (str(x[0]), unicode(x[1])), keymap.iteritems())) ctx.installData.keyData = keymap ctx.interface.informationWindow.hide() if "," in keymap["xkblayout"]: message = _("Use Alt-Shift to toggle between alternative keyboard layouts") ctx.interface.informationWindow.update(message, type="warning") else: ctx.interface.informationWindow.hide() yali.util.setKeymap(keymap["xkblayout"], keymap["xkbvariant"]) def execute(self): ctx.interface.informationWindow.hide() ctx.logger.debug("Selected keymap is : %s" % ctx.installData.keyData["name"]) return True
__init__
identifier_name
ScrKeyboard.py
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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. # # Please read the COPYING file. # import gettext _ = gettext.translation('yali', fallback=True).ugettext from PyQt5.Qt import QWidget, pyqtSignal, QVariant import yali.util import yali.localedata import yali.postinstall import yali.context as ctx from yali.gui import ScreenWidget from yali.gui.Ui.keyboardwidget import Ui_KeyboardWidget ## # Keyboard setup screen class Widget(QWidget, ScreenWidget): name = "keyboardSetup" def __init__(self): QWidget.__init__(self) self.ui = Ui_KeyboardWidget() self.ui.setupUi(self) index = 0 # comboBox.addItem doesn't increase the currentIndex self.default_layout_index = None locales = sorted([(country, data) for country, data in yali.localedata.locales.items()]) for country, data in locales: if data["xkbvariant"]: i = 0 for variant in data["xkbvariant"]: _d = dict(data) _d["xkbvariant"] = variant[0] _d["name"] = variant[1] _d["consolekeymap"] = data["consolekeymap"][i] self.ui.keyboard_list.addItem(_d["name"], QVariant(_d)) i += 1 else: self.ui.keyboard_list.addItem(data["name"], QVariant(data)) if ctx.consts.lang == country: if ctx.consts.lang == "tr": self.default_layout_index = index + 1 else: self.default_layout_index = index index += 1 self.ui.keyboard_list.setCurrentIndex(self.default_layout_index) self.ui.keyboard_list.currentIndexChanged[int].connect(self.slotLayoutChanged) def shown(self): self.slotLayoutChanged() def slotLayoutChanged(self):
def execute(self): ctx.interface.informationWindow.hide() ctx.logger.debug("Selected keymap is : %s" % ctx.installData.keyData["name"]) return True
index = self.ui.keyboard_list.currentIndex() keymap = self.ui.keyboard_list.itemData(index)#.toMap() # Gökmen's converter keymap = dict(map(lambda x: (str(x[0]), unicode(x[1])), keymap.iteritems())) ctx.installData.keyData = keymap ctx.interface.informationWindow.hide() if "," in keymap["xkblayout"]: message = _("Use Alt-Shift to toggle between alternative keyboard layouts") ctx.interface.informationWindow.update(message, type="warning") else: ctx.interface.informationWindow.hide() yali.util.setKeymap(keymap["xkblayout"], keymap["xkbvariant"])
identifier_body
ScrKeyboard.py
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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. # # Please read the COPYING file. # import gettext _ = gettext.translation('yali', fallback=True).ugettext from PyQt5.Qt import QWidget, pyqtSignal, QVariant import yali.util import yali.localedata import yali.postinstall import yali.context as ctx from yali.gui import ScreenWidget from yali.gui.Ui.keyboardwidget import Ui_KeyboardWidget ## # Keyboard setup screen class Widget(QWidget, ScreenWidget): name = "keyboardSetup" def __init__(self): QWidget.__init__(self) self.ui = Ui_KeyboardWidget() self.ui.setupUi(self) index = 0 # comboBox.addItem doesn't increase the currentIndex self.default_layout_index = None locales = sorted([(country, data) for country, data in yali.localedata.locales.items()]) for country, data in locales: if data["xkbvariant"]: i = 0 for variant in data["xkbvariant"]: _d = dict(data) _d["xkbvariant"] = variant[0] _d["name"] = variant[1] _d["consolekeymap"] = data["consolekeymap"][i] self.ui.keyboard_list.addItem(_d["name"], QVariant(_d)) i += 1 else: self.ui.keyboard_list.addItem(data["name"], QVariant(data)) if ctx.consts.lang == country: if ctx.consts.lang == "tr": self.default_layout_index = index + 1 else:
index += 1 self.ui.keyboard_list.setCurrentIndex(self.default_layout_index) self.ui.keyboard_list.currentIndexChanged[int].connect(self.slotLayoutChanged) def shown(self): self.slotLayoutChanged() def slotLayoutChanged(self): index = self.ui.keyboard_list.currentIndex() keymap = self.ui.keyboard_list.itemData(index)#.toMap() # Gökmen's converter keymap = dict(map(lambda x: (str(x[0]), unicode(x[1])), keymap.iteritems())) ctx.installData.keyData = keymap ctx.interface.informationWindow.hide() if "," in keymap["xkblayout"]: message = _("Use Alt-Shift to toggle between alternative keyboard layouts") ctx.interface.informationWindow.update(message, type="warning") else: ctx.interface.informationWindow.hide() yali.util.setKeymap(keymap["xkblayout"], keymap["xkbvariant"]) def execute(self): ctx.interface.informationWindow.hide() ctx.logger.debug("Selected keymap is : %s" % ctx.installData.keyData["name"]) return True
self.default_layout_index = index
conditional_block
ScrKeyboard.py
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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. # # Please read the COPYING file. # import gettext _ = gettext.translation('yali', fallback=True).ugettext from PyQt5.Qt import QWidget, pyqtSignal, QVariant import yali.util import yali.localedata import yali.postinstall import yali.context as ctx from yali.gui import ScreenWidget from yali.gui.Ui.keyboardwidget import Ui_KeyboardWidget ## # Keyboard setup screen class Widget(QWidget, ScreenWidget): name = "keyboardSetup" def __init__(self): QWidget.__init__(self) self.ui = Ui_KeyboardWidget() self.ui.setupUi(self) index = 0 # comboBox.addItem doesn't increase the currentIndex self.default_layout_index = None locales = sorted([(country, data) for country, data in yali.localedata.locales.items()]) for country, data in locales: if data["xkbvariant"]: i = 0 for variant in data["xkbvariant"]: _d = dict(data)
_d["consolekeymap"] = data["consolekeymap"][i] self.ui.keyboard_list.addItem(_d["name"], QVariant(_d)) i += 1 else: self.ui.keyboard_list.addItem(data["name"], QVariant(data)) if ctx.consts.lang == country: if ctx.consts.lang == "tr": self.default_layout_index = index + 1 else: self.default_layout_index = index index += 1 self.ui.keyboard_list.setCurrentIndex(self.default_layout_index) self.ui.keyboard_list.currentIndexChanged[int].connect(self.slotLayoutChanged) def shown(self): self.slotLayoutChanged() def slotLayoutChanged(self): index = self.ui.keyboard_list.currentIndex() keymap = self.ui.keyboard_list.itemData(index)#.toMap() # Gökmen's converter keymap = dict(map(lambda x: (str(x[0]), unicode(x[1])), keymap.iteritems())) ctx.installData.keyData = keymap ctx.interface.informationWindow.hide() if "," in keymap["xkblayout"]: message = _("Use Alt-Shift to toggle between alternative keyboard layouts") ctx.interface.informationWindow.update(message, type="warning") else: ctx.interface.informationWindow.hide() yali.util.setKeymap(keymap["xkblayout"], keymap["xkbvariant"]) def execute(self): ctx.interface.informationWindow.hide() ctx.logger.debug("Selected keymap is : %s" % ctx.installData.keyData["name"]) return True
_d["xkbvariant"] = variant[0] _d["name"] = variant[1]
random_line_split
OptionSchemas.ts
/** * Individual option schema within a menu. */ export type OptionSchema = | ActionSchema | BooleanSchema | MultiSelectSchema | NumberSchema | SelectSchema | StringSchema; /** * Type of an option schema. */ export enum OptionType { /** * Simple triggerable action. */ Action = "action", /** * Boolean toggle state. */ Boolean = "boolean", /** * Multiple selections of given preset values. */ MultiSelect = "multi-select", /** * Numeric value within a range. */ Number = "number", /** * One of given preset values. */
*/ String = "string", } /** * Basic details for option schemas. */ export interface BasicSchema { /** * Displayed title of the option. */ title: string; /** * Type of the option. */ type: OptionType; } /** * Option that just calls an action. */ export interface ActionSchema extends BasicSchema { /** * Action the option will call. */ action(): void; /** * Type of the action (action). */ type: OptionType.Action; } /** * Schema for an option whose value is saved locally. * * @template TValue Type of the value. */ export interface SaveableSchema<TValue> extends BasicSchema { /** * @returns An initial state for the value. */ getInitialValue(): TValue; /** * Saves a new state value. * * @param newValue New state for the value. * @param oldValue Old state for the value. */ saveValue(newValue: TValue, oldValue: TValue): void; } /** * Option that stores a boolean value. */ export interface BooleanSchema extends SaveableSchema<boolean> { /** * Type of the option (boolean). */ type: OptionType.Boolean; } /** * Option that stores multiple options within preset values. */ export interface MultiSelectSchema extends SaveableSchema<string[]> { /** * Given preset values. */ options: string[]; /** * How many of the preset options must be chosen at once. */ selections: number; /** * Type of the option (select). */ type: OptionType.MultiSelect; } /** * Option that stores a numeric value. */ export interface NumberSchema extends SaveableSchema<number> { /** * Maximum numeric value, if any. */ maximum?: number; /** * Minimum numeric value, if any. */ minimum?: number; /** * Type of the option (numeric). */ type: OptionType.Number; } /** * Option that stores one of its preset values. */ export interface SelectSchema extends SaveableSchema<string> { /** * Given preset values. */ options: string[]; /** * Type of the option (select). */ type: OptionType.Select; } /** * Option that stores a string value. */ export interface StringSchema extends SaveableSchema<string> { /** * Type of the option (string). */ type: OptionType.String; }
Select = "select", /** * Any string value.
random_line_split
all.js
'use strict';
description: 'A KanBan system for FogBugz using MeanJS', keywords: 'KanBan, FogBugz, MeanJS' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js' ] }, css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
module.exports = { app: { title: 'FrogBan',
random_line_split
main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate yak_client; extern crate capnp; extern crate log4rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::Error; use std::path::Path; use yak_client::{WireProtocol,Request,Response,Operation,Datum,SeqNo,YakError}; #[macro_use] mod store; mod sqlite_store; macro_rules! try_box { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { return Err(From::from(Box::new(err) as Box<Error + 'static>)) } }) } #[derive(Debug)] enum ServerError { CapnpError(capnp::Error), CapnpNotInSchema(capnp::NotInSchema), IoError(std::io::Error), DownstreamError(YakError), StoreError(Box<Error>), } impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &ServerError::CapnpError(ref e) => e.fmt(f), &ServerError::CapnpNotInSchema(ref e) => e.fmt(f),
&ServerError::IoError(ref e) => e.fmt(f), &ServerError::DownstreamError(ref e) => e.fmt(f), &ServerError::StoreError(ref e) => write!(f, "{}", e), } } } impl Error for ServerError { fn description(&self) -> &str { match self { &ServerError::CapnpError(ref e) => e.description(), &ServerError::CapnpNotInSchema(ref e) => e.description(), &ServerError::IoError(ref e) => e.description(), &ServerError::DownstreamError(ref e) => e.description(), &ServerError::StoreError(ref e) => e.description(), } } } struct DownStream<S: Read+Write> { protocol: Arc<Mutex<WireProtocol<S>>>, } impl <S: ::std::fmt::Debug + Read + Write> ::std::fmt::Debug for DownStream<S> where S: ::std::fmt::Debug + 'static { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self.protocol.try_lock() { Ok(ref proto) => write!(fmt, "DownStream{{ protocol: {:?} }}", &**proto), Err(_) => write!(fmt, "DownStream{{ protocol: <locked> }}"), } } } impl<S> Clone for DownStream<S> where S: Read+Write { fn clone(&self) -> DownStream<S> { DownStream { protocol: self.protocol.clone() } } } static LOG_FILE: &'static str = "log.toml"; pub fn main() { if let Err(e) = log4rs::init_file(LOG_FILE, Default::default()) { panic!("Could not init logger from file {}: {}", LOG_FILE, e); } match do_run() { Ok(()) => info!("Terminated normally"), Err(e) => panic!("Failed: {}", e), } } fn do_run() -> Result<(), ServerError> { let mut a = std::env::args().skip(1); let storedir = a.next().unwrap(); let local : String = a.next().unwrap(); let next = match a.next() { Some(ref addr) => Some(try!(DownStream::new(addr))), None => None }; let listener = TcpListener::bind(&local as &str).unwrap(); info!("listening started on {}, ready to accept", local); let store = sqlite_store::SqliteStore::new(Path::new(&storedir)).unwrap(); for stream in listener.incoming() { let next = next.clone(); let store = store.clone(); let sock = stream.unwrap(); let peer = sock.peer_addr().unwrap(); let _ = try!(thread::Builder::new().name(format!("C{}", peer)).spawn(move || { debug!("Accept stream from {:?}", peer); match Session::new(peer, sock, store, next).process_requests() { Err(e) => report_session_errors(&e), _ => () } })); } Ok(()) } fn report_session_errors(error: &Error) { error!("Session failed with: {}", error); while let Some(error) = error.cause() { error!("\tCaused by: {}", error); } } impl DownStream<TcpStream> { fn new(addr: &str) -> Result<DownStream<TcpStream>, ServerError> { debug!("Connect downstream: {:?}", addr); let proto = try_box!(WireProtocol::connect(addr)); debug!("Connected downstream: {:?}", proto); Ok(DownStream { protocol: Arc::new(Mutex::new(proto)) }) } } fn ptr_addr<T>(obj:&T) -> usize { return obj as *const T as usize; } impl<S: Read+Write> DownStream<S> { fn handle(&self, msg: &Request) -> Result<Response, ServerError> { let mut wire = self.protocol.lock().unwrap(); debug!("Downstream: -> {:x}", ptr_addr(&msg)); try!(wire.send(msg)); debug!("Downstream wait: {:x}", ptr_addr(&msg)); let resp = try!(wire.read::<Response>()); debug!("Downstream: <- {:x}", ptr_addr(&resp)); resp.map(Ok).unwrap_or(Err(ServerError::DownstreamError(YakError::ProtocolError))) } } struct Session<Id, S:Read+Write+'static, ST> { id: Id, protocol: WireProtocol<S>, store: ST, next: Option<DownStream<S>> } impl<Id: fmt::Display, S: Read+Write, ST:store::Store> Session<Id, S, ST> { fn new(id: Id, conn: S, store: ST, next: Option<DownStream<S>>) -> Session<Id, S, ST> { Session { id: id, protocol: WireProtocol::new(conn), store: store, next: next } } fn process_requests(&mut self) -> Result<(), ServerError> { trace!("{}: Waiting for message", self.id); while let Some(msg) = try!(self.protocol.read::<Request>()) { try!(self.process_one(msg)); } Ok(()) } fn process_one(&mut self, msg: Request) -> Result<(), ServerError> { trace!("{}: Handle message: {:x}", self.id, ptr_addr(&msg)); let resp = match msg.operation { Operation::Write { ref key, ref value } => { let resp = try!(self.write(msg.sequence, &msg.space, &key, &value)); try!(self.send_downstream_or(&msg, resp)) }, Operation::Read { key } => try!(self.read(msg.sequence, &msg.space, &key)), Operation::Subscribe => { try!(self.subscribe(msg.sequence, &msg.space)); Response::Okay(msg.sequence) }, }; trace!("Response: {:?}", resp); try!(self.protocol.send(&resp)); Ok(()) } fn send_downstream_or(&self, msg: &Request, default: Response) -> Result<Response, ServerError> { match self.next { Some(ref d) => d.handle(msg), None => Ok(default), } } fn read(&self, seq: SeqNo, space: &str, key: &[u8]) -> Result<Response, ServerError> { let val = try_box!(self.store.read(space, key)); trace!("{}/{:?}: read:{:?}: -> {:?}", self.id, space, key, val); let data = val.iter().map(|c| Datum { key: Vec::new(), content: c.clone() }).collect(); Ok(Response::OkayData(seq, data)) } fn write(&self, seq: SeqNo, space: &str, key: &[u8], val: &[u8]) -> Result<Response, ServerError> { trace!("{}/{:?}: write:{:?} -> {:?}", self.id, space, key, val); try_box!(self.store.write(space, key, val)); Ok(Response::Okay(seq)) } fn subscribe(&mut self, seq: SeqNo, space: &str) -> Result<(), ServerError> { try!(self.protocol.send(&Response::Okay(seq))); for d in try_box!(self.store.subscribe(space)) { try!(self.protocol.send(&Response::Delivery(d))); } Ok(()) } } impl From<capnp::Error> for ServerError { fn from(err: capnp::Error) -> ServerError { ServerError::CapnpError(err) } } impl From<capnp::NotInSchema> for ServerError { fn from(err: capnp::NotInSchema) -> ServerError { ServerError::CapnpNotInSchema(err) } } impl From<io::Error> for ServerError { fn from(err: io::Error) -> ServerError { ServerError::IoError(err) } } impl From<YakError> for ServerError { fn from(err: YakError) -> ServerError { ServerError::DownstreamError(err) } } impl From<Box<Error>> for ServerError { fn from(err: Box<Error>) -> ServerError { ServerError::StoreError(err) } }
random_line_split
main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate yak_client; extern crate capnp; extern crate log4rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::Error; use std::path::Path; use yak_client::{WireProtocol,Request,Response,Operation,Datum,SeqNo,YakError}; #[macro_use] mod store; mod sqlite_store; macro_rules! try_box { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { return Err(From::from(Box::new(err) as Box<Error + 'static>)) } }) } #[derive(Debug)] enum ServerError { CapnpError(capnp::Error), CapnpNotInSchema(capnp::NotInSchema), IoError(std::io::Error), DownstreamError(YakError), StoreError(Box<Error>), } impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &ServerError::CapnpError(ref e) => e.fmt(f), &ServerError::CapnpNotInSchema(ref e) => e.fmt(f), &ServerError::IoError(ref e) => e.fmt(f), &ServerError::DownstreamError(ref e) => e.fmt(f), &ServerError::StoreError(ref e) => write!(f, "{}", e), } } } impl Error for ServerError { fn description(&self) -> &str { match self { &ServerError::CapnpError(ref e) => e.description(), &ServerError::CapnpNotInSchema(ref e) => e.description(), &ServerError::IoError(ref e) => e.description(), &ServerError::DownstreamError(ref e) => e.description(), &ServerError::StoreError(ref e) => e.description(), } } } struct DownStream<S: Read+Write> { protocol: Arc<Mutex<WireProtocol<S>>>, } impl <S: ::std::fmt::Debug + Read + Write> ::std::fmt::Debug for DownStream<S> where S: ::std::fmt::Debug + 'static { fn
(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self.protocol.try_lock() { Ok(ref proto) => write!(fmt, "DownStream{{ protocol: {:?} }}", &**proto), Err(_) => write!(fmt, "DownStream{{ protocol: <locked> }}"), } } } impl<S> Clone for DownStream<S> where S: Read+Write { fn clone(&self) -> DownStream<S> { DownStream { protocol: self.protocol.clone() } } } static LOG_FILE: &'static str = "log.toml"; pub fn main() { if let Err(e) = log4rs::init_file(LOG_FILE, Default::default()) { panic!("Could not init logger from file {}: {}", LOG_FILE, e); } match do_run() { Ok(()) => info!("Terminated normally"), Err(e) => panic!("Failed: {}", e), } } fn do_run() -> Result<(), ServerError> { let mut a = std::env::args().skip(1); let storedir = a.next().unwrap(); let local : String = a.next().unwrap(); let next = match a.next() { Some(ref addr) => Some(try!(DownStream::new(addr))), None => None }; let listener = TcpListener::bind(&local as &str).unwrap(); info!("listening started on {}, ready to accept", local); let store = sqlite_store::SqliteStore::new(Path::new(&storedir)).unwrap(); for stream in listener.incoming() { let next = next.clone(); let store = store.clone(); let sock = stream.unwrap(); let peer = sock.peer_addr().unwrap(); let _ = try!(thread::Builder::new().name(format!("C{}", peer)).spawn(move || { debug!("Accept stream from {:?}", peer); match Session::new(peer, sock, store, next).process_requests() { Err(e) => report_session_errors(&e), _ => () } })); } Ok(()) } fn report_session_errors(error: &Error) { error!("Session failed with: {}", error); while let Some(error) = error.cause() { error!("\tCaused by: {}", error); } } impl DownStream<TcpStream> { fn new(addr: &str) -> Result<DownStream<TcpStream>, ServerError> { debug!("Connect downstream: {:?}", addr); let proto = try_box!(WireProtocol::connect(addr)); debug!("Connected downstream: {:?}", proto); Ok(DownStream { protocol: Arc::new(Mutex::new(proto)) }) } } fn ptr_addr<T>(obj:&T) -> usize { return obj as *const T as usize; } impl<S: Read+Write> DownStream<S> { fn handle(&self, msg: &Request) -> Result<Response, ServerError> { let mut wire = self.protocol.lock().unwrap(); debug!("Downstream: -> {:x}", ptr_addr(&msg)); try!(wire.send(msg)); debug!("Downstream wait: {:x}", ptr_addr(&msg)); let resp = try!(wire.read::<Response>()); debug!("Downstream: <- {:x}", ptr_addr(&resp)); resp.map(Ok).unwrap_or(Err(ServerError::DownstreamError(YakError::ProtocolError))) } } struct Session<Id, S:Read+Write+'static, ST> { id: Id, protocol: WireProtocol<S>, store: ST, next: Option<DownStream<S>> } impl<Id: fmt::Display, S: Read+Write, ST:store::Store> Session<Id, S, ST> { fn new(id: Id, conn: S, store: ST, next: Option<DownStream<S>>) -> Session<Id, S, ST> { Session { id: id, protocol: WireProtocol::new(conn), store: store, next: next } } fn process_requests(&mut self) -> Result<(), ServerError> { trace!("{}: Waiting for message", self.id); while let Some(msg) = try!(self.protocol.read::<Request>()) { try!(self.process_one(msg)); } Ok(()) } fn process_one(&mut self, msg: Request) -> Result<(), ServerError> { trace!("{}: Handle message: {:x}", self.id, ptr_addr(&msg)); let resp = match msg.operation { Operation::Write { ref key, ref value } => { let resp = try!(self.write(msg.sequence, &msg.space, &key, &value)); try!(self.send_downstream_or(&msg, resp)) }, Operation::Read { key } => try!(self.read(msg.sequence, &msg.space, &key)), Operation::Subscribe => { try!(self.subscribe(msg.sequence, &msg.space)); Response::Okay(msg.sequence) }, }; trace!("Response: {:?}", resp); try!(self.protocol.send(&resp)); Ok(()) } fn send_downstream_or(&self, msg: &Request, default: Response) -> Result<Response, ServerError> { match self.next { Some(ref d) => d.handle(msg), None => Ok(default), } } fn read(&self, seq: SeqNo, space: &str, key: &[u8]) -> Result<Response, ServerError> { let val = try_box!(self.store.read(space, key)); trace!("{}/{:?}: read:{:?}: -> {:?}", self.id, space, key, val); let data = val.iter().map(|c| Datum { key: Vec::new(), content: c.clone() }).collect(); Ok(Response::OkayData(seq, data)) } fn write(&self, seq: SeqNo, space: &str, key: &[u8], val: &[u8]) -> Result<Response, ServerError> { trace!("{}/{:?}: write:{:?} -> {:?}", self.id, space, key, val); try_box!(self.store.write(space, key, val)); Ok(Response::Okay(seq)) } fn subscribe(&mut self, seq: SeqNo, space: &str) -> Result<(), ServerError> { try!(self.protocol.send(&Response::Okay(seq))); for d in try_box!(self.store.subscribe(space)) { try!(self.protocol.send(&Response::Delivery(d))); } Ok(()) } } impl From<capnp::Error> for ServerError { fn from(err: capnp::Error) -> ServerError { ServerError::CapnpError(err) } } impl From<capnp::NotInSchema> for ServerError { fn from(err: capnp::NotInSchema) -> ServerError { ServerError::CapnpNotInSchema(err) } } impl From<io::Error> for ServerError { fn from(err: io::Error) -> ServerError { ServerError::IoError(err) } } impl From<YakError> for ServerError { fn from(err: YakError) -> ServerError { ServerError::DownstreamError(err) } } impl From<Box<Error>> for ServerError { fn from(err: Box<Error>) -> ServerError { ServerError::StoreError(err) } }
fmt
identifier_name
main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate yak_client; extern crate capnp; extern crate log4rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::Error; use std::path::Path; use yak_client::{WireProtocol,Request,Response,Operation,Datum,SeqNo,YakError}; #[macro_use] mod store; mod sqlite_store; macro_rules! try_box { ($expr:expr) => (match $expr { Ok(val) => val, Err(err) => { return Err(From::from(Box::new(err) as Box<Error + 'static>)) } }) } #[derive(Debug)] enum ServerError { CapnpError(capnp::Error), CapnpNotInSchema(capnp::NotInSchema), IoError(std::io::Error), DownstreamError(YakError), StoreError(Box<Error>), } impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { &ServerError::CapnpError(ref e) => e.fmt(f), &ServerError::CapnpNotInSchema(ref e) => e.fmt(f), &ServerError::IoError(ref e) => e.fmt(f), &ServerError::DownstreamError(ref e) => e.fmt(f), &ServerError::StoreError(ref e) => write!(f, "{}", e), } } } impl Error for ServerError { fn description(&self) -> &str { match self { &ServerError::CapnpError(ref e) => e.description(), &ServerError::CapnpNotInSchema(ref e) => e.description(), &ServerError::IoError(ref e) => e.description(), &ServerError::DownstreamError(ref e) => e.description(), &ServerError::StoreError(ref e) => e.description(), } } } struct DownStream<S: Read+Write> { protocol: Arc<Mutex<WireProtocol<S>>>, } impl <S: ::std::fmt::Debug + Read + Write> ::std::fmt::Debug for DownStream<S> where S: ::std::fmt::Debug + 'static { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self.protocol.try_lock() { Ok(ref proto) => write!(fmt, "DownStream{{ protocol: {:?} }}", &**proto), Err(_) => write!(fmt, "DownStream{{ protocol: <locked> }}"), } } } impl<S> Clone for DownStream<S> where S: Read+Write { fn clone(&self) -> DownStream<S> { DownStream { protocol: self.protocol.clone() } } } static LOG_FILE: &'static str = "log.toml"; pub fn main() { if let Err(e) = log4rs::init_file(LOG_FILE, Default::default()) { panic!("Could not init logger from file {}: {}", LOG_FILE, e); } match do_run() { Ok(()) => info!("Terminated normally"), Err(e) => panic!("Failed: {}", e), } } fn do_run() -> Result<(), ServerError> { let mut a = std::env::args().skip(1); let storedir = a.next().unwrap(); let local : String = a.next().unwrap(); let next = match a.next() { Some(ref addr) => Some(try!(DownStream::new(addr))), None => None }; let listener = TcpListener::bind(&local as &str).unwrap(); info!("listening started on {}, ready to accept", local); let store = sqlite_store::SqliteStore::new(Path::new(&storedir)).unwrap(); for stream in listener.incoming() { let next = next.clone(); let store = store.clone(); let sock = stream.unwrap(); let peer = sock.peer_addr().unwrap(); let _ = try!(thread::Builder::new().name(format!("C{}", peer)).spawn(move || { debug!("Accept stream from {:?}", peer); match Session::new(peer, sock, store, next).process_requests() { Err(e) => report_session_errors(&e), _ => () } })); } Ok(()) } fn report_session_errors(error: &Error) { error!("Session failed with: {}", error); while let Some(error) = error.cause() { error!("\tCaused by: {}", error); } } impl DownStream<TcpStream> { fn new(addr: &str) -> Result<DownStream<TcpStream>, ServerError> { debug!("Connect downstream: {:?}", addr); let proto = try_box!(WireProtocol::connect(addr)); debug!("Connected downstream: {:?}", proto); Ok(DownStream { protocol: Arc::new(Mutex::new(proto)) }) } } fn ptr_addr<T>(obj:&T) -> usize { return obj as *const T as usize; } impl<S: Read+Write> DownStream<S> { fn handle(&self, msg: &Request) -> Result<Response, ServerError> { let mut wire = self.protocol.lock().unwrap(); debug!("Downstream: -> {:x}", ptr_addr(&msg)); try!(wire.send(msg)); debug!("Downstream wait: {:x}", ptr_addr(&msg)); let resp = try!(wire.read::<Response>()); debug!("Downstream: <- {:x}", ptr_addr(&resp)); resp.map(Ok).unwrap_or(Err(ServerError::DownstreamError(YakError::ProtocolError))) } } struct Session<Id, S:Read+Write+'static, ST> { id: Id, protocol: WireProtocol<S>, store: ST, next: Option<DownStream<S>> } impl<Id: fmt::Display, S: Read+Write, ST:store::Store> Session<Id, S, ST> { fn new(id: Id, conn: S, store: ST, next: Option<DownStream<S>>) -> Session<Id, S, ST> { Session { id: id, protocol: WireProtocol::new(conn), store: store, next: next } } fn process_requests(&mut self) -> Result<(), ServerError> { trace!("{}: Waiting for message", self.id); while let Some(msg) = try!(self.protocol.read::<Request>()) { try!(self.process_one(msg)); } Ok(()) } fn process_one(&mut self, msg: Request) -> Result<(), ServerError> { trace!("{}: Handle message: {:x}", self.id, ptr_addr(&msg)); let resp = match msg.operation { Operation::Write { ref key, ref value } => { let resp = try!(self.write(msg.sequence, &msg.space, &key, &value)); try!(self.send_downstream_or(&msg, resp)) }, Operation::Read { key } => try!(self.read(msg.sequence, &msg.space, &key)), Operation::Subscribe => { try!(self.subscribe(msg.sequence, &msg.space)); Response::Okay(msg.sequence) }, }; trace!("Response: {:?}", resp); try!(self.protocol.send(&resp)); Ok(()) } fn send_downstream_or(&self, msg: &Request, default: Response) -> Result<Response, ServerError> { match self.next { Some(ref d) => d.handle(msg), None => Ok(default), } } fn read(&self, seq: SeqNo, space: &str, key: &[u8]) -> Result<Response, ServerError>
fn write(&self, seq: SeqNo, space: &str, key: &[u8], val: &[u8]) -> Result<Response, ServerError> { trace!("{}/{:?}: write:{:?} -> {:?}", self.id, space, key, val); try_box!(self.store.write(space, key, val)); Ok(Response::Okay(seq)) } fn subscribe(&mut self, seq: SeqNo, space: &str) -> Result<(), ServerError> { try!(self.protocol.send(&Response::Okay(seq))); for d in try_box!(self.store.subscribe(space)) { try!(self.protocol.send(&Response::Delivery(d))); } Ok(()) } } impl From<capnp::Error> for ServerError { fn from(err: capnp::Error) -> ServerError { ServerError::CapnpError(err) } } impl From<capnp::NotInSchema> for ServerError { fn from(err: capnp::NotInSchema) -> ServerError { ServerError::CapnpNotInSchema(err) } } impl From<io::Error> for ServerError { fn from(err: io::Error) -> ServerError { ServerError::IoError(err) } } impl From<YakError> for ServerError { fn from(err: YakError) -> ServerError { ServerError::DownstreamError(err) } } impl From<Box<Error>> for ServerError { fn from(err: Box<Error>) -> ServerError { ServerError::StoreError(err) } }
{ let val = try_box!(self.store.read(space, key)); trace!("{}/{:?}: read:{:?}: -> {:?}", self.id, space, key, val); let data = val.iter().map(|c| Datum { key: Vec::new(), content: c.clone() }).collect(); Ok(Response::OkayData(seq, data)) }
identifier_body
signup.component.ts
import { Component, OnInit } from "@angular/core"; import { Router } from '@angular/router' import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; import { AuthService } from '../../services/authServices/auth.service'; @Component({ moduleId: module.id, selector: 'signup', templateUrl: 'signup.component.html' }) export class SignUpComponent{ email: string; password: string; password_confirmation: string; errors: any; constructor(private _AuthService: AuthService, private _Router: Router) {
onSignup() { var signupInfo = { email: this.email, password: this.password, password_confirmation: this.password_confirmation }; this._AuthService.signUp(signupInfo).subscribe( response => { console.log("Success Response " + response); console.log(response); this._Router.navigate(['/']); }, error => { console.log("Error happened " + error); this.errors = error.json().errors; console.log(this.errors); }, function() { console.log("the subscription is completed")} ); } ngOnInit(): void { } }
this.email = ''; this.password = ''; this.password_confirmation = ''; }
random_line_split
signup.component.ts
import { Component, OnInit } from "@angular/core"; import { Router } from '@angular/router' import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; import { AuthService } from '../../services/authServices/auth.service'; @Component({ moduleId: module.id, selector: 'signup', templateUrl: 'signup.component.html' }) export class SignUpComponent{ email: string; password: string; password_confirmation: string; errors: any; constructor(private _AuthService: AuthService, private _Router: Router) { this.email = ''; this.password = ''; this.password_confirmation = ''; }
() { var signupInfo = { email: this.email, password: this.password, password_confirmation: this.password_confirmation }; this._AuthService.signUp(signupInfo).subscribe( response => { console.log("Success Response " + response); console.log(response); this._Router.navigate(['/']); }, error => { console.log("Error happened " + error); this.errors = error.json().errors; console.log(this.errors); }, function() { console.log("the subscription is completed")} ); } ngOnInit(): void { } }
onSignup
identifier_name
signup.component.ts
import { Component, OnInit } from "@angular/core"; import { Router } from '@angular/router' import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; import { AuthService } from '../../services/authServices/auth.service'; @Component({ moduleId: module.id, selector: 'signup', templateUrl: 'signup.component.html' }) export class SignUpComponent{ email: string; password: string; password_confirmation: string; errors: any; constructor(private _AuthService: AuthService, private _Router: Router) { this.email = ''; this.password = ''; this.password_confirmation = ''; } onSignup()
ngOnInit(): void { } }
{ var signupInfo = { email: this.email, password: this.password, password_confirmation: this.password_confirmation }; this._AuthService.signUp(signupInfo).subscribe( response => { console.log("Success Response " + response); console.log(response); this._Router.navigate(['/']); }, error => { console.log("Error happened " + error); this.errors = error.json().errors; console.log(this.errors); }, function() { console.log("the subscription is completed")} ); }
identifier_body
Position.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Position */ 'use strict'; var PooledClass = require('react/lib/PooledClass'); var twoArgumentPooler = PooledClass.twoArgumentPooler; /** * Position does not expose methods for construction via an `HTMLDOMElement`, * because it isn't meaningful to construct such a thing without first defining * a frame of reference. * * @param {number} windowStartKey Key that window starts at. * @param {number} windowEndKey Key that window ends at. */ function
(left, top) { this.left = left; this.top = top; } Position.prototype.destructor = function() { this.left = null; this.top = null; }; PooledClass.addPoolingTo(Position, twoArgumentPooler); module.exports = Position;
Position
identifier_name
Position.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Position */ 'use strict'; var PooledClass = require('react/lib/PooledClass'); var twoArgumentPooler = PooledClass.twoArgumentPooler; /** * Position does not expose methods for construction via an `HTMLDOMElement`, * because it isn't meaningful to construct such a thing without first defining * a frame of reference. * * @param {number} windowStartKey Key that window starts at. * @param {number} windowEndKey Key that window ends at. */ function Position(left, top)
Position.prototype.destructor = function() { this.left = null; this.top = null; }; PooledClass.addPoolingTo(Position, twoArgumentPooler); module.exports = Position;
{ this.left = left; this.top = top; }
identifier_body
Position.js
/**
* of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Position */ 'use strict'; var PooledClass = require('react/lib/PooledClass'); var twoArgumentPooler = PooledClass.twoArgumentPooler; /** * Position does not expose methods for construction via an `HTMLDOMElement`, * because it isn't meaningful to construct such a thing without first defining * a frame of reference. * * @param {number} windowStartKey Key that window starts at. * @param {number} windowEndKey Key that window ends at. */ function Position(left, top) { this.left = left; this.top = top; } Position.prototype.destructor = function() { this.left = null; this.top = null; }; PooledClass.addPoolingTo(Position, twoArgumentPooler); module.exports = Position;
* Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant
random_line_split
wiki_model.py
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class WikiModel(): def __init__(self): self.vocabulary = set() self.stop_words = set() self.english_words = set() self.label_map = {} self.reverse_label_map = {} self.count_data = [] self.labels = [] self.vectorizer = None self.classifier = None self.load_training_data() def load_training_data(self): # make some dictionaries to preprocess the words english_words = set() with open(PATH + "american-english.txt") as english_dictionary: english_words = set( word.strip().lower() for word in english_dictionary) stop_words = set() with open(PATH + "english_stopwords.txt") as stopwords: stop_words = set(word.strip().lower() for word in stopwords) self.english_words = english_words self.stop_words = stop_words if not os.path.isfile(PATH + 'categories.pickle'): scrape_wikipedia() categories = pickle.load(open(PATH + 'categories.pickle', 'rb')) # parse the html, turning it into a list of words # and removing stop words and non-dictionary words # we'll also collect all of the words so that we can make a map of # words to numbers all_words = set() # the category level for k, v in categories.iteritems(): # the document level for inner_k, inner_document in v.iteritems(): # parse the html to get lists of words per document words = parse_html_simple(inner_document) parsed = [] for word in words: if word in english_words and word not in stop_words: all_words.add(word) parsed.append(word) categories[k][inner_k] = parsed # aggregate all of the documents into one big data set while # transforming them into counts self.vocabulary = set(all_words) self.vectorizer = CountVectorizer(vocabulary=self.vocabulary) count_data = [] string_data = [] labels = [] # the category level for k, v in categories.iteritems(): # the document level for inner_k, inner_document in v.iteritems(): # oops, we actually need this in string format string_data.append(' '.join(inner_document)) labels.append(k) # transform the string data into count data count_data = self.vectorizer.transform(string_data).todense() # transform count_data and babels into numpy arrays for easy indexing count_data = numpy.array(count_data) labels = numpy.array(labels).squeeze() # make a map from the string label to a number and vice versa self.label_map = {} self.reverse_label_map = {} i = 0 for label in sorted(set(labels)): self.reverse_label_map[i] = label self.label_map[label] = i i += 1 # fit the model self.classifier = MultinomialNB() self.classifier.fit(count_data, labels) def classify_url(self, domain, page, depth=0): """ Classify the documents after crawling them. args: domain - the domain part of the url page - the other part of the url depth - how deep to crawl returns: a list of predicted probabilities for each instance belonging to each class """ # get the documents documents, _ = crawl_page(domain, page, depth=0) # parse the documents string_data = [] for page, doc in documents.iteritems(): words = parse_html_simple(doc) parsed = [] for word in words:
string_data.append(' '.join(parsed)) count_data = self.vectorizer.transform(string_data) # classify the documents probs = self.classifier.predict_proba(count_data) return probs
if (word in self.english_words and word not in self.stop_words and word in self.vocabulary): parsed.append(word)
conditional_block
wiki_model.py
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class WikiModel(): def __init__(self):
def load_training_data(self): # make some dictionaries to preprocess the words english_words = set() with open(PATH + "american-english.txt") as english_dictionary: english_words = set( word.strip().lower() for word in english_dictionary) stop_words = set() with open(PATH + "english_stopwords.txt") as stopwords: stop_words = set(word.strip().lower() for word in stopwords) self.english_words = english_words self.stop_words = stop_words if not os.path.isfile(PATH + 'categories.pickle'): scrape_wikipedia() categories = pickle.load(open(PATH + 'categories.pickle', 'rb')) # parse the html, turning it into a list of words # and removing stop words and non-dictionary words # we'll also collect all of the words so that we can make a map of # words to numbers all_words = set() # the category level for k, v in categories.iteritems(): # the document level for inner_k, inner_document in v.iteritems(): # parse the html to get lists of words per document words = parse_html_simple(inner_document) parsed = [] for word in words: if word in english_words and word not in stop_words: all_words.add(word) parsed.append(word) categories[k][inner_k] = parsed # aggregate all of the documents into one big data set while # transforming them into counts self.vocabulary = set(all_words) self.vectorizer = CountVectorizer(vocabulary=self.vocabulary) count_data = [] string_data = [] labels = [] # the category level for k, v in categories.iteritems(): # the document level for inner_k, inner_document in v.iteritems(): # oops, we actually need this in string format string_data.append(' '.join(inner_document)) labels.append(k) # transform the string data into count data count_data = self.vectorizer.transform(string_data).todense() # transform count_data and babels into numpy arrays for easy indexing count_data = numpy.array(count_data) labels = numpy.array(labels).squeeze() # make a map from the string label to a number and vice versa self.label_map = {} self.reverse_label_map = {} i = 0 for label in sorted(set(labels)): self.reverse_label_map[i] = label self.label_map[label] = i i += 1 # fit the model self.classifier = MultinomialNB() self.classifier.fit(count_data, labels) def classify_url(self, domain, page, depth=0): """ Classify the documents after crawling them. args: domain - the domain part of the url page - the other part of the url depth - how deep to crawl returns: a list of predicted probabilities for each instance belonging to each class """ # get the documents documents, _ = crawl_page(domain, page, depth=0) # parse the documents string_data = [] for page, doc in documents.iteritems(): words = parse_html_simple(doc) parsed = [] for word in words: if (word in self.english_words and word not in self.stop_words and word in self.vocabulary): parsed.append(word) string_data.append(' '.join(parsed)) count_data = self.vectorizer.transform(string_data) # classify the documents probs = self.classifier.predict_proba(count_data) return probs
self.vocabulary = set() self.stop_words = set() self.english_words = set() self.label_map = {} self.reverse_label_map = {} self.count_data = [] self.labels = [] self.vectorizer = None self.classifier = None self.load_training_data()
identifier_body
wiki_model.py
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class
(): def __init__(self): self.vocabulary = set() self.stop_words = set() self.english_words = set() self.label_map = {} self.reverse_label_map = {} self.count_data = [] self.labels = [] self.vectorizer = None self.classifier = None self.load_training_data() def load_training_data(self): # make some dictionaries to preprocess the words english_words = set() with open(PATH + "american-english.txt") as english_dictionary: english_words = set( word.strip().lower() for word in english_dictionary) stop_words = set() with open(PATH + "english_stopwords.txt") as stopwords: stop_words = set(word.strip().lower() for word in stopwords) self.english_words = english_words self.stop_words = stop_words if not os.path.isfile(PATH + 'categories.pickle'): scrape_wikipedia() categories = pickle.load(open(PATH + 'categories.pickle', 'rb')) # parse the html, turning it into a list of words # and removing stop words and non-dictionary words # we'll also collect all of the words so that we can make a map of # words to numbers all_words = set() # the category level for k, v in categories.iteritems(): # the document level for inner_k, inner_document in v.iteritems(): # parse the html to get lists of words per document words = parse_html_simple(inner_document) parsed = [] for word in words: if word in english_words and word not in stop_words: all_words.add(word) parsed.append(word) categories[k][inner_k] = parsed # aggregate all of the documents into one big data set while # transforming them into counts self.vocabulary = set(all_words) self.vectorizer = CountVectorizer(vocabulary=self.vocabulary) count_data = [] string_data = [] labels = [] # the category level for k, v in categories.iteritems(): # the document level for inner_k, inner_document in v.iteritems(): # oops, we actually need this in string format string_data.append(' '.join(inner_document)) labels.append(k) # transform the string data into count data count_data = self.vectorizer.transform(string_data).todense() # transform count_data and babels into numpy arrays for easy indexing count_data = numpy.array(count_data) labels = numpy.array(labels).squeeze() # make a map from the string label to a number and vice versa self.label_map = {} self.reverse_label_map = {} i = 0 for label in sorted(set(labels)): self.reverse_label_map[i] = label self.label_map[label] = i i += 1 # fit the model self.classifier = MultinomialNB() self.classifier.fit(count_data, labels) def classify_url(self, domain, page, depth=0): """ Classify the documents after crawling them. args: domain - the domain part of the url page - the other part of the url depth - how deep to crawl returns: a list of predicted probabilities for each instance belonging to each class """ # get the documents documents, _ = crawl_page(domain, page, depth=0) # parse the documents string_data = [] for page, doc in documents.iteritems(): words = parse_html_simple(doc) parsed = [] for word in words: if (word in self.english_words and word not in self.stop_words and word in self.vocabulary): parsed.append(word) string_data.append(' '.join(parsed)) count_data = self.vectorizer.transform(string_data) # classify the documents probs = self.classifier.predict_proba(count_data) return probs
WikiModel
identifier_name
wiki_model.py
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class WikiModel(): def __init__(self): self.vocabulary = set() self.stop_words = set() self.english_words = set() self.label_map = {} self.reverse_label_map = {} self.count_data = [] self.labels = [] self.vectorizer = None self.classifier = None self.load_training_data() def load_training_data(self): # make some dictionaries to preprocess the words english_words = set() with open(PATH + "american-english.txt") as english_dictionary: english_words = set( word.strip().lower() for word in english_dictionary) stop_words = set() with open(PATH + "english_stopwords.txt") as stopwords: stop_words = set(word.strip().lower() for word in stopwords) self.english_words = english_words self.stop_words = stop_words if not os.path.isfile(PATH + 'categories.pickle'): scrape_wikipedia() categories = pickle.load(open(PATH + 'categories.pickle', 'rb')) # parse the html, turning it into a list of words # and removing stop words and non-dictionary words # we'll also collect all of the words so that we can make a map of # words to numbers all_words = set() # the category level for k, v in categories.iteritems(): # the document level for inner_k, inner_document in v.iteritems(): # parse the html to get lists of words per document words = parse_html_simple(inner_document) parsed = []
parsed.append(word) categories[k][inner_k] = parsed # aggregate all of the documents into one big data set while # transforming them into counts self.vocabulary = set(all_words) self.vectorizer = CountVectorizer(vocabulary=self.vocabulary) count_data = [] string_data = [] labels = [] # the category level for k, v in categories.iteritems(): # the document level for inner_k, inner_document in v.iteritems(): # oops, we actually need this in string format string_data.append(' '.join(inner_document)) labels.append(k) # transform the string data into count data count_data = self.vectorizer.transform(string_data).todense() # transform count_data and babels into numpy arrays for easy indexing count_data = numpy.array(count_data) labels = numpy.array(labels).squeeze() # make a map from the string label to a number and vice versa self.label_map = {} self.reverse_label_map = {} i = 0 for label in sorted(set(labels)): self.reverse_label_map[i] = label self.label_map[label] = i i += 1 # fit the model self.classifier = MultinomialNB() self.classifier.fit(count_data, labels) def classify_url(self, domain, page, depth=0): """ Classify the documents after crawling them. args: domain - the domain part of the url page - the other part of the url depth - how deep to crawl returns: a list of predicted probabilities for each instance belonging to each class """ # get the documents documents, _ = crawl_page(domain, page, depth=0) # parse the documents string_data = [] for page, doc in documents.iteritems(): words = parse_html_simple(doc) parsed = [] for word in words: if (word in self.english_words and word not in self.stop_words and word in self.vocabulary): parsed.append(word) string_data.append(' '.join(parsed)) count_data = self.vectorizer.transform(string_data) # classify the documents probs = self.classifier.predict_proba(count_data) return probs
for word in words: if word in english_words and word not in stop_words: all_words.add(word)
random_line_split
__init__.py
from functools import reduce def vartype(var): if var.is_discrete: return 1 elif var.is_continuous: return 2 elif var.is_string: return 3 else: return 0 def progress_bar_milestones(count, iterations=100): return set([int(i*count/float(iterations)) for i in range(iterations)]) def getdeepattr(obj, attr, *arg, **kwarg):
except AttributeError: if arg: return arg[0] if kwarg: return kwarg["default"] raise def getHtmlCompatibleString(strVal): return strVal.replace("<=", "&#8804;").replace(">=","&#8805;").replace("<", "&#60;").replace(">","&#62;").replace("=\\=", "&#8800;")
if isinstance(obj, dict): return obj.get(attr) try: return reduce(getattr, attr.split("."), obj)
random_line_split
__init__.py
from functools import reduce def vartype(var): if var.is_discrete: return 1 elif var.is_continuous: return 2 elif var.is_string: return 3 else: return 0 def progress_bar_milestones(count, iterations=100): return set([int(i*count/float(iterations)) for i in range(iterations)]) def getdeepattr(obj, attr, *arg, **kwarg): if isinstance(obj, dict): return obj.get(attr) try: return reduce(getattr, attr.split("."), obj) except AttributeError: if arg: return arg[0] if kwarg: return kwarg["default"] raise def
(strVal): return strVal.replace("<=", "&#8804;").replace(">=","&#8805;").replace("<", "&#60;").replace(">","&#62;").replace("=\\=", "&#8800;")
getHtmlCompatibleString
identifier_name
__init__.py
from functools import reduce def vartype(var): if var.is_discrete: return 1 elif var.is_continuous: return 2 elif var.is_string: return 3 else: return 0 def progress_bar_milestones(count, iterations=100): return set([int(i*count/float(iterations)) for i in range(iterations)]) def getdeepattr(obj, attr, *arg, **kwarg):
def getHtmlCompatibleString(strVal): return strVal.replace("<=", "&#8804;").replace(">=","&#8805;").replace("<", "&#60;").replace(">","&#62;").replace("=\\=", "&#8800;")
if isinstance(obj, dict): return obj.get(attr) try: return reduce(getattr, attr.split("."), obj) except AttributeError: if arg: return arg[0] if kwarg: return kwarg["default"] raise
identifier_body
__init__.py
from functools import reduce def vartype(var): if var.is_discrete:
elif var.is_continuous: return 2 elif var.is_string: return 3 else: return 0 def progress_bar_milestones(count, iterations=100): return set([int(i*count/float(iterations)) for i in range(iterations)]) def getdeepattr(obj, attr, *arg, **kwarg): if isinstance(obj, dict): return obj.get(attr) try: return reduce(getattr, attr.split("."), obj) except AttributeError: if arg: return arg[0] if kwarg: return kwarg["default"] raise def getHtmlCompatibleString(strVal): return strVal.replace("<=", "&#8804;").replace(">=","&#8805;").replace("<", "&#60;").replace(">","&#62;").replace("=\\=", "&#8800;")
return 1
conditional_block
list-link-handler.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 { Injectable } from '@angular/core'; import { CoreContentLinksModuleListHandler } from '@core/contentlinks/classes/module-list-handler'; import { CoreContentLinksHelperProvider } from '@core/contentlinks/providers/helper'; import { TranslateService } from '@ngx-translate/core'; import { AddonModAssignProvider } from './assign'; /** * Handler to treat links to assign list page. */ @Injectable() export class AddonModAssignListLinkHandler extends CoreContentLinksModuleListHandler { name = 'AddonModAssignListLinkHandler'; constructor(linkHelper: CoreContentLinksHelperProvider, translate: TranslateService, protected assignProvider: AddonModAssignProvider)
/** * Check if the handler is enabled on a site level. * * @return {boolean} Whether or not the handler is enabled on a site level. */ isEnabled(): boolean { return this.assignProvider.isPluginEnabled(); } }
{ super(linkHelper, translate, 'AddonModAssign', 'assign'); }
identifier_body
list-link-handler.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 { Injectable } from '@angular/core'; import { CoreContentLinksModuleListHandler } from '@core/contentlinks/classes/module-list-handler'; import { CoreContentLinksHelperProvider } from '@core/contentlinks/providers/helper'; import { TranslateService } from '@ngx-translate/core'; import { AddonModAssignProvider } from './assign'; /** * Handler to treat links to assign list page.
constructor(linkHelper: CoreContentLinksHelperProvider, translate: TranslateService, protected assignProvider: AddonModAssignProvider) { super(linkHelper, translate, 'AddonModAssign', 'assign'); } /** * Check if the handler is enabled on a site level. * * @return {boolean} Whether or not the handler is enabled on a site level. */ isEnabled(): boolean { return this.assignProvider.isPluginEnabled(); } }
*/ @Injectable() export class AddonModAssignListLinkHandler extends CoreContentLinksModuleListHandler { name = 'AddonModAssignListLinkHandler';
random_line_split
list-link-handler.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 { Injectable } from '@angular/core'; import { CoreContentLinksModuleListHandler } from '@core/contentlinks/classes/module-list-handler'; import { CoreContentLinksHelperProvider } from '@core/contentlinks/providers/helper'; import { TranslateService } from '@ngx-translate/core'; import { AddonModAssignProvider } from './assign'; /** * Handler to treat links to assign list page. */ @Injectable() export class AddonModAssignListLinkHandler extends CoreContentLinksModuleListHandler { name = 'AddonModAssignListLinkHandler'; constructor(linkHelper: CoreContentLinksHelperProvider, translate: TranslateService, protected assignProvider: AddonModAssignProvider) { super(linkHelper, translate, 'AddonModAssign', 'assign'); } /** * Check if the handler is enabled on a site level. * * @return {boolean} Whether or not the handler is enabled on a site level. */
(): boolean { return this.assignProvider.isPluginEnabled(); } }
isEnabled
identifier_name
GridPrimitive.ts
import { mustBeInteger } from '../checks/mustBeInteger'; import { BeginMode } from '../core/BeginMode'; import { notSupported } from '../i18n/notSupported'; import { readOnly } from '../i18n/readOnly'; import { numPostsForFence } from './numPostsForFence'; import { numVerticesForGrid } from './numVerticesForGrid'; import { Transform } from './Transform'; import { Vertex } from './Vertex'; import { VertexPrimitive } from './VertexPrimitive'; /** * Used for creating a VertexPrimitive for a surface. * The vertices generated have coordinates (u, v) and the traversal creates * counter-clockwise orientation when increasing u is the first direction and * increasing v the second direction. * @hidden */ export class GridPrimitive extends VertexPrimitive { private _uSegments: number; private _uClosed = false; private _vSegments: number; private _vClosed = false; constructor(mode: BeginMode, uSegments: number, vSegments: number) { super(mode, numVerticesForGrid(uSegments, vSegments), 2); this._uSegments = uSegments; this._vSegments = vSegments; } get uSegments(): number { return this._uSegments; } set uSegments(uSegments: number) { mustBeInteger('uSegments', uSegments); throw new Error(readOnly('uSegments').message); } /** * uLength = uSegments + 1 */ get uLength(): number { return numPostsForFence(this._uSegments, this._uClosed); } set uLength(uLength: number) { mustBeInteger('uLength', uLength); throw new Error(readOnly('uLength').message); } get vSegments(): number { return this._vSegments; } set vSegments(vSegments: number) { mustBeInteger('vSegments', vSegments); throw new Error(readOnly('vSegments').message); } /** * vLength = vSegments + 1 */ get vLength(): number
set vLength(vLength: number) { mustBeInteger('vLength', vLength); throw new Error(readOnly('vLength').message); } public vertexTransform(transform: Transform): void { const iLen = this.vertices.length; for (let i = 0; i < iLen; i++) { const vertex = this.vertices[i]; const u = vertex.coords.getComponent(0); const v = vertex.coords.getComponent(1); transform.exec(vertex, u, v, this.uLength, this.vLength); } } /** * Derived classes must override. */ vertex(i: number, j: number): Vertex { mustBeInteger('i', i); mustBeInteger('j', j); throw new Error(notSupported('vertex').message); } }
{ return numPostsForFence(this._vSegments, this._vClosed); }
identifier_body
GridPrimitive.ts
import { mustBeInteger } from '../checks/mustBeInteger'; import { BeginMode } from '../core/BeginMode'; import { notSupported } from '../i18n/notSupported'; import { readOnly } from '../i18n/readOnly'; import { numPostsForFence } from './numPostsForFence'; import { numVerticesForGrid } from './numVerticesForGrid'; import { Transform } from './Transform'; import { Vertex } from './Vertex'; import { VertexPrimitive } from './VertexPrimitive'; /** * Used for creating a VertexPrimitive for a surface. * The vertices generated have coordinates (u, v) and the traversal creates * counter-clockwise orientation when increasing u is the first direction and * increasing v the second direction. * @hidden */ export class GridPrimitive extends VertexPrimitive { private _uSegments: number; private _uClosed = false; private _vSegments: number; private _vClosed = false; constructor(mode: BeginMode, uSegments: number, vSegments: number) { super(mode, numVerticesForGrid(uSegments, vSegments), 2); this._uSegments = uSegments; this._vSegments = vSegments; } get uSegments(): number { return this._uSegments; } set uSegments(uSegments: number) { mustBeInteger('uSegments', uSegments); throw new Error(readOnly('uSegments').message); } /** * uLength = uSegments + 1 */ get uLength(): number { return numPostsForFence(this._uSegments, this._uClosed); } set uLength(uLength: number) { mustBeInteger('uLength', uLength); throw new Error(readOnly('uLength').message); } get vSegments(): number { return this._vSegments; } set vSegments(vSegments: number) { mustBeInteger('vSegments', vSegments); throw new Error(readOnly('vSegments').message); } /** * vLength = vSegments + 1 */ get vLength(): number { return numPostsForFence(this._vSegments, this._vClosed); } set vLength(vLength: number) { mustBeInteger('vLength', vLength); throw new Error(readOnly('vLength').message); } public vertexTransform(transform: Transform): void { const iLen = this.vertices.length; for (let i = 0; i < iLen; i++)
} /** * Derived classes must override. */ vertex(i: number, j: number): Vertex { mustBeInteger('i', i); mustBeInteger('j', j); throw new Error(notSupported('vertex').message); } }
{ const vertex = this.vertices[i]; const u = vertex.coords.getComponent(0); const v = vertex.coords.getComponent(1); transform.exec(vertex, u, v, this.uLength, this.vLength); }
conditional_block
GridPrimitive.ts
import { mustBeInteger } from '../checks/mustBeInteger'; import { BeginMode } from '../core/BeginMode'; import { notSupported } from '../i18n/notSupported'; import { readOnly } from '../i18n/readOnly'; import { numPostsForFence } from './numPostsForFence'; import { numVerticesForGrid } from './numVerticesForGrid'; import { Transform } from './Transform'; import { Vertex } from './Vertex'; import { VertexPrimitive } from './VertexPrimitive'; /** * Used for creating a VertexPrimitive for a surface. * The vertices generated have coordinates (u, v) and the traversal creates * counter-clockwise orientation when increasing u is the first direction and * increasing v the second direction. * @hidden */ export class GridPrimitive extends VertexPrimitive { private _uSegments: number; private _uClosed = false; private _vSegments: number; private _vClosed = false; constructor(mode: BeginMode, uSegments: number, vSegments: number) { super(mode, numVerticesForGrid(uSegments, vSegments), 2); this._uSegments = uSegments; this._vSegments = vSegments; } get uSegments(): number { return this._uSegments; } set uSegments(uSegments: number) { mustBeInteger('uSegments', uSegments); throw new Error(readOnly('uSegments').message); } /** * uLength = uSegments + 1 */ get uLength(): number { return numPostsForFence(this._uSegments, this._uClosed); } set uLength(uLength: number) { mustBeInteger('uLength', uLength); throw new Error(readOnly('uLength').message); } get vSegments(): number { return this._vSegments; } set vSegments(vSegments: number) { mustBeInteger('vSegments', vSegments); throw new Error(readOnly('vSegments').message); } /** * vLength = vSegments + 1 */ get vLength(): number { return numPostsForFence(this._vSegments, this._vClosed); } set vLength(vLength: number) { mustBeInteger('vLength', vLength); throw new Error(readOnly('vLength').message); } public
(transform: Transform): void { const iLen = this.vertices.length; for (let i = 0; i < iLen; i++) { const vertex = this.vertices[i]; const u = vertex.coords.getComponent(0); const v = vertex.coords.getComponent(1); transform.exec(vertex, u, v, this.uLength, this.vLength); } } /** * Derived classes must override. */ vertex(i: number, j: number): Vertex { mustBeInteger('i', i); mustBeInteger('j', j); throw new Error(notSupported('vertex').message); } }
vertexTransform
identifier_name
GridPrimitive.ts
import { mustBeInteger } from '../checks/mustBeInteger'; import { BeginMode } from '../core/BeginMode'; import { notSupported } from '../i18n/notSupported'; import { readOnly } from '../i18n/readOnly'; import { numPostsForFence } from './numPostsForFence'; import { numVerticesForGrid } from './numVerticesForGrid'; import { Transform } from './Transform'; import { Vertex } from './Vertex'; import { VertexPrimitive } from './VertexPrimitive'; /** * Used for creating a VertexPrimitive for a surface. * The vertices generated have coordinates (u, v) and the traversal creates * counter-clockwise orientation when increasing u is the first direction and * increasing v the second direction. * @hidden */ export class GridPrimitive extends VertexPrimitive { private _uSegments: number; private _uClosed = false; private _vSegments: number; private _vClosed = false; constructor(mode: BeginMode, uSegments: number, vSegments: number) { super(mode, numVerticesForGrid(uSegments, vSegments), 2); this._uSegments = uSegments; this._vSegments = vSegments; } get uSegments(): number { return this._uSegments; } set uSegments(uSegments: number) { mustBeInteger('uSegments', uSegments); throw new Error(readOnly('uSegments').message); } /** * uLength = uSegments + 1 */ get uLength(): number { return numPostsForFence(this._uSegments, this._uClosed); } set uLength(uLength: number) { mustBeInteger('uLength', uLength); throw new Error(readOnly('uLength').message); } get vSegments(): number { return this._vSegments; } set vSegments(vSegments: number) { mustBeInteger('vSegments', vSegments); throw new Error(readOnly('vSegments').message); } /** * vLength = vSegments + 1 */ get vLength(): number { return numPostsForFence(this._vSegments, this._vClosed); } set vLength(vLength: number) { mustBeInteger('vLength', vLength); throw new Error(readOnly('vLength').message); } public vertexTransform(transform: Transform): void { const iLen = this.vertices.length; for (let i = 0; i < iLen; i++) { const vertex = this.vertices[i]; const u = vertex.coords.getComponent(0); const v = vertex.coords.getComponent(1); transform.exec(vertex, u, v, this.uLength, this.vLength); } }
* Derived classes must override. */ vertex(i: number, j: number): Vertex { mustBeInteger('i', i); mustBeInteger('j', j); throw new Error(notSupported('vertex').message); } }
/**
random_line_split
cinder_service_check.py
#!/usr/bin/env python # Copyright 2014, Rackspace US, 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. import argparse # Technically maas_common isn't third-party but our own thing but hacking # consideres it third-party from maas_common import get_auth_ref from maas_common import get_keystone_client from maas_common import metric_bool from maas_common import print_output from maas_common import status_err from maas_common import status_ok import requests from requests import exceptions as exc # NOTE(mancdaz): until https://review.openstack.org/#/c/111051/ # lands, there is no way to pass a custom (local) endpoint to # cinderclient. Only way to test local is direct http. :sadface: def check(auth_ref, args): keystone = get_keystone_client(auth_ref) auth_token = keystone.auth_token VOLUME_ENDPOINT = ( '{protocol}://{hostname}:8776/v1/{tenant}'.format( protocol=args.protocol, hostname=args.hostname, tenant=keystone.tenant_id) ) s = requests.Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try:
# We cannot do /os-services?host=X as cinder returns a hostname of # X@lvm for cinder-volume binary r = s.get('%s/os-services' % VOLUME_ENDPOINT, verify=False, timeout=5) except (exc.ConnectionError, exc.HTTPError, exc.Timeout) as e: metric_bool('client_success', False, m_name='maas_cinder') status_err(str(e), m_name='maas_cinder') if not r.ok: metric_bool('client_success', False, m_name='maas_cinder') status_err( 'Could not get response from Cinder API', m_name='cinder' ) else: metric_bool('client_success', True, m_name='maas_cinder') services = r.json()['services'] # We need to match against a host of X and X@lvm (or whatever backend) if args.host: backend = ''.join((args.host, '@')) services = [service for service in services if (service['host'].startswith(backend) or service['host'] == args.host)] if len(services) == 0: status_err( 'No host(s) found in the service list', m_name='maas_cinder' ) status_ok(m_name='maas_cinder') if args.host: for service in services: service_is_up = True name = '%s_status' % service['binary'] if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False if '@' in service['host']: [host, backend] = service['host'].split('@') name = '%s-%s_status' % (service['binary'], backend) metric_bool(name, service_is_up) else: for service in services: service_is_up = True if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False name = '%s_on_host_%s' % (service['binary'], service['host']) metric_bool(name, service_is_up) def main(args): auth_ref = get_auth_ref() check(auth_ref, args) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Check Cinder API against" " local or remote address") parser.add_argument('hostname', type=str, help='Cinder API hostname or IP address') parser.add_argument('--host', type=str, help='Only return metrics for the specified host') parser.add_argument('--telegraf-output', action='store_true', default=False, help='Set the output format to telegraf') parser.add_argument('--protocol', type=str, default='http', help='Protocol to use for cinder client') args = parser.parse_args() with print_output(print_telegraf=args.telegraf_output): main(args)
random_line_split
cinder_service_check.py
#!/usr/bin/env python # Copyright 2014, Rackspace US, 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. import argparse # Technically maas_common isn't third-party but our own thing but hacking # consideres it third-party from maas_common import get_auth_ref from maas_common import get_keystone_client from maas_common import metric_bool from maas_common import print_output from maas_common import status_err from maas_common import status_ok import requests from requests import exceptions as exc # NOTE(mancdaz): until https://review.openstack.org/#/c/111051/ # lands, there is no way to pass a custom (local) endpoint to # cinderclient. Only way to test local is direct http. :sadface: def
(auth_ref, args): keystone = get_keystone_client(auth_ref) auth_token = keystone.auth_token VOLUME_ENDPOINT = ( '{protocol}://{hostname}:8776/v1/{tenant}'.format( protocol=args.protocol, hostname=args.hostname, tenant=keystone.tenant_id) ) s = requests.Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # We cannot do /os-services?host=X as cinder returns a hostname of # X@lvm for cinder-volume binary r = s.get('%s/os-services' % VOLUME_ENDPOINT, verify=False, timeout=5) except (exc.ConnectionError, exc.HTTPError, exc.Timeout) as e: metric_bool('client_success', False, m_name='maas_cinder') status_err(str(e), m_name='maas_cinder') if not r.ok: metric_bool('client_success', False, m_name='maas_cinder') status_err( 'Could not get response from Cinder API', m_name='cinder' ) else: metric_bool('client_success', True, m_name='maas_cinder') services = r.json()['services'] # We need to match against a host of X and X@lvm (or whatever backend) if args.host: backend = ''.join((args.host, '@')) services = [service for service in services if (service['host'].startswith(backend) or service['host'] == args.host)] if len(services) == 0: status_err( 'No host(s) found in the service list', m_name='maas_cinder' ) status_ok(m_name='maas_cinder') if args.host: for service in services: service_is_up = True name = '%s_status' % service['binary'] if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False if '@' in service['host']: [host, backend] = service['host'].split('@') name = '%s-%s_status' % (service['binary'], backend) metric_bool(name, service_is_up) else: for service in services: service_is_up = True if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False name = '%s_on_host_%s' % (service['binary'], service['host']) metric_bool(name, service_is_up) def main(args): auth_ref = get_auth_ref() check(auth_ref, args) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Check Cinder API against" " local or remote address") parser.add_argument('hostname', type=str, help='Cinder API hostname or IP address') parser.add_argument('--host', type=str, help='Only return metrics for the specified host') parser.add_argument('--telegraf-output', action='store_true', default=False, help='Set the output format to telegraf') parser.add_argument('--protocol', type=str, default='http', help='Protocol to use for cinder client') args = parser.parse_args() with print_output(print_telegraf=args.telegraf_output): main(args)
check
identifier_name
cinder_service_check.py
#!/usr/bin/env python # Copyright 2014, Rackspace US, 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. import argparse # Technically maas_common isn't third-party but our own thing but hacking # consideres it third-party from maas_common import get_auth_ref from maas_common import get_keystone_client from maas_common import metric_bool from maas_common import print_output from maas_common import status_err from maas_common import status_ok import requests from requests import exceptions as exc # NOTE(mancdaz): until https://review.openstack.org/#/c/111051/ # lands, there is no way to pass a custom (local) endpoint to # cinderclient. Only way to test local is direct http. :sadface: def check(auth_ref, args):
def main(args): auth_ref = get_auth_ref() check(auth_ref, args) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Check Cinder API against" " local or remote address") parser.add_argument('hostname', type=str, help='Cinder API hostname or IP address') parser.add_argument('--host', type=str, help='Only return metrics for the specified host') parser.add_argument('--telegraf-output', action='store_true', default=False, help='Set the output format to telegraf') parser.add_argument('--protocol', type=str, default='http', help='Protocol to use for cinder client') args = parser.parse_args() with print_output(print_telegraf=args.telegraf_output): main(args)
keystone = get_keystone_client(auth_ref) auth_token = keystone.auth_token VOLUME_ENDPOINT = ( '{protocol}://{hostname}:8776/v1/{tenant}'.format( protocol=args.protocol, hostname=args.hostname, tenant=keystone.tenant_id) ) s = requests.Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # We cannot do /os-services?host=X as cinder returns a hostname of # X@lvm for cinder-volume binary r = s.get('%s/os-services' % VOLUME_ENDPOINT, verify=False, timeout=5) except (exc.ConnectionError, exc.HTTPError, exc.Timeout) as e: metric_bool('client_success', False, m_name='maas_cinder') status_err(str(e), m_name='maas_cinder') if not r.ok: metric_bool('client_success', False, m_name='maas_cinder') status_err( 'Could not get response from Cinder API', m_name='cinder' ) else: metric_bool('client_success', True, m_name='maas_cinder') services = r.json()['services'] # We need to match against a host of X and X@lvm (or whatever backend) if args.host: backend = ''.join((args.host, '@')) services = [service for service in services if (service['host'].startswith(backend) or service['host'] == args.host)] if len(services) == 0: status_err( 'No host(s) found in the service list', m_name='maas_cinder' ) status_ok(m_name='maas_cinder') if args.host: for service in services: service_is_up = True name = '%s_status' % service['binary'] if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False if '@' in service['host']: [host, backend] = service['host'].split('@') name = '%s-%s_status' % (service['binary'], backend) metric_bool(name, service_is_up) else: for service in services: service_is_up = True if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False name = '%s_on_host_%s' % (service['binary'], service['host']) metric_bool(name, service_is_up)
identifier_body
cinder_service_check.py
#!/usr/bin/env python # Copyright 2014, Rackspace US, 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. import argparse # Technically maas_common isn't third-party but our own thing but hacking # consideres it third-party from maas_common import get_auth_ref from maas_common import get_keystone_client from maas_common import metric_bool from maas_common import print_output from maas_common import status_err from maas_common import status_ok import requests from requests import exceptions as exc # NOTE(mancdaz): until https://review.openstack.org/#/c/111051/ # lands, there is no way to pass a custom (local) endpoint to # cinderclient. Only way to test local is direct http. :sadface: def check(auth_ref, args): keystone = get_keystone_client(auth_ref) auth_token = keystone.auth_token VOLUME_ENDPOINT = ( '{protocol}://{hostname}:8776/v1/{tenant}'.format( protocol=args.protocol, hostname=args.hostname, tenant=keystone.tenant_id) ) s = requests.Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # We cannot do /os-services?host=X as cinder returns a hostname of # X@lvm for cinder-volume binary r = s.get('%s/os-services' % VOLUME_ENDPOINT, verify=False, timeout=5) except (exc.ConnectionError, exc.HTTPError, exc.Timeout) as e: metric_bool('client_success', False, m_name='maas_cinder') status_err(str(e), m_name='maas_cinder') if not r.ok: metric_bool('client_success', False, m_name='maas_cinder') status_err( 'Could not get response from Cinder API', m_name='cinder' ) else: metric_bool('client_success', True, m_name='maas_cinder') services = r.json()['services'] # We need to match against a host of X and X@lvm (or whatever backend) if args.host: backend = ''.join((args.host, '@')) services = [service for service in services if (service['host'].startswith(backend) or service['host'] == args.host)] if len(services) == 0: status_err( 'No host(s) found in the service list', m_name='maas_cinder' ) status_ok(m_name='maas_cinder') if args.host: for service in services: service_is_up = True name = '%s_status' % service['binary'] if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False if '@' in service['host']:
metric_bool(name, service_is_up) else: for service in services: service_is_up = True if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False name = '%s_on_host_%s' % (service['binary'], service['host']) metric_bool(name, service_is_up) def main(args): auth_ref = get_auth_ref() check(auth_ref, args) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Check Cinder API against" " local or remote address") parser.add_argument('hostname', type=str, help='Cinder API hostname or IP address') parser.add_argument('--host', type=str, help='Only return metrics for the specified host') parser.add_argument('--telegraf-output', action='store_true', default=False, help='Set the output format to telegraf') parser.add_argument('--protocol', type=str, default='http', help='Protocol to use for cinder client') args = parser.parse_args() with print_output(print_telegraf=args.telegraf_output): main(args)
[host, backend] = service['host'].split('@') name = '%s-%s_status' % (service['binary'], backend)
conditional_block
lib.rs
#![crate_name = "r6"] //! r6.rs is an attempt to implement R6RS Scheme in Rust language #![feature(slice_patterns)] #![feature(io)] // This line should be at the top of the extern link list, // because some weird compiler bug lets log imported from rustc, not crates.io log #[macro_use] extern crate log; #[macro_use] extern crate enum_primitive; extern crate phf; extern crate regex; extern crate num; extern crate unicode_categories; extern crate immutable_map; #[cfg(test)] macro_rules! list{ ($($x:expr),*) => ( vec![$($x),*].into_iter().collect() ) } #[cfg(test)] macro_rules! sym{ ($e:expr) => ( Datum::Sym(Cow::Borrowed($e)) ) } #[cfg(test)] macro_rules! num{ ($e:expr) => ( Datum::Num(Number::new_int($e, 0)) ) } /// Error values returned from parser, compiler or runtime pub mod error; /// Basic datum types pub mod datum; /// Implement eqv? primitive pub mod eqv; pub mod parser; pub mod lexer; /// Virtual machine running the bytecode pub mod runtime; /// Primitive functions pub mod primitive; /// Compiles datum into a bytecode pub mod compiler; /// R6RS `base` library pub mod base; /// Real part of the numerical tower pub mod real; /// Numerical tower pub mod number; /// Cast Datum into rust types
pub mod cast; /// Macro implementations pub mod syntax;
random_line_split
sentiment-satisfied-outlined.js
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("circle", {
cy: "9.5", r: "1.5" }), h("circle", { cx: "8.5", cy: "9.5", r: "1.5" }), h("path", { d: "M12 16c-1.48 0-2.75-.81-3.45-2H6.88c.8 2.05 2.79 3.5 5.12 3.5s4.32-1.45 5.12-3.5h-1.67c-.7 1.19-1.97 2-3.45 2zm-.01-14C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z" })), 'SentimentSatisfiedOutlined');
cx: "15.5",
random_line_split
royal-american.js
var cheerio = require('cheerio') , request = require('request') , url = 'http://theroyalamerican.com/schedule/' , shows = [] , months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] function royalamerican (done) { request(url, function(err, response, body) { var $ = cheerio.load(body) $('.gig').each(function(i, elem) { var price, time var $$ = cheerio.load(elem) var title = $$('.title').text().trim() if($$('.with').text().trim()) title += $$('.with').text().trim() var date = $$('.date').text().trim() var timePrice = $$('.details').text().trim().split('Show: ').join('').split('|') if(timePrice[0]) time = timePrice[0].trim() if(timePrice[1] && timePrice[1].trim().slice(0,1) === '$') price = timePrice[1].split('Cover')[0].trim() else price = '' var year = $('#gigs_left').children().attr('name') date = normalizeDate(date, year) var show = { venue: 'The Royal American', venueUrl: 'http://theroyalamerican.com/', title: title, time: time.slice(0,5).trim(), price: price,
} shows.push(show) }) done(null, shows) }) } module.exports = royalamerican function normalizeDate(date, year) { var newDate = [] date = date.split(' ') var day = date.pop() if(day.length < 2) day = '0'+day var month = date.pop() month = (months.indexOf(month)+1).toString() if(month.length < 2) month = '0'+month year = year.split('_')[1] newDate.push(year) newDate.push(month) newDate.push(day) return newDate.join('-') }
url: $$('.details').first().find('a').attr('href'), date: date
random_line_split
royal-american.js
var cheerio = require('cheerio') , request = require('request') , url = 'http://theroyalamerican.com/schedule/' , shows = [] , months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] function royalamerican (done)
module.exports = royalamerican function normalizeDate(date, year) { var newDate = [] date = date.split(' ') var day = date.pop() if(day.length < 2) day = '0'+day var month = date.pop() month = (months.indexOf(month)+1).toString() if(month.length < 2) month = '0'+month year = year.split('_')[1] newDate.push(year) newDate.push(month) newDate.push(day) return newDate.join('-') }
{ request(url, function(err, response, body) { var $ = cheerio.load(body) $('.gig').each(function(i, elem) { var price, time var $$ = cheerio.load(elem) var title = $$('.title').text().trim() if($$('.with').text().trim()) title += $$('.with').text().trim() var date = $$('.date').text().trim() var timePrice = $$('.details').text().trim().split('Show: ').join('').split('|') if(timePrice[0]) time = timePrice[0].trim() if(timePrice[1] && timePrice[1].trim().slice(0,1) === '$') price = timePrice[1].split('Cover')[0].trim() else price = '' var year = $('#gigs_left').children().attr('name') date = normalizeDate(date, year) var show = { venue: 'The Royal American', venueUrl: 'http://theroyalamerican.com/', title: title, time: time.slice(0,5).trim(), price: price, url: $$('.details').first().find('a').attr('href'), date: date } shows.push(show) }) done(null, shows) }) }
identifier_body
royal-american.js
var cheerio = require('cheerio') , request = require('request') , url = 'http://theroyalamerican.com/schedule/' , shows = [] , months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] function royalamerican (done) { request(url, function(err, response, body) { var $ = cheerio.load(body) $('.gig').each(function(i, elem) { var price, time var $$ = cheerio.load(elem) var title = $$('.title').text().trim() if($$('.with').text().trim()) title += $$('.with').text().trim() var date = $$('.date').text().trim() var timePrice = $$('.details').text().trim().split('Show: ').join('').split('|') if(timePrice[0]) time = timePrice[0].trim() if(timePrice[1] && timePrice[1].trim().slice(0,1) === '$') price = timePrice[1].split('Cover')[0].trim() else price = '' var year = $('#gigs_left').children().attr('name') date = normalizeDate(date, year) var show = { venue: 'The Royal American', venueUrl: 'http://theroyalamerican.com/', title: title, time: time.slice(0,5).trim(), price: price, url: $$('.details').first().find('a').attr('href'), date: date } shows.push(show) }) done(null, shows) }) } module.exports = royalamerican function
(date, year) { var newDate = [] date = date.split(' ') var day = date.pop() if(day.length < 2) day = '0'+day var month = date.pop() month = (months.indexOf(month)+1).toString() if(month.length < 2) month = '0'+month year = year.split('_')[1] newDate.push(year) newDate.push(month) newDate.push(day) return newDate.join('-') }
normalizeDate
identifier_name
index.debug.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["VueBootfy"] = factory(); else root["VueBootfy"] = factory(); })(this, (function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId)
/******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 389); /******/ }) /************************************************************************/ /******/ ({ /***/ 389: /***/ (function(module, exports, __webpack_require__) { (function webpackMissingModule() { throw new Error("Cannot find module \"./src/components/vCollapse\""); }()); /***/ }) /******/ }); }));
{ /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ }
identifier_body
index.debug.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["VueBootfy"] = factory(); else root["VueBootfy"] = factory(); })(this, (function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function
(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 389); /******/ }) /************************************************************************/ /******/ ({ /***/ 389: /***/ (function(module, exports, __webpack_require__) { (function webpackMissingModule() { throw new Error("Cannot find module \"./src/components/vCollapse\""); }()); /***/ }) /******/ }); }));
__webpack_require__
identifier_name
index.debug.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["VueBootfy"] = factory(); else root["VueBootfy"] = factory(); })(this, (function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true,
/******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 389); /******/ }) /************************************************************************/ /******/ ({ /***/ 389: /***/ (function(module, exports, __webpack_require__) { (function webpackMissingModule() { throw new Error("Cannot find module \"./src/components/vCollapse\""); }()); /***/ }) /******/ }); }));
/******/ get: getter /******/ }); /******/ } /******/ }; /******/
random_line_split
errors.py
""" The MIT License (MIT) Copyright (c) 2014 Chris Wimbrow 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. """
random_line_split
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub use self::statement_cache::{MaybeCached, StatementCache, StatementCacheKey}; pub use self::transaction_manager::{AnsiTransactionManager, TransactionManager}; /// Perform simple operations on a backend. /// /// You should likely use [`Connection`] instead. pub trait SimpleConnection { /// Execute multiple SQL statements within the same string. /// /// This function is used to execute migrations, /// which may contain more than one SQL statement. fn batch_execute(&self, query: &str) -> QueryResult<()>; } /// A connection to a database pub trait Connection: SimpleConnection + Send { /// The backend this type connects to type Backend: Backend; /// Establishes a new connection to the database /// /// The argument to this method and the method's behavior varies by backend. /// See the documentation for that backend's connection class /// for details about what it accepts and how it behaves. fn establish(database_url: &str) -> ConnectionResult<Self> where Self: Sized; /// Executes the given function inside of a database transaction /// /// If there is already an open transaction, /// savepoints will be used instead. /// /// If the transaction fails to commit due to a `SerializationFailure` or a /// `ReadOnlyTransaction` a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. In the second case the connection should be considered broken /// as it contains a uncommitted unabortable open transaction. /// /// If a nested transaction fails to release the corresponding savepoint /// a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// })?; /// /// conn.transaction::<(), _, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Pascal")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby", "Pascal"], all_names); /// /// // If we want to roll back the transaction, but don't have an /// // actual error to return, we can return `RollbackTransaction`. /// Err(Error::RollbackTransaction) /// }); /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// # Ok(()) /// # } /// ``` fn transaction<T, E, F>(&self, f: F) -> Result<T, E> where Self: Sized, F: FnOnce() -> Result<T, E>, E: From<Error>, { let transaction_manager = self.transaction_manager(); transaction_manager.begin_transaction(self)?; match f() { Ok(value) => { transaction_manager.commit_transaction(self)?; Ok(value) } Err(e) => { transaction_manager.rollback_transaction(self)?; Err(e) } } } /// Creates a transaction that will never be committed. This is useful for /// tests. Panics if called while inside of a transaction. fn begin_test_transaction(&self) -> QueryResult<()> where Self: Sized, { let transaction_manager = self.transaction_manager(); assert_eq!(transaction_manager.get_transaction_depth(), 0); transaction_manager.begin_transaction(self) } /// Executes the given function inside a transaction, but does not commit /// it. Panics if the given function returns an error. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.test_transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?;
/// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// }); /// /// // Even though we returned `Ok`, the transaction wasn't committed. /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess"], all_names); /// # Ok(()) /// # } /// ``` fn test_transaction<T, E, F>(&self, f: F) -> T where F: FnOnce() -> Result<T, E>, E: Debug, Self: Sized, { let mut user_result = None; let _ = self.transaction::<(), _, _>(|| { user_result = f().ok(); Err(Error::RollbackTransaction) }); user_result.expect("Transaction did not succeed") } #[doc(hidden)] fn execute(&self, query: &str) -> QueryResult<usize>; #[doc(hidden)] fn load<T, U>(&self, source: T) -> QueryResult<Vec<U>> where Self: Sized, T: AsQuery, T::Query: QueryFragment<Self::Backend> + QueryId, U: FromSqlRow<T::SqlType, Self::Backend>, Self::Backend: QueryMetadata<T::SqlType>; #[doc(hidden)] fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize> where Self: Sized, T: QueryFragment<Self::Backend> + QueryId; #[doc(hidden)] fn transaction_manager(&self) -> &dyn TransactionManager<Self> where Self: Sized; } /// A variant of the [`Connection`](trait.Connection.html) trait that is /// usable with dynamic dispatch /// /// If you are looking for a way to use pass database connections /// for different database backends around in your application /// this trait won't help you much. Normally you should only /// need to use this trait if you are interacting with a connection /// passed to a [`Migration`](../migration/trait.Migration.html) pub trait BoxableConnection<DB: Backend>: Connection<Backend = DB> + std::any::Any { #[doc(hidden)] fn as_any(&self) -> &dyn std::any::Any; } impl<C> BoxableConnection<C::Backend> for C where C: Connection + std::any::Any, { fn as_any(&self) -> &dyn std::any::Any { self } } impl<DB: Backend> dyn BoxableConnection<DB> { /// Downcast the current connection to a specific connection /// type. /// /// This will return `None` if the underlying /// connection does not match the corresponding /// type, otherwise a reference to the underlying connection is returned pub fn downcast_ref<T>(&self) -> Option<&T> where T: Connection<Backend = DB> + 'static, { self.as_any().downcast_ref::<T>() } /// Check if the current connection is /// a specific connection type pub fn is<T>(&self) -> bool where T: Connection<Backend = DB> + 'static, { self.as_any().is::<T>() } }
/// /// let all_names = users.select(name).load::<String>(&conn)?;
random_line_split
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub use self::statement_cache::{MaybeCached, StatementCache, StatementCacheKey}; pub use self::transaction_manager::{AnsiTransactionManager, TransactionManager}; /// Perform simple operations on a backend. /// /// You should likely use [`Connection`] instead. pub trait SimpleConnection { /// Execute multiple SQL statements within the same string. /// /// This function is used to execute migrations, /// which may contain more than one SQL statement. fn batch_execute(&self, query: &str) -> QueryResult<()>; } /// A connection to a database pub trait Connection: SimpleConnection + Send { /// The backend this type connects to type Backend: Backend; /// Establishes a new connection to the database /// /// The argument to this method and the method's behavior varies by backend. /// See the documentation for that backend's connection class /// for details about what it accepts and how it behaves. fn establish(database_url: &str) -> ConnectionResult<Self> where Self: Sized; /// Executes the given function inside of a database transaction /// /// If there is already an open transaction, /// savepoints will be used instead. /// /// If the transaction fails to commit due to a `SerializationFailure` or a /// `ReadOnlyTransaction` a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. In the second case the connection should be considered broken /// as it contains a uncommitted unabortable open transaction. /// /// If a nested transaction fails to release the corresponding savepoint /// a rollback will be attempted. If the rollback succeeds, /// the original error will be returned, otherwise the error generated by the rollback /// will be returned. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// })?; /// /// conn.transaction::<(), _, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Pascal")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby", "Pascal"], all_names); /// /// // If we want to roll back the transaction, but don't have an /// // actual error to return, we can return `RollbackTransaction`. /// Err(Error::RollbackTransaction) /// }); /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// # Ok(()) /// # } /// ``` fn transaction<T, E, F>(&self, f: F) -> Result<T, E> where Self: Sized, F: FnOnce() -> Result<T, E>, E: From<Error>, { let transaction_manager = self.transaction_manager(); transaction_manager.begin_transaction(self)?; match f() { Ok(value) => { transaction_manager.commit_transaction(self)?; Ok(value) } Err(e) =>
} } /// Creates a transaction that will never be committed. This is useful for /// tests. Panics if called while inside of a transaction. fn begin_test_transaction(&self) -> QueryResult<()> where Self: Sized, { let transaction_manager = self.transaction_manager(); assert_eq!(transaction_manager.get_transaction_depth(), 0); transaction_manager.begin_transaction(self) } /// Executes the given function inside a transaction, but does not commit /// it. Panics if the given function returns an error. /// /// # Example /// /// ```rust /// # include!("../doctest_setup.rs"); /// use diesel::result::Error; /// /// # fn main() { /// # run_test().unwrap(); /// # } /// # /// # fn run_test() -> QueryResult<()> { /// # use schema::users::dsl::*; /// # let conn = establish_connection(); /// conn.test_transaction::<_, Error, _>(|| { /// diesel::insert_into(users) /// .values(name.eq("Ruby")) /// .execute(&conn)?; /// /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// }); /// /// // Even though we returned `Ok`, the transaction wasn't committed. /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess"], all_names); /// # Ok(()) /// # } /// ``` fn test_transaction<T, E, F>(&self, f: F) -> T where F: FnOnce() -> Result<T, E>, E: Debug, Self: Sized, { let mut user_result = None; let _ = self.transaction::<(), _, _>(|| { user_result = f().ok(); Err(Error::RollbackTransaction) }); user_result.expect("Transaction did not succeed") } #[doc(hidden)] fn execute(&self, query: &str) -> QueryResult<usize>; #[doc(hidden)] fn load<T, U>(&self, source: T) -> QueryResult<Vec<U>> where Self: Sized, T: AsQuery, T::Query: QueryFragment<Self::Backend> + QueryId, U: FromSqlRow<T::SqlType, Self::Backend>, Self::Backend: QueryMetadata<T::SqlType>; #[doc(hidden)] fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize> where Self: Sized, T: QueryFragment<Self::Backend> + QueryId; #[doc(hidden)] fn transaction_manager(&self) -> &dyn TransactionManager<Self> where Self: Sized; } /// A variant of the [`Connection`](trait.Connection.html) trait that is /// usable with dynamic dispatch /// /// If you are looking for a way to use pass database connections /// for different database backends around in your application /// this trait won't help you much. Normally you should only /// need to use this trait if you are interacting with a connection /// passed to a [`Migration`](../migration/trait.Migration.html) pub trait BoxableConnection<DB: Backend>: Connection<Backend = DB> + std::any::Any { #[doc(hidden)] fn as_any(&self) -> &dyn std::any::Any; } impl<C> BoxableConnection<C::Backend> for C where C: Connection + std::any::Any, { fn as_any(&self) -> &dyn std::any::Any { self } } impl<DB: Backend> dyn BoxableConnection<DB> { /// Downcast the current connection to a specific connection /// type. /// /// This will return `None` if the underlying /// connection does not match the corresponding /// type, otherwise a reference to the underlying connection is returned pub fn downcast_ref<T>(&self) -> Option<&T> where T: Connection<Backend = DB> + 'static, { self.as_any().downcast_ref::<T>() } /// Check if the current connection is /// a specific connection type pub fn is<T>(&self) -> bool where T: Connection<Backend = DB> + 'static, { self.as_any().is::<T>() } }
{ transaction_manager.rollback_transaction(self)?; Err(e) }
conditional_block