prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>wifi_out.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import bpy
from bpy.props import StringProperty, EnumProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode
# Warning, changing this node without modifying the update system might break functionlaity
# bl_idname and var_name is used by the update system
class WifiOutNode(bpy.types.Node, SverchCustomTreeNode):
''' WifiOutNode '''
bl_idname = 'WifiOutNode'
bl_label = 'Wifi out'
bl_icon = 'OUTLINER_OB_EMPTY'
var_name = StringProperty(name='var_name',
default='')
def avail_var_name(self, context):
ng = self.id_data
out = [(n.var_name, n.var_name, "") for n in ng.nodes
if n.bl_idname == 'WifiInNode']
if out:
out.sort(key=lambda n: n[0])
return out
var_names = EnumProperty(items=avail_var_name, name="var names")
def set_var_name(self):
self.var_name = self.var_names
ng = self.id_data
wifi_dict = {node.var_name: node
for node in ng.nodes
if node.bl_idname == 'WifiInNode'}
self.outputs.clear()
if self.var_name in wifi_dict:
self.outputs.clear()
node = wifi_dict[self.var_name]
self.update()
else:
self.outputs.clear()
def reset_var_name(self):
self.var_name = ""
self.outputs.clear()
def draw_buttons(self, context, layout):
op_name = 'node.sverchok_text_callback'
if self.var_name:
row = layout.row()
row.label(text="Var:")
row.label(text=self.var_name)
op = layout.operator(op_name, text='Unlink')
op.fn_name = "reset_var_name"
else:
layout.prop(self, "var_names")
op = layout.operator(op_name, text='Link')
op.fn_name = "set_var_name"
def sv_init(self, context):
pass
def gen_var_name(self):
#from socket
if self.outputs:
n = self.outputs[0].name.rstrip("[0]")
self.var_name = n
def update(self):
if not self.var_name and self.outputs:
self.gen_var_name()
ng = self.id_data
wifi_dict = {node.var_name: node
for name, node in ng.nodes.items()
if node.bl_idname == 'WifiInNode'}
node = wifi_dict.get(self.var_name)
if node:
inputs = node.inputs
outputs = self.outputs
# match socket type
for idx, i_o in enumerate(zip(inputs, outputs)):
i_socket, o_socket = i_o
if i_socket.links:
f_socket = i_socket.links[0].from_socket
if f_socket.bl_idname != o_socket.bl_idname:
outputs.remove(o_socket)
outputs.new(f_socket.bl_idname, i_socket.name)
outputs.move(len(self.outputs)-1, idx)
# adjust number of inputs
while len(outputs) != len(inputs)-1:
if len(outputs) > len(inputs)-1:
outputs.remove(outputs[-1])
else:
n = len(outputs)
socket = inputs[n]
if socket.links:
s_type = socket.links[0].from_socket.bl_idname
else:
s_type = 'StringsSocket'
s_name = socket.name
outputs.new(s_type, s_name)
def process(self):
ng = self.id_data
wifi_dict = {node.var_name: node
for name, node in ng.nodes.items()
if node.bl_idname == 'WifiInNode'}
node = wifi_dict.get(self.var_name)
# transfer data
for in_socket, out_socket in zip(node.inputs, self.outputs):
if in_socket.is_linked and out_socket.is_linked:
data = in_socket.sv_get(deepcopy=False)
out_socket.sv_set(data)<|fim▁hole|> bpy.utils.register_class(WifiOutNode)
def unregister():
bpy.utils.unregister_class(WifiOutNode)<|fim▁end|> |
def register(): |
<|file_name|>scopeperm.go<|end_file_name|><|fim▁begin|>// Copyright 2015, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// 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.
package config
import "github.com/corestoreio/csfw/utils"
// ScopePerm is a bit set and used for permissions, ScopeGroup is not a part of this bit set.
// Type ScopeGroup is a subpart of ScopePerm
type ScopePerm uint64
// ScopePermAll convenient helper variable contains all scope permission levels
var ScopePermAll = ScopePerm(1<<ScopeDefaultID | 1<<ScopeWebsiteID | 1<<ScopeStoreID)
// NewScopePerm returns a new permission container
func NewScopePerm(scopes ...ScopeGroup) ScopePerm {
p := ScopePerm(0)
p.Set(scopes...)
return p
}
// All applies all scopes
func (bits *ScopePerm) All() ScopePerm {
bits.Set(ScopeDefaultID, ScopeWebsiteID, ScopeStoreID)
return *bits
}
// Set takes a variadic amount of ScopeGroup to set them to ScopeBits<|fim▁hole|> return *bits
}
// Has checks if ScopeGroup is in ScopeBits
func (bits ScopePerm) Has(s ScopeGroup) bool {
var one ScopeGroup = 1 // ^^
return (bits & ScopePerm(one<<s)) != 0
}
// Human readable representation of the permissions
func (bits ScopePerm) Human() utils.StringSlice {
var ret utils.StringSlice
var i uint
for i = 0; i < 64; i++ {
bit := ((bits & (1 << i)) != 0)
if bit {
ret.Append(ScopeGroup(i).String())
}
}
return ret
}
// MarshalJSON implements marshaling into an array or null if no bits are set. @todo UnMarshal
func (bits ScopePerm) MarshalJSON() ([]byte, error) {
if bits == 0 {
return []byte("null"), nil
}
return []byte(`["` + bits.Human().Join(`","`) + `"]`), nil
}<|fim▁end|> | func (bits *ScopePerm) Set(scopes ...ScopeGroup) ScopePerm {
for _, i := range scopes {
*bits = *bits | (1 << i) // (1 << power = 2^power)
} |
<|file_name|>0008_auto_20150630_1859.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
<|fim▁hole|> ]
operations = [
migrations.AddField(
model_name='schedule',
name='logic_delete',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='flight',
name='pub_date',
field=models.DateTimeField(default=datetime.datetime(2015, 6, 30, 18, 59, 57, 180047), null=True, verbose_name=b'date published'),
),
migrations.AlterField(
model_name='schedule',
name='pub_date',
field=models.DateTimeField(default=datetime.datetime(2015, 6, 30, 18, 59, 57, 180807), null=True, verbose_name=b'date published'),
),
]<|fim▁end|> | class Migration(migrations.Migration):
dependencies = [
('flyerapp', '0007_auto_20150629_1135'), |
<|file_name|>ColladaLoader.js<|end_file_name|><|fim▁begin|>/**
* @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
*/
THREE.ColladaLoader = function () {
var COLLADA = null;
var scene = null;
var daeScene;
var readyCallbackFunc = null;
var sources = {};
var images = {};
var animations = {};
var controllers = {};
var geometries = {};
var materials = {};
var effects = {};
var cameras = {};
var lights = {};
var animData;
var visualScenes;
var baseUrl;
var morphs;
var skins;
var flip_uv = true;
var preferredShading = THREE.SmoothShading;
var options = {
// Force Geometry to always be centered at the local origin of the
// containing Mesh.
centerGeometry: false,
// Axis conversion is done for geometries, animations, and controllers.
// If we ever pull cameras or lights out of the COLLADA file, they'll
// need extra work.
convertUpAxis: false,
subdivideFaces: true,
upAxis: 'Y',
// For reflective or refractive materials we'll use this cubemap
defaultEnvMap: null
};
var colladaUnit = 1.0;
var colladaUp = 'Y';
var upConversion = null;
function load ( url, readyCallback, progressCallback ) {
var length = 0;
if ( document.implementation && document.implementation.createDocument ) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if( request.readyState == 4 ) {
if( request.status == 0 || request.status == 200 ) {
if ( request.responseXML ) {
readyCallbackFunc = readyCallback;
parse( request.responseXML, undefined, url );
} else if ( request.responseText ) {
readyCallbackFunc = readyCallback;
var xmlParser = new DOMParser();
var responseXML = xmlParser.parseFromString( request.responseText, "application/xml" );
parse( responseXML, undefined, url );
} else {
console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
}
}
} else if ( request.readyState == 3 ) {
if ( progressCallback ) {
if ( length == 0 ) {
length = request.getResponseHeader( "Content-Length" );
}
progressCallback( { total: length, loaded: request.responseText.length } );
}
}
}
request.open( "GET", url, true );
request.send( null );
} else {
alert( "Don't know how to parse XML!" );
}
};
function parse( doc, callBack, url ) {
COLLADA = doc;
callBack = callBack || readyCallbackFunc;
if ( url !== undefined ) {
var parts = url.split( '/' );
parts.pop();
baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
}
parseAsset();
setUpConversion();
images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
materials = parseLib( "//dae:library_materials/dae:material", Material, "material" );
effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
lights = parseLib( ".//dae:library_lights/dae:light", Light, "light" );
controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
morphs = [];
skins = [];
daeScene = parseScene();
scene = new THREE.Object3D();
for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
}
// unit conversion
scene.scale.multiplyScalar( colladaUnit );
createAnimations();
var result = {
scene: scene,
morphs: morphs,
skins: skins,
animations: animData,
dae: {
images: images,
materials: materials,
cameras: cameras,
lights: lights,
effects: effects,
geometries: geometries,
controllers: controllers,
animations: animations,
visualScenes: visualScenes,
scene: daeScene
}
};
if ( callBack ) {
callBack( result );
}
return result;
};
function setPreferredShading ( shading ) {
preferredShading = shading;
};
function parseAsset () {
var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
var element = elements.iterateNext();
if ( element && element.childNodes ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'unit':
var meter = child.getAttribute( 'meter' );
if ( meter ) {
colladaUnit = parseFloat( meter );
}
break;
case 'up_axis':
colladaUp = child.textContent.charAt(0);
break;
}
}
}
};
function parseLib ( q, classSpec, prefix ) {
var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
var lib = {};
var element = elements.iterateNext();
var i = 0;
while ( element ) {
var daeElement = ( new classSpec() ).parse( element );
if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
lib[ daeElement.id ] = daeElement;
element = elements.iterateNext();
}
return lib;
};
function parseScene() {
var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
if ( sceneElement ) {
var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
} else {
return null;
}
};
function createAnimations() {
animData = [];
// fill in the keys
recurseHierarchy( scene );
};
function recurseHierarchy( node ) {
var n = daeScene.getChildById( node.name, true ),
newData = null;
if ( n && n.keys ) {
newData = {
fps: 60,
hierarchy: [ {
node: n,
keys: n.keys,
sids: n.sids
} ],
node: node,
name: 'animation_' + node.name,
length: 0
};
animData.push(newData);
for ( var i = 0, il = n.keys.length; i < il; i++ ) {
newData.length = Math.max( newData.length, n.keys[i].time );
}
} else {
newData = {
hierarchy: [ {
keys: [],
sids: []
} ]
}
}
for ( var i = 0, il = node.children.length; i < il; i++ ) {
var d = recurseHierarchy( node.children[i] );
for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
newData.hierarchy.push( {
keys: [],
sids: []
} );
}
}
return newData;
};
function calcAnimationBounds () {
var start = 1000000;
var end = -start;
var frames = 0;
for ( var id in animations ) {
var animation = animations[ id ];
for ( var i = 0; i < animation.sampler.length; i ++ ) {
var sampler = animation.sampler[ i ];
sampler.create();
start = Math.min( start, sampler.startTime );
end = Math.max( end, sampler.endTime );
frames = Math.max( frames, sampler.input.length );
}
}
return { start:start, end:end, frames:frames };
};
function createMorph ( geometry, ctrl ) {
var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
if ( !morphCtrl || !morphCtrl.morph ) {
console.log("could not find morph controller!");
return;
}
var morph = morphCtrl.morph;
for ( var i = 0; i < morph.targets.length; i ++ ) {
var target_id = morph.targets[ i ];
var daeGeometry = geometries[ target_id ];
if ( !daeGeometry.mesh ||
!daeGeometry.mesh.primitives ||
!daeGeometry.mesh.primitives.length ) {
continue;
}
var target = daeGeometry.mesh.primitives[ 0 ].geometry;
if ( target.vertices.length === geometry.vertices.length ) {
geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
}
}
geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
};
function createSkin ( geometry, ctrl, applyBindShape ) {
var skinCtrl = controllers[ ctrl.url ];
if ( !skinCtrl || !skinCtrl.skin ) {
console.log( "could not find skin controller!" );
return;
}
if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
console.log( "could not find the skeleton for the skin!" );
return;
}
var skin = skinCtrl.skin;
var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
var hierarchy = [];
applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
var bones = [];
geometry.skinWeights = [];
geometry.skinIndices = [];
//createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
//createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
/*
geometry.animation = {
name: 'take_001',
fps: 30,
length: 2,
JIT: true,
hierarchy: hierarchy
};
*/
if ( applyBindShape ) {
for ( var i = 0; i < geometry.vertices.length; i ++ ) {
geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
}
}
};
function setupSkeleton ( node, bones, frame, parent ) {
node.world = node.world || new THREE.Matrix4();
node.world.copy( node.matrix );
if ( node.channels && node.channels.length ) {
var channel = node.channels[ 0 ];
var m = channel.sampler.output[ frame ];
if ( m instanceof THREE.Matrix4 ) {
node.world.copy( m );
}
}
if ( parent ) {
node.world.multiplyMatrices( parent, node.world );
}
bones.push( node );
for ( var i = 0; i < node.nodes.length; i ++ ) {
setupSkeleton( node.nodes[ i ], bones, frame, node.world );
}
};
function setupSkinningMatrices ( bones, skin ) {
// FIXME: this is dumb...
for ( var i = 0; i < bones.length; i ++ ) {
var bone = bones[ i ];
var found = -1;
if ( bone.type != 'JOINT' ) continue;
for ( var j = 0; j < skin.joints.length; j ++ ) {
if ( bone.sid == skin.joints[ j ] ) {
found = j;
break;
}
}
if ( found >= 0 ) {
var inv = skin.invBindMatrices[ found ];
bone.invBindMatrix = inv;
bone.skinningMatrix = new THREE.Matrix4();
bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
bone.weights = [];
for ( var j = 0; j < skin.weights.length; j ++ ) {
for (var k = 0; k < skin.weights[ j ].length; k ++) {
var w = skin.weights[ j ][ k ];
if ( w.joint == found ) {
bone.weights.push( w );
}
}
}
} else {
throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
}
}
};
function applySkin ( geometry, instanceCtrl, frame ) {
var skinController = controllers[ instanceCtrl.url ];
frame = frame !== undefined ? frame : 40;
if ( !skinController || !skinController.skin ) {
console.log( 'ColladaLoader: Could not find skin controller.' );
return;
}
if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
return;
}
var animationBounds = calcAnimationBounds();
var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
var i, j, w, vidx, weight;
var v = new THREE.Vector3(), o, s;
// move vertices to bind shape
for ( i = 0; i < geometry.vertices.length; i ++ ) {
geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
}
// process animation, or simply pose the rig if no animation
for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
var bones = [];
var skinned = [];
// zero skinned vertices
for ( i = 0; i < geometry.vertices.length; i++ ) {
skinned.push( new THREE.Vector3() );
}
// process the frame and setup the rig with a fresh
// transform, possibly from the bone's animation channel(s)
setupSkeleton( skeleton, bones, frame );
setupSkinningMatrices( bones, skinController.skin );
// skin 'm
for ( i = 0; i < bones.length; i ++ ) {
if ( bones[ i ].type != 'JOINT' ) continue;
for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
w = bones[ i ].weights[ j ];
vidx = w.index;
weight = w.weight;
o = geometry.vertices[vidx];
s = skinned[vidx];
v.x = o.x;
v.y = o.y;
v.z = o.z;
v.applyMatrix4( bones[i].skinningMatrix );
s.x += (v.x * weight);
s.y += (v.y * weight);
s.z += (v.z * weight);
}
}
geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
}
};
function createSceneGraph ( node, parent ) {
var obj = new THREE.Object3D();
var skinned = false;
var skinController;
var morphController;
var i, j;
// FIXME: controllers
for ( i = 0; i < node.controllers.length; i ++ ) {
var controller = controllers[ node.controllers[ i ].url ];
switch ( controller.type ) {
case 'skin':
if ( geometries[ controller.skin.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = controller.skin.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
skinned = true;
skinController = node.controllers[ i ];
} else if ( controllers[ controller.skin.source ] ) {
// urgh: controller can be chained
// handle the most basic case...
var second = controllers[ controller.skin.source ];
morphController = second;
// skinController = node.controllers[i];
if ( second.morph && geometries[ second.morph.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = second.morph.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
}
}
break;
case 'morph':
if ( geometries[ controller.morph.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = controller.morph.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
morphController = node.controllers[ i ];
}
console.log( 'ColladaLoader: Morph-controller partially supported.' );
default:
break;
}
}
// FIXME: multi-material mesh?
// geometries
var double_sided_materials = {};
for ( i = 0; i < node.geometries.length; i ++ ) {
var instance_geometry = node.geometries[i];
var instance_materials = instance_geometry.instance_material;
var geometry = geometries[ instance_geometry.url ];
var used_materials = {};
var used_materials_array = [];
var num_materials = 0;
var first_material;
if ( geometry ) {
if ( !geometry.mesh || !geometry.mesh.primitives )
continue;
if ( obj.name.length == 0 ) {
obj.name = geometry.id;
}
// collect used fx for this geometry-instance
if ( instance_materials ) {
for ( j = 0; j < instance_materials.length; j ++ ) {
var instance_material = instance_materials[ j ];
var mat = materials[ instance_material.target ];
var effect_id = mat.instance_effect.url;
var shader = effects[ effect_id ].shader;
var material3js = shader.material;
if ( geometry.doubleSided ) {
if ( !( material3js in double_sided_materials ) ) {
var _copied_material = material3js.clone();
_copied_material.side = THREE.DoubleSide;
double_sided_materials[ material3js ] = _copied_material;
}
material3js = double_sided_materials[ material3js ];
}
material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
used_materials[ instance_material.symbol ] = num_materials;
used_materials_array.push( material3js );
first_material = material3js;
first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
num_materials ++;
}
}
var mesh;
var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
var geom = geometry.mesh.geometry3js;
if ( num_materials > 1 ) {
material = new THREE.MeshFaceMaterial( used_materials_array );
for ( j = 0; j < geom.faces.length; j ++ ) {
var face = geom.faces[ j ];
face.materialIndex = used_materials[ face.daeMaterial ]
}
}
if ( skinController !== undefined ) {
applySkin( geom, skinController );
material.morphTargets = true;
mesh = new THREE.SkinnedMesh( geom, material, false );
mesh.skeleton = skinController.skeleton;
mesh.skinController = controllers[ skinController.url ];
mesh.skinInstanceController = skinController;
mesh.name = 'skin_' + skins.length;
skins.push( mesh );
} else if ( morphController !== undefined ) {
createMorph( geom, morphController );
material.morphTargets = true;
mesh = new THREE.Mesh( geom, material );
mesh.name = 'morph_' + morphs.length;
morphs.push( mesh );
} else {
mesh = new THREE.Mesh( geom, material );
// mesh.geom.name = geometry.id;
}
node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
}
}
for ( i = 0; i < node.cameras.length; i ++ ) {
var params = cameras[node.cameras[i].url];
obj = new THREE.PerspectiveCamera(params.fov, params.aspect_ratio, params.znear, params.zfar);
}
for ( i = 0; i < node.lights.length; i ++ ) {
var params = lights[node.lights[i].url];
switch ( params.technique ) {
case 'ambient':
obj = new THREE.AmbientLight(params.color);
break;
case 'point':
obj = new THREE.PointLight(params.color);
break;
case 'directional':
obj = new THREE.DirectionalLight(params.color);
break;
}
}
obj.name = node.name || node.id || "";
obj.matrix = node.matrix;
var props = node.matrix.decompose();
obj.position = props[ 0 ];
obj.quaternion = props[ 1 ];
obj.useQuaternion = true;
obj.scale = props[ 2 ];
if ( options.centerGeometry && obj.geometry ) {
var delta = THREE.GeometryUtils.center( obj.geometry );
delta.multiply( obj.scale );
delta.applyQuaternion( obj.quaternion );
obj.position.sub( delta );
}
for ( i = 0; i < node.nodes.length; i ++ ) {
obj.add( createSceneGraph( node.nodes[i], node ) );
}
return obj;
};
function getJointId( skin, id ) {
for ( var i = 0; i < skin.joints.length; i ++ ) {
if ( skin.joints[ i ] == id ) {
return i;
}
}
};
function getLibraryNode( id ) {
return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
};
function getChannelsForNode (node ) {
var channels = [];
var startTime = 1000000;
var endTime = -1000000;
for ( var id in animations ) {
var animation = animations[id];
for ( var i = 0; i < animation.channel.length; i ++ ) {
var channel = animation.channel[i];
var sampler = animation.sampler[i];
var id = channel.target.split('/')[0];
if ( id == node.id ) {
sampler.create();
channel.sampler = sampler;
startTime = Math.min(startTime, sampler.startTime);
endTime = Math.max(endTime, sampler.endTime);
channels.push(channel);
}
}
}
if ( channels.length ) {
node.startTime = startTime;
node.endTime = endTime;
}
return channels;
};
function calcFrameDuration( node ) {
var minT = 10000000;
for ( var i = 0; i < node.channels.length; i ++ ) {
var sampler = node.channels[i].sampler;
for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
var t0 = sampler.input[ j ];
var t1 = sampler.input[ j + 1 ];
minT = Math.min( minT, t1 - t0 );
}
}
return minT;
};
function calcMatrixAt( node, t ) {
var animated = {};
var i, j;
for ( i = 0; i < node.channels.length; i ++ ) {
var channel = node.channels[ i ];
animated[ channel.sid ] = channel;
}
var matrix = new THREE.Matrix4();
for ( i = 0; i < node.transforms.length; i ++ ) {
var transform = node.transforms[ i ];
var channel = animated[ transform.sid ];
if ( channel !== undefined ) {
var sampler = channel.sampler;
var value;
for ( j = 0; j < sampler.input.length - 1; j ++ ) {
if ( sampler.input[ j + 1 ] > t ) {
value = sampler.output[ j ];
//console.log(value.flatten)
break;
}
}
if ( value !== undefined ) {
if ( value instanceof THREE.Matrix4 ) {
matrix.multiplyMatrices( matrix, value );
} else {
// FIXME: handle other types
matrix.multiplyMatrices( matrix, transform.matrix );
}
} else {
matrix.multiplyMatrices( matrix, transform.matrix );
}
} else {
matrix.multiplyMatrices( matrix, transform.matrix );
}
}
return matrix;
};
function bakeAnimations ( node ) {
if ( node.channels && node.channels.length ) {
var keys = [],
sids = [];
for ( var i = 0, il = node.channels.length; i < il; i++ ) {
var channel = node.channels[i],
fullSid = channel.fullSid,
sampler = channel.sampler,
input = sampler.input,
transform = node.getTransformBySid( channel.sid ),
member;
if ( channel.arrIndices ) {
member = [];
for ( var j = 0, jl = channel.arrIndices.length; j < jl; j++ ) {
member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
}
} else {
member = getConvertedMember( channel.member );
}
if ( transform ) {
if ( sids.indexOf( fullSid ) === -1 ) {
sids.push( fullSid );
}
for ( var j = 0, jl = input.length; j < jl; j++ ) {
var time = input[j],
data = sampler.getData( transform.type, j ),
key = findKey( keys, time );
if ( !key ) {
key = new Key( time );
var timeNdx = findTimeNdx( keys, time );
keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
}
key.addTarget( fullSid, transform, member, data );
}
} else {
console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
}
}
// post process
for ( var i = 0; i < sids.length; i++ ) {
var sid = sids[ i ];
for ( var j = 0; j < keys.length; j++ ) {
var key = keys[ j ];
if ( !key.hasTarget( sid ) ) {
interpolateKeys( keys, key, j, sid );
}
}
}
node.keys = keys;
node.sids = sids;
}
};
function findKey ( keys, time) {
var retVal = null;
for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
var key = keys[i];
if ( key.time === time ) {
retVal = key;
} else if ( key.time > time ) {
break;
}
}
return retVal;
};
function findTimeNdx ( keys, time) {
var ndx = -1;
for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
var key = keys[i];
if ( key.time >= time ) {
ndx = i;
}
}
return ndx;
};
function interpolateKeys ( keys, key, ndx, fullSid ) {
var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
if ( prevKey && nextKey ) {
var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
prevTarget = prevKey.getTarget( fullSid ),
nextData = nextKey.getTarget( fullSid ).data,
prevData = prevTarget.data,
data;
if ( prevTarget.type === 'matrix' ) {
data = prevData;
} else if ( prevData.length ) {
data = [];
for ( var i = 0; i < prevData.length; ++i ) {
data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
}
} else {
data = prevData + ( nextData - prevData ) * scale;
}
key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
}
};
// Get next key with given sid
function getNextKeyWith( keys, fullSid, ndx ) {
for ( ; ndx < keys.length; ndx++ ) {
var key = keys[ ndx ];
if ( key.hasTarget( fullSid ) ) {
return key;
}
}
return null;
};
// Get previous key with given sid
function getPrevKeyWith( keys, fullSid, ndx ) {
ndx = ndx >= 0 ? ndx : ndx + keys.length;
for ( ; ndx >= 0; ndx-- ) {
var key = keys[ ndx ];
if ( key.hasTarget( fullSid ) ) {
return key;
}
}
return null;
};
function _Image() {
this.id = "";
this.init_from = "";
};
_Image.prototype.parse = function(element) {
this.id = element.getAttribute('id');
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeName == 'init_from' ) {
this.init_from = child.textContent;
}
}
return this;
};
function Controller() {
this.id = "";
this.name = "";
this.type = "";
this.skin = null;
this.morph = null;
};
Controller.prototype.parse = function( element ) {
this.id = element.getAttribute('id');
this.name = element.getAttribute('name');
this.type = "none";
for ( var i = 0; i < element.childNodes.length; i++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'skin':
this.skin = (new Skin()).parse(child);
this.type = child.nodeName;
break;
case 'morph':
this.morph = (new Morph()).parse(child);
this.type = child.nodeName;
break;
default:
break;
}
}
return this;
};
function Morph() {
this.method = null;
this.source = null;
this.targets = null;
this.weights = null;
};
Morph.prototype.parse = function( element ) {
var sources = {};
var inputs = [];
var i;
this.method = element.getAttribute( 'method' );
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
for ( i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'source':
var source = ( new Source() ).parse( child );
sources[ source.id ] = source;
break;
case 'targets':
inputs = this.parseInputs( child );
break;
default:
console.log( child.nodeName );
break;
}
}
for ( i = 0; i < inputs.length; i ++ ) {
var input = inputs[ i ];
var source = sources[ input.source ];
switch ( input.semantic ) {
case 'MORPH_TARGET':
this.targets = source.read();
break;
case 'MORPH_WEIGHT':
this.weights = source.read();
break;
default:
break;
}
}
return this;
};
Morph.prototype.parseInputs = function(element) {
var inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1) continue;
switch ( child.nodeName ) {
case 'input':
inputs.push( (new Input()).parse(child) );
break;
default:
break;
}
}
return inputs;
};
function Skin() {
this.source = "";
this.bindShapeMatrix = null;
this.invBindMatrices = [];
this.joints = [];
this.weights = [];
};
Skin.prototype.parse = function( element ) {
var sources = {};
var joints, weights;
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
this.invBindMatrices = [];
this.joints = [];
this.weights = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'bind_shape_matrix':
var f = _floats(child.textContent);
this.bindShapeMatrix = getConvertedMat4( f );
break;
case 'source':
var src = new Source().parse(child);
sources[ src.id ] = src;
break;
case 'joints':
joints = child;
break;
case 'vertex_weights':
weights = child;
break;
default:
console.log( child.nodeName );
break;
}
}
this.parseJoints( joints, sources );
this.parseWeights( weights, sources );
return this;
};
Skin.prototype.parseJoints = function ( element, sources ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var input = ( new Input() ).parse( child );
var source = sources[ input.source ];
if ( input.semantic == 'JOINT' ) {
this.joints = source.read();
} else if ( input.semantic == 'INV_BIND_MATRIX' ) {
this.invBindMatrices = source.read();
}
break;
default:
break;
}
}
};
Skin.prototype.parseWeights = function ( element, sources ) {
var v, vcount, inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
inputs.push( ( new Input() ).parse( child ) );
break;
case 'v':
v = _ints( child.textContent );
break;
case 'vcount':
vcount = _ints( child.textContent );
break;
default:
break;
}
}
var index = 0;
for ( var i = 0; i < vcount.length; i ++ ) {
var numBones = vcount[i];
var vertex_weights = [];
for ( var j = 0; j < numBones; j++ ) {
var influence = {};
for ( var k = 0; k < inputs.length; k ++ ) {
var input = inputs[ k ];
var value = v[ index + input.offset ];
switch ( input.semantic ) {
case 'JOINT':
influence.joint = value;//this.joints[value];
break;
case 'WEIGHT':
influence.weight = sources[ input.source ].data[ value ];
break;
default:
break;
}
}
vertex_weights.push( influence );
index += inputs.length;
}
for ( var j = 0; j < vertex_weights.length; j ++ ) {
vertex_weights[ j ].index = i;
}
this.weights.push( vertex_weights );
}
};
function VisualScene () {
this.id = "";
this.name = "";
this.nodes = [];
this.scene = new THREE.Object3D();
};
VisualScene.prototype.getChildById = function( id, recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var node = this.nodes[ i ].getChildById( id, recursive );
if ( node ) {
return node;
}
}
return null;
};
VisualScene.prototype.getChildBySid = function( sid, recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var node = this.nodes[ i ].getChildBySid( sid, recursive );
if ( node ) {
return node;
}
}
return null;
};
VisualScene.prototype.parse = function( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
this.nodes = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'node':
this.nodes.push( ( new Node() ).parse( child ) );
break;
default:
break;
}
}
return this;
};
function Node() {
this.id = "";
this.name = "";
this.sid = "";
this.nodes = [];
this.controllers = [];
this.transforms = [];
this.geometries = [];
this.channels = [];
this.matrix = new THREE.Matrix4();
};
Node.prototype.getChannelForTransform = function( transformSid ) {
for ( var i = 0; i < this.channels.length; i ++ ) {
var channel = this.channels[i];
var parts = channel.target.split('/');
var id = parts.shift();
var sid = parts.shift();
var dotSyntax = (sid.indexOf(".") >= 0);
var arrSyntax = (sid.indexOf("(") >= 0);
var arrIndices;
var member;
if ( dotSyntax ) {
parts = sid.split(".");
sid = parts.shift();
member = parts.shift();
} else if ( arrSyntax ) {
arrIndices = sid.split("(");
sid = arrIndices.shift();
for ( var j = 0; j < arrIndices.length; j ++ ) {
arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
}
}
if ( sid == transformSid ) {
channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
return channel;
}
}
return null;
};
Node.prototype.getChildById = function ( id, recursive ) {
if ( this.id == id ) {
return this;
}
if ( recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var n = this.nodes[ i ].getChildById( id, recursive );
if ( n ) {
return n;
}
}
}
return null;
};
Node.prototype.getChildBySid = function ( sid, recursive ) {
if ( this.sid == sid ) {
return this;
}
if ( recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var n = this.nodes[ i ].getChildBySid( sid, recursive );
if ( n ) {
return n;
}
}
}
return null;
};
Node.prototype.getTransformBySid = function ( sid ) {
for ( var i = 0; i < this.transforms.length; i ++ ) {
if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
}
return null;
};
Node.prototype.parse = function( element ) {
var url;
this.id = element.getAttribute('id');
this.sid = element.getAttribute('sid');
this.name = element.getAttribute('name');
this.type = element.getAttribute('type');
this.type = this.type == 'JOINT' ? this.type : 'NODE';
this.nodes = [];
this.transforms = [];
this.geometries = [];
this.cameras = [];
this.lights = [];
this.controllers = [];
this.matrix = new THREE.Matrix4();
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'node':
this.nodes.push( ( new Node() ).parse( child ) );
break;
case 'instance_camera':
this.cameras.push( ( new InstanceCamera() ).parse( child ) );
break;
case 'instance_light':
this.lights.push( ( new InstanceLight() ).parse( child ) );
break;
case 'instance_controller':
this.controllers.push( ( new InstanceController() ).parse( child ) );
break;
case 'instance_geometry':
this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
break;
case 'instance_node':
url = child.getAttribute( 'url' ).replace( /^#/, '' );
var iNode = getLibraryNode( url );
if ( iNode ) {
this.nodes.push( ( new Node() ).parse( iNode )) ;
}
break;
case 'rotate':
case 'translate':
case 'scale':
case 'matrix':
case 'lookat':
case 'skew':
this.transforms.push( ( new Transform() ).parse( child ) );
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
this.channels = getChannelsForNode( this );
bakeAnimations( this );
this.updateMatrix();
return this;
};
<|fim▁hole|> this.matrix.identity();
for ( var i = 0; i < this.transforms.length; i ++ ) {
this.transforms[ i ].apply( this.matrix );
}
};
function Transform () {
this.sid = "";
this.type = "";
this.data = [];
this.obj = null;
};
Transform.prototype.parse = function ( element ) {
this.sid = element.getAttribute( 'sid' );
this.type = element.nodeName;
this.data = _floats( element.textContent );
this.convert();
return this;
};
Transform.prototype.convert = function () {
switch ( this.type ) {
case 'matrix':
this.obj = getConvertedMat4( this.data );
break;
case 'rotate':
this.angle = THREE.Math.degToRad( this.data[3] );
case 'translate':
fixCoords( this.data, -1 );
this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
break;
case 'scale':
fixCoords( this.data, 1 );
this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
break;
default:
console.log( 'Can not convert Transform of type ' + this.type );
break;
}
};
Transform.prototype.apply = function () {
var m1 = new THREE.Matrix4();
return function ( matrix ) {
switch ( this.type ) {
case 'matrix':
matrix.multiply( this.obj );
break;
case 'translate':
matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
break;
case 'rotate':
matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
break;
case 'scale':
matrix.scale( this.obj );
break;
}
};
}();
Transform.prototype.update = function ( data, member ) {
var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
switch ( this.type ) {
case 'matrix':
if ( ! member ) {
this.obj.copy( data );
} else if ( member.length === 1 ) {
switch ( member[ 0 ] ) {
case 0:
this.obj.n11 = data[ 0 ];
this.obj.n21 = data[ 1 ];
this.obj.n31 = data[ 2 ];
this.obj.n41 = data[ 3 ];
break;
case 1:
this.obj.n12 = data[ 0 ];
this.obj.n22 = data[ 1 ];
this.obj.n32 = data[ 2 ];
this.obj.n42 = data[ 3 ];
break;
case 2:
this.obj.n13 = data[ 0 ];
this.obj.n23 = data[ 1 ];
this.obj.n33 = data[ 2 ];
this.obj.n43 = data[ 3 ];
break;
case 3:
this.obj.n14 = data[ 0 ];
this.obj.n24 = data[ 1 ];
this.obj.n34 = data[ 2 ];
this.obj.n44 = data[ 3 ];
break;
}
} else if ( member.length === 2 ) {
var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
this.obj[ propName ] = data;
} else {
console.log('Incorrect addressing of matrix in transform.');
}
break;
case 'translate':
case 'scale':
if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
member = members[ member[ 0 ] ];
}
switch ( member ) {
case 'X':
this.obj.x = data;
break;
case 'Y':
this.obj.y = data;
break;
case 'Z':
this.obj.z = data;
break;
default:
this.obj.x = data[ 0 ];
this.obj.y = data[ 1 ];
this.obj.z = data[ 2 ];
break;
}
break;
case 'rotate':
if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
member = members[ member[ 0 ] ];
}
switch ( member ) {
case 'X':
this.obj.x = data;
break;
case 'Y':
this.obj.y = data;
break;
case 'Z':
this.obj.z = data;
break;
case 'ANGLE':
this.angle = THREE.Math.degToRad( data );
break;
default:
this.obj.x = data[ 0 ];
this.obj.y = data[ 1 ];
this.obj.z = data[ 2 ];
this.angle = THREE.Math.degToRad( data[ 3 ] );
break;
}
break;
}
};
function InstanceController() {
this.url = "";
this.skeleton = [];
this.instance_material = [];
};
InstanceController.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
this.skeleton = [];
this.instance_material = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'skeleton':
this.skeleton.push( child.textContent.replace(/^#/, '') );
break;
case 'bind_material':
var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( instances ) {
var instance = instances.iterateNext();
while ( instance ) {
this.instance_material.push( (new InstanceMaterial()).parse(instance) );
instance = instances.iterateNext();
}
}
break;
case 'extra':
break;
default:
break;
}
}
return this;
};
function InstanceMaterial () {
this.symbol = "";
this.target = "";
};
InstanceMaterial.prototype.parse = function ( element ) {
this.symbol = element.getAttribute('symbol');
this.target = element.getAttribute('target').replace(/^#/, '');
return this;
};
function InstanceGeometry() {
this.url = "";
this.instance_material = [];
};
InstanceGeometry.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
this.instance_material = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
if ( child.nodeName == 'bind_material' ) {
var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( instances ) {
var instance = instances.iterateNext();
while ( instance ) {
this.instance_material.push( (new InstanceMaterial()).parse(instance) );
instance = instances.iterateNext();
}
}
break;
}
}
return this;
};
function Geometry() {
this.id = "";
this.mesh = null;
};
Geometry.prototype.parse = function ( element ) {
this.id = element.getAttribute('id');
extractDoubleSided( this, element );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
switch ( child.nodeName ) {
case 'mesh':
this.mesh = (new Mesh(this)).parse(child);
break;
case 'extra':
// console.log( child );
break;
default:
break;
}
}
return this;
};
function Mesh( geometry ) {
this.geometry = geometry.id;
this.primitives = [];
this.vertices = null;
this.geometry3js = null;
};
Mesh.prototype.parse = function( element ) {
this.primitives = [];
var i, j;
for ( i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'source':
_source( child );
break;
case 'vertices':
this.vertices = ( new Vertices() ).parse( child );
break;
case 'triangles':
this.primitives.push( ( new Triangles().parse( child ) ) );
break;
case 'polygons':
this.primitives.push( ( new Polygons().parse( child ) ) );
break;
case 'polylist':
this.primitives.push( ( new Polylist().parse( child ) ) );
break;
default:
break;
}
}
this.geometry3js = new THREE.Geometry();
var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
for ( i = 0; i < vertexData.length; i += 3 ) {
this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
}
for ( i = 0; i < this.primitives.length; i ++ ) {
var primitive = this.primitives[ i ];
primitive.setVertices( this.vertices );
this.handlePrimitive( primitive, this.geometry3js );
}
this.geometry3js.computeCentroids();
this.geometry3js.computeFaceNormals();
if ( this.geometry3js.calcNormals ) {
this.geometry3js.computeVertexNormals();
delete this.geometry3js.calcNormals;
}
this.geometry3js.computeBoundingBox();
return this;
};
Mesh.prototype.handlePrimitive = function( primitive, geom ) {
var j, k, pList = primitive.p, inputs = primitive.inputs;
var input, index, idx32;
var source, numParams;
var vcIndex = 0, vcount = 3, maxOffset = 0;
var texture_sets = [];
for ( j = 0; j < inputs.length; j ++ ) {
input = inputs[ j ];
var offset = input.offset + 1;
maxOffset = (maxOffset < offset)? offset : maxOffset;
switch ( input.semantic ) {
case 'TEXCOORD':
texture_sets.push( input.set );
break;
}
}
for ( var pCount = 0; pCount < pList.length; ++pCount ) {
var p = pList[ pCount ], i = 0;
while ( i < p.length ) {
var vs = [];
var ns = [];
var ts = null;
var cs = [];
if ( primitive.vcount ) {
vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
} else {
vcount = p.length / maxOffset;
}
for ( j = 0; j < vcount; j ++ ) {
for ( k = 0; k < inputs.length; k ++ ) {
input = inputs[ k ];
source = sources[ input.source ];
index = p[ i + ( j * maxOffset ) + input.offset ];
numParams = source.accessor.params.length;
idx32 = index * numParams;
switch ( input.semantic ) {
case 'VERTEX':
vs.push( index );
break;
case 'NORMAL':
ns.push( getConvertedVec3( source.data, idx32 ) );
break;
case 'TEXCOORD':
ts = ts || { };
if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
// invert the V
ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
break;
case 'COLOR':
cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
break;
default:
break;
}
}
}
if ( ns.length == 0 ) {
// check the vertices inputs
input = this.vertices.input.NORMAL;
if ( input ) {
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
}
} else {
geom.calcNormals = true;
}
}
if ( !ts ) {
ts = { };
// check the vertices inputs
input = this.vertices.input.TEXCOORD;
if ( input ) {
texture_sets.push( input.set );
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
idx32 = vs[ ndx ] * numParams;
if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
// invert the V
ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
}
}
}
if ( cs.length == 0 ) {
// check the vertices inputs
input = this.vertices.input.COLOR;
if ( input ) {
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
idx32 = vs[ ndx ] * numParams;
cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
}
}
}
var face = null, faces = [], uv, uvArr;
if ( vcount === 3 ) {
faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
} else if ( vcount === 4 ) {
faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
} else if ( vcount > 4 && options.subdivideFaces ) {
var clr = cs.length ? cs : new THREE.Color(),
vec1, vec2, vec3, v1, v2, norm;
// subdivide into multiple Face3s
for ( k = 1; k < vcount - 1; ) {
// FIXME: normals don't seem to be quite right
faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
}
}
if ( faces.length ) {
for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
face = faces[ndx];
face.daeMaterial = primitive.material;
geom.faces.push( face );
for ( k = 0; k < texture_sets.length; k++ ) {
uv = ts[ texture_sets[k] ];
if ( vcount > 4 ) {
// Grab the right UVs for the vertices in this face
uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
} else if ( vcount === 4 ) {
uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
} else {
uvArr = [ uv[0], uv[1], uv[2] ];
}
if ( !geom.faceVertexUvs[k] ) {
geom.faceVertexUvs[k] = [];
}
geom.faceVertexUvs[k].push( uvArr );
}
}
} else {
console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
}
i += maxOffset * vcount;
}
}
};
function Polygons () {
this.material = "";
this.count = 0;
this.inputs = [];
this.vcount = null;
this.p = [];
this.geometry = new THREE.Geometry();
};
Polygons.prototype.setVertices = function ( vertices ) {
for ( var i = 0; i < this.inputs.length; i ++ ) {
if ( this.inputs[ i ].source == vertices.id ) {
this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
}
}
};
Polygons.prototype.parse = function ( element ) {
this.material = element.getAttribute( 'material' );
this.count = _attr_as_int( element, 'count', 0 );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'input':
this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
break;
case 'vcount':
this.vcount = _ints( child.textContent );
break;
case 'p':
this.p.push( _ints( child.textContent ) );
break;
case 'ph':
console.warn( 'polygon holes not yet supported!' );
break;
default:
break;
}
}
return this;
};
function Polylist () {
Polygons.call( this );
this.vcount = [];
};
Polylist.prototype = Object.create( Polygons.prototype );
function Triangles () {
Polygons.call( this );
this.vcount = 3;
};
Triangles.prototype = Object.create( Polygons.prototype );
function Accessor() {
this.source = "";
this.count = 0;
this.stride = 0;
this.params = [];
};
Accessor.prototype.parse = function ( element ) {
this.params = [];
this.source = element.getAttribute( 'source' );
this.count = _attr_as_int( element, 'count', 0 );
this.stride = _attr_as_int( element, 'stride', 0 );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeName == 'param' ) {
var param = {};
param[ 'name' ] = child.getAttribute( 'name' );
param[ 'type' ] = child.getAttribute( 'type' );
this.params.push( param );
}
}
return this;
};
function Vertices() {
this.input = {};
};
Vertices.prototype.parse = function ( element ) {
this.id = element.getAttribute('id');
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[i].nodeName == 'input' ) {
var input = ( new Input() ).parse( element.childNodes[ i ] );
this.input[ input.semantic ] = input;
}
}
return this;
};
function Input () {
this.semantic = "";
this.offset = 0;
this.source = "";
this.set = 0;
};
Input.prototype.parse = function ( element ) {
this.semantic = element.getAttribute('semantic');
this.source = element.getAttribute('source').replace(/^#/, '');
this.set = _attr_as_int(element, 'set', -1);
this.offset = _attr_as_int(element, 'offset', 0);
if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
this.set = 0;
}
return this;
};
function Source ( id ) {
this.id = id;
this.type = null;
};
Source.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
switch ( child.nodeName ) {
case 'bool_array':
this.data = _bools( child.textContent );
this.type = child.nodeName;
break;
case 'float_array':
this.data = _floats( child.textContent );
this.type = child.nodeName;
break;
case 'int_array':
this.data = _ints( child.textContent );
this.type = child.nodeName;
break;
case 'IDREF_array':
case 'Name_array':
this.data = _strings( child.textContent );
this.type = child.nodeName;
break;
case 'technique_common':
for ( var j = 0; j < child.childNodes.length; j ++ ) {
if ( child.childNodes[ j ].nodeName == 'accessor' ) {
this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
break;
}
}
break;
default:
// console.log(child.nodeName);
break;
}
}
return this;
};
Source.prototype.read = function () {
var result = [];
//for (var i = 0; i < this.accessor.params.length; i++) {
var param = this.accessor.params[ 0 ];
//console.log(param.name + " " + param.type);
switch ( param.type ) {
case 'IDREF':
case 'Name': case 'name':
case 'float':
return this.data;
case 'float4x4':
for ( var j = 0; j < this.data.length; j += 16 ) {
var s = this.data.slice( j, j + 16 );
var m = getConvertedMat4( s );
result.push( m );
}
break;
default:
console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
break;
}
//}
return result;
};
function Material () {
this.id = "";
this.name = "";
this.instance_effect = null;
};
Material.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
break;
}
}
return this;
};
function ColorOrTexture () {
this.color = new THREE.Color();
this.color.setRGB( Math.random(), Math.random(), Math.random() );
this.color.a = 1.0;
this.texture = null;
this.texcoord = null;
this.texOpts = null;
};
ColorOrTexture.prototype.isColor = function () {
return ( this.texture == null );
};
ColorOrTexture.prototype.isTexture = function () {
return ( this.texture != null );
};
ColorOrTexture.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'color':
var rgba = _floats( child.textContent );
this.color = new THREE.Color();
this.color.setRGB( rgba[0], rgba[1], rgba[2] );
this.color.a = rgba[3];
break;
case 'texture':
this.texture = child.getAttribute('texture');
this.texcoord = child.getAttribute('texcoord');
// Defaults from:
// https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
this.texOpts = {
offsetU: 0,
offsetV: 0,
repeatU: 1,
repeatV: 1,
wrapU: 1,
wrapV: 1,
};
this.parseTexture( child );
break;
default:
break;
}
}
return this;
};
ColorOrTexture.prototype.parseTexture = function ( element ) {
if ( ! element.childNodes ) return this;
// This should be supported by Maya, 3dsMax, and MotionBuilder
if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
element = element.childNodes[1];
if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
element = element.childNodes[1];
}
}
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'offsetU':
case 'offsetV':
case 'repeatU':
case 'repeatV':
this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
break;
case 'wrapU':
case 'wrapV':
this.texOpts[ child.nodeName ] = parseInt( child.textContent );
break;
default:
this.texOpts[ child.nodeName ] = child.textContent;
break;
}
}
return this;
};
function Shader ( type, effect ) {
this.type = type;
this.effect = effect;
this.material = null;
};
Shader.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'ambient':
case 'emission':
case 'diffuse':
case 'specular':
case 'transparent':
this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
break;
case 'shininess':
case 'reflectivity':
case 'index_of_refraction':
case 'transparency':
var f = evaluateXPath( child, './/dae:float' );
if ( f.length > 0 )
this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
break;
default:
break;
}
}
this.create();
return this;
};
Shader.prototype.create = function() {
var props = {};
var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
for ( var prop in this ) {
switch ( prop ) {
case 'ambient':
case 'emission':
case 'diffuse':
case 'specular':
var cot = this[ prop ];
if ( cot instanceof ColorOrTexture ) {
if ( cot.isTexture() ) {
var samplerId = cot.texture;
var surfaceId = this.effect.sampler[samplerId].source;
if ( surfaceId ) {
var surface = this.effect.surface[surfaceId];
var image = images[surface.init_from];
if (image) {
var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.offset.x = cot.texOpts.offsetU;
texture.offset.y = cot.texOpts.offsetV;
texture.repeat.x = cot.texOpts.repeatU;
texture.repeat.y = cot.texOpts.repeatV;
props['map'] = texture;
// Texture with baked lighting?
if (prop === 'emission') props['emissive'] = 0xffffff;
}
}
} else if ( prop === 'diffuse' || !transparent ) {
if ( prop === 'emission' ) {
props[ 'emissive' ] = cot.color.getHex();
} else {
props[ prop ] = cot.color.getHex();
}
}
}
break;
case 'shininess':
props[ prop ] = this[ prop ];
break;
case 'reflectivity':
props[ prop ] = this[ prop ];
if( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
break;
case 'index_of_refraction':
props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
break;
case 'transparency':
if ( transparent ) {
props[ 'transparent' ] = true;
props[ 'opacity' ] = this[ prop ];
transparent = true;
}
break;
default:
break;
}
}
props[ 'shading' ] = preferredShading;
props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
switch ( this.type ) {
case 'constant':
if (props.emissive != undefined) props.color = props.emissive;
this.material = new THREE.MeshBasicMaterial( props );
break;
case 'phong':
case 'blinn':
if (props.diffuse != undefined) props.color = props.diffuse;
this.material = new THREE.MeshPhongMaterial( props );
break;
case 'lambert':
default:
if (props.diffuse != undefined) props.color = props.diffuse;
this.material = new THREE.MeshLambertMaterial( props );
break;
}
return this.material;
};
function Surface ( effect ) {
this.effect = effect;
this.init_from = null;
this.format = null;
};
Surface.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'init_from':
this.init_from = child.textContent;
break;
case 'format':
this.format = child.textContent;
break;
default:
console.log( "unhandled Surface prop: " + child.nodeName );
break;
}
}
return this;
};
function Sampler2D ( effect ) {
this.effect = effect;
this.source = null;
this.wrap_s = null;
this.wrap_t = null;
this.minfilter = null;
this.magfilter = null;
this.mipfilter = null;
};
Sampler2D.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'source':
this.source = child.textContent;
break;
case 'minfilter':
this.minfilter = child.textContent;
break;
case 'magfilter':
this.magfilter = child.textContent;
break;
case 'mipfilter':
this.mipfilter = child.textContent;
break;
case 'wrap_s':
this.wrap_s = child.textContent;
break;
case 'wrap_t':
this.wrap_t = child.textContent;
break;
default:
console.log( "unhandled Sampler2D prop: " + child.nodeName );
break;
}
}
return this;
};
function Effect () {
this.id = "";
this.name = "";
this.shader = null;
this.surface = {};
this.sampler = {};
};
Effect.prototype.create = function () {
if ( this.shader == null ) {
return null;
}
};
Effect.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
extractDoubleSided( this, element );
this.shader = null;
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'profile_COMMON':
this.parseTechnique( this.parseProfileCOMMON( child ) );
break;
default:
break;
}
}
return this;
};
Effect.prototype.parseNewparam = function ( element ) {
var sid = element.getAttribute( 'sid' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'surface':
this.surface[sid] = ( new Surface( this ) ).parse( child );
break;
case 'sampler2D':
this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
};
Effect.prototype.parseProfileCOMMON = function ( element ) {
var technique;
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'profile_COMMON':
this.parseProfileCOMMON( child );
break;
case 'technique':
technique = child;
break;
case 'newparam':
this.parseNewparam( child );
break;
case 'image':
var _image = ( new _Image() ).parse( child );
images[ _image.id ] = _image;
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
return technique;
};
Effect.prototype.parseTechnique= function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'constant':
case 'lambert':
case 'blinn':
case 'phong':
this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
break;
default:
break;
}
}
};
function InstanceEffect () {
this.url = "";
};
InstanceEffect.prototype.parse = function ( element ) {
this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
return this;
};
function Animation() {
this.id = "";
this.name = "";
this.source = {};
this.sampler = [];
this.channel = [];
};
Animation.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
this.source = {};
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'animation':
var anim = ( new Animation() ).parse( child );
for ( var src in anim.source ) {
this.source[ src ] = anim.source[ src ];
}
for ( var j = 0; j < anim.channel.length; j ++ ) {
this.channel.push( anim.channel[ j ] );
this.sampler.push( anim.sampler[ j ] );
}
break;
case 'source':
var src = ( new Source() ).parse( child );
this.source[ src.id ] = src;
break;
case 'sampler':
this.sampler.push( ( new Sampler( this ) ).parse( child ) );
break;
case 'channel':
this.channel.push( ( new Channel( this ) ).parse( child ) );
break;
default:
break;
}
}
return this;
};
function Channel( animation ) {
this.animation = animation;
this.source = "";
this.target = "";
this.fullSid = null;
this.sid = null;
this.dotSyntax = null;
this.arrSyntax = null;
this.arrIndices = null;
this.member = null;
};
Channel.prototype.parse = function ( element ) {
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
this.target = element.getAttribute( 'target' );
var parts = this.target.split( '/' );
var id = parts.shift();
var sid = parts.shift();
var dotSyntax = ( sid.indexOf(".") >= 0 );
var arrSyntax = ( sid.indexOf("(") >= 0 );
if ( dotSyntax ) {
parts = sid.split(".");
this.sid = parts.shift();
this.member = parts.shift();
} else if ( arrSyntax ) {
var arrIndices = sid.split("(");
this.sid = arrIndices.shift();
for (var j = 0; j < arrIndices.length; j ++ ) {
arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
}
this.arrIndices = arrIndices;
} else {
this.sid = sid;
}
this.fullSid = sid;
this.dotSyntax = dotSyntax;
this.arrSyntax = arrSyntax;
return this;
};
function Sampler ( animation ) {
this.id = "";
this.animation = animation;
this.inputs = [];
this.input = null;
this.output = null;
this.strideOut = null;
this.interpolation = null;
this.startTime = null;
this.endTime = null;
this.duration = 0;
};
Sampler.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
this.inputs.push( (new Input()).parse( child ) );
break;
default:
break;
}
}
return this;
};
Sampler.prototype.create = function () {
for ( var i = 0; i < this.inputs.length; i ++ ) {
var input = this.inputs[ i ];
var source = this.animation.source[ input.source ];
switch ( input.semantic ) {
case 'INPUT':
this.input = source.read();
break;
case 'OUTPUT':
this.output = source.read();
this.strideOut = source.accessor.stride;
break;
case 'INTERPOLATION':
this.interpolation = source.read();
break;
case 'IN_TANGENT':
break;
case 'OUT_TANGENT':
break;
default:
console.log(input.semantic);
break;
}
}
this.startTime = 0;
this.endTime = 0;
this.duration = 0;
if ( this.input.length ) {
this.startTime = 100000000;
this.endTime = -100000000;
for ( var i = 0; i < this.input.length; i ++ ) {
this.startTime = Math.min( this.startTime, this.input[ i ] );
this.endTime = Math.max( this.endTime, this.input[ i ] );
}
this.duration = this.endTime - this.startTime;
}
};
Sampler.prototype.getData = function ( type, ndx ) {
var data;
if ( type === 'matrix' && this.strideOut === 16 ) {
data = this.output[ ndx ];
} else if ( this.strideOut > 1 ) {
data = [];
ndx *= this.strideOut;
for ( var i = 0; i < this.strideOut; ++i ) {
data[ i ] = this.output[ ndx + i ];
}
if ( this.strideOut === 3 ) {
switch ( type ) {
case 'rotate':
case 'translate':
fixCoords( data, -1 );
break;
case 'scale':
fixCoords( data, 1 );
break;
}
} else if ( this.strideOut === 4 && type === 'matrix' ) {
fixCoords( data, -1 );
}
} else {
data = this.output[ ndx ];
}
return data;
};
function Key ( time ) {
this.targets = [];
this.time = time;
};
Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
this.targets.push( {
sid: fullSid,
member: member,
transform: transform,
data: data
} );
};
Key.prototype.apply = function ( opt_sid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
var target = this.targets[ i ];
if ( !opt_sid || target.sid === opt_sid ) {
target.transform.update( target.data, target.member );
}
}
};
Key.prototype.getTarget = function ( fullSid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
if ( this.targets[ i ].sid === fullSid ) {
return this.targets[ i ];
}
}
return null;
};
Key.prototype.hasTarget = function ( fullSid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
if ( this.targets[ i ].sid === fullSid ) {
return true;
}
}
return false;
};
// TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
Key.prototype.interpolate = function ( nextKey, time ) {
for ( var i = 0; i < this.targets.length; ++i ) {
var target = this.targets[ i ],
nextTarget = nextKey.getTarget( target.sid ),
data;
if ( target.transform.type !== 'matrix' && nextTarget ) {
var scale = ( time - this.time ) / ( nextKey.time - this.time ),
nextData = nextTarget.data,
prevData = target.data;
// check scale error
if ( scale < 0 || scale > 1 ) {
console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
scale = scale < 0 ? 0 : 1;
}
if ( prevData.length ) {
data = [];
for ( var j = 0; j < prevData.length; ++j ) {
data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
}
} else {
data = prevData + ( nextData - prevData ) * scale;
}
} else {
data = target.data;
}
target.transform.update( data, target.member );
}
};
// Camera
function Camera() {
this.id = "";
this.name = "";
this.technique = "";
};
Camera.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'optics':
this.parseOptics( child );
break;
}
}
return this;
};
Camera.prototype.parseOptics = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
var technique = element.childNodes[ i ];
for ( var j = 0; j < technique.childNodes.length; j ++ ) {
this.technique = technique.childNodes[ j ].nodeName;
if ( this.technique == 'perspective' ) {
var perspective = technique.childNodes[ j ];
for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
var param = perspective.childNodes[ k ];
switch ( param.nodeName ) {
case 'yfov':
this.yfov = param.textContent;
break;
case 'xfov':
this.xfov = param.textContent;
break;
case 'znear':
this.znear = param.textContent;
break;
case 'zfar':
this.zfar = param.textContent;
break;
case 'aspect_ratio':
this.aspect_ratio = param.textContent;
break;
}
}
} else if ( this.technique == 'orthographic' ) {
var orthographic = technique.childNodes[ j ];
for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
var param = orthographic.childNodes[ k ];
switch ( param.nodeName ) {
case 'xmag':
this.xmag = param.textContent;
break;
case 'ymag':
this.ymag = param.textContent;
break;
case 'znear':
this.znear = param.textContent;
break;
case 'zfar':
this.zfar = param.textContent;
break;
case 'aspect_ratio':
this.aspect_ratio = param.textContent;
break;
}
}
}
}
}
}
return this;
};
function InstanceCamera() {
this.url = "";
};
InstanceCamera.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
return this;
};
// Light
function Light() {
this.id = "";
this.name = "";
this.technique = "";
};
Light.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'technique_common':
this.parseTechnique( child );
break;
}
}
return this;
};
Light.prototype.parseTechnique = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'ambient':
case 'point':
case 'directional':
this.technique = child.nodeName;
for ( var k = 0; k < child.childNodes.length; k ++ ) {
var param = child.childNodes[ k ];
switch ( param.nodeName ) {
case 'color':
var vector = new THREE.Vector3().fromArray( _floats( param.textContent ) );
this.color = new THREE.Color().setRGB( vector.x, vector.y, vector.z );
break;
}
}
break;
}
}
};
function InstanceLight() {
this.url = "";
};
InstanceLight.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
return this;
};
function _source( element ) {
var id = element.getAttribute( 'id' );
if ( sources[ id ] != undefined ) {
return sources[ id ];
}
sources[ id ] = ( new Source(id )).parse( element );
return sources[ id ];
};
function _nsResolver( nsPrefix ) {
if ( nsPrefix == "dae" ) {
return "http://www.collada.org/2005/11/COLLADASchema";
}
return null;
};
function _bools( str ) {
var raw = _strings( str );
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
}
return data;
};
function _floats( str ) {
var raw = _strings(str);
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( parseFloat( raw[ i ] ) );
}
return data;
};
function _ints( str ) {
var raw = _strings( str );
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( parseInt( raw[ i ], 10 ) );
}
return data;
};
function _strings( str ) {
return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
};
function _trimString( str ) {
return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
};
function _attr_as_float( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return parseFloat( element.getAttribute( name ) );
} else {
return defaultValue;
}
};
function _attr_as_int( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return parseInt( element.getAttribute( name ), 10) ;
} else {
return defaultValue;
}
};
function _attr_as_string( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return element.getAttribute( name );
} else {
return defaultValue;
}
};
function _format_float( f, num ) {
if ( f === undefined ) {
var s = '0.';
while ( s.length < num + 2 ) {
s += '0';
}
return s;
}
num = num || 2;
var parts = f.toString().split( '.' );
parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
while( parts[ 1 ].length < num ) {
parts[ 1 ] += '0';
}
return parts.join( '.' );
};
function evaluateXPath( node, query ) {
var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
var inst = instances.iterateNext();
var result = [];
while ( inst ) {
result.push( inst );
inst = instances.iterateNext();
}
return result;
};
function extractDoubleSided( obj, element ) {
obj.doubleSided = false;
var node = COLLADA.evaluate( './/dae:extra//dae:double_sided', element, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( node ) {
node = node.iterateNext();
if ( node && parseInt( node.textContent, 10 ) === 1 ) {
obj.doubleSided = true;
}
}
};
// Up axis conversion
function setUpConversion() {
if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
upConversion = null;
} else {
switch ( colladaUp ) {
case 'X':
upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
break;
case 'Y':
upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
break;
case 'Z':
upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
break;
}
}
};
function fixCoords( data, sign ) {
if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
return;
}
switch ( upConversion ) {
case 'XtoY':
var tmp = data[ 0 ];
data[ 0 ] = sign * data[ 1 ];
data[ 1 ] = tmp;
break;
case 'XtoZ':
var tmp = data[ 2 ];
data[ 2 ] = data[ 1 ];
data[ 1 ] = data[ 0 ];
data[ 0 ] = tmp;
break;
case 'YtoX':
var tmp = data[ 0 ];
data[ 0 ] = data[ 1 ];
data[ 1 ] = sign * tmp;
break;
case 'YtoZ':
var tmp = data[ 1 ];
data[ 1 ] = sign * data[ 2 ];
data[ 2 ] = tmp;
break;
case 'ZtoX':
var tmp = data[ 0 ];
data[ 0 ] = data[ 1 ];
data[ 1 ] = data[ 2 ];
data[ 2 ] = tmp;
break;
case 'ZtoY':
var tmp = data[ 1 ];
data[ 1 ] = data[ 2 ];
data[ 2 ] = sign * tmp;
break;
}
};
function getConvertedVec3( data, offset ) {
var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
fixCoords( arr, -1 );
return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
};
function getConvertedMat4( data ) {
if ( options.convertUpAxis ) {
// First fix rotation and scale
// Columns first
var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
fixCoords( arr, -1 );
data[ 0 ] = arr[ 0 ];
data[ 4 ] = arr[ 1 ];
data[ 8 ] = arr[ 2 ];
arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
fixCoords( arr, -1 );
data[ 1 ] = arr[ 0 ];
data[ 5 ] = arr[ 1 ];
data[ 9 ] = arr[ 2 ];
arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
fixCoords( arr, -1 );
data[ 2 ] = arr[ 0 ];
data[ 6 ] = arr[ 1 ];
data[ 10 ] = arr[ 2 ];
// Rows second
arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
fixCoords( arr, -1 );
data[ 0 ] = arr[ 0 ];
data[ 1 ] = arr[ 1 ];
data[ 2 ] = arr[ 2 ];
arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
fixCoords( arr, -1 );
data[ 4 ] = arr[ 0 ];
data[ 5 ] = arr[ 1 ];
data[ 6 ] = arr[ 2 ];
arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
fixCoords( arr, -1 );
data[ 8 ] = arr[ 0 ];
data[ 9 ] = arr[ 1 ];
data[ 10 ] = arr[ 2 ];
// Now fix translation
arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
fixCoords( arr, -1 );
data[ 3 ] = arr[ 0 ];
data[ 7 ] = arr[ 1 ];
data[ 11 ] = arr[ 2 ];
}
return new THREE.Matrix4(
data[0], data[1], data[2], data[3],
data[4], data[5], data[6], data[7],
data[8], data[9], data[10], data[11],
data[12], data[13], data[14], data[15]
);
};
function getConvertedIndex( index ) {
if ( index > -1 && index < 3 ) {
var members = ['X', 'Y', 'Z'],
indices = { X: 0, Y: 1, Z: 2 };
index = getConvertedMember( members[ index ] );
index = indices[ index ];
}
return index;
};
function getConvertedMember( member ) {
if ( options.convertUpAxis ) {
switch ( member ) {
case 'X':
switch ( upConversion ) {
case 'XtoY':
case 'XtoZ':
case 'YtoX':
member = 'Y';
break;
case 'ZtoX':
member = 'Z';
break;
}
break;
case 'Y':
switch ( upConversion ) {
case 'XtoY':
case 'YtoX':
case 'ZtoX':
member = 'X';
break;
case 'XtoZ':
case 'YtoZ':
case 'ZtoY':
member = 'Z';
break;
}
break;
case 'Z':
switch ( upConversion ) {
case 'XtoZ':
member = 'X';
break;
case 'YtoZ':
case 'ZtoX':
case 'ZtoY':
member = 'Y';
break;
}
break;
}
}
return member;
};
return {
load: load,
parse: parse,
setPreferredShading: setPreferredShading,
applySkin: applySkin,
geometries : geometries,
options: options
};
};<|fim▁end|> | Node.prototype.updateMatrix = function () {
|
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from django import forms
from ncdjango.interfaces.arcgis.form_fields import SrField<|fim▁hole|>class PointForm(forms.Form):
x = forms.FloatField()
y = forms.FloatField()
projection = SrField()<|fim▁end|> | |
<|file_name|>kallisto_quant.py<|end_file_name|><|fim▁begin|>"""
created 09/05/17
For executation of the kallisto quantification step
To be run with three arguements
* basedir - top level output directory
* input directory - contains folders with .fastq.gz files
* max_threads - how many threads to allocate to kallisto
Returns kallisto quantifications and associated log files to a directory
within the top level output dir.
An example pair of files is:
25uM_1_R1_trimmed_1P.fastq.gz
25uM_1_R1_trimmed_2P.fastq.gz
Outputs kallisto files for each read pair and
associated log files in a nested directory
"""
# --- packages
import os
import sys
from subprocess import call
# --- variables using sys.argv
basedir = sys.argv[1]
inputdirectory = sys.argv[2]
max_threads = sys.argv[3]
processed = basedir + "kallisto/"
# --- functions
def kallisto_call(read1):
"""
l is the lock object
read1 is the forward read
calls kallisto quant for the read pair specified by the arguements
Rewrite this to be more specific for a single read pair
so it can be parallelised
also review how to actually do this... current way does not seem to.
"""
dividing = read1.split(".")
basename = dividing[0].replace("_1P", "")
read2 = read1.replace("1P", "2P")
call(
"kallisto quant -i " + basedir +
"transcriptome_kallisto.idx -t " +
max_threads + " -o " + processed + basename + " -b 100 " +<|fim▁hole|> inputdirectory + read1 + " " + inputdirectory + read2, shell=True)
# --- __main__ call
if __name__ == "__main__":
# --- check dirs and create if neccessary
if not os.path.exists(processed):
os.makedirs(processed)
# --- create list of read1 pair file names
read_list = []
for fname in os.listdir(inputdirectory):
if "1P" in fname:
read_list.append(fname)
# --- call kallisto_call on each read pair in parallel
for read in read_list:
kallisto_call(read)<|fim▁end|> | |
<|file_name|>json.rs<|end_file_name|><|fim▁begin|>// Rust JSON serialization library.
// Copyright (c) 2011 Google Inc.
#![forbid(non_camel_case_types)]
#![allow(missing_docs)]
//! JSON parsing and serialization
//!
//! # What is JSON?
//!
//! JSON (JavaScript Object Notation) is a way to write data in Javascript.
//! Like XML, it allows to encode structured data in a text format that can be easily read by humans
//! Its simple syntax and native compatibility with JavaScript have made it a widely used format.
//!
//! Data types that can be encoded are JavaScript types (see the `Json` enum for more details):
//!
//! * `Boolean`: equivalent to rust's `bool`
//! * `Number`: equivalent to rust's `f64`
//! * `String`: equivalent to rust's `String`
//! * `Array`: equivalent to rust's `Vec<T>`, but also allowing objects of different types in the
//! same array
//! * `Object`: equivalent to rust's `BTreeMap<String, json::Json>`
//! * `Null`
//!
//! An object is a series of string keys mapping to values, in `"key": value` format.
//! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }).
//! A simple JSON document encoding a person, their age, address and phone numbers could look like
//!
//! ```json
//! {
//! "FirstName": "John",
//! "LastName": "Doe",
//! "Age": 43,
//! "Address": {
//! "Street": "Downing Street 10",
//! "City": "London",
//! "Country": "Great Britain"
//! },
//! "PhoneNumbers": [
//! "+44 1234567",
//! "+44 2345678"
//! ]
//! }
//! ```
//!
//! # Rust Type-based Encoding and Decoding
//!
//! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via
//! the serialization API.
//! To be able to encode a piece of data, it must implement the `serialize::Encodable` trait.
//! To be able to decode a piece of data, it must implement the `serialize::Decodable` trait.
//! The Rust compiler provides an annotation to automatically generate the code for these traits:
//! `#[derive(Decodable, Encodable)]`
//!
//! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects.
//! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value.
//! A `json::Json` value can be encoded as a string or buffer using the functions described above.
//! You can also use the `json::Encoder` object, which implements the `Encoder` trait.
//!
//! When using `ToJson` the `Encodable` trait implementation is not mandatory.
//!
//! # Examples of use
//!
//! ## Using Autoserialization
//!
//! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the
//! serialization API, using the derived serialization code.
//!
//! ```rust
//! # #![feature(rustc_private)]
//! use rustc_macros::{Decodable, Encodable};
//! use rustc_serialize::json;
//!
//! // Automatically generate `Decodable` and `Encodable` trait implementations
//! #[derive(Decodable, Encodable)]
//! pub struct TestStruct {
//! data_int: u8,
//! data_str: String,
//! data_vector: Vec<u8>,
//! }
//!
//! let object = TestStruct {
//! data_int: 1,
//! data_str: "homura".to_string(),
//! data_vector: vec![2,3,4,5],
//! };
//!
//! // Serialize using `json::encode`
//! let encoded = json::encode(&object).unwrap();
//!
//! // Deserialize using `json::decode`
//! let decoded: TestStruct = json::decode(&encoded[..]).unwrap();
//! ```
//!
//! ## Using the `ToJson` trait
//!
//! The examples above use the `ToJson` trait to generate the JSON string, which is required
//! for custom mappings.
//!
//! ### Simple example of `ToJson` usage
//!
//! ```rust
//! # #![feature(rustc_private)]
//! use rustc_macros::Encodable;
//! use rustc_serialize::json::{self, ToJson, Json};
//!
//! // A custom data structure
//! struct ComplexNum {
//! a: f64,
//! b: f64,
//! }
//!
//! // JSON value representation
//! impl ToJson for ComplexNum {
//! fn to_json(&self) -> Json {
//! Json::String(format!("{}+{}i", self.a, self.b))
//! }
//! }
//!
//! // Only generate `Encodable` trait implementation
//! #[derive(Encodable)]
//! pub struct ComplexNumRecord {
//! uid: u8,
//! dsc: String,
//! val: Json,
//! }
//!
//! let num = ComplexNum { a: 0.0001, b: 12.539 };
//! let data: String = json::encode(&ComplexNumRecord{
//! uid: 1,
//! dsc: "test".to_string(),
//! val: num.to_json(),
//! }).unwrap();
//! println!("data: {}", data);
//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539i"};
//! ```
//!
//! ### Verbose example of `ToJson` usage
//!
//! ```rust
//! # #![feature(rustc_private)]
//! use rustc_macros::Decodable;
//! use std::collections::BTreeMap;
//! use rustc_serialize::json::{self, Json, ToJson};
//!
//! // Only generate `Decodable` trait implementation
//! #[derive(Decodable)]
//! pub struct TestStruct {
//! data_int: u8,
//! data_str: String,
//! data_vector: Vec<u8>,
//! }
//!
//! // Specify encoding method manually
//! impl ToJson for TestStruct {
//! fn to_json(&self) -> Json {
//! let mut d = BTreeMap::new();
//! // All standard types implement `to_json()`, so use it
//! d.insert("data_int".to_string(), self.data_int.to_json());
//! d.insert("data_str".to_string(), self.data_str.to_json());
//! d.insert("data_vector".to_string(), self.data_vector.to_json());
//! Json::Object(d)
//! }
//! }
//!
//! // Serialize using `ToJson`
//! let input_data = TestStruct {
//! data_int: 1,
//! data_str: "madoka".to_string(),
//! data_vector: vec![2,3,4,5],
//! };
//! let json_obj: Json = input_data.to_json();
//! let json_str: String = json_obj.to_string();
//!
//! // Deserialize like before
//! let decoded: TestStruct = json::decode(&json_str).unwrap();
//! ```
use self::DecoderError::*;
use self::ErrorCode::*;
use self::InternalStackElement::*;
use self::JsonEvent::*;
use self::ParserError::*;
use self::ParserState::*;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::io;
use std::io::prelude::*;
use std::mem::swap;
use std::num::FpCategory as Fp;
use std::ops::Index;
use std::str::FromStr;
use std::string;
use std::{char, fmt, str};
use crate::Encodable;
/// Represents a json value
#[derive(Clone, PartialEq, PartialOrd, Debug)]
pub enum Json {
I64(i64),
U64(u64),
F64(f64),
String(string::String),
Boolean(bool),
Array(self::Array),
Object(self::Object),
Null,
}
pub type Array = Vec<Json>;
pub type Object = BTreeMap<string::String, Json>;
pub struct PrettyJson<'a> {
inner: &'a Json,
}
pub struct AsJson<'a, T> {
inner: &'a T,
}
pub struct AsPrettyJson<'a, T> {
inner: &'a T,
indent: Option<usize>,
}
/// The errors that can arise while parsing a JSON stream.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ErrorCode {
InvalidSyntax,
InvalidNumber,
EOFWhileParsingObject,
EOFWhileParsingArray,
EOFWhileParsingValue,
EOFWhileParsingString,
KeyMustBeAString,
ExpectedColon,
TrailingCharacters,
TrailingComma,
InvalidEscape,
InvalidUnicodeCodePoint,
LoneLeadingSurrogateInHexEscape,
UnexpectedEndOfHexEscape,
UnrecognizedHex,
NotFourDigit,
NotUtf8,
}
#[derive(Clone, PartialEq, Debug)]
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, usize, usize),
IoError(io::ErrorKind, String),
}
// Builder and Parser have the same errors.
pub type BuilderError = ParserError;
#[derive(Clone, PartialEq, Debug)]
pub enum DecoderError {
ParseError(ParserError),
ExpectedError(string::String, string::String),
MissingFieldError(string::String),
UnknownVariantError(string::String),
ApplicationError(string::String),
}
#[derive(Copy, Clone, Debug)]
pub enum EncoderError {
FmtError(fmt::Error),
BadHashmapKey,
}
/// Returns a readable error string for a given error code.
pub fn error_str(error: ErrorCode) -> &'static str {
match error {
InvalidSyntax => "invalid syntax",
InvalidNumber => "invalid number",
EOFWhileParsingObject => "EOF While parsing object",
EOFWhileParsingArray => "EOF While parsing array",
EOFWhileParsingValue => "EOF While parsing value",
EOFWhileParsingString => "EOF While parsing string",
KeyMustBeAString => "key must be a string",
ExpectedColon => "expected `:`",
TrailingCharacters => "trailing characters",
TrailingComma => "trailing comma",
InvalidEscape => "invalid escape",
UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)",
NotFourDigit => "invalid \\u{ esc}ape (not four digits)",
NotUtf8 => "contents not utf-8",
InvalidUnicodeCodePoint => "invalid Unicode code point",
LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape",
UnexpectedEndOfHexEscape => "unexpected end of hex escape",
}
}
/// Shortcut function to decode a JSON `&str` into an object
pub fn decode<T: crate::Decodable<Decoder>>(s: &str) -> DecodeResult<T> {
let json = match from_str(s) {
Ok(x) => x,
Err(e) => return Err(ParseError(e)),
};
let mut decoder = Decoder::new(json);
crate::Decodable::decode(&mut decoder)
}
/// Shortcut function to encode a `T` into a JSON `String`
pub fn encode<T: for<'r> crate::Encodable<Encoder<'r>>>(
object: &T,
) -> Result<string::String, EncoderError> {
let mut s = String::new();
{
let mut encoder = Encoder::new(&mut s);
object.encode(&mut encoder)?;
}
Ok(s)
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
error_str(*self).fmt(f)
}
}
fn io_error_to_error(io: io::Error) -> ParserError {
IoError(io.kind(), io.to_string())
}
impl fmt::Display for ParserError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// FIXME this should be a nicer error
fmt::Debug::fmt(self, f)
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// FIXME this should be a nicer error
fmt::Debug::fmt(self, f)
}
}
impl std::error::Error for DecoderError {}
impl fmt::Display for EncoderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// FIXME this should be a nicer error
fmt::Debug::fmt(self, f)
}
}
impl std::error::Error for EncoderError {}
impl From<fmt::Error> for EncoderError {
/// Converts a [`fmt::Error`] into `EncoderError`
///
/// This conversion does not allocate memory.
fn from(err: fmt::Error) -> EncoderError {
EncoderError::FmtError(err)
}
}
pub type EncodeResult = Result<(), EncoderError>;
pub type DecodeResult<T> = Result<T, DecoderError>;
fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult {
wr.write_str("\"")?;
let mut start = 0;
for (i, byte) in v.bytes().enumerate() {
let escaped = match byte {
b'"' => "\\\"",
b'\\' => "\\\\",
b'\x00' => "\\u0000",
b'\x01' => "\\u0001",
b'\x02' => "\\u0002",
b'\x03' => "\\u0003",
b'\x04' => "\\u0004",
b'\x05' => "\\u0005",
b'\x06' => "\\u0006",
b'\x07' => "\\u0007",
b'\x08' => "\\b",
b'\t' => "\\t",
b'\n' => "\\n",
b'\x0b' => "\\u000b",
b'\x0c' => "\\f",
b'\r' => "\\r",
b'\x0e' => "\\u000e",
b'\x0f' => "\\u000f",
b'\x10' => "\\u0010",
b'\x11' => "\\u0011",
b'\x12' => "\\u0012",
b'\x13' => "\\u0013",
b'\x14' => "\\u0014",
b'\x15' => "\\u0015",
b'\x16' => "\\u0016",
b'\x17' => "\\u0017",
b'\x18' => "\\u0018",
b'\x19' => "\\u0019",
b'\x1a' => "\\u001a",
b'\x1b' => "\\u001b",
b'\x1c' => "\\u001c",
b'\x1d' => "\\u001d",
b'\x1e' => "\\u001e",
b'\x1f' => "\\u001f",
b'\x7f' => "\\u007f",
_ => {
continue;
}
};
if start < i {
wr.write_str(&v[start..i])?;
}
wr.write_str(escaped)?;
start = i + 1;
}
if start != v.len() {
wr.write_str(&v[start..])?;
}
wr.write_str("\"")?;
Ok(())
}
fn escape_char(writer: &mut dyn fmt::Write, v: char) -> EncodeResult {
escape_str(writer, v.encode_utf8(&mut [0; 4]))
}
fn spaces(wr: &mut dyn fmt::Write, mut n: usize) -> EncodeResult {
const BUF: &str = " ";
while n >= BUF.len() {
wr.write_str(BUF)?;
n -= BUF.len();
}
if n > 0 {
wr.write_str(&BUF[..n])?;
}
Ok(())
}
fn fmt_number_or_null(v: f64) -> string::String {
match v.classify() {
Fp::Nan | Fp::Infinite => string::String::from("null"),
_ if v.fract() != 0f64 => v.to_string(),
_ => v.to_string() + ".0",
}
}
/// A structure for implementing serialization to JSON.
pub struct Encoder<'a> {
writer: &'a mut (dyn fmt::Write + 'a),
is_emitting_map_key: bool,
}
impl<'a> Encoder<'a> {
/// Creates a new JSON encoder whose output will be written to the writer
/// specified.
pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> {
Encoder { writer, is_emitting_map_key: false }
}
}
macro_rules! emit_enquoted_if_mapkey {
($enc:ident,$e:expr) => {{
if $enc.is_emitting_map_key {
write!($enc.writer, "\"{}\"", $e)?;
} else {
write!($enc.writer, "{}", $e)?;
}
Ok(())
}};
}
impl<'a> crate::Encoder for Encoder<'a> {
type Error = EncoderError;
fn emit_unit(&mut self) -> EncodeResult {
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
write!(self.writer, "null")?;
Ok(())
}
fn emit_usize(&mut self, v: usize) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u128(&mut self, v: u128) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u64(&mut self, v: u64) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u32(&mut self, v: u32) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u16(&mut self, v: u16) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u8(&mut self, v: u8) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_isize(&mut self, v: isize) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i128(&mut self, v: i128) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i64(&mut self, v: i64) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i32(&mut self, v: i32) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i16(&mut self, v: i16) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i8(&mut self, v: i8) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_bool(&mut self, v: bool) -> EncodeResult {
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if v {
write!(self.writer, "true")?;
} else {
write!(self.writer, "false")?;
}
Ok(())
}
fn emit_f64(&mut self, v: f64) -> EncodeResult {
emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
}
fn emit_f32(&mut self, v: f32) -> EncodeResult {
self.emit_f64(f64::from(v))
}
fn emit_char(&mut self, v: char) -> EncodeResult {
escape_char(self.writer, v)
}
fn emit_str(&mut self, v: &str) -> EncodeResult {
escape_str(self.writer, v)
}
fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
for &c in s.iter() {
self.emit_u8(c)?;
}
Ok(())
}
fn emit_enum<F>(&mut self, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
f(self)
}
fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
// enums are encoded as strings or objects
// Bunny => "Bunny"
// Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]}
if cnt == 0 {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
write!(self.writer, "{{\"variant\":")?;
escape_str(self.writer, name)?;
write!(self.writer, ",\"fields\":[")?;
f(self)?;
write!(self.writer, "]}}")?;
Ok(())
}
}
fn emit_enum_variant_arg<F>(&mut self, first: bool, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if !first {
write!(self.writer, ",")?;
}
f(self)
}
fn emit_struct<F>(&mut self, _: bool, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
write!(self.writer, "{{")?;
f(self)?;
write!(self.writer, "}}")?;
Ok(())
}
fn emit_struct_field<F>(&mut self, name: &str, first: bool, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if !first {
write!(self.writer, ",")?;
}
escape_str(self.writer, name)?;
write!(self.writer, ":")?;
f(self)
}
fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
self.emit_seq(len, f)
}
fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
self.emit_seq_elt(idx, f)
}
fn emit_option<F>(&mut self, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
f(self)
}
fn emit_option_none(&mut self) -> EncodeResult {
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
self.emit_unit()
}
fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
f(self)
}
fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
write!(self.writer, "[")?;
f(self)?;
write!(self.writer, "]")?;
Ok(())
}
fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if idx != 0 {
write!(self.writer, ",")?;
}
f(self)
}
fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
write!(self.writer, "{{")?;
f(self)?;
write!(self.writer, "}}")?;
Ok(())
}
fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if idx != 0 {
write!(self.writer, ",")?
}
self.is_emitting_map_key = true;
f(self)?;
self.is_emitting_map_key = false;
Ok(())
}
fn emit_map_elt_val<F>(&mut self, f: F) -> EncodeResult
where
F: FnOnce(&mut Encoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
write!(self.writer, ":")?;
f(self)
}
}
/// Another encoder for JSON, but prints out human-readable JSON instead of
/// compact data
pub struct PrettyEncoder<'a> {
writer: &'a mut (dyn fmt::Write + 'a),
curr_indent: usize,
indent: usize,
is_emitting_map_key: bool,
}
impl<'a> PrettyEncoder<'a> {
/// Creates a new encoder whose output will be written to the specified writer
pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> {
PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false }
}
/// Sets the number of spaces to indent for each level.
/// This is safe to set during encoding.
pub fn set_indent(&mut self, indent: usize) {
// self.indent very well could be 0 so we need to use checked division.
let level = self.curr_indent.checked_div(self.indent).unwrap_or(0);
self.indent = indent;
self.curr_indent = level * self.indent;
}
}
impl<'a> crate::Encoder for PrettyEncoder<'a> {
type Error = EncoderError;
fn emit_unit(&mut self) -> EncodeResult {
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
write!(self.writer, "null")?;
Ok(())
}
fn emit_usize(&mut self, v: usize) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u128(&mut self, v: u128) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u64(&mut self, v: u64) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u32(&mut self, v: u32) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u16(&mut self, v: u16) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_u8(&mut self, v: u8) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_isize(&mut self, v: isize) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i128(&mut self, v: i128) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i64(&mut self, v: i64) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i32(&mut self, v: i32) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i16(&mut self, v: i16) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_i8(&mut self, v: i8) -> EncodeResult {
emit_enquoted_if_mapkey!(self, v)
}
fn emit_bool(&mut self, v: bool) -> EncodeResult {
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if v {
write!(self.writer, "true")?;
} else {
write!(self.writer, "false")?;
}
Ok(())
}
fn emit_f64(&mut self, v: f64) -> EncodeResult {
emit_enquoted_if_mapkey!(self, fmt_number_or_null(v))
}
fn emit_f32(&mut self, v: f32) -> EncodeResult {
self.emit_f64(f64::from(v))
}
fn emit_char(&mut self, v: char) -> EncodeResult {
escape_char(self.writer, v)
}
fn emit_str(&mut self, v: &str) -> EncodeResult {
escape_str(self.writer, v)
}
fn emit_raw_bytes(&mut self, s: &[u8]) -> Result<(), Self::Error> {
for &c in s.iter() {
self.emit_u8(c)?;
}
Ok(())
}
fn emit_enum<F>(&mut self, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
f(self)
}
fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if cnt == 0 {
escape_str(self.writer, name)
} else {
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
writeln!(self.writer, "{{")?;
self.curr_indent += self.indent;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "\"variant\": ")?;
escape_str(self.writer, name)?;
writeln!(self.writer, ",")?;
spaces(self.writer, self.curr_indent)?;
writeln!(self.writer, "\"fields\": [")?;
self.curr_indent += self.indent;
f(self)?;
self.curr_indent -= self.indent;
writeln!(self.writer)?;
spaces(self.writer, self.curr_indent)?;
self.curr_indent -= self.indent;
writeln!(self.writer, "]")?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
Ok(())
}
}
fn emit_enum_variant_arg<F>(&mut self, first: bool, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if !first {
writeln!(self.writer, ",")?;
}
spaces(self.writer, self.curr_indent)?;
f(self)
}
fn emit_struct<F>(&mut self, no_fields: bool, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if no_fields {
write!(self.writer, "{{}}")?;
} else {
write!(self.writer, "{{")?;
self.curr_indent += self.indent;
f(self)?;
self.curr_indent -= self.indent;
writeln!(self.writer)?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
}
Ok(())
}
fn emit_struct_field<F>(&mut self, name: &str, first: bool, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if first {
writeln!(self.writer)?;
} else {
writeln!(self.writer, ",")?;
}
spaces(self.writer, self.curr_indent)?;
escape_str(self.writer, name)?;
write!(self.writer, ": ")?;
f(self)
}
fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
self.emit_seq(len, f)
}
fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
self.emit_seq_elt(idx, f)
}
fn emit_option<F>(&mut self, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
f(self)
}
fn emit_option_none(&mut self) -> EncodeResult {
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
self.emit_unit()
}
fn emit_option_some<F>(&mut self, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
f(self)
}
fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if len == 0 {
write!(self.writer, "[]")?;
} else {
write!(self.writer, "[")?;
self.curr_indent += self.indent;
f(self)?;
self.curr_indent -= self.indent;
writeln!(self.writer)?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "]")?;
}
Ok(())
}
fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if idx == 0 {
writeln!(self.writer)?;
} else {
writeln!(self.writer, ",")?;
}
spaces(self.writer, self.curr_indent)?;
f(self)
}
fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if len == 0 {
write!(self.writer, "{{}}")?;
} else {
write!(self.writer, "{{")?;
self.curr_indent += self.indent;
f(self)?;
self.curr_indent -= self.indent;
writeln!(self.writer)?;
spaces(self.writer, self.curr_indent)?;
write!(self.writer, "}}")?;
}
Ok(())
}
fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
if idx == 0 {
writeln!(self.writer)?;
} else {
writeln!(self.writer, ",")?;
}
spaces(self.writer, self.curr_indent)?;
self.is_emitting_map_key = true;
f(self)?;
self.is_emitting_map_key = false;
Ok(())
}
fn emit_map_elt_val<F>(&mut self, f: F) -> EncodeResult
where
F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult,
{
if self.is_emitting_map_key {
return Err(EncoderError::BadHashmapKey);
}
write!(self.writer, ": ")?;
f(self)
}
}
impl<E: crate::Encoder> Encodable<E> for Json {
fn encode(&self, e: &mut E) -> Result<(), E::Error> {
match *self {
Json::I64(v) => v.encode(e),
Json::U64(v) => v.encode(e),
Json::F64(v) => v.encode(e),
Json::String(ref v) => v.encode(e),
Json::Boolean(v) => v.encode(e),
Json::Array(ref v) => v.encode(e),
Json::Object(ref v) => v.encode(e),
Json::Null => e.emit_unit(),
}
}
}
/// Creates an `AsJson` wrapper which can be used to print a value as JSON
/// on-the-fly via `write!`
pub fn as_json<T>(t: &T) -> AsJson<'_, T> {
AsJson { inner: t }
}
/// Creates an `AsPrettyJson` wrapper which can be used to print a value as JSON
/// on-the-fly via `write!`
pub fn as_pretty_json<T>(t: &T) -> AsPrettyJson<'_, T> {
AsPrettyJson { inner: t, indent: None }
}
impl Json {
/// Borrow this json object as a pretty object to generate a pretty
/// representation for it via `Display`.
pub fn pretty(&self) -> PrettyJson<'_> {
PrettyJson { inner: self }
}
/// If the Json value is an Object, returns the value associated with the provided key.
/// Otherwise, returns None.
pub fn find(&self, key: &str) -> Option<&Json> {
match *self {
Json::Object(ref map) => map.get(key),
_ => None,
}
}
/// If the Json value is an Object, deletes the value associated with the
/// provided key from the Object and returns it. Otherwise, returns None.
pub fn remove_key(&mut self, key: &str) -> Option<Json> {
match *self {
Json::Object(ref mut map) => map.remove(key),
_ => None,
}
}
/// Attempts to get a nested Json Object for each key in `keys`.
/// If any key is found not to exist, `find_path` will return `None`.
/// Otherwise, it will return the Json value associated with the final key.
pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> {
let mut target = self;
for key in keys {
target = target.find(*key)?;
}
Some(target)
}
/// If the Json value is an Object, performs a depth-first search until
/// a value associated with the provided key is found. If no value is found
/// or the Json value is not an Object, returns `None`.
pub fn search(&self, key: &str) -> Option<&Json> {
match *self {
Json::Object(ref map) => match map.get(key) {
Some(json_value) => Some(json_value),
None => {
for v in map.values() {
match v.search(key) {
x if x.is_some() => return x,
_ => (),
}
}
None
}
},
_ => None,
}
}
/// Returns `true` if the Json value is an `Object`.
pub fn is_object(&self) -> bool {
self.as_object().is_some()
}
/// If the Json value is an `Object`, returns the associated `BTreeMap`;
/// returns `None` otherwise.
pub fn as_object(&self) -> Option<&Object> {
match *self {
Json::Object(ref map) => Some(map),
_ => None,
}
}
/// Returns `true` if the Json value is an `Array`.
pub fn is_array(&self) -> bool {
self.as_array().is_some()
}
/// If the Json value is an `Array`, returns the associated vector;
/// returns `None` otherwise.
pub fn as_array(&self) -> Option<&Array> {
match *self {
Json::Array(ref array) => Some(&*array),
_ => None,
}
}
/// Returns `true` if the Json value is a `String`.
pub fn is_string(&self) -> bool {
self.as_string().is_some()
}
/// If the Json value is a `String`, returns the associated `str`;
/// returns `None` otherwise.
pub fn as_string(&self) -> Option<&str> {
match *self {
Json::String(ref s) => Some(&s[..]),
_ => None,
}
}
/// Returns `true` if the Json value is a `Number`.
pub fn is_number(&self) -> bool {
matches!(*self, Json::I64(_) | Json::U64(_) | Json::F64(_))
}
/// Returns `true` if the Json value is an `i64`.
pub fn is_i64(&self) -> bool {
matches!(*self, Json::I64(_))
}
/// Returns `true` if the Json value is a `u64`.
pub fn is_u64(&self) -> bool {
matches!(*self, Json::U64(_))
}
/// Returns `true` if the Json value is a `f64`.
pub fn is_f64(&self) -> bool {
matches!(*self, Json::F64(_))
}
/// If the Json value is a number, returns or cast it to an `i64`;
/// returns `None` otherwise.
pub fn as_i64(&self) -> Option<i64> {
match *self {
Json::I64(n) => Some(n),
Json::U64(n) => Some(n as i64),
_ => None,
}
}
/// If the Json value is a number, returns or cast it to a `u64`;
/// returns `None` otherwise.
pub fn as_u64(&self) -> Option<u64> {
match *self {
Json::I64(n) => Some(n as u64),
Json::U64(n) => Some(n),
_ => None,
}
}
/// If the Json value is a number, returns or cast it to a `f64`;
/// returns `None` otherwise.
pub fn as_f64(&self) -> Option<f64> {
match *self {
Json::I64(n) => Some(n as f64),
Json::U64(n) => Some(n as f64),
Json::F64(n) => Some(n),
_ => None,
}
}
/// Returns `true` if the Json value is a `Boolean`.
pub fn is_boolean(&self) -> bool {
self.as_boolean().is_some()
}
/// If the Json value is a `Boolean`, returns the associated `bool`;
/// returns `None` otherwise.
pub fn as_boolean(&self) -> Option<bool> {
match *self {
Json::Boolean(b) => Some(b),
_ => None,
}
}
/// Returns `true` if the Json value is a `Null`.
pub fn is_null(&self) -> bool {
self.as_null().is_some()
}
/// If the Json value is a `Null`, returns `()`;
/// returns `None` otherwise.
pub fn as_null(&self) -> Option<()> {
match *self {
Json::Null => Some(()),
_ => None,
}
}
}
impl<'a> Index<&'a str> for Json {
type Output = Json;
fn index(&self, idx: &'a str) -> &Json {
self.find(idx).unwrap()
}
}
impl Index<usize> for Json {
type Output = Json;
fn index(&self, idx: usize) -> &Json {
match *self {
Json::Array(ref v) => &v[idx],
_ => panic!("can only index Json with usize if it is an array"),
}
}
}
/// The output of the streaming parser.
#[derive(PartialEq, Clone, Debug)]
pub enum JsonEvent {
ObjectStart,
ObjectEnd,
ArrayStart,
ArrayEnd,
BooleanValue(bool),
I64Value(i64),
U64Value(u64),
F64Value(f64),
StringValue(string::String),
NullValue,
Error(ParserError),
}
#[derive(PartialEq, Debug)]
enum ParserState {
// Parse a value in an array, true means first element.
ParseArray(bool),
// Parse ',' or ']' after an element in an array.
ParseArrayComma,
// Parse a key:value in an object, true means first element.
ParseObject(bool),
// Parse ',' or ']' after an element in an object.
ParseObjectComma,
// Initial state.
ParseStart,
// Expecting the stream to end.
ParseBeforeFinish,
// Parsing can't continue.
ParseFinished,
}
/// A Stack represents the current position of the parser in the logical
/// structure of the JSON stream.
///
/// An example is `foo.bar[3].x`.
#[derive(Default)]
pub struct Stack {
stack: Vec<InternalStackElement>,
str_buffer: Vec<u8>,
}
/// StackElements compose a Stack.
///
/// As an example, `StackElement::Key("foo")`, `StackElement::Key("bar")`,
/// `StackElement::Index(3)`, and `StackElement::Key("x")` are the
/// StackElements composing the stack that represents `foo.bar[3].x`.
#[derive(PartialEq, Clone, Debug)]
pub enum StackElement<'l> {
Index(u32),
Key(&'l str),
}
// Internally, Key elements are stored as indices in a buffer to avoid
// allocating a string for every member of an object.
#[derive(PartialEq, Clone, Debug)]
enum InternalStackElement {
InternalIndex(u32),
InternalKey(u16, u16), // start, size
}
impl Stack {
pub fn new() -> Stack {
Self::default()
}
/// Returns The number of elements in the Stack.
pub fn len(&self) -> usize {
self.stack.len()
}
/// Returns `true` if the stack is empty.
pub fn is_empty(&self) -> bool {
self.stack.is_empty()
}
/// Provides access to the StackElement at a given index.
/// lower indices are at the bottom of the stack while higher indices are
/// at the top.
pub fn get(&self, idx: usize) -> StackElement<'_> {
match self.stack[idx] {
InternalIndex(i) => StackElement::Index(i),
InternalKey(start, size) => StackElement::Key(
str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize])
.unwrap(),
),
}
}
/// Compares this stack with an array of StackElement<'_>s.
pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool {
if self.stack.len() != rhs.len() {
return false;
}
for (i, r) in rhs.iter().enumerate() {
if self.get(i) != *r {
return false;
}
}
true
}
/// Returns `true` if the bottom-most elements of this stack are the same as
/// the ones passed as parameter.
pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool {
if self.stack.len() < rhs.len() {
return false;
}
for (i, r) in rhs.iter().enumerate() {
if self.get(i) != *r {
return false;
}
}
true
}
/// Returns `true` if the top-most elements of this stack are the same as
/// the ones passed as parameter.
pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool {
if self.stack.len() < rhs.len() {
return false;
}
let offset = self.stack.len() - rhs.len();
for (i, r) in rhs.iter().enumerate() {
if self.get(i + offset) != *r {
return false;
}
}
true
}
/// Returns the top-most element (if any).
pub fn top(&self) -> Option<StackElement<'_>> {
match self.stack.last() {
None => None,
Some(&InternalIndex(i)) => Some(StackElement::Index(i)),
Some(&InternalKey(start, size)) => Some(StackElement::Key(
str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(),
)),
}
}
// Used by Parser to insert StackElement::Key elements at the top of the stack.
fn push_key(&mut self, key: string::String) {
self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16));
self.str_buffer.extend(key.as_bytes());
}
// Used by Parser to insert StackElement::Index elements at the top of the stack.
fn push_index(&mut self, index: u32) {
self.stack.push(InternalIndex(index));
}
// Used by Parser to remove the top-most element of the stack.
fn pop(&mut self) {
assert!(!self.is_empty());
match *self.stack.last().unwrap() {
InternalKey(_, sz) => {
let new_size = self.str_buffer.len() - sz as usize;
self.str_buffer.truncate(new_size);
}
InternalIndex(_) => {}
}
self.stack.pop();
}
// Used by Parser to test whether the top-most element is an index.
fn last_is_index(&self) -> bool {
matches!(self.stack.last(), Some(InternalIndex(_)))
}
// Used by Parser to increment the index of the top-most element.
fn bump_index(&mut self) {
let len = self.stack.len();
let idx = match *self.stack.last().unwrap() {
InternalIndex(i) => i + 1,
_ => {
panic!();
}
};
self.stack[len - 1] = InternalIndex(idx);
}
}<|fim▁hole|>
/// A streaming JSON parser implemented as an iterator of JsonEvent, consuming
/// an iterator of char.
pub struct Parser<T> {
rdr: T,
ch: Option<char>,
line: usize,
col: usize,
// We maintain a stack representing where we are in the logical structure
// of the JSON stream.
stack: Stack,
// A state machine is kept to make it possible to interrupt and resume parsing.
state: ParserState,
}
impl<T: Iterator<Item = char>> Iterator for Parser<T> {
type Item = JsonEvent;
fn next(&mut self) -> Option<JsonEvent> {
if self.state == ParseFinished {
return None;
}
if self.state == ParseBeforeFinish {
self.parse_whitespace();
// Make sure there is no trailing characters.
if self.eof() {
self.state = ParseFinished;
return None;
} else {
return Some(self.error_event(TrailingCharacters));
}
}
Some(self.parse())
}
}
impl<T: Iterator<Item = char>> Parser<T> {
/// Creates the JSON parser.
pub fn new(rdr: T) -> Parser<T> {
let mut p = Parser {
rdr,
ch: Some('\x00'),
line: 1,
col: 0,
stack: Stack::new(),
state: ParseStart,
};
p.bump();
p
}
/// Provides access to the current position in the logical structure of the
/// JSON stream.
pub fn stack(&self) -> &Stack {
&self.stack
}
fn eof(&self) -> bool {
self.ch.is_none()
}
fn ch_or_null(&self) -> char {
self.ch.unwrap_or('\x00')
}
fn bump(&mut self) {
self.ch = self.rdr.next();
if self.ch_is('\n') {
self.line += 1;
self.col = 1;
} else {
self.col += 1;
}
}
fn next_char(&mut self) -> Option<char> {
self.bump();
self.ch
}
fn ch_is(&self, c: char) -> bool {
self.ch == Some(c)
}
fn error<U>(&self, reason: ErrorCode) -> Result<U, ParserError> {
Err(SyntaxError(reason, self.line, self.col))
}
fn parse_whitespace(&mut self) {
while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') {
self.bump();
}
}
fn parse_number(&mut self) -> JsonEvent {
let neg = if self.ch_is('-') {
self.bump();
true
} else {
false
};
let res = match self.parse_u64() {
Ok(res) => res,
Err(e) => {
return Error(e);
}
};
if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') {
let mut res = res as f64;
if self.ch_is('.') {
res = match self.parse_decimal(res) {
Ok(res) => res,
Err(e) => {
return Error(e);
}
};
}
if self.ch_is('e') || self.ch_is('E') {
res = match self.parse_exponent(res) {
Ok(res) => res,
Err(e) => {
return Error(e);
}
};
}
if neg {
res *= -1.0;
}
F64Value(res)
} else if neg {
let res = (res as i64).wrapping_neg();
// Make sure we didn't underflow.
if res > 0 {
Error(SyntaxError(InvalidNumber, self.line, self.col))
} else {
I64Value(res)
}
} else {
U64Value(res)
}
}
fn parse_u64(&mut self) -> Result<u64, ParserError> {
let mut accum = 0u64;
let last_accum = 0; // necessary to detect overflow.
match self.ch_or_null() {
'0' => {
self.bump();
// A leading '0' must be the only digit before the decimal point.
if let '0'..='9' = self.ch_or_null() {
return self.error(InvalidNumber);
}
}
'1'..='9' => {
while !self.eof() {
match self.ch_or_null() {
c @ '0'..='9' => {
accum = accum.wrapping_mul(10);
accum = accum.wrapping_add((c as u64) - ('0' as u64));
// Detect overflow by comparing to the last value.
if accum <= last_accum {
return self.error(InvalidNumber);
}
self.bump();
}
_ => break,
}
}
}
_ => return self.error(InvalidNumber),
}
Ok(accum)
}
fn parse_decimal(&mut self, mut res: f64) -> Result<f64, ParserError> {
self.bump();
// Make sure a digit follows the decimal place.
match self.ch_or_null() {
'0'..='9' => (),
_ => return self.error(InvalidNumber),
}
let mut dec = 1.0;
while !self.eof() {
match self.ch_or_null() {
c @ '0'..='9' => {
dec /= 10.0;
res += (((c as isize) - ('0' as isize)) as f64) * dec;
self.bump();
}
_ => break,
}
}
Ok(res)
}
fn parse_exponent(&mut self, mut res: f64) -> Result<f64, ParserError> {
self.bump();
let mut exp = 0;
let mut neg_exp = false;
if self.ch_is('+') {
self.bump();
} else if self.ch_is('-') {
self.bump();
neg_exp = true;
}
// Make sure a digit follows the exponent place.
match self.ch_or_null() {
'0'..='9' => (),
_ => return self.error(InvalidNumber),
}
while !self.eof() {
match self.ch_or_null() {
c @ '0'..='9' => {
exp *= 10;
exp += (c as usize) - ('0' as usize);
self.bump();
}
_ => break,
}
}
let exp = 10_f64.powi(exp as i32);
if neg_exp {
res /= exp;
} else {
res *= exp;
}
Ok(res)
}
fn decode_hex_escape(&mut self) -> Result<u16, ParserError> {
let mut i = 0;
let mut n = 0;
while i < 4 && !self.eof() {
self.bump();
n = match self.ch_or_null() {
c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)),
'a' | 'A' => n * 16 + 10,
'b' | 'B' => n * 16 + 11,
'c' | 'C' => n * 16 + 12,
'd' | 'D' => n * 16 + 13,
'e' | 'E' => n * 16 + 14,
'f' | 'F' => n * 16 + 15,
_ => return self.error(InvalidEscape),
};
i += 1;
}
// Error out if we didn't parse 4 digits.
if i != 4 {
return self.error(InvalidEscape);
}
Ok(n)
}
fn parse_str(&mut self) -> Result<string::String, ParserError> {
let mut escape = false;
let mut res = string::String::new();
loop {
self.bump();
if self.eof() {
return self.error(EOFWhileParsingString);
}
if escape {
match self.ch_or_null() {
'"' => res.push('"'),
'\\' => res.push('\\'),
'/' => res.push('/'),
'b' => res.push('\x08'),
'f' => res.push('\x0c'),
'n' => res.push('\n'),
'r' => res.push('\r'),
't' => res.push('\t'),
'u' => match self.decode_hex_escape()? {
0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape),
// Non-BMP characters are encoded as a sequence of
// two hex escapes, representing UTF-16 surrogates.
n1 @ 0xD800..=0xDBFF => {
match (self.next_char(), self.next_char()) {
(Some('\\'), Some('u')) => (),
_ => return self.error(UnexpectedEndOfHexEscape),
}
let n2 = self.decode_hex_escape()?;
if !(0xDC00..=0xDFFF).contains(&n2) {
return self.error(LoneLeadingSurrogateInHexEscape);
}
let c =
(u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000;
res.push(char::from_u32(c).unwrap());
}
n => match char::from_u32(u32::from(n)) {
Some(c) => res.push(c),
None => return self.error(InvalidUnicodeCodePoint),
},
},
_ => return self.error(InvalidEscape),
}
escape = false;
} else if self.ch_is('\\') {
escape = true;
} else {
match self.ch {
Some('"') => {
self.bump();
return Ok(res);
}
Some(c) => res.push(c),
None => unreachable!(),
}
}
}
}
// Invoked at each iteration, consumes the stream until it has enough
// information to return a JsonEvent.
// Manages an internal state so that parsing can be interrupted and resumed.
// Also keeps track of the position in the logical structure of the json
// stream isize the form of a stack that can be queried by the user using the
// stack() method.
fn parse(&mut self) -> JsonEvent {
loop {
// The only paths where the loop can spin a new iteration
// are in the cases ParseArrayComma and ParseObjectComma if ','
// is parsed. In these cases the state is set to (respectively)
// ParseArray(false) and ParseObject(false), which always return,
// so there is no risk of getting stuck in an infinite loop.
// All other paths return before the end of the loop's iteration.
self.parse_whitespace();
match self.state {
ParseStart => {
return self.parse_start();
}
ParseArray(first) => {
return self.parse_array(first);
}
ParseArrayComma => {
if let Some(evt) = self.parse_array_comma_or_end() {
return evt;
}
}
ParseObject(first) => {
return self.parse_object(first);
}
ParseObjectComma => {
self.stack.pop();
if self.ch_is(',') {
self.state = ParseObject(false);
self.bump();
} else {
return self.parse_object_end();
}
}
_ => {
return self.error_event(InvalidSyntax);
}
}
}
}
fn parse_start(&mut self) -> JsonEvent {
let val = self.parse_value();
self.state = match val {
Error(_) => ParseFinished,
ArrayStart => ParseArray(true),
ObjectStart => ParseObject(true),
_ => ParseBeforeFinish,
};
val
}
fn parse_array(&mut self, first: bool) -> JsonEvent {
if self.ch_is(']') {
if !first {
self.error_event(InvalidSyntax)
} else {
self.state = if self.stack.is_empty() {
ParseBeforeFinish
} else if self.stack.last_is_index() {
ParseArrayComma
} else {
ParseObjectComma
};
self.bump();
ArrayEnd
}
} else {
if first {
self.stack.push_index(0);
}
let val = self.parse_value();
self.state = match val {
Error(_) => ParseFinished,
ArrayStart => ParseArray(true),
ObjectStart => ParseObject(true),
_ => ParseArrayComma,
};
val
}
}
fn parse_array_comma_or_end(&mut self) -> Option<JsonEvent> {
if self.ch_is(',') {
self.stack.bump_index();
self.state = ParseArray(false);
self.bump();
None
} else if self.ch_is(']') {
self.stack.pop();
self.state = if self.stack.is_empty() {
ParseBeforeFinish
} else if self.stack.last_is_index() {
ParseArrayComma
} else {
ParseObjectComma
};
self.bump();
Some(ArrayEnd)
} else if self.eof() {
Some(self.error_event(EOFWhileParsingArray))
} else {
Some(self.error_event(InvalidSyntax))
}
}
fn parse_object(&mut self, first: bool) -> JsonEvent {
if self.ch_is('}') {
if !first {
if self.stack.is_empty() {
return self.error_event(TrailingComma);
} else {
self.stack.pop();
}
}
self.state = if self.stack.is_empty() {
ParseBeforeFinish
} else if self.stack.last_is_index() {
ParseArrayComma
} else {
ParseObjectComma
};
self.bump();
return ObjectEnd;
}
if self.eof() {
return self.error_event(EOFWhileParsingObject);
}
if !self.ch_is('"') {
return self.error_event(KeyMustBeAString);
}
let s = match self.parse_str() {
Ok(s) => s,
Err(e) => {
self.state = ParseFinished;
return Error(e);
}
};
self.parse_whitespace();
if self.eof() {
return self.error_event(EOFWhileParsingObject);
} else if self.ch_or_null() != ':' {
return self.error_event(ExpectedColon);
}
self.stack.push_key(s);
self.bump();
self.parse_whitespace();
let val = self.parse_value();
self.state = match val {
Error(_) => ParseFinished,
ArrayStart => ParseArray(true),
ObjectStart => ParseObject(true),
_ => ParseObjectComma,
};
val
}
fn parse_object_end(&mut self) -> JsonEvent {
if self.ch_is('}') {
self.state = if self.stack.is_empty() {
ParseBeforeFinish
} else if self.stack.last_is_index() {
ParseArrayComma
} else {
ParseObjectComma
};
self.bump();
ObjectEnd
} else if self.eof() {
self.error_event(EOFWhileParsingObject)
} else {
self.error_event(InvalidSyntax)
}
}
fn parse_value(&mut self) -> JsonEvent {
if self.eof() {
return self.error_event(EOFWhileParsingValue);
}
match self.ch_or_null() {
'n' => self.parse_ident("ull", NullValue),
't' => self.parse_ident("rue", BooleanValue(true)),
'f' => self.parse_ident("alse", BooleanValue(false)),
'0'..='9' | '-' => self.parse_number(),
'"' => match self.parse_str() {
Ok(s) => StringValue(s),
Err(e) => Error(e),
},
'[' => {
self.bump();
ArrayStart
}
'{' => {
self.bump();
ObjectStart
}
_ => self.error_event(InvalidSyntax),
}
}
fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent {
if ident.chars().all(|c| Some(c) == self.next_char()) {
self.bump();
value
} else {
Error(SyntaxError(InvalidSyntax, self.line, self.col))
}
}
fn error_event(&mut self, reason: ErrorCode) -> JsonEvent {
self.state = ParseFinished;
Error(SyntaxError(reason, self.line, self.col))
}
}
/// A Builder consumes a json::Parser to create a generic Json structure.
pub struct Builder<T> {
parser: Parser<T>,
token: Option<JsonEvent>,
}
impl<T: Iterator<Item = char>> Builder<T> {
/// Creates a JSON Builder.
pub fn new(src: T) -> Builder<T> {
Builder { parser: Parser::new(src), token: None }
}
// Decode a Json value from a Parser.
pub fn build(&mut self) -> Result<Json, BuilderError> {
self.bump();
let result = self.build_value();
self.bump();
match self.token {
None => {}
Some(Error(ref e)) => {
return Err(e.clone());
}
ref tok => {
panic!("unexpected token {:?}", tok.clone());
}
}
result
}
fn bump(&mut self) {
self.token = self.parser.next();
}
fn build_value(&mut self) -> Result<Json, BuilderError> {
match self.token {
Some(NullValue) => Ok(Json::Null),
Some(I64Value(n)) => Ok(Json::I64(n)),
Some(U64Value(n)) => Ok(Json::U64(n)),
Some(F64Value(n)) => Ok(Json::F64(n)),
Some(BooleanValue(b)) => Ok(Json::Boolean(b)),
Some(StringValue(ref mut s)) => {
let mut temp = string::String::new();
swap(s, &mut temp);
Ok(Json::String(temp))
}
Some(Error(ref e)) => Err(e.clone()),
Some(ArrayStart) => self.build_array(),
Some(ObjectStart) => self.build_object(),
Some(ObjectEnd) => self.parser.error(InvalidSyntax),
Some(ArrayEnd) => self.parser.error(InvalidSyntax),
None => self.parser.error(EOFWhileParsingValue),
}
}
fn build_array(&mut self) -> Result<Json, BuilderError> {
self.bump();
let mut values = Vec::new();
loop {
if self.token == Some(ArrayEnd) {
return Ok(Json::Array(values.into_iter().collect()));
}
match self.build_value() {
Ok(v) => values.push(v),
Err(e) => return Err(e),
}
self.bump();
}
}
fn build_object(&mut self) -> Result<Json, BuilderError> {
self.bump();
let mut values = BTreeMap::new();
loop {
match self.token {
Some(ObjectEnd) => {
return Ok(Json::Object(values));
}
Some(Error(ref e)) => {
return Err(e.clone());
}
None => {
break;
}
_ => {}
}
let key = match self.parser.stack().top() {
Some(StackElement::Key(k)) => k.to_owned(),
_ => {
panic!("invalid state");
}
};
match self.build_value() {
Ok(value) => {
values.insert(key, value);
}
Err(e) => {
return Err(e);
}
}
self.bump();
}
self.parser.error(EOFWhileParsingObject)
}
}
/// Decodes a json value from an `&mut io::Read`
pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
let mut contents = Vec::new();
match rdr.read_to_end(&mut contents) {
Ok(c) => c,
Err(e) => return Err(io_error_to_error(e)),
};
let s = match str::from_utf8(&contents).ok() {
Some(s) => s,
_ => return Err(SyntaxError(NotUtf8, 0, 0)),
};
let mut builder = Builder::new(s.chars());
builder.build()
}
/// Decodes a json value from a string
pub fn from_str(s: &str) -> Result<Json, BuilderError> {
let mut builder = Builder::new(s.chars());
builder.build()
}
/// A structure to decode JSON to values in rust.
pub struct Decoder {
stack: Vec<Json>,
}
impl Decoder {
/// Creates a new decoder instance for decoding the specified JSON value.
pub fn new(json: Json) -> Decoder {
Decoder { stack: vec![json] }
}
fn pop(&mut self) -> Json {
self.stack.pop().unwrap()
}
}
macro_rules! expect {
($e:expr, Null) => {{
match $e {
Json::Null => Ok(()),
other => Err(ExpectedError("Null".to_owned(), other.to_string())),
}
}};
($e:expr, $t:ident) => {{
match $e {
Json::$t(v) => Ok(v),
other => Err(ExpectedError(stringify!($t).to_owned(), other.to_string())),
}
}};
}
macro_rules! read_primitive {
($name:ident, $ty:ty) => {
fn $name(&mut self) -> DecodeResult<$ty> {
match self.pop() {
Json::I64(f) => Ok(f as $ty),
Json::U64(f) => Ok(f as $ty),
Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())),
// re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
// is going to have a string here, as per JSON spec.
Json::String(s) => match s.parse().ok() {
Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_owned(), s)),
},
value => Err(ExpectedError("Number".to_owned(), value.to_string())),
}
}
};
}
impl crate::Decoder for Decoder {
type Error = DecoderError;
fn read_nil(&mut self) -> DecodeResult<()> {
expect!(self.pop(), Null)
}
read_primitive! { read_usize, usize }
read_primitive! { read_u8, u8 }
read_primitive! { read_u16, u16 }
read_primitive! { read_u32, u32 }
read_primitive! { read_u64, u64 }
read_primitive! { read_u128, u128 }
read_primitive! { read_isize, isize }
read_primitive! { read_i8, i8 }
read_primitive! { read_i16, i16 }
read_primitive! { read_i32, i32 }
read_primitive! { read_i64, i64 }
read_primitive! { read_i128, i128 }
fn read_f32(&mut self) -> DecodeResult<f32> {
self.read_f64().map(|x| x as f32)
}
fn read_f64(&mut self) -> DecodeResult<f64> {
match self.pop() {
Json::I64(f) => Ok(f as f64),
Json::U64(f) => Ok(f as f64),
Json::F64(f) => Ok(f),
Json::String(s) => {
// re: #12967.. a type w/ numeric keys (ie HashMap<usize, V> etc)
// is going to have a string here, as per JSON spec.
match s.parse().ok() {
Some(f) => Ok(f),
None => Err(ExpectedError("Number".to_owned(), s)),
}
}
Json::Null => Ok(f64::NAN),
value => Err(ExpectedError("Number".to_owned(), value.to_string())),
}
}
fn read_bool(&mut self) -> DecodeResult<bool> {
expect!(self.pop(), Boolean)
}
fn read_char(&mut self) -> DecodeResult<char> {
let s = self.read_str()?;
{
let mut it = s.chars();
if let (Some(c), None) = (it.next(), it.next()) {
// exactly one character
return Ok(c);
}
}
Err(ExpectedError("single character string".to_owned(), s.to_string()))
}
fn read_str(&mut self) -> DecodeResult<Cow<'_, str>> {
expect!(self.pop(), String).map(Cow::Owned)
}
fn read_raw_bytes_into(&mut self, s: &mut [u8]) -> Result<(), Self::Error> {
for c in s.iter_mut() {
*c = self.read_u8()?;
}
Ok(())
}
fn read_enum<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
f(self)
}
fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodeResult<T>
where
F: FnMut(&mut Decoder, usize) -> DecodeResult<T>,
{
let name = match self.pop() {
Json::String(s) => s,
Json::Object(mut o) => {
let n = match o.remove(&"variant".to_owned()) {
Some(Json::String(s)) => s,
Some(val) => return Err(ExpectedError("String".to_owned(), val.to_string())),
None => return Err(MissingFieldError("variant".to_owned())),
};
match o.remove(&"fields".to_string()) {
Some(Json::Array(l)) => {
self.stack.extend(l.into_iter().rev());
}
Some(val) => return Err(ExpectedError("Array".to_owned(), val.to_string())),
None => return Err(MissingFieldError("fields".to_owned())),
}
n
}
json => return Err(ExpectedError("String or Object".to_owned(), json.to_string())),
};
let idx = match names.iter().position(|n| *n == &name[..]) {
Some(idx) => idx,
None => return Err(UnknownVariantError(name)),
};
f(self, idx)
}
fn read_enum_variant_arg<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
f(self)
}
fn read_struct<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
let value = f(self)?;
self.pop();
Ok(value)
}
fn read_struct_field<T, F>(&mut self, name: &str, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
let mut obj = expect!(self.pop(), Object)?;
let value = match obj.remove(&name.to_string()) {
None => {
// Add a Null and try to parse it as an Option<_>
// to get None as a default value.
self.stack.push(Json::Null);
match f(self) {
Ok(x) => x,
Err(_) => return Err(MissingFieldError(name.to_string())),
}
}
Some(json) => {
self.stack.push(json);
f(self)?
}
};
self.stack.push(Json::Object(obj));
Ok(value)
}
fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
self.read_seq(move |d, len| {
if len == tuple_len {
f(d)
} else {
Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len)))
}
})
}
fn read_tuple_arg<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
self.read_seq_elt(f)
}
fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T>
where
F: FnMut(&mut Decoder, bool) -> DecodeResult<T>,
{
match self.pop() {
Json::Null => f(self, false),
value => {
self.stack.push(value);
f(self, true)
}
}
}
fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
{
let array = expect!(self.pop(), Array)?;
let len = array.len();
self.stack.extend(array.into_iter().rev());
f(self, len)
}
fn read_seq_elt<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
f(self)
}
fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>,
{
let obj = expect!(self.pop(), Object)?;
let len = obj.len();
for (key, value) in obj {
self.stack.push(value);
self.stack.push(Json::String(key));
}
f(self, len)
}
fn read_map_elt_key<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
f(self)
}
fn read_map_elt_val<T, F>(&mut self, f: F) -> DecodeResult<T>
where
F: FnOnce(&mut Decoder) -> DecodeResult<T>,
{
f(self)
}
fn error(&mut self, err: &str) -> DecoderError {
ApplicationError(err.to_string())
}
}
/// A trait for converting values to JSON
pub trait ToJson {
/// Converts the value of `self` to an instance of JSON
fn to_json(&self) -> Json;
}
macro_rules! to_json_impl_i64 {
($($t:ty), +) => (
$(impl ToJson for $t {
fn to_json(&self) -> Json {
Json::I64(*self as i64)
}
})+
)
}
to_json_impl_i64! { isize, i8, i16, i32, i64 }
macro_rules! to_json_impl_u64 {
($($t:ty), +) => (
$(impl ToJson for $t {
fn to_json(&self) -> Json {
Json::U64(*self as u64)
}
})+
)
}
to_json_impl_u64! { usize, u8, u16, u32, u64 }
impl ToJson for Json {
fn to_json(&self) -> Json {
self.clone()
}
}
impl ToJson for f32 {
fn to_json(&self) -> Json {
f64::from(*self).to_json()
}
}
impl ToJson for f64 {
fn to_json(&self) -> Json {
match self.classify() {
Fp::Nan | Fp::Infinite => Json::Null,
_ => Json::F64(*self),
}
}
}
impl ToJson for () {
fn to_json(&self) -> Json {
Json::Null
}
}
impl ToJson for bool {
fn to_json(&self) -> Json {
Json::Boolean(*self)
}
}
impl ToJson for str {
fn to_json(&self) -> Json {
Json::String(self.to_string())
}
}
impl ToJson for string::String {
fn to_json(&self) -> Json {
Json::String((*self).clone())
}
}
macro_rules! tuple_impl {
// use variables to indicate the arity of the tuple
($($tyvar:ident),* ) => {
// the trailing commas are for the 1 tuple
impl<
$( $tyvar : ToJson ),*
> ToJson for ( $( $tyvar ),* , ) {
#[inline]
#[allow(non_snake_case)]
fn to_json(&self) -> Json {
match *self {
($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*])
}
}
}
}
}
tuple_impl! {A}
tuple_impl! {A, B}
tuple_impl! {A, B, C}
tuple_impl! {A, B, C, D}
tuple_impl! {A, B, C, D, E}
tuple_impl! {A, B, C, D, E, F}
tuple_impl! {A, B, C, D, E, F, G}
tuple_impl! {A, B, C, D, E, F, G, H}
tuple_impl! {A, B, C, D, E, F, G, H, I}
tuple_impl! {A, B, C, D, E, F, G, H, I, J}
tuple_impl! {A, B, C, D, E, F, G, H, I, J, K}
tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L}
impl<A: ToJson> ToJson for [A] {
fn to_json(&self) -> Json {
Json::Array(self.iter().map(|elt| elt.to_json()).collect())
}
}
impl<A: ToJson> ToJson for Vec<A> {
fn to_json(&self) -> Json {
Json::Array(self.iter().map(|elt| elt.to_json()).collect())
}
}
impl<T: ToString, A: ToJson> ToJson for BTreeMap<T, A> {
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
for (key, value) in self {
d.insert(key.to_string(), value.to_json());
}
Json::Object(d)
}
}
impl<A: ToJson> ToJson for HashMap<string::String, A> {
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
for (key, value) in self {
d.insert((*key).clone(), value.to_json());
}
Json::Object(d)
}
}
impl<A: ToJson> ToJson for Option<A> {
fn to_json(&self) -> Json {
match *self {
None => Json::Null,
Some(ref value) => value.to_json(),
}
}
}
struct FormatShim<'a, 'b> {
inner: &'a mut fmt::Formatter<'b>,
}
impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> {
fn write_str(&mut self, s: &str) -> fmt::Result {
match self.inner.write_str(s) {
Ok(_) => Ok(()),
Err(_) => Err(fmt::Error),
}
}
}
impl fmt::Display for Json {
/// Encodes a json value into a string
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut shim = FormatShim { inner: f };
let mut encoder = Encoder::new(&mut shim);
match self.encode(&mut encoder) {
Ok(_) => Ok(()),
Err(_) => Err(fmt::Error),
}
}
}
impl<'a> fmt::Display for PrettyJson<'a> {
/// Encodes a json value into a string
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut shim = FormatShim { inner: f };
let mut encoder = PrettyEncoder::new(&mut shim);
match self.inner.encode(&mut encoder) {
Ok(_) => Ok(()),
Err(_) => Err(fmt::Error),
}
}
}
impl<'a, T: for<'r> Encodable<Encoder<'r>>> fmt::Display for AsJson<'a, T> {
/// Encodes a json value into a string
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut shim = FormatShim { inner: f };
let mut encoder = Encoder::new(&mut shim);
match self.inner.encode(&mut encoder) {
Ok(_) => Ok(()),
Err(_) => Err(fmt::Error),
}
}
}
impl<'a, T> AsPrettyJson<'a, T> {
/// Sets the indentation level for the emitted JSON
pub fn indent(mut self, indent: usize) -> AsPrettyJson<'a, T> {
self.indent = Some(indent);
self
}
}
impl<'a, T: for<'x> Encodable<PrettyEncoder<'x>>> fmt::Display for AsPrettyJson<'a, T> {
/// Encodes a json value into a string
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut shim = FormatShim { inner: f };
let mut encoder = PrettyEncoder::new(&mut shim);
if let Some(n) = self.indent {
encoder.set_indent(n);
}
match self.inner.encode(&mut encoder) {
Ok(_) => Ok(()),
Err(_) => Err(fmt::Error),
}
}
}
impl FromStr for Json {
type Err = BuilderError;
fn from_str(s: &str) -> Result<Json, BuilderError> {
from_str(s)
}
}
#[cfg(test)]
mod tests;<|fim▁end|> | |
<|file_name|>project_euler_problem_16.cpp<|end_file_name|><|fim▁begin|>/**
@file project_euler_problem_15.cpp
@author Terence Henriod
Project Euler Problem 15
@brief Solves the following problem for the general case of any power of 2
(within system limitations):
"2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?"
@version Original Code 1.00 (1/4/2014) - T. Henriod
*/
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HEADER FILES / NAMESPACES
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#include <cassert>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <mpirxx.h>
using namespace std;
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GLOBAL CONSTANTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTION PROTOTYPES
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/**
FunctionName
A short description
@param
@return
@pre
-#
<|fim▁hole|>
@detail @bAlgorithm
-#
@exception
@code
@endcode
*/
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MAIN FUNCTION
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
int main(int argc, char** argv) {
// variables
// DID IT IN JAVA - a good method is with a string though
// unsigned int power = 1000;
// unsigned int digit_sum = 0;
// mpz_class large_number = 0;
// char file_name [] = "project_euler_problem_16.txt";
// ofstream fout;
// FILE* file;
//
// // get the power of 2 to use
// printf("The number whose digits to be summed is: 2^");
// scanf("%u", &power);
//
// // compute the power
// large_number = 4; //pow(2, power);
//
//cout << large_number << endl;
//
// // write it to the file
// file = fopen(file_name, "w");
// fprintf(file, "%lf", large_number);
// fclose(file);
//
// // compute the sum of the digits
// //digit_sum = sumDigits(file_name);
//
// // report the result to the user
// printf("\nThe sum of %lf's \ndigits is: %u\n", large_number, digit_sum);
// scanf("%s", file_name);
// return 0 on successful completion
return 0;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTION IMPLEMENTATIONS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/<|fim▁end|> | @post
-# |
<|file_name|>config.py<|end_file_name|><|fim▁begin|># Snap! Configuration Manager
#
# (C) Copyright 2011 Mo Morsi ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, Version 3,
# as published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
import os
import os.path
import optparse, ConfigParser
import snap
from snap.options import *
from snap.snapshottarget import SnapshotTarget
from snap.exceptions import ArgError
class ConfigOptions:
"""Container holding all the configuration options available
to the Snap system"""
# modes of operation
RESTORE = 0
BACKUP = 1
def __init__(self):
'''initialize configuration'''
# mode of operation
self.mode = None
# mapping of targets to lists of backends to use when backing up / restoring them
self.target_backends = {}
# mapping of targets to lists of entities to include when backing up
self.target_includes = {}
# mapping of targets to lists of entities to exclude when backing up
self.target_excludes = {}
# output log level
# currently supports 'quiet', 'normal', 'verbose', 'debug'
self.log_level = 'normal'
# output format to backup / restore
self.outputformat = 'snapfile'
# location of the snapfile to backup to / restore from
self.snapfile = None
# Encryption/decryption password to use, if left as None, encryption will be disabled
self.encryption_password = None
# hash of key/value pairs of service-specific options
self.service_options = {}
for backend in SnapshotTarget.BACKENDS:
self.target_backends[backend] = False
self.target_includes[backend] = []
self.target_excludes[backend] = []
def log_level_at_least(self, comparison):
return (comparison == 'quiet') or \
(comparison == 'normal' and self.log_level != 'quiet') or \
(comparison == 'verbose' and (self.log_level == 'verbose' or self.log_level == 'debug')) or \
(comparison == 'debug' and self.log_level == 'debug')
class ConfigFile:
"""Represents the snap config file to be read and parsed"""
parser = None
def __init__(self, config_file):
'''
Initialize the config file, specifying its path
@param file - the path to the file to load
'''
# if config file doesn't exist, just ignore
if not os.path.exists(config_file):
if snap.config.options.log_level_at_least("verbose"):
snap.callback.snapcallback.warn("Config file " + config_file + " not found")
else:
self.parser = ConfigParser.ConfigParser()
self.parser.read(config_file)
self.__parse()
def string_to_bool(string):
'''Static helper to convert a string to a boolean value'''
if string == 'True' or string == 'true' or string == '1':
return True
elif string == 'False' or string == 'false' or string == '0':
return False
return None
string_to_bool = staticmethod(string_to_bool)
def string_to_array(string):
'''Static helper to convert a colon deliminated string to an array of strings'''
return string.split(':')
string_to_array = staticmethod(string_to_array)
def __get_bool(self, key, section='main'):
'''
Retreive the indicated boolean value from the config file
@param key - the string key corresponding to the boolean value to retrieve
@param section - the section to retrieve the value from
@returns - the value or False if not found
'''
try:
return ConfigFile.string_to_bool(self.parser.get(section, key))
except:
return None
def __get_string(self, key, section='main'):
'''
Retreive the indicated string value from the config file
@param key - the string key corresponding to the string value to retrieve
@param section - the section to retrieve the value from
@returns - the value or None if not found
'''
try:
return self.parser.get(section, key)
except:
return None
def __get_array(self, section='main'):
'''return array of key/value pairs from the config file section
@param section - the section which to retrieve the key / values from
@returns - the array of key / value pairs or None if not found
'''
try:
return self.parser.items(section)
except:
return None
def __parse(self):
'''parse configuration out of the config file'''
for backend in SnapshotTarget.BACKENDS:
val = self.__get_bool(backend)
if val is not None:
snap.config.options.target_backends[backend] = val
else:
val = self.__get_string(backend)
if val:
snap.config.options.target_backends[backend] = True
val = ConfigFile.string_to_array(val)
for include in val:
if include[0] == '!':
snap.config.options.target_excludes[backend].append(include[1:])
else:
snap.config.options.target_includes[backend].append(include)
else:
val = self.__get_bool('no' + backend)
if val:
snap.config.options.target_backends[backend] = False
of = self.__get_string('outputformat')
sf = self.__get_string('snapfile')
ll = self.__get_string('loglevel')
enp = self.__get_string('encryption_password')
if of != None:
snap.config.options.outputformat = of
if sf != None:
snap.config.options.snapfile = sf
if ll != None:
snap.config.options.log_level = ll
if enp != None:
snap.config.options.encryption_password = enp
services = self.__get_array('services')
if services:
for k, v in services:
snap.config.options.service_options[k] = v
class Config:
"""The configuration manager, used to set and verify snap config values
from the config file and command line. Primary interface to the
Configuration System"""
configoptions = None
parser = None
# read values from the config files and set them in the target ConfigOptions
def read_config(self):
# add conf stored in resources if running from local checkout
CONFIG_FILES.append(os.path.join(os.path.dirname(__file__), "..", "resources", "snap.conf"))
for config_file in CONFIG_FILES:
ConfigFile(config_file)
def parse_cli(self):
'''
parses the command line an set them in the target ConfigOptions
'''
usage = "usage: %prog [options] arg"
self.parser = optparse.OptionParser(usage, version=SNAP_VERSION)
self.parser.add_option('', '--restore', dest='restore', action='store_true', default=False, help='Restore snapshot')
self.parser.add_option('', '--backup', dest='backup', action='store_true', default=False, help='Take snapshot')
self.parser.add_option('-l', '--log-level', dest='log_level', action='store', default="normal", help='Log level (quiet, normal, verbose, debug)')
self.parser.add_option('-o', '--outputformat', dest='outputformat', action='store', default=None, help='Output file format')
self.parser.add_option('-f', '--snapfile', dest='snapfile', action='store', default=None, help='Snapshot file, use - for stdout')
self.parser.add_option('-p', '--password', dest='encryption_password', action='store', default=None, help='Snapshot File Encryption/Decryption Password')
# FIXME how to permit parameter lists for some of these
for backend in SnapshotTarget.BACKENDS:
self.parser.add_option('', '--' + backend, dest=backend, action='store_true', help='Enable ' + backend + ' snapshots/restoration')
self.parser.add_option('', '--no' + backend, dest=backend, action='store_false', help='Disable ' + backend + ' snapshots/restoration')
(options, args) = self.parser.parse_args()
if options.restore != False:
snap.config.options.mode = ConfigOptions.RESTORE
if options.backup != False:
snap.config.options.mode = ConfigOptions.BACKUP
if options.log_level:
snap.config.options.log_level = options.log_level
if options.outputformat != None:<|fim▁hole|> if options.snapfile != None:
snap.config.options.snapfile = options.snapfile
if options.encryption_password != None:
snap.config.options.encryption_password = options.encryption_password
for backend in SnapshotTarget.BACKENDS:
val = getattr(options, backend)
if val != None:
if type(val) == str:
snap.config.options.target_backends[backend] = True
val = ConfigFile.string_to_array(val)
for include in val:
if include[0] == '!':
snap.config.options.target_excludes[backend].append(include[1:])
else:
snap.config.options.target_includes[backend].append(include)
else:
snap.config.options.target_backends[backend] = val
def verify_integrity(self):
'''
verify the integrity of the current option set
@raises - ArgError if the options are invalid
'''
if snap.config.options.mode == None: # mode not specified
raise snap.exceptions.ArgError("Must specify backup or restore")
if snap.config.options.snapfile == None: # need to specify snapfile location
raise snap.exceptions.ArgError("Must specify snapfile")
# TODO verify output format is one of permitted types
if snap.config.options.outputformat == None: # need to specify output format
raise snap.exceptions.ArgError("Must specify valid output format")
# static shared options
options = ConfigOptions()<|fim▁end|> | snap.config.options.outputformat = options.outputformat |
<|file_name|>compiletest.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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. This file may not be copied, modified, or distributed
// except according to those terms.
#[crate_type = "bin"];
#[allow(non_camel_case_types)];
#[deny(warnings)];
extern mod extra;
use std::os;
use std::rt;
use std::io::fs;
use extra::getopts;
use extra::getopts::groups::{optopt, optflag, reqopt};
use extra::test;
use common::config;
use common::mode_run_pass;
use common::mode_run_fail;
use common::mode_compile_fail;
use common::mode_pretty;
use common::mode_debug_info;
use common::mode_codegen;
use common::mode;
use util::logv;
pub mod procsrv;
pub mod util;
pub mod header;
pub mod runtest;
pub mod common;
pub mod errors;
pub fn main() {
let args = os::args();
let config = parse_config(args);
log_config(&config);
run_tests(&config);
}
pub fn parse_config(args: ~[~str]) -> config {
let groups : ~[getopts::groups::OptGroup] =
~[reqopt("", "compile-lib-path", "path to host shared libraries", "PATH"),
reqopt("", "run-lib-path", "path to target shared libraries", "PATH"),
reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"),
optopt("", "clang-path", "path to executable for codegen tests", "PATH"),
optopt("", "llvm-bin-path", "path to directory holding llvm binaries", "DIR"),
reqopt("", "src-base", "directory to scan for test files", "PATH"),
reqopt("", "build-base", "directory to deposit test outputs", "PATH"),
reqopt("", "aux-base", "directory to find auxiliary test files", "PATH"),
reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET"),
reqopt("", "mode", "which sort of compile tests to run",
"(compile-fail|run-fail|run-pass|pretty|debug-info)"),
optflag("", "ignored", "run tests marked as ignored / xfailed"),
optopt("", "runtool", "supervisor program to run tests under \
(eg. emulator, valgrind)", "PROGRAM"),
optopt("", "rustcflags", "flags to pass to rustc", "FLAGS"),
optflag("", "verbose", "run tests verbosely, showing all output"),
optopt("", "logfile", "file to log test execution to", "FILE"),
optopt("", "save-metrics", "file to save metrics to", "FILE"),
optopt("", "ratchet-metrics", "file to ratchet metrics against", "FILE"),
optopt("", "ratchet-noise-percent",
"percent change in metrics to consider noise", "N"),
optflag("", "jit", "run tests under the JIT"),
optopt("", "target", "the target to build for", "TARGET"),
optopt("", "adb-path", "path to the android debugger", "PATH"),
optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH"),
optopt("", "test-shard", "run shard A, of B shards, worth of the testsuite", "A.B"),
optflag("h", "help", "show this message"),
];
assert!(!args.is_empty());
let argv0 = args[0].clone();
let args_ = args.tail();
if args[1] == ~"-h" || args[1] == ~"--help" {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println(getopts::groups::usage(message, groups));
println("");
fail!()
}
let matches =
&match getopts::groups::getopts(args_, groups) {
Ok(m) => m,
Err(f) => fail!("{}", f.to_err_msg())
};
if matches.opt_present("h") || matches.opt_present("help") {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println(getopts::groups::usage(message, groups));
println("");
fail!()
}
fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
Path::new(m.opt_str(nm).unwrap())
}
config {
compile_lib_path: matches.opt_str("compile-lib-path").unwrap(),
run_lib_path: matches.opt_str("run-lib-path").unwrap(),
rustc_path: opt_path(matches, "rustc-path"),
clang_path: matches.opt_str("clang-path").map(|s| Path::new(s)),
llvm_bin_path: matches.opt_str("llvm-bin-path").map(|s| Path::new(s)),
src_base: opt_path(matches, "src-base"),
build_base: opt_path(matches, "build-base"),
aux_base: opt_path(matches, "aux-base"),
stage_id: matches.opt_str("stage-id").unwrap(),
mode: str_mode(matches.opt_str("mode").unwrap()),
run_ignored: matches.opt_present("ignored"),
filter:
if !matches.free.is_empty() {
Some(matches.free[0].clone())
} else {
None
},
logfile: matches.opt_str("logfile").map(|s| Path::new(s)),
save_metrics: matches.opt_str("save-metrics").map(|s| Path::new(s)),
ratchet_metrics:
matches.opt_str("ratchet-metrics").map(|s| Path::new(s)),
ratchet_noise_percent:
matches.opt_str("ratchet-noise-percent").and_then(|s| from_str::<f64>(s)),
runtool: matches.opt_str("runtool"),
rustcflags: matches.opt_str("rustcflags"),
jit: matches.opt_present("jit"),
target: opt_str2(matches.opt_str("target")).to_str(),
adb_path: opt_str2(matches.opt_str("adb-path")).to_str(),
adb_test_dir:
opt_str2(matches.opt_str("adb-test-dir")).to_str(),
adb_device_status:
if (opt_str2(matches.opt_str("target")) ==
~"arm-linux-androideabi") {
if (opt_str2(matches.opt_str("adb-test-dir")) !=
~"(none)" &&
opt_str2(matches.opt_str("adb-test-dir")) !=
~"") { true }
else { false }
} else { false },
test_shard: test::opt_shard(matches.opt_str("test-shard")),
verbose: matches.opt_present("verbose")
}
}
pub fn log_config(config: &config) {
let c = config;
logv(c, format!("configuration:"));
logv(c, format!("compile_lib_path: {}", config.compile_lib_path));
logv(c, format!("run_lib_path: {}", config.run_lib_path));
logv(c, format!("rustc_path: {}", config.rustc_path.display()));
logv(c, format!("src_base: {}", config.src_base.display()));
logv(c, format!("build_base: {}", config.build_base.display()));
logv(c, format!("stage_id: {}", config.stage_id));
logv(c, format!("mode: {}", mode_str(config.mode)));
logv(c, format!("run_ignored: {}", config.run_ignored));
logv(c, format!("filter: {}", opt_str(&config.filter)));
logv(c, format!("runtool: {}", opt_str(&config.runtool)));
logv(c, format!("rustcflags: {}", opt_str(&config.rustcflags)));
logv(c, format!("jit: {}", config.jit));
logv(c, format!("target: {}", config.target));
logv(c, format!("adb_path: {}", config.adb_path));
logv(c, format!("adb_test_dir: {}", config.adb_test_dir));
logv(c, format!("adb_device_status: {}", config.adb_device_status));
match config.test_shard {
None => logv(c, ~"test_shard: (all)"),
Some((a,b)) => logv(c, format!("test_shard: {}.{}", a, b))
}
logv(c, format!("verbose: {}", config.verbose));
logv(c, format!("\n"));
}
pub fn opt_str<'a>(maybestr: &'a Option<~str>) -> &'a str {
match *maybestr {
None => "(none)",
Some(ref s) => {
let s: &'a str = *s;
s
}
}
}
pub fn opt_str2(maybestr: Option<~str>) -> ~str {
match maybestr { None => ~"(none)", Some(s) => { s } }
}
pub fn str_mode(s: ~str) -> mode {
match s {
~"compile-fail" => mode_compile_fail,
~"run-fail" => mode_run_fail,
~"run-pass" => mode_run_pass,
~"pretty" => mode_pretty,
~"debug-info" => mode_debug_info,
~"codegen" => mode_codegen,
_ => fail!("invalid mode")
}
}
pub fn mode_str(mode: mode) -> ~str {
match mode {
mode_compile_fail => ~"compile-fail",
mode_run_fail => ~"run-fail",
mode_run_pass => ~"run-pass",
mode_pretty => ~"pretty",
mode_debug_info => ~"debug-info",
mode_codegen => ~"codegen",
}
}
pub fn run_tests(config: &config) {
if config.target == ~"arm-linux-androideabi" {
match config.mode{
mode_debug_info => {
println("arm-linux-androideabi debug-info \
test uses tcp 5039 port. please reserve it");
//arm-linux-androideabi debug-info test uses remote debugger
//so, we test 1 task at once
os::setenv("RUST_TEST_TASKS","1");
}
_ =>{}
}
}
let opts = test_opts(config);
let tests = make_tests(config);
// sadly osx needs some file descriptor limits raised for running tests in
// parallel (especially when we have lots and lots of child processes).
// For context, see #8904
rt::test::prepare_for_lots_of_tests();
let res = test::run_tests_console(&opts, tests);
if !res { fail!("Some tests failed"); }
}
pub fn test_opts(config: &config) -> test::TestOpts {
test::TestOpts {
filter: config.filter.clone(),
run_ignored: config.run_ignored,
logfile: config.logfile.clone(),
run_tests: true,
run_benchmarks: true,
ratchet_metrics: config.ratchet_metrics.clone(),
ratchet_noise_percent: config.ratchet_noise_percent.clone(),
save_metrics: config.save_metrics.clone(),
test_shard: config.test_shard.clone()
}
}
pub fn make_tests(config: &config) -> ~[test::TestDescAndFn] {
debug!("making tests from {}",
config.src_base.display());
let mut tests = ~[];
let dirs = fs::readdir(&config.src_base);
for file in dirs.iter() {
let file = file.clone();
debug!("inspecting file {}", file.display());
if is_test(config, &file) {
let t = make_test(config, &file, || {
match config.mode {
mode_codegen => make_metrics_test_closure(config, &file),
_ => make_test_closure(config, &file)
}
});
tests.push(t)
}
}
tests
}
pub fn is_test(config: &config, testfile: &Path) -> bool {
// Pretty-printer does not work with .rc files yet
let valid_extensions =
match config.mode {
mode_pretty => ~[~".rs"],
_ => ~[~".rc", ~".rs"]
};
let invalid_prefixes = ~[~".", ~"#", ~"~"];
let name = testfile.filename_str().unwrap();
let mut valid = false;
for ext in valid_extensions.iter() {
if name.ends_with(*ext) { valid = true; }
}
for pre in invalid_prefixes.iter() {
if name.starts_with(*pre) { valid = false; }
}
return valid;
}
pub fn make_test(config: &config, testfile: &Path, f: || -> test::TestFn)
-> test::TestDescAndFn {
test::TestDescAndFn {
desc: test::TestDesc {
name: make_test_name(config, testfile),
ignore: header::is_test_ignored(config, testfile),
should_fail: false
},
testfn: f(),
}
}
pub fn make_test_name(config: &config, testfile: &Path) -> test::TestName {
// Try to elide redundant long paths
fn shorten(path: &Path) -> ~str {
let filename = path.filename_str();<|fim▁hole|> format!("{}/{}", dir.unwrap_or(""), filename.unwrap_or(""))
}
test::DynTestName(format!("[{}] {}",
mode_str(config.mode),
shorten(testfile)))
}
pub fn make_test_closure(config: &config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_owned();
test::DynTestFn(proc() { runtest::run(config, testfile) })
}
pub fn make_metrics_test_closure(config: &config, testfile: &Path) -> test::TestFn {
let config = (*config).clone();
// FIXME (#9639): This needs to handle non-utf8 paths
let testfile = testfile.as_str().unwrap().to_owned();
test::DynMetricFn(proc(mm) {
runtest::run_metrics(config, testfile, mm)
})
}<|fim▁end|> | let p = path.dir_path();
let dir = p.filename_str(); |
<|file_name|>ez_setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""Bootstrap setuptools installation
To use setuptools in your package's setup.py, include this
file in the same directory and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
To require a specific version of setuptools, set a download
mirror, or use an alternate download directory, simply supply
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlib
from distutils import log
try:
# noinspection PyCompatibility
from urllib.request import urlopen
except ImportError:
# noinspection PyCompatibility
from urllib2 import urlopen
try:
from site import USER_SITE
except ImportError:
USER_SITE = None
DEFAULT_VERSION = "7.0"
DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
def _python_cmd(*args):
"""
Return True if the command succeeded.
"""
args = (sys.executable,) + args
return subprocess.call(args) == 0
def _install(archive_filename, install_args=()):
with archive_context(archive_filename):
# installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
def _build_egg(egg, archive_filename, to_dir):
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
class ContextualZipFile(zipfile.ZipFile):
"""
Supplement ZipFile class to support context manager for Python 2.6
"""
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __new__(cls, *args, **kwargs):
"""
Construct a ZipFile or ContextualZipFile as appropriate
"""
if hasattr(zipfile.ZipFile, '__exit__'):
return zipfile.ZipFile(*args, **kwargs)
return super(ContextualZipFile, cls).__new__(cls)
@contextlib.contextmanager
def archive_context(filename):
# extracting the archive
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
with ContextualZipFile(filename) as archive:
archive.extractall()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
yield
finally:
os.chdir(old_wd)
shutil.rmtree(tmpdir)
def _do_download(version, download_base, to_dir, download_delay):
egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
% (version, sys.version_info[0], sys.version_info[1]))
if not os.path.exists(egg):
archive = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, archive, to_dir)
sys.path.insert(0, egg)
# Remove previously-imported pkg_resources if present (see
# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
if 'pkg_resources' in sys.modules:
del sys.modules['pkg_resources']
import setuptools
setuptools.bootstrap_install_from = egg
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15):
to_dir = os.path.abspath(to_dir)
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("setuptools>=" + version)
return
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir, download_delay)
except pkg_resources.VersionConflict as VC_err:
if imported:
msg = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""").format(VC_err=VC_err, version=version)
sys.stderr.write(msg)
sys.exit(2)
# otherwise, reload ok
del pkg_resources, sys.modules['pkg_resources']
return _do_download(version, download_base, to_dir, download_delay)
def _clean_check(cmd, target):
"""
Run the command to download target. If the command fails, clean up before
re-raising the error.
"""
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
if os.access(target, os.F_OK):
os.unlink(target)
raise
def download_file_powershell(url, target):
"""
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
"""
target = os.path.abspath(target)
ps_cmd = (
"[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
"[System.Net.CredentialCache]::DefaultCredentials; "
"(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)"
% vars()
)
cmd = [
'powershell',
'-Command',
ps_cmd,
]
_clean_check(cmd, target)
<|fim▁hole|>
def has_powershell():
if platform.system() != 'Windows':
return False
cmd = ['powershell', '-Command', 'echo test']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_powershell.viable = has_powershell
def download_file_curl(url, target):
cmd = ['curl', url, '--silent', '--output', target]
_clean_check(cmd, target)
def has_curl():
cmd = ['curl', '--version']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_curl.viable = has_curl
def download_file_wget(url, target):
cmd = ['wget', url, '--quiet', '--output-document', target]
_clean_check(cmd, target)
def has_wget():
cmd = ['wget', '--version']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_wget.viable = has_wget
def download_file_insecure(url, target):
"""
Use Python to download the file, even though it cannot authenticate the
connection.
"""
src = urlopen(url)
try:
# Read all the data in one block.
data = src.read()
finally:
src.close()
# Write all the data in one block to avoid creating a partial file.
with open(target, "wb") as dst:
dst.write(data)
download_file_insecure.viable = lambda: True
def get_best_downloader():
downloaders = (
download_file_powershell,
download_file_curl,
download_file_wget,
download_file_insecure,
)
viable_downloaders = (dl for dl in downloaders if dl.viable())
return next(viable_downloaders, None)
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader):
"""
Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an sdist for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
``downloader_factory`` should be a function taking no arguments and
returning a function for downloading a URL to a target.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
zip_name = "setuptools-%s.zip" % version
url = download_base + zip_name
saveto = os.path.join(to_dir, zip_name)
if not os.path.exists(saveto): # Avoid repeated downloads
log.warn("Downloading %s", url)
downloader = downloader_factory()
downloader(url, saveto)
return os.path.realpath(saveto)
def _build_install_args(options):
"""
Build the arguments to 'python setup.py install' on the setuptools package
"""
return ['--user'] if options.user_install else []
def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default=False,
help='install in user site package (requires Python 2.6 or later)')
parser.add_option(
'--download-base', dest='download_base', metavar="URL",
default=DEFAULT_URL,
help='alternative URL from where to download the setuptools package')
parser.add_option(
'--insecure', dest='downloader_factory', action='store_const',
const=lambda: download_file_insecure, default=get_best_downloader,
help='Use internal, non-validating downloader'
)
parser.add_option(
'--version', help="Specify which version to download",
default=DEFAULT_VERSION,
)
options, args = parser.parse_args()
# positional arguments are ignored
return options
def main():
"""Install or upgrade setuptools and EasyInstall"""
options = _parse_args()
archive = download_setuptools(
version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory,
)
return _install(archive, _build_install_args(options))
if __name__ == '__main__':
sys.exit(main())<|fim▁end|> | |
<|file_name|>pool.rs<|end_file_name|><|fim▁begin|>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::collections::HashMap;
use std::path::Path;
use std::vec::Vec;
use dbus;
use dbus::arg::{Array, IterAppend};
use dbus::tree::{
Access, EmitsChangedSignal, Factory, MTFn, MethodErr, MethodInfo, MethodResult, PropInfo,
};
use dbus::Message;
use uuid::Uuid;
use devicemapper::Sectors;
use crate::dbus_api::consts;
use crate::engine::{BlockDevTier, MaybeDbusPath, Name, Pool, RenameAction};
use crate::dbus_api::blockdev::create_dbus_blockdev;
use crate::dbus_api::filesystem::create_dbus_filesystem;
use crate::dbus_api::types::{DbusContext, DbusErrorEnum, OPContext, TData};
use crate::dbus_api::util::{
engine_to_dbus_err_tuple, get_next_arg, get_uuid, make_object_path, msg_code_ok, msg_string_ok,
};
fn create_filesystems(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
let message: &Message = m.msg;
let mut iter = message.iter_init();
let filesystems: Array<&str, _> = get_next_arg(&mut iter, 0)?;
let dbus_context = m.tree.get_data();
let object_path = m.path.get_name();
let return_message = message.method_return();
let default_return: Vec<(dbus::Path, &str)> = Vec::new();
if filesystems.count() > 1 {
let error_message = "only 1 filesystem per request allowed";
let (rc, rs) = (DbusErrorEnum::ERROR as u16, error_message);
return Ok(vec![return_message.append3(default_return, rc, rs)]);
}
let pool_path = m
.tree
.get(object_path)
.expect("implicit argument must be in tree");
let pool_uuid = get_data!(pool_path; default_return; return_message).uuid;
let mut engine = dbus_context.engine.borrow_mut();
let (pool_name, pool) = get_mut_pool!(engine; pool_uuid; default_return; return_message);
let result = pool.create_filesystems(
pool_uuid,
&pool_name,
&filesystems
.map(|x| (x, None))
.collect::<Vec<(&str, Option<Sectors>)>>(),
);
let msg = match result {
Ok(ref infos) => {
let return_value = infos
.iter()
.map(|&(name, uuid)| {
(
// FIXME: To avoid this expect, modify create_filesystem
// so that it returns a mutable reference to the
// filesystem created.
create_dbus_filesystem(
dbus_context,
object_path.clone(),
uuid,
pool.get_mut_filesystem(uuid)
.expect("just inserted by create_filesystems")
.1,
),
name,
)
})
.collect::<Vec<_>>();
return_message.append3(return_value, msg_code_ok(), msg_string_ok())
}
Err(err) => {
let (rc, rs) = engine_to_dbus_err_tuple(&err);
return_message.append3(default_return, rc, rs)
}
};
Ok(vec![msg])
}
fn destroy_filesystems(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
let message: &Message = m.msg;
let mut iter = message.iter_init();
let filesystems: Array<dbus::Path<'static>, _> = get_next_arg(&mut iter, 0)?;
let dbus_context = m.tree.get_data();
let object_path = m.path.get_name();
let return_message = message.method_return();
let default_return: Vec<&str> = Vec::new();
let pool_path = m
.tree
.get(object_path)
.expect("implicit argument must be in tree");
let pool_uuid = get_data!(pool_path; default_return; return_message).uuid;
let mut engine = dbus_context.engine.borrow_mut();
let (pool_name, pool) = get_mut_pool!(engine; pool_uuid; default_return; return_message);
let mut filesystem_map: HashMap<Uuid, dbus::Path<'static>> = HashMap::new();
for op in filesystems {
if let Some(filesystem_path) = m.tree.get(&op) {
let filesystem_uuid = get_data!(filesystem_path; default_return; return_message).uuid;
filesystem_map.insert(filesystem_uuid, op);
}
}
let result = pool.destroy_filesystems(
&pool_name,
&filesystem_map.keys().cloned().collect::<Vec<Uuid>>(),
);
let msg = match result {
Ok(ref uuids) => {
for uuid in uuids {
let op = filesystem_map
.get(uuid)
.expect("'uuids' is a subset of filesystem_map.keys()");
dbus_context.actions.borrow_mut().push_remove(op, m.tree);
}
let return_value: Vec<String> = uuids
.iter()
.map(|n| n.to_simple_ref().to_string())
.collect();
return_message.append3(return_value, msg_code_ok(), msg_string_ok())
}
Err(err) => {
let (rc, rs) = engine_to_dbus_err_tuple(&err);
return_message.append3(default_return, rc, rs)
}
};<|fim▁hole|>fn snapshot_filesystem(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
let message: &Message = m.msg;
let mut iter = message.iter_init();
let filesystem: dbus::Path<'static> = get_next_arg(&mut iter, 0)?;
let snapshot_name: &str = get_next_arg(&mut iter, 0)?;
let dbus_context = m.tree.get_data();
let object_path = m.path.get_name();
let return_message = message.method_return();
let default_return = dbus::Path::default();
let pool_path = m
.tree
.get(object_path)
.expect("implicit argument must be in tree");
let pool_uuid = get_data!(pool_path; default_return; return_message).uuid;
let fs_uuid = match m.tree.get(&filesystem) {
Some(op) => get_data!(op; default_return; return_message).uuid,
None => {
let message = format!("no data for object path {}", filesystem);
let (rc, rs) = (DbusErrorEnum::NOTFOUND as u16, message);
return Ok(vec![return_message.append3(default_return, rc, rs)]);
}
};
let mut engine = dbus_context.engine.borrow_mut();
let (pool_name, pool) = get_mut_pool!(engine; pool_uuid; default_return; return_message);
let msg = match pool.snapshot_filesystem(pool_uuid, &pool_name, fs_uuid, snapshot_name) {
Ok((uuid, fs)) => {
let fs_object_path: dbus::Path =
create_dbus_filesystem(dbus_context, object_path.clone(), uuid, fs);
return_message.append3(fs_object_path, msg_code_ok(), msg_string_ok())
}
Err(err) => {
let (rc, rs) = engine_to_dbus_err_tuple(&err);
return_message.append3(default_return, rc, rs)
}
};
Ok(vec![msg])
}
fn add_blockdevs(m: &MethodInfo<MTFn<TData>, TData>, tier: BlockDevTier) -> MethodResult {
let message: &Message = m.msg;
let mut iter = message.iter_init();
let devs: Array<&str, _> = get_next_arg(&mut iter, 1)?;
let dbus_context = m.tree.get_data();
let object_path = m.path.get_name();
let return_message = message.method_return();
let default_return: Vec<dbus::Path> = Vec::new();
let pool_path = m
.tree
.get(object_path)
.expect("implicit argument must be in tree");
let pool_uuid = get_data!(pool_path; default_return; return_message).uuid;
let mut engine = dbus_context.engine.borrow_mut();
let (pool_name, pool) = get_mut_pool!(engine; pool_uuid; default_return; return_message);
let blockdevs = devs.map(|x| Path::new(x)).collect::<Vec<&Path>>();
let result = pool.add_blockdevs(pool_uuid, &*pool_name, &blockdevs, tier);
let msg = match result {
Ok(uuids) => {
let return_value = uuids
.iter()
.map(|uuid| {
// FIXME: To avoid this expect, modify add_blockdevs
// so that it returns a mutable reference to each
// blockdev created.
create_dbus_blockdev(
dbus_context,
object_path.clone(),
*uuid,
pool.get_mut_blockdev(*uuid)
.expect("just inserted by add_blockdevs")
.1,
)
})
.collect::<Vec<_>>();
return_message.append3(return_value, msg_code_ok(), msg_string_ok())
}
Err(err) => {
let (rc, rs) = engine_to_dbus_err_tuple(&err);
return_message.append3(default_return, rc, rs)
}
};
Ok(vec![msg])
}
fn add_datadevs(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
add_blockdevs(m, BlockDevTier::Data)
}
fn add_cachedevs(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
add_blockdevs(m, BlockDevTier::Cache)
}
fn rename_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
let message: &Message = m.msg;
let mut iter = message.iter_init();
let new_name: &str = get_next_arg(&mut iter, 0)?;
let dbus_context = m.tree.get_data();
let object_path = m.path.get_name();
let return_message = message.method_return();
let default_return = false;
let pool_path = m
.tree
.get(object_path)
.expect("implicit argument must be in tree");
let pool_uuid = get_data!(pool_path; default_return; return_message).uuid;
let msg = match dbus_context
.engine
.borrow_mut()
.rename_pool(pool_uuid, new_name)
{
Ok(RenameAction::NoSource) => {
let error_message = format!("engine doesn't know about pool {}", &pool_uuid);
let (rc, rs) = (DbusErrorEnum::INTERNAL_ERROR as u16, error_message);
return_message.append3(default_return, rc, rs)
}
Ok(RenameAction::Identity) => return_message.append3(false, msg_code_ok(), msg_string_ok()),
Ok(RenameAction::Renamed) => return_message.append3(true, msg_code_ok(), msg_string_ok()),
Err(err) => {
let (rc, rs) = engine_to_dbus_err_tuple(&err);
return_message.append3(default_return, rc, rs)
}
};
Ok(vec![msg])
}
/// Get a pool property and place it on the D-Bus. The property is
/// found by means of the getter method which takes a reference to a
/// Pool and obtains the property from the pool.
fn get_pool_property<F, R>(
i: &mut IterAppend,
p: &PropInfo<MTFn<TData>, TData>,
getter: F,
) -> Result<(), MethodErr>
where
F: Fn((Name, Uuid, &Pool)) -> Result<R, MethodErr>,
R: dbus::arg::Append,
{
let dbus_context = p.tree.get_data();
let object_path = p.path.get_name();
let pool_path = p
.tree
.get(object_path)
.expect("implicit argument must be in tree");
let pool_uuid = pool_path
.get_data()
.as_ref()
.ok_or_else(|| MethodErr::failed(&format!("no data for object path {}", object_path)))?
.uuid;
let engine = dbus_context.engine.borrow();
let (pool_name, pool) = engine.get_pool(pool_uuid).ok_or_else(|| {
MethodErr::failed(&format!("no pool corresponding to uuid {}", &pool_uuid))
})?;
i.append(getter((pool_name, pool_uuid, pool))?);
Ok(())
}
fn get_pool_name(i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>) -> Result<(), MethodErr> {
get_pool_property(i, p, |(name, _, _)| Ok(name.to_owned()))
}
fn get_pool_total_physical_used(
i: &mut IterAppend,
p: &PropInfo<MTFn<TData>, TData>,
) -> Result<(), MethodErr> {
fn get_used((_, uuid, pool): (Name, Uuid, &Pool)) -> Result<String, MethodErr> {
let err_func = |_| {
MethodErr::failed(&format!(
"no total physical size computed for pool with uuid {}",
uuid
))
};
pool.total_physical_used()
.map(|u| Ok(format!("{}", *u)))
.map_err(err_func)?
}
get_pool_property(i, p, get_used)
}
fn get_pool_total_physical_size(
i: &mut IterAppend,
p: &PropInfo<MTFn<TData>, TData>,
) -> Result<(), MethodErr> {
get_pool_property(i, p, |(_, _, p)| {
Ok(format!("{}", *p.total_physical_size()))
})
}
fn get_pool_state(i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>) -> Result<(), MethodErr> {
get_pool_property(i, p, |(_, _, pool)| Ok(pool.state() as u16))
}
fn get_pool_extend_state(
i: &mut IterAppend,
p: &PropInfo<MTFn<TData>, TData>,
) -> Result<(), MethodErr> {
get_pool_property(i, p, |(_, _, pool)| Ok(pool.extend_state() as u16))
}
fn get_space_state(i: &mut IterAppend, p: &PropInfo<MTFn<TData>, TData>) -> Result<(), MethodErr> {
get_pool_property(i, p, |(_, _, pool)| Ok(pool.free_space_state() as u16))
}
pub fn create_dbus_pool<'a>(
dbus_context: &DbusContext,
parent: dbus::Path<'static>,
uuid: Uuid,
pool: &mut Pool,
) -> dbus::Path<'a> {
let f = Factory::new_fn();
let create_filesystems_method = f
.method("CreateFilesystems", (), create_filesystems)
.in_arg(("specs", "as"))
.out_arg(("filesystems", "a(os)"))
.out_arg(("return_code", "q"))
.out_arg(("return_string", "s"));
let destroy_filesystems_method = f
.method("DestroyFilesystems", (), destroy_filesystems)
.in_arg(("filesystems", "ao"))
.out_arg(("results", "as"))
.out_arg(("return_code", "q"))
.out_arg(("return_string", "s"));
let add_blockdevs_method = f
.method("AddDataDevs", (), add_datadevs)
.in_arg(("devices", "as"))
.out_arg(("results", "ao"))
.out_arg(("return_code", "q"))
.out_arg(("return_string", "s"));
let add_cachedevs_method = f
.method("AddCacheDevs", (), add_cachedevs)
.in_arg(("devices", "as"))
.out_arg(("results", "ao"))
.out_arg(("return_code", "q"))
.out_arg(("return_string", "s"));
let rename_method = f
.method("SetName", (), rename_pool)
.in_arg(("name", "s"))
.out_arg(("action", "b"))
.out_arg(("return_code", "q"))
.out_arg(("return_string", "s"));
let snapshot_method = f
.method("SnapshotFilesystem", (), snapshot_filesystem)
.in_arg(("origin", "o"))
.in_arg(("snapshot_name", "s"))
.out_arg(("result", "o"))
.out_arg(("return_code", "q"))
.out_arg(("return_string", "s"));
let name_property = f
.property::<&str, _>(consts::POOL_NAME_PROP, ())
.access(Access::Read)
.emits_changed(EmitsChangedSignal::True)
.on_get(get_pool_name);
let total_physical_size_property = f
.property::<&str, _>("TotalPhysicalSize", ())
.access(Access::Read)
.emits_changed(EmitsChangedSignal::False)
.on_get(get_pool_total_physical_size);
let total_physical_used_property = f
.property::<&str, _>("TotalPhysicalUsed", ())
.access(Access::Read)
.emits_changed(EmitsChangedSignal::False)
.on_get(get_pool_total_physical_used);
let uuid_property = f
.property::<&str, _>("Uuid", ())
.access(Access::Read)
.emits_changed(EmitsChangedSignal::Const)
.on_get(get_uuid);
let state_property = f
.property::<u16, _>(consts::POOL_STATE_PROP, ())
.access(Access::Read)
.emits_changed(EmitsChangedSignal::True)
.on_get(get_pool_state);
let extend_state_property = f
.property::<u16, _>(consts::POOL_EXTEND_STATE_PROP, ())
.access(Access::Read)
.emits_changed(EmitsChangedSignal::True)
.on_get(get_pool_extend_state);
let space_state_property = f
.property::<u16, _>(consts::POOL_SPACE_STATE_PROP, ())
.access(Access::Read)
.emits_changed(EmitsChangedSignal::True)
.on_get(get_space_state);
let object_name = make_object_path(dbus_context);
let object_path = f
.object_path(object_name, Some(OPContext::new(parent, uuid)))
.introspectable()
.add(
f.interface(consts::POOL_INTERFACE_NAME, ())
.add_m(create_filesystems_method)
.add_m(destroy_filesystems_method)
.add_m(snapshot_method)
.add_m(add_blockdevs_method)
.add_m(add_cachedevs_method)
.add_m(rename_method)
.add_p(name_property)
.add_p(total_physical_size_property)
.add_p(total_physical_used_property)
.add_p(uuid_property)
.add_p(state_property)
.add_p(space_state_property)
.add_p(extend_state_property),
);
let path = object_path.get_name().to_owned();
dbus_context.actions.borrow_mut().push_add(object_path);
pool.set_dbus_path(MaybeDbusPath(Some(path.clone())));
path
}<|fim▁end|> | Ok(vec![msg])
}
|
<|file_name|>email_alerts.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""A simple wrapper to send email alerts."""
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import logging
import re
import smtplib
import socket
from grr.lib import config_lib
from grr.lib import registry
from grr.lib.rdfvalues import standard as rdf_standard
class EmailAlerterBase(object):
"""The email alerter base class."""
__metaclass__ = registry.MetaclassRegistry
def RemoveHtmlTags(self, data):
p = re.compile(r"<.*?>")
return p.sub("", data)
def AddEmailDomain(self, address):
suffix = config_lib.CONFIG["Logging.domain"]
if isinstance(address, rdf_standard.DomainEmailAddress):
address = str(address)
if suffix and "@" not in address:
return address + "@%s" % suffix
return address
def SplitEmailsAndAppendEmailDomain(self, address_list):
"""Splits a string of comma-separated emails, appending default domain."""
result = []
# Process email addresses, and build up a list.
if isinstance(address_list, rdf_standard.DomainEmailAddress):
address_list = [str(address_list)]
elif isinstance(address_list, basestring):
address_list = [address for address in address_list.split(",") if address]
for address in address_list:
result.append(self.AddEmailDomain(address))
return result
def SendEmail(self,
to_addresses,
from_address,
subject,
message,
attachments=None,
is_html=True,
cc_addresses=None,
message_id=None,
headers=None):
raise NotImplementedError()
class SMTPEmailAlerter(EmailAlerterBase):
def SendEmail(self,<|fim▁hole|> message,
attachments=None,
is_html=True,
cc_addresses=None,
message_id=None,
headers=None):
"""This method sends an email notification.
Args:
to_addresses: [email protected] string, list of addresses as csv string,
or rdf_standard.DomainEmailAddress
from_address: [email protected] string
subject: email subject string
message: message contents string, as HTML or plain text
attachments: iterable of filename string and file data tuples,
e.g. {"/file/name/string": filedata}
is_html: true if message is in HTML format
cc_addresses: [email protected] string, or list of addresses as
csv string
message_id: smtp message_id. Used to enable conversation threading
headers: dict of str-> str, headers to set
Raises:
RuntimeError: for problems connecting to smtp server.
"""
headers = headers or {}
msg = MIMEMultipart("alternative")
if is_html:
text = self.RemoveHtmlTags(message)
part1 = MIMEText(text, "plain")
msg.attach(part1)
part2 = MIMEText(message, "html")
msg.attach(part2)
else:
part1 = MIMEText(message, "plain")
msg.attach(part1)
if attachments:
for file_name, file_data in attachments.iteritems():
part = MIMEBase("application", "octet-stream")
part.set_payload(file_data)
encoders.encode_base64(part)
part.add_header("Content-Disposition",
"attachment; filename=\"%s\"" % file_name)
msg.attach(part)
msg["Subject"] = subject
from_address = self.AddEmailDomain(from_address)
to_addresses = self.SplitEmailsAndAppendEmailDomain(to_addresses)
cc_addresses = self.SplitEmailsAndAppendEmailDomain(cc_addresses or "")
msg["From"] = from_address
msg["To"] = ",".join(to_addresses)
if cc_addresses:
msg["CC"] = ",".join(cc_addresses)
if message_id:
msg.add_header("Message-ID", message_id)
for header, value in headers.iteritems():
msg.add_header(header, value)
try:
s = smtplib.SMTP(config_lib.CONFIG["Worker.smtp_server"],
int(config_lib.CONFIG["Worker.smtp_port"]))
s.ehlo()
if config_lib.CONFIG["Worker.smtp_starttls"]:
s.starttls()
s.ehlo()
if (config_lib.CONFIG["Worker.smtp_user"] and
config_lib.CONFIG["Worker.smtp_password"]):
s.login(config_lib.CONFIG["Worker.smtp_user"],
config_lib.CONFIG["Worker.smtp_password"])
s.sendmail(from_address, to_addresses + cc_addresses, msg.as_string())
s.quit()
except (socket.error, smtplib.SMTPException) as e:
raise RuntimeError("Could not connect to SMTP server to send email. "
"Please check config option Worker.smtp_server. "
"Currently set to %s. Error: %s" %
(config_lib.CONFIG["Worker.smtp_server"], e))
EMAIL_ALERTER = None
class EmailAlerterInit(registry.InitHook):
def RunOnce(self):
global EMAIL_ALERTER
email_alerter_cls_name = config_lib.CONFIG["Server.email_alerter_class"]
logging.debug("Using email alerter: %s", email_alerter_cls_name)
cls = EmailAlerterBase.GetPlugin(email_alerter_cls_name)
EMAIL_ALERTER = cls()<|fim▁end|> | to_addresses,
from_address,
subject, |
<|file_name|>assets.rs<|end_file_name|><|fim▁begin|>#[cfg(not(feature="dynamic-assets"))]
mod static_assets {
use std::collections::HashMap;
use futures::Future;
use web::{Resource, ResponseFuture};
// The CSS should be built to a single CSS file at compile time
#[derive(StaticResource)]
#[filename = "assets/themes.css"]
#[mime = "text/css"]
pub struct ThemesCss;
#[derive(StaticResource)]
#[filename = "assets/style.css"]
#[mime = "text/css"]
pub struct StyleCss;
#[derive(StaticResource)]
#[filename = "assets/script.js"]
#[mime = "application/javascript"]
pub struct ScriptJs;
#[derive(StaticResource)]
#[filename = "assets/search.js"]
#[mime = "application/javascript"]
pub struct SearchJs;
// SIL Open Font License 1.1: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL
// Copyright 2015 The Amatic SC Project Authors ([email protected])
// #[derive(StaticResource)]
// #[filename = "assets/amatic-sc-v9-latin-regular.woff"]
// #[mime = "application/font-woff"]
// pub struct AmaticFont;
type BoxResource = Box<Resource + Sync + Send>;
type ResourceFn = Box<Fn() -> BoxResource + Sync + Send>;
lazy_static! {
pub static ref ASSETS_MAP: HashMap<&'static str, ResourceFn> = hashmap!{
// The CSS should be built to a single CSS file at compile time
ThemesCss::resource_name() =>
Box::new(|| Box::new(ThemesCss) as BoxResource) as ResourceFn,
StyleCss::resource_name() =>
Box::new(|| Box::new(StyleCss) as BoxResource) as ResourceFn,
ScriptJs::resource_name() =>
Box::new(|| Box::new(ScriptJs) as BoxResource) as ResourceFn,
SearchJs::resource_name() =>
Box::new(|| Box::new(SearchJs) as BoxResource) as ResourceFn,
};
}
}
#[cfg(not(feature="dynamic-assets"))]
pub use self::static_assets::*;
#[cfg(feature="dynamic-assets")]
mod dynamic_assets {
pub struct ThemesCss;
impl ThemesCss {
pub fn resource_name() -> &'static str { "themes.css" }
}
pub struct StyleCss;
impl StyleCss {
pub fn resource_name() -> &'static str { "style.css" }
}
pub struct ScriptJs;
impl ScriptJs {
pub fn resource_name() -> &'static str { "script.js" }<|fim▁hole|> }
pub struct SearchJs;
impl SearchJs {
pub fn resource_name() -> &'static str { "search.js" }
}
}
#[cfg(feature="dynamic-assets")]
pub use self::dynamic_assets::*;<|fim▁end|> | |
<|file_name|>test_intersect.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""
Test the intersection of Coords
"""
# import iris tests first so that some things can be initialised before importing anything else
import iris.tests as tests # isort:skip
import numpy as np
import iris
import iris.coord_systems
import iris.coords
import iris.cube
import iris.tests.stock
class TestCubeIntersectTheoretical(tests.IrisTest):
def test_simple_intersect(self):
cube = iris.cube.Cube(
np.array(
[
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8],
[5, 6, 7, 8, 9],
],
dtype=np.int32,
)
)
lonlat_cs = iris.coord_systems.RotatedGeogCS(10, 20)
cube.add_dim_coord(
iris.coords.DimCoord(
np.arange(5, dtype=np.float32) * 90 - 180,
"longitude",
units="degrees",
coord_system=lonlat_cs,
),
1,
)
cube.add_dim_coord(
iris.coords.DimCoord(
np.arange(5, dtype=np.float32) * 45 - 90,
"latitude",
units="degrees",
coord_system=lonlat_cs,
),
0,
)
cube.add_aux_coord(
iris.coords.DimCoord(
points=np.int32(11), long_name="pressure", units="Pa"
)
)
cube.rename("temperature")
cube.units = "K"
cube2 = iris.cube.Cube(
np.array(
[
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8],
[5, 6, 7, 8, 50],
],
dtype=np.int32,
)
)
lonlat_cs = iris.coord_systems.RotatedGeogCS(10, 20)
cube2.add_dim_coord(
iris.coords.DimCoord(
np.arange(5, dtype=np.float32) * 90,
"longitude",
units="degrees",
coord_system=lonlat_cs,
),<|fim▁hole|> )
cube2.add_dim_coord(
iris.coords.DimCoord(
np.arange(5, dtype=np.float32) * 45 - 90,
"latitude",
units="degrees",
coord_system=lonlat_cs,
),
0,
)
cube2.add_aux_coord(
iris.coords.DimCoord(
points=np.int32(11), long_name="pressure", units="Pa"
)
)
cube2.rename("")
r = iris.analysis.maths.intersection_of_cubes(cube, cube2)
self.assertCML(r, ("cdm", "test_simple_cube_intersection.cml"))
class TestCoordIntersect(tests.IrisTest):
def test_commutative(self):
step = 4.0
c1 = iris.coords.DimCoord(np.arange(100) * step)
offset_points = c1.points.copy()
offset_points -= step * 30
c2 = c1.copy(points=offset_points)
i1 = c1.intersect(c2)
i2 = c2.intersect(c1)
self.assertEqual(i1, i2)
if __name__ == "__main__":
tests.main()<|fim▁end|> | 1, |
<|file_name|>TransformMatrix.js<|end_file_name|><|fim▁begin|>/***********************************************************************
* Module: Transform Matrix
* Description:
* Author: Copyright 2012-2014, Tyler Beck
* License: MIT
***********************************************************************/
define([
'../math/Matrix4x4',
'../math/Vector4'
], function( M, V ){
/*================================================
* Helper Methods
*===============================================*/
/**
* converts almost 0 float values to true 0
* @param v
* @returns {*}
*/
function floatZero( v ){
if (v == 0) {
v = 0;
}
return v;
}
/**
* converts degrees to radians
* @param deg
* @returns {number}
*/
function degToRad( deg ){
return deg * Math.PI / 180;
}
/**
* true 0 cosine
* @param a
* @returns {*}
*/
function cos( a ){
return floatZero( Math.cos(a ) );
}
/**
* true 0 sine
* @param a
* @returns {*}<|fim▁hole|> */
function sin( a ){
return floatZero( Math.sin(a ) );
}
/**
* true 0 tangent
* @param a
* @returns {*}
*/
function tan( a ){
return floatZero( Math.tan(a ) );
}
/*================================================
* Transform Constructor
*===============================================*/
var TransformMatrix = function( v ){
this.init( v );
return this;
};
/*================================================
* Transform Prototype
*===============================================*/
TransformMatrix.prototype = {
/**
* initialize class
* @param v
*/
init: function( v ){
this.value = M.identity();
if (v && v.length ){
var l = v.length;
for (var i = 0; i < l; i++ ){
this.value[i] = v[i];
}
}
},
/**
* applies translation
* @param x
* @param y
* @param z
* @returns {TransformMatrix}
*/
translate: function( x, y, z ){
var translation = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 ];
return new TransformMatrix( M.multiply( this.value, translation ) );
},
/**
* applies scale
* @param x
* @param y
* @param z
* @returns {TransformMatrix}
*/
scale: function( x, y, z ){
var scaler = [ x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 ];
return new TransformMatrix( M.multiply( this.value, scaler ) );
},
/**
* applies x axis rotation
* @param a
* @returns {TransformMatrix}
*/
rotateX: function( a ){
return this.rotate( 1, 0, 0, a );
},
/**
* applies y axis rotation
* @param a
* @returns {TransformMatrix}
*/
rotateY: function( a ){
return this.rotate( 0, 1, 0, a );
},
/**
* applies z axis rotation
* @param a
* @returns {TransformMatrix}
*/
rotateZ: function( a ){
return this.rotate( 0, 0, 1, a );
},
/**
* applies vector rotation
* @param x
* @param y
* @param z
* @param a
* @returns {TransformMatrix}
*/
rotate: function( x, y, z, a ){
var norm = ( new V( x, y, z ) ).normalize();
x = norm.x;
y = norm.y;
z = norm.z;
var c = cos(a);
var s = sin(a);
var rotation = [
1+(1-c)*(x*x-1), z*s+x*y*(1-c), -y*s+x*z*(1-c), 0,
-z*s+x*y*(1-c), 1+(1-c)*(y*y-1), x*s+y*z*(1-c), 0,
y*s+x*z*(1-c), -x*s+y*z*(1-c), 1+(1-c)*(z*z-1), 0,
0, 0, 0, 1
];
return new TransformMatrix( M.multiply( this.value, rotation ) );
},
/**
* applies x skew
* @param a
* @returns {TransformMatrix}
*/
skewX: function( a ){
var t = tan( a );
var skew = [ 1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
return new TransformMatrix( M.multiply( this.value, skew ) );
},
/**
* applies y skew
* @param a
* @returns {TransformMatrix}
*/
skewY: function( a ){
var t = tan( a );
var skew = [ 1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
return new TransformMatrix( M.multiply( this.value, skew ) );
},
/**
* decomposes transform into component parts
* @returns {{}}
*/
decompose: function(){
var m = this.value;
var i, j, p, perspective, translate, scale, skew, quaternion;
// Normalize the matrix.
if (m[15] == 0) return false;
p = m[15];
for ( i=0; i<4; ++i ){
for ( j=0; j<4; ++j ){
m[i*4+j] /= p;
}
}
// perspectiveMatrix is used to solve for perspective, but it also provides
// an easy way to test for singularity of the upper 3x3 component.
var perspectiveMatrix = m.slice(0);
perspectiveMatrix[3] = 0;
perspectiveMatrix[7] = 0;
perspectiveMatrix[11] = 0;
perspectiveMatrix[15] = 1;
if ( M.determinant( perspectiveMatrix ) == 0){
return false;
}
//perspective.
if (m[3] != 0 || m[7] != 0 || m[11] != 0) {
// rightHandSide is the right hand side of the equation.
var right = new V( m[3], m[7], m[11], m[15] );
var tranInvPers = M.transpose( M.inverse( perspectiveMatrix ) );
perspective = right.multiplyMatrix( tranInvPers );
}
else{
perspective = new V(0,0,0,1);
}
//translation
translate = new V( m[12], m[13], m[14] );
//scale & skew
var row = [ new V(), new V(), new V() ];
for ( i = 0; i < 3; i++ ) {
row[i].x = m[4*i];
row[i].y = m[4*i+1];
row[i].z = m[4*i+2];
}
scale = new V();
skew = new V();
scale.x = row[0].length();
row[0] = row[0].normalize();
// Compute XY shear factor and make 2nd row orthogonal to 1st.
skew.x = row[0].dot(row[1]);
row[1] = row[1].combine(row[0], 1.0, -skew.x);
// Now, compute Y scale and normalize 2nd row.
scale.y = row[1].length();
row[1] = row[1].normalize();
skew.x = skew.x/scale.y;
// Compute XZ and YZ shears, orthogonalize 3rd row
skew.y = row[0].dot(row[2]);
row[2] = row[2].combine(row[0], 1.0, -skew.y);
skew.z = row[1].dot(row[2]);
row[2] = row[2].combine(row[1], 1.0, -skew.z);
// Next, get Z scale and normalize 3rd row.
scale.z = row[2].length();
row[2] = row[2].normalize();
skew.y = (skew.y / scale.z);
skew.z = (skew.z / scale.z);
// At this point, the matrix (in rows) is orthonormal.
// Check for a coordinate system flip. If the determinant
// is -1, then negate the matrix and the scaling factors.
var pdum3 = row[1].cross(row[2]);
if (row[0].dot( pdum3 ) < 0) {
for (i = 0; i < 3; i++) {
scale.at(i, scale.at(i)* -1);
row[i].x *= -1;
row[i].y *= -1;
row[i].z *= -1;
}
}
// Now, get the rotations out
// FROM W3C
quaternion = new V();
quaternion.x = 0.5 * Math.sqrt(Math.max(1 + row[0].x - row[1].y - row[2].z, 0));
quaternion.y = 0.5 * Math.sqrt(Math.max(1 - row[0].x + row[1].y - row[2].z, 0));
quaternion.z = 0.5 * Math.sqrt(Math.max(1 - row[0].x - row[1].y + row[2].z, 0));
quaternion.w = 0.5 * Math.sqrt(Math.max(1 + row[0].x + row[1].y + row[2].z, 0));
if (row[2].y > row[1].z) quaternion.x = -quaternion.x;
if (row[0].z > row[2].x) quaternion.y = -quaternion.y;
if (row[1].x > row[0].y) quaternion.z = -quaternion.z;
return {
perspective: perspective,
translate: translate,
skew: skew,
scale: scale,
quaternion: quaternion.normalize()
};
},
/**
* converts matrix to css string
* @returns {string}
*/
toString: function(){
return "matrix3d("+ this.value.join(", ")+ ")";
}
};
/**
* recomposes transform from component parts
* @param d
* @returns {TransformMatrix}
*/
TransformMatrix.recompose = function( d ){
//console.log('Matrix4x4.recompose');
var m = M.identity();
var i, j, x, y, z, w;
var perspective = d.perspective;
var translate = d.translate;
var skew = d.skew;
var scale = d.scale;
var quaternion = d.quaternion;
// apply perspective
m[3] = perspective.x;
m[7] = perspective.y;
m[11] = perspective.z;
m[15] = perspective.w;
// apply translation
for ( i=0; i<3; ++i ){
for ( j=0; j<3; ++j ){
m[12+i] += translate.at( j ) * m[j*4+i]
}
}
// apply rotation
x = quaternion.x;
y = quaternion.y;
z = quaternion.z;
w = quaternion.w;
// Construct a composite rotation matrix from the quaternion values
/**/
var rmv = M.identity();
rmv[0] = 1 - 2 * ( y * y + z * z );
rmv[1] = 2 * ( x * y - z * w );
rmv[2] = 2 * ( x * z + y * w );
rmv[4] = 2 * ( x * y + z * w );
rmv[5] = 1 - 2 * ( x * x + z * z );
rmv[6] = 2 * ( y * z - x * w );
rmv[8] = 2 * ( x * z - y * w );
rmv[9] = 2 * ( y * z + x * w );
rmv[10] = 1 - 2 * ( x * x + y * y );
/*
var rmv = [
1 - 2*y*y - 2*z*z, 2*x*y - 2*z*w, 2*x*z + 2*y*w, 0,
2*x*y + 2*z*w, 1 - 2*x*x - 2*z*z, 2*y*z - 2*x*w, 0,
2*x*z - 2*y*w, 2*y*z + 2*x*w, 1 - 2*x*x - 2*y*y, 0,
0, 0, 0, 1
];
*/
var rotationMatrix = M.transpose( rmv );
var matrix = M.multiply( m, rotationMatrix );
//console.log(' skew');
// apply skew
var temp = Matrix4x4.identity();
if ( skew.z ){
temp[9] = skew.z;
matrix = M.multiply( matrix, temp );
}
if (skew.y){
temp[9] = 0;
temp[8] = skew.y;
matrix = M.multiply( matrix, temp );
}
if (skew.x){
temp[8] = 0;
temp[4] = skew.x;
matrix = M.multiply( matrix, temp );
}
// apply scale
m = matrix;
for ( i=0; i<3; ++i ){
for ( j=0; j<3; ++j ){
m[4*i+j] *= scale.at( i );
}
}
return new TransformMatrix( m );
}
return TransformMatrix;
});<|fim▁end|> | |
<|file_name|>deployment_controller.go<|end_file_name|><|fim▁begin|>/*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package deployment
import (
"fmt"
"math"
"time"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/apis/experimental"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/fields"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/util"
deploymentUtil "k8s.io/kubernetes/pkg/util/deployment"
)
type DeploymentController struct {
client client.Interface
expClient client.ExperimentalInterface
}
func New(client client.Interface) *DeploymentController {
return &DeploymentController{
client: client,
expClient: client.Experimental(),<|fim▁hole|>
func (d *DeploymentController) Run(syncPeriod time.Duration) {
go util.Until(func() {
errs := d.reconcileDeployments()
for _, err := range errs {
glog.Errorf("Failed to reconcile: %v", err)
}
}, syncPeriod, util.NeverStop)
}
func (d *DeploymentController) reconcileDeployments() []error {
list, err := d.expClient.Deployments(api.NamespaceAll).List(labels.Everything(), fields.Everything())
if err != nil {
return []error{fmt.Errorf("error listing deployments: %v", err)}
}
errs := []error{}
for _, deployment := range list.Items {
if err := d.reconcileDeployment(&deployment); err != nil {
errs = append(errs, fmt.Errorf("error in reconciling deployment %s: %v", deployment.Name, err))
}
}
return errs
}
func (d *DeploymentController) reconcileDeployment(deployment *experimental.Deployment) error {
switch deployment.Spec.Strategy.Type {
case experimental.RecreateDeploymentStrategyType:
return d.reconcileRecreateDeployment(*deployment)
case experimental.RollingUpdateDeploymentStrategyType:
return d.reconcileRollingUpdateDeployment(*deployment)
}
return fmt.Errorf("unexpected deployment strategy type: %s", deployment.Spec.Strategy.Type)
}
func (d *DeploymentController) reconcileRecreateDeployment(deployment experimental.Deployment) error {
// TODO: implement me.
return nil
}
func (d *DeploymentController) reconcileRollingUpdateDeployment(deployment experimental.Deployment) error {
newRC, err := d.getNewRC(deployment)
if err != nil {
return err
}
oldRCs, err := d.getOldRCs(deployment)
if err != nil {
return err
}
allRCs := []*api.ReplicationController{}
allRCs = append(allRCs, oldRCs...)
allRCs = append(allRCs, newRC)
// Scale up, if we can.
scaledUp, err := d.scaleUp(allRCs, newRC, deployment)
if err != nil {
return err
}
if scaledUp {
// Update DeploymentStatus
return d.updateDeploymentStatus(allRCs, newRC, deployment)
}
// Scale down, if we can.
scaledDown, err := d.scaleDown(allRCs, oldRCs, newRC, deployment)
if err != nil {
return err
}
if scaledDown {
// Update DeploymentStatus
return d.updateDeploymentStatus(allRCs, newRC, deployment)
}
// TODO: raise an event, neither scaled up nor down.
return nil
}
func (d *DeploymentController) getOldRCs(deployment experimental.Deployment) ([]*api.ReplicationController, error) {
return deploymentUtil.GetOldRCs(deployment, d.client)
}
// Returns an RC that matches the intent of the given deployment.
// It creates a new RC if required.
func (d *DeploymentController) getNewRC(deployment experimental.Deployment) (*api.ReplicationController, error) {
existingNewRC, err := deploymentUtil.GetNewRC(deployment, d.client)
if err != nil || existingNewRC != nil {
return existingNewRC, err
}
// new RC does not exist, create one.
namespace := deployment.ObjectMeta.Namespace
podTemplateSpecHash := deploymentUtil.GetPodTemplateSpecHash(deployment.Spec.Template)
rcName := fmt.Sprintf("deploymentrc-%d", podTemplateSpecHash)
newRCTemplate := deploymentUtil.GetNewRCTemplate(deployment)
newRC := api.ReplicationController{
ObjectMeta: api.ObjectMeta{
Name: rcName,
Namespace: namespace,
},
Spec: api.ReplicationControllerSpec{
Replicas: 0,
Selector: newRCTemplate.ObjectMeta.Labels,
Template: newRCTemplate,
},
}
createdRC, err := d.client.ReplicationControllers(namespace).Create(&newRC)
if err != nil {
return nil, fmt.Errorf("error creating replication controller: %v", err)
}
return createdRC, nil
}
func (d *DeploymentController) getPodsForRCs(replicationControllers []*api.ReplicationController) ([]api.Pod, error) {
allPods := []api.Pod{}
for _, rc := range replicationControllers {
podList, err := d.client.Pods(rc.ObjectMeta.Namespace).List(labels.SelectorFromSet(rc.Spec.Selector), fields.Everything())
if err != nil {
return allPods, fmt.Errorf("error listing pods: %v", err)
}
allPods = append(allPods, podList.Items...)
}
return allPods, nil
}
func (d *DeploymentController) getReplicaCountForRCs(replicationControllers []*api.ReplicationController) int {
totalReplicaCount := 0
for _, rc := range replicationControllers {
totalReplicaCount += rc.Spec.Replicas
}
return totalReplicaCount
}
func (d *DeploymentController) scaleUp(allRCs []*api.ReplicationController, newRC *api.ReplicationController, deployment experimental.Deployment) (bool, error) {
if newRC.Spec.Replicas == deployment.Spec.Replicas {
// Scaling up not required.
return false, nil
}
maxSurge, isPercent, err := util.GetIntOrPercentValue(&deployment.Spec.Strategy.RollingUpdate.MaxSurge)
if err != nil {
return false, fmt.Errorf("invalid value for MaxSurge: %v", err)
}
if isPercent {
maxSurge = util.GetValueFromPercent(maxSurge, deployment.Spec.Replicas)
}
// Find the total number of pods
allPods, err := d.getPodsForRCs(allRCs)
if err != nil {
return false, err
}
currentPodCount := len(allPods)
// Check if we can scale up.
maxTotalPods := deployment.Spec.Replicas + maxSurge
if currentPodCount >= maxTotalPods {
// Cannot scale up.
return false, nil
}
// Scale up.
scaleUpCount := maxTotalPods - currentPodCount
scaleUpCount = int(math.Min(float64(scaleUpCount), float64(deployment.Spec.Replicas-newRC.Spec.Replicas)))
_, err = d.scaleRC(newRC, newRC.Spec.Replicas+scaleUpCount)
return true, err
}
func (d *DeploymentController) scaleDown(allRCs []*api.ReplicationController, oldRCs []*api.ReplicationController, newRC *api.ReplicationController, deployment experimental.Deployment) (bool, error) {
oldPodsCount := d.getReplicaCountForRCs(oldRCs)
if oldPodsCount == 0 {
// Cant scale down further
return false, nil
}
maxUnavailable, isPercent, err := util.GetIntOrPercentValue(&deployment.Spec.Strategy.RollingUpdate.MaxUnavailable)
if err != nil {
return false, fmt.Errorf("invalid value for MaxUnavailable: %v", err)
}
if isPercent {
maxUnavailable = util.GetValueFromPercent(maxUnavailable, deployment.Spec.Replicas)
}
// Check if we can scale down.
minAvailable := deployment.Spec.Replicas - maxUnavailable
// Find the number of ready pods.
// TODO: Use MinReadySeconds once https://github.com/kubernetes/kubernetes/pull/12894 is merged.
readyPodCount := 0
allPods, err := d.getPodsForRCs(allRCs)
for _, pod := range allPods {
if api.IsPodReady(&pod) {
readyPodCount++
}
}
if readyPodCount <= minAvailable {
// Cannot scale down.
return false, nil
}
totalScaleDownCount := readyPodCount - minAvailable
for _, targetRC := range oldRCs {
if totalScaleDownCount == 0 {
// No further scaling required.
break
}
if targetRC.Spec.Replicas == 0 {
// cannot scale down this RC.
continue
}
// Scale down.
scaleDownCount := int(math.Min(float64(targetRC.Spec.Replicas), float64(totalScaleDownCount)))
_, err = d.scaleRC(targetRC, targetRC.Spec.Replicas-scaleDownCount)
if err != nil {
return false, err
}
totalScaleDownCount -= scaleDownCount
}
return true, err
}
func (d *DeploymentController) updateDeploymentStatus(allRCs []*api.ReplicationController, newRC *api.ReplicationController, deployment experimental.Deployment) error {
totalReplicas := d.getReplicaCountForRCs(allRCs)
updatedReplicas := d.getReplicaCountForRCs([]*api.ReplicationController{newRC})
newDeployment := deployment
// TODO: Reconcile this with API definition. API definition talks about ready pods, while this just computes created pods.
newDeployment.Status = experimental.DeploymentStatus{
Replicas: totalReplicas,
UpdatedReplicas: updatedReplicas,
}
_, err := d.updateDeployment(&newDeployment)
return err
}
func (d *DeploymentController) scaleRC(rc *api.ReplicationController, newScale int) (*api.ReplicationController, error) {
// TODO: Using client for now, update to use store when it is ready.
rc.Spec.Replicas = newScale
return d.client.ReplicationControllers(rc.ObjectMeta.Namespace).Update(rc)
}
func (d *DeploymentController) updateDeployment(deployment *experimental.Deployment) (*experimental.Deployment, error) {
// TODO: Using client for now, update to use store when it is ready.
return d.client.Experimental().Deployments(deployment.ObjectMeta.Namespace).Update(deployment)
}<|fim▁end|> | }
} |
<|file_name|>test_hyperlink15.py<|end_file_name|><|fim▁begin|>###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, [email protected]
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'hyperlink15.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks.This example doesn't have any link formatting and tests the relationshiplinkage code."""
workbook = Workbook(self.got_filename)
# Turn off default URL format for testing.
workbook.default_url_format = None
worksheet = workbook.add_worksheet()
worksheet.write_url('B2', 'external:subdir/blank.xlsx')
workbook.close()<|fim▁hole|>
self.assertExcelEqual()<|fim▁end|> | |
<|file_name|>channel.rs<|end_file_name|><|fim▁begin|>use std::any::Any;
use std::fmt;
use std::sync::{Arc, Mutex};
use std::collections::VecDeque;
use base::types::{ArcType, Type};
use {Error, Result as VmResult};
use api::record::{Record, HList};
use api::{Generic, VmType, primitive, WithVM, Function, Pushable, RuntimeResult};
use api::generic::A;
use gc::{Traverseable, Gc, GcPtr};
use vm::{Thread, RootedThread, Status};
use thread::ThreadInternal;
use value::{Userdata, Value};
use stack::{State, StackFrame};
pub struct Sender<T> {
// No need to traverse this thread reference as any thread having a reference to this `Sender`
// would also directly own a reference to the `Thread`
thread: GcPtr<Thread>,
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> Userdata for Sender<T> where T: Any + Send + Sync + fmt::Debug + Traverseable, {}
impl<T> fmt::Debug for Sender<T>
where T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Traverseable for Sender<T> {
fn traverse(&self, _gc: &mut Gc) {
// No need to traverse in Sender as values can only be accessed through Receiver
}
}
impl<T> Sender<T> {
fn send(&self, value: T) {
self.queue.lock().unwrap().push_back(value);
}
}
impl<T: Traverseable> Traverseable for Receiver<T> {
fn traverse(&self, gc: &mut Gc) {
self.queue.lock().unwrap().traverse(gc);
}
}
pub struct Receiver<T> {
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> Userdata for Receiver<T> where T: Any + Send + Sync + fmt::Debug + Traverseable, {}
impl<T> fmt::Debug for Receiver<T>
where T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Receiver<T> {
fn try_recv(&self) -> Result<T, ()> {
self.queue
.lock()
.unwrap()
.pop_front()
.ok_or(())
}
}
impl<T: VmType> VmType for Sender<T>
where T::Type: Sized,
{
type Type = Sender<T::Type>;
fn make_type(vm: &Thread) -> ArcType {
let symbol = vm.global_env().get_env().find_type_info("Sender").unwrap().name.clone();
Type::app(Type::ident(symbol), vec![T::make_type(vm)])
}
}
impl<T: VmType> VmType for Receiver<T>
where T::Type: Sized,
{
type Type = Receiver<T::Type>;
fn make_type(vm: &Thread) -> ArcType {
let symbol = vm.global_env().get_env().find_type_info("Receiver").unwrap().name.clone();
Type::app(Type::ident(symbol), vec![T::make_type(vm)])
}
}
<|fim▁hole|>
pub type ChannelRecord<S, R> = Record<HList<(_field::sender, S), HList<(_field::receiver, R), ()>>>;
/// FIXME The dummy `a` argument should not be needed to ensure that the channel can only be used
/// with a single type
fn channel(WithVM { vm, .. }: WithVM<Generic<A>>)
-> ChannelRecord<Sender<Generic<A>>, Receiver<Generic<A>>> {
let sender = Sender {
thread: unsafe { GcPtr::from_raw(vm) },
queue: Arc::new(Mutex::new(VecDeque::new())),
};
let receiver = Receiver { queue: sender.queue.clone() };
record_no_decl!(sender => sender, receiver => receiver)
}
fn recv(receiver: &Receiver<Generic<A>>) -> Result<Generic<A>, ()> {
receiver.try_recv()
.map_err(|_| ())
}
fn send(sender: &Sender<Generic<A>>, value: Generic<A>) -> Result<(), ()> {
let value = try!(sender.thread.deep_clone(value.0).map_err(|_| ()));
Ok(sender.send(Generic::from(value)))
}
fn resume(vm: &Thread) -> Status {
let mut context = vm.context();
let value = StackFrame::current(&mut context.stack)[0];
match value {
Value::Thread(child) => {
let lock = StackFrame::current(&mut context.stack).into_lock();
drop(context);
let result = child.resume();
context = vm.context();
context.stack.release_lock(lock);
match result {
Ok(()) |
Err(Error::Yield) => {
let value: Result<(), &str> = Ok(());
value.status_push(vm, &mut context)
}
Err(Error::Dead) => {
let value: Result<(), &str> = Err("Attempted to resume a dead thread");
value.status_push(vm, &mut context)
}
Err(err) => {
let fmt = format!("{}", err);
let result = Value::String(context.alloc_ignore_limit(&fmt[..]));
context.stack.push(result);
Status::Error
}
}
}
_ => unreachable!(),
}
}
fn yield_(_vm: &Thread) -> Status {
Status::Yield
}
fn spawn<'vm>(value: WithVM<'vm, Function<&'vm Thread, fn(())>>)
-> RuntimeResult<RootedThread, Error> {
match spawn_(value) {
Ok(x) => RuntimeResult::Return(x),
Err(err) => RuntimeResult::Panic(err),
}
}
fn spawn_<'vm>(value: WithVM<'vm, Function<&'vm Thread, fn(())>>) -> VmResult<RootedThread> {
let thread = try!(value.vm.new_thread());
{
let mut context = thread.context();
let callable = match value.value.value() {
Value::Closure(c) => State::Closure(c),
Value::Function(c) => State::Extern(c),
_ => State::Unknown,
};
try!(value.value.push(value.vm, &mut context));
context.stack.push(Value::Int(0));
StackFrame::current(&mut context.stack).enter_scope(1, callable);
}
Ok(thread)
}
fn f1<A, R>(f: fn(A) -> R) -> fn(A) -> R {
f
}
fn f2<A, B, R>(f: fn(A, B) -> R) -> fn(A, B) -> R {
f
}
pub fn load(vm: &Thread) -> VmResult<()> {
let _ = vm.register_type::<Sender<A>>("Sender", &["a"]);
let _ = vm.register_type::<Receiver<A>>("Receiver", &["a"]);
try!(vm.define_global("channel", f1(channel)));
try!(vm.define_global("recv", f1(recv)));
try!(vm.define_global("send", f2(send)));
try!(vm.define_global("resume",
primitive::<fn(RootedThread) -> Result<(), String>>("resume", resume)));
try!(vm.define_global("yield", primitive::<fn(())>("yield", yield_)));
try!(vm.define_global("spawn", f1(spawn)));
Ok(())
}<|fim▁end|> | field_decl!{ sender, receiver }
|
<|file_name|>flow.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
from taskflow.utils import reflection
class Flow(six.with_metaclass(abc.ABCMeta)):
"""The base abstract class of all flow implementations.
A flow is a structure that defines relationships between tasks. You can
add tasks and other flows (as subflows) to the flow, and the flow provides
a way to implicitly or explicitly define how they are interdependent.
Exact structure of the relationships is defined by concrete
implementation, while this class defines common interface and adds
human-readable (not necessary unique) name.
NOTE(harlowja): if a flow is placed in another flow as a subflow, a desired
way to compose flows together, then it is valid and permissible that during
execution the subflow & parent flow may be flattened into a new flow. Since
a flow is just a 'structuring' concept this is typically a behavior that
should not be worried about (as it is not visible to the user), but it is
worth mentioning here.
Flows are expected to provide the following methods/properties:
- add
- __len__
- requires
- provides
"""
def __init__(self, name):
self._name = str(name)
@property
def name(self):
"""A non-unique name for this flow (human readable)"""
return self._name
@abc.abstractmethod
def __len__(self):
"""Returns how many items are in this flow."""
<|fim▁hole|> lines = ["%s: %s" % (reflection.get_class_name(self), self.name)]
lines.append("%s" % (len(self)))
return "; ".join(lines)
@abc.abstractmethod
def add(self, *items):
"""Adds a given item/items to this flow."""
@abc.abstractproperty
def requires(self):
"""Browse argument requirement names this flow requires to run."""
@abc.abstractproperty
def provides(self):
"""Browse argument names provided by the flow."""<|fim▁end|> | def __str__(self): |
<|file_name|>scan_results.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
Script to fetch test status info from sqlit data base. Before use this
script, avocado We must be lanuch with '--journal' option.
"""
import os
import sys
import sqlite3
import argparse
from avocado.core import data_dir
from dateutil import parser as dateparser
def colour_result(result):
"""Colour result in the test status info"""
colours_map = {"PASS": "\033[92mPASS\033[00m",
"ERROR": "\033[93mERROR\033[00m",
"FAIL": "\033[91mFAIL\033[00m"}
return colours_map.get(result) or result
def summarise_records(records):
"""Summarise test records and print it in cyan"""
num_row = len(records[0])
rows = tuple([("row%s" % x) for x in xrange(num_row)])
records_summary = {}
for rows in records:
records_summary[rows[1]] = records_summary.get(rows[1], 0) + 1
records_summary[rows[4]] = records_summary.get(rows[4], 0) + 1
res = ", ".join("%s=%r" % (
key, val) for (key, val) in records_summary.iteritems())
print "\033[96mSummary: \n" + res + "\033[00m"
def get_total_seconds(td):
""" Alias for get total_seconds in python2.6 """
if hasattr(td, 'total_seconds'):
return td.total_seconds()
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6
def fetch_data(db_file=".journal.sqlite"):
""" Fetch tests status info from journal database"""
records = []
con = sqlite3.connect(db_file)
try:
cur = con.cursor()
cur.execute("select tag, time, action, status from test_journal")
while True:
# First record contation start info, second contain end info
# merged start info and end info into one record.
data = cur.fetchmany(2)
if not data:
break
tag = data[0][0]
result = "N/A"
status = "Running"
end_time = None
end_str = None
elapsed = None
start_time = dateparser.parse(data[0][1])
start_str = start_time.strftime("%Y-%m-%d %X")
if len(data) > 1:
status = "Finshed"
result = data[1][3]
end_time = dateparser.parse(data[1][1])
time_delta = end_time - start_time
elapsed = get_total_seconds(time_delta)
end_str = end_time.strftime("%Y-%m-%d %X")
record = (tag, status, start_str, end_str, result, elapsed)
records.append(record)
finally:
con.close()
return records
def print_data(records, skip_timestamp=False):
""" Print formated tests status info"""
if not records:
return
if not skip_timestamp:
print "%-40s %-15s %-15s %-15s %-10s %-10s" % (
"CaseName", "Status", "StartTime",
"EndTime", "Result", "TimeElapsed")
else:
print "%-40s %-15s %-10s" % ("CaseName", "Status", "Result")
for row in records:
if not skip_timestamp:
print "%s %s %s %s %s %s" % (
row[0], row[1], row[2], row[3], colour_result(row[4]), row[5])
else:
print "%s %s %s" % (row[0], row[1], colour_result(row[4]))
summarise_records(records)
if __name__ == "__main__":
default_results_dir = os.path.join(data_dir.get_logs_dir(), 'latest')
parser = argparse.ArgumentParser(description="Avocado journal dump tool")
parser.add_argument(<|fim▁hole|> default=default_results_dir,
dest='results_dir',
help="avocado test results dir, Default: %s" %
default_results_dir)
parser.add_argument(
'-s',
'--skip-timestamp',
action='store_true',
default=False,
dest='skip_timestamp',
help="skip timestamp output (leaving status and result enabled)")
parser.add_argument(
'-v',
'--version',
action='version',
version='%(prog)s 1.0')
arguments = parser.parse_args()
db_file = os.path.join(arguments.results_dir, '.journal.sqlite')
if not os.path.isfile(db_file):
print "`.journal.sqlite` DB not found in results directory, "
print "Please start avocado with option '--journal'."
parser.print_help()
sys.exit(1)
data = fetch_data(db_file)
print_data(data, arguments.skip_timestamp)<|fim▁end|> | '-d',
'--test-results-dir',
action='store', |
<|file_name|>from_hex.py<|end_file_name|><|fim▁begin|># Copyright (C) 2009-2010 Sergey Koposov
# This file is part of astrolibpy
#
# astrolibpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# astrolibpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with astrolibpy. If not, see <http://www.gnu.org/licenses/>.
import numpy, re
def from_hex(arr, delim=':'):
r=re.compile('\s*(\-?)(.+)%s(.+)%s(.+)'%(delim,delim))
ret=[]
for a in arr:
m = r.search(a)
sign = m.group(1)=='-'
if sign:
sign=-1
else:
sign=1
i1 = int(m.group(2))<|fim▁hole|> i2 = int(m.group(3))
i3 = float(m.group(4))
val = sign*(int(i1)+int(i2)/60.+(float(i3))/3600.)
ret.append(val)
return numpy.array(ret)<|fim▁end|> | |
<|file_name|>BeanException.java<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2015 See AUTHORS file
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mini2Dx.core.di.exception;
/**
* A base class for bean exceptions
*/
public class BeanException extends Exception {<|fim▁hole|> super(message);
}
}<|fim▁end|> | private static final long serialVersionUID = 4487528732406582847L;
public BeanException(String message) { |
<|file_name|>cover.py<|end_file_name|><|fim▁begin|>"""Platform for the Garadget cover component."""
import logging
import requests
import voluptuous as vol
from homeassistant.components.cover import PLATFORM_SCHEMA, CoverDevice
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_COVERS,
CONF_DEVICE,
CONF_NAME,
CONF_PASSWORD,
CONF_USERNAME,
STATE_CLOSED,
STATE_OPEN,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_utc_time_change
_LOGGER = logging.getLogger(__name__)
ATTR_AVAILABLE = "available"
ATTR_SENSOR_STRENGTH = "sensor_reflection_rate"
ATTR_SIGNAL_STRENGTH = "wifi_signal_strength"
ATTR_TIME_IN_STATE = "time_in_state"
DEFAULT_NAME = "Garadget"
STATE_CLOSING = "closing"
STATE_OFFLINE = "offline"
STATE_OPENING = "opening"
STATE_STOPPED = "stopped"
STATES_MAP = {
"open": STATE_OPEN,
"opening": STATE_OPENING,
"closed": STATE_CLOSED,
"closing": STATE_CLOSING,
"stopped": STATE_STOPPED,
}
COVER_SCHEMA = vol.Schema(
{
vol.Optional(CONF_ACCESS_TOKEN): cv.string,
vol.Optional(CONF_DEVICE): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_USERNAME): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_COVERS): cv.schema_with_slug_keys(COVER_SCHEMA)}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Garadget covers."""
covers = []
devices = config.get(CONF_COVERS)
for device_id, device_config in devices.items():
args = {
"name": device_config.get(CONF_NAME),
"device_id": device_config.get(CONF_DEVICE, device_id),
"username": device_config.get(CONF_USERNAME),
"password": device_config.get(CONF_PASSWORD),
"access_token": device_config.get(CONF_ACCESS_TOKEN),
}
covers.append(GaradgetCover(hass, args))
add_entities(covers)
class GaradgetCover(CoverDevice):
"""Representation of a Garadget cover."""
def __init__(self, hass, args):
"""Initialize the cover."""
self.particle_url = "https://api.particle.io"
self.hass = hass
self._name = args["name"]
self.device_id = args["device_id"]
self.access_token = args["access_token"]
self.obtained_token = False
self._username = args["username"]
self._password = args["password"]
self._state = None
self.time_in_state = None
self.signal = None
self.sensor = None
self._unsub_listener_cover = None
self._available = True
if self.access_token is None:
self.access_token = self.get_token()
self._obtained_token = True
try:
if self._name is None:
doorconfig = self._get_variable("doorConfig")
if doorconfig["nme"] is not None:
self._name = doorconfig["nme"]
self.update()
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to server: %(reason)s", dict(reason=ex))
self._state = STATE_OFFLINE
self._available = False
self._name = DEFAULT_NAME
except KeyError:
_LOGGER.warning(
"Garadget device %(device)s seems to be offline",
dict(device=self.device_id),
)
self._name = DEFAULT_NAME
self._state = STATE_OFFLINE
self._available = False
def __del__(self):
"""Try to remove token."""
if self._obtained_token is True:
if self.access_token is not None:
self.remove_token()
@property<|fim▁hole|> """Return the name of the cover."""
return self._name
@property
def should_poll(self):
"""No polling needed for a demo cover."""
return True
@property
def available(self):
"""Return True if entity is available."""
return self._available
@property
def device_state_attributes(self):
"""Return the device state attributes."""
data = {}
if self.signal is not None:
data[ATTR_SIGNAL_STRENGTH] = self.signal
if self.time_in_state is not None:
data[ATTR_TIME_IN_STATE] = self.time_in_state
if self.sensor is not None:
data[ATTR_SENSOR_STRENGTH] = self.sensor
if self.access_token is not None:
data[CONF_ACCESS_TOKEN] = self.access_token
return data
@property
def is_closed(self):
"""Return if the cover is closed."""
if self._state is None:
return None
return self._state == STATE_CLOSED
@property
def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return "garage"
def get_token(self):
"""Get new token for usage during this session."""
args = {
"grant_type": "password",
"username": self._username,
"password": self._password,
}
url = f"{self.particle_url}/oauth/token"
ret = requests.post(url, auth=("particle", "particle"), data=args, timeout=10)
try:
return ret.json()["access_token"]
except KeyError:
_LOGGER.error("Unable to retrieve access token")
def remove_token(self):
"""Remove authorization token from API."""
url = f"{self.particle_url}/v1/access_tokens/{self.access_token}"
ret = requests.delete(url, auth=(self._username, self._password), timeout=10)
return ret.text
def _start_watcher(self, command):
"""Start watcher."""
_LOGGER.debug("Starting Watcher for command: %s ", command)
if self._unsub_listener_cover is None:
self._unsub_listener_cover = track_utc_time_change(
self.hass, self._check_state
)
def _check_state(self, now):
"""Check the state of the service during an operation."""
self.schedule_update_ha_state(True)
def close_cover(self, **kwargs):
"""Close the cover."""
if self._state not in ["close", "closing"]:
ret = self._put_command("setState", "close")
self._start_watcher("close")
return ret.get("return_value") == 1
def open_cover(self, **kwargs):
"""Open the cover."""
if self._state not in ["open", "opening"]:
ret = self._put_command("setState", "open")
self._start_watcher("open")
return ret.get("return_value") == 1
def stop_cover(self, **kwargs):
"""Stop the door where it is."""
if self._state not in ["stopped"]:
ret = self._put_command("setState", "stop")
self._start_watcher("stop")
return ret["return_value"] == 1
def update(self):
"""Get updated status from API."""
try:
status = self._get_variable("doorStatus")
_LOGGER.debug("Current Status: %s", status["status"])
self._state = STATES_MAP.get(status["status"], None)
self.time_in_state = status["time"]
self.signal = status["signal"]
self.sensor = status["sensor"]
self._available = True
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to server: %(reason)s", dict(reason=ex))
self._state = STATE_OFFLINE
except KeyError:
_LOGGER.warning(
"Garadget device %(device)s seems to be offline",
dict(device=self.device_id),
)
self._state = STATE_OFFLINE
if self._state not in [STATE_CLOSING, STATE_OPENING]:
if self._unsub_listener_cover is not None:
self._unsub_listener_cover()
self._unsub_listener_cover = None
def _get_variable(self, var):
"""Get latest status."""
url = "{}/v1/devices/{}/{}?access_token={}".format(
self.particle_url, self.device_id, var, self.access_token
)
ret = requests.get(url, timeout=10)
result = {}
for pairs in ret.json()["result"].split("|"):
key = pairs.split("=")
result[key[0]] = key[1]
return result
def _put_command(self, func, arg=None):
"""Send commands to API."""
params = {"access_token": self.access_token}
if arg:
params["command"] = arg
url = f"{self.particle_url}/v1/devices/{self.device_id}/{func}"
ret = requests.post(url, data=params, timeout=10)
return ret.json()<|fim▁end|> | def name(self): |
<|file_name|>defaults.py<|end_file_name|><|fim▁begin|>"""
Misago default settings
This fille sets everything Misago needs to run.
If you want to add custom app, middleware or path, please update setting vallue
defined in this file instead of copying setting from here to your settings.py.
Yes:
#yourproject/settings.py
INSTALLED_APPS += (
'myawesomeapp',
)
No:
#yourproject/settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'misago.core',
'misago.conf',
...
'myawesomeapp',
)
"""
# Build paths inside the project like this: os.path.join(MISAGO_BASE_DIR, ...)
import os
MISAGO_BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Default JS debug to false
# This setting used exclusively by test runner and isn't part of public API
_MISAGO_JS_DEBUG = False
# Assets Pipeline
# See http://django-pipeline.readthedocs.org/en/latest/configuration.html
PIPELINE_CSS = {
'misago_admin': {
'source_filenames': (
'misago/admin/css/style.less',
),
'output_filename': 'misago_admin.css',
},
}
PIPELINE_JS = {
'misago_admin': {
'source_filenames': (
'misago/admin/js/jquery.js',
'misago/admin/js/bootstrap.js',
'misago/admin/js/moment.min.js',
'misago/admin/js/bootstrap-datetimepicker.min.js',
'misago/admin/js/misago-datetimepicker.js',
'misago/admin/js/misago-timestamps.js',
'misago/admin/js/misago-tooltips.js',
'misago/admin/js/misago-tables.js',
'misago/admin/js/misago-yesnoswitch.js',
),<|fim▁hole|>PIPELINE_COMPILERS = (
'pipeline.compilers.less.LessCompiler',
)
PIPELINE_TEMPLATE_EXT = '.hbs'
PIPELINE_TEMPLATE_FUNC = 'Ember.Handlebars.compile'
PIPELINE_TEMPLATE_NAMESPACE = 'window.Ember.TEMPLATES'
PIPELINE_TEMPLATE_SEPARATOR = '/'
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor'
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
# Keep misago.users above django.contrib.auth
# so our management commands take precedence over theirs
'misago.users',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'debug_toolbar',
'pipeline',
'crispy_forms',
'mptt',
'rest_framework',
'misago.admin',
'misago.acl',
'misago.core',
'misago.conf',
'misago.markup',
'misago.notifications',
'misago.legal',
'misago.forums',
'misago.threads',
'misago.readtracker',
'misago.faker',
)
MIDDLEWARE_CLASSES = (
'misago.core.middleware.embercliredirects.EmberCLIRedirectsMiddleware',
'misago.users.middleware.AvatarServerMiddleware',
'misago.users.middleware.RealIPMiddleware',
'misago.core.middleware.frontendcontext.FrontendContextMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'misago.users.middleware.UserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'misago.core.middleware.exceptionhandler.ExceptionHandlerMiddleware',
'misago.users.middleware.OnlineTrackerMiddleware',
'misago.admin.middleware.AdminAuthMiddleware',
'misago.threads.middleware.UnreadThreadsCountMiddleware',
'misago.core.middleware.threadstore.ThreadStoreMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'misago.core.context_processors.site_address',
'misago.conf.context_processors.settings',
'misago.users.context_processors.sites_links',
# Data preloaders
'misago.conf.context_processors.preload_settings_json',
'misago.users.context_processors.preload_user_json',
# Note: keep frontend_context processor last for previous processors
# to be able to add data to request.frontend_context
'misago.core.context_processors.frontend_context',
)
MISAGO_ACL_EXTENSIONS = (
'misago.users.permissions.account',
'misago.users.permissions.profiles',
'misago.users.permissions.warnings',
'misago.users.permissions.moderation',
'misago.users.permissions.delete',
'misago.forums.permissions',
'misago.threads.permissions.threads',
'misago.threads.permissions.privatethreads',
)
MISAGO_MARKUP_EXTENSIONS = ()
MISAGO_POSTING_MIDDLEWARES = (
# Note: always keep FloodProtectionMiddleware middleware first one
'misago.threads.posting.floodprotection.FloodProtectionMiddleware',
'misago.threads.posting.reply.ReplyFormMiddleware',
'misago.threads.posting.participants.ThreadParticipantsFormMiddleware',
'misago.threads.posting.threadlabel.ThreadLabelFormMiddleware',
'misago.threads.posting.threadpin.ThreadPinFormMiddleware',
'misago.threads.posting.threadclose.ThreadCloseFormMiddleware',
'misago.threads.posting.recordedit.RecordEditMiddleware',
'misago.threads.posting.updatestats.UpdateStatsMiddleware',
# Note: always keep SaveChangesMiddleware middleware last one
'misago.threads.posting.savechanges.SaveChangesMiddleware',
)
MISAGO_THREAD_TYPES = (
# category and redirect types
'misago.forums.forumtypes.RootCategory',
'misago.forums.forumtypes.Category',
'misago.forums.forumtypes.Redirect',
# real thread types
'misago.threads.threadtypes.forumthread.ForumThread',
'misago.threads.threadtypes.privatethread.PrivateThread',
'misago.threads.threadtypes.report.Report',
)
# Register Misago directories
LOCALE_PATHS = (
os.path.join(MISAGO_BASE_DIR, 'locale'),
)
STATICFILES_DIRS = (
os.path.join(MISAGO_BASE_DIR, 'static'),
)
TEMPLATE_DIRS = (
os.path.join(MISAGO_BASE_DIR, 'templates'),
)
# Internationalization
USE_I18N = True
USE_L10N = True
USE_TZ = True
TIME_ZONE = 'UTC'
# Misago specific date formats
# https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
MISAGO_COMPACT_DATE_FORMAT_DAY_MONTH = 'j M'
MISAGO_COMPACT_DATE_FORMAT_DAY_MONTH_YEAR = 'M \'y'
# Use Misago CSRF Failure Page
CSRF_FAILURE_VIEW = 'misago.core.errorpages.csrf_failure'
# Use Misago authentication
AUTH_USER_MODEL = 'misago_users.User'
AUTHENTICATION_BACKENDS = (
'misago.users.authbackends.MisagoBackend',
)
MISAGO_NEW_REGISTRATIONS_VALIDATORS = (
'misago.users.validators.validate_gmail_email',
'misago.users.validators.validate_with_sfs',
)
MISAGO_STOP_FORUM_SPAM_USE = True
MISAGO_STOP_FORUM_SPAM_MIN_CONFIDENCE = 80
# How many e-mails should be sent in single step.
# This is used for conserving memory usage when mailing many users at same time
MISAGO_MAILER_BATCH_SIZE = 20
# Auth paths
MISAGO_LOGIN_API_URL = 'auth'
LOGIN_REDIRECT_URL = 'misago:index'
LOGIN_URL = 'misago:login'
LOGOUT_URL = 'misago:logout'
# Misago Admin Path
# Omit starting and trailing slashes
# To disable Misago admin, empty this value
MISAGO_ADMIN_PATH = 'admincp'
# Admin urls namespaces that Misago's AdminAuthMiddleware should protect
MISAGO_ADMIN_NAMESPACES = (
'admin',
'misago:admin',
)
# How long (in minutes) since previous request to admin namespace should
# admin session last.
MISAGO_ADMIN_SESSION_EXPIRATION = 60
# Max age of notifications in days
# Notifications older than this are deleted
# On very active forums its better to keep this smaller
MISAGO_NOTIFICATIONS_MAX_AGE = 40
# Fail-safe limits in case forum is raided by spambot
# No user may exceed those limits, however you may disable
# them by changing them to 0
MISAGO_DIALY_POST_LIMIT = 600
MISAGO_HOURLY_POST_LIMIT = 100
# Function used for generating individual avatar for user
MISAGO_DYNAMIC_AVATAR_DRAWER = 'misago.users.avatars.dynamic.draw_default'
# For which sizes avatars should be cached
# Keep sizes ordered from greatest to smallest
# Max size also controls min size of uploaded image as well as crop size
MISAGO_AVATARS_SIZES = (200, 150, 100, 64, 50, 30, 20)
# Path to avatar server
# This path is used to detect avatar requests, which bypass most of
# Request/Response processing for performance reasons
MISAGO_AVATAR_SERVER_PATH = '/user-avatar'
# Number of posts displayed on single thread page
MISAGO_POSTS_PER_PAGE = 15
MISAGO_THREAD_TAIL = 7
# Controls max age in days of items that Misago has to process to make rankings
# Used for active posters and most liked users lists
# If your forum runs out of memory when trying to generate users rankings list
# or you want those to be more dynamic, give this setting lower value
# You don't have to be overzelous with this as user rankings are cached for 24h
MISAGO_RANKING_LENGTH = 30
# Controls max number of items displayed on ranked lists
MISAGO_RANKING_SIZE = 50
# Controls max number of items displayed on online list
MISAGO_ONLINE_LIST_SIZE = 50
# For how long should online list be cached (in seconds)
MISAGO_ONLINE_LIST_CACHE = 40
# Controls number of users displayed on single page
MISAGO_USERS_PER_PAGE = 12
# Controls amount of data used for new threads/replies lists
# Only unread threads younger than number of days specified in this setting
# will be considered fresh for "new threads" list
# Only unread threads with last reply younger than number of days specified
# there will be confidered fresh for "Threads with unread replies" list
MISAGO_FRESH_CONTENT_PERIOD = 40
# Number of minutes between updates of new content counts like new threads,
# unread replies or moderated threads/posts
MISAGO_CONTENT_COUNTING_FREQUENCY = 5
# X-Sendfile
# X-Sendfile is feature provided by Http servers that allows web apps to
# delegate serving files over to the better performing server instead of
# doing it within app.
# If your server supports X-Sendfile or its variation, enter header name here.
# For example if you are using Nginx with X-accel enabled, set this setting
# to "X-Accel-Redirect".
# Leave this setting empty to Django fallback instead
MISAGO_SENDFILE_HEADER = ''
# Allows you to use location feature of your Http server
# For example, if you have internal location /mymisago/avatar_cache/
# that points at /home/myweb/misagoforum/avatar_cache/, set this setting
# to "mymisago".
MISAGO_SENDFILE_LOCATIONS_PATH = ''
# Default forms templates
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# Ember-CLI dev server address, used in rewriting redirects in dev
# If you are using different port to run Ember-CLI dev server,
# override this setting in your settings.py.
MISAGO_EMBER_CLI_ORIGIN = 'http://localhost:4200'
# Rest Framework Configuration
REST_FRAMEWORK = {
'UNAUTHENTICATED_USER': 'misago.users.models.AnonymousUser',
'EXCEPTION_HANDLER': 'misago.core.exceptionhandler.handle_api_exception',
'DEFAULT_PERMISSION_CLASSES': (
'misago.users.rest_permissions.IsAuthenticatedOrReadOnly',
)
}
# Register Misago debug panels
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'misago.acl.panels.MisagoACLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
)<|fim▁end|> | 'output_filename': 'misago_admin.js',
},
}
|
<|file_name|>issue_315.rs<|end_file_name|><|fim▁begin|>#![allow(
dead_code,
non_snake_case,
non_camel_case_types,<|fim▁hole|>)]
/// <div rustbindgen replaces="c"></div>
pub type c<a> = a;<|fim▁end|> | non_upper_case_globals |
<|file_name|>ngb-calendar-islamic-umalqura.ts<|end_file_name|><|fim▁begin|>import {NgbCalendarIslamicCivil} from './ngb-calendar-islamic-civil';
import {NgbDate} from '../ngb-date';
import {Injectable} from '@angular/core';
/**
* Umalqura calendar is one type of Hijri calendars used in islamic countries.
* This Calendar is used by Saudi Arabia for administrative purpose.
* Unlike tabular calendars, the algorithm involves astronomical calculation, but it's still deterministic.
* http://cldr.unicode.org/development/development-process/design-proposals/islamic-calendar-types
*/
const GREGORIAN_FIRST_DATE = new Date(1882, 10, 12);
const GREGORIAN_LAST_DATE = new Date(2174, 10, 25);
const HIJRI_BEGIN = 1300;
const HIJRI_END = 1600;
const ONE_DAY = 1000 * 60 * 60 * 24;
const MONTH_LENGTH = [
// 1300-1304
'101010101010', '110101010100', '111011001001', '011011010100', '011011101010',
// 1305-1309
'001101101100', '101010101101', '010101010101', '011010101001', '011110010010',
// 1310-1314
'101110101001', '010111010100', '101011011010', '010101011100', '110100101101',
// 1315-1319
'011010010101', '011101001010', '101101010100', '101101101010', '010110101101',
// 1320-1324
'010010101110', '101001001111', '010100010111', '011010001011', '011010100101',
// 1325-1329
'101011010101', '001011010110', '100101011011', '010010011101', '101001001101',
// 1330-1334
'110100100110', '110110010101', '010110101100', '100110110110', '001010111010',
// 1335-1339
'101001011011', '010100101011', '101010010101', '011011001010', '101011101001',
// 1340-1344
'001011110100', '100101110110', '001010110110', '100101010110', '101011001010',
// 1345-1349
'101110100100', '101111010010', '010111011001', '001011011100', '100101101101',
// 1350-1354
'010101001101', '101010100101', '101101010010', '101110100101', '010110110100',
// 1355-1359
'100110110110', '010101010111', '001010010111', '010101001011', '011010100011',
// 1360-1364
'011101010010', '101101100101', '010101101010', '101010101011', '010100101011',
// 1365-1369
'110010010101', '110101001010', '110110100101', '010111001010', '101011010110',
// 1370-1374
'100101010111', '010010101011', '100101001011', '101010100101', '101101010010',
// 1375-1379
'101101101010', '010101110101', '001001110110', '100010110111', '010001011011',
// 1380-1384
'010101010101', '010110101001', '010110110100', '100111011010', '010011011101',
// 1385-1389
'001001101110', '100100110110', '101010101010', '110101010100', '110110110010',
// 1390-1394
'010111010101', '001011011010', '100101011011', '010010101011', '101001010101',
// 1395-1399
'101101001001', '101101100100', '101101110001', '010110110100', '101010110101',
// 1400-1404
'101001010101', '110100100101', '111010010010', '111011001001', '011011010100',
// 1405-1409
'101011101001', '100101101011', '010010101011', '101010010011', '110101001001',
// 1410-1414
'110110100100', '110110110010', '101010111001', '010010111010', '101001011011',
// 1415-1419
'010100101011', '101010010101', '101100101010', '101101010101', '010101011100',
// 1420-1424
'010010111101', '001000111101', '100100011101', '101010010101', '101101001010',
// 1425-1429
'101101011010', '010101101101', '001010110110', '100100111011', '010010011011',
// 1430-1434
'011001010101', '011010101001', '011101010100', '101101101010', '010101101100',
// 1435-1439
'101010101101', '010101010101', '101100101001', '101110010010', '101110101001',
// 1440-1444
'010111010100', '101011011010', '010101011010', '101010101011', '010110010101',
// 1445-1449
'011101001001', '011101100100', '101110101010', '010110110101', '001010110110',
// 1450-1454
'101001010110', '111001001101', '101100100101', '101101010010', '101101101010',
// 1455-1459
'010110101101', '001010101110', '100100101111', '010010010111', '011001001011',
// 1460-1464
'011010100101', '011010101100', '101011010110', '010101011101', '010010011101',
// 1465-1469
'101001001101', '110100010110', '110110010101', '010110101010', '010110110101',
// 1470-1474
'001011011010', '100101011011', '010010101101', '010110010101', '011011001010',
// 1475-1479
'011011100100', '101011101010', '010011110101', '001010110110', '100101010110',
// 1480-1484
'101010101010', '101101010100', '101111010010', '010111011001', '001011101010',
// 1485-1489
'100101101101', '010010101101', '101010010101', '101101001010', '101110100101',
// 1490-1494
'010110110010', '100110110101', '010011010110', '101010010111', '010101000111',
// 1495-1499
'011010010011', '011101001001', '101101010101', '010101101010', '101001101011',
// 1500-1504
'010100101011', '101010001011', '110101000110', '110110100011', '010111001010',
// 1505-1509
'101011010110', '010011011011', '001001101011', '100101001011', '101010100101',
// 1510-1514
'101101010010', '101101101001', '010101110101', '000101110110', '100010110111',
// 1515-1519
'001001011011', '010100101011', '010101100101', '010110110100', '100111011010',
// 1520-1524
'010011101101', '000101101101', '100010110110', '101010100110', '110101010010',
// 1525-1529
'110110101001', '010111010100', '101011011010', '100101011011', '010010101011',
// 1530-1534
'011001010011', '011100101001', '011101100010', '101110101001', '010110110010',
// 1535-1539
'101010110101', '010101010101', '101100100101', '110110010010', '111011001001',
// 1540-1544
'011011010010', '101011101001', '010101101011', '010010101011', '101001010101',
// 1545-1549
'110100101001', '110101010100', '110110101010', '100110110101', '010010111010',
// 1550-1554
'101000111011', '010010011011', '101001001101', '101010101010', '101011010101',
// 1555-1559
'001011011010', '100101011101', '010001011110', '101000101110', '110010011010',
// 1560-1564
'110101010101', '011010110010', '011010111001', '010010111010', '101001011101',
// 1565-1569
'010100101101', '101010010101', '101101010010', '101110101000', '101110110100',
// 1570-1574
'010110111001', '001011011010', '100101011010', '101101001010', '110110100100',
// 1575-1579
'111011010001', '011011101000', '101101101010', '010101101101', '010100110101',
// 1580-1584
'011010010101', '110101001010', '110110101000', '110111010100', '011011011010',
// 1585-1589
'010101011011', '001010011101', '011000101011', '101100010101', '101101001010',
// 1590-1594
'101110010101', '010110101010', '101010101110', '100100101110', '110010001111',
// 1595-1599
'010100100111', '011010010101', '011010101010', '101011010110', '010101011101',
// 1600
'001010011101'
];
function getDaysDiff(date1: Date, date2: Date): number {
const diff = Math.abs(date1.getTime() - date2.getTime());
return Math.round(diff / ONE_DAY);
}
@Injectable()
export class NgbCalendarIslamicUmalqura extends NgbCalendarIslamicCivil {
/**
* Returns the equivalent islamic(Umalqura) date value for a give input Gregorian date.
* `gdate` is s JS Date to be converted to Hijri.
*/
fromGregorian(gDate: Date): NgbDate {
let hDay = 1, hMonth = 0, hYear = 1300;
let daysDiff = getDaysDiff(gDate, GREGORIAN_FIRST_DATE);
if (gDate.getTime() - GREGORIAN_FIRST_DATE.getTime() >= 0 && gDate.getTime() - GREGORIAN_LAST_DATE.getTime() <= 0) {
let year = 1300;
for (let i = 0; i < MONTH_LENGTH.length; i++, year++) {<|fim▁hole|> let numOfDays = +MONTH_LENGTH[i][j] + 29;
if (daysDiff <= numOfDays) {
hDay = daysDiff + 1;
if (hDay > numOfDays) {
hDay = 1;
j++;
}
if (j > 11) {
j = 0;
year++;
}
hMonth = j;
hYear = year;
return new NgbDate(hYear, hMonth + 1, hDay);
}
daysDiff = daysDiff - numOfDays;
}
}
} else {
return super.fromGregorian(gDate);
}
}
/**
* Converts the current Hijri date to Gregorian.
*/
toGregorian(hDate: NgbDate): Date {
const hYear = hDate.year;
const hMonth = hDate.month - 1;
const hDay = hDate.day;
let gDate = new Date(GREGORIAN_FIRST_DATE);
let dayDiff = hDay - 1;
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
for (let y = 0; y < hYear - HIJRI_BEGIN; y++) {
for (let m = 0; m < 12; m++) {
dayDiff += +MONTH_LENGTH[y][m] + 29;
}
}
for (let m = 0; m < hMonth; m++) {
dayDiff += +MONTH_LENGTH[hYear - HIJRI_BEGIN][m] + 29;
}
gDate.setDate(GREGORIAN_FIRST_DATE.getDate() + dayDiff);
} else {
gDate = super.toGregorian(hDate);
}
return gDate;
}
/**
* Returns the number of days in a specific Hijri hMonth.
* `hMonth` is 1 for Muharram, 2 for Safar, etc.
* `hYear` is any Hijri hYear.
*/
getDaysPerMonth(hMonth: number, hYear: number): number {
if (hYear >= HIJRI_BEGIN && hYear <= HIJRI_END) {
const pos = hYear - HIJRI_BEGIN;
return +MONTH_LENGTH[pos][hMonth - 1] + 29;
}
return super.getDaysPerMonth(hMonth, hYear);
}
}<|fim▁end|> | for (let j = 0; j < 12; j++) { |
<|file_name|>compare-generic-enums.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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. This file may not be copied, modified, or distributed
// except according to those terms.
type an_int = int;
fn cmp(x: Option<an_int>, y: Option<int>) -> bool {
x == y
}
pub fn main() {
assert!(!cmp(Some(3), None));
assert!(!cmp(Some(3), Some(4)));
assert!(cmp(Some(3), Some(3)));
assert!(cmp(None, None));<|fim▁hole|>}<|fim▁end|> | |
<|file_name|>test_port.py<|end_file_name|><|fim▁begin|># 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<|fim▁hole|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from neutron_lib.api.definitions import port
from neutron_lib.tests.unit.api.definitions import base
class PortDefinitionTestCase(base.DefinitionBaseTestCase):
extension_module = port
extension_attributes = ()<|fim▁end|> | |
<|file_name|>ExampleInstrumentedTest.java<|end_file_name|><|fim▁begin|>package es.guiguegon.geoapi;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;<|fim▁hole|>
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("es.guiguegon.geoapi", appContext.getPackageName());
}
}<|fim▁end|> | import org.junit.runner.RunWith; |
<|file_name|>attributes.go<|end_file_name|><|fim▁begin|>/*
Copyright 2021 The CloudEvents Authors
SPDX-License-Identifier: Apache-2.0
*/
package spec
import (
"fmt"
"time"
"github.com/cloudevents/sdk-go/v2/event"
"github.com/cloudevents/sdk-go/v2/types"
)
// Kind is a version-independent identifier for a CloudEvent context attribute.
type Kind uint8
const (
// Required cloudevents attributes
ID Kind = iota
Source
SpecVersion
Type
// Optional cloudevents attributes
DataContentType
DataSchema
Subject
Time
)
const nAttrs = int(Time) + 1
var kindNames = [nAttrs]string{
"id",
"source",
"specversion",
"type",
"datacontenttype",
"dataschema",
"subject",
"time",
}
// String is a human-readable string, for a valid attribute name use Attribute.Name
func (k Kind) String() string { return kindNames[k] }
// IsRequired returns true for attributes defined as "required" by the CE spec.
func (k Kind) IsRequired() bool { return k < DataContentType }
// Attribute is a named attribute accessor.
// The attribute name is specific to a Version.
type Attribute interface {
Kind() Kind
// Name of the attribute with respect to the current spec Version() with prefix
PrefixedName() string
// Name of the attribute with respect to the current spec Version()
Name() string
// Version of the spec that this attribute belongs to
Version() Version
// Get the value of this attribute from an event context
Get(event.EventContextReader) interface{}
// Set the value of this attribute on an event context
Set(event.EventContextWriter, interface{}) error
// Delete this attribute from and event context, when possible
Delete(event.EventContextWriter) error
}
// accessor provides Kind, Get, Set.
type accessor interface {
Kind() Kind
Get(event.EventContextReader) interface{}
Set(event.EventContextWriter, interface{}) error
Delete(event.EventContextWriter) error
}
var acc = [nAttrs]accessor{
&aStr{aKind(ID), event.EventContextReader.GetID, event.EventContextWriter.SetID},
&aStr{aKind(Source), event.EventContextReader.GetSource, event.EventContextWriter.SetSource},
&aStr{aKind(SpecVersion), event.EventContextReader.GetSpecVersion, func(writer event.EventContextWriter, s string) error { return nil }},
&aStr{aKind(Type), event.EventContextReader.GetType, event.EventContextWriter.SetType},
&aStr{aKind(DataContentType), event.EventContextReader.GetDataContentType, event.EventContextWriter.SetDataContentType},
&aStr{aKind(DataSchema), event.EventContextReader.GetDataSchema, event.EventContextWriter.SetDataSchema},
&aStr{aKind(Subject), event.EventContextReader.GetSubject, event.EventContextWriter.SetSubject},
&aTime{aKind(Time), event.EventContextReader.GetTime, event.EventContextWriter.SetTime},
}
// aKind implements Kind()
type aKind Kind
func (kind aKind) Kind() Kind { return Kind(kind) }
type aStr struct {
aKind
get func(event.EventContextReader) string
set func(event.EventContextWriter, string) error
}
func (a *aStr) Get(c event.EventContextReader) interface{} {
if s := a.get(c); s != "" {
return s
}
return nil // Treat blank as missing
}
func (a *aStr) Set(c event.EventContextWriter, v interface{}) error {
s, err := types.ToString(v)
if err != nil {
return fmt.Errorf("invalid value for %s: %#v", a.Kind(), v)
}
return a.set(c, s)
}
func (a *aStr) Delete(c event.EventContextWriter) error {
return a.set(c, "")
}
type aTime struct {
aKind
get func(event.EventContextReader) time.Time
set func(event.EventContextWriter, time.Time) error
}<|fim▁hole|>func (a *aTime) Get(c event.EventContextReader) interface{} {
if v := a.get(c); !v.IsZero() {
return v
}
return nil // Treat zero time as missing.
}
func (a *aTime) Set(c event.EventContextWriter, v interface{}) error {
t, err := types.ToTime(v)
if err != nil {
return fmt.Errorf("invalid value for %s: %#v", a.Kind(), v)
}
return a.set(c, t)
}
func (a *aTime) Delete(c event.EventContextWriter) error {
return a.set(c, time.Time{})
}<|fim▁end|> | |
<|file_name|>formio.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit, Optional, ViewEncapsulation, Input, NgZone, OnChanges } from '@angular/core';
import { FormioAppConfig } from '../../formio.config';
import { Formio, Form } from 'formiojs';
import { FormioBaseComponent } from '../../FormioBaseComponent';
import { CustomTagsService } from '../../custom-component/custom-tags.service';
/* tslint:disable */
@Component({
selector: 'formio',
templateUrl: './formio.component.html',
styleUrls: ['../../../../../node_modules/formiojs/dist/formio.form.min.css'],
encapsulation: ViewEncapsulation.None,<|fim▁hole|>})
/* tslint:enable */
export class FormioComponent extends FormioBaseComponent implements OnInit, OnChanges {
constructor(
public ngZone: NgZone,
@Optional() public config: FormioAppConfig,
@Optional() public customTags?: CustomTagsService,
) {
super(ngZone, config, customTags);
if (this.config) {
Formio.setBaseUrl(this.config.apiUrl);
Formio.setProjectUrl(this.config.appUrl);
} else {
console.warn('You must provide an AppConfig within your application!');
}
}
getRenderer() {
return this.renderer || Form;
}
}<|fim▁end|> | |
<|file_name|>test_user_login_and_registration.py<|end_file_name|><|fim▁begin|>from pytest import mark
from django.urls import reverse
from email_template.models import Email
from assopy.models import AssopyUser
from conference.accounts import PRIVACY_POLICY_CHECKBOX, PRIVACY_POLICY_ERROR
from conference.models import CaptchaQuestion
from conference.users import RANDOM_USERNAME_LENGTH
from tests.common_tools import make_user, redirects_to, template_used, create_homepage_in_cms
SIGNUP_SUCCESFUL_302 = 302
SIGNUP_FAILED_200 = 200
login_url = reverse("accounts:login")
def check_login(client, email):
"Small helper for tests to check if login works correctly"
response = client.post(
login_url,
{
"email": email,
"password": "password",
"i_accept_privacy_policy": True,
},
)
# redirect means successful login, 200 means errors on form
LOGIN_SUCCESFUL_302 = 302
assert response.status_code == LOGIN_SUCCESFUL_302
return True
def activate_only_user():
user = AssopyUser.objects.get()
user.user.is_active = True
user.user.save()
@mark.django_db
def test_user_registration(client):
"""
Tests if users can create new account on the website
(to buy tickets, etc).
"""
# required for redirects to /
create_homepage_in_cms()
# 1. test if user can create new account
sign_up_url = reverse("accounts:signup_step_1_create_account")
response = client.get(sign_up_url)
assert response.status_code == 200
assert template_used(response, "conference/accounts/signup.html")
assert template_used(response, "conference/accounts/_login_with_google.html")
assert template_used(response, "conference/base.html")
assert PRIVACY_POLICY_CHECKBOX in response.content.decode("utf-8")
assert AssopyUser.objects.all().count() == 0
response = client.post(
sign_up_url,
{
"first_name": "Joe",
"last_name": "Doe",
"email": "[email protected]",
"password1": "password",
"password2": "password",
},
follow=True,
)
assert response.status_code == SIGNUP_FAILED_200
assert "/privacy/" in PRIVACY_POLICY_CHECKBOX
assert "I consent to the use of my data" in PRIVACY_POLICY_CHECKBOX
assert response.context["form"].errors["__all__"] == [PRIVACY_POLICY_ERROR]
response = client.post(
sign_up_url,
{
"first_name": "Joe",
"last_name": "Doe",
"email": "[email protected]",
"password1": "password",
"password2": "password",
"i_accept_privacy_policy": True,
},
follow=True,
)
# check if redirect was correct
assert template_used(
response, "conference/accounts/signup_please_verify_email.html"
)
assert template_used(response, "conference/base.html")
user = AssopyUser.objects.get()
assert user.name() == "Joe Doe"
assert user.user.is_active is False
# check if the random username was generated
assert len(user.user.username) == RANDOM_USERNAME_LENGTH
is_logged_in = client.login(
email="[email protected]", password="password"
)
assert is_logged_in is False # user is inactive
response = client.get("/")
assert template_used(response, "conference/homepage/home_template.html")
assert "Joe Doe" not in response.content.decode("utf-8")
assert "Log out" not in response.content.decode("utf-8")
# enable the user
user.user.is_active = True
user.user.save()
is_logged_in = client.login(
email="[email protected]", password="password"
)
assert is_logged_in
response = client.get("/")
assert template_used(response, "conference/homepage/home_template.html")
# checking if user is logged in.
assert "Joe Doe" in response.content.decode("utf-8")
@mark.django_db
def test_393_emails_are_lowercased_and_login_is_case_insensitive(client):
"""
https://github.com/EuroPython/epcon/issues/393
Test if we can regiester new account if we use the same email with
different case.
"""
sign_up_url = reverse("accounts:signup_step_1_create_account")
response = client.post(
sign_up_url,
{
"first_name": "Joe",
"last_name": "Doe",
"email": "[email protected]",
"password1": "password",
"password2": "password",
"i_accept_privacy_policy": True,
},
)
assert response.status_code == SIGNUP_SUCCESFUL_302
user = AssopyUser.objects.get()
assert user.name() == "Joe Doe"
assert user.user.email == "[email protected]"
response = client.post(
sign_up_url,
{
"first_name": "Joe",
"last_name": "Doe",
"email": "[email protected]",
"password1": "password",
"password2": "password",
"i_accept_privacy_policy": True,
},
)
assert response.status_code == SIGNUP_FAILED_200
assert response.context["form"].errors["email"] == ["Email already in use"]
user = AssopyUser.objects.get() # still only one user
assert user.name() == "Joe Doe"
assert user.user.email == "[email protected]"
# activate user so we can log in
user.user.is_active = True
user.user.save()
# check if we can login with lowercase
# the emails will be lowercased in db, but user is still able to log in
# using whatever case they want
assert check_login(client, email="[email protected]")
assert check_login(client, email="[email protected]")
assert check_login(client, email="[email protected]")
assert check_login(client, email="[email protected]")
@mark.django_db
def test_703_test_captcha_questions(client):
"""
https://github.com/EuroPython/epcon/issues/703
"""
QUESTION = "Can you foo in Python?"
ANSWER = "Yes you can"
CaptchaQuestion.objects.create(question=QUESTION, answer=ANSWER)
Email.objects.create(code="verify-account")
sign_up_url = reverse("accounts:signup_step_1_create_account")
response = client.get(sign_up_url)
# we have question in captcha_question.initial and captcha_answer.label<|fim▁hole|> response = client.post(
sign_up_url,
{
"first_name": "Joe",
"last_name": "Doe",
"email": "[email protected]",
"password1": "password",
"password2": "password",
"i_accept_privacy_policy": True,
},
)
assert response.status_code == SIGNUP_FAILED_200 # because missing captcha
response = client.post(
sign_up_url,
{
"first_name": "Joe",
"last_name": "Doe",
"email": "[email protected]",
"password1": "password",
"password2": "password",
"captcha_question": QUESTION,
"captcha_answer": "No you can't",
"i_accept_privacy_policy": True,
},
)
assert response.status_code == SIGNUP_FAILED_200 # because wrong answer
wrong_answer = ["Sorry, that's a wrong answer"]
assert response.context["form"].errors["captcha_answer"] == wrong_answer
response = client.post(
sign_up_url,
{
"first_name": "Joe",
"last_name": "Doe",
"email": "[email protected]",
"password1": "password",
"password2": "password",
"captcha_question": QUESTION,
"captcha_answer": ANSWER,
"i_accept_privacy_policy": True,
},
)
assert response.status_code == SIGNUP_SUCCESFUL_302
activate_only_user()
assert check_login(client, email="[email protected]")
# if there are no enabled questions they don't appear on the form
CaptchaQuestion.objects.update(enabled=False)
response = client.get(sign_up_url)
assert "captcha_question" not in response.content.decode("utf-8")
assert "captcha_answer" not in response.content.decode("utf-8")
assert response.content.decode("utf-8").count(QUESTION) == 0
@mark.django_db
def test_872_login_redirects_to_user_dashboard(client):
u = make_user(email='[email protected]', password='foobar')
response = client.post(
login_url,
{
"email": u.email,
"password": 'foobar',
"i_accept_privacy_policy": True,
},
)
assert response.status_code == 302
assert redirects_to(response, "/user-panel/")<|fim▁end|> | assert "captcha_question" in response.content.decode("utf-8")
assert "captcha_answer" in response.content.decode("utf-8")
assert response.content.decode("utf-8").count(QUESTION) == 2
|
<|file_name|>frmHome.js<|end_file_name|><|fim▁begin|>//Form JS File
function frmHome_stopWatch_onClick_seq0() {
alert("You clicked on stop watch");
};
function frmHome_button214149106640_onClick_seq0(eventobject) {
var a = frmHome.stopWatch.stopWatch();
alert(a);
};
function frmHome_button214149106641_onClick_seq0(eventobject) {
frmHome.stopWatch.startWatch();
};
function addWidgetsfrmHome() {
var stopWatch = new CustomStopWatch.StopWatch({
"id": "stopWatch",
"image": null,
"isVisible": true,
"hExpand": true,
"vExpand": false,
"textSize": 35,
"bgTransparancy": 0,
"onClick": frmHome_stopWatch_onClick_seq0
}, {
"widgetAlign": 5,
"containerWeight": 6,
"margin": [5, 5, 5, 5],
"marginInPixel": false,
"padding": [15, 15, 15, 15],
"paddingInPixel": false
}, {
"widgetName": "StopWatch"
});
var button214149106640 = new kony.ui.Button({
"id": "button214149106640",
"isVisible": true,
"text": "Stop Watch",
"skin": "sknBtnKonyThemeNormal",
"focusSkin": "sknBtnKonyThemeFocus",
"onClick": frmHome_button214149106640_onClick_seq0
}, {
"widgetAlignment": constants.WIDGET_ALIGN_CENTER,
"vExpand": false,
"hExpand": true,
"margin": [3, 2, 3, 2],
"padding": [2, 3, 2, 3],
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"marginInPixel": false,
"paddingInPixel": false,
"containerWeight": 6
}, {
"glowEffect": false,
"showProgressIndicator": true
});
var button214149106641 = new kony.ui.Button({
"id": "button214149106641",
"isVisible": true,
"text": "Start Watch",
"skin": "sknBtnKonyThemeNormal",
"focusSkin": "sknBtnKonyThemeFocus",
"onClick": frmHome_button214149106641_onClick_seq0
}, {
"widgetAlignment": constants.WIDGET_ALIGN_CENTER,
"vExpand": false,
"hExpand": true,
"margin": [3, 2, 3, 2],
"padding": [2, 3, 2, 3],
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"marginInPixel": false,
"paddingInPixel": false,
"containerWeight": 6
}, {
"glowEffect": false,
"showProgressIndicator": true
});
frmHome.add(
stopWatch, button214149106640, button214149106641);
};
function frmHomeGlobals() {
var MenuId = [];
frmHome = new kony.ui.Form2({
"id": "frmHome",
"needAppMenu": true,
"title": "StopWatch",
"enabledForIdleTimeout": false,
"skin": "frm",
"addWidgets": addWidgetsfrmHome
}, {
"padding": [0, 0, 0, 0],
"displayOrientation": constants.FORM_DISPLAY_ORIENTATION_PORTRAIT,
"paddingInPixel": false,
"layoutType": constants.CONTAINER_LAYOUT_BOX
}, {
"retainScrollPosition": false,
"needsIndicatorDuringPostShow": true,
"formTransparencyDuringPostShow": "100",
"inputAccessoryViewType": constants.FORM_INPUTACCESSORYVIEW_DEFAULT,
"bounces": true,
"configureExtendTop": false,
"configureExtendBottom": false,
"configureStatusBarStyle": false,
"titleBar": true,
"titleBarSkin": "titleBar",
"titleBarConfig": {
"renderTitleText": true,
"titleBarRightSideView": "title",
"titleBarLeftSideView": "none",
"closureRightSideView": navigateToSettings,<|fim▁hole|> "footerOverlap": false,
"headerOverlap": false,
"inTransitionConfig": {
"transitionDirection": "none",
"transitionEffect": "none"
},
"outTransitionConfig": {
"transitionDirection": "none",
"transitionEffect": "none"
},
"deprecated": {
"titleBarBackGroundImage": "blue_pixel.png"
}
});
};<|fim▁end|> | "labelRightSideView": "Settings"
}, |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc))]
#[cfg(feature = "serde1")]
extern crate serde;
#[cfg(feature = "serde1")]
#[macro_use]
extern crate serde_derive;
#[cfg(not(feature = "std"))]
#[macro_use]
pub extern crate alloc;
#[cfg(not(feature = "std"))]
mod std {
pub use core::{ops, hash, fmt, cmp, mem, slice, iter, borrow};
pub use alloc::*;
}
pub mod flat_map;
pub use flat_map::Entry::*;<|fim▁hole|><|fim▁end|> | pub use flat_map::FlatMap; |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import './skottie-library-sk';<|fim▁hole|><|fim▁end|> | import './skottie-library-sk.scss'; |
<|file_name|>AC_dfs_n.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_dfs_n.py
# Create Date: 2015-08-16 10:15:54
# Usage: AC_dfs_n.py
# Descripton:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root
# @return {string[]}
def binaryTreePaths(self, root):
path =[]
paths = []
def dfs(root):
if root:
path.append(str(root.val))
if root.left == None and root.right == None:
paths.append('->'.join(path))
dfs(root.left)<|fim▁hole|> dfs(root.right)
path.pop()
dfs(root)
return paths<|fim▁end|> | |
<|file_name|>deprecatedProperty.py<|end_file_name|><|fim▁begin|>class Foo:<|fim▁hole|> def bar(self):
import warnings
warnings.warn("this is deprecated", DeprecationWarning, 2)
foo = Foo()
foo.<warning descr="this is deprecated">bar</warning><|fim▁end|> | @property |
<|file_name|>ADeclarationEdge.java<|end_file_name|><|fim▁begin|>/*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cfa.model;
import org.sosy_lab.cpachecker.cfa.ast.FileLocation;
import org.sosy_lab.cpachecker.cfa.ast.ADeclaration;
import com.google.common.base.Optional;
public class ADeclarationEdge extends AbstractCFAEdge {
protected final ADeclaration declaration;
protected ADeclarationEdge(final String pRawSignature, final FileLocation pFileLocation,
final CFANode pPredecessor, final CFANode pSuccessor, final ADeclaration pDeclaration) {
super(pRawSignature, pFileLocation, pPredecessor, pSuccessor);
declaration = pDeclaration;
}
@Override
public CFAEdgeType getEdgeType() {
return CFAEdgeType.DeclarationEdge;
}
public ADeclaration getDeclaration() {
return declaration;
}
<|fim▁hole|> return Optional.of(declaration);
}
@Override
public String getCode() {
return declaration.toASTString();
}
}<|fim▁end|> | @Override
public Optional<? extends ADeclaration> getRawAST() { |
<|file_name|>app.rs<|end_file_name|><|fim▁begin|>use delorean::*;
use js_sys::Date;
use rand::{rngs::SmallRng, SeedableRng};
use serde_json::from_str;
use wasm_bindgen::{prelude::*, JsCast, UnwrapThrowExt};
use web_sys::{Element, Event};
use crate::{<|fim▁hole|> hydrate_row, new_row,
row::{row_element, Row, RowDOM},
update_row,
};
#[wasm_bindgen]
extern "C" {
fn get_state() -> String;
}
pub struct NonKeyed {
pub id: usize,
pub data: Vec<Row>,
pub selected: Option<usize>,
pub rng: SmallRng,
// Black box
pub t_root: u8,
pub old_selected: Option<usize>,
pub tbody: Element,
pub tbody_children: Vec<RowDOM>,
//
tr: Element,
}
#[inline]
fn each_render(app: &mut NonKeyed, mb: DeLorean<NonKeyed>) {
if app.t_root & 0b0000_0001 == 0 {
return;
}
let dom_len = app.tbody_children.len();
let row_len = app.data.len();
if row_len == 0 {
// Clear
app.tbody.set_text_content(None);
app.tbody_children.clear()
} else {
// Update
for (dom, row) in app
.tbody_children
.iter_mut()
.zip(app.data.iter())
.filter(|(dom, _)| dom.t_root != 0)
{
update_row!(dom, row, mb);
}
if dom_len < row_len {
// Add
for row in app.data.iter().skip(dom_len) {
app.tbody_children
.push(new_row!(row, app.tr, mb, app.tbody));
}
} else {
// Remove
for dom in app.tbody_children.drain(row_len..) {
dom.root.remove()
}
}
}
}
#[inline]
fn select_render(app: &mut NonKeyed) {
if app.t_root & 0b0000_0011 == 0 {
return;
}
if let Some(old) = app
.old_selected
.take()
.and_then(|x| app.tbody_children.get(x))
{
old.root.set_class_name("");
}
if let Some(new) = app.selected {
if let Some((dom, i)) = app
.data
.iter()
.position(|x| x.id == new)
.and_then(|x| app.tbody_children.get(x).map(|dom| (dom, x)))
{
dom.root.set_class_name("danger");
app.old_selected = Some(i);
} else {
app.selected = None;
}
}
}
impl App for NonKeyed {
type BlackBox = ();
type Message = Msg;
fn __render(&mut self, mb: DeLorean<Self>) {
if self.t_root == 0 {
return;
}
each_render(self, mb);
select_render(self);
self.t_root = 0;
}
fn __hydrate(&mut self, mb: DeLorean<Self>) {
let document = web_sys::window().unwrap_throw().document().unwrap_throw();
let f = document
.body()
.unwrap_throw()
.first_child()
.unwrap_throw()
.first_child()
.unwrap_throw(); // div.jumbotron
let f_0 = f.first_child().unwrap_throw(); // div.row
let f_0_0 = f_0.first_child().unwrap_throw(); // div.col-md-6
let f_0_1 = f_0_0.next_sibling().unwrap_throw(); // div.col-md-6
let f_0_1_0 = f_0_1.first_child().unwrap_throw(); // div.row
let f_0_1_0_0 = f_0_1_0.first_child().unwrap_throw(); // div.col-sm-6 smallpad
let button_create = f_0_1_0_0.first_child().unwrap_throw(); // button CREATE 1_000
let cloned = mb.clone();
let cl = Closure::wrap(Box::new(move |event: Event| {
event.prevent_default();
cloned.send(Msg::Create);
}) as Box<dyn Fn(Event)>);
button_create
.add_event_listener_with_callback("click", cl.as_ref().unchecked_ref())
.unwrap_throw();
cl.forget();
let f_0_1_0_1 = f_0_1_0_0.next_sibling().unwrap_throw(); // div.col-sm-6 smallpad
let button_create_10 = f_0_1_0_1.first_child().unwrap_throw(); // button CREATE 10_000
let cloned = mb.clone();
let cl = Closure::wrap(Box::new(move |event: Event| {
event.prevent_default();
cloned.send(Msg::Create10);
}) as Box<dyn Fn(Event)>);
button_create_10
.add_event_listener_with_callback("click", cl.as_ref().unchecked_ref())
.unwrap_throw();
cl.forget();
let f_0_1_0_2 = f_0_1_0_1.next_sibling().unwrap_throw(); // div.col-sm-6 smallpad
let button_append = f_0_1_0_2.first_child().unwrap_throw(); // button APPEND 1_000
let cloned = mb.clone();
let cl = Closure::wrap(Box::new(move |event: Event| {
event.prevent_default();
cloned.send(Msg::Append)
}) as Box<dyn Fn(Event)>);
button_append
.add_event_listener_with_callback("click", cl.as_ref().unchecked_ref())
.unwrap_throw();
cl.forget();
let f_0_1_0_3 = f_0_1_0_2.next_sibling().unwrap_throw(); // div.col-sm-6 smallpad
let button_update = f_0_1_0_3.first_child().unwrap_throw(); // button UPDATE
let cloned = mb.clone();
let cl = Closure::wrap(Box::new(move |event: Event| {
event.prevent_default();
cloned.send(Msg::Update);
}) as Box<dyn Fn(Event)>);
button_update
.add_event_listener_with_callback("click", cl.as_ref().unchecked_ref())
.unwrap_throw();
cl.forget();
let f_0_1_0_4 = f_0_1_0_3.next_sibling().unwrap_throw(); // div.col-sm-6 smallpad
let button_clear = f_0_1_0_4.first_child().unwrap_throw(); // button CLEAR
let cloned = mb.clone();
let cl = Closure::wrap(Box::new(move |event: Event| {
event.prevent_default();
cloned.send(Msg::Clear);
}) as Box<dyn Fn(Event)>);
button_clear
.add_event_listener_with_callback("click", cl.as_ref().unchecked_ref())
.unwrap_throw();
cl.forget();
let f_0_1_0_5 = f_0_1_0_4.next_sibling().unwrap_throw(); // div.col-sm-6 smallpad
let button_swap = f_0_1_0_5.first_child().unwrap_throw(); // button SWAP
let cloned = mb.clone();
let cl = Closure::wrap(Box::new(move |event: Event| {
event.prevent_default();
cloned.send(Msg::Swap)
}) as Box<dyn Fn(Event)>);
button_swap
.add_event_listener_with_callback("click", cl.as_ref().unchecked_ref())
.unwrap_throw();
cl.forget();
assert_eq!(self.tbody_children.len(), self.data.len());
// hydrate Each
for (dom, row) in self.tbody_children.iter_mut().zip(self.data.iter()) {
hydrate_row!(dom, row, mb);
}
}
fn __dispatch(&mut self, msg: <Self as App>::Message, addr: DeLorean<Self>) {
match msg {
Msg::Append => append(self, addr),
Msg::Clear => clear(self, addr),
Msg::Create => create(self, addr),
Msg::Create10 => create_10(self, addr),
Msg::Delete(i) => delete(self, i, addr),
Msg::Select(i) => select(self, i, addr),
Msg::Swap => swap(self, addr),
Msg::Update => update(self, addr),
}
}
}
#[derive(Debug, Default, Deserialize)]
struct InitialState {
#[serde(default)]
data: Vec<Row>,
#[serde(default)]
id: usize,
#[serde(default)]
selected: Option<usize>,
}
// Construct pre hydrate App
impl Default for NonKeyed {
fn default() -> Self {
let state = get_state();
let InitialState { data, id, selected }: InitialState =
from_str(&state).unwrap_or_default();
let doc = web_sys::window().unwrap_throw().document().unwrap_throw();
let body = doc.body().unwrap_throw();
let node = body.first_element_child().unwrap_throw();
let f = node.first_element_child().unwrap_throw(); // div.jumbotron
let n1 = f.next_element_sibling().unwrap_throw(); // table.table table-hover table-striped test-data
let tbody = n1.first_element_child().unwrap_throw(); // tbody
let mut tbody_children = vec![];
if let Some(mut curr) = tbody.first_element_child() {
loop {
let id_node = curr.first_element_child().unwrap_throw();
let label_parent = id_node.next_element_sibling().unwrap_throw();
let label_node = label_parent.first_element_child().unwrap_throw();
let delete_parent = label_parent.next_element_sibling().unwrap_throw();
let delete_node = delete_parent.first_element_child().unwrap_throw();
curr = if let Some(new) = curr.next_element_sibling() {
tbody_children.push(RowDOM {
t_root: 0,
root: curr,
id_node,
label_node,
delete_node,
closure_select: None,
closure_delete: None,
});
new
} else {
tbody_children.push(RowDOM {
t_root: 0,
root: curr,
id_node,
label_node,
delete_node,
closure_select: None,
closure_delete: None,
});
break;
}
}
}
Self {
// state template variables
id,
data,
selected,
// state variable
rng: SmallRng::seed_from_u64(Date::now() as u64),
// Black box
t_root: 0,
old_selected: None,
tbody,
tbody_children,
tr: row_element(),
}
}
}<|fim▁end|> | handler::*, |
<|file_name|>ItaniumCXXABI.cpp<|end_file_name|><|fim▁begin|>//===------- ItaniumCXXABI.cpp - Emit LLVM Code from ASTs for a Module ----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This provides C++ code generation targeting the Itanium C++ ABI. The class
// in this file generates structures that follow the Itanium C++ ABI, which is
// documented at:
// https://itanium-cxx-abi.github.io/cxx-abi/abi.html
// https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html
//
// It also supports the closely-related ARM ABI, documented at:
// https://developer.arm.com/documentation/ihi0041/g/
//
//===----------------------------------------------------------------------===//
#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGRecordLayout.h"
#include "CGVTables.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "TargetInfo.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/Type.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/ScopedPrinter.h"
using namespace clang;
using namespace CodeGen;
namespace {
class ItaniumCXXABI : public CodeGen::CGCXXABI {
/// VTables - All the vtables which have been defined.
llvm::DenseMap<const CXXRecordDecl *, llvm::GlobalVariable *> VTables;
/// All the thread wrapper functions that have been used.
llvm::SmallVector<std::pair<const VarDecl *, llvm::Function *>, 8>
ThreadWrappers;
protected:
bool UseARMMethodPtrABI;
bool UseARMGuardVarABI;
bool Use32BitVTableOffsetABI;
ItaniumMangleContext &getMangleContext() {
return cast<ItaniumMangleContext>(CodeGen::CGCXXABI::getMangleContext());
}
public:
ItaniumCXXABI(CodeGen::CodeGenModule &CGM,
bool UseARMMethodPtrABI = false,
bool UseARMGuardVarABI = false) :
CGCXXABI(CGM), UseARMMethodPtrABI(UseARMMethodPtrABI),
UseARMGuardVarABI(UseARMGuardVarABI),
Use32BitVTableOffsetABI(false) { }
bool classifyReturnType(CGFunctionInfo &FI) const override;
RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override {
// If C++ prohibits us from making a copy, pass by address.
if (!RD->canPassInRegisters())
return RAA_Indirect;
return RAA_Default;
}
bool isThisCompleteObject(GlobalDecl GD) const override {
// The Itanium ABI has separate complete-object vs. base-object
// variants of both constructors and destructors.
if (isa<CXXDestructorDecl>(GD.getDecl())) {
switch (GD.getDtorType()) {
case Dtor_Complete:
case Dtor_Deleting:
return true;
case Dtor_Base:
return false;
case Dtor_Comdat:
llvm_unreachable("emitting dtor comdat as function?");
}
llvm_unreachable("bad dtor kind");
}
if (isa<CXXConstructorDecl>(GD.getDecl())) {
switch (GD.getCtorType()) {
case Ctor_Complete:
return true;
case Ctor_Base:
return false;
case Ctor_CopyingClosure:
case Ctor_DefaultClosure:
llvm_unreachable("closure ctors in Itanium ABI?");
case Ctor_Comdat:
llvm_unreachable("emitting ctor comdat as function?");
}
llvm_unreachable("bad dtor kind");
}
// No other kinds.
return false;
}
bool isZeroInitializable(const MemberPointerType *MPT) override;
llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
CGCallee
EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
const Expr *E,
Address This,
llvm::Value *&ThisPtrForCall,
llvm::Value *MemFnPtr,
const MemberPointerType *MPT) override;
llvm::Value *
EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
Address Base,
llvm::Value *MemPtr,
const MemberPointerType *MPT) override;
llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
const CastExpr *E,
llvm::Value *Src) override;
llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
llvm::Constant *Src) override;
llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
CharUnits offset) override;
llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
CharUnits ThisAdjustment);
llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
llvm::Value *L, llvm::Value *R,
const MemberPointerType *MPT,
bool Inequality) override;
llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
llvm::Value *Addr,
const MemberPointerType *MPT) override;
void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
Address Ptr, QualType ElementType,
const CXXDestructorDecl *Dtor) override;
void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
llvm::CallInst *
emitTerminateForUnexpectedException(CodeGenFunction &CGF,
llvm::Value *Exn) override;
void EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD);
llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
CatchTypeInfo
getAddrOfCXXCatchHandlerType(QualType Ty,
QualType CatchHandlerType) override {
return CatchTypeInfo{getAddrOfRTTIDescriptor(Ty), 0};
}
bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
void EmitBadTypeidCall(CodeGenFunction &CGF) override;
llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
Address ThisPtr,
llvm::Type *StdTypeInfoPtrTy) override;
bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
QualType SrcRecordTy) override;
llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
QualType SrcRecordTy, QualType DestTy,
QualType DestRecordTy,
llvm::BasicBlock *CastEnd) override;
llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
QualType SrcRecordTy,
QualType DestTy) override;
bool EmitBadCastCall(CodeGenFunction &CGF) override;
llvm::Value *
GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) override;
void EmitCXXConstructors(const CXXConstructorDecl *D) override;
AddedStructorArgCounts
buildStructorSignature(GlobalDecl GD,
SmallVectorImpl<CanQualType> &ArgTys) override;
bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
CXXDtorType DT) const override {
// Itanium does not emit any destructor variant as an inline thunk.
// Delegating may occur as an optimization, but all variants are either
// emitted with external linkage or as linkonce if they are inline and used.
return false;
}
void EmitCXXDestructors(const CXXDestructorDecl *D) override;
void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
FunctionArgList &Params) override;
void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
const CXXConstructorDecl *D,
CXXCtorType Type,
bool ForVirtualBase,
bool Delegating) override;
llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
const CXXDestructorDecl *DD,
CXXDtorType Type,
bool ForVirtualBase,
bool Delegating) override;
void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
CXXDtorType Type, bool ForVirtualBase,
bool Delegating, Address This,
QualType ThisTy) override;
void emitVTableDefinitions(CodeGenVTables &CGVT,
const CXXRecordDecl *RD) override;
bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
CodeGenFunction::VPtr Vptr) override;
bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
return true;
}
llvm::Constant *
getVTableAddressPoint(BaseSubobject Base,
const CXXRecordDecl *VTableClass) override;
llvm::Value *getVTableAddressPointInStructor(
CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
llvm::Value *getVTableAddressPointInStructorWithVTT(
CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
BaseSubobject Base, const CXXRecordDecl *NearestVBase);
llvm::Constant *
getVTableAddressPointForConstExpr(BaseSubobject Base,
const CXXRecordDecl *VTableClass) override;
llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
CharUnits VPtrOffset) override;
CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Address This, llvm::Type *Ty,
SourceLocation Loc) override;
llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *Dtor,
CXXDtorType DtorType, Address This,
DeleteOrMemberCallExpr E) override;
void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override;
bool canSpeculativelyEmitVTableAsBaseClass(const CXXRecordDecl *RD) const;
void setThunkLinkage(llvm::Function *Thunk, bool ForVTable, GlobalDecl GD,
bool ReturnAdjustment) override {
// Allow inlining of thunks by emitting them with available_externally
// linkage together with vtables when needed.
if (ForVTable && !Thunk->hasLocalLinkage())
Thunk->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
CGM.setGVProperties(Thunk, GD);
}
bool exportThunk() override { return true; }
llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
const ThisAdjustment &TA) override;
llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
const ReturnAdjustment &RA) override;
size_t getSrcArgforCopyCtor(const CXXConstructorDecl *,
FunctionArgList &Args) const override {
assert(!Args.empty() && "expected the arglist to not be empty!");
return Args.size() - 1;
}
StringRef GetPureVirtualCallName() override { return "__cxa_pure_virtual"; }
StringRef GetDeletedVirtualCallName() override
{ return "__cxa_deleted_virtual"; }
CharUnits getArrayCookieSizeImpl(QualType elementType) override;
Address InitializeArrayCookie(CodeGenFunction &CGF,
Address NewPtr,
llvm::Value *NumElements,
const CXXNewExpr *expr,
QualType ElementType) override;
llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
Address allocPtr,
CharUnits cookieSize) override;
void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
llvm::GlobalVariable *DeclPtr,
bool PerformInit) override;
void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
llvm::FunctionCallee dtor,
llvm::Constant *addr) override;
llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
llvm::Value *Val);
void EmitThreadLocalInitFuncs(
CodeGenModule &CGM,
ArrayRef<const VarDecl *> CXXThreadLocals,
ArrayRef<llvm::Function *> CXXThreadLocalInits,
ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
/// Determine whether we will definitely emit this variable with a constant
/// initializer, either because the language semantics demand it or because
/// we know that the initializer is a constant.
bool isEmittedWithConstantInitializer(const VarDecl *VD) const {
VD = VD->getMostRecentDecl();
if (VD->hasAttr<ConstInitAttr>())
return true;
// All later checks examine the initializer specified on the variable. If
// the variable is weak, such examination would not be correct.
if (VD->isWeak() || VD->hasAttr<SelectAnyAttr>())
return false;
const VarDecl *InitDecl = VD->getInitializingDeclaration();
if (!InitDecl)
return false;
// If there's no initializer to run, this is constant initialization.
if (!InitDecl->hasInit())
return true;
// If we have the only definition, we don't need a thread wrapper if we
// will emit the value as a constant.
if (isUniqueGVALinkage(getContext().GetGVALinkageForVariable(VD)))
return !VD->needsDestruction(getContext()) && InitDecl->evaluateValue();
// Otherwise, we need a thread wrapper unless we know that every
// translation unit will emit the value as a constant. We rely on
// ICE-ness not varying between translation units, which isn't actually
// guaranteed by the standard but is necessary for sanity.
return InitDecl->isInitKnownICE() && InitDecl->isInitICE();
}
bool usesThreadWrapperFunction(const VarDecl *VD) const override {
return !isEmittedWithConstantInitializer(VD) ||
VD->needsDestruction(getContext());
}
LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
QualType LValType) override;
bool NeedsVTTParameter(GlobalDecl GD) override;
/**************************** RTTI Uniqueness ******************************/
protected:
/// Returns true if the ABI requires RTTI type_info objects to be unique
/// across a program.
virtual bool shouldRTTIBeUnique() const { return true; }
public:
/// What sort of unique-RTTI behavior should we use?
enum RTTIUniquenessKind {
/// We are guaranteeing, or need to guarantee, that the RTTI string
/// is unique.
RUK_Unique,
/// We are not guaranteeing uniqueness for the RTTI string, so we
/// can demote to hidden visibility but must use string comparisons.
RUK_NonUniqueHidden,
/// We are not guaranteeing uniqueness for the RTTI string, so we
/// have to use string comparisons, but we also have to emit it with
/// non-hidden visibility.
RUK_NonUniqueVisible
};
/// Return the required visibility status for the given type and linkage in
/// the current ABI.
RTTIUniquenessKind
classifyRTTIUniqueness(QualType CanTy,
llvm::GlobalValue::LinkageTypes Linkage) const;
friend class ItaniumRTTIBuilder;
void emitCXXStructor(GlobalDecl GD) override;
std::pair<llvm::Value *, const CXXRecordDecl *>
LoadVTablePtr(CodeGenFunction &CGF, Address This,
const CXXRecordDecl *RD) override;
private:
bool hasAnyUnusedVirtualInlineFunction(const CXXRecordDecl *RD) const {
const auto &VtableLayout =
CGM.getItaniumVTableContext().getVTableLayout(RD);
for (const auto &VtableComponent : VtableLayout.vtable_components()) {
// Skip empty slot.
if (!VtableComponent.isUsedFunctionPointerKind())
continue;
const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
if (!Method->getCanonicalDecl()->isInlined())
continue;
StringRef Name = CGM.getMangledName(VtableComponent.getGlobalDecl());
auto *Entry = CGM.GetGlobalValue(Name);
// This checks if virtual inline function has already been emitted.
// Note that it is possible that this inline function would be emitted
// after trying to emit vtable speculatively. Because of this we do
// an extra pass after emitting all deferred vtables to find and emit
// these vtables opportunistically.
if (!Entry || Entry->isDeclaration())
return true;
}
return false;
}
bool isVTableHidden(const CXXRecordDecl *RD) const {
const auto &VtableLayout =
CGM.getItaniumVTableContext().getVTableLayout(RD);
for (const auto &VtableComponent : VtableLayout.vtable_components()) {
if (VtableComponent.isRTTIKind()) {
const CXXRecordDecl *RTTIDecl = VtableComponent.getRTTIDecl();
if (RTTIDecl->getVisibility() == Visibility::HiddenVisibility)
return true;
} else if (VtableComponent.isUsedFunctionPointerKind()) {
const CXXMethodDecl *Method = VtableComponent.getFunctionDecl();
if (Method->getVisibility() == Visibility::HiddenVisibility &&
!Method->isDefined())
return true;
}
}
return false;
}
};
class ARMCXXABI : public ItaniumCXXABI {
public:
ARMCXXABI(CodeGen::CodeGenModule &CGM) :
ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
/*UseARMGuardVarABI=*/true) {}
bool HasThisReturn(GlobalDecl GD) const override {
return (isa<CXXConstructorDecl>(GD.getDecl()) || (
isa<CXXDestructorDecl>(GD.getDecl()) &&
GD.getDtorType() != Dtor_Deleting));
}
void EmitReturnFromThunk(CodeGenFunction &CGF, RValue RV,
QualType ResTy) override;
CharUnits getArrayCookieSizeImpl(QualType elementType) override;
Address InitializeArrayCookie(CodeGenFunction &CGF,
Address NewPtr,
llvm::Value *NumElements,
const CXXNewExpr *expr,
QualType ElementType) override;
llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF, Address allocPtr,
CharUnits cookieSize) override;
};
class iOS64CXXABI : public ARMCXXABI {
public:
iOS64CXXABI(CodeGen::CodeGenModule &CGM) : ARMCXXABI(CGM) {
Use32BitVTableOffsetABI = true;
}
// ARM64 libraries are prepared for non-unique RTTI.
bool shouldRTTIBeUnique() const override { return false; }
};
class FuchsiaCXXABI final : public ItaniumCXXABI {
public:
explicit FuchsiaCXXABI(CodeGen::CodeGenModule &CGM)
: ItaniumCXXABI(CGM) {}
private:
bool HasThisReturn(GlobalDecl GD) const override {
return isa<CXXConstructorDecl>(GD.getDecl()) ||
(isa<CXXDestructorDecl>(GD.getDecl()) &&
GD.getDtorType() != Dtor_Deleting);
}
};
class WebAssemblyCXXABI final : public ItaniumCXXABI {
public:
explicit WebAssemblyCXXABI(CodeGen::CodeGenModule &CGM)
: ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
/*UseARMGuardVarABI=*/true) {}
void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
private:
bool HasThisReturn(GlobalDecl GD) const override {
return isa<CXXConstructorDecl>(GD.getDecl()) ||
(isa<CXXDestructorDecl>(GD.getDecl()) &&
GD.getDtorType() != Dtor_Deleting);
}
bool canCallMismatchedFunctionType() const override { return false; }
};
class XLCXXABI final : public ItaniumCXXABI {
public:
explicit XLCXXABI(CodeGen::CodeGenModule &CGM)
: ItaniumCXXABI(CGM) {}
void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
llvm::FunctionCallee dtor,
llvm::Constant *addr) override;
bool useSinitAndSterm() const override { return true; }
private:
void emitCXXStermFinalizer(const VarDecl &D, llvm::Function *dtorStub,
llvm::Constant *addr);
};
}
CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
switch (CGM.getTarget().getCXXABI().getKind()) {
// For IR-generation purposes, there's no significant difference
// between the ARM and iOS ABIs.
case TargetCXXABI::GenericARM:
case TargetCXXABI::iOS:
case TargetCXXABI::WatchOS:
return new ARMCXXABI(CGM);
case TargetCXXABI::iOS64:
return new iOS64CXXABI(CGM);
case TargetCXXABI::Fuchsia:
return new FuchsiaCXXABI(CGM);
// Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
// include the other 32-bit ARM oddities: constructor/destructor return values
// and array cookies.
case TargetCXXABI::GenericAArch64:
return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true,
/*UseARMGuardVarABI=*/true);
case TargetCXXABI::GenericMIPS:
return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
case TargetCXXABI::WebAssembly:
return new WebAssemblyCXXABI(CGM);
case TargetCXXABI::XL:
return new XLCXXABI(CGM);
case TargetCXXABI::GenericItanium:
if (CGM.getContext().getTargetInfo().getTriple().getArch()
== llvm::Triple::le32) {
// For PNaCl, use ARM-style method pointers so that PNaCl code
// does not assume anything about the alignment of function
// pointers.
return new ItaniumCXXABI(CGM, /*UseARMMethodPtrABI=*/true);
}
return new ItaniumCXXABI(CGM);
case TargetCXXABI::Microsoft:
llvm_unreachable("Microsoft ABI is not Itanium-based");
}
llvm_unreachable("bad ABI kind");
}
llvm::Type *
ItaniumCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
if (MPT->isMemberDataPointer())
return CGM.PtrDiffTy;
return llvm::StructType::get(CGM.PtrDiffTy, CGM.PtrDiffTy);
}
/// In the Itanium and ARM ABIs, method pointers have the form:
/// struct { ptrdiff_t ptr; ptrdiff_t adj; } memptr;
///
/// In the Itanium ABI:
/// - method pointers are virtual if (memptr.ptr & 1) is nonzero
/// - the this-adjustment is (memptr.adj)
/// - the virtual offset is (memptr.ptr - 1)
///
/// In the ARM ABI:
/// - method pointers are virtual if (memptr.adj & 1) is nonzero
/// - the this-adjustment is (memptr.adj >> 1)
/// - the virtual offset is (memptr.ptr)
/// ARM uses 'adj' for the virtual flag because Thumb functions
/// may be only single-byte aligned.
///
/// If the member is virtual, the adjusted 'this' pointer points
/// to a vtable pointer from which the virtual offset is applied.
///
/// If the member is non-virtual, memptr.ptr is the address of
/// the function to call.
CGCallee ItaniumCXXABI::EmitLoadOfMemberFunctionPointer(
CodeGenFunction &CGF, const Expr *E, Address ThisAddr,
llvm::Value *&ThisPtrForCall,
llvm::Value *MemFnPtr, const MemberPointerType *MPT) {
CGBuilderTy &Builder = CGF.Builder;
const FunctionProtoType *FPT =
MPT->getPointeeType()->getAs<FunctionProtoType>();
auto *RD =
cast<CXXRecordDecl>(MPT->getClass()->castAs<RecordType>()->getDecl());
llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
CGM.getTypes().arrangeCXXMethodType(RD, FPT, /*FD=*/nullptr));
llvm::Constant *ptrdiff_1 = llvm::ConstantInt::get(CGM.PtrDiffTy, 1);
llvm::BasicBlock *FnVirtual = CGF.createBasicBlock("memptr.virtual");
llvm::BasicBlock *FnNonVirtual = CGF.createBasicBlock("memptr.nonvirtual");
llvm::BasicBlock *FnEnd = CGF.createBasicBlock("memptr.end");
// Extract memptr.adj, which is in the second field.
llvm::Value *RawAdj = Builder.CreateExtractValue(MemFnPtr, 1, "memptr.adj");
// Compute the true adjustment.
llvm::Value *Adj = RawAdj;
if (UseARMMethodPtrABI)
Adj = Builder.CreateAShr(Adj, ptrdiff_1, "memptr.adj.shifted");
// Apply the adjustment and cast back to the original struct type
// for consistency.
llvm::Value *This = ThisAddr.getPointer();
llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
Ptr = Builder.CreateInBoundsGEP(Ptr, Adj);
This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
ThisPtrForCall = This;
// Load the function pointer.
llvm::Value *FnAsInt = Builder.CreateExtractValue(MemFnPtr, 0, "memptr.ptr");
// If the LSB in the function pointer is 1, the function pointer points to
// a virtual function.
llvm::Value *IsVirtual;
if (UseARMMethodPtrABI)
IsVirtual = Builder.CreateAnd(RawAdj, ptrdiff_1);
else
IsVirtual = Builder.CreateAnd(FnAsInt, ptrdiff_1);
IsVirtual = Builder.CreateIsNotNull(IsVirtual, "memptr.isvirtual");
Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual);
// In the virtual path, the adjustment left 'This' pointing to the
// vtable of the correct base subobject. The "function pointer" is an
// offset within the vtable (+1 for the virtual flag on non-ARM).
CGF.EmitBlock(FnVirtual);
// Cast the adjusted this to a pointer to vtable pointer and load.
llvm::Type *VTableTy = Builder.getInt8PtrTy();
CharUnits VTablePtrAlign =
CGF.CGM.getDynamicOffsetAlignment(ThisAddr.getAlignment(), RD,
CGF.getPointerAlign());
llvm::Value *VTable =
CGF.GetVTablePtr(Address(This, VTablePtrAlign), VTableTy, RD);
// Apply the offset.
// On ARM64, to reserve extra space in virtual member function pointers,
// we only pay attention to the low 32 bits of the offset.
llvm::Value *VTableOffset = FnAsInt;
if (!UseARMMethodPtrABI)
VTableOffset = Builder.CreateSub(VTableOffset, ptrdiff_1);
if (Use32BitVTableOffsetABI) {
VTableOffset = Builder.CreateTrunc(VTableOffset, CGF.Int32Ty);
VTableOffset = Builder.CreateZExt(VTableOffset, CGM.PtrDiffTy);
}
// Check the address of the function pointer if CFI on member function
// pointers is enabled.
llvm::Constant *CheckSourceLocation;
llvm::Constant *CheckTypeDesc;
bool ShouldEmitCFICheck = CGF.SanOpts.has(SanitizerKind::CFIMFCall) &&
CGM.HasHiddenLTOVisibility(RD);
bool ShouldEmitVFEInfo = CGM.getCodeGenOpts().VirtualFunctionElimination &&
CGM.HasHiddenLTOVisibility(RD);
bool ShouldEmitWPDInfo =
CGM.getCodeGenOpts().WholeProgramVTables &&
// Don't insert type tests if we are forcing public std visibility.
!CGM.HasLTOVisibilityPublicStd(RD);
llvm::Value *VirtualFn = nullptr;
{
CodeGenFunction::SanitizerScope SanScope(&CGF);
llvm::Value *TypeId = nullptr;
llvm::Value *CheckResult = nullptr;
if (ShouldEmitCFICheck || ShouldEmitVFEInfo || ShouldEmitWPDInfo) {
// If doing CFI, VFE or WPD, we will need the metadata node to check
// against.
llvm::Metadata *MD =
CGM.CreateMetadataIdentifierForVirtualMemPtrType(QualType(MPT, 0));
TypeId = llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
}
if (ShouldEmitVFEInfo) {
llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
// If doing VFE, load from the vtable with a type.checked.load intrinsic
// call. Note that we use the GEP to calculate the address to load from
// and pass 0 as the offset to the intrinsic. This is because every
// vtable slot of the correct type is marked with matching metadata, and
// we know that the load must be from one of these slots.
llvm::Value *CheckedLoad = Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
{VFPAddr, llvm::ConstantInt::get(CGM.Int32Ty, 0), TypeId});
CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
VirtualFn = Builder.CreateExtractValue(CheckedLoad, 0);
VirtualFn = Builder.CreateBitCast(VirtualFn, FTy->getPointerTo(),
"memptr.virtualfn");
} else {
// When not doing VFE, emit a normal load, as it allows more
// optimisations than type.checked.load.
if (ShouldEmitCFICheck || ShouldEmitWPDInfo) {
llvm::Value *VFPAddr = Builder.CreateGEP(VTable, VTableOffset);
CheckResult = Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::type_test),
{Builder.CreateBitCast(VFPAddr, CGF.Int8PtrTy), TypeId});
}
if (CGM.getItaniumVTableContext().isRelativeLayout()) {
VirtualFn = CGF.Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::load_relative,
{VTableOffset->getType()}),
{VTable, VTableOffset});
VirtualFn = CGF.Builder.CreateBitCast(VirtualFn, FTy->getPointerTo());
} else {
llvm::Value *VFPAddr = CGF.Builder.CreateGEP(VTable, VTableOffset);
VFPAddr = CGF.Builder.CreateBitCast(
VFPAddr, FTy->getPointerTo()->getPointerTo());
VirtualFn = CGF.Builder.CreateAlignedLoad(
VFPAddr, CGF.getPointerAlign(), "memptr.virtualfn");
}
}
assert(VirtualFn && "Virtual fuction pointer not created!");
assert((!ShouldEmitCFICheck || !ShouldEmitVFEInfo || !ShouldEmitWPDInfo ||
CheckResult) &&
"Check result required but not created!");
if (ShouldEmitCFICheck) {
// If doing CFI, emit the check.
CheckSourceLocation = CGF.EmitCheckSourceLocation(E->getBeginLoc());
CheckTypeDesc = CGF.EmitCheckTypeDescriptor(QualType(MPT, 0));
llvm::Constant *StaticData[] = {
llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_VMFCall),
CheckSourceLocation,
CheckTypeDesc,
};
if (CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIMFCall)) {
CGF.EmitTrapCheck(CheckResult);
} else {
llvm::Value *AllVtables = llvm::MetadataAsValue::get(
CGM.getLLVMContext(),
llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
llvm::Value *ValidVtable = Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::type_test), {VTable, AllVtables});
CGF.EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIMFCall),
SanitizerHandler::CFICheckFail, StaticData,
{VTable, ValidVtable});
}
FnVirtual = Builder.GetInsertBlock();
}
} // End of sanitizer scope
CGF.EmitBranch(FnEnd);
// In the non-virtual path, the function pointer is actually a
// function pointer.
CGF.EmitBlock(FnNonVirtual);
llvm::Value *NonVirtualFn =
Builder.CreateIntToPtr(FnAsInt, FTy->getPointerTo(), "memptr.nonvirtualfn");
// Check the function pointer if CFI on member function pointers is enabled.
if (ShouldEmitCFICheck) {
CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
if (RD->hasDefinition()) {
CodeGenFunction::SanitizerScope SanScope(&CGF);
llvm::Constant *StaticData[] = {
llvm::ConstantInt::get(CGF.Int8Ty, CodeGenFunction::CFITCK_NVMFCall),
CheckSourceLocation,
CheckTypeDesc,
};
llvm::Value *Bit = Builder.getFalse();
llvm::Value *CastedNonVirtualFn =
Builder.CreateBitCast(NonVirtualFn, CGF.Int8PtrTy);
for (const CXXRecordDecl *Base : CGM.getMostBaseClasses(RD)) {
llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(
getContext().getMemberPointerType(
MPT->getPointeeType(),
getContext().getRecordType(Base).getTypePtr()));
llvm::Value *TypeId =
llvm::MetadataAsValue::get(CGF.getLLVMContext(), MD);
llvm::Value *TypeTest =
Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
{CastedNonVirtualFn, TypeId});
Bit = Builder.CreateOr(Bit, TypeTest);
}
CGF.EmitCheck(std::make_pair(Bit, SanitizerKind::CFIMFCall),
SanitizerHandler::CFICheckFail, StaticData,
{CastedNonVirtualFn, llvm::UndefValue::get(CGF.IntPtrTy)});
FnNonVirtual = Builder.GetInsertBlock();
}
}
// We're done.
CGF.EmitBlock(FnEnd);
llvm::PHINode *CalleePtr = Builder.CreatePHI(FTy->getPointerTo(), 2);
CalleePtr->addIncoming(VirtualFn, FnVirtual);
CalleePtr->addIncoming(NonVirtualFn, FnNonVirtual);
CGCallee Callee(FPT, CalleePtr);
return Callee;
}
/// Compute an l-value by applying the given pointer-to-member to a
/// base object.
llvm::Value *ItaniumCXXABI::EmitMemberDataPointerAddress(
CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
const MemberPointerType *MPT) {
assert(MemPtr->getType() == CGM.PtrDiffTy);
CGBuilderTy &Builder = CGF.Builder;
// Cast to char*.
Base = Builder.CreateElementBitCast(Base, CGF.Int8Ty);
// Apply the offset, which we assume is non-null.
llvm::Value *Addr =
Builder.CreateInBoundsGEP(Base.getPointer(), MemPtr, "memptr.offset");
// Cast the address to the appropriate pointer type, adopting the
// address space of the base pointer.
llvm::Type *PType = CGF.ConvertTypeForMem(MPT->getPointeeType())
->getPointerTo(Base.getAddressSpace());
return Builder.CreateBitCast(Addr, PType);
}
/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
/// conversion.
///
/// Bitcast conversions are always a no-op under Itanium.
///
/// Obligatory offset/adjustment diagram:
/// <-- offset --> <-- adjustment -->
/// |--------------------------|----------------------|--------------------|
/// ^Derived address point ^Base address point ^Member address point
///
/// So when converting a base member pointer to a derived member pointer,
/// we add the offset to the adjustment because the address point has
/// decreased; and conversely, when converting a derived MP to a base MP
/// we subtract the offset from the adjustment because the address point
/// has increased.
///
/// The standard forbids (at compile time) conversion to and from
/// virtual bases, which is why we don't have to consider them here.
///
/// The standard forbids (at run time) casting a derived MP to a base
/// MP when the derived MP does not point to a member of the base.
/// This is why -1 is a reasonable choice for null data member
/// pointers.
llvm::Value *
ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
const CastExpr *E,
llvm::Value *src) {
assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
E->getCastKind() == CK_BaseToDerivedMemberPointer ||
E->getCastKind() == CK_ReinterpretMemberPointer);
// Under Itanium, reinterprets don't require any additional processing.
if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
// Use constant emission if we can.
if (isa<llvm::Constant>(src))
return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
llvm::Constant *adj = getMemberPointerAdjustment(E);
if (!adj) return src;
CGBuilderTy &Builder = CGF.Builder;
bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
const MemberPointerType *destTy =
E->getType()->castAs<MemberPointerType>();
// For member data pointers, this is just a matter of adding the
// offset if the source is non-null.
if (destTy->isMemberDataPointer()) {
llvm::Value *dst;
if (isDerivedToBase)
dst = Builder.CreateNSWSub(src, adj, "adj");
else
dst = Builder.CreateNSWAdd(src, adj, "adj");
// Null check.
llvm::Value *null = llvm::Constant::getAllOnesValue(src->getType());
llvm::Value *isNull = Builder.CreateICmpEQ(src, null, "memptr.isnull");
return Builder.CreateSelect(isNull, src, dst);
}
// The this-adjustment is left-shifted by 1 on ARM.
if (UseARMMethodPtrABI) {
uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
offset <<= 1;
adj = llvm::ConstantInt::get(adj->getType(), offset);
}
llvm::Value *srcAdj = Builder.CreateExtractValue(src, 1, "src.adj");
llvm::Value *dstAdj;
if (isDerivedToBase)
dstAdj = Builder.CreateNSWSub(srcAdj, adj, "adj");
else
dstAdj = Builder.CreateNSWAdd(srcAdj, adj, "adj");
return Builder.CreateInsertValue(src, dstAdj, 1);
}
llvm::Constant *
ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
llvm::Constant *src) {
assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
E->getCastKind() == CK_BaseToDerivedMemberPointer ||
E->getCastKind() == CK_ReinterpretMemberPointer);
// Under Itanium, reinterprets don't require any additional processing.
if (E->getCastKind() == CK_ReinterpretMemberPointer) return src;
// If the adjustment is trivial, we don't need to do anything.
llvm::Constant *adj = getMemberPointerAdjustment(E);
if (!adj) return src;
bool isDerivedToBase = (E->getCastKind() == CK_DerivedToBaseMemberPointer);
const MemberPointerType *destTy =
E->getType()->castAs<MemberPointerType>();
// For member data pointers, this is just a matter of adding the
// offset if the source is non-null.
if (destTy->isMemberDataPointer()) {
// null maps to null.
if (src->isAllOnesValue()) return src;
if (isDerivedToBase)
return llvm::ConstantExpr::getNSWSub(src, adj);
else
return llvm::ConstantExpr::getNSWAdd(src, adj);
}
// The this-adjustment is left-shifted by 1 on ARM.
if (UseARMMethodPtrABI) {
uint64_t offset = cast<llvm::ConstantInt>(adj)->getZExtValue();
offset <<= 1;
adj = llvm::ConstantInt::get(adj->getType(), offset);
}
llvm::Constant *srcAdj = llvm::ConstantExpr::getExtractValue(src, 1);
llvm::Constant *dstAdj;
if (isDerivedToBase)
dstAdj = llvm::ConstantExpr::getNSWSub(srcAdj, adj);
else
dstAdj = llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
}
llvm::Constant *
ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
// Itanium C++ ABI 2.3:
// A NULL pointer is represented as -1.
if (MPT->isMemberDataPointer())
return llvm::ConstantInt::get(CGM.PtrDiffTy, -1ULL, /*isSigned=*/true);
llvm::Constant *Zero = llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
llvm::Constant *Values[2] = { Zero, Zero };
return llvm::ConstantStruct::getAnon(Values);
}
llvm::Constant *
ItaniumCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
CharUnits offset) {
// Itanium C++ ABI 2.3:
// A pointer to data member is an offset from the base address of
// the class object containing it, represented as a ptrdiff_t
return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
}
llvm::Constant *
ItaniumCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
return BuildMemberPointer(MD, CharUnits::Zero());
}
llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
CharUnits ThisAdjustment) {
assert(MD->isInstance() && "Member function must not be static!");
CodeGenTypes &Types = CGM.getTypes();
// Get the function pointer (or index if this is a virtual function).
llvm::Constant *MemPtr[2];
if (MD->isVirtual()) {
uint64_t Index = CGM.getItaniumVTableContext().getMethodVTableIndex(MD);
uint64_t VTableOffset;
if (CGM.getItaniumVTableContext().isRelativeLayout()) {
// Multiply by 4-byte relative offsets.
VTableOffset = Index * 4;
} else {
const ASTContext &Context = getContext();
CharUnits PointerWidth = Context.toCharUnitsFromBits(
Context.getTargetInfo().getPointerWidth(0));
VTableOffset = Index * PointerWidth.getQuantity();
}
if (UseARMMethodPtrABI) {
// ARM C++ ABI 3.2.1:
// This ABI specifies that adj contains twice the this
// adjustment, plus 1 if the member function is virtual. The
// least significant bit of adj then makes exactly the same
// discrimination as the least significant bit of ptr does for
// Itanium.
MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset);
MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
2 * ThisAdjustment.getQuantity() + 1);
} else {
// Itanium C++ ABI 2.3:
// For a virtual function, [the pointer field] is 1 plus the
// virtual table offset (in bytes) of the function,
// represented as a ptrdiff_t.
MemPtr[0] = llvm::ConstantInt::get(CGM.PtrDiffTy, VTableOffset + 1);
MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
ThisAdjustment.getQuantity());
}
} else {
const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
llvm::Type *Ty;
// Check whether the function has a computable LLVM signature.
if (Types.isFuncTypeConvertible(FPT)) {
// The function has a computable LLVM signature; use the correct type.
Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
} else {
// Use an arbitrary non-function type to tell GetAddrOfFunction that the
// function type is incomplete.
Ty = CGM.PtrDiffTy;
}
llvm::Constant *addr = CGM.GetAddrOfFunction(MD, Ty);
MemPtr[0] = llvm::ConstantExpr::getPtrToInt(addr, CGM.PtrDiffTy);
MemPtr[1] = llvm::ConstantInt::get(CGM.PtrDiffTy,
(UseARMMethodPtrABI ? 2 : 1) *
ThisAdjustment.getQuantity());
}
return llvm::ConstantStruct::getAnon(MemPtr);
}
llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
QualType MPType) {
const MemberPointerType *MPT = MPType->castAs<MemberPointerType>();
const ValueDecl *MPD = MP.getMemberPointerDecl();
if (!MPD)
return EmitNullMemberPointer(MPT);
CharUnits ThisAdjustment = getMemberPointerPathAdjustment(MP);
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD))
return BuildMemberPointer(MD, ThisAdjustment);
CharUnits FieldOffset =
getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
}
/// The comparison algorithm is pretty easy: the member pointers are
/// the same if they're either bitwise identical *or* both null.
///
/// ARM is different here only because null-ness is more complicated.
llvm::Value *
ItaniumCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
llvm::Value *L,
llvm::Value *R,
const MemberPointerType *MPT,
bool Inequality) {
CGBuilderTy &Builder = CGF.Builder;
llvm::ICmpInst::Predicate Eq;
llvm::Instruction::BinaryOps And, Or;
if (Inequality) {
Eq = llvm::ICmpInst::ICMP_NE;
And = llvm::Instruction::Or;
Or = llvm::Instruction::And;
} else {
Eq = llvm::ICmpInst::ICMP_EQ;
And = llvm::Instruction::And;
Or = llvm::Instruction::Or;
}
// Member data pointers are easy because there's a unique null
// value, so it just comes down to bitwise equality.
if (MPT->isMemberDataPointer())
return Builder.CreateICmp(Eq, L, R);
// For member function pointers, the tautologies are more complex.
// The Itanium tautology is:
// (L == R) <==> (L.ptr == R.ptr && (L.ptr == 0 || L.adj == R.adj))
// The ARM tautology is:
// (L == R) <==> (L.ptr == R.ptr &&
// (L.adj == R.adj ||
// (L.ptr == 0 && ((L.adj|R.adj) & 1) == 0)))
// The inequality tautologies have exactly the same structure, except
// applying De Morgan's laws.
llvm::Value *LPtr = Builder.CreateExtractValue(L, 0, "lhs.memptr.ptr");
llvm::Value *RPtr = Builder.CreateExtractValue(R, 0, "rhs.memptr.ptr");
// This condition tests whether L.ptr == R.ptr. This must always be
// true for equality to hold.
llvm::Value *PtrEq = Builder.CreateICmp(Eq, LPtr, RPtr, "cmp.ptr");
// This condition, together with the assumption that L.ptr == R.ptr,
// tests whether the pointers are both null. ARM imposes an extra
// condition.
llvm::Value *Zero = llvm::Constant::getNullValue(LPtr->getType());
llvm::Value *EqZero = Builder.CreateICmp(Eq, LPtr, Zero, "cmp.ptr.null");
// This condition tests whether L.adj == R.adj. If this isn't
// true, the pointers are unequal unless they're both null.
llvm::Value *LAdj = Builder.CreateExtractValue(L, 1, "lhs.memptr.adj");
llvm::Value *RAdj = Builder.CreateExtractValue(R, 1, "rhs.memptr.adj");
llvm::Value *AdjEq = Builder.CreateICmp(Eq, LAdj, RAdj, "cmp.adj");
// Null member function pointers on ARM clear the low bit of Adj,
// so the zero condition has to check that neither low bit is set.
if (UseARMMethodPtrABI) {
llvm::Value *One = llvm::ConstantInt::get(LPtr->getType(), 1);
// Compute (l.adj | r.adj) & 1 and test it against zero.
llvm::Value *OrAdj = Builder.CreateOr(LAdj, RAdj, "or.adj");
llvm::Value *OrAdjAnd1 = Builder.CreateAnd(OrAdj, One);
llvm::Value *OrAdjAnd1EqZero = Builder.CreateICmp(Eq, OrAdjAnd1, Zero,
"cmp.or.adj");
EqZero = Builder.CreateBinOp(And, EqZero, OrAdjAnd1EqZero);
}
// Tie together all our conditions.
llvm::Value *Result = Builder.CreateBinOp(Or, EqZero, AdjEq);
Result = Builder.CreateBinOp(And, PtrEq, Result,
Inequality ? "memptr.ne" : "memptr.eq");
return Result;
}
llvm::Value *
ItaniumCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
llvm::Value *MemPtr,
const MemberPointerType *MPT) {
CGBuilderTy &Builder = CGF.Builder;
/// For member data pointers, this is just a check against -1.
if (MPT->isMemberDataPointer()) {
assert(MemPtr->getType() == CGM.PtrDiffTy);
llvm::Value *NegativeOne =
llvm::Constant::getAllOnesValue(MemPtr->getType());
return Builder.CreateICmpNE(MemPtr, NegativeOne, "memptr.tobool");
}
// In Itanium, a member function pointer is not null if 'ptr' is not null.
llvm::Value *Ptr = Builder.CreateExtractValue(MemPtr, 0, "memptr.ptr");
llvm::Constant *Zero = llvm::ConstantInt::get(Ptr->getType(), 0);
llvm::Value *Result = Builder.CreateICmpNE(Ptr, Zero, "memptr.tobool");
// On ARM, a member function pointer is also non-null if the low bit of 'adj'
// (the virtual bit) is set.
if (UseARMMethodPtrABI) {
llvm::Constant *One = llvm::ConstantInt::get(Ptr->getType(), 1);
llvm::Value *Adj = Builder.CreateExtractValue(MemPtr, 1, "memptr.adj");
llvm::Value *VirtualBit = Builder.CreateAnd(Adj, One, "memptr.virtualbit");
llvm::Value *IsVirtual = Builder.CreateICmpNE(VirtualBit, Zero,
"memptr.isvirtual");
Result = Builder.CreateOr(Result, IsVirtual);
}
return Result;
}
bool ItaniumCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
if (!RD)
return false;
// If C++ prohibits us from making a copy, return by address.
if (!RD->canPassInRegisters()) {
auto Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
return true;<|fim▁hole|>
/// The Itanium ABI requires non-zero initialization only for data
/// member pointers, for which '0' is a valid offset.
bool ItaniumCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
return MPT->isMemberFunctionPointer();
}
/// The Itanium ABI always places an offset to the complete object
/// at entry -2 in the vtable.
void ItaniumCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
const CXXDeleteExpr *DE,
Address Ptr,
QualType ElementType,
const CXXDestructorDecl *Dtor) {
bool UseGlobalDelete = DE->isGlobalDelete();
if (UseGlobalDelete) {
// Derive the complete-object pointer, which is what we need
// to pass to the deallocation function.
// Grab the vtable pointer as an intptr_t*.
auto *ClassDecl =
cast<CXXRecordDecl>(ElementType->castAs<RecordType>()->getDecl());
llvm::Value *VTable =
CGF.GetVTablePtr(Ptr, CGF.IntPtrTy->getPointerTo(), ClassDecl);
// Track back to entry -2 and pull out the offset there.
llvm::Value *OffsetPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
VTable, -2, "complete-offset.ptr");
llvm::Value *Offset =
CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
// Apply the offset.
llvm::Value *CompletePtr =
CGF.Builder.CreateBitCast(Ptr.getPointer(), CGF.Int8PtrTy);
CompletePtr = CGF.Builder.CreateInBoundsGEP(CompletePtr, Offset);
// If we're supposed to call the global delete, make sure we do so
// even if the destructor throws.
CGF.pushCallObjectDeleteCleanup(DE->getOperatorDelete(), CompletePtr,
ElementType);
}
// FIXME: Provide a source location here even though there's no
// CXXMemberCallExpr for dtor call.
CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
if (UseGlobalDelete)
CGF.PopCleanupBlock();
}
void ItaniumCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
// void __cxa_rethrow();
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FTy, "__cxa_rethrow");
if (isNoReturn)
CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, None);
else
CGF.EmitRuntimeCallOrInvoke(Fn);
}
static llvm::FunctionCallee getAllocateExceptionFn(CodeGenModule &CGM) {
// void *__cxa_allocate_exception(size_t thrown_size);
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.Int8PtrTy, CGM.SizeTy, /*isVarArg=*/false);
return CGM.CreateRuntimeFunction(FTy, "__cxa_allocate_exception");
}
static llvm::FunctionCallee getThrowFn(CodeGenModule &CGM) {
// void __cxa_throw(void *thrown_exception, std::type_info *tinfo,
// void (*dest) (void *));
llvm::Type *Args[3] = { CGM.Int8PtrTy, CGM.Int8PtrTy, CGM.Int8PtrTy };
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, Args, /*isVarArg=*/false);
return CGM.CreateRuntimeFunction(FTy, "__cxa_throw");
}
void ItaniumCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
QualType ThrowType = E->getSubExpr()->getType();
// Now allocate the exception object.
llvm::Type *SizeTy = CGF.ConvertType(getContext().getSizeType());
uint64_t TypeSize = getContext().getTypeSizeInChars(ThrowType).getQuantity();
llvm::FunctionCallee AllocExceptionFn = getAllocateExceptionFn(CGM);
llvm::CallInst *ExceptionPtr = CGF.EmitNounwindRuntimeCall(
AllocExceptionFn, llvm::ConstantInt::get(SizeTy, TypeSize), "exception");
CharUnits ExnAlign = CGF.getContext().getExnObjectAlignment();
CGF.EmitAnyExprToExn(E->getSubExpr(), Address(ExceptionPtr, ExnAlign));
// Now throw the exception.
llvm::Constant *TypeInfo = CGM.GetAddrOfRTTIDescriptor(ThrowType,
/*ForEH=*/true);
// The address of the destructor. If the exception type has a
// trivial destructor (or isn't a record), we just pass null.
llvm::Constant *Dtor = nullptr;
if (const RecordType *RecordTy = ThrowType->getAs<RecordType>()) {
CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
if (!Record->hasTrivialDestructor()) {
CXXDestructorDecl *DtorD = Record->getDestructor();
Dtor = CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete));
Dtor = llvm::ConstantExpr::getBitCast(Dtor, CGM.Int8PtrTy);
}
}
if (!Dtor) Dtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
llvm::Value *args[] = { ExceptionPtr, TypeInfo, Dtor };
CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(CGM), args);
}
static llvm::FunctionCallee getItaniumDynamicCastFn(CodeGenFunction &CGF) {
// void *__dynamic_cast(const void *sub,
// const abi::__class_type_info *src,
// const abi::__class_type_info *dst,
// std::ptrdiff_t src2dst_offset);
llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
llvm::Type *PtrDiffTy =
CGF.ConvertType(CGF.getContext().getPointerDiffType());
llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
// Mark the function as nounwind readonly.
llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
llvm::Attribute::ReadOnly };
llvm::AttributeList Attrs = llvm::AttributeList::get(
CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, FuncAttrs);
return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
}
static llvm::FunctionCallee getBadCastFn(CodeGenFunction &CGF) {
// void __cxa_bad_cast();
llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
}
/// Compute the src2dst_offset hint as described in the
/// Itanium C++ ABI [2.9.7]
static CharUnits computeOffsetHint(ASTContext &Context,
const CXXRecordDecl *Src,
const CXXRecordDecl *Dst) {
CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
/*DetectVirtual=*/false);
// If Dst is not derived from Src we can skip the whole computation below and
// return that Src is not a public base of Dst. Record all inheritance paths.
if (!Dst->isDerivedFrom(Src, Paths))
return CharUnits::fromQuantity(-2ULL);
unsigned NumPublicPaths = 0;
CharUnits Offset;
// Now walk all possible inheritance paths.
for (const CXXBasePath &Path : Paths) {
if (Path.Access != AS_public) // Ignore non-public inheritance.
continue;
++NumPublicPaths;
for (const CXXBasePathElement &PathElement : Path) {
// If the path contains a virtual base class we can't give any hint.
// -1: no hint.
if (PathElement.Base->isVirtual())
return CharUnits::fromQuantity(-1ULL);
if (NumPublicPaths > 1) // Won't use offsets, skip computation.
continue;
// Accumulate the base class offsets.
const ASTRecordLayout &L = Context.getASTRecordLayout(PathElement.Class);
Offset += L.getBaseClassOffset(
PathElement.Base->getType()->getAsCXXRecordDecl());
}
}
// -2: Src is not a public base of Dst.
if (NumPublicPaths == 0)
return CharUnits::fromQuantity(-2ULL);
// -3: Src is a multiple public base type but never a virtual base type.
if (NumPublicPaths > 1)
return CharUnits::fromQuantity(-3ULL);
// Otherwise, the Src type is a unique public nonvirtual base type of Dst.
// Return the offset of Src from the origin of Dst.
return Offset;
}
static llvm::FunctionCallee getBadTypeidFn(CodeGenFunction &CGF) {
// void __cxa_bad_typeid();
llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
}
bool ItaniumCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
QualType SrcRecordTy) {
return IsDeref;
}
void ItaniumCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
llvm::FunctionCallee Fn = getBadTypeidFn(CGF);
llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
Call->setDoesNotReturn();
CGF.Builder.CreateUnreachable();
}
llvm::Value *ItaniumCXXABI::EmitTypeid(CodeGenFunction &CGF,
QualType SrcRecordTy,
Address ThisPtr,
llvm::Type *StdTypeInfoPtrTy) {
auto *ClassDecl =
cast<CXXRecordDecl>(SrcRecordTy->castAs<RecordType>()->getDecl());
llvm::Value *Value =
CGF.GetVTablePtr(ThisPtr, StdTypeInfoPtrTy->getPointerTo(), ClassDecl);
if (CGM.getItaniumVTableContext().isRelativeLayout()) {
// Load the type info.
Value = CGF.Builder.CreateBitCast(Value, CGM.Int8PtrTy);
Value = CGF.Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
{Value, llvm::ConstantInt::get(CGM.Int32Ty, -4)});
// Setup to dereference again since this is a proxy we accessed.
Value = CGF.Builder.CreateBitCast(Value, StdTypeInfoPtrTy->getPointerTo());
} else {
// Load the type info.
Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
}
return CGF.Builder.CreateAlignedLoad(Value, CGF.getPointerAlign());
}
bool ItaniumCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
QualType SrcRecordTy) {
return SrcIsPtr;
}
llvm::Value *ItaniumCXXABI::EmitDynamicCastCall(
CodeGenFunction &CGF, Address ThisAddr, QualType SrcRecordTy,
QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
llvm::Type *PtrDiffLTy =
CGF.ConvertType(CGF.getContext().getPointerDiffType());
llvm::Type *DestLTy = CGF.ConvertType(DestTy);
llvm::Value *SrcRTTI =
CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
llvm::Value *DestRTTI =
CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
// Compute the offset hint.
const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
llvm::Value *OffsetHint = llvm::ConstantInt::get(
PtrDiffLTy,
computeOffsetHint(CGF.getContext(), SrcDecl, DestDecl).getQuantity());
// Emit the call to __dynamic_cast.
llvm::Value *Value = ThisAddr.getPointer();
Value = CGF.EmitCastToVoidPtr(Value);
llvm::Value *args[] = {Value, SrcRTTI, DestRTTI, OffsetHint};
Value = CGF.EmitNounwindRuntimeCall(getItaniumDynamicCastFn(CGF), args);
Value = CGF.Builder.CreateBitCast(Value, DestLTy);
/// C++ [expr.dynamic.cast]p9:
/// A failed cast to reference type throws std::bad_cast
if (DestTy->isReferenceType()) {
llvm::BasicBlock *BadCastBlock =
CGF.createBasicBlock("dynamic_cast.bad_cast");
llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
CGF.EmitBlock(BadCastBlock);
EmitBadCastCall(CGF);
}
return Value;
}
llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,
Address ThisAddr,
QualType SrcRecordTy,
QualType DestTy) {
llvm::Type *DestLTy = CGF.ConvertType(DestTy);
auto *ClassDecl =
cast<CXXRecordDecl>(SrcRecordTy->castAs<RecordType>()->getDecl());
llvm::Value *OffsetToTop;
if (CGM.getItaniumVTableContext().isRelativeLayout()) {
// Get the vtable pointer.
llvm::Value *VTable =
CGF.GetVTablePtr(ThisAddr, CGM.Int32Ty->getPointerTo(), ClassDecl);
// Get the offset-to-top from the vtable.
OffsetToTop =
CGF.Builder.CreateConstInBoundsGEP1_32(/*Type=*/nullptr, VTable, -2U);
OffsetToTop = CGF.Builder.CreateAlignedLoad(
OffsetToTop, CharUnits::fromQuantity(4), "offset.to.top");
} else {
llvm::Type *PtrDiffLTy =
CGF.ConvertType(CGF.getContext().getPointerDiffType());
// Get the vtable pointer.
llvm::Value *VTable =
CGF.GetVTablePtr(ThisAddr, PtrDiffLTy->getPointerTo(), ClassDecl);
// Get the offset-to-top from the vtable.
OffsetToTop = CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
OffsetToTop = CGF.Builder.CreateAlignedLoad(
OffsetToTop, CGF.getPointerAlign(), "offset.to.top");
}
// Finally, add the offset to the pointer.
llvm::Value *Value = ThisAddr.getPointer();
Value = CGF.EmitCastToVoidPtr(Value);
Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
return CGF.Builder.CreateBitCast(Value, DestLTy);
}
bool ItaniumCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
llvm::FunctionCallee Fn = getBadCastFn(CGF);
llvm::CallBase *Call = CGF.EmitRuntimeCallOrInvoke(Fn);
Call->setDoesNotReturn();
CGF.Builder.CreateUnreachable();
return true;
}
llvm::Value *
ItaniumCXXABI::GetVirtualBaseClassOffset(CodeGenFunction &CGF,
Address This,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) {
llvm::Value *VTablePtr = CGF.GetVTablePtr(This, CGM.Int8PtrTy, ClassDecl);
CharUnits VBaseOffsetOffset =
CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(ClassDecl,
BaseClassDecl);
llvm::Value *VBaseOffsetPtr =
CGF.Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
"vbase.offset.ptr");
llvm::Value *VBaseOffset;
if (CGM.getItaniumVTableContext().isRelativeLayout()) {
VBaseOffsetPtr =
CGF.Builder.CreateBitCast(VBaseOffsetPtr, CGF.Int32Ty->getPointerTo());
VBaseOffset = CGF.Builder.CreateAlignedLoad(
VBaseOffsetPtr, CharUnits::fromQuantity(4), "vbase.offset");
} else {
VBaseOffsetPtr = CGF.Builder.CreateBitCast(VBaseOffsetPtr,
CGM.PtrDiffTy->getPointerTo());
VBaseOffset = CGF.Builder.CreateAlignedLoad(
VBaseOffsetPtr, CGF.getPointerAlign(), "vbase.offset");
}
return VBaseOffset;
}
void ItaniumCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
// Just make sure we're in sync with TargetCXXABI.
assert(CGM.getTarget().getCXXABI().hasConstructorVariants());
// The constructor used for constructing this as a base class;
// ignores virtual bases.
CGM.EmitGlobal(GlobalDecl(D, Ctor_Base));
// The constructor used for constructing this as a complete class;
// constructs the virtual bases, then calls the base constructor.
if (!D->getParent()->isAbstract()) {
// We don't need to emit the complete ctor if the class is abstract.
CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
}
}
CGCXXABI::AddedStructorArgCounts
ItaniumCXXABI::buildStructorSignature(GlobalDecl GD,
SmallVectorImpl<CanQualType> &ArgTys) {
ASTContext &Context = getContext();
// All parameters are already in place except VTT, which goes after 'this'.
// These are Clang types, so we don't need to worry about sret yet.
// Check if we need to add a VTT parameter (which has type void **).
if ((isa<CXXConstructorDecl>(GD.getDecl()) ? GD.getCtorType() == Ctor_Base
: GD.getDtorType() == Dtor_Base) &&
cast<CXXMethodDecl>(GD.getDecl())->getParent()->getNumVBases() != 0) {
ArgTys.insert(ArgTys.begin() + 1,
Context.getPointerType(Context.VoidPtrTy));
return AddedStructorArgCounts::prefix(1);
}
return AddedStructorArgCounts{};
}
void ItaniumCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
// The destructor used for destructing this as a base class; ignores
// virtual bases.
CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
// The destructor used for destructing this as a most-derived class;
// call the base destructor and then destructs any virtual bases.
CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
// The destructor in a virtual table is always a 'deleting'
// destructor, which calls the complete destructor and then uses the
// appropriate operator delete.
if (D->isVirtual())
CGM.EmitGlobal(GlobalDecl(D, Dtor_Deleting));
}
void ItaniumCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
QualType &ResTy,
FunctionArgList &Params) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
// Check if we need a VTT parameter as well.
if (NeedsVTTParameter(CGF.CurGD)) {
ASTContext &Context = getContext();
// FIXME: avoid the fake decl
QualType T = Context.getPointerType(Context.VoidPtrTy);
auto *VTTDecl = ImplicitParamDecl::Create(
Context, /*DC=*/nullptr, MD->getLocation(), &Context.Idents.get("vtt"),
T, ImplicitParamDecl::CXXVTT);
Params.insert(Params.begin() + 1, VTTDecl);
getStructorImplicitParamDecl(CGF) = VTTDecl;
}
}
void ItaniumCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
// Naked functions have no prolog.
if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
return;
/// Initialize the 'this' slot. In the Itanium C++ ABI, no prologue
/// adjustments are required, because they are all handled by thunks.
setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
/// Initialize the 'vtt' slot if needed.
if (getStructorImplicitParamDecl(CGF)) {
getStructorImplicitParamValue(CGF) = CGF.Builder.CreateLoad(
CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)), "vtt");
}
/// If this is a function that the ABI specifies returns 'this', initialize
/// the return slot to 'this' at the start of the function.
///
/// Unlike the setting of return types, this is done within the ABI
/// implementation instead of by clients of CGCXXABI because:
/// 1) getThisValue is currently protected
/// 2) in theory, an ABI could implement 'this' returns some other way;
/// HasThisReturn only specifies a contract, not the implementation
if (HasThisReturn(CGF.CurGD))
CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
}
CGCXXABI::AddedStructorArgs ItaniumCXXABI::getImplicitConstructorArgs(
CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
bool ForVirtualBase, bool Delegating) {
if (!NeedsVTTParameter(GlobalDecl(D, Type)))
return AddedStructorArgs{};
// Insert the implicit 'vtt' argument as the second argument.
llvm::Value *VTT =
CGF.GetVTTParameter(GlobalDecl(D, Type), ForVirtualBase, Delegating);
QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
return AddedStructorArgs::prefix({{VTT, VTTTy}});
}
llvm::Value *ItaniumCXXABI::getCXXDestructorImplicitParam(
CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
bool ForVirtualBase, bool Delegating) {
GlobalDecl GD(DD, Type);
return CGF.GetVTTParameter(GD, ForVirtualBase, Delegating);
}
void ItaniumCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *DD,
CXXDtorType Type, bool ForVirtualBase,
bool Delegating, Address This,
QualType ThisTy) {
GlobalDecl GD(DD, Type);
llvm::Value *VTT =
getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase, Delegating);
QualType VTTTy = getContext().getPointerType(getContext().VoidPtrTy);
CGCallee Callee;
if (getContext().getLangOpts().AppleKext &&
Type != Dtor_Base && DD->isVirtual())
Callee = CGF.BuildAppleKextVirtualDestructorCall(DD, Type, DD->getParent());
else
Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, VTT, VTTTy,
nullptr);
}
void ItaniumCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
const CXXRecordDecl *RD) {
llvm::GlobalVariable *VTable = getAddrOfVTable(RD, CharUnits());
if (VTable->hasInitializer())
return;
ItaniumVTableContext &VTContext = CGM.getItaniumVTableContext();
const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
llvm::Constant *RTTI =
CGM.GetAddrOfRTTIDescriptor(CGM.getContext().getTagDeclType(RD));
// Create and set the initializer.
ConstantInitBuilder builder(CGM);
auto components = builder.beginStruct();
CGVT.createVTableInitializer(components, VTLayout, RTTI,
llvm::GlobalValue::isLocalLinkage(Linkage));
components.finishAndSetAsInitializer(VTable);
// Set the correct linkage.
VTable->setLinkage(Linkage);
if (CGM.supportsCOMDAT() && VTable->isWeakForLinker())
VTable->setComdat(CGM.getModule().getOrInsertComdat(VTable->getName()));
// Set the right visibility.
CGM.setGVProperties(VTable, RD);
// If this is the magic class __cxxabiv1::__fundamental_type_info,
// we will emit the typeinfo for the fundamental types. This is the
// same behaviour as GCC.
const DeclContext *DC = RD->getDeclContext();
if (RD->getIdentifier() &&
RD->getIdentifier()->isStr("__fundamental_type_info") &&
isa<NamespaceDecl>(DC) && cast<NamespaceDecl>(DC)->getIdentifier() &&
cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
DC->getParent()->isTranslationUnit())
EmitFundamentalRTTIDescriptors(RD);
if (!VTable->isDeclarationForLinker())
CGM.EmitVTableTypeMetadata(RD, VTable, VTLayout);
if (VTContext.isRelativeLayout() && !VTable->isDSOLocal())
CGVT.GenerateRelativeVTableAlias(VTable, VTable->getName());
}
bool ItaniumCXXABI::isVirtualOffsetNeededForVTableField(
CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
if (Vptr.NearestVBase == nullptr)
return false;
return NeedsVTTParameter(CGF.CurGD);
}
llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructor(
CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
const CXXRecordDecl *NearestVBase) {
if ((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
NeedsVTTParameter(CGF.CurGD)) {
return getVTableAddressPointInStructorWithVTT(CGF, VTableClass, Base,
NearestVBase);
}
return getVTableAddressPoint(Base, VTableClass);
}
llvm::Constant *
ItaniumCXXABI::getVTableAddressPoint(BaseSubobject Base,
const CXXRecordDecl *VTableClass) {
llvm::GlobalValue *VTable = getAddrOfVTable(VTableClass, CharUnits());
// Find the appropriate vtable within the vtable group, and the address point
// within that vtable.
VTableLayout::AddressPointLocation AddressPoint =
CGM.getItaniumVTableContext()
.getVTableLayout(VTableClass)
.getAddressPoint(Base);
llvm::Value *Indices[] = {
llvm::ConstantInt::get(CGM.Int32Ty, 0),
llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.VTableIndex),
llvm::ConstantInt::get(CGM.Int32Ty, AddressPoint.AddressPointIndex),
};
return llvm::ConstantExpr::getGetElementPtr(VTable->getValueType(), VTable,
Indices, /*InBounds=*/true,
/*InRangeIndex=*/1);
}
llvm::Value *ItaniumCXXABI::getVTableAddressPointInStructorWithVTT(
CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
const CXXRecordDecl *NearestVBase) {
assert((Base.getBase()->getNumVBases() || NearestVBase != nullptr) &&
NeedsVTTParameter(CGF.CurGD) && "This class doesn't have VTT");
// Get the secondary vpointer index.
uint64_t VirtualPointerIndex =
CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
/// Load the VTT.
llvm::Value *VTT = CGF.LoadCXXVTT();
if (VirtualPointerIndex)
VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
// And load the address point from the VTT.
return CGF.Builder.CreateAlignedLoad(VTT, CGF.getPointerAlign());
}
llvm::Constant *ItaniumCXXABI::getVTableAddressPointForConstExpr(
BaseSubobject Base, const CXXRecordDecl *VTableClass) {
return getVTableAddressPoint(Base, VTableClass);
}
llvm::GlobalVariable *ItaniumCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
CharUnits VPtrOffset) {
assert(VPtrOffset.isZero() && "Itanium ABI only supports zero vptr offsets");
llvm::GlobalVariable *&VTable = VTables[RD];
if (VTable)
return VTable;
// Queue up this vtable for possible deferred emission.
CGM.addDeferredVTable(RD);
SmallString<256> Name;
llvm::raw_svector_ostream Out(Name);
getMangleContext().mangleCXXVTable(RD, Out);
const VTableLayout &VTLayout =
CGM.getItaniumVTableContext().getVTableLayout(RD);
llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
// Use pointer alignment for the vtable. Otherwise we would align them based
// on the size of the initializer which doesn't make sense as only single
// values are read.
unsigned PAlign = CGM.getItaniumVTableContext().isRelativeLayout()
? 32
: CGM.getTarget().getPointerAlign(0);
VTable = CGM.CreateOrReplaceCXXRuntimeVariable(
Name, VTableType, llvm::GlobalValue::ExternalLinkage,
getContext().toCharUnitsFromBits(PAlign).getQuantity());
VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
CGM.setGVProperties(VTable, RD);
return VTable;
}
CGCallee ItaniumCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
GlobalDecl GD,
Address This,
llvm::Type *Ty,
SourceLocation Loc) {
auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
llvm::Value *VTable = CGF.GetVTablePtr(
This, Ty->getPointerTo()->getPointerTo(), MethodDecl->getParent());
uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
llvm::Value *VFunc;
if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
VFunc = CGF.EmitVTableTypeCheckedLoad(
MethodDecl->getParent(), VTable,
VTableIndex * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
} else {
CGF.EmitTypeMetadataCodeForVCall(MethodDecl->getParent(), VTable, Loc);
llvm::Value *VFuncLoad;
if (CGM.getItaniumVTableContext().isRelativeLayout()) {
VTable = CGF.Builder.CreateBitCast(VTable, CGM.Int8PtrTy);
llvm::Value *Load = CGF.Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::load_relative, {CGM.Int32Ty}),
{VTable, llvm::ConstantInt::get(CGM.Int32Ty, 4 * VTableIndex)});
VFuncLoad = CGF.Builder.CreateBitCast(Load, Ty->getPointerTo());
} else {
VTable =
CGF.Builder.CreateBitCast(VTable, Ty->getPointerTo()->getPointerTo());
llvm::Value *VTableSlotPtr =
CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
VFuncLoad =
CGF.Builder.CreateAlignedLoad(VTableSlotPtr, CGF.getPointerAlign());
}
// Add !invariant.load md to virtual function load to indicate that
// function didn't change inside vtable.
// It's safe to add it without -fstrict-vtable-pointers, but it would not
// help in devirtualization because it will only matter if we will have 2
// the same virtual function loads from the same vtable load, which won't
// happen without enabled devirtualization with -fstrict-vtable-pointers.
if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
CGM.getCodeGenOpts().StrictVTablePointers) {
if (auto *VFuncLoadInstr = dyn_cast<llvm::Instruction>(VFuncLoad)) {
VFuncLoadInstr->setMetadata(
llvm::LLVMContext::MD_invariant_load,
llvm::MDNode::get(CGM.getLLVMContext(),
llvm::ArrayRef<llvm::Metadata *>()));
}
}
VFunc = VFuncLoad;
}
CGCallee Callee(GD, VFunc);
return Callee;
}
llvm::Value *ItaniumCXXABI::EmitVirtualDestructorCall(
CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
Address This, DeleteOrMemberCallExpr E) {
auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
auto *D = E.dyn_cast<const CXXDeleteExpr *>();
assert((CE != nullptr) ^ (D != nullptr));
assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
GlobalDecl GD(Dtor, DtorType);
const CGFunctionInfo *FInfo =
&CGM.getTypes().arrangeCXXStructorDeclaration(GD);
llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
QualType ThisTy;
if (CE) {
ThisTy = CE->getObjectType();
} else {
ThisTy = D->getDestroyedType();
}
CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy, nullptr,
QualType(), nullptr);
return nullptr;
}
void ItaniumCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
CodeGenVTables &VTables = CGM.getVTables();
llvm::GlobalVariable *VTT = VTables.GetAddrOfVTT(RD);
VTables.EmitVTTDefinition(VTT, CGM.getVTableLinkage(RD), RD);
}
bool ItaniumCXXABI::canSpeculativelyEmitVTableAsBaseClass(
const CXXRecordDecl *RD) const {
// We don't emit available_externally vtables if we are in -fapple-kext mode
// because kext mode does not permit devirtualization.
if (CGM.getLangOpts().AppleKext)
return false;
// If the vtable is hidden then it is not safe to emit an available_externally
// copy of vtable.
if (isVTableHidden(RD))
return false;
if (CGM.getCodeGenOpts().ForceEmitVTables)
return true;
// If we don't have any not emitted inline virtual function then we are safe
// to emit an available_externally copy of vtable.
// FIXME we can still emit a copy of the vtable if we
// can emit definition of the inline functions.
if (hasAnyUnusedVirtualInlineFunction(RD))
return false;
// For a class with virtual bases, we must also be able to speculatively
// emit the VTT, because CodeGen doesn't have separate notions of "can emit
// the vtable" and "can emit the VTT". For a base subobject, this means we
// need to be able to emit non-virtual base vtables.
if (RD->getNumVBases()) {
for (const auto &B : RD->bases()) {
auto *BRD = B.getType()->getAsCXXRecordDecl();
assert(BRD && "no class for base specifier");
if (B.isVirtual() || !BRD->isDynamicClass())
continue;
if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
return false;
}
}
return true;
}
bool ItaniumCXXABI::canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const {
if (!canSpeculativelyEmitVTableAsBaseClass(RD))
return false;
// For a complete-object vtable (or more specifically, for the VTT), we need
// to be able to speculatively emit the vtables of all dynamic virtual bases.
for (const auto &B : RD->vbases()) {
auto *BRD = B.getType()->getAsCXXRecordDecl();
assert(BRD && "no class for base specifier");
if (!BRD->isDynamicClass())
continue;
if (!canSpeculativelyEmitVTableAsBaseClass(BRD))
return false;
}
return true;
}
static llvm::Value *performTypeAdjustment(CodeGenFunction &CGF,
Address InitialPtr,
int64_t NonVirtualAdjustment,
int64_t VirtualAdjustment,
bool IsReturnAdjustment) {
if (!NonVirtualAdjustment && !VirtualAdjustment)
return InitialPtr.getPointer();
Address V = CGF.Builder.CreateElementBitCast(InitialPtr, CGF.Int8Ty);
// In a base-to-derived cast, the non-virtual adjustment is applied first.
if (NonVirtualAdjustment && !IsReturnAdjustment) {
V = CGF.Builder.CreateConstInBoundsByteGEP(V,
CharUnits::fromQuantity(NonVirtualAdjustment));
}
// Perform the virtual adjustment if we have one.
llvm::Value *ResultPtr;
if (VirtualAdjustment) {
Address VTablePtrPtr = CGF.Builder.CreateElementBitCast(V, CGF.Int8PtrTy);
llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
llvm::Value *Offset;
llvm::Value *OffsetPtr =
CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
if (CGF.CGM.getItaniumVTableContext().isRelativeLayout()) {
// Load the adjustment offset from the vtable as a 32-bit int.
OffsetPtr =
CGF.Builder.CreateBitCast(OffsetPtr, CGF.Int32Ty->getPointerTo());
Offset =
CGF.Builder.CreateAlignedLoad(OffsetPtr, CharUnits::fromQuantity(4));
} else {
llvm::Type *PtrDiffTy =
CGF.ConvertType(CGF.getContext().getPointerDiffType());
OffsetPtr =
CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
// Load the adjustment offset from the vtable.
Offset = CGF.Builder.CreateAlignedLoad(OffsetPtr, CGF.getPointerAlign());
}
// Adjust our pointer.
ResultPtr = CGF.Builder.CreateInBoundsGEP(V.getPointer(), Offset);
} else {
ResultPtr = V.getPointer();
}
// In a derived-to-base conversion, the non-virtual adjustment is
// applied second.
if (NonVirtualAdjustment && IsReturnAdjustment) {
ResultPtr = CGF.Builder.CreateConstInBoundsGEP1_64(ResultPtr,
NonVirtualAdjustment);
}
// Cast back to the original type.
return CGF.Builder.CreateBitCast(ResultPtr, InitialPtr.getType());
}
llvm::Value *ItaniumCXXABI::performThisAdjustment(CodeGenFunction &CGF,
Address This,
const ThisAdjustment &TA) {
return performTypeAdjustment(CGF, This, TA.NonVirtual,
TA.Virtual.Itanium.VCallOffsetOffset,
/*IsReturnAdjustment=*/false);
}
llvm::Value *
ItaniumCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
const ReturnAdjustment &RA) {
return performTypeAdjustment(CGF, Ret, RA.NonVirtual,
RA.Virtual.Itanium.VBaseOffsetOffset,
/*IsReturnAdjustment=*/true);
}
void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
RValue RV, QualType ResultType) {
if (!isa<CXXDestructorDecl>(CGF.CurGD.getDecl()))
return ItaniumCXXABI::EmitReturnFromThunk(CGF, RV, ResultType);
// Destructor thunks in the ARM ABI have indeterminate results.
llvm::Type *T = CGF.ReturnValue.getElementType();
RValue Undef = RValue::get(llvm::UndefValue::get(T));
return ItaniumCXXABI::EmitReturnFromThunk(CGF, Undef, ResultType);
}
/************************** Array allocation cookies **************************/
CharUnits ItaniumCXXABI::getArrayCookieSizeImpl(QualType elementType) {
// The array cookie is a size_t; pad that up to the element alignment.
// The cookie is actually right-justified in that space.
return std::max(CharUnits::fromQuantity(CGM.SizeSizeInBytes),
CGM.getContext().getTypeAlignInChars(elementType));
}
Address ItaniumCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
Address NewPtr,
llvm::Value *NumElements,
const CXXNewExpr *expr,
QualType ElementType) {
assert(requiresArrayCookie(expr));
unsigned AS = NewPtr.getAddressSpace();
ASTContext &Ctx = getContext();
CharUnits SizeSize = CGF.getSizeSize();
// The size of the cookie.
CharUnits CookieSize =
std::max(SizeSize, Ctx.getTypeAlignInChars(ElementType));
assert(CookieSize == getArrayCookieSizeImpl(ElementType));
// Compute an offset to the cookie.
Address CookiePtr = NewPtr;
CharUnits CookieOffset = CookieSize - SizeSize;
if (!CookieOffset.isZero())
CookiePtr = CGF.Builder.CreateConstInBoundsByteGEP(CookiePtr, CookieOffset);
// Write the number of elements into the appropriate slot.
Address NumElementsPtr =
CGF.Builder.CreateElementBitCast(CookiePtr, CGF.SizeTy);
llvm::Instruction *SI = CGF.Builder.CreateStore(NumElements, NumElementsPtr);
// Handle the array cookie specially in ASan.
if (CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) && AS == 0 &&
(expr->getOperatorNew()->isReplaceableGlobalAllocationFunction() ||
CGM.getCodeGenOpts().SanitizeAddressPoisonCustomArrayCookie)) {
// The store to the CookiePtr does not need to be instrumented.
CGM.getSanitizerMetadata()->disableSanitizerForInstruction(SI);
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, NumElementsPtr.getType(), false);
llvm::FunctionCallee F =
CGM.CreateRuntimeFunction(FTy, "__asan_poison_cxx_array_cookie");
CGF.Builder.CreateCall(F, NumElementsPtr.getPointer());
}
// Finally, compute a pointer to the actual data buffer by skipping
// over the cookie completely.
return CGF.Builder.CreateConstInBoundsByteGEP(NewPtr, CookieSize);
}
llvm::Value *ItaniumCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
Address allocPtr,
CharUnits cookieSize) {
// The element size is right-justified in the cookie.
Address numElementsPtr = allocPtr;
CharUnits numElementsOffset = cookieSize - CGF.getSizeSize();
if (!numElementsOffset.isZero())
numElementsPtr =
CGF.Builder.CreateConstInBoundsByteGEP(numElementsPtr, numElementsOffset);
unsigned AS = allocPtr.getAddressSpace();
numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
if (!CGM.getLangOpts().Sanitize.has(SanitizerKind::Address) || AS != 0)
return CGF.Builder.CreateLoad(numElementsPtr);
// In asan mode emit a function call instead of a regular load and let the
// run-time deal with it: if the shadow is properly poisoned return the
// cookie, otherwise return 0 to avoid an infinite loop calling DTORs.
// We can't simply ignore this load using nosanitize metadata because
// the metadata may be lost.
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGF.SizeTy, CGF.SizeTy->getPointerTo(0), false);
llvm::FunctionCallee F =
CGM.CreateRuntimeFunction(FTy, "__asan_load_cxx_array_cookie");
return CGF.Builder.CreateCall(F, numElementsPtr.getPointer());
}
CharUnits ARMCXXABI::getArrayCookieSizeImpl(QualType elementType) {
// ARM says that the cookie is always:
// struct array_cookie {
// std::size_t element_size; // element_size != 0
// std::size_t element_count;
// };
// But the base ABI doesn't give anything an alignment greater than
// 8, so we can dismiss this as typical ABI-author blindness to
// actual language complexity and round up to the element alignment.
return std::max(CharUnits::fromQuantity(2 * CGM.SizeSizeInBytes),
CGM.getContext().getTypeAlignInChars(elementType));
}
Address ARMCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
Address newPtr,
llvm::Value *numElements,
const CXXNewExpr *expr,
QualType elementType) {
assert(requiresArrayCookie(expr));
// The cookie is always at the start of the buffer.
Address cookie = newPtr;
// The first element is the element size.
cookie = CGF.Builder.CreateElementBitCast(cookie, CGF.SizeTy);
llvm::Value *elementSize = llvm::ConstantInt::get(CGF.SizeTy,
getContext().getTypeSizeInChars(elementType).getQuantity());
CGF.Builder.CreateStore(elementSize, cookie);
// The second element is the element count.
cookie = CGF.Builder.CreateConstInBoundsGEP(cookie, 1);
CGF.Builder.CreateStore(numElements, cookie);
// Finally, compute a pointer to the actual data buffer by skipping
// over the cookie completely.
CharUnits cookieSize = ARMCXXABI::getArrayCookieSizeImpl(elementType);
return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
}
llvm::Value *ARMCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
Address allocPtr,
CharUnits cookieSize) {
// The number of elements is at offset sizeof(size_t) relative to
// the allocated pointer.
Address numElementsPtr
= CGF.Builder.CreateConstInBoundsByteGEP(allocPtr, CGF.getSizeSize());
numElementsPtr = CGF.Builder.CreateElementBitCast(numElementsPtr, CGF.SizeTy);
return CGF.Builder.CreateLoad(numElementsPtr);
}
/*********************** Static local initialization **************************/
static llvm::FunctionCallee getGuardAcquireFn(CodeGenModule &CGM,
llvm::PointerType *GuardPtrTy) {
// int __cxa_guard_acquire(__guard *guard_object);
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().IntTy),
GuardPtrTy, /*isVarArg=*/false);
return CGM.CreateRuntimeFunction(
FTy, "__cxa_guard_acquire",
llvm::AttributeList::get(CGM.getLLVMContext(),
llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind));
}
static llvm::FunctionCallee getGuardReleaseFn(CodeGenModule &CGM,
llvm::PointerType *GuardPtrTy) {
// void __cxa_guard_release(__guard *guard_object);
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
return CGM.CreateRuntimeFunction(
FTy, "__cxa_guard_release",
llvm::AttributeList::get(CGM.getLLVMContext(),
llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind));
}
static llvm::FunctionCallee getGuardAbortFn(CodeGenModule &CGM,
llvm::PointerType *GuardPtrTy) {
// void __cxa_guard_abort(__guard *guard_object);
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=*/false);
return CGM.CreateRuntimeFunction(
FTy, "__cxa_guard_abort",
llvm::AttributeList::get(CGM.getLLVMContext(),
llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind));
}
namespace {
struct CallGuardAbort final : EHScopeStack::Cleanup {
llvm::GlobalVariable *Guard;
CallGuardAbort(llvm::GlobalVariable *Guard) : Guard(Guard) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
CGF.EmitNounwindRuntimeCall(getGuardAbortFn(CGF.CGM, Guard->getType()),
Guard);
}
};
}
/// The ARM code here follows the Itanium code closely enough that we
/// just special-case it at particular places.
void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
const VarDecl &D,
llvm::GlobalVariable *var,
bool shouldPerformInit) {
CGBuilderTy &Builder = CGF.Builder;
// Inline variables that weren't instantiated from variable templates have
// partially-ordered initialization within their translation unit.
bool NonTemplateInline =
D.isInline() &&
!isTemplateInstantiation(D.getTemplateSpecializationKind());
// We only need to use thread-safe statics for local non-TLS variables and
// inline variables; other global initialization is always single-threaded
// or (through lazy dynamic loading in multiple threads) unsequenced.
bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
(D.isLocalVarDecl() || NonTemplateInline) &&
!D.getTLSKind();
// If we have a global variable with internal linkage and thread-safe statics
// are disabled, we can just let the guard variable be of type i8.
bool useInt8GuardVariable = !threadsafe && var->hasInternalLinkage();
llvm::IntegerType *guardTy;
CharUnits guardAlignment;
if (useInt8GuardVariable) {
guardTy = CGF.Int8Ty;
guardAlignment = CharUnits::One();
} else {
// Guard variables are 64 bits in the generic ABI and size width on ARM
// (i.e. 32-bit on AArch32, 64-bit on AArch64).
if (UseARMGuardVarABI) {
guardTy = CGF.SizeTy;
guardAlignment = CGF.getSizeAlign();
} else {
guardTy = CGF.Int64Ty;
guardAlignment = CharUnits::fromQuantity(
CGM.getDataLayout().getABITypeAlignment(guardTy));
}
}
llvm::PointerType *guardPtrTy = guardTy->getPointerTo();
// Create the guard variable if we don't already have it (as we
// might if we're double-emitting this function body).
llvm::GlobalVariable *guard = CGM.getStaticLocalDeclGuardAddress(&D);
if (!guard) {
// Mangle the name for the guard.
SmallString<256> guardName;
{
llvm::raw_svector_ostream out(guardName);
getMangleContext().mangleStaticGuardVariable(&D, out);
}
// Create the guard variable with a zero-initializer.
// Just absorb linkage and visibility from the guarded variable.
guard = new llvm::GlobalVariable(CGM.getModule(), guardTy,
false, var->getLinkage(),
llvm::ConstantInt::get(guardTy, 0),
guardName.str());
guard->setDSOLocal(var->isDSOLocal());
guard->setVisibility(var->getVisibility());
// If the variable is thread-local, so is its guard variable.
guard->setThreadLocalMode(var->getThreadLocalMode());
guard->setAlignment(guardAlignment.getAsAlign());
// The ABI says: "It is suggested that it be emitted in the same COMDAT
// group as the associated data object." In practice, this doesn't work for
// non-ELF and non-Wasm object formats, so only do it for ELF and Wasm.
llvm::Comdat *C = var->getComdat();
if (!D.isLocalVarDecl() && C &&
(CGM.getTarget().getTriple().isOSBinFormatELF() ||
CGM.getTarget().getTriple().isOSBinFormatWasm())) {
guard->setComdat(C);
// An inline variable's guard function is run from the per-TU
// initialization function, not via a dedicated global ctor function, so
// we can't put it in a comdat.
if (!NonTemplateInline)
CGF.CurFn->setComdat(C);
} else if (CGM.supportsCOMDAT() && guard->isWeakForLinker()) {
guard->setComdat(CGM.getModule().getOrInsertComdat(guard->getName()));
}
CGM.setStaticLocalDeclGuardAddress(&D, guard);
}
Address guardAddr = Address(guard, guardAlignment);
// Test whether the variable has completed initialization.
//
// Itanium C++ ABI 3.3.2:
// The following is pseudo-code showing how these functions can be used:
// if (obj_guard.first_byte == 0) {
// if ( __cxa_guard_acquire (&obj_guard) ) {
// try {
// ... initialize the object ...;
// } catch (...) {
// __cxa_guard_abort (&obj_guard);
// throw;
// }
// ... queue object destructor with __cxa_atexit() ...;
// __cxa_guard_release (&obj_guard);
// }
// }
// Load the first byte of the guard variable.
llvm::LoadInst *LI =
Builder.CreateLoad(Builder.CreateElementBitCast(guardAddr, CGM.Int8Ty));
// Itanium ABI:
// An implementation supporting thread-safety on multiprocessor
// systems must also guarantee that references to the initialized
// object do not occur before the load of the initialization flag.
//
// In LLVM, we do this by marking the load Acquire.
if (threadsafe)
LI->setAtomic(llvm::AtomicOrdering::Acquire);
// For ARM, we should only check the first bit, rather than the entire byte:
//
// ARM C++ ABI 3.2.3.1:
// To support the potential use of initialization guard variables
// as semaphores that are the target of ARM SWP and LDREX/STREX
// synchronizing instructions we define a static initialization
// guard variable to be a 4-byte aligned, 4-byte word with the
// following inline access protocol.
// #define INITIALIZED 1
// if ((obj_guard & INITIALIZED) != INITIALIZED) {
// if (__cxa_guard_acquire(&obj_guard))
// ...
// }
//
// and similarly for ARM64:
//
// ARM64 C++ ABI 3.2.2:
// This ABI instead only specifies the value bit 0 of the static guard
// variable; all other bits are platform defined. Bit 0 shall be 0 when the
// variable is not initialized and 1 when it is.
llvm::Value *V =
(UseARMGuardVarABI && !useInt8GuardVariable)
? Builder.CreateAnd(LI, llvm::ConstantInt::get(CGM.Int8Ty, 1))
: LI;
llvm::Value *NeedsInit = Builder.CreateIsNull(V, "guard.uninitialized");
llvm::BasicBlock *InitCheckBlock = CGF.createBasicBlock("init.check");
llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
// Check if the first byte of the guard variable is zero.
CGF.EmitCXXGuardedInitBranch(NeedsInit, InitCheckBlock, EndBlock,
CodeGenFunction::GuardKind::VariableGuard, &D);
CGF.EmitBlock(InitCheckBlock);
// Variables used when coping with thread-safe statics and exceptions.
if (threadsafe) {
// Call __cxa_guard_acquire.
llvm::Value *V
= CGF.EmitNounwindRuntimeCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Builder.CreateCondBr(Builder.CreateIsNotNull(V, "tobool"),
InitBlock, EndBlock);
// Call __cxa_guard_abort along the exceptional edge.
CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
CGF.EmitBlock(InitBlock);
}
// Emit the initializer and add a global destructor if appropriate.
CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
if (threadsafe) {
// Pop the guard-abort cleanup if we pushed one.
CGF.PopCleanupBlock();
// Call __cxa_guard_release. This cannot throw.
CGF.EmitNounwindRuntimeCall(getGuardReleaseFn(CGM, guardPtrTy),
guardAddr.getPointer());
} else {
Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guardAddr);
}
CGF.EmitBlock(EndBlock);
}
/// Register a global destructor using __cxa_atexit.
static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
llvm::FunctionCallee dtor,
llvm::Constant *addr, bool TLS) {
assert((TLS || CGF.getTypes().getCodeGenOpts().CXAAtExit) &&
"__cxa_atexit is disabled");
const char *Name = "__cxa_atexit";
if (TLS) {
const llvm::Triple &T = CGF.getTarget().getTriple();
Name = T.isOSDarwin() ? "_tlv_atexit" : "__cxa_thread_atexit";
}
// We're assuming that the destructor function is something we can
// reasonably call with the default CC. Go ahead and cast it to the
// right prototype.
llvm::Type *dtorTy =
llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerTo();
// Preserve address space of addr.
auto AddrAS = addr ? addr->getType()->getPointerAddressSpace() : 0;
auto AddrInt8PtrTy =
AddrAS ? CGF.Int8Ty->getPointerTo(AddrAS) : CGF.Int8PtrTy;
// Create a variable that binds the atexit to this shared object.
llvm::Constant *handle =
CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
auto *GV = cast<llvm::GlobalValue>(handle->stripPointerCasts());
GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
// extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
llvm::Type *paramTys[] = {dtorTy, AddrInt8PtrTy, handle->getType()};
llvm::FunctionType *atexitTy =
llvm::FunctionType::get(CGF.IntTy, paramTys, false);
// Fetch the actual function.
llvm::FunctionCallee atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit.getCallee()))
fn->setDoesNotThrow();
if (!addr)
// addr is null when we are trying to register a dtor annotated with
// __attribute__((destructor)) in a constructor function. Using null here is
// okay because this argument is just passed back to the destructor
// function.
addr = llvm::Constant::getNullValue(CGF.Int8PtrTy);
llvm::Value *args[] = {llvm::ConstantExpr::getBitCast(
cast<llvm::Constant>(dtor.getCallee()), dtorTy),
llvm::ConstantExpr::getBitCast(addr, AddrInt8PtrTy),
handle};
CGF.EmitNounwindRuntimeCall(atexit, args);
}
void CodeGenModule::registerGlobalDtorsWithAtExit() {
for (const auto &I : DtorsUsingAtExit) {
int Priority = I.first;
const llvm::TinyPtrVector<llvm::Function *> &Dtors = I.second;
// Create a function that registers destructors that have the same priority.
//
// Since constructor functions are run in non-descending order of their
// priorities, destructors are registered in non-descending order of their
// priorities, and since destructor functions are run in the reverse order
// of their registration, destructor functions are run in non-ascending
// order of their priorities.
CodeGenFunction CGF(*this);
std::string GlobalInitFnName =
std::string("__GLOBAL_init_") + llvm::to_string(Priority);
llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
llvm::Function *GlobalInitFn = CreateGlobalInitOrCleanUpFunction(
FTy, GlobalInitFnName, getTypes().arrangeNullaryFunction(),
SourceLocation());
ASTContext &Ctx = getContext();
QualType ReturnTy = Ctx.VoidTy;
QualType FunctionTy = Ctx.getFunctionType(ReturnTy, llvm::None, {});
FunctionDecl *FD = FunctionDecl::Create(
Ctx, Ctx.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
&Ctx.Idents.get(GlobalInitFnName), FunctionTy, nullptr, SC_Static,
false, false);
CGF.StartFunction(GlobalDecl(FD), ReturnTy, GlobalInitFn,
getTypes().arrangeNullaryFunction(), FunctionArgList(),
SourceLocation(), SourceLocation());
for (auto *Dtor : Dtors) {
// Register the destructor function calling __cxa_atexit if it is
// available. Otherwise fall back on calling atexit.
if (getCodeGenOpts().CXAAtExit)
emitGlobalDtorWithCXAAtExit(CGF, Dtor, nullptr, false);
else
CGF.registerGlobalDtorWithAtExit(Dtor);
}
CGF.FinishFunction();
AddGlobalCtor(GlobalInitFn, Priority, nullptr);
}
}
/// Register a global destructor as best as we know how.
void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
llvm::FunctionCallee dtor,
llvm::Constant *addr) {
if (D.isNoDestroy(CGM.getContext()))
return;
// emitGlobalDtorWithCXAAtExit will emit a call to either __cxa_thread_atexit
// or __cxa_atexit depending on whether this VarDecl is a thread-local storage
// or not. CXAAtExit controls only __cxa_atexit, so use it if it is enabled.
// We can always use __cxa_thread_atexit.
if (CGM.getCodeGenOpts().CXAAtExit || D.getTLSKind())
return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
// In Apple kexts, we want to add a global destructor entry.
// FIXME: shouldn't this be guarded by some variable?
if (CGM.getLangOpts().AppleKext) {
// Generate a global destructor entry.
return CGM.AddCXXDtorEntry(dtor, addr);
}
CGF.registerGlobalDtorWithAtExit(D, dtor, addr);
}
static bool isThreadWrapperReplaceable(const VarDecl *VD,
CodeGen::CodeGenModule &CGM) {
assert(!VD->isStaticLocal() && "static local VarDecls don't need wrappers!");
// Darwin prefers to have references to thread local variables to go through
// the thread wrapper instead of directly referencing the backing variable.
return VD->getTLSKind() == VarDecl::TLS_Dynamic &&
CGM.getTarget().getTriple().isOSDarwin();
}
/// Get the appropriate linkage for the wrapper function. This is essentially
/// the weak form of the variable's linkage; every translation unit which needs
/// the wrapper emits a copy, and we want the linker to merge them.
static llvm::GlobalValue::LinkageTypes
getThreadLocalWrapperLinkage(const VarDecl *VD, CodeGen::CodeGenModule &CGM) {
llvm::GlobalValue::LinkageTypes VarLinkage =
CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
// For internal linkage variables, we don't need an external or weak wrapper.
if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
return VarLinkage;
// If the thread wrapper is replaceable, give it appropriate linkage.
if (isThreadWrapperReplaceable(VD, CGM))
if (!llvm::GlobalVariable::isLinkOnceLinkage(VarLinkage) &&
!llvm::GlobalVariable::isWeakODRLinkage(VarLinkage))
return VarLinkage;
return llvm::GlobalValue::WeakODRLinkage;
}
llvm::Function *
ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
llvm::Value *Val) {
// Mangle the name for the thread_local wrapper function.
SmallString<256> WrapperName;
{
llvm::raw_svector_ostream Out(WrapperName);
getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
}
// FIXME: If VD is a definition, we should regenerate the function attributes
// before returning.
if (llvm::Value *V = CGM.getModule().getNamedValue(WrapperName))
return cast<llvm::Function>(V);
QualType RetQT = VD->getType();
if (RetQT->isReferenceType())
RetQT = RetQT.getNonReferenceType();
const CGFunctionInfo &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
getContext().getPointerType(RetQT), FunctionArgList());
llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *Wrapper =
llvm::Function::Create(FnTy, getThreadLocalWrapperLinkage(VD, CGM),
WrapperName.str(), &CGM.getModule());
if (CGM.supportsCOMDAT() && Wrapper->isWeakForLinker())
Wrapper->setComdat(CGM.getModule().getOrInsertComdat(Wrapper->getName()));
CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Wrapper);
// Always resolve references to the wrapper at link time.
if (!Wrapper->hasLocalLinkage())
if (!isThreadWrapperReplaceable(VD, CGM) ||
llvm::GlobalVariable::isLinkOnceLinkage(Wrapper->getLinkage()) ||
llvm::GlobalVariable::isWeakODRLinkage(Wrapper->getLinkage()) ||
VD->getVisibility() == HiddenVisibility)
Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
if (isThreadWrapperReplaceable(VD, CGM)) {
Wrapper->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
Wrapper->addFnAttr(llvm::Attribute::NoUnwind);
}
ThreadWrappers.push_back({VD, Wrapper});
return Wrapper;
}
void ItaniumCXXABI::EmitThreadLocalInitFuncs(
CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
ArrayRef<llvm::Function *> CXXThreadLocalInits,
ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
llvm::Function *InitFunc = nullptr;
// Separate initializers into those with ordered (or partially-ordered)
// initialization and those with unordered initialization.
llvm::SmallVector<llvm::Function *, 8> OrderedInits;
llvm::SmallDenseMap<const VarDecl *, llvm::Function *> UnorderedInits;
for (unsigned I = 0; I != CXXThreadLocalInits.size(); ++I) {
if (isTemplateInstantiation(
CXXThreadLocalInitVars[I]->getTemplateSpecializationKind()))
UnorderedInits[CXXThreadLocalInitVars[I]->getCanonicalDecl()] =
CXXThreadLocalInits[I];
else
OrderedInits.push_back(CXXThreadLocalInits[I]);
}
if (!OrderedInits.empty()) {
// Generate a guarded initialization function.
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(FTy, "__tls_init", FI,
SourceLocation(),
/*TLS=*/true);
llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
llvm::GlobalVariable::InternalLinkage,
llvm::ConstantInt::get(CGM.Int8Ty, 0), "__tls_guard");
Guard->setThreadLocal(true);
Guard->setThreadLocalMode(CGM.GetDefaultLLVMTLSModel());
CharUnits GuardAlign = CharUnits::One();
Guard->setAlignment(GuardAlign.getAsAlign());
CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(
InitFunc, OrderedInits, ConstantAddress(Guard, GuardAlign));
// On Darwin platforms, use CXX_FAST_TLS calling convention.
if (CGM.getTarget().getTriple().isOSDarwin()) {
InitFunc->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
InitFunc->addFnAttr(llvm::Attribute::NoUnwind);
}
}
// Create declarations for thread wrappers for all thread-local variables
// with non-discardable definitions in this translation unit.
for (const VarDecl *VD : CXXThreadLocals) {
if (VD->hasDefinition() &&
!isDiscardableGVALinkage(getContext().GetGVALinkageForVariable(VD))) {
llvm::GlobalValue *GV = CGM.GetGlobalValue(CGM.getMangledName(VD));
getOrCreateThreadLocalWrapper(VD, GV);
}
}
// Emit all referenced thread wrappers.
for (auto VDAndWrapper : ThreadWrappers) {
const VarDecl *VD = VDAndWrapper.first;
llvm::GlobalVariable *Var =
cast<llvm::GlobalVariable>(CGM.GetGlobalValue(CGM.getMangledName(VD)));
llvm::Function *Wrapper = VDAndWrapper.second;
// Some targets require that all access to thread local variables go through
// the thread wrapper. This means that we cannot attempt to create a thread
// wrapper or a thread helper.
if (!VD->hasDefinition()) {
if (isThreadWrapperReplaceable(VD, CGM)) {
Wrapper->setLinkage(llvm::Function::ExternalLinkage);
continue;
}
// If this isn't a TU in which this variable is defined, the thread
// wrapper is discardable.
if (Wrapper->getLinkage() == llvm::Function::WeakODRLinkage)
Wrapper->setLinkage(llvm::Function::LinkOnceODRLinkage);
}
CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Wrapper);
// Mangle the name for the thread_local initialization function.
SmallString<256> InitFnName;
{
llvm::raw_svector_ostream Out(InitFnName);
getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
}
llvm::FunctionType *InitFnTy = llvm::FunctionType::get(CGM.VoidTy, false);
// If we have a definition for the variable, emit the initialization
// function as an alias to the global Init function (if any). Otherwise,
// produce a declaration of the initialization function.
llvm::GlobalValue *Init = nullptr;
bool InitIsInitFunc = false;
bool HasConstantInitialization = false;
if (!usesThreadWrapperFunction(VD)) {
HasConstantInitialization = true;
} else if (VD->hasDefinition()) {
InitIsInitFunc = true;
llvm::Function *InitFuncToUse = InitFunc;
if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
InitFuncToUse = UnorderedInits.lookup(VD->getCanonicalDecl());
if (InitFuncToUse)
Init = llvm::GlobalAlias::create(Var->getLinkage(), InitFnName.str(),
InitFuncToUse);
} else {
// Emit a weak global function referring to the initialization function.
// This function will not exist if the TU defining the thread_local
// variable in question does not need any dynamic initialization for
// its thread_local variables.
Init = llvm::Function::Create(InitFnTy,
llvm::GlobalVariable::ExternalWeakLinkage,
InitFnName.str(), &CGM.getModule());
const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI,
cast<llvm::Function>(Init));
}
if (Init) {
Init->setVisibility(Var->getVisibility());
// Don't mark an extern_weak function DSO local on windows.
if (!CGM.getTriple().isOSWindows() || !Init->hasExternalWeakLinkage())
Init->setDSOLocal(Var->isDSOLocal());
}
llvm::LLVMContext &Context = CGM.getModule().getContext();
llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
CGBuilderTy Builder(CGM, Entry);
if (HasConstantInitialization) {
// No dynamic initialization to invoke.
} else if (InitIsInitFunc) {
if (Init) {
llvm::CallInst *CallVal = Builder.CreateCall(InitFnTy, Init);
if (isThreadWrapperReplaceable(VD, CGM)) {
CallVal->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
llvm::Function *Fn =
cast<llvm::Function>(cast<llvm::GlobalAlias>(Init)->getAliasee());
Fn->setCallingConv(llvm::CallingConv::CXX_FAST_TLS);
}
}
} else {
// Don't know whether we have an init function. Call it if it exists.
llvm::Value *Have = Builder.CreateIsNotNull(Init);
llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
Builder.CreateCondBr(Have, InitBB, ExitBB);
Builder.SetInsertPoint(InitBB);
Builder.CreateCall(InitFnTy, Init);
Builder.CreateBr(ExitBB);
Builder.SetInsertPoint(ExitBB);
}
// For a reference, the result of the wrapper function is a pointer to
// the referenced object.
llvm::Value *Val = Var;
if (VD->getType()->isReferenceType()) {
CharUnits Align = CGM.getContext().getDeclAlign(VD);
Val = Builder.CreateAlignedLoad(Val, Align);
}
if (Val->getType() != Wrapper->getReturnType())
Val = Builder.CreatePointerBitCastOrAddrSpaceCast(
Val, Wrapper->getReturnType(), "");
Builder.CreateRet(Val);
}
}
LValue ItaniumCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
const VarDecl *VD,
QualType LValType) {
llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD);
llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Val);
llvm::CallInst *CallVal = CGF.Builder.CreateCall(Wrapper);
CallVal->setCallingConv(Wrapper->getCallingConv());
LValue LV;
if (VD->getType()->isReferenceType())
LV = CGF.MakeNaturalAlignAddrLValue(CallVal, LValType);
else
LV = CGF.MakeAddrLValue(CallVal, LValType,
CGF.getContext().getDeclAlign(VD));
// FIXME: need setObjCGCLValueClass?
return LV;
}
/// Return whether the given global decl needs a VTT parameter, which it does
/// if it's a base constructor or destructor with virtual bases.
bool ItaniumCXXABI::NeedsVTTParameter(GlobalDecl GD) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
// We don't have any virtual bases, just return early.
if (!MD->getParent()->getNumVBases())
return false;
// Check if we have a base constructor.
if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base)
return true;
// Check if we have a base destructor.
if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
return true;
return false;
}
namespace {
class ItaniumRTTIBuilder {
CodeGenModule &CGM; // Per-module state.
llvm::LLVMContext &VMContext;
const ItaniumCXXABI &CXXABI; // Per-module state.
/// Fields - The fields of the RTTI descriptor currently being built.
SmallVector<llvm::Constant *, 16> Fields;
/// GetAddrOfTypeName - Returns the mangled type name of the given type.
llvm::GlobalVariable *
GetAddrOfTypeName(QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage);
/// GetAddrOfExternalRTTIDescriptor - Returns the constant for the RTTI
/// descriptor of the given type.
llvm::Constant *GetAddrOfExternalRTTIDescriptor(QualType Ty);
/// BuildVTablePointer - Build the vtable pointer for the given type.
void BuildVTablePointer(const Type *Ty);
/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
/// inheritance, according to the Itanium C++ ABI, 2.9.5p6b.
void BuildSIClassTypeInfo(const CXXRecordDecl *RD);
/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
/// classes with bases that do not satisfy the abi::__si_class_type_info
/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
void BuildVMIClassTypeInfo(const CXXRecordDecl *RD);
/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct, used
/// for pointer types.
void BuildPointerTypeInfo(QualType PointeeTy);
/// BuildObjCObjectTypeInfo - Build the appropriate kind of
/// type_info for an object type.
void BuildObjCObjectTypeInfo(const ObjCObjectType *Ty);
/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
/// struct, used for member pointer types.
void BuildPointerToMemberTypeInfo(const MemberPointerType *Ty);
public:
ItaniumRTTIBuilder(const ItaniumCXXABI &ABI)
: CGM(ABI.CGM), VMContext(CGM.getModule().getContext()), CXXABI(ABI) {}
// Pointer type info flags.
enum {
/// PTI_Const - Type has const qualifier.
PTI_Const = 0x1,
/// PTI_Volatile - Type has volatile qualifier.
PTI_Volatile = 0x2,
/// PTI_Restrict - Type has restrict qualifier.
PTI_Restrict = 0x4,
/// PTI_Incomplete - Type is incomplete.
PTI_Incomplete = 0x8,
/// PTI_ContainingClassIncomplete - Containing class is incomplete.
/// (in pointer to member).
PTI_ContainingClassIncomplete = 0x10,
/// PTI_TransactionSafe - Pointee is transaction_safe function (C++ TM TS).
//PTI_TransactionSafe = 0x20,
/// PTI_Noexcept - Pointee is noexcept function (C++1z).
PTI_Noexcept = 0x40,
};
// VMI type info flags.
enum {
/// VMI_NonDiamondRepeat - Class has non-diamond repeated inheritance.
VMI_NonDiamondRepeat = 0x1,
/// VMI_DiamondShaped - Class is diamond shaped.
VMI_DiamondShaped = 0x2
};
// Base class type info flags.
enum {
/// BCTI_Virtual - Base class is virtual.
BCTI_Virtual = 0x1,
/// BCTI_Public - Base class is public.
BCTI_Public = 0x2
};
/// BuildTypeInfo - Build the RTTI type info struct for the given type, or
/// link to an existing RTTI descriptor if one already exists.
llvm::Constant *BuildTypeInfo(QualType Ty);
/// BuildTypeInfo - Build the RTTI type info struct for the given type.
llvm::Constant *BuildTypeInfo(
QualType Ty,
llvm::GlobalVariable::LinkageTypes Linkage,
llvm::GlobalValue::VisibilityTypes Visibility,
llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass);
};
}
llvm::GlobalVariable *ItaniumRTTIBuilder::GetAddrOfTypeName(
QualType Ty, llvm::GlobalVariable::LinkageTypes Linkage) {
SmallString<256> Name;
llvm::raw_svector_ostream Out(Name);
CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
// We know that the mangled name of the type starts at index 4 of the
// mangled name of the typename, so we can just index into it in order to
// get the mangled name of the type.
llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
Name.substr(4));
auto Align = CGM.getContext().getTypeAlignInChars(CGM.getContext().CharTy);
llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
Name, Init->getType(), Linkage, Align.getQuantity());
GV->setInitializer(Init);
return GV;
}
llvm::Constant *
ItaniumRTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
// Mangle the RTTI name.
SmallString<256> Name;
llvm::raw_svector_ostream Out(Name);
CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
// Look for an existing global.
llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name);
if (!GV) {
// Create a new global variable.
// Note for the future: If we would ever like to do deferred emission of
// RTTI, check if emitting vtables opportunistically need any adjustment.
GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
/*isConstant=*/true,
llvm::GlobalValue::ExternalLinkage, nullptr,
Name);
const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
CGM.setGVProperties(GV, RD);
}
return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
}
/// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether the type
/// info for that type is defined in the standard library.
static bool TypeInfoIsInStandardLibrary(const BuiltinType *Ty) {
// Itanium C++ ABI 2.9.2:
// Basic type information (e.g. for "int", "bool", etc.) will be kept in
// the run-time support library. Specifically, the run-time support
// library should contain type_info objects for the types X, X* and
// X const*, for every X in: void, std::nullptr_t, bool, wchar_t, char,
// unsigned char, signed char, short, unsigned short, int, unsigned int,
// long, unsigned long, long long, unsigned long long, float, double,
// long double, char16_t, char32_t, and the IEEE 754r decimal and
// half-precision floating point types.
//
// GCC also emits RTTI for __int128.
// FIXME: We do not emit RTTI information for decimal types here.
// Types added here must also be added to EmitFundamentalRTTIDescriptors.
switch (Ty->getKind()) {
case BuiltinType::Void:
case BuiltinType::NullPtr:
case BuiltinType::Bool:
case BuiltinType::WChar_S:
case BuiltinType::WChar_U:
case BuiltinType::Char_U:
case BuiltinType::Char_S:
case BuiltinType::UChar:
case BuiltinType::SChar:
case BuiltinType::Short:
case BuiltinType::UShort:
case BuiltinType::Int:
case BuiltinType::UInt:
case BuiltinType::Long:
case BuiltinType::ULong:
case BuiltinType::LongLong:
case BuiltinType::ULongLong:
case BuiltinType::Half:
case BuiltinType::Float:
case BuiltinType::Double:
case BuiltinType::LongDouble:
case BuiltinType::Float16:
case BuiltinType::Float128:
case BuiltinType::Char8:
case BuiltinType::Char16:
case BuiltinType::Char32:
case BuiltinType::Int128:
case BuiltinType::UInt128:
return true;
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
case BuiltinType::Id:
#include "clang/Basic/OpenCLImageTypes.def"
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
case BuiltinType::Id:
#include "clang/Basic/OpenCLExtensionTypes.def"
case BuiltinType::OCLSampler:
case BuiltinType::OCLEvent:
case BuiltinType::OCLClkEvent:
case BuiltinType::OCLQueue:
case BuiltinType::OCLReserveID:
#define SVE_TYPE(Name, Id, SingletonId) \
case BuiltinType::Id:
#include "clang/Basic/AArch64SVEACLETypes.def"
case BuiltinType::ShortAccum:
case BuiltinType::Accum:
case BuiltinType::LongAccum:
case BuiltinType::UShortAccum:
case BuiltinType::UAccum:
case BuiltinType::ULongAccum:
case BuiltinType::ShortFract:
case BuiltinType::Fract:
case BuiltinType::LongFract:
case BuiltinType::UShortFract:
case BuiltinType::UFract:
case BuiltinType::ULongFract:
case BuiltinType::SatShortAccum:
case BuiltinType::SatAccum:
case BuiltinType::SatLongAccum:
case BuiltinType::SatUShortAccum:
case BuiltinType::SatUAccum:
case BuiltinType::SatULongAccum:
case BuiltinType::SatShortFract:
case BuiltinType::SatFract:
case BuiltinType::SatLongFract:
case BuiltinType::SatUShortFract:
case BuiltinType::SatUFract:
case BuiltinType::SatULongFract:
case BuiltinType::BFloat16:
return false;
case BuiltinType::Dependent:
#define BUILTIN_TYPE(Id, SingletonId)
#define PLACEHOLDER_TYPE(Id, SingletonId) \
case BuiltinType::Id:
#include "clang/AST/BuiltinTypes.def"
llvm_unreachable("asking for RRTI for a placeholder type!");
case BuiltinType::ObjCId:
case BuiltinType::ObjCClass:
case BuiltinType::ObjCSel:
llvm_unreachable("FIXME: Objective-C types are unsupported!");
}
llvm_unreachable("Invalid BuiltinType Kind!");
}
static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
QualType PointeeTy = PointerTy->getPointeeType();
const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(PointeeTy);
if (!BuiltinTy)
return false;
// Check the qualifiers.
Qualifiers Quals = PointeeTy.getQualifiers();
Quals.removeConst();
if (!Quals.empty())
return false;
return TypeInfoIsInStandardLibrary(BuiltinTy);
}
/// IsStandardLibraryRTTIDescriptor - Returns whether the type
/// information for the given type exists in the standard library.
static bool IsStandardLibraryRTTIDescriptor(QualType Ty) {
// Type info for builtin types is defined in the standard library.
if (const BuiltinType *BuiltinTy = dyn_cast<BuiltinType>(Ty))
return TypeInfoIsInStandardLibrary(BuiltinTy);
// Type info for some pointer types to builtin types is defined in the
// standard library.
if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
return TypeInfoIsInStandardLibrary(PointerTy);
return false;
}
/// ShouldUseExternalRTTIDescriptor - Returns whether the type information for
/// the given type exists somewhere else, and that we should not emit the type
/// information in this translation unit. Assumes that it is not a
/// standard-library type.
static bool ShouldUseExternalRTTIDescriptor(CodeGenModule &CGM,
QualType Ty) {
ASTContext &Context = CGM.getContext();
// If RTTI is disabled, assume it might be disabled in the
// translation unit that defines any potential key function, too.
if (!Context.getLangOpts().RTTI) return false;
if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
const CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
if (!RD->hasDefinition())
return false;
if (!RD->isDynamicClass())
return false;
// FIXME: this may need to be reconsidered if the key function
// changes.
// N.B. We must always emit the RTTI data ourselves if there exists a key
// function.
bool IsDLLImport = RD->hasAttr<DLLImportAttr>();
// Don't import the RTTI but emit it locally.
if (CGM.getTriple().isWindowsGNUEnvironment())
return false;
if (CGM.getVTables().isVTableExternal(RD))
return IsDLLImport && !CGM.getTriple().isWindowsItaniumEnvironment()
? false
: true;
if (IsDLLImport)
return true;
}
return false;
}
/// IsIncompleteClassType - Returns whether the given record type is incomplete.
static bool IsIncompleteClassType(const RecordType *RecordTy) {
return !RecordTy->getDecl()->isCompleteDefinition();
}
/// ContainsIncompleteClassType - Returns whether the given type contains an
/// incomplete class type. This is true if
///
/// * The given type is an incomplete class type.
/// * The given type is a pointer type whose pointee type contains an
/// incomplete class type.
/// * The given type is a member pointer type whose class is an incomplete
/// class type.
/// * The given type is a member pointer type whoise pointee type contains an
/// incomplete class type.
/// is an indirect or direct pointer to an incomplete class type.
static bool ContainsIncompleteClassType(QualType Ty) {
if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
if (IsIncompleteClassType(RecordTy))
return true;
}
if (const PointerType *PointerTy = dyn_cast<PointerType>(Ty))
return ContainsIncompleteClassType(PointerTy->getPointeeType());
if (const MemberPointerType *MemberPointerTy =
dyn_cast<MemberPointerType>(Ty)) {
// Check if the class type is incomplete.
const RecordType *ClassType = cast<RecordType>(MemberPointerTy->getClass());
if (IsIncompleteClassType(ClassType))
return true;
return ContainsIncompleteClassType(MemberPointerTy->getPointeeType());
}
return false;
}
// CanUseSingleInheritance - Return whether the given record decl has a "single,
// public, non-virtual base at offset zero (i.e. the derived class is dynamic
// iff the base is)", according to Itanium C++ ABI, 2.95p6b.
static bool CanUseSingleInheritance(const CXXRecordDecl *RD) {
// Check the number of bases.
if (RD->getNumBases() != 1)
return false;
// Get the base.
CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin();
// Check that the base is not virtual.
if (Base->isVirtual())
return false;
// Check that the base is public.
if (Base->getAccessSpecifier() != AS_public)
return false;
// Check that the class is dynamic iff the base is.
auto *BaseDecl =
cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
if (!BaseDecl->isEmpty() &&
BaseDecl->isDynamicClass() != RD->isDynamicClass())
return false;
return true;
}
void ItaniumRTTIBuilder::BuildVTablePointer(const Type *Ty) {
// abi::__class_type_info.
static const char * const ClassTypeInfo =
"_ZTVN10__cxxabiv117__class_type_infoE";
// abi::__si_class_type_info.
static const char * const SIClassTypeInfo =
"_ZTVN10__cxxabiv120__si_class_type_infoE";
// abi::__vmi_class_type_info.
static const char * const VMIClassTypeInfo =
"_ZTVN10__cxxabiv121__vmi_class_type_infoE";
const char *VTableName = nullptr;
switch (Ty->getTypeClass()) {
#define TYPE(Class, Base)
#define ABSTRACT_TYPE(Class, Base)
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
#include "clang/AST/TypeNodes.inc"
llvm_unreachable("Non-canonical and dependent types shouldn't get here");
case Type::LValueReference:
case Type::RValueReference:
llvm_unreachable("References shouldn't get here");
case Type::Auto:
case Type::DeducedTemplateSpecialization:
llvm_unreachable("Undeduced type shouldn't get here");
case Type::Pipe:
llvm_unreachable("Pipe types shouldn't get here");
case Type::Builtin:
case Type::ExtInt:
// GCC treats vector and complex types as fundamental types.
case Type::Vector:
case Type::ExtVector:
case Type::ConstantMatrix:
case Type::Complex:
case Type::Atomic:
// FIXME: GCC treats block pointers as fundamental types?!
case Type::BlockPointer:
// abi::__fundamental_type_info.
VTableName = "_ZTVN10__cxxabiv123__fundamental_type_infoE";
break;
case Type::ConstantArray:
case Type::IncompleteArray:
case Type::VariableArray:
// abi::__array_type_info.
VTableName = "_ZTVN10__cxxabiv117__array_type_infoE";
break;
case Type::FunctionNoProto:
case Type::FunctionProto:
// abi::__function_type_info.
VTableName = "_ZTVN10__cxxabiv120__function_type_infoE";
break;
case Type::Enum:
// abi::__enum_type_info.
VTableName = "_ZTVN10__cxxabiv116__enum_type_infoE";
break;
case Type::Record: {
const CXXRecordDecl *RD =
cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
if (!RD->hasDefinition() || !RD->getNumBases()) {
VTableName = ClassTypeInfo;
} else if (CanUseSingleInheritance(RD)) {
VTableName = SIClassTypeInfo;
} else {
VTableName = VMIClassTypeInfo;
}
break;
}
case Type::ObjCObject:
// Ignore protocol qualifiers.
Ty = cast<ObjCObjectType>(Ty)->getBaseType().getTypePtr();
// Handle id and Class.
if (isa<BuiltinType>(Ty)) {
VTableName = ClassTypeInfo;
break;
}
assert(isa<ObjCInterfaceType>(Ty));
LLVM_FALLTHROUGH;
case Type::ObjCInterface:
if (cast<ObjCInterfaceType>(Ty)->getDecl()->getSuperClass()) {
VTableName = SIClassTypeInfo;
} else {
VTableName = ClassTypeInfo;
}
break;
case Type::ObjCObjectPointer:
case Type::Pointer:
// abi::__pointer_type_info.
VTableName = "_ZTVN10__cxxabiv119__pointer_type_infoE";
break;
case Type::MemberPointer:
// abi::__pointer_to_member_type_info.
VTableName = "_ZTVN10__cxxabiv129__pointer_to_member_type_infoE";
break;
}
llvm::Constant *VTable = nullptr;
// Check if the alias exists. If it doesn't, then get or create the global.
if (CGM.getItaniumVTableContext().isRelativeLayout())
VTable = CGM.getModule().getNamedAlias(VTableName);
if (!VTable)
VTable = CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
CGM.setDSOLocal(cast<llvm::GlobalValue>(VTable->stripPointerCasts()));
llvm::Type *PtrDiffTy =
CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
// The vtable address point is 2.
if (CGM.getItaniumVTableContext().isRelativeLayout()) {
// The vtable address point is 8 bytes after its start:
// 4 for the offset to top + 4 for the relative offset to rtti.
llvm::Constant *Eight = llvm::ConstantInt::get(CGM.Int32Ty, 8);
VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
VTable =
llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8Ty, VTable, Eight);
} else {
llvm::Constant *Two = llvm::ConstantInt::get(PtrDiffTy, 2);
VTable = llvm::ConstantExpr::getInBoundsGetElementPtr(CGM.Int8PtrTy, VTable,
Two);
}
VTable = llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
Fields.push_back(VTable);
}
/// Return the linkage that the type info and type info name constants
/// should have for the given type.
static llvm::GlobalVariable::LinkageTypes getTypeInfoLinkage(CodeGenModule &CGM,
QualType Ty) {
// Itanium C++ ABI 2.9.5p7:
// In addition, it and all of the intermediate abi::__pointer_type_info
// structs in the chain down to the abi::__class_type_info for the
// incomplete class type must be prevented from resolving to the
// corresponding type_info structs for the complete class type, possibly
// by making them local static objects. Finally, a dummy class RTTI is
// generated for the incomplete type that will not resolve to the final
// complete class RTTI (because the latter need not exist), possibly by
// making it a local static object.
if (ContainsIncompleteClassType(Ty))
return llvm::GlobalValue::InternalLinkage;
switch (Ty->getLinkage()) {
case NoLinkage:
case InternalLinkage:
case UniqueExternalLinkage:
return llvm::GlobalValue::InternalLinkage;
case VisibleNoLinkage:
case ModuleInternalLinkage:
case ModuleLinkage:
case ExternalLinkage:
// RTTI is not enabled, which means that this type info struct is going
// to be used for exception handling. Give it linkonce_odr linkage.
if (!CGM.getLangOpts().RTTI)
return llvm::GlobalValue::LinkOnceODRLinkage;
if (const RecordType *Record = dyn_cast<RecordType>(Ty)) {
const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
if (RD->hasAttr<WeakAttr>())
return llvm::GlobalValue::WeakODRLinkage;
if (CGM.getTriple().isWindowsItaniumEnvironment())
if (RD->hasAttr<DLLImportAttr>() &&
ShouldUseExternalRTTIDescriptor(CGM, Ty))
return llvm::GlobalValue::ExternalLinkage;
// MinGW always uses LinkOnceODRLinkage for type info.
if (RD->isDynamicClass() &&
!CGM.getContext()
.getTargetInfo()
.getTriple()
.isWindowsGNUEnvironment())
return CGM.getVTableLinkage(RD);
}
return llvm::GlobalValue::LinkOnceODRLinkage;
}
llvm_unreachable("Invalid linkage!");
}
llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(QualType Ty) {
// We want to operate on the canonical type.
Ty = Ty.getCanonicalType();
// Check if we've already emitted an RTTI descriptor for this type.
SmallString<256> Name;
llvm::raw_svector_ostream Out(Name);
CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
llvm::GlobalVariable *OldGV = CGM.getModule().getNamedGlobal(Name);
if (OldGV && !OldGV->isDeclaration()) {
assert(!OldGV->hasAvailableExternallyLinkage() &&
"available_externally typeinfos not yet implemented");
return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
}
// Check if there is already an external RTTI descriptor for this type.
if (IsStandardLibraryRTTIDescriptor(Ty) ||
ShouldUseExternalRTTIDescriptor(CGM, Ty))
return GetAddrOfExternalRTTIDescriptor(Ty);
// Emit the standard library with external linkage.
llvm::GlobalVariable::LinkageTypes Linkage = getTypeInfoLinkage(CGM, Ty);
// Give the type_info object and name the formal visibility of the
// type itself.
llvm::GlobalValue::VisibilityTypes llvmVisibility;
if (llvm::GlobalValue::isLocalLinkage(Linkage))
// If the linkage is local, only default visibility makes sense.
llvmVisibility = llvm::GlobalValue::DefaultVisibility;
else if (CXXABI.classifyRTTIUniqueness(Ty, Linkage) ==
ItaniumCXXABI::RUK_NonUniqueHidden)
llvmVisibility = llvm::GlobalValue::HiddenVisibility;
else
llvmVisibility = CodeGenModule::GetLLVMVisibility(Ty->getVisibility());
llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
llvm::GlobalValue::DefaultStorageClass;
if (CGM.getTriple().isWindowsItaniumEnvironment()) {
auto RD = Ty->getAsCXXRecordDecl();
if (RD && RD->hasAttr<DLLExportAttr>())
DLLStorageClass = llvm::GlobalValue::DLLExportStorageClass;
}
return BuildTypeInfo(Ty, Linkage, llvmVisibility, DLLStorageClass);
}
llvm::Constant *ItaniumRTTIBuilder::BuildTypeInfo(
QualType Ty,
llvm::GlobalVariable::LinkageTypes Linkage,
llvm::GlobalValue::VisibilityTypes Visibility,
llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass) {
// Add the vtable pointer.
BuildVTablePointer(cast<Type>(Ty));
// And the name.
llvm::GlobalVariable *TypeName = GetAddrOfTypeName(Ty, Linkage);
llvm::Constant *TypeNameField;
// If we're supposed to demote the visibility, be sure to set a flag
// to use a string comparison for type_info comparisons.
ItaniumCXXABI::RTTIUniquenessKind RTTIUniqueness =
CXXABI.classifyRTTIUniqueness(Ty, Linkage);
if (RTTIUniqueness != ItaniumCXXABI::RUK_Unique) {
// The flag is the sign bit, which on ARM64 is defined to be clear
// for global pointers. This is very ARM64-specific.
TypeNameField = llvm::ConstantExpr::getPtrToInt(TypeName, CGM.Int64Ty);
llvm::Constant *flag =
llvm::ConstantInt::get(CGM.Int64Ty, ((uint64_t)1) << 63);
TypeNameField = llvm::ConstantExpr::getAdd(TypeNameField, flag);
TypeNameField =
llvm::ConstantExpr::getIntToPtr(TypeNameField, CGM.Int8PtrTy);
} else {
TypeNameField = llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy);
}
Fields.push_back(TypeNameField);
switch (Ty->getTypeClass()) {
#define TYPE(Class, Base)
#define ABSTRACT_TYPE(Class, Base)
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
#include "clang/AST/TypeNodes.inc"
llvm_unreachable("Non-canonical and dependent types shouldn't get here");
// GCC treats vector types as fundamental types.
case Type::Builtin:
case Type::Vector:
case Type::ExtVector:
case Type::ConstantMatrix:
case Type::Complex:
case Type::BlockPointer:
// Itanium C++ ABI 2.9.5p4:
// abi::__fundamental_type_info adds no data members to std::type_info.
break;
case Type::LValueReference:
case Type::RValueReference:
llvm_unreachable("References shouldn't get here");
case Type::Auto:
case Type::DeducedTemplateSpecialization:
llvm_unreachable("Undeduced type shouldn't get here");
case Type::Pipe:
break;
case Type::ExtInt:
break;
case Type::ConstantArray:
case Type::IncompleteArray:
case Type::VariableArray:
// Itanium C++ ABI 2.9.5p5:
// abi::__array_type_info adds no data members to std::type_info.
break;
case Type::FunctionNoProto:
case Type::FunctionProto:
// Itanium C++ ABI 2.9.5p5:
// abi::__function_type_info adds no data members to std::type_info.
break;
case Type::Enum:
// Itanium C++ ABI 2.9.5p5:
// abi::__enum_type_info adds no data members to std::type_info.
break;
case Type::Record: {
const CXXRecordDecl *RD =
cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
if (!RD->hasDefinition() || !RD->getNumBases()) {
// We don't need to emit any fields.
break;
}
if (CanUseSingleInheritance(RD))
BuildSIClassTypeInfo(RD);
else
BuildVMIClassTypeInfo(RD);
break;
}
case Type::ObjCObject:
case Type::ObjCInterface:
BuildObjCObjectTypeInfo(cast<ObjCObjectType>(Ty));
break;
case Type::ObjCObjectPointer:
BuildPointerTypeInfo(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
break;
case Type::Pointer:
BuildPointerTypeInfo(cast<PointerType>(Ty)->getPointeeType());
break;
case Type::MemberPointer:
BuildPointerToMemberTypeInfo(cast<MemberPointerType>(Ty));
break;
case Type::Atomic:
// No fields, at least for the moment.
break;
}
llvm::Constant *Init = llvm::ConstantStruct::getAnon(Fields);
SmallString<256> Name;
llvm::raw_svector_ostream Out(Name);
CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
llvm::Module &M = CGM.getModule();
llvm::GlobalVariable *OldGV = M.getNamedGlobal(Name);
llvm::GlobalVariable *GV =
new llvm::GlobalVariable(M, Init->getType(),
/*isConstant=*/true, Linkage, Init, Name);
// If there's already an old global variable, replace it with the new one.
if (OldGV) {
GV->takeName(OldGV);
llvm::Constant *NewPtr =
llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
OldGV->replaceAllUsesWith(NewPtr);
OldGV->eraseFromParent();
}
if (CGM.supportsCOMDAT() && GV->isWeakForLinker())
GV->setComdat(M.getOrInsertComdat(GV->getName()));
CharUnits Align =
CGM.getContext().toCharUnitsFromBits(CGM.getTarget().getPointerAlign(0));
GV->setAlignment(Align.getAsAlign());
// The Itanium ABI specifies that type_info objects must be globally
// unique, with one exception: if the type is an incomplete class
// type or a (possibly indirect) pointer to one. That exception
// affects the general case of comparing type_info objects produced
// by the typeid operator, which is why the comparison operators on
// std::type_info generally use the type_info name pointers instead
// of the object addresses. However, the language's built-in uses
// of RTTI generally require class types to be complete, even when
// manipulating pointers to those class types. This allows the
// implementation of dynamic_cast to rely on address equality tests,
// which is much faster.
// All of this is to say that it's important that both the type_info
// object and the type_info name be uniqued when weakly emitted.
TypeName->setVisibility(Visibility);
CGM.setDSOLocal(TypeName);
GV->setVisibility(Visibility);
CGM.setDSOLocal(GV);
TypeName->setDLLStorageClass(DLLStorageClass);
GV->setDLLStorageClass(DLLStorageClass);
TypeName->setPartition(CGM.getCodeGenOpts().SymbolPartition);
GV->setPartition(CGM.getCodeGenOpts().SymbolPartition);
return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
}
/// BuildObjCObjectTypeInfo - Build the appropriate kind of type_info
/// for the given Objective-C object type.
void ItaniumRTTIBuilder::BuildObjCObjectTypeInfo(const ObjCObjectType *OT) {
// Drop qualifiers.
const Type *T = OT->getBaseType().getTypePtr();
assert(isa<BuiltinType>(T) || isa<ObjCInterfaceType>(T));
// The builtin types are abi::__class_type_infos and don't require
// extra fields.
if (isa<BuiltinType>(T)) return;
ObjCInterfaceDecl *Class = cast<ObjCInterfaceType>(T)->getDecl();
ObjCInterfaceDecl *Super = Class->getSuperClass();
// Root classes are also __class_type_info.
if (!Super) return;
QualType SuperTy = CGM.getContext().getObjCInterfaceType(Super);
// Everything else is single inheritance.
llvm::Constant *BaseTypeInfo =
ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(SuperTy);
Fields.push_back(BaseTypeInfo);
}
/// BuildSIClassTypeInfo - Build an abi::__si_class_type_info, used for single
/// inheritance, according to the Itanium C++ ABI, 2.95p6b.
void ItaniumRTTIBuilder::BuildSIClassTypeInfo(const CXXRecordDecl *RD) {
// Itanium C++ ABI 2.9.5p6b:
// It adds to abi::__class_type_info a single member pointing to the
// type_info structure for the base type,
llvm::Constant *BaseTypeInfo =
ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(RD->bases_begin()->getType());
Fields.push_back(BaseTypeInfo);
}
namespace {
/// SeenBases - Contains virtual and non-virtual bases seen when traversing
/// a class hierarchy.
struct SeenBases {
llvm::SmallPtrSet<const CXXRecordDecl *, 16> NonVirtualBases;
llvm::SmallPtrSet<const CXXRecordDecl *, 16> VirtualBases;
};
}
/// ComputeVMIClassTypeInfoFlags - Compute the value of the flags member in
/// abi::__vmi_class_type_info.
///
static unsigned ComputeVMIClassTypeInfoFlags(const CXXBaseSpecifier *Base,
SeenBases &Bases) {
unsigned Flags = 0;
auto *BaseDecl =
cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
if (Base->isVirtual()) {
// Mark the virtual base as seen.
if (!Bases.VirtualBases.insert(BaseDecl).second) {
// If this virtual base has been seen before, then the class is diamond
// shaped.
Flags |= ItaniumRTTIBuilder::VMI_DiamondShaped;
} else {
if (Bases.NonVirtualBases.count(BaseDecl))
Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
}
} else {
// Mark the non-virtual base as seen.
if (!Bases.NonVirtualBases.insert(BaseDecl).second) {
// If this non-virtual base has been seen before, then the class has non-
// diamond shaped repeated inheritance.
Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
} else {
if (Bases.VirtualBases.count(BaseDecl))
Flags |= ItaniumRTTIBuilder::VMI_NonDiamondRepeat;
}
}
// Walk all bases.
for (const auto &I : BaseDecl->bases())
Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
return Flags;
}
static unsigned ComputeVMIClassTypeInfoFlags(const CXXRecordDecl *RD) {
unsigned Flags = 0;
SeenBases Bases;
// Walk all bases.
for (const auto &I : RD->bases())
Flags |= ComputeVMIClassTypeInfoFlags(&I, Bases);
return Flags;
}
/// BuildVMIClassTypeInfo - Build an abi::__vmi_class_type_info, used for
/// classes with bases that do not satisfy the abi::__si_class_type_info
/// constraints, according ti the Itanium C++ ABI, 2.9.5p5c.
void ItaniumRTTIBuilder::BuildVMIClassTypeInfo(const CXXRecordDecl *RD) {
llvm::Type *UnsignedIntLTy =
CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
// Itanium C++ ABI 2.9.5p6c:
// __flags is a word with flags describing details about the class
// structure, which may be referenced by using the __flags_masks
// enumeration. These flags refer to both direct and indirect bases.
unsigned Flags = ComputeVMIClassTypeInfoFlags(RD);
Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
// Itanium C++ ABI 2.9.5p6c:
// __base_count is a word with the number of direct proper base class
// descriptions that follow.
Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, RD->getNumBases()));
if (!RD->getNumBases())
return;
// Now add the base class descriptions.
// Itanium C++ ABI 2.9.5p6c:
// __base_info[] is an array of base class descriptions -- one for every
// direct proper base. Each description is of the type:
//
// struct abi::__base_class_type_info {
// public:
// const __class_type_info *__base_type;
// long __offset_flags;
//
// enum __offset_flags_masks {
// __virtual_mask = 0x1,
// __public_mask = 0x2,
// __offset_shift = 8
// };
// };
// If we're in mingw and 'long' isn't wide enough for a pointer, use 'long
// long' instead of 'long' for __offset_flags. libstdc++abi uses long long on
// LLP64 platforms.
// FIXME: Consider updating libc++abi to match, and extend this logic to all
// LLP64 platforms.
QualType OffsetFlagsTy = CGM.getContext().LongTy;
const TargetInfo &TI = CGM.getContext().getTargetInfo();
if (TI.getTriple().isOSCygMing() && TI.getPointerWidth(0) > TI.getLongWidth())
OffsetFlagsTy = CGM.getContext().LongLongTy;
llvm::Type *OffsetFlagsLTy =
CGM.getTypes().ConvertType(OffsetFlagsTy);
for (const auto &Base : RD->bases()) {
// The __base_type member points to the RTTI for the base type.
Fields.push_back(ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(Base.getType()));
auto *BaseDecl =
cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
int64_t OffsetFlags = 0;
// All but the lower 8 bits of __offset_flags are a signed offset.
// For a non-virtual base, this is the offset in the object of the base
// subobject. For a virtual base, this is the offset in the virtual table of
// the virtual base offset for the virtual base referenced (negative).
CharUnits Offset;
if (Base.isVirtual())
Offset =
CGM.getItaniumVTableContext().getVirtualBaseOffsetOffset(RD, BaseDecl);
else {
const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
Offset = Layout.getBaseClassOffset(BaseDecl);
};
OffsetFlags = uint64_t(Offset.getQuantity()) << 8;
// The low-order byte of __offset_flags contains flags, as given by the
// masks from the enumeration __offset_flags_masks.
if (Base.isVirtual())
OffsetFlags |= BCTI_Virtual;
if (Base.getAccessSpecifier() == AS_public)
OffsetFlags |= BCTI_Public;
Fields.push_back(llvm::ConstantInt::get(OffsetFlagsLTy, OffsetFlags));
}
}
/// Compute the flags for a __pbase_type_info, and remove the corresponding
/// pieces from \p Type.
static unsigned extractPBaseFlags(ASTContext &Ctx, QualType &Type) {
unsigned Flags = 0;
if (Type.isConstQualified())
Flags |= ItaniumRTTIBuilder::PTI_Const;
if (Type.isVolatileQualified())
Flags |= ItaniumRTTIBuilder::PTI_Volatile;
if (Type.isRestrictQualified())
Flags |= ItaniumRTTIBuilder::PTI_Restrict;
Type = Type.getUnqualifiedType();
// Itanium C++ ABI 2.9.5p7:
// When the abi::__pbase_type_info is for a direct or indirect pointer to an
// incomplete class type, the incomplete target type flag is set.
if (ContainsIncompleteClassType(Type))
Flags |= ItaniumRTTIBuilder::PTI_Incomplete;
if (auto *Proto = Type->getAs<FunctionProtoType>()) {
if (Proto->isNothrow()) {
Flags |= ItaniumRTTIBuilder::PTI_Noexcept;
Type = Ctx.getFunctionTypeWithExceptionSpec(Type, EST_None);
}
}
return Flags;
}
/// BuildPointerTypeInfo - Build an abi::__pointer_type_info struct,
/// used for pointer types.
void ItaniumRTTIBuilder::BuildPointerTypeInfo(QualType PointeeTy) {
// Itanium C++ ABI 2.9.5p7:
// __flags is a flag word describing the cv-qualification and other
// attributes of the type pointed to
unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
llvm::Type *UnsignedIntLTy =
CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
// Itanium C++ ABI 2.9.5p7:
// __pointee is a pointer to the std::type_info derivation for the
// unqualified type being pointed to.
llvm::Constant *PointeeTypeInfo =
ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
Fields.push_back(PointeeTypeInfo);
}
/// BuildPointerToMemberTypeInfo - Build an abi::__pointer_to_member_type_info
/// struct, used for member pointer types.
void
ItaniumRTTIBuilder::BuildPointerToMemberTypeInfo(const MemberPointerType *Ty) {
QualType PointeeTy = Ty->getPointeeType();
// Itanium C++ ABI 2.9.5p7:
// __flags is a flag word describing the cv-qualification and other
// attributes of the type pointed to.
unsigned Flags = extractPBaseFlags(CGM.getContext(), PointeeTy);
const RecordType *ClassType = cast<RecordType>(Ty->getClass());
if (IsIncompleteClassType(ClassType))
Flags |= PTI_ContainingClassIncomplete;
llvm::Type *UnsignedIntLTy =
CGM.getTypes().ConvertType(CGM.getContext().UnsignedIntTy);
Fields.push_back(llvm::ConstantInt::get(UnsignedIntLTy, Flags));
// Itanium C++ ABI 2.9.5p7:
// __pointee is a pointer to the std::type_info derivation for the
// unqualified type being pointed to.
llvm::Constant *PointeeTypeInfo =
ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(PointeeTy);
Fields.push_back(PointeeTypeInfo);
// Itanium C++ ABI 2.9.5p9:
// __context is a pointer to an abi::__class_type_info corresponding to the
// class type containing the member pointed to
// (e.g., the "A" in "int A::*").
Fields.push_back(
ItaniumRTTIBuilder(CXXABI).BuildTypeInfo(QualType(ClassType, 0)));
}
llvm::Constant *ItaniumCXXABI::getAddrOfRTTIDescriptor(QualType Ty) {
return ItaniumRTTIBuilder(*this).BuildTypeInfo(Ty);
}
void ItaniumCXXABI::EmitFundamentalRTTIDescriptors(const CXXRecordDecl *RD) {
// Types added here must also be added to TypeInfoIsInStandardLibrary.
QualType FundamentalTypes[] = {
getContext().VoidTy, getContext().NullPtrTy,
getContext().BoolTy, getContext().WCharTy,
getContext().CharTy, getContext().UnsignedCharTy,
getContext().SignedCharTy, getContext().ShortTy,
getContext().UnsignedShortTy, getContext().IntTy,
getContext().UnsignedIntTy, getContext().LongTy,
getContext().UnsignedLongTy, getContext().LongLongTy,
getContext().UnsignedLongLongTy, getContext().Int128Ty,
getContext().UnsignedInt128Ty, getContext().HalfTy,
getContext().FloatTy, getContext().DoubleTy,
getContext().LongDoubleTy, getContext().Float128Ty,
getContext().Char8Ty, getContext().Char16Ty,
getContext().Char32Ty
};
llvm::GlobalValue::DLLStorageClassTypes DLLStorageClass =
RD->hasAttr<DLLExportAttr>()
? llvm::GlobalValue::DLLExportStorageClass
: llvm::GlobalValue::DefaultStorageClass;
llvm::GlobalValue::VisibilityTypes Visibility =
CodeGenModule::GetLLVMVisibility(RD->getVisibility());
for (const QualType &FundamentalType : FundamentalTypes) {
QualType PointerType = getContext().getPointerType(FundamentalType);
QualType PointerTypeConst = getContext().getPointerType(
FundamentalType.withConst());
for (QualType Type : {FundamentalType, PointerType, PointerTypeConst})
ItaniumRTTIBuilder(*this).BuildTypeInfo(
Type, llvm::GlobalValue::ExternalLinkage,
Visibility, DLLStorageClass);
}
}
/// What sort of uniqueness rules should we use for the RTTI for the
/// given type?
ItaniumCXXABI::RTTIUniquenessKind ItaniumCXXABI::classifyRTTIUniqueness(
QualType CanTy, llvm::GlobalValue::LinkageTypes Linkage) const {
if (shouldRTTIBeUnique())
return RUK_Unique;
// It's only necessary for linkonce_odr or weak_odr linkage.
if (Linkage != llvm::GlobalValue::LinkOnceODRLinkage &&
Linkage != llvm::GlobalValue::WeakODRLinkage)
return RUK_Unique;
// It's only necessary with default visibility.
if (CanTy->getVisibility() != DefaultVisibility)
return RUK_Unique;
// If we're not required to publish this symbol, hide it.
if (Linkage == llvm::GlobalValue::LinkOnceODRLinkage)
return RUK_NonUniqueHidden;
// If we're required to publish this symbol, as we might be under an
// explicit instantiation, leave it with default visibility but
// enable string-comparisons.
assert(Linkage == llvm::GlobalValue::WeakODRLinkage);
return RUK_NonUniqueVisible;
}
// Find out how to codegen the complete destructor and constructor
namespace {
enum class StructorCodegen { Emit, RAUW, Alias, COMDAT };
}
static StructorCodegen getCodegenToUse(CodeGenModule &CGM,
const CXXMethodDecl *MD) {
if (!CGM.getCodeGenOpts().CXXCtorDtorAliases)
return StructorCodegen::Emit;
// The complete and base structors are not equivalent if there are any virtual
// bases, so emit separate functions.
if (MD->getParent()->getNumVBases())
return StructorCodegen::Emit;
GlobalDecl AliasDecl;
if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
AliasDecl = GlobalDecl(DD, Dtor_Complete);
} else {
const auto *CD = cast<CXXConstructorDecl>(MD);
AliasDecl = GlobalDecl(CD, Ctor_Complete);
}
llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
if (llvm::GlobalValue::isDiscardableIfUnused(Linkage))
return StructorCodegen::RAUW;
// FIXME: Should we allow available_externally aliases?
if (!llvm::GlobalAlias::isValidLinkage(Linkage))
return StructorCodegen::RAUW;
if (llvm::GlobalValue::isWeakForLinker(Linkage)) {
// Only ELF and wasm support COMDATs with arbitrary names (C5/D5).
if (CGM.getTarget().getTriple().isOSBinFormatELF() ||
CGM.getTarget().getTriple().isOSBinFormatWasm())
return StructorCodegen::COMDAT;
return StructorCodegen::Emit;
}
return StructorCodegen::Alias;
}
static void emitConstructorDestructorAlias(CodeGenModule &CGM,
GlobalDecl AliasDecl,
GlobalDecl TargetDecl) {
llvm::GlobalValue::LinkageTypes Linkage = CGM.getFunctionLinkage(AliasDecl);
StringRef MangledName = CGM.getMangledName(AliasDecl);
llvm::GlobalValue *Entry = CGM.GetGlobalValue(MangledName);
if (Entry && !Entry->isDeclaration())
return;
auto *Aliasee = cast<llvm::GlobalValue>(CGM.GetAddrOfGlobal(TargetDecl));
// Create the alias with no name.
auto *Alias = llvm::GlobalAlias::create(Linkage, "", Aliasee);
// Constructors and destructors are always unnamed_addr.
Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
// Switch any previous uses to the alias.
if (Entry) {
assert(Entry->getType() == Aliasee->getType() &&
"declaration exists with different type");
Alias->takeName(Entry);
Entry->replaceAllUsesWith(Alias);
Entry->eraseFromParent();
} else {
Alias->setName(MangledName);
}
// Finally, set up the alias with its proper name and attributes.
CGM.SetCommonAttributes(AliasDecl, Alias);
}
void ItaniumCXXABI::emitCXXStructor(GlobalDecl GD) {
auto *MD = cast<CXXMethodDecl>(GD.getDecl());
auto *CD = dyn_cast<CXXConstructorDecl>(MD);
const CXXDestructorDecl *DD = CD ? nullptr : cast<CXXDestructorDecl>(MD);
StructorCodegen CGType = getCodegenToUse(CGM, MD);
if (CD ? GD.getCtorType() == Ctor_Complete
: GD.getDtorType() == Dtor_Complete) {
GlobalDecl BaseDecl;
if (CD)
BaseDecl = GD.getWithCtorType(Ctor_Base);
else
BaseDecl = GD.getWithDtorType(Dtor_Base);
if (CGType == StructorCodegen::Alias || CGType == StructorCodegen::COMDAT) {
emitConstructorDestructorAlias(CGM, GD, BaseDecl);
return;
}
if (CGType == StructorCodegen::RAUW) {
StringRef MangledName = CGM.getMangledName(GD);
auto *Aliasee = CGM.GetAddrOfGlobal(BaseDecl);
CGM.addReplacement(MangledName, Aliasee);
return;
}
}
// The base destructor is equivalent to the base destructor of its
// base class if there is exactly one non-virtual base class with a
// non-trivial destructor, there are no fields with a non-trivial
// destructor, and the body of the destructor is trivial.
if (DD && GD.getDtorType() == Dtor_Base &&
CGType != StructorCodegen::COMDAT &&
!CGM.TryEmitBaseDestructorAsAlias(DD))
return;
// FIXME: The deleting destructor is equivalent to the selected operator
// delete if:
// * either the delete is a destroying operator delete or the destructor
// would be trivial if it weren't virtual,
// * the conversion from the 'this' parameter to the first parameter of the
// destructor is equivalent to a bitcast,
// * the destructor does not have an implicit "this" return, and
// * the operator delete has the same calling convention and IR function type
// as the destructor.
// In such cases we should try to emit the deleting dtor as an alias to the
// selected 'operator delete'.
llvm::Function *Fn = CGM.codegenCXXStructor(GD);
if (CGType == StructorCodegen::COMDAT) {
SmallString<256> Buffer;
llvm::raw_svector_ostream Out(Buffer);
if (DD)
getMangleContext().mangleCXXDtorComdat(DD, Out);
else
getMangleContext().mangleCXXCtorComdat(CD, Out);
llvm::Comdat *C = CGM.getModule().getOrInsertComdat(Out.str());
Fn->setComdat(C);
} else {
CGM.maybeSetTrivialComdat(*MD, *Fn);
}
}
static llvm::FunctionCallee getBeginCatchFn(CodeGenModule &CGM) {
// void *__cxa_begin_catch(void*);
llvm::FunctionType *FTy = llvm::FunctionType::get(
CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
return CGM.CreateRuntimeFunction(FTy, "__cxa_begin_catch");
}
static llvm::FunctionCallee getEndCatchFn(CodeGenModule &CGM) {
// void __cxa_end_catch();
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
return CGM.CreateRuntimeFunction(FTy, "__cxa_end_catch");
}
static llvm::FunctionCallee getGetExceptionPtrFn(CodeGenModule &CGM) {
// void *__cxa_get_exception_ptr(void*);
llvm::FunctionType *FTy = llvm::FunctionType::get(
CGM.Int8PtrTy, CGM.Int8PtrTy, /*isVarArg=*/false);
return CGM.CreateRuntimeFunction(FTy, "__cxa_get_exception_ptr");
}
namespace {
/// A cleanup to call __cxa_end_catch. In many cases, the caught
/// exception type lets us state definitively that the thrown exception
/// type does not have a destructor. In particular:
/// - Catch-alls tell us nothing, so we have to conservatively
/// assume that the thrown exception might have a destructor.
/// - Catches by reference behave according to their base types.
/// - Catches of non-record types will only trigger for exceptions
/// of non-record types, which never have destructors.
/// - Catches of record types can trigger for arbitrary subclasses
/// of the caught type, so we have to assume the actual thrown
/// exception type might have a throwing destructor, even if the
/// caught type's destructor is trivial or nothrow.
struct CallEndCatch final : EHScopeStack::Cleanup {
CallEndCatch(bool MightThrow) : MightThrow(MightThrow) {}
bool MightThrow;
void Emit(CodeGenFunction &CGF, Flags flags) override {
if (!MightThrow) {
CGF.EmitNounwindRuntimeCall(getEndCatchFn(CGF.CGM));
return;
}
CGF.EmitRuntimeCallOrInvoke(getEndCatchFn(CGF.CGM));
}
};
}
/// Emits a call to __cxa_begin_catch and enters a cleanup to call
/// __cxa_end_catch.
///
/// \param EndMightThrow - true if __cxa_end_catch might throw
static llvm::Value *CallBeginCatch(CodeGenFunction &CGF,
llvm::Value *Exn,
bool EndMightThrow) {
llvm::CallInst *call =
CGF.EmitNounwindRuntimeCall(getBeginCatchFn(CGF.CGM), Exn);
CGF.EHStack.pushCleanup<CallEndCatch>(NormalAndEHCleanup, EndMightThrow);
return call;
}
/// A "special initializer" callback for initializing a catch
/// parameter during catch initialization.
static void InitCatchParam(CodeGenFunction &CGF,
const VarDecl &CatchParam,
Address ParamAddr,
SourceLocation Loc) {
// Load the exception from where the landing pad saved it.
llvm::Value *Exn = CGF.getExceptionFromSlot();
CanQualType CatchType =
CGF.CGM.getContext().getCanonicalType(CatchParam.getType());
llvm::Type *LLVMCatchTy = CGF.ConvertTypeForMem(CatchType);
// If we're catching by reference, we can just cast the object
// pointer to the appropriate pointer.
if (isa<ReferenceType>(CatchType)) {
QualType CaughtType = cast<ReferenceType>(CatchType)->getPointeeType();
bool EndCatchMightThrow = CaughtType->isRecordType();
// __cxa_begin_catch returns the adjusted object pointer.
llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, EndCatchMightThrow);
// We have no way to tell the personality function that we're
// catching by reference, so if we're catching a pointer,
// __cxa_begin_catch will actually return that pointer by value.
if (const PointerType *PT = dyn_cast<PointerType>(CaughtType)) {
QualType PointeeType = PT->getPointeeType();
// When catching by reference, generally we should just ignore
// this by-value pointer and use the exception object instead.
if (!PointeeType->isRecordType()) {
// Exn points to the struct _Unwind_Exception header, which
// we have to skip past in order to reach the exception data.
unsigned HeaderSize =
CGF.CGM.getTargetCodeGenInfo().getSizeOfUnwindException();
AdjustedExn = CGF.Builder.CreateConstGEP1_32(Exn, HeaderSize);
// However, if we're catching a pointer-to-record type that won't
// work, because the personality function might have adjusted
// the pointer. There's actually no way for us to fully satisfy
// the language/ABI contract here: we can't use Exn because it
// might have the wrong adjustment, but we can't use the by-value
// pointer because it's off by a level of abstraction.
//
// The current solution is to dump the adjusted pointer into an
// alloca, which breaks language semantics (because changing the
// pointer doesn't change the exception) but at least works.
// The better solution would be to filter out non-exact matches
// and rethrow them, but this is tricky because the rethrow
// really needs to be catchable by other sites at this landing
// pad. The best solution is to fix the personality function.
} else {
// Pull the pointer for the reference type off.
llvm::Type *PtrTy =
cast<llvm::PointerType>(LLVMCatchTy)->getElementType();
// Create the temporary and write the adjusted pointer into it.
Address ExnPtrTmp =
CGF.CreateTempAlloca(PtrTy, CGF.getPointerAlign(), "exn.byref.tmp");
llvm::Value *Casted = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
CGF.Builder.CreateStore(Casted, ExnPtrTmp);
// Bind the reference to the temporary.
AdjustedExn = ExnPtrTmp.getPointer();
}
}
llvm::Value *ExnCast =
CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.byref");
CGF.Builder.CreateStore(ExnCast, ParamAddr);
return;
}
// Scalars and complexes.
TypeEvaluationKind TEK = CGF.getEvaluationKind(CatchType);
if (TEK != TEK_Aggregate) {
llvm::Value *AdjustedExn = CallBeginCatch(CGF, Exn, false);
// If the catch type is a pointer type, __cxa_begin_catch returns
// the pointer by value.
if (CatchType->hasPointerRepresentation()) {
llvm::Value *CastExn =
CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
switch (CatchType.getQualifiers().getObjCLifetime()) {
case Qualifiers::OCL_Strong:
CastExn = CGF.EmitARCRetainNonBlock(CastExn);
LLVM_FALLTHROUGH;
case Qualifiers::OCL_None:
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Autoreleasing:
CGF.Builder.CreateStore(CastExn, ParamAddr);
return;
case Qualifiers::OCL_Weak:
CGF.EmitARCInitWeak(ParamAddr, CastExn);
return;
}
llvm_unreachable("bad ownership qualifier!");
}
// Otherwise, it returns a pointer into the exception object.
llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
llvm::Value *Cast = CGF.Builder.CreateBitCast(AdjustedExn, PtrTy);
LValue srcLV = CGF.MakeNaturalAlignAddrLValue(Cast, CatchType);
LValue destLV = CGF.MakeAddrLValue(ParamAddr, CatchType);
switch (TEK) {
case TEK_Complex:
CGF.EmitStoreOfComplex(CGF.EmitLoadOfComplex(srcLV, Loc), destLV,
/*init*/ true);
return;
case TEK_Scalar: {
llvm::Value *ExnLoad = CGF.EmitLoadOfScalar(srcLV, Loc);
CGF.EmitStoreOfScalar(ExnLoad, destLV, /*init*/ true);
return;
}
case TEK_Aggregate:
llvm_unreachable("evaluation kind filtered out!");
}
llvm_unreachable("bad evaluation kind");
}
assert(isa<RecordType>(CatchType) && "unexpected catch type!");
auto catchRD = CatchType->getAsCXXRecordDecl();
CharUnits caughtExnAlignment = CGF.CGM.getClassPointerAlignment(catchRD);
llvm::Type *PtrTy = LLVMCatchTy->getPointerTo(0); // addrspace 0 ok
// Check for a copy expression. If we don't have a copy expression,
// that means a trivial copy is okay.
const Expr *copyExpr = CatchParam.getInit();
if (!copyExpr) {
llvm::Value *rawAdjustedExn = CallBeginCatch(CGF, Exn, true);
Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
caughtExnAlignment);
LValue Dest = CGF.MakeAddrLValue(ParamAddr, CatchType);
LValue Src = CGF.MakeAddrLValue(adjustedExn, CatchType);
CGF.EmitAggregateCopy(Dest, Src, CatchType, AggValueSlot::DoesNotOverlap);
return;
}
// We have to call __cxa_get_exception_ptr to get the adjusted
// pointer before copying.
llvm::CallInst *rawAdjustedExn =
CGF.EmitNounwindRuntimeCall(getGetExceptionPtrFn(CGF.CGM), Exn);
// Cast that to the appropriate type.
Address adjustedExn(CGF.Builder.CreateBitCast(rawAdjustedExn, PtrTy),
caughtExnAlignment);
// The copy expression is defined in terms of an OpaqueValueExpr.
// Find it and map it to the adjusted expression.
CodeGenFunction::OpaqueValueMapping
opaque(CGF, OpaqueValueExpr::findInCopyConstruct(copyExpr),
CGF.MakeAddrLValue(adjustedExn, CatchParam.getType()));
// Call the copy ctor in a terminate scope.
CGF.EHStack.pushTerminate();
// Perform the copy construction.
CGF.EmitAggExpr(copyExpr,
AggValueSlot::forAddr(ParamAddr, Qualifiers(),
AggValueSlot::IsNotDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased,
AggValueSlot::DoesNotOverlap));
// Leave the terminate scope.
CGF.EHStack.popTerminate();
// Undo the opaque value mapping.
opaque.pop();
// Finally we can call __cxa_begin_catch.
CallBeginCatch(CGF, Exn, true);
}
/// Begins a catch statement by initializing the catch variable and
/// calling __cxa_begin_catch.
void ItaniumCXXABI::emitBeginCatch(CodeGenFunction &CGF,
const CXXCatchStmt *S) {
// We have to be very careful with the ordering of cleanups here:
// C++ [except.throw]p4:
// The destruction [of the exception temporary] occurs
// immediately after the destruction of the object declared in
// the exception-declaration in the handler.
//
// So the precise ordering is:
// 1. Construct catch variable.
// 2. __cxa_begin_catch
// 3. Enter __cxa_end_catch cleanup
// 4. Enter dtor cleanup
//
// We do this by using a slightly abnormal initialization process.
// Delegation sequence:
// - ExitCXXTryStmt opens a RunCleanupsScope
// - EmitAutoVarAlloca creates the variable and debug info
// - InitCatchParam initializes the variable from the exception
// - CallBeginCatch calls __cxa_begin_catch
// - CallBeginCatch enters the __cxa_end_catch cleanup
// - EmitAutoVarCleanups enters the variable destructor cleanup
// - EmitCXXTryStmt emits the code for the catch body
// - EmitCXXTryStmt close the RunCleanupsScope
VarDecl *CatchParam = S->getExceptionDecl();
if (!CatchParam) {
llvm::Value *Exn = CGF.getExceptionFromSlot();
CallBeginCatch(CGF, Exn, true);
return;
}
// Emit the local.
CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
InitCatchParam(CGF, *CatchParam, var.getObjectAddress(CGF), S->getBeginLoc());
CGF.EmitAutoVarCleanups(var);
}
/// Get or define the following function:
/// void @__clang_call_terminate(i8* %exn) nounwind noreturn
/// This code is used only in C++.
static llvm::FunctionCallee getClangCallTerminateFn(CodeGenModule &CGM) {
llvm::FunctionType *fnTy =
llvm::FunctionType::get(CGM.VoidTy, CGM.Int8PtrTy, /*isVarArg=*/false);
llvm::FunctionCallee fnRef = CGM.CreateRuntimeFunction(
fnTy, "__clang_call_terminate", llvm::AttributeList(), /*Local=*/true);
llvm::Function *fn =
cast<llvm::Function>(fnRef.getCallee()->stripPointerCasts());
if (fn->empty()) {
fn->setDoesNotThrow();
fn->setDoesNotReturn();
// What we really want is to massively penalize inlining without
// forbidding it completely. The difference between that and
// 'noinline' is negligible.
fn->addFnAttr(llvm::Attribute::NoInline);
// Allow this function to be shared across translation units, but
// we don't want it to turn into an exported symbol.
fn->setLinkage(llvm::Function::LinkOnceODRLinkage);
fn->setVisibility(llvm::Function::HiddenVisibility);
if (CGM.supportsCOMDAT())
fn->setComdat(CGM.getModule().getOrInsertComdat(fn->getName()));
// Set up the function.
llvm::BasicBlock *entry =
llvm::BasicBlock::Create(CGM.getLLVMContext(), "", fn);
CGBuilderTy builder(CGM, entry);
// Pull the exception pointer out of the parameter list.
llvm::Value *exn = &*fn->arg_begin();
// Call __cxa_begin_catch(exn).
llvm::CallInst *catchCall = builder.CreateCall(getBeginCatchFn(CGM), exn);
catchCall->setDoesNotThrow();
catchCall->setCallingConv(CGM.getRuntimeCC());
// Call std::terminate().
llvm::CallInst *termCall = builder.CreateCall(CGM.getTerminateFn());
termCall->setDoesNotThrow();
termCall->setDoesNotReturn();
termCall->setCallingConv(CGM.getRuntimeCC());
// std::terminate cannot return.
builder.CreateUnreachable();
}
return fnRef;
}
llvm::CallInst *
ItaniumCXXABI::emitTerminateForUnexpectedException(CodeGenFunction &CGF,
llvm::Value *Exn) {
// In C++, we want to call __cxa_begin_catch() before terminating.
if (Exn) {
assert(CGF.CGM.getLangOpts().CPlusPlus);
return CGF.EmitNounwindRuntimeCall(getClangCallTerminateFn(CGF.CGM), Exn);
}
return CGF.EmitNounwindRuntimeCall(CGF.CGM.getTerminateFn());
}
std::pair<llvm::Value *, const CXXRecordDecl *>
ItaniumCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
const CXXRecordDecl *RD) {
return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
}
void WebAssemblyCXXABI::emitBeginCatch(CodeGenFunction &CGF,
const CXXCatchStmt *C) {
if (CGF.getTarget().hasFeature("exception-handling"))
CGF.EHStack.pushCleanup<CatchRetScope>(
NormalCleanup, cast<llvm::CatchPadInst>(CGF.CurrentFuncletPad));
ItaniumCXXABI::emitBeginCatch(CGF, C);
}
/// Register a global destructor as best as we know how.
void XLCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
llvm::FunctionCallee dtor,
llvm::Constant *addr) {
if (D.getTLSKind() != VarDecl::TLS_None)
llvm::report_fatal_error("thread local storage not yet implemented on AIX");
// Create __dtor function for the var decl.
llvm::Function *dtorStub = CGF.createAtExitStub(D, dtor, addr);
// Register above __dtor with atexit().
CGF.registerGlobalDtorWithAtExit(dtorStub);
// Emit __finalize function to unregister __dtor and (as appropriate) call
// __dtor.
emitCXXStermFinalizer(D, dtorStub, addr);
}
void XLCXXABI::emitCXXStermFinalizer(const VarDecl &D, llvm::Function *dtorStub,
llvm::Constant *addr) {
llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
SmallString<256> FnName;
{
llvm::raw_svector_ostream Out(FnName);
getMangleContext().mangleDynamicStermFinalizer(&D, Out);
}
// Create the finalization action associated with a variable.
const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
llvm::Function *StermFinalizer = CGM.CreateGlobalInitOrCleanUpFunction(
FTy, FnName.str(), FI, D.getLocation());
CodeGenFunction CGF(CGM);
CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, StermFinalizer, FI,
FunctionArgList(), D.getLocation(),
D.getInit()->getExprLoc());
// The unatexit subroutine unregisters __dtor functions that were previously
// registered by the atexit subroutine. If the referenced function is found,
// the unatexit returns a value of 0, meaning that the cleanup is still
// pending (and we should call the __dtor function).
llvm::Value *V = CGF.unregisterGlobalDtorWithUnAtExit(dtorStub);
llvm::Value *NeedsDestruct = CGF.Builder.CreateIsNull(V, "needs_destruct");
llvm::BasicBlock *DestructCallBlock = CGF.createBasicBlock("destruct.call");
llvm::BasicBlock *EndBlock = CGF.createBasicBlock("destruct.end");
// Check if unatexit returns a value of 0. If it does, jump to
// DestructCallBlock, otherwise jump to EndBlock directly.
CGF.Builder.CreateCondBr(NeedsDestruct, DestructCallBlock, EndBlock);
CGF.EmitBlock(DestructCallBlock);
// Emit the call to dtorStub.
llvm::CallInst *CI = CGF.Builder.CreateCall(dtorStub);
// Make sure the call and the callee agree on calling convention.
CI->setCallingConv(dtorStub->getCallingConv());
CGF.EmitBlock(EndBlock);
CGF.FinishFunction();
assert(!D.getAttr<InitPriorityAttr>() &&
"Prioritized sinit and sterm functions are not yet supported.");
if (isTemplateInstantiation(D.getTemplateSpecializationKind()) ||
getContext().GetGVALinkageForVariable(&D) == GVA_DiscardableODR)
// According to C++ [basic.start.init]p2, class template static data
// members (i.e., implicitly or explicitly instantiated specializations)
// have unordered initialization. As a consequence, we can put them into
// their own llvm.global_dtors entry.
CGM.AddCXXStermFinalizerToGlobalDtor(StermFinalizer, 65535);
else
CGM.AddCXXStermFinalizerEntry(StermFinalizer);
}<|fim▁end|> | }
return false;
} |
<|file_name|>bookmark.py<|end_file_name|><|fim▁begin|># vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2011, Timothy Legge <[email protected]> and Kovid Goyal <[email protected]>'
__docformat__ = 'restructuredtext en'
import os
from contextlib import closing
class Bookmark(): # {{{
'''
A simple class fetching bookmark data
kobo-specific
'''<|fim▁hole|> def __init__(self, db_path, contentid, path, id, book_format, bookmark_extension):
self.book_format = book_format
self.bookmark_extension = bookmark_extension
self.book_length = 0 # Not Used
self.id = id
self.last_read = 0
self.last_read_location = 0 # Not Used
self.path = path
self.timestamp = 0
self.user_notes = None
self.db_path = db_path
self.contentid = contentid
self.percent_read = 0
self.get_bookmark_data()
self.get_book_length() # Not Used
def get_bookmark_data(self):
''' Return the timestamp and last_read_location '''
import sqlite3 as sqlite
user_notes = {}
self.timestamp = os.path.getmtime(self.path)
with closing(sqlite.connect(self.db_path)) as connection:
# return bytestrings if the content cannot the decoded as unicode
connection.text_factory = lambda x: unicode(x, "utf-8", "ignore")
cursor = connection.cursor()
t = (self.contentid,)
cursor.execute('select bm.bookmarkid, bm.contentid, bm.volumeid, '
'bm.text, bm.annotation, bm.ChapterProgress, '
'bm.StartContainerChildIndex, bm.StartOffset, c.BookTitle, '
'c.TITLE, c.volumeIndex, c.___NumPages '
'from Bookmark bm inner join Content c on '
'bm.contentid = c.contentid and '
'bm.volumeid = ? order by bm.volumeid, bm.chapterprogress', t)
previous_chapter = 0
bm_count = 0
for row in cursor:
current_chapter = row[10]
if previous_chapter == current_chapter:
bm_count = bm_count + 1
else:
bm_count = 0
text = row[3]
annotation = row[4]
# A dog ear (bent upper right corner) is a bookmark
if row[6] == row[7] == 0: # StartContainerChildIndex = StartOffset = 0
e_type = 'Bookmark'
text = row[9]
# highlight is text with no annotation
elif text is not None and (annotation is None or annotation == ""):
e_type = 'Highlight'
elif text and annotation:
e_type = 'Annotation'
else:
e_type = 'Unknown annotation type'
note_id = row[10] + bm_count
chapter_title = row[9]
# book_title = row[8]
chapter_progress = min(round(float(100*row[5]),2),100)
user_notes[note_id] = dict(id=self.id,
displayed_location=note_id,
type=e_type,
text=text,
annotation=annotation,
chapter=row[10],
chapter_title=chapter_title,
chapter_progress=chapter_progress)
previous_chapter = row[10]
# debug_print("e_type:" , e_type, '\t', 'loc: ', note_id, 'text: ', text,
# 'annotation: ', annotation, 'chapter_title: ', chapter_title,
# 'chapter_progress: ', chapter_progress, 'date: ')
cursor.execute('select datelastread, ___PercentRead from content '
'where bookid is Null and '
'contentid = ?', t)
for row in cursor:
self.last_read = row[0]
self.percent_read = row[1]
# print row[1]
cursor.close()
# self.last_read_location = self.last_read - self.pdf_page_offset
self.user_notes = user_notes
def get_book_length(self):
#TL self.book_length = 0
#TL self.book_length = int(unpack('>I', record0[0x04:0x08])[0])
pass
# }}}<|fim▁end|> | |
<|file_name|>MarkerCanvas.js<|end_file_name|><|fim▁begin|>import React from 'react'
import PropTypes from 'prop-types'
import { MarkerCanvasProvider } from './MarkerCanvasContext'
import TimelineMarkersRenderer from './TimelineMarkersRenderer'
import { TimelineStateConsumer } from '../timeline/TimelineStateContext'
// expand to fill entire parent container (ScrollElement)
const staticStyles = {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0
}
/**
* Renders registered markers and exposes a mouse over listener for
* CursorMarkers to subscribe to
*/
class MarkerCanvas extends React.Component {
static propTypes = {
getDateFromLeftOffsetPosition: PropTypes.func.isRequired,
children: PropTypes.node
}
handleMouseMove = evt => {
if (this.subscription != null) {
const { pageX } = evt
// FIXME: dont use getBoundingClientRect. Use passed in scroll amount
const { left: containerLeft } = this.containerEl.getBoundingClientRect()
// number of pixels from left we are on canvas
// we do this calculation as pageX is based on x from viewport whereas
// our canvas can be scrolled left and right and is generally outside
// of the viewport. This calculation is to get how many pixels the cursor
// is from left of this element
const canvasX = pageX - containerLeft
const date = this.props.getDateFromLeftOffsetPosition(canvasX)
this.subscription({
leftOffset: canvasX,
date,
isCursorOverCanvas: true
})
}
}
handleMouseLeave = () => {
if (this.subscription != null) {
// tell subscriber that we're not on canvas
this.subscription({ leftOffset: 0, date: 0, isCursorOverCanvas: false })
}
}
handleMouseMoveSubscribe = sub => {
this.subscription = sub
return () => {
this.subscription = null
}
}
state = {
subscribeToMouseOver: this.handleMouseMoveSubscribe
}<|fim▁hole|> return (
<MarkerCanvasProvider value={this.state}>
<div
style={staticStyles}
onMouseMove={this.handleMouseMove}
onMouseLeave={this.handleMouseLeave}
ref={el => (this.containerEl = el)}
>
<TimelineMarkersRenderer />
{this.props.children}
</div>
</MarkerCanvasProvider>
)
}
}
const MarkerCanvasWrapper = props => (
<TimelineStateConsumer>
{({ getDateFromLeftOffsetPosition }) => (
<MarkerCanvas
getDateFromLeftOffsetPosition={getDateFromLeftOffsetPosition}
{...props}
/>
)}
</TimelineStateConsumer>
)
export default MarkerCanvasWrapper<|fim▁end|> |
render() { |
<|file_name|>SimpleFieldsResourceGeneratorTest.java<|end_file_name|><|fim▁begin|>/*
* eGov suite of products aim to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) <2015> eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/ or
* http://www.gnu.org/licenses/gpl.html .
*<|fim▁hole|> * In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at [email protected].
*/
package org.egov.search.service;
import org.egov.search.domain.entities.Address;
import org.egov.search.domain.entities.Person;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import static com.jayway.jsonassert.JsonAssert.with;
public class SimpleFieldsResourceGeneratorTest {
private String json;
@Before
public void before() {
Person person = Person.newInstance();
ResourceGenerator<Person> resourceGenerator = new ResourceGenerator<>(Person.class, person);
JSONObject resource = resourceGenerator.generate();
json = resource.toJSONString();
}
@Test
public void withMultipleFields() {
with(json).assertEquals("$.searchable.citizen", true);
with(json).assertEquals("$.searchable.age", 37);
with(json).assertEquals("$.clauses.status", "ACTIVE");
with(json).assertNotDefined("$.searchable.role");
}
@Test
public void withMultipleFields_WithGivenName() {
with(json).assertEquals("$.searchable.citizen_name", "Elzan");
}
@Test
public void withAListField() {
with(json).assertEquals("$.searchable.jobs", Arrays.asList("Job One", "Job Two"));
}
@Test
public void withAMapField() {
with(json).assertEquals("$.searchable.serviceHistory.company1", "Job One");
with(json).assertEquals("$.searchable.serviceHistory.company2", "Job Two");
}
@Test
public void shouldGroupFields() {
Address address = new Address("street1", "560001");
ResourceGenerator<Address> resourceGenerator = new ResourceGenerator<>(Address.class, address);
JSONObject resource = resourceGenerator.generate();
String json = resource.toJSONString();
with(json).assertEquals("$.searchable.street", "street1");
with(json).assertEquals("$.searchable.pincode", "560001");
with(json).assertNotDefined("$.clauses");
with(json).assertNotDefined("$.common");
}
}<|fim▁end|> | |
<|file_name|>extract_cats_dogs.py<|end_file_name|><|fim▁begin|>"""One-time script for extracting all the cat and dog images from CIFAR-10."""
import cPickle
import numpy as np
from PIL import Image
TRAIN_FILES = ['cifar-10-batches-py/data_batch_%d' % i for i in range(1,6)]
TEST_FILE = 'test_batch'
CAT_INPUT_LABEL = 3
DOG_INPUT_LABEL = 5
CAT_OUTPUT_LABEL = 1
DOG_OUTPUT_LABEL = 0
def unpickle(file):
with open(file, 'rb') as fo:
dict = cPickle.load(fo)
return dict
data = []
# Count number of cats/dogs
num_cats = 0
num_dogs = 0
for data_file in TRAIN_FILES:
d = unpickle(data_file)
data.append(d)
for label in d['labels']:
if label == CAT_INPUT_LABEL:
num_cats += 1
if label == DOG_INPUT_LABEL:
num_dogs += 1
# Copy the cats/dogs into new array
images = np.empty((num_cats + num_dogs, 32, 32, 3), dtype=np.uint8)
labels = np.empty((num_cats + num_dogs), dtype=np.uint8)
index = 0
for data_batch in data:
for batch_index, label in enumerate(data_batch['labels']):
if label == CAT_INPUT_LABEL or label == DOG_INPUT_LABEL:
# Data is stored in B x 3072 format, convert to B' x 32 x 32 x 3
images[index, :, :, :] = np.transpose(
np.reshape(data_batch['data'][batch_index, :],
newshape=(3, 32, 32)),
axes=(1, 2, 0))
if label == CAT_INPUT_LABEL:
labels[index] = CAT_OUTPUT_LABEL
else:
labels[index] = DOG_OUTPUT_LABEL<|fim▁hole|>
np.save('catdog_data.npy', {'images': images, 'labels': labels})
# Make sure images look correct
img = Image.fromarray(images[10, :, :, :])
img.show()<|fim▁end|> | index += 1 |
<|file_name|>template.js<|end_file_name|><|fim▁begin|>import defaults from './defaults.js';
import _ from './underscore.js';
import './templateSettings.js';
// When customizing `_.templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {<|fim▁hole|> "'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
function escapeChar(match) {
return '\\' + escapes[match];
}
// In order to prevent third-party code injection through
// `_.templateSettings.variable`, we test it against the following regular
// expression. It is intentionally a bit more liberal than just matching valid
// identifiers, but still prevents possible loopholes through defaults or
// destructuring assignment.
var bareIdentifier = /^\s*(\w|\$)+\s*$/;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
export default function template(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offset.
return match;
});
source += "';\n";
var argument = settings.variable;
if (argument) {
// Insure against third-party code injection. (CVE-2021-23358)
if (!bareIdentifier.test(argument)) throw new Error(
'variable is not a bare identifier: ' + argument
);
} else {
// If a variable is not specified, place data values in local scope.
source = 'with(obj||{}){\n' + source + '}\n';
argument = 'obj';
}
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
var render;
try {
render = new Function(argument, '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
}<|fim▁end|> | |
<|file_name|>0004_auto_20161103_1044.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-03 10:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
<|fim▁hole|> ('domains', '0003_auto_20161103_1031'),
]
operations = [
migrations.RemoveField(
model_name='domain',
name='subtopics',
),
migrations.AddField(
model_name='subtopic',
name='dmain',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='subtopics', to='domains.domain'),
),
]<|fim▁end|> | dependencies = [ |
<|file_name|>profile-addresses.component.ts<|end_file_name|><|fim▁begin|>/// <reference types="@types/google-maps" />
import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Injector, Input, OnInit, ViewChild } from '@angular/core';
import { AddressView } from 'app/api/models';
import { Breakpoint } from 'app/core/layout.service';
import { BaseComponent } from 'app/shared/base.component';
import { AddressHelperService } from 'app/ui/core/address-helper.service';
import { MapsService } from 'app/ui/core/maps.service';
import { UiLayoutService } from 'app/ui/core/ui-layout.service';
import { CountriesResolve } from 'app/ui/countries.resolve';
/**
* Shows the user / advertisement address(es) in the view page
*/
@Component({
selector: 'profile-addresses',
templateUrl: 'profile-addresses.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProfileAddressesComponent extends BaseComponent implements OnInit, AfterViewInit {
constructor(
injector: Injector,
private uiLayout: UiLayoutService,
public addressHelper: AddressHelperService,
public maps: MapsService,
public countriesResolve: CountriesResolve,
) {
super(injector);
}
@ViewChild('mapContainer') mapContainer: ElementRef;
map: google.maps.Map;
private allInfoWindows: google.maps.InfoWindow[] = [];
@Input() addresses: AddressView[];
locatedAddresses: AddressView[];
ngOnInit() {
super.ngOnInit();
this.locatedAddresses = (this.addresses || []).filter(a => a.location);
}
ngAfterViewInit() {
// We'll only use a dynamic map with multiple located addresses
if (this.locatedAddresses.length > 1) {
this.addSub(this.maps.ensureScriptLoaded().subscribe(() => this.showMap()));
}
}
closeAllInfoWindows() {
this.allInfoWindows.forEach(iw => iw.close());<|fim▁hole|>
singleMapWidth(breakpoints: Set<Breakpoint>): number | 'auto' {
if (breakpoints.has('xl')) {
return 400;
} else if (breakpoints.has('gt-xs')) {
return 340;
} else {
return 'auto';
}
}
private showMap() {
const container = this.mapContainer.nativeElement as HTMLElement;
this.map = new google.maps.Map(container, {
mapTypeControl: false,
streetViewControl: false,
minZoom: 2,
maxZoom: 17,
styles: this.uiLayout.googleMapStyles,
});
const bounds = new google.maps.LatLngBounds();
this.locatedAddresses.map(a => {
const marker = new google.maps.Marker({
title: a.name,
icon: this.dataForFrontendHolder.dataForFrontend.mapMarkerUrl,
position: new google.maps.LatLng(a.location.latitude, a.location.longitude),
});
bounds.extend(marker.getPosition());
marker.addListener('click', () => {
this.closeAllInfoWindows();
let infoWindow = marker['infoWindow'] as google.maps.InfoWindow;
if (!infoWindow) {
infoWindow = new google.maps.InfoWindow({
content: marker.getTitle(),
});
this.allInfoWindows.push(infoWindow);
}
infoWindow.open(marker.getMap(), marker);
});
marker.setMap(this.map);
});
this.map.addListener('click', () => this.closeAllInfoWindows());
this.map.fitBounds(bounds);
}
}<|fim▁end|> | } |
<|file_name|>MachineLoginFilter.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2012-2017 Red Hat, Inc.<|fim▁hole|> * http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.machine.authentication.server;
import static com.google.common.base.Strings.nullToEmpty;
import java.io.IOException;
import java.security.Principal;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.model.user.User;
import org.eclipse.che.api.user.server.UserManager;
import org.eclipse.che.commons.auth.token.RequestTokenExtractor;
import org.eclipse.che.commons.env.EnvironmentContext;
import org.eclipse.che.commons.subject.Subject;
import org.eclipse.che.commons.subject.SubjectImpl;
import org.eclipse.che.multiuser.api.permission.server.AuthorizedSubject;
import org.eclipse.che.multiuser.api.permission.server.PermissionChecker;
/** @author Max Shaposhnik ([email protected]) */
@Singleton
public class MachineLoginFilter implements Filter {
@Inject private RequestTokenExtractor tokenExtractor;
@Inject private MachineTokenRegistry machineTokenRegistry;
@Inject private UserManager userManager;
@Inject private PermissionChecker permissionChecker;
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(
ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
if (httpRequest.getScheme().startsWith("ws")
|| !nullToEmpty(tokenExtractor.getToken(httpRequest)).startsWith("machine")) {
filterChain.doFilter(servletRequest, servletResponse);
return;
} else {
String tokenString;
User user;
try {
tokenString = tokenExtractor.getToken(httpRequest);
String userId = machineTokenRegistry.getUserId(tokenString);
user = userManager.getById(userId);
} catch (NotFoundException | ServerException e) {
throw new ServletException("Cannot find user by machine token.");
}
final Subject subject =
new AuthorizedSubject(
new SubjectImpl(user.getName(), user.getId(), tokenString, false), permissionChecker);
try {
EnvironmentContext.getCurrent().setSubject(subject);
filterChain.doFilter(addUserInRequest(httpRequest, subject), servletResponse);
} finally {
EnvironmentContext.reset();
}
}
}
private HttpServletRequest addUserInRequest(
final HttpServletRequest httpRequest, final Subject subject) {
return new HttpServletRequestWrapper(httpRequest) {
@Override
public String getRemoteUser() {
return subject.getUserName();
}
@Override
public Principal getUserPrincipal() {
return subject::getUserName;
}
};
}
@Override
public void destroy() {}
}<|fim▁end|> | * All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at |
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#################################################################################
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Dmitry Sovetov
#
# https://github.com/dmsovetov
#
# 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.
#
#################################################################################
import os, argparse
from Workspace import Workspace
# class Pygling
class Pygling:
@staticmethod
def main():
name = os.path.basename( os.getcwd() )
# Parse arguments
parser = argparse.ArgumentParser( prog = 'Pygling', description = 'Pygling C++ workspace generator.', prefix_chars = '--', formatter_class = argparse.ArgumentDefaultsHelpFormatter )
parser.add_argument( "action", type = str, help = "Action", choices = ["configure", "build", "install"] )
parser.add_argument( "-p", "--platform", default = 'all', type = str, help = "Target platform" )
parser.add_argument( "-s", "--source", default = '.', type = str, help = "Project source path" )
parser.add_argument( "-o", "--output", default = 'projects', type = str, help = "Output path" )
parser.add_argument( "-n", "--name", default = name, type = str, help = "Workspace (solution) name" )
parser.add_argument( "-a", "--arch", default = 'default', type = str, help = "Target build architecture" )
parser.add_argument( "-x", "--std", default = 'cxx98', type = str, help = "C++ standard", choices = ['cxx99', 'cxx11'] )
parser.add_argument( "-c", "--configuration", default = 'Release', type = str, help = "Build configuration" )
parser.add_argument( "--package", type = str, help = "Application package identifier" )
parser.add_argument( "--platformSdk", type = str, help = "Platform SDK identifier" )<|fim▁hole|> parser.add_argument( "--xcteam", type = str, help = "Xcode provisioning profile to be used" )
# Check action
args, unknown = parser.parse_known_args()
workspace = Workspace(args.name, args.source, args.output, args, unknown)
if args.action == 'configure': workspace.configure(args.platform)
elif args.action == 'build': workspace.build(args.platform)
elif args.action == 'install': workspace.install(args.platform)
# Entry point
if __name__ == "__main__":
Pygling.main()<|fim▁end|> | |
<|file_name|>platform_browser.ts<|end_file_name|><|fim▁begin|>/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import {env} from '../environment';
import {Platform} from './platform';
export class PlatformBrowser implements Platform {
// According to the spec, the built-in encoder can do only UTF-8 encoding.
// https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder
private textEncoder: TextEncoder;
<|fim▁hole|> now(): number {
return performance.now();
}
encode(text: string, encoding: string): Uint8Array {
if (encoding !== 'utf-8' && encoding !== 'utf8') {
throw new Error(
`Browser's encoder only supports utf-8, but got ${encoding}`);
}
if (this.textEncoder == null) {
this.textEncoder = new TextEncoder();
}
return this.textEncoder.encode(text);
}
decode(bytes: Uint8Array, encoding: string): string {
return new TextDecoder(encoding).decode(bytes);
}
}
if (env().get('IS_BROWSER')) {
env().setPlatform('browser', new PlatformBrowser());
}<|fim▁end|> | fetch(path: string, init?: RequestInit): Promise<Response> {
return fetch(path, init);
}
|
<|file_name|>singleton.hpp<|end_file_name|><|fim▁begin|>/**
* @file singleton.hpp
* @brief dynamic Singleton pattern design template class
* @author Byunghun Hwang<[email protected]>
* @date 2015. 8. 2
* @details singleton ÆÐÅÏ ÅÛÇø´ Ŭ·¡½º
*/
#ifndef _COSSB_ARCH_SINGLETON_HPP_
#define _COSSB_ARCH_SINGLETON_HPP_
#include <iostream>
#include <utility>
using namespace std;
namespace cossb {
namespace arch {
/**
* @brief dynamic singleton design pattern
*/
template <class T>
class singleton {
public:
template<typename... Args>
static T* instance(Args... args) {
if(!_instance) {
_instance = new T(std::forward<Args>(args)...);
}<|fim▁hole|> return _instance;
}
static void destroy() {
if(_instance) {
delete _instance;
_instance = nullptr;
}
}
protected:
singleton() {}
singleton(singleton const&) {}
singleton& operator=(singleton const&) { return *this; }
private:
static T* _instance;
};
template <class T> T* singleton<T>::_instance = nullptr;
} /* namespace arch */
} /* namespace cossb */
#endif /* _COSSB_ARCH_SINGLETON_HPP_ */<|fim▁end|> | |
<|file_name|>CustomFormAuthenticationFilter.java<|end_file_name|><|fim▁begin|>package com.cell.user.web.shrio.filter.authc;
import javax.servlet.ServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.cell.user.vo.single.SysUserVo;
import com.cell.user.web.service.UserService;
/**
* 基于几点修改: 1、onLoginFailure 时 把异常添加到request attribute中 而不是异常类名 2、登录成功时:成功页面重定向:
* 2.1、如果前一个页面是登录页面,-->2.3 2.2、如果有SavedRequest 则返回到SavedRequest
* 2.3、否则根据当前登录的用户决定返回到管理员首页/前台首页
<|fim▁hole|> UserService userService;
/**
* 默认的成功地址
*/
@Value("${shiro.default.success.url}")
private String defaultSuccessUrl;
/**
* 管理员默认的成功地址
*/
@Value("${shiro.admin.default.success.url}")
private String adminDefaultSuccessUrl;
@Override
protected void setFailureAttribute(ServletRequest request,
AuthenticationException ae) {
request.setAttribute(getFailureKeyAttribute(), ae);
}
/**
* 根据用户选择成功地址
*
* @return
*/
@Override
public String getSuccessUrl() {
String username = (String) SecurityUtils.getSubject().getPrincipal();
SysUserVo user = userService.findByUsername(username);
if (user != null && Boolean.TRUE.equals(user.getAdmin())) {
return this.adminDefaultSuccessUrl;
}
return this.defaultSuccessUrl;
}
}<|fim▁end|> | * <p/>
*/
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
@Autowired
|
<|file_name|>version.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation
#
# 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<|fim▁hole|># 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 pbr.version
version_info = pbr.version.VersionInfo('glance')
version_string = version_info.version_string<|fim▁end|> | # |
<|file_name|>services.go<|end_file_name|><|fim▁begin|>// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2018 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package ctlcmd
import (
"errors"
"fmt"
"sort"
"text/tabwriter"
"github.com/snapcore/snapd/client/clientutil"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/overlord/servicestate"
"github.com/snapcore/snapd/progress"
"github.com/snapcore/snapd/snap"
)
var (
shortServicesHelp = i18n.G("Query the status of services")
longServicesHelp = i18n.G(`
The services command lists information about the services specified.
`)
)
func init() {
addCommand("services", shortServicesHelp, longServicesHelp, func() command { return &servicesCommand{} })
}
type servicesCommand struct {
baseCommand
Positional struct {
ServiceNames []string `positional-arg-name:"<service>"`
} `positional-args:"yes"`
}
var errNoContextForServices = errors.New(i18n.G("cannot query services without a context"))
type byApp []*snap.AppInfo
func (a byApp) Len() int { return len(a) }
func (a byApp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byApp) Less(i, j int) bool {
return a[i].Name < a[j].Name<|fim▁hole|>}
func (c *servicesCommand) Execute([]string) error {
context := c.context()
if context == nil {
return errNoContextForServices
}
st := context.State()
svcInfos, err := getServiceInfos(st, context.InstanceName(), c.Positional.ServiceNames)
if err != nil {
return err
}
sort.Sort(byApp(svcInfos))
sd := servicestate.NewStatusDecorator(progress.Null)
services, err := clientutil.ClientAppInfosFromSnapAppInfos(svcInfos, sd)
if err != nil || len(services) == 0 {
return err
}
w := tabwriter.NewWriter(c.stdout, 5, 3, 2, ' ', 0)
defer w.Flush()
fmt.Fprintln(w, i18n.G("Service\tStartup\tCurrent\tNotes"))
for _, svc := range services {
startup := i18n.G("disabled")
if svc.Enabled {
startup = i18n.G("enabled")
}
current := i18n.G("inactive")
if svc.DaemonScope == snap.UserDaemon {
current = "-"
} else if svc.Active {
current = i18n.G("active")
}
fmt.Fprintf(w, "%s.%s\t%s\t%s\t%s\n", svc.Snap, svc.Name, startup, current, clientutil.ClientAppInfoNotes(&svc))
}
return nil
}<|fim▁end|> | |
<|file_name|>HeroContainer.js<|end_file_name|><|fim▁begin|>import React from 'react'
import { Hero } from '../../components'
<|fim▁hole|>
export default HeroContainer<|fim▁end|> | const HeroContainer = () => (
<Hero />
) |
<|file_name|>camera_pulse.py<|end_file_name|><|fim▁begin|>"""Run the interactive pulse program.
Keys:
- Escape - Exit the program
- Space - Update program image
- C - Calibrate the image again
"""
import time
import cv2
from pulse_programming import PulseField
from camera_calibration import Calibration
window = "Camera Pulse Programming"
cv2.namedWindow("Threshold", cv2.WINDOW_AUTOSIZE)<|fim▁hole|>
def calibrate():
calibration.record_points(20)
calibration.show_area_in_camera()
print("Please move the window to fill the screen and press any key.")
calibration.wait_for_key_press()
calibrate()
def update_pulse_program_from_camera():
calibration.fill_white()
cv2.waitKey(1)
image = calibration.warp_camera_in_projection()
cv2.imshow("Capture", image)
pulse_field.set_program_image(image, blue_threshold=0.57)
pulse_field = PulseField()
#pulse_field.DELATION_ITERATIONS = 4
#pulse_field.EROSION_ITERATIONS = 3
update_pulse_program_from_camera()
while True:
key = cv2.waitKey(1)
if key == 27: # Escape
exit(0)
elif key == 32: # Space
update_pulse_program_from_camera()
elif key == ord("c"): # Calibrate
calibrate()
t = time.time()
pulse_field.pulse()
print("duration:", time.time() - t)
cv2.imshow(window, pulse_field.get_pulse_gray())<|fim▁end|> | cv2.namedWindow("Capture", cv2.WINDOW_AUTOSIZE)
calibration = Calibration((1024, 768), window_name=window) |
<|file_name|>tokens.py<|end_file_name|><|fim▁begin|>class Token(object):
def __init__(self, start_mark, end_mark):
self.start_mark = start_mark
self.end_mark = end_mark
def __repr__(self):
attributes = [key for key in self.__dict__
if not key.endswith('_mark')]<|fim▁hole|> attributes.sort()
arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
for key in attributes])
return '%s(%s)' % (self.__class__.__name__, arguments)
#class BOMToken(Token):
# id = '<byte order mark>'
class DirectiveToken(Token):
id = '<directive>'
def __init__(self, name, value, start_mark, end_mark):
self.name = name
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
class DocumentStartToken(Token):
id = '<document start>'
class DocumentEndToken(Token):
id = '<document end>'
class StreamStartToken(Token):
id = '<stream start>'
def __init__(self, start_mark=None, end_mark=None,
encoding=None):
self.start_mark = start_mark
self.end_mark = end_mark
self.encoding = encoding
class StreamEndToken(Token):
id = '<stream end>'
class BlockSequenceStartToken(Token):
id = '<block sequence start>'
class BlockMappingStartToken(Token):
id = '<block mapping start>'
class BlockEndToken(Token):
id = '<block end>'
class FlowSequenceStartToken(Token):
id = '['
class FlowMappingStartToken(Token):
id = '{'
class FlowSequenceEndToken(Token):
id = ']'
class FlowMappingEndToken(Token):
id = '}'
class KeyToken(Token):
id = '?'
class ValueToken(Token):
id = ':'
class BlockEntryToken(Token):
id = '-'
class FlowEntryToken(Token):
id = ','
class AliasToken(Token):
id = '<alias>'
def __init__(self, value, start_mark, end_mark):
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
class AnchorToken(Token):
id = '<anchor>'
def __init__(self, value, start_mark, end_mark):
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
class TagToken(Token):
id = '<tag>'
def __init__(self, value, start_mark, end_mark):
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
class ScalarToken(Token):
id = '<scalar>'
def __init__(self, value, plain, start_mark, end_mark, style=None):
self.value = value
self.plain = plain
self.start_mark = start_mark
self.end_mark = end_mark
self.style = style<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2011 Sebastien Maccagnoni-Munch<|fim▁hole|>#
# Omoma 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, version 3.
#
# Omoma is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Omoma. If not, see <http://www.gnu.org/licenses/>.
"""
Django template tags for Omoma
"""<|fim▁end|> | #
# This file is part of Omoma. |
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from os import chmod
from spack import *
class Tbl2asn(Package):
"""Tbl2asn is a command-line program that automates the creation of
sequence records for submission to GenBank."""
homepage = "https://www.ncbi.nlm.nih.gov/genbank/tbl2asn2/"
version('2020-03-01', sha256='7cc1119d3cfcbbffdbd4ecf33cef8bbdd44fc5625c72976bee08b1157625377e')
def url_for_version(self, ver):
return "https://ftp.ncbi.nih.gov/toolbox/ncbi_tools/converters/by_program/tbl2asn/linux.tbl2asn.gz"
def install(self, spec, prefix):
mkdirp(prefix.bin)
install('../linux.tbl2asn', prefix.bin.tbl2asn)<|fim▁hole|> chmod(prefix.bin.tbl2asn, 0o775)<|fim▁end|> | |
<|file_name|>Consumer.java<|end_file_name|><|fim▁begin|>/**
* Copyright 2002-2016 xiaoyuepeng
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.<|fim▁hole|> * 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.
*
*
* @author xiaoyuepeng <[email protected]>
*/
package com.xyp260466.dubbo.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Created by xyp on 16-5-9.
*/
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Documented
public @interface Consumer {
String value() default "";
}<|fim▁end|> | |
<|file_name|>query-parameters-v2.spec.ts<|end_file_name|><|fim▁begin|>import { asUrlQueryString } from './query-parameters-v2';
describe('asUrlQueryString', () => {
it('should create a empty query', () => {
expect(asUrlQueryString({})).toBe('');
});
it('should create a query string with one argument', () => {
expect(asUrlQueryString({ foo: 'bar' })).toBe('?foo=bar');
});
it('should create a query string with multiple argument', () => {
expect(asUrlQueryString({ foo1: 'bar1', foo2: 'bar2' })).toBe('?foo1=bar1&foo2=bar2');
});
it('should expand any array argument', () => {
expect(asUrlQueryString({ foo: ['bar1', 'bar2'] })).toBe('?foo=bar1&foo=bar2');
});
it('should skip undefined values', () => {
expect(asUrlQueryString({ foo: 'bar', foo1: undefined })).toBe('?foo=bar');
});
it('should skip undefined values in array', () => {
expect(asUrlQueryString({ foo: ['bar1', undefined, 'bar2'] })).toBe('?foo=bar1&foo=bar2');
});<|fim▁hole|><|fim▁end|> | }); |
<|file_name|>ApplicationInterface.java<|end_file_name|><|fim▁begin|>/*
*
* 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.
*
*/
package org.apache.airavata.registry.core.app.catalog.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.sql.Timestamp;
@Entity
@Table(name = "APPLICATION_INTERFACE")
public class ApplicationInterface implements Serializable {
@Id
@Column(name = "INTERFACE_ID")
private String interfaceID;
@Column(name = "APPLICATION_NAME")
private String appName;
@Column(name = "APPLICATION_DESCRIPTION")
private String appDescription;<|fim▁hole|> @Column(name = "GATEWAY_ID")
private String gatewayId;
@Column(name = "ARCHIVE_WORKING_DIRECTORY")
private boolean archiveWorkingDirectory;
@Column(name = "HAS_OPTIONAL_FILE_INPUTS")
private boolean hasOptionalFileInputs;
@Column(name = "UPDATE_TIME")
private Timestamp updateTime;
public String getGatewayId() {
return gatewayId;
}
public void setGatewayId(String gatewayId) {
this.gatewayId = gatewayId;
}
public boolean isArchiveWorkingDirectory() {
return archiveWorkingDirectory;
}
public void setArchiveWorkingDirectory(boolean archiveWorkingDirectory) {
this.archiveWorkingDirectory = archiveWorkingDirectory;
}
public Timestamp getCreationTime() {
return creationTime;
}
public void setCreationTime(Timestamp creationTime) {
this.creationTime = creationTime;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getInterfaceID() {
return interfaceID;
}
public void setInterfaceID(String interfaceID) {
this.interfaceID = interfaceID;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppDescription() {
return appDescription;
}
public void setAppDescription(String appDescription) {
this.appDescription = appDescription;
}
public boolean isHasOptionalFileInputs() {
return hasOptionalFileInputs;
}
public void setHasOptionalFileInputs(boolean hasOptionalFileInputs) {
this.hasOptionalFileInputs = hasOptionalFileInputs;
}
}<|fim▁end|> | @Column(name = "CREATION_TIME")
private Timestamp creationTime; |
<|file_name|>case_label.cc<|end_file_name|><|fim▁begin|>// { dg-do compile }
// { dg-options "-Wall" { target *-*-* } }
// -*- C++ -*-
// Copyright (C) 2004-2014 Free Software Foundation, Inc.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3, or (at
// your option) any later version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING3. If not see<|fim▁hole|>// Benjamin Kosnik <[email protected]>
#include <ios>
// PR libstdc++/17922
// -Wall
typedef std::ios_base::seekdir test_type;
void
case_labels(test_type b)
{
switch (b)
{
case std::ios_base::beg:
break;
case std::ios_base::cur:
break;
case std::ios_base::end:
break;
case std::_S_ios_fmtflags_end:
break;
}
}<|fim▁end|> | // <http://www.gnu.org/licenses/>.
|
<|file_name|>c_str.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
C-string manipulation and management
This modules provides the basic methods for creating and manipulating
null-terminated strings for use with FFI calls (back to C). Most C APIs require
that the string being passed to them is null-terminated, and by default rust's
string types are *not* null terminated.
The other problem with translating Rust strings to C strings is that Rust
strings can validly contain a null-byte in the middle of the string (0 is a
valid unicode codepoint). This means that not all Rust strings can actually be
translated to C strings.
# Creation of a C string
A C string is managed through the `CString` type defined in this module. It
"owns" the internal buffer of characters and will automatically deallocate the
buffer when the string is dropped. The `ToCStr` trait is implemented for `&str`
and `&[u8]`, but the conversions can fail due to some of the limitations
explained above.
This also means that currently whenever a C string is created, an allocation
must be performed to place the data elsewhere (the lifetime of the C string is
not tied to the lifetime of the original string/data buffer). If C strings are
heavily used in applications, then caching may be advisable to prevent
unnecessary amounts of allocations.
An example of creating and using a C string would be:
```rust
extern crate libc;
extern {
fn puts(s: *libc::c_char);
}
fn main() {
let my_string = "Hello, world!";
// Allocate the C string with an explicit local that owns the string. The
// `c_buffer` pointer will be deallocated when `my_c_string` goes out of scope.
let my_c_string = my_string.to_c_str();
my_c_string.with_ref(|c_buffer| {
unsafe { puts(c_buffer); }
});
// Don't save off the allocation of the C string, the `c_buffer` will be
// deallocated when this block returns!
my_string.with_c_str(|c_buffer| {
unsafe { puts(c_buffer); }
});
}
```
*/
use cast;
use container::Container;
use iter::{Iterator, range};
use libc;
use kinds::marker;
use ops::Drop;
use cmp::Eq;
use clone::Clone;
use mem;
use option::{Option, Some, None};
use ptr::RawPtr;
use ptr;
use str::StrSlice;
use str;
use slice::{ImmutableVector, MutableVector};
use slice;
use rt::global_heap::malloc_raw;
use raw::Slice;
/// The representation of a C String.
///
/// This structure wraps a `*libc::c_char`, and will automatically free the
/// memory it is pointing to when it goes out of scope.
pub struct CString {
buf: *libc::c_char,
owns_buffer_: bool,
}
impl Clone for CString {
/// Clone this CString into a new, uniquely owned CString. For safety
/// reasons, this is always a deep clone, rather than the usual shallow
/// clone.
fn clone(&self) -> CString {
if self.buf.is_null() {
CString { buf: self.buf, owns_buffer_: self.owns_buffer_ }
} else {
let len = self.len() + 1;
let buf = unsafe { malloc_raw(len) } as *mut libc::c_char;
unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, len); }
CString { buf: buf as *libc::c_char, owns_buffer_: true }
}
}
}
impl Eq for CString {
fn eq(&self, other: &CString) -> bool {
if self.buf as uint == other.buf as uint {
true
} else if self.buf.is_null() || other.buf.is_null() {
false
} else {
unsafe {
libc::strcmp(self.buf, other.buf) == 0
}
}
}
}
impl CString {
/// Create a C String from a pointer.
pub unsafe fn new(buf: *libc::c_char, owns_buffer: bool) -> CString {
CString { buf: buf, owns_buffer_: owns_buffer }
}
/// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
/// Any ownership of the buffer by the `CString` wrapper is forgotten.
pub unsafe fn unwrap(self) -> *libc::c_char {
let mut c_str = self;
c_str.owns_buffer_ = false;
c_str.buf
}
/// Calls a closure with a reference to the underlying `*libc::c_char`.
///
/// # Failure
///
/// Fails if the CString is null.
pub fn with_ref<T>(&self, f: |*libc::c_char| -> T) -> T {
if self.buf.is_null() { fail!("CString is null!"); }
f(self.buf)
}
/// Calls a closure with a mutable reference to the underlying `*libc::c_char`.
///
/// # Failure
///
/// Fails if the CString is null.
pub fn with_mut_ref<T>(&mut self, f: |*mut libc::c_char| -> T) -> T {
if self.buf.is_null() { fail!("CString is null!"); }
f(unsafe { cast::transmute_mut_unsafe(self.buf) })
}
/// Returns true if the CString is a null.
pub fn is_null(&self) -> bool {
self.buf.is_null()
}
/// Returns true if the CString is not null.
pub fn is_not_null(&self) -> bool {
self.buf.is_not_null()
}
/// Returns whether or not the `CString` owns the buffer.
pub fn owns_buffer(&self) -> bool {
self.owns_buffer_
}
/// Converts the CString into a `&[u8]` without copying.
/// Includes the terminating NUL byte.
///
/// # Failure
///
/// Fails if the CString is null.
#[inline]
pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
if self.buf.is_null() { fail!("CString is null!"); }
unsafe {
cast::transmute(Slice { data: self.buf, len: self.len() + 1 })
}
}
/// Converts the CString into a `&[u8]` without copying.
/// Does not include the terminating NUL byte.
///
/// # Failure
///
/// Fails if the CString is null.
#[inline]
pub fn as_bytes_no_nul<'a>(&'a self) -> &'a [u8] {
if self.buf.is_null() { fail!("CString is null!"); }
unsafe {
cast::transmute(Slice { data: self.buf, len: self.len() })
}
}
/// Converts the CString into a `&str` without copying.
/// Returns None if the CString is not UTF-8.
///
/// # Failure
///
/// Fails if the CString is null.
#[inline]
pub fn as_str<'a>(&'a self) -> Option<&'a str> {
let buf = self.as_bytes_no_nul();
str::from_utf8(buf)
}
/// Return a CString iterator.
///
/// # Failure
///
/// Fails if the CString is null.
pub fn iter<'a>(&'a self) -> CChars<'a> {
if self.buf.is_null() { fail!("CString is null!"); }
CChars {
ptr: self.buf,
marker: marker::ContravariantLifetime,
}
}
}
impl Drop for CString {
fn drop(&mut self) {
if self.owns_buffer_ {
unsafe {
libc::free(self.buf as *mut libc::c_void)
}
}
}
}
impl Container for CString {
/// Return the number of bytes in the CString (not including the NUL terminator).
///
/// # Failure
///
/// Fails if the CString is null.
#[inline]
fn len(&self) -> uint {
if self.buf.is_null() { fail!("CString is null!"); }
unsafe {
ptr::position(self.buf, |c| *c == 0)
}
}
}
/// A generic trait for converting a value to a CString.
pub trait ToCStr {
/// Copy the receiver into a CString.
///
/// # Failure
///
/// Fails the task if the receiver has an interior null.
fn to_c_str(&self) -> CString;
/// Unsafe variant of `to_c_str()` that doesn't check for nulls.
unsafe fn to_c_str_unchecked(&self) -> CString;
/// Work with a temporary CString constructed from the receiver.
/// The provided `*libc::c_char` will be freed immediately upon return.
///
/// # Example
///
/// ```rust
/// extern crate libc;
///
/// fn main() {
/// let s = "PATH".with_c_str(|path| unsafe {
/// libc::getenv(path)
/// });
/// }
/// ```
///
/// # Failure
///
/// Fails the task if the receiver has an interior null.
#[inline]
fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
self.to_c_str().with_ref(f)
}
/// Unsafe variant of `with_c_str()` that doesn't check for nulls.
#[inline]
unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
self.to_c_str_unchecked().with_ref(f)
}
}
impl<'a> ToCStr for &'a str {
#[inline]
fn to_c_str(&self) -> CString {
self.as_bytes().to_c_str()
}
#[inline]
unsafe fn to_c_str_unchecked(&self) -> CString {
self.as_bytes().to_c_str_unchecked()
}
#[inline]
fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
self.as_bytes().with_c_str(f)
}
#[inline]
unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
self.as_bytes().with_c_str_unchecked(f)
}
}
// The length of the stack allocated buffer for `vec.with_c_str()`
static BUF_LEN: uint = 128;
impl<'a> ToCStr for &'a [u8] {
fn to_c_str(&self) -> CString {
let mut cs = unsafe { self.to_c_str_unchecked() };
cs.with_mut_ref(|buf| check_for_null(*self, buf));
cs
}
unsafe fn to_c_str_unchecked(&self) -> CString {
let self_len = self.len();
let buf = malloc_raw(self_len + 1);
ptr::copy_memory(buf, self.as_ptr(), self_len);
*buf.offset(self_len as int) = 0;
CString::new(buf as *libc::c_char, true)
}
fn with_c_str<T>(&self, f: |*libc::c_char| -> T) -> T {
unsafe { with_c_str(*self, true, f) }
}
unsafe fn with_c_str_unchecked<T>(&self, f: |*libc::c_char| -> T) -> T {
with_c_str(*self, false, f)
}
}
// Unsafe function that handles possibly copying the &[u8] into a stack array.
unsafe fn with_c_str<T>(v: &[u8], checked: bool, f: |*libc::c_char| -> T) -> T {
if v.len() < BUF_LEN {
let mut buf: [u8, .. BUF_LEN] = mem::uninit();
slice::bytes::copy_memory(buf, v);
buf[v.len()] = 0;
let buf = buf.as_mut_ptr();
if checked {
check_for_null(v, buf as *mut libc::c_char);
}
f(buf as *libc::c_char)
} else if checked {
v.to_c_str().with_ref(f)
} else {
v.to_c_str_unchecked().with_ref(f)
}
}
#[inline]
fn check_for_null(v: &[u8], buf: *mut libc::c_char) {
for i in range(0, v.len()) {
unsafe {
let p = buf.offset(i as int);
assert!(*p != 0);
}
}
}
/// External iterator for a CString's bytes.
///
/// Use with the `std::iter` module.
pub struct CChars<'a> {
ptr: *libc::c_char,
marker: marker::ContravariantLifetime<'a>,
}
impl<'a> Iterator<libc::c_char> for CChars<'a> {
fn next(&mut self) -> Option<libc::c_char> {
let ch = unsafe { *self.ptr };
if ch == 0 {
None
} else {
self.ptr = unsafe { self.ptr.offset(1) };
Some(ch)
}
}
}
/// Parses a C "multistring", eg windows env values or
/// the req->ptr result in a uv_fs_readdir() call.
///
/// Optionally, a `count` can be passed in, limiting the
/// parsing to only being done `count`-times.
///
/// The specified closure is invoked with each string that
/// is found, and the number of strings found is returned.
pub unsafe fn from_c_multistring(buf: *libc::c_char,
count: Option<uint>,
f: |&CString|) -> uint {
let mut curr_ptr: uint = buf as uint;
let mut ctr = 0;
let (limited_count, limit) = match count {
Some(limit) => (true, limit),
None => (false, 0)
};
while ((limited_count && ctr < limit) || !limited_count)
&& *(curr_ptr as *libc::c_char) != 0 as libc::c_char {
let cstr = CString::new(curr_ptr as *libc::c_char, false);
f(&cstr);
curr_ptr += cstr.len() + 1;
ctr += 1;
}
return ctr;
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::*;
use libc;
use ptr;
use str::StrSlice;
#[test]
fn test_str_multistring_parsing() {
unsafe {
let input = bytes!("zero", "\x00", "one", "\x00", "\x00");
let ptr = input.as_ptr();
let expected = ["zero", "one"];
let mut it = expected.iter();
let result = from_c_multistring(ptr as *libc::c_char, None, |c| {
let cbytes = c.as_bytes_no_nul();
assert_eq!(cbytes, it.next().unwrap().as_bytes());
});
assert_eq!(result, 2);
assert!(it.next().is_none());
}
}
#[test]
fn test_str_to_c_str() {
"".to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*buf.offset(0), 0);
}
});
"hello".to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*buf.offset(0), 'h' as libc::c_char);
assert_eq!(*buf.offset(1), 'e' as libc::c_char);
assert_eq!(*buf.offset(2), 'l' as libc::c_char);
assert_eq!(*buf.offset(3), 'l' as libc::c_char);
assert_eq!(*buf.offset(4), 'o' as libc::c_char);
assert_eq!(*buf.offset(5), 0);
}
})
}
#[test]
fn test_vec_to_c_str() {
let b: &[u8] = [];
b.to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*buf.offset(0), 0);
}
});
let _ = bytes!("hello").to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*buf.offset(0), 'h' as libc::c_char);
assert_eq!(*buf.offset(1), 'e' as libc::c_char);
assert_eq!(*buf.offset(2), 'l' as libc::c_char);
assert_eq!(*buf.offset(3), 'l' as libc::c_char);
assert_eq!(*buf.offset(4), 'o' as libc::c_char);
assert_eq!(*buf.offset(5), 0);
}
});
let _ = bytes!("foo", 0xff).to_c_str().with_ref(|buf| {
unsafe {
assert_eq!(*buf.offset(0), 'f' as libc::c_char);
assert_eq!(*buf.offset(1), 'o' as libc::c_char);
assert_eq!(*buf.offset(2), 'o' as libc::c_char);
assert_eq!(*buf.offset(3), 0xff as i8);
assert_eq!(*buf.offset(4), 0);
}
});
}
#[test]
fn test_is_null() {
let c_str = unsafe { CString::new(ptr::null(), false) };
assert!(c_str.is_null());
assert!(!c_str.is_not_null());
}
#[test]
fn test_unwrap() {
let c_str = "hello".to_c_str();
unsafe { libc::free(c_str.unwrap() as *mut libc::c_void) }
}
#[test]
fn test_with_ref() {
let c_str = "hello".to_c_str();
let len = unsafe { c_str.with_ref(|buf| libc::strlen(buf)) };
assert!(!c_str.is_null());
assert!(c_str.is_not_null());
assert_eq!(len, 5);
}
#[test]
#[should_fail]
fn test_with_ref_empty_fail() {
let c_str = unsafe { CString::new(ptr::null(), false) };
c_str.with_ref(|_| ());
}
#[test]
fn test_iterator() {
let c_str = "".to_c_str();
let mut iter = c_str.iter();
assert_eq!(iter.next(), None);
let c_str = "hello".to_c_str();
let mut iter = c_str.iter();
assert_eq!(iter.next(), Some('h' as libc::c_char));
assert_eq!(iter.next(), Some('e' as libc::c_char));
assert_eq!(iter.next(), Some('l' as libc::c_char));
assert_eq!(iter.next(), Some('l' as libc::c_char));
assert_eq!(iter.next(), Some('o' as libc::c_char));
assert_eq!(iter.next(), None);
}
#[test]
fn test_to_c_str_fail() {
use task;
assert!(task::try(proc() { "he\x00llo".to_c_str() }).is_err());
}
#[test]
fn test_to_c_str_unchecked() {
unsafe {
"he\x00llo".to_c_str_unchecked().with_ref(|buf| {
assert_eq!(*buf.offset(0), 'h' as libc::c_char);
assert_eq!(*buf.offset(1), 'e' as libc::c_char);
assert_eq!(*buf.offset(2), 0);
assert_eq!(*buf.offset(3), 'l' as libc::c_char);
assert_eq!(*buf.offset(4), 'l' as libc::c_char);
assert_eq!(*buf.offset(5), 'o' as libc::c_char);
assert_eq!(*buf.offset(6), 0);
})
}
}
#[test]
fn test_as_bytes() {
let c_str = "hello".to_c_str();
assert_eq!(c_str.as_bytes(), bytes!("hello", 0));
let c_str = "".to_c_str();
assert_eq!(c_str.as_bytes(), bytes!(0));
let c_str = bytes!("foo", 0xff).to_c_str();
assert_eq!(c_str.as_bytes(), bytes!("foo", 0xff, 0));
}
#[test]
fn test_as_bytes_no_nul() {
let c_str = "hello".to_c_str();
assert_eq!(c_str.as_bytes_no_nul(), bytes!("hello"));
let c_str = "".to_c_str();
let exp: &[u8] = [];
assert_eq!(c_str.as_bytes_no_nul(), exp);
let c_str = bytes!("foo", 0xff).to_c_str();
assert_eq!(c_str.as_bytes_no_nul(), bytes!("foo", 0xff));
}
#[test]
#[should_fail]
fn test_as_bytes_fail() {
let c_str = unsafe { CString::new(ptr::null(), false) };
c_str.as_bytes();
}
#[test]
#[should_fail]
fn test_as_bytes_no_nul_fail() {
let c_str = unsafe { CString::new(ptr::null(), false) };
c_str.as_bytes_no_nul();
}
#[test]
fn test_as_str() {
let c_str = "hello".to_c_str();
assert_eq!(c_str.as_str(), Some("hello"));
let c_str = "".to_c_str();
assert_eq!(c_str.as_str(), Some(""));
let c_str = bytes!("foo", 0xff).to_c_str();
assert_eq!(c_str.as_str(), None);
}<|fim▁hole|> #[should_fail]
fn test_as_str_fail() {
let c_str = unsafe { CString::new(ptr::null(), false) };
c_str.as_str();
}
#[test]
#[should_fail]
fn test_len_fail() {
let c_str = unsafe { CString::new(ptr::null(), false) };
c_str.len();
}
#[test]
#[should_fail]
fn test_iter_fail() {
let c_str = unsafe { CString::new(ptr::null(), false) };
c_str.iter();
}
#[test]
fn test_clone() {
let a = "hello".to_c_str();
let b = a.clone();
assert!(a == b);
}
#[test]
fn test_clone_noleak() {
fn foo(f: |c: &CString|) {
let s = "test".to_owned();
let c = s.to_c_str();
// give the closure a non-owned CString
let mut c_ = c.with_ref(|c| unsafe { CString::new(c, false) } );
f(&c_);
// muck with the buffer for later printing
c_.with_mut_ref(|c| unsafe { *c = 'X' as libc::c_char } );
}
let mut c_: Option<CString> = None;
foo(|c| {
c_ = Some(c.clone());
c.clone();
// force a copy, reading the memory
c.as_bytes().to_owned();
});
let c_ = c_.unwrap();
// force a copy, reading the memory
c_.as_bytes().to_owned();
}
#[test]
fn test_clone_eq_null() {
let x = unsafe { CString::new(ptr::null(), false) };
let y = x.clone();
assert!(x == y);
}
}
#[cfg(test)]
mod bench {
extern crate test;
use self::test::Bencher;
use libc;
use prelude::*;
#[inline]
fn check(s: &str, c_str: *libc::c_char) {
let s_buf = s.as_ptr();
for i in range(0, s.len()) {
unsafe {
assert_eq!(
*s_buf.offset(i as int) as libc::c_char,
*c_str.offset(i as int));
}
}
}
static s_short: &'static str = "Mary";
static s_medium: &'static str = "Mary had a little lamb";
static s_long: &'static str = "\
Mary had a little lamb, Little lamb
Mary had a little lamb, Little lamb
Mary had a little lamb, Little lamb
Mary had a little lamb, Little lamb
Mary had a little lamb, Little lamb
Mary had a little lamb, Little lamb";
fn bench_to_str(b: &mut Bencher, s: &str) {
b.iter(|| {
let c_str = s.to_c_str();
c_str.with_ref(|c_str_buf| check(s, c_str_buf))
})
}
#[bench]
fn bench_to_c_str_short(b: &mut Bencher) {
bench_to_str(b, s_short)
}
#[bench]
fn bench_to_c_str_medium(b: &mut Bencher) {
bench_to_str(b, s_medium)
}
#[bench]
fn bench_to_c_str_long(b: &mut Bencher) {
bench_to_str(b, s_long)
}
fn bench_to_c_str_unchecked(b: &mut Bencher, s: &str) {
b.iter(|| {
let c_str = unsafe { s.to_c_str_unchecked() };
c_str.with_ref(|c_str_buf| check(s, c_str_buf))
})
}
#[bench]
fn bench_to_c_str_unchecked_short(b: &mut Bencher) {
bench_to_c_str_unchecked(b, s_short)
}
#[bench]
fn bench_to_c_str_unchecked_medium(b: &mut Bencher) {
bench_to_c_str_unchecked(b, s_medium)
}
#[bench]
fn bench_to_c_str_unchecked_long(b: &mut Bencher) {
bench_to_c_str_unchecked(b, s_long)
}
fn bench_with_c_str(b: &mut Bencher, s: &str) {
b.iter(|| {
s.with_c_str(|c_str_buf| check(s, c_str_buf))
})
}
#[bench]
fn bench_with_c_str_short(b: &mut Bencher) {
bench_with_c_str(b, s_short)
}
#[bench]
fn bench_with_c_str_medium(b: &mut Bencher) {
bench_with_c_str(b, s_medium)
}
#[bench]
fn bench_with_c_str_long(b: &mut Bencher) {
bench_with_c_str(b, s_long)
}
fn bench_with_c_str_unchecked(b: &mut Bencher, s: &str) {
b.iter(|| {
unsafe {
s.with_c_str_unchecked(|c_str_buf| check(s, c_str_buf))
}
})
}
#[bench]
fn bench_with_c_str_unchecked_short(b: &mut Bencher) {
bench_with_c_str_unchecked(b, s_short)
}
#[bench]
fn bench_with_c_str_unchecked_medium(b: &mut Bencher) {
bench_with_c_str_unchecked(b, s_medium)
}
#[bench]
fn bench_with_c_str_unchecked_long(b: &mut Bencher) {
bench_with_c_str_unchecked(b, s_long)
}
}<|fim▁end|> |
#[test] |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># vim:ts=4:sts=4:sw=4:expandtab
"""Package. Manages event queues.
Writing event-driven code
-------------------------
Event-driven procedures should be written as python coroutines (extended generators).
To call the event API, yield an instance of the appropriate command. You can use
sub-procedures - just yield the appropriate generator (a minor nuisance is that you
cannot have such sub-procedure return a value).
Example
-------
.. code:: python
from satori.events import *
def countdown():
queue = QueueId('any string will do')
mapping = yield Map({}, queue)
yield Attach(queue)
yield Send(Event(left=10))
while True:
q, event = yield Receive()
if event.left == 0:
break
event.left -= 1
yield Send(event)
yield Unmap(mapping)
yield Detach(queue)
"""
from .api import Event, MappingId, QueueId
from .protocol import Attach, Detach
from .protocol import Map, Unmap
from .protocol import Send, Receive
from .protocol import KeepAlive, Disconnect, ProtocolError
from .api import Manager
from .master import Master
from .slave import Slave<|fim▁hole|>__all__ = (
'Event', 'MappingId', 'QueueId',
'Attach', 'Detach',
'Map', 'Unmap',
'Send', 'Receive',
'KeepAlive', 'ProtocolError',
'Master', 'Slave',
)<|fim▁end|> | from .client2 import Client2
from .slave2 import Slave2
|
<|file_name|>makenugetpackagetask.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os
import ntpath
import glob
from pyhammer.tasks.taskbase import TaskBase
from pyhammer.utils import execProg
class MakeNugetPackageTask(TaskBase):
"""Make Nuget Package Task"""<|fim▁hole|> super(MakeNugetPackageTask, self).__init__()
self.csProjectPath = csProjectPath
self.solutionDir = solutionDir
self.tempDir = tempDir
self.publishDir = publishDir
self.visualStudioVersion = visualStudioVersion
def do( self ):
self.reporter.message( "MAKING NUGET PACKAGE FROM: %s" % ntpath.basename(self.csProjectPath) )
result = execProg("msbuild.exe \"%s\" /t:Rebuild /p:Configuration=Release;VisualStudioVersion=%s" % ( self.csProjectPath, self.visualStudioVersion ), self.reporter, self.solutionDir)
if(not result == 0):
return False
result = execProg("nuget.exe pack \"%s\" -IncludeReferencedProjects -prop Configuration=Release -OutputDirectory \"%s\"" % (self.csProjectPath, self.tempDir), self.reporter)
if(not result == 0):
return False
if(self.publishDir is not None):
os.chdir(self.tempDir)
files = glob.glob("*.nupkg")
result = execProg("nuget.exe push \"%s\" -Source \"%s\"" % (files[0], self.publishDir), self.reporter)
os.remove(files[0])
if(not result == 0):
return False
return True<|fim▁end|> |
def __init__( self, csProjectPath, solutionDir, tempDir, publishDir, visualStudioVersion = "12.0" ): |
<|file_name|>TrackSystem.cpp<|end_file_name|><|fim▁begin|>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle.
// TODO: read in subsystem data w/ JSON input files
//
// =============================================================================
#include <cstdio>
#include <sstream>
#include "subsys/trackSystem/TrackSystem.h"
namespace chrono {
// -----------------------------------------------------------------------------
// Static variables
// idler, right side
const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);
// drive gear, right side
const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0.2447); // relative to local csys
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);
// suspension
const int TrackSystem::m_numSuspensions = 5;
TrackSystem::TrackSystem(const std::string& name, int track_idx, const double idler_preload)
: m_track_idx(track_idx), m_name(name), m_idler_preload(idler_preload) {
// FILE* fp = fopen(filename.c_str(), "r");
// char readBuffer[65536];
// fclose(fp);
Create(track_idx);
}
// Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems()
// TODO: replace hard-coded junk with JSON input files for each subsystem
void TrackSystem::Create(int track_idx) {
/*
// read idler info
assert(d.HasMember("Idler"));
m_idlerMass = d["Idler"]["Mass"].GetDouble();
m_idlerPos = loadVector(d["Idler"]["Location"]);
m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
m_idlerWidth = d["Spindle"]["Width"].GetDouble();
m_idler_K = d["Idler"]["SpringK"].GetDouble();
m_idler_C = d["Idler"]["SpringC"].GetDouble();
*/
/*
// Read Drive Gear data
assert(d.HasMember("Drive Gear"));
assert(d["Drive Gear"].IsObject());
m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
m_gearPos = loadVector(d["Drive Gear"]["Location"]);
m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
m_gearWidth = d["Drive Gear"]["Width"].GetDouble();
// Read Suspension data
assert(d.HasMember("Suspension"));
assert(d["Suspension"].IsObject());
assert(d["Suspension"]["Location"].IsArray() );
m_suspensionFilename = d["Suspension"]["Input File"].GetString();
m_NumSuspensions = d["Suspension"]["Location"].Size();
*/
m_suspensions.resize(m_numSuspensions);
m_suspensionLocs.resize(m_numSuspensions);
// hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket
m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0);
m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0);
// trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position
m_suspensionLocs[2] = ChVector<>(0, 0, 0);
m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0);
m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0);
/*
for(int j = 0; j < m_numSuspensions; j++)
{
m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
}
// Read Track Chain data
assert(d.HasMember("Track Chain"));
assert(d["Track Chain"].IsObject());
m_trackChainFilename = d["Track Chain"]["Input File"].GetString()
*/
// create the various subsystems, from the hardcoded static variables in each subsystem class
BuildSubsystems();
}
void TrackSystem::BuildSubsystems() {
std::stringstream gearName;
gearName << "drive gear " << m_track_idx;
// build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES
m_driveGear = ChSharedPtr<DriveGear>(new DriveGear(gearName.str(), VisualizationType::Mesh,
// CollisionType::Primitives) );
// VisualizationType::Primitives,
CollisionType::CallbackFunction));
std::stringstream idlerName;
idlerName << "idler " << m_track_idx;
m_idler =
ChSharedPtr<IdlerSimple>(new IdlerSimple(idlerName.str(), VisualizationType::Mesh, CollisionType::Primitives));
std::stringstream chainname;
chainname << "chain " << m_track_idx;
m_chain = ChSharedPtr<TrackChain>(new TrackChain(chainname.str(),
// VisualizationType::Primitives,
VisualizationType::CompoundPrimitives, CollisionType::Primitives));
// CollisionType::CompoundPrimitives) );
// build suspension/road wheel subsystems
for (int i = 0; i < m_numSuspensions; i++) {
std::stringstream susp_name;
susp_name << "suspension " << i << ", chain " << m_track_idx;
m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(
new TorsionArmSuspension(susp_name.str(), VisualizationType::Primitives, CollisionType::Primitives,
0, i ));
}
}
void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
const ChVector<>& local_pos,
ChTrackVehicle* vehicle,
double pin_damping) {
m_local_pos = local_pos;
m_gearPosRel = m_gearPos;
m_idlerPosRel = m_idlerPos;
// if we're on the left side of the vehicle, switch lateral z-axis on all relative positions
if (m_local_pos.z < 0) {
m_gearPosRel.z *= -1;
m_idlerPosRel.z *= -1;
}
// Create list of the center location of the rolling elements and their clearance.
// Clearance is a sphere shaped envelope at each center location, where it can
// be guaranteed that the track chain geometry will not penetrate the sphere.
std::vector<ChVector<> > rolling_elem_locs; // w.r.t. chassis ref. frame
std::vector<double> clearance; // 1 per rolling elem
std::vector<ChVector<> > rolling_elem_spin_axis; /// w.r.t. abs. frame
// initialize 1 of each of the following subsystems.
// will use the chassis ref frame to do the transforms, since the TrackSystem
// local ref. frame has same rot (just difference in position)
// NOTE: move drive Gear Init() AFTER the chain of shoes is created, since
// need the list of shoes to be passed in to create custom collision w/ gear
// HOWEVER, still add the info to the rolling element lists passed into TrackChain Init().
// drive sprocket is First added to the lists passed into TrackChain Init()
rolling_elem_locs.push_back(m_local_pos + Get_gearPosRel());
clearance.push_back(m_driveGear->GetRadius());
rolling_elem_spin_axis.push_back(m_driveGear->GetBody()->GetRot().GetZaxis());
// initialize the torsion arm suspension subsystems
for (int s_idx = 0; s_idx < m_suspensionLocs.size(); s_idx++) {
m_suspensions[s_idx]->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + m_suspensionLocs[s_idx], QUNIT));<|fim▁hole|> rolling_elem_locs.push_back(m_local_pos + m_suspensionLocs[s_idx] + m_suspensions[s_idx]->GetWheelPosRel());
clearance.push_back(m_suspensions[s_idx]->GetWheelRadius());
rolling_elem_spin_axis.push_back(m_suspensions[s_idx]->GetWheelBody()->GetRot().GetZaxis());
}
// last control point: the idler body
m_idler->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + Get_idlerPosRel(), Q_from_AngAxis(CH_C_PI, VECT_Z)),
m_idler_preload);
// add to the lists passed into the track chain Init()
rolling_elem_locs.push_back(m_local_pos + Get_idlerPosRel());
clearance.push_back(m_idler->GetRadius());
rolling_elem_spin_axis.push_back(m_idler->GetBody()->GetRot().GetZaxis());
// After all rolling elements have been initialized, now able to setup the TrackChain.
// Assumed that start_pos is between idler and gear control points, e.g., on the top
// of the track chain.
ChVector<> start_pos = (rolling_elem_locs.front() + rolling_elem_locs.back()) / 2.0;
start_pos.y += (clearance.front() + clearance.back()) / 2.0;
// Assumption: start_pos should lie close to where the actual track chain would
// pass between the idler and driveGears.
// MUST be on the top part of the chain so the chain wrap rotation direction can be assumed.
m_chain->Initialize(chassis, chassis->GetFrame_REF_to_abs(), rolling_elem_locs, clearance, rolling_elem_spin_axis,
start_pos);
// add some initial damping to the inter-shoe pin joints
if (pin_damping > 0)
m_chain->Set_pin_friction(pin_damping);
// chain of shoes available for gear init
m_driveGear->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + Get_gearPosRel(), QUNIT), m_chain->GetShoeBody(), vehicle);
}
const ChVector<> TrackSystem::Get_idler_spring_react() {
return m_idler->m_shock->Get_react_force();
}
} // end namespace chrono<|fim▁end|> |
// add to the lists passed into the track chain, find location of each wheel center w.r.t. chassis coords. |
<|file_name|>whois-parsed-tests.ts<|end_file_name|><|fim▁begin|>import * as whoIs from 'whois-parsed';
const lookupTestDomain = async () => {
const { domainName, isAvailable } = await whoIs.lookup('https://codecademy.com');
return { domainName, isAvailable };
};
<|fim▁hole|><|fim▁end|> | Promise.resolve(lookupTestDomain()).then(result => {}); |
<|file_name|>scram.go<|end_file_name|><|fim▁begin|>// mgo - MongoDB driver for Go
//
// Copyright (c) 2014 - Gustavo Niemeyer <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Pacakage scram implements a SCRAM-{SHA-1,etc} client per RFC5802.
//
// http://tools.ietf.org/html/rfc5802
//
package scram<|fim▁hole|>import (
"bytes"
"crypto/hmac"
"crypto/rand"
"encoding/base64"
"fmt"
"hash"
"strconv"
"strings"
)
// Client implements a SCRAM-* client (SCRAM-SHA-1, SCRAM-SHA-256, etc).
//
// A Client may be used within a SASL conversation with logic resembling:
//
// var in []byte
// var client = scram.NewClient(sha1.New, user, pass)
// for client.Step(in) {
// out := client.Out()
// // send out to server
// in := serverOut
// }
// if client.Err() != nil {
// // auth failed
// }
//
type Client struct {
newHash func() hash.Hash
user string
pass string
step int
out bytes.Buffer
err error
clientNonce []byte
serverNonce []byte
saltedPass []byte
authMsg bytes.Buffer
}
// NewClient returns a new SCRAM-* client with the provided hash algorithm.
//
// For SCRAM-SHA-1, for example, use:
//
// client := scram.NewClient(sha1.New, user, pass)
//
func NewClient(newHash func() hash.Hash, user, pass string) *Client {
c := &Client{
newHash: newHash,
user: user,
pass: pass,
}
c.out.Grow(256)
c.authMsg.Grow(256)
return c
}
// Out returns the data to be sent to the server in the current step.
func (c *Client) Out() []byte {
if c.out.Len() == 0 {
return nil
}
return c.out.Bytes()
}
// Err returns the error that ocurred, or nil if there were no errors.
func (c *Client) Err() error {
return c.err
}
// SetNonce sets the client nonce to the provided value.
// If not set, the nonce is generated automatically out of crypto/rand on the first step.
func (c *Client) SetNonce(nonce []byte) {
c.clientNonce = nonce
}
var escaper = strings.NewReplacer("=", "=3D", ",", "=2C")
// Step processes the incoming data from the server and makes the
// next round of data for the server available via Client.Out.
// Step returns false if there are no errors and more data is
// still expected.
func (c *Client) Step(in []byte) bool {
c.out.Reset()
if c.step > 2 || c.err != nil {
return false
}
c.step++
switch c.step {
case 1:
c.err = c.step1(in)
case 2:
c.err = c.step2(in)
case 3:
c.err = c.step3(in)
}
return c.step > 2 || c.err != nil
}
func (c *Client) step1(in []byte) error {
if len(c.clientNonce) == 0 {
const nonceLen = 6
buf := make([]byte, nonceLen+b64.EncodedLen(nonceLen))
if _, err := rand.Read(buf[:nonceLen]); err != nil {
return fmt.Errorf("cannot read random SCRAM-SHA-1 nonce from operating system: %v", err)
}
c.clientNonce = buf[nonceLen:]
b64.Encode(c.clientNonce, buf[:nonceLen])
}
c.authMsg.WriteString("n=")
escaper.WriteString(&c.authMsg, c.user)
c.authMsg.WriteString(",r=")
c.authMsg.Write(c.clientNonce)
c.out.WriteString("n,,")
c.out.Write(c.authMsg.Bytes())
return nil
}
var b64 = base64.StdEncoding
func (c *Client) step2(in []byte) error {
c.authMsg.WriteByte(',')
c.authMsg.Write(in)
fields := bytes.Split(in, []byte(","))
if len(fields) != 3 {
return fmt.Errorf("expected 3 fields in first SCRAM-SHA-1 server message, got %d: %q", len(fields), in)
}
if !bytes.HasPrefix(fields[0], []byte("r=")) || len(fields[0]) < 2 {
return fmt.Errorf("server sent an invalid SCRAM-SHA-1 nonce: %q", fields[0])
}
if !bytes.HasPrefix(fields[1], []byte("s=")) || len(fields[1]) < 6 {
return fmt.Errorf("server sent an invalid SCRAM-SHA-1 salt: %q", fields[1])
}
if !bytes.HasPrefix(fields[2], []byte("i=")) || len(fields[2]) < 6 {
return fmt.Errorf("server sent an invalid SCRAM-SHA-1 iteration count: %q", fields[2])
}
c.serverNonce = fields[0][2:]
if !bytes.HasPrefix(c.serverNonce, c.clientNonce) {
return fmt.Errorf("server SCRAM-SHA-1 nonce is not prefixed by client nonce: got %q, want %q+\"...\"", c.serverNonce, c.clientNonce)
}
salt := make([]byte, b64.DecodedLen(len(fields[1][2:])))
n, err := b64.Decode(salt, fields[1][2:])
if err != nil {
return fmt.Errorf("cannot decode SCRAM-SHA-1 salt sent by server: %q", fields[1])
}
salt = salt[:n]
iterCount, err := strconv.Atoi(string(fields[2][2:]))
if err != nil {
return fmt.Errorf("server sent an invalid SCRAM-SHA-1 iteration count: %q", fields[2])
}
c.saltPassword(salt, iterCount)
c.authMsg.WriteString(",c=biws,r=")
c.authMsg.Write(c.serverNonce)
c.out.WriteString("c=biws,r=")
c.out.Write(c.serverNonce)
c.out.WriteString(",p=")
c.out.Write(c.clientProof())
return nil
}
func (c *Client) step3(in []byte) error {
var isv, ise bool
var fields = bytes.Split(in, []byte(","))
if len(fields) == 1 {
isv = bytes.HasPrefix(fields[0], []byte("v="))
ise = bytes.HasPrefix(fields[0], []byte("e="))
}
if ise {
return fmt.Errorf("SCRAM-SHA-1 authentication error: %s", fields[0][2:])
} else if !isv {
return fmt.Errorf("unsupported SCRAM-SHA-1 final message from server: %q", in)
}
if !bytes.Equal(c.serverSignature(), fields[0][2:]) {
return fmt.Errorf("cannot authenticate SCRAM-SHA-1 server signature: %q", fields[0][2:])
}
return nil
}
func (c *Client) saltPassword(salt []byte, iterCount int) {
mac := hmac.New(c.newHash, []byte(c.pass))
mac.Write(salt)
mac.Write([]byte{0, 0, 0, 1})
ui := mac.Sum(nil)
hi := make([]byte, len(ui))
copy(hi, ui)
for i := 1; i < iterCount; i++ {
mac.Reset()
mac.Write(ui)
mac.Sum(ui[:0])
for j, b := range ui {
hi[j] ^= b
}
}
c.saltedPass = hi
}
func (c *Client) clientProof() []byte {
mac := hmac.New(c.newHash, c.saltedPass)
mac.Write([]byte("Client Key"))
clientKey := mac.Sum(nil)
hash := c.newHash()
hash.Write(clientKey)
storedKey := hash.Sum(nil)
mac = hmac.New(c.newHash, storedKey)
mac.Write(c.authMsg.Bytes())
clientProof := mac.Sum(nil)
for i, b := range clientKey {
clientProof[i] ^= b
}
clientProof64 := make([]byte, b64.EncodedLen(len(clientProof)))
b64.Encode(clientProof64, clientProof)
return clientProof64
}
func (c *Client) serverSignature() []byte {
mac := hmac.New(c.newHash, c.saltedPass)
mac.Write([]byte("Server Key"))
serverKey := mac.Sum(nil)
mac = hmac.New(c.newHash, serverKey)
mac.Write(c.authMsg.Bytes())
serverSignature := mac.Sum(nil)
encoded := make([]byte, b64.EncodedLen(len(serverSignature)))
b64.Encode(encoded, serverSignature)
return encoded
}<|fim▁end|> | |
<|file_name|>EssentialsAntiBuild.java<|end_file_name|><|fim▁begin|>package com.earth2me.essentials.antibuild;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild
{
private final transient Map<AntiBuildConfig, Boolean> settingsBoolean = new EnumMap<AntiBuildConfig, Boolean>(AntiBuildConfig.class);
private final transient Map<AntiBuildConfig, List<Integer>> settingsList = new EnumMap<AntiBuildConfig, List<Integer>>(AntiBuildConfig.class);
private transient EssentialsConnect ess = null;
@Override
public void onEnable()
{
final PluginManager pm = this.getServer().getPluginManager();
final Plugin essPlugin = pm.getPlugin("Essentials");
if (essPlugin == null || !essPlugin.isEnabled())
{
return;
}
ess = new EssentialsConnect(essPlugin, this);
final EssentialsAntiBuildListener blockListener = new EssentialsAntiBuildListener(this);
pm.registerEvents(blockListener, this);
}
@Override
public boolean checkProtectionItems(final AntiBuildConfig list, final int id)
{
final List<Integer> itemList = settingsList.get(list);
return itemList != null && !itemList.isEmpty() && itemList.contains(id);
}
@Override
public EssentialsConnect getEssentialsConnect()
{
return ess;
}
@Override
public Map<AntiBuildConfig, Boolean> getSettingsBoolean()
{
return settingsBoolean;
}
<|fim▁hole|> return settingsList;
}
@Override
public boolean getSettingBool(final AntiBuildConfig protectConfig)
{
final Boolean bool = settingsBoolean.get(protectConfig);
return bool == null ? protectConfig.getDefaultValueBoolean() : bool;
}
}<|fim▁end|> | @Override
public Map<AntiBuildConfig, List<Integer>> getSettingsList()
{ |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import url
from .views import HomePage, PlayerList, PlayerDetail, SignUpForm
urlpatterns = [
url(r'^$', HomePage.as_view(),
name='home'),
url(r'^list$', PlayerList.as_view(),
name='player_list'),
url(r'signup/$', SignUpForm.as_view(),
name="signup"),
url(r'^(?P<pk>[0-9]+)/$', PlayerDetail.as_view(), name='player_detail'), <|fim▁hole|><|fim▁end|> | ] |
<|file_name|>PredefinedCrsPanel.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.crs;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.TableLayout.Anchor;
import com.bc.ceres.swing.TableLayout.Fill;
import com.jidesoft.swing.LabeledTextField;
import org.esa.snap.ui.util.FilteredListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.Container;
import java.awt.Dimension;
import java.util.logging.Logger;
class PredefinedCrsPanel extends JPanel {
public static final Logger LOG = Logger.getLogger(PredefinedCrsPanel.class.getName());
private final CrsInfoListModel crsListModel;
private JTextArea infoArea;
private JList<CrsInfo> crsList;
private LabeledTextField filterField;
private CrsInfo selectedCrsInfo;
private FilteredListModel<CrsInfo> filteredListModel;
// for testing the UI
public static void main(String[] args) {
final JFrame frame = new JFrame("CRS Selection Panel");
Container contentPane = frame.getContentPane();
final CrsInfoListModel listModel = new CrsInfoListModel(CrsInfo.generateCRSList());
PredefinedCrsPanel predefinedCrsForm = new PredefinedCrsPanel(listModel);
contentPane.add(predefinedCrsForm);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(() -> frame.setVisible(true));
}
PredefinedCrsPanel(CrsInfoListModel model) {
crsListModel = model;
createUI();
}
private void createUI() {
filterField = new LabeledTextField();
filterField.setHintText("Type here to filter CRS");
filterField.getTextField().getDocument().addDocumentListener(new FilterDocumentListener());
filteredListModel = new FilteredListModel<>(crsListModel);
crsList = new JList<>(filteredListModel);
crsList.setVisibleRowCount(15);
crsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JLabel filterLabel = new JLabel("Filter:");
final JLabel infoLabel = new JLabel("Well-Known Text (WKT):");
final JScrollPane crsListScrollPane = new JScrollPane(crsList);
crsListScrollPane.setPreferredSize(new Dimension(200, 150));
infoArea = new JTextArea(15, 30);
infoArea.setEditable(false);
crsList.addListSelectionListener(new CrsListSelectionListener());
crsList.setSelectedIndex(0);
final JScrollPane infoAreaScrollPane = new JScrollPane(infoArea);
TableLayout tableLayout = new TableLayout(3);
setLayout(tableLayout);
tableLayout.setTableFill(Fill.BOTH);
tableLayout.setTableAnchor(Anchor.NORTHWEST);
tableLayout.setTableWeightX(1.0);
tableLayout.setTablePadding(4, 4);
tableLayout.setRowWeightY(0, 0.0); // no weight Y for first row
tableLayout.setCellWeightX(0, 0, 0.0); // filter label; no grow in X
tableLayout.setRowWeightY(1, 1.0); // second row grow in Y
tableLayout.setCellColspan(1, 0, 2); // CRS list; spans 2 cols
tableLayout.setCellRowspan(1, 2, 2); // info area; spans 2 rows
tableLayout.setCellColspan(2, 0, 2); // defineCrsBtn button; spans to cols
add(filterLabel);
add(filterField);
add(infoLabel);
add(crsListScrollPane);
add(infoAreaScrollPane);
addPropertyChangeListener("enabled", evt -> {
filterLabel.setEnabled((Boolean) evt.getNewValue());
filterField.setEnabled((Boolean) evt.getNewValue());<|fim▁hole|> crsListScrollPane.setEnabled((Boolean) evt.getNewValue());
infoArea.setEnabled((Boolean) evt.getNewValue());
infoAreaScrollPane.setEnabled((Boolean) evt.getNewValue());
});
crsList.getSelectionModel().setSelectionInterval(0, 0);
}
private class FilterDocumentListener implements DocumentListener {
@Override
public void insertUpdate(DocumentEvent e) {
updateFilter(getFilterText(e));
clearListSelection();
}
@Override
public void removeUpdate(DocumentEvent e) {
updateFilter(getFilterText(e));
clearListSelection();
}
private void clearListSelection() {
crsList.clearSelection();
setInfoText("");
}
@Override
public void changedUpdate(DocumentEvent e) {
}
private void updateFilter(String text) {
filteredListModel.setFilter(crsInfo -> {
String description = crsInfo.toString().toLowerCase();
return description.contains(text.trim().toLowerCase());
});
}
private String getFilterText(DocumentEvent e) {
Document document = e.getDocument();
String text = null;
try {
text = document.getText(0, document.getLength());
} catch (BadLocationException e1) {
LOG.severe(e1.getMessage());
}
return text;
}
}
private class CrsListSelectionListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
final JList list = (JList) e.getSource();
selectedCrsInfo = (CrsInfo) list.getSelectedValue();
if (selectedCrsInfo != null) {
try {
setInfoText(selectedCrsInfo.getDescription());
} catch (Exception e1) {
String message = e1.getMessage();
if (message != null) {
setInfoText("Error while creating CRS:\n\n" + message);
}
}
}
}
}
CrsInfo getSelectedCrsInfo() {
return selectedCrsInfo;
}
private void setInfoText(String infoText) {
infoArea.setText(infoText);
infoArea.setCaretPosition(0);
}
}<|fim▁end|> | infoLabel.setEnabled((Boolean) evt.getNewValue());
crsList.setEnabled((Boolean) evt.getNewValue()); |
<|file_name|>moneyclient_pt_PT.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About MoneyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>MoneyCoin</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2014-%1 The MoneyCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2014-[CLIENT_LAST_COPYRIGHT] The MoneyCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:[email protected]">[email protected]</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+218"/>
<source>Label</source>
<translation>Rótulo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+0"/>
<source>pubkey</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>stealth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>(no label)</source>
<translation>(sem rótulo)</translation>
</message>
<message>
<location line="+4"/>
<source>Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>n/a</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de Frase-Passe</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Escreva a frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nova frase de segurança</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita a nova frase de segurança</translation>
</message>
<message>
<location line="+33"/>
<location line="+16"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Enable messaging</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+39"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Escreva a nova frase de seguraça da sua carteira. <br/> Por favor, use uma frase de <b>10 ou mais caracteres aleatórios,</b> ou <b>oito ou mais palavras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Encriptar carteira</translation>
</message>
<message>
<location line="+11"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear carteira</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Desencriptar carteira</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Alterar frase de segurança</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Escreva a frase de segurança antiga seguida da nova para a carteira.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar encriptação da carteira</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Tem a certeza que deseja encriptar a carteira?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANTE: Qualquer cópia de segurança anterior da carteira deverá ser substituída com o novo, actualmente encriptado, ficheiro de carteira. Por razões de segurança, cópias de segurança não encriptadas efectuadas anteriormente do ficheiro da carteira tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation>
</message>
<message>
<location line="+104"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Atenção: A tecla Caps Lock está activa!</translation>
</message>
<message>
<location line="-134"/>
<location line="+61"/>
<source>Wallet encrypted</source>
<translation>Carteira encriptada</translation>
</message>
<message>
<location line="-59"/>
<source>MoneyCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+45"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>A encriptação da carteira falhou</translation>
</message>
<message>
<location line="-57"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation>
</message>
<message>
<location line="+7"/>
<location line="+51"/>
<source>The supplied passphrases do not match.</source>
<translation>As frases de segurança fornecidas não coincidem.</translation>
</message>
<message>
<location line="-39"/>
<source>Wallet unlock failed</source>
<translation>O desbloqueio da carteira falhou</translation>
</message>
<message>
<location line="+1"/>
<location line="+13"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>A desencriptação da carteira falhou</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>A frase de segurança da carteira foi alterada com êxito.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+137"/>
<source>Network Alert</source>
<translation>Alerta da Rede</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Quantidade:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Quantia:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Prioridade:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Taxa:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Saída Baixa:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+528"/>
<location line="+30"/>
<source>no</source>
<translation>não</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Depois de taxas:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Troco:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>(des)seleccionar todos</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Modo de árvore</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Modo lista</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmados</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmada</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Prioridade</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-520"/>
<source>Copy address</source>
<translation>Copiar endereço</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar rótulo</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copiar quantia</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copiar ID da Transação</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copiar quantidade</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Taxa de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Taxa depois de cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copiar bytes</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Prioridade de Cópia</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copiar output baixo</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copiar alteração</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>o maior</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>médio-alto</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>médio</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>baixo-médio</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>baixo</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>O mais baixo</translation>
</message>
<message>
<location line="+130"/>
<location line="+30"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<location line="+30"/>
<source>yes</source>
<translation>sim</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(Sem rótulo)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>Alteração de %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(Alteração)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Endereço</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Rótulo</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>E&ndereço</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Novo endereço de entrada</translation>
</message>
<message>
<location line="+7"/>
<source>New sending address</source>
<translation>Novo endereço de saída</translation>
</message>
<message>
<location line="+4"/>
<source>Edit receiving address</source>
<translation>Editar endereço de entrada</translation>
</message>
<message>
<location line="+7"/>
<source>Edit sending address</source>
<translation>Editar endereço de saída</translation>
</message>
<message>
<location line="+82"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>O endereço introduzido "%1" já se encontra no livro de endereços.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid MoneyCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Impossível desbloquear carteira.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Falha ao gerar nova chave.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+526"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+12"/>
<source>Money</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>MessageModel</name>
<message>
<location filename="../messagemodel.cpp" line="+376"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Sent Date Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Received Date Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>To Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>From Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send Secure Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send failed: %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+1"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start money: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<location filename="../peertablemodel.cpp" line="+118"/>
<source>Address/Hostname</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>User Agent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Ping Time</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../guiutil.cpp" line="-470"/>
<source>%1 d</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<location line="+55"/>
<source>%1 s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>None</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>%1 ms</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nome do Cliente</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+23"/>
<location line="+491"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<source>N/A</source>
<translation>N/D</translation>
</message>
<message>
<location line="-1062"/>
<source>Client version</source>
<translation>Versão do Cliente</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informação</translation>
</message>
<message>
<location line="-10"/>
<source>Money - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Money Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Using OpenSSL version</source>
<translation>Usando versão OpenSSL</translation>
</message>
<message>
<location line="+26"/>
<source>Using BerkeleyDB version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Tempo de início</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Rede</translation>
</message>
<message>
<location line="+7"/>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Number of connections</source>
<translation>Número de ligações</translation>
</message>
<message>
<location line="+157"/>
<source>Show the Money help message to get a list with possible Money command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+99"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<location filename="../rpcconsole.cpp" line="+396"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<location filename="../rpcconsole.cpp" line="+1"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>&Peers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<location filename="../rpcconsole.cpp" line="-167"/>
<location line="+328"/>
<source>Select a peer to view detailed information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Peer ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Direction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>User Agent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Services</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Starting Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Sync Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Ban Score</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Connection Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Bytes Sent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Bytes Received</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Ping Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Time Offset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-866"/>
<source>Block chain</source>
<translation>Cadeia de blocos</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Total estimado de blocos</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Tempo do último bloco</translation>
</message>
<message>
<location line="+49"/>
<source>Open the Money debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="-266"/>
<source>Build date</source>
<translation>Data de construção</translation>
</message>
<message>
<location line="+206"/>
<source>Debug log file</source>
<translation>Ficheiro de registo de depuração</translation>
</message>
<message>
<location line="+109"/>
<source>Clear console</source>
<translation>Limpar consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-197"/>
<source>Welcome to the Money Core RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use as setas para cima e para baixo para navegar no histórico e <b>Ctrl-L</b> para limpar o ecrã.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Digite <b>help</b> para visualizar os comandos disponíveis.</translation>
</message>
<message>
<location line="+233"/>
<source>via %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+1"/>
<source>never</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Inbound</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Outbound</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Unknown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<location line="+1"/>
<source>Fetching...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>MoneyBridge</name>
<message>
<location filename="../moneybridge.cpp" line="+410"/>
<source>Incoming Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+58"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source><b>%1</b> to MONEY %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source><b>%1</b> MONEY, ring size %2 to MONEY %3 (%4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source><b>%1</b> MONEY, ring size %2 to MONEY %3 (%4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<location line="+10"/>
<location line="+12"/>
<location line="+8"/>
<source>Error:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Unknown txn type detected %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Input types must match for all recipients.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Ring sizes must match for all recipients.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Ring size outside range [%1, %2].</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<location line="+9"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Are you sure you want to send?
Ring size of one is not anonymous, and harms the network.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+9"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<location line="+25"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>The change address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<location line="+376"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-371"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<location line="+365"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-360"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Narration is too long.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Ring Size Error.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Input Type Error.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Must be in full mode to send anon.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Invalid Stealth Address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your money balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error generating transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error generating transaction: %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+304"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>The message can't be empty.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Error: Message creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The message was rejected.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+98"/>
<source>Sanity Error!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: a sanity check prevented the transfer of a non-group private key, please close your wallet and report this error to the development team as soon as possible.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bridgetranslations.h" line="+8"/>
<source>Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Notifications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Management</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add New Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Import Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Advanced</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change Passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(Un)lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Tools</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chain Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Block Explorer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Debug</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>About Money</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>About QT</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>QR code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Narration:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>MONEY</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>mMONEY</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>µMONEY</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Moneyshi</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add new receive address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Add Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add a new contact</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Lookup</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Normal</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Stealth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>BIP32</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Public Key</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction Hash</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recent Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Market</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Advanced Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Make payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balance transfer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>LowOutput:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>From account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>PUBLIC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>PRIVATE</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Ring Size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>To account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Pay to</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+135"/>
<source>Tor connection offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>i2p connection offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet is encrypted and currently locked</source>
<translation type="unfinished"/>
</message>
<message>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open chat list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Values</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Outputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a MoneyCash address to sign the message with (e.g. SaKYqfD8J3vw4RTnqtgk2K9B67CBaL3mhV)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the message you want to sign</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Click sign message to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy the signed message signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a MoneyCash address to verify the message with (e.g. SaKYqfD8J3vw4RTnqtgk2K9B67CBaL3mhV)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the message you want to verify</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a MoneyCash signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Paste signature from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Your total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balances overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recent in/out transactions or stakes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select inputs to spend</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Optional address to receive transaction change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Current spendable send payment balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Current spendable balance to account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>The address to transfer the balance to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The label for this address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount to transfer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Double click to edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Short payment note.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The address to send the payment to (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a public key for the address above</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Name for this Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a password</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Would you like to create a bip44 path?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Your recovery phrase (Keep this safe!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Make Default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Activate/Deactivate</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set as Master</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>0 active connections to MoneyCoin network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>The address to send the payment to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a short note to send with payment (max 24 characters)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Wallet Name for recovered account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the password for the wallet you are trying to recover</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Is this a bip44 path?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-66"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-122"/>
<source>Narration</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Default Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Clear All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Suggest Ring Size</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>RECEIVE</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Filter by type..</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>TRANSACTIONS</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ADDRESSBOOK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Delete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Private Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Name:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Public Key:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose identity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Identity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Group Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Group name:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Create Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite others</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite others to group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite to Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>GROUP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>BOOK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start private conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start group conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>CHAT</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Leave Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>CHAIN DATA</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Coin Value</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Owned (Mature)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>System (Mature)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Spends</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Least Depth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>BLOCK EXPLORER</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Refresh</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Hash</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Value Out</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>OPTIONS</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>I2P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Tor</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Money on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Pay transaction fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Most transactions are 1kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enable Staking</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Reserve:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimum Stake Interval</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimum Ring size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum Ring size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Automatically select ring size</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enable Secure messaging</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Mode (Requires Restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Full Index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Index Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Map port using UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Proxy IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>SOCKS Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>User Interface language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rows per page:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Notifications:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Visible Transaction Types:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>I2P (coming soon)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>TOR (coming soon)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Ok</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lets create a New Wallet and Account to get you started!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Password</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add an optional Password to secure the Recovery Phrase (shown on next page)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Would you like to create a Multi-Account HD Key? (BIP44)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Language</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>English</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>French</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Japanese</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Spanish</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chinese (Simplified)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chinese (Traditional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Next Step</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Write your Wallet Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Important!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need the Wallet Recovery Phrase to restore this wallet. Write it down and keep them somewhere safe.
You will be asked to confirm the Wallet Recovery Phrase in the next screen to ensure you have written it down correctly</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Back</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Please confirm your Wallet Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Congratulations! You have successfully created a New Wallet and Account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You can now use your Account to send and receive funds :)
Remember to keep your Wallet Recovery Phrase and Password (if set) safe in case you ever need to recover your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Lets import your Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The Wallet Recovery Phrase could require a password to be imported</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Is this a Multi-Account HD Key (BIP44)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recovery Phrase (Usually 24 words)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Congratulations! You have successfully imported your Wallet from your Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You can now use your Account to send and receive funds :)
Remember to keep your Wallet Recovery Phrase and Password safe in case you ever need to recover your wallet again!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Accounts</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Created</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Active Account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Keys</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Path</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Active</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Master</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>MoneyGUI</name>
<message>
<location filename="../money.cpp" line="+111"/>
<source>A fatal error occurred. Money can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../moneygui.cpp" line="+89"/>
<location line="+178"/>
<source>MoneyClient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-178"/>
<source>Client</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&About MoneyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about MoneyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Modify configuration options for MoneyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+74"/>
<source>MoneyClient client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+63"/>
<source>%n active connection(s) to MoneyCoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>header</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>headers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<location line="+22"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Downloading filtered blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>~%1 filtered block(s) remaining (%2% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Importing blocks...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+5"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+13"/>
<location line="+4"/>
<source>Imported</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<location line="+4"/>
<source>Downloaded</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-3"/>
<source>%1 of %2 %3 of transaction history (%4% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>%1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+23"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+3"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+7"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Last received %1 was generated %2.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<location line="+15"/>
<source>Incoming Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
From Address: %2
To Address: %3
Message: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid MoneyCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking and messaging only.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for messaging only.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking only.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet must first be encrypted to be locked.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+69"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+9"/>
<source>Staking.
Your weight is %1
Network weight is %2
Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Not staking because wallet is in thin mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking, staking is disabled</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../transactionrecord.cpp" line="+23"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received money</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent money</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+79"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+7"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/desligado</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/não confirmada</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmações</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Origem</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Gerado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<location line="+20"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="-19"/>
<location line="+20"/>
<location line="+23"/>
<location line="+57"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-96"/>
<location line="+2"/>
<location line="+18"/>
<location line="+2"/>
<source>own address</source>
<translation>endereço próprio</translation>
</message>
<message>
<location line="-22"/>
<location line="+20"/>
<source>label</source>
<translation>rótulo</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+44"/>
<location line="+20"/>
<location line="+40"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-114"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>matura daqui por %n bloco</numerusform><numerusform>matura daqui por %n blocos</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>não aceite</translation>
</message>
<message>
<location line="+43"/>
<location line="+8"/>
<location line="+16"/>
<location line="+42"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-52"/>
<source>Transaction fee</source>
<translation>Taxa de transação</translation>
</message>
<message>
<location line="+19"/>
<source>Net amount</source>
<translation>Valor líquido</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensagem</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentário</translation>
</message>
<message>
<location line="+12"/>
<source>Transaction ID</source>
<translation>ID da Transação</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informação de depuração</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transação</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Entradas</translation>
</message>
<message>
<location line="+44"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verdadeiro</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falso</translation>
</message>
<message>
<location line="-266"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ainda não foi transmitida com sucesso</translation>
</message>
<message>
<location line="+36"/>
<location line="+20"/>
<source>unknown</source>
<translation>desconhecido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalhes da transação</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta janela mostra uma descrição detalhada da transação</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+217"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Endereço</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Quantia</translation>
</message>
<message>
<location line="+54"/>
<source>Open until %1</source>
<translation>Aberto até %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmada (%1 confirmações)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation>
</message>
<message>
<location line="-51"/>
<source>Narration</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Gerado mas não aceite</translation>
</message>
<message>
<location line="+49"/>
<source>(n/a)</source>
<translation>(n/d)</translation>
</message>
<message>
<location line="+202"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado da transação. Pairar por cima deste campo para mostrar o número de confirmações.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Data e hora a que esta transação foi recebida.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Endereço de destino da transação.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Quantia retirada ou adicionada ao saldo.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+393"/>
<location line="+246"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>MoneyCoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Utilização:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or moneycoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Listar comandos</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Obter ajuda para um comando</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Opções:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: moneycoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: moneycoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Especifique ficheiro de carteira (dentro da pasta de dados)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especificar pasta de dados</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Definir o tamanho da cache de base de dados em megabytes (por defeito: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 51737 or testnet: 51997)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Manter no máximo <n> ligações a outros nós da rede (por defeito: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Especifique o seu endereço público</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Tolerância para desligar nós mal-formados (por defeito: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos a impedir que nós mal-formados se liguem de novo (por defeito: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 51736 or testnet: 51996)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceitar comandos da consola e JSON-RPC</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr o processo como um daemon e aceitar comandos</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Utilizar a rede de testes - testnet</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar IPv4: %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong MoneyCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Atenção: wallet.dat corrupto, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar de uma cópia de segurança.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Opções de criação de bloco:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Apenas ligar ao(s) nó(s) especificado(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descobrir endereço IP próprio (padrão: 1 ao escutar e sem -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Falhou a escutar em qualquer porta. Use -listen=0 se quer isto.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Armazenamento intermédio de recepção por ligação, <n>*1000 bytes (por defeito: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Armazenamento intermédio de envio por ligação, <n>*1000 bytes (por defeito: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Apenas ligar a nós na rede <net> (IPv4, IPv6 ou Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Opções SSL: (ver a Wiki Bitcoin para instruções de configuração SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especificar tempo de espera da ligação em millisegundos (por defeito: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Nome de utilizador para ligações JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupta, recuperação falhou</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Palavra-passe para ligações JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=moneycoinrpc
rpcpassword=%s
(you do not need to remember this password)<|fim▁hole|>for example: alertnotify=echo %%s | mail -s "MoneyCoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir ligações JSON-RPC do endereço IP especificado</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Enviar comandos para o nó a correr em <ip> (por defeito: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Executar comando quando mudar o melhor bloco (no comando, %s é substituído pela hash do bloco)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Atualize a carteira para o formato mais recente</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Definir o tamanho da memória de chaves para <n> (por defeito: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Reexaminar a cadeia de blocos para transações em falta na carteira</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para ligações JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Chave privada do servidor (por defeito: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Esta mensagem de ajuda</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. MoneyCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>MoneyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Incapaz de vincular a %s neste computador (vínculo retornou erro %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Carregar endereços...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erro ao carregar wallet.dat: Carteira danificada</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of MoneyCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart MoneyCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Erro ao carregar wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Endereço -proxy inválido: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Rede desconhecida especificada em -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Versão desconhecida de proxy -socks requisitada: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Não conseguiu resolver endereço -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Não conseguiu resolver endereço -externalip: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Quantia inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Quantia inválida</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fundos insuficientes</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Carregar índice de blocos...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Adicione um nó ao qual se ligar e tentar manter a ligação aberta</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. MoneyCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Carregar carteira...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Impossível mudar a carteira para uma versão anterior</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Impossível escrever endereço por defeito</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Reexaminando...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Carregamento completo</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Para usar a opção %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Erro</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Deverá definir rpcpassword=<password> no ficheiro de configuração:
%s
Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.</translation>
</message>
</context>
</TS><|fim▁end|> | The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems; |
<|file_name|>FilePicker.java<|end_file_name|><|fim▁begin|>//simple GUI for the Matching program
package compare;
//importing requird libraries
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FilePicker extends JPanel {
//declaring required variables
private String textFieldLabel;
private String buttonLabel;
private JLabel label;
public static JTextField textField;
private JButton browseButton;
private JFileChooser fileChooser;
public static String fileName, outputDestination, filePath;
private int mode;
public static final int MODE_OPEN = 1;
public static final int MODE_SAVE = 2;
public static JLabel categoryLabel;
//Constructor for the UI
public FilePicker(String textFieldLabel, String buttonLabel) {
this.textFieldLabel = textFieldLabel;
this.buttonLabel = buttonLabel;
fileChooser = new JFileChooser();
label = new JLabel(textFieldLabel);
textField = new JTextField(30);
browseButton = new JButton(buttonLabel);
browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
browseButtonActionPerformed(evt);
}
});
add(label);
add(textField);
add(browseButton);
}
//browse button click event
private void browseButtonActionPerformed(ActionEvent evt) {
if (mode == MODE_OPEN) {
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
} else if (mode == MODE_SAVE) {
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
}
this.filePath = getSelectedFilePath();
}
//adding required filter for browsing files
public void addFileTypeFilter(String extension, String description) {
FileTypeFilter filter = new FileTypeFilter(extension, description);
fileChooser.addChoosableFileFilter(filter);
}
//browsing mode
public void setMode(int mode) {
this.mode = mode;
}
<|fim▁hole|> return textField.getText();
}
//get the file Chooser
public JFileChooser getFileChooser() {
return this.fileChooser;
}
}<|fim▁end|> | //get file path of the selected file
public static String getSelectedFilePath() {
|
<|file_name|>VInteger.cpp<|end_file_name|><|fim▁begin|>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.<|fim▁hole|>** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "items/VInteger.h"
#include "ModelBase/src/model/Model.h"
namespace Visualization {
ITEM_COMMON_DEFINITIONS(VInteger, "item")
VInteger::VInteger(Item* parent, NodeType *node, const StyleType *style) :
Super(parent, node, style)
{
TextRenderer::setText( QString::number(node->get()) );
}
bool VInteger::setText(const QString& newText)
{
bool ok = false;
int value = newText.toInt(&ok);
if (ok)
{
node()->model()->beginModification(node(), "Set integer");
node()->set(value);
node()->model()->endModification();
TextRenderer::setText(newText);
return true;
}
else return false;
}
QString VInteger::currentText()
{
return QString::number( node()->get() );
}
}<|fim▁end|> | |
<|file_name|>factory_of_factories.py<|end_file_name|><|fim▁begin|>"""`Factory of Factories` pattern."""
from dependency_injector import containers, providers
class SqlAlchemyDatabaseService:
def __init__(self, session, base_class):
self.session = session
self.base_class = base_class
class TokensService:
def __init__(self, id_generator, database):
self.id_generator = id_generator
self.database = database
class Token:
...
class UsersService:
def __init__(self, id_generator, database):
self.id_generator = id_generator
self.database = database
class User:
...
# Sample objects
session = object()
id_generator = object()
class Container(containers.DeclarativeContainer):
database_factory = providers.Factory(
providers.Factory,
SqlAlchemyDatabaseService,
session=session,
)
token_service = providers.Factory(
TokensService,
id_generator=id_generator,
database=database_factory(base_class=Token),
)
user_service = providers.Factory(
UsersService,
id_generator=id_generator,
database=database_factory(base_class=User),
)
if __name__ == '__main__':
container = Container()
token_service = container.token_service()
assert token_service.database.base_class is Token
user_service = container.user_service()<|fim▁hole|><|fim▁end|> | assert user_service.database.base_class is User |
<|file_name|>services.js<|end_file_name|><|fim▁begin|>angular.module('app.services', [
'app.services.actions',
'app.services.connection',
'app.services.coverart',
'app.services.locale',
'app.services.logging',
'app.services.mopidy',
'app.services.paging',
'app.services.platform',
'app.services.router',
'app.services.servers',
'app.services.settings'<|fim▁hole|><|fim▁end|> | ]); |
<|file_name|>Cmd.java<|end_file_name|><|fim▁begin|>package net.nopattern.cordova.brightcoveplayer;<|fim▁hole|> */
public enum Cmd {
LOAD,
LOADED,
DISABLE,
ENABLE,
PAUSE,
PLAY,
HIDE,
SHOW,
SEEK,
RATE,
RESUME,
REPOSITION
};<|fim▁end|> |
/**
* Created by peterchin on 6/9/16. |
<|file_name|>Effect3D.java<|end_file_name|><|fim▁begin|>/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------
* Effect3D.java
* -------------
* (C) Copyright 2002-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Nov-2002 : Version 1 (DG);
* 14-Nov-2002 : Modified to have independent x and y offsets (DG);
*
*/
package org.jfree.chart;
/**
* An interface that should be implemented by renderers that use a 3D effect.
* This allows the axes to mirror the same effect by querying the renderer.
*/
<|fim▁hole|> * Returns the x-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getXOffset();
/**
* Returns the y-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getYOffset();
}<|fim▁end|> | public interface Effect3D {
/**
|
<|file_name|>ProductList.js<|end_file_name|><|fim▁begin|>import React, { PropTypes, Component } from 'react';
import { Breadcrumb, Table, Button, Col } from 'react-bootstrap';
import cx from 'classnames';
import _ from 'lodash';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ProductList.css';
import Link from '../Link';
class ProductList extends Component {
static propTypes = {
isFetching: PropTypes.bool,
rs: PropTypes.array,
popAddApp: PropTypes.func,
};
static defaultProps = {
isFetching: true,
rs: [],
popAddApp: () => {},
};
constructor() {
super();
this.renderRow = this.renderRow.bind(this);
}
renderRow(rowData, index) {
const appName = _.get(rowData, 'name');
return (
<tr key={_.get(rowData, 'name')}>
<td>
<Link to={`/apps/${appName}`}>{appName}</Link>
</td>
<td style={{ textAlign: 'left' }}>
<ul>
{
_.map(_.get(rowData, 'collaborators'), (item, email) => (
<li key={email}>
{email}
<span className={s.permission}>
(<em>{_.get(item, 'permission')}</em>)
</span>
{
_.get(item, 'isCurrentAccount') ?
<span className={cx(s.label, s.labelSuccess)}>
it's you
</span>
: null
}
</li>
))
}
</ul>
</td>
<td>
<ul>
{
_.map(_.get(rowData, 'deployments'), (item, email) => (
<li key={email} style={item === 'Production' ? { color: 'green' } : null} >
<Link to={`/apps/${appName}/${item}`}>{item}</Link>
</li>
))
}
</ul>
</td>
<td />
</tr>
);
}
render() {
const self = this;
const tipText = '暂无数据';
return (
<div className={s.root}>
<div className={s.container}>
<Breadcrumb>
<Breadcrumb.Item active>
应用列表
</Breadcrumb.Item>
</Breadcrumb>
<Col style={{ marginBottom: '20px' }}>
<Button
onClick={this.props.popAddApp}
bsStyle="primary"
>
添加应用
</Button>
</Col>
<Table striped bordered condensed hover responsive>
<thead><|fim▁hole|> <th style={{ textAlign: 'center' }} >Deployments</th>
<th style={{ textAlign: 'center' }} >操作</th>
</tr>
</thead>
<tbody>
{
this.props.rs.length > 0 ?
_.map(this.props.rs, (item, index) => self.renderRow(item, index))
:
<tr>
<td colSpan="4" >{tipText}</td>
</tr>
}
</tbody>
</Table>
</div>
</div>
);
}
}
export default withStyles(s)(ProductList);<|fim▁end|> | <tr>
<th style={{ textAlign: 'center' }} >产品名</th>
<th style={{ textAlign: 'center' }} >成员</th> |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from couchpotato.core.event import addEvent
from couchpotato.core.helpers.variable import tryFloat
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotato.environment import Env
from urlparse import urlparse
import re
import time
log = CPLog(__name__)
class Provider(Plugin):
type = None # movie, nzb, torrent, subtitle, trailer
http_time_between_calls = 10 # Default timeout for url requests
last_available_check = {}
is_available = {}
def isAvailable(self, test_url):
if Env.get('dev'): return True
now = time.time()
host = urlparse(test_url).hostname
if self.last_available_check.get(host) < now - 900:
self.last_available_check[host] = now
try:
self.urlopen(test_url, 30)
self.is_available[host] = True
except:
log.error('"%s" unavailable, trying again in an 15 minutes.', host)
self.is_available[host] = False
return self.is_available.get(host, False)
class YarrProvider(Provider):
cat_ids = []
sizeGb = ['gb', 'gib']
sizeMb = ['mb', 'mib']
sizeKb = ['kb', 'kib']
def __init__(self):
addEvent('provider.belongs_to', self.belongsTo)<|fim▁hole|> addEvent('nzb.feed', self.feed)
def download(self, url = '', nzb_id = ''):
return self.urlopen(url)
def feed(self):
return []
def search(self, movie, quality):
return []
def belongsTo(self, url, provider = None, host = None):
try:
if provider and provider == self.getName():
return self
hostname = urlparse(url).hostname
if host and hostname in host:
return self
else:
for url_type in self.urls:
download_url = self.urls[url_type]
if hostname in download_url:
return self
except:
log.debug('Url % s doesn\'t belong to %s', (url, self.getName()))
return
def parseSize(self, size):
sizeRaw = size.lower()
size = tryFloat(re.sub(r'[^0-9.]', '', size).strip())
for s in self.sizeGb:
if s in sizeRaw:
return size * 1024
for s in self.sizeMb:
if s in sizeRaw:
return size
for s in self.sizeKb:
if s in sizeRaw:
return size / 1024
return 0
def getCatId(self, identifier):
for cats in self.cat_ids:
ids, qualities = cats
if identifier in qualities:
return ids
return [self.cat_backup_id]
def found(self, new):
log.info('Found: score(%(score)s) on %(provider)s: %(name)s', new)<|fim▁end|> |
addEvent('%s.search' % self.type, self.search)
addEvent('yarr.search', self.search)
|
<|file_name|>solution.py<|end_file_name|><|fim▁begin|># We slice the array in two parts at index d, then print them
# in reverse order.
n, d = map(int, input().split())
A = list(map(int, input().split()))<|fim▁hole|>print(*(A[d:] + A[:d]))<|fim▁end|> | |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>export const MRoot = {
name: 'm-root',
nodeName: 'm-node',
data() {
return {
nodeVMs: [],
};
},
methods: {
walk(func) {
let queue = [];
queue = queue.concat(this.nodeVMs);<|fim▁hole|> const result = func(nodeVM);
if (result !== undefined)
return result;
}
},
find(func) {
return this.walk((nodeVM) => {
if (func(nodeVM))
return nodeVM;
});
},
},
};
export { MNode } from './m-node.vue';
export default MRoot;<|fim▁end|> | let nodeVM;
while ((nodeVM = queue.shift())) {
queue = queue.concat(nodeVM.nodeVMs); |
<|file_name|>env.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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. This file may not be copied, modified, or distributed
// except according to those terms.
/*
* The compiler code necessary to support the env! extension. Eventually this
* should all get sucked into either the compiler syntax extension plugin
* interface.
*/<|fim▁hole|>use ast;
use codemap::Span;
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;
use parse::token;
use std::env;
pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult+'cx> {
let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") {
None => return DummyResult::expr(sp),
Some(v) => v
};
let e = match env::var(&var[..]) {
Err(..) => {
cx.expr_path(cx.path_all(sp,
true,
cx.std_path(&["option", "Option", "None"]),
Vec::new(),
vec!(cx.ty_rptr(sp,
cx.ty_ident(sp,
cx.ident_of("str")),
Some(cx.lifetime(sp,
cx.ident_of(
"'static").name)),
ast::MutImmutable)),
Vec::new()))
}
Ok(s) => {
cx.expr_call_global(sp,
cx.std_path(&["option", "Option", "Some"]),
vec!(cx.expr_str(sp,
token::intern_and_get_ident(
&s[..]))))
}
};
MacEager::expr(e)
}
pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult+'cx> {
let mut exprs = match get_exprs_from_tts(cx, sp, tts) {
Some(ref exprs) if exprs.is_empty() => {
cx.span_err(sp, "env! takes 1 or 2 arguments");
return DummyResult::expr(sp);
}
None => return DummyResult::expr(sp),
Some(exprs) => exprs.into_iter()
};
let var = match expr_to_string(cx,
exprs.next().unwrap(),
"expected string literal") {
None => return DummyResult::expr(sp),
Some((v, _style)) => v
};
let msg = match exprs.next() {
None => {
token::intern_and_get_ident(&format!("environment variable `{}` \
not defined",
var))
}
Some(second) => {
match expr_to_string(cx, second, "expected string literal") {
None => return DummyResult::expr(sp),
Some((s, _style)) => s
}
}
};
match exprs.next() {
None => {}
Some(_) => {
cx.span_err(sp, "env! takes 1 or 2 arguments");
return DummyResult::expr(sp);
}
}
let e = match env::var(&var[..]) {
Err(_) => {
cx.span_err(sp, &msg);
cx.expr_usize(sp, 0)
}
Ok(s) => cx.expr_str(sp, token::intern_and_get_ident(&s))
};
MacEager::expr(e)
}<|fim▁end|> | |
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>use std::io::{Read, Cursor};
use FromCursor;
use compression::Compression;
use frame::frame_response::ResponseBody;
use super::*;
use types::{from_bytes, UUID_LEN, CStringList};
use types::data_serialization_types::decode_timeuuid;
use error;
pub fn parse_frame(mut cursor: &mut Read, compressor: &Compression) -> error::Result<Frame> {
// TODO: try to use slices instead
let mut version_bytes = [0; VERSION_LEN];
let mut flag_bytes = [0; FLAG_LEN];
let mut opcode_bytes = [0; OPCODE_LEN];
let mut stream_bytes = [0; STREAM_LEN];
let mut length_bytes = [0; LENGTH_LEN];
// NOTE: order of reads matters
try!(cursor.read(&mut version_bytes));
try!(cursor.read(&mut flag_bytes));
try!(cursor.read(&mut stream_bytes));
try!(cursor.read(&mut opcode_bytes));
try!(cursor.read(&mut length_bytes));<|fim▁hole|>
let version = Version::from(version_bytes.to_vec());
let flags = Flag::get_collection(flag_bytes[0]);
let stream = from_bytes(stream_bytes.to_vec().as_slice());
let opcode = Opcode::from(opcode_bytes[0]);
let length = from_bytes(length_bytes.to_vec().as_slice()) as usize;
let mut body_bytes = Vec::with_capacity(length);
unsafe {
body_bytes.set_len(length);
}
try!(cursor.read_exact(&mut body_bytes));
let full_body = if flags.iter().any(|flag| flag == &Flag::Compression) {
try!(compressor.decode(body_bytes))
} else {
try!(Compression::None.decode(body_bytes))
};
// Use cursor to get tracing id, warnings and actual body
let mut body_cursor = Cursor::new(full_body.as_slice());
let tracing_id = if flags.iter().any(|flag| flag == &Flag::Tracing) {
let mut tracing_bytes = Vec::with_capacity(UUID_LEN);
unsafe {
tracing_bytes.set_len(UUID_LEN);
}
// TODO: try to use slice instead
try!(body_cursor.read_exact(&mut tracing_bytes));
decode_timeuuid(tracing_bytes.as_slice()).ok()
} else {
None
};
let warnings = if flags.iter().any(|flag| flag == &Flag::Warning) {
CStringList::from_cursor(&mut body_cursor)?.into_plain()
} else {
vec![]
};
let mut body = vec![];
try!(body_cursor.read_to_end(&mut body));
let frame = Frame {
version: version,
flags: flags,
opcode: opcode,
stream: stream,
body: body,
tracing_id: tracing_id,
warnings: warnings,
};
conver_frame_into_result(frame)
}
fn conver_frame_into_result(frame: Frame) -> error::Result<Frame> {
match frame.opcode {
Opcode::Error => {
frame
.get_body()
.and_then(|err| match err {
ResponseBody::Error(err) => Err(error::Error::Server(err)),
_ => unreachable!(),
})
}
_ => Ok(frame),
}
}<|fim▁end|> | |
<|file_name|>volatile.py<|end_file_name|><|fim▁begin|>"""
[DEPRECATED] Run a single container in debug mode
"""
import typer
from controller import print_and_exit
from controller.app import Application
# Deprecated since 2.1
@Application.app.command(help="Replaced by run --debug command")
def volatile(
service: str = typer.Argument(
...,
help="Service name",
shell_complete=Application.autocomplete_allservice,
),
command: str = typer.Argument(
"bash", help="UNIX command to be executed on selected running service"
),
user: str = typer.Option(
None,<|fim▁hole|> show_default=False,
),
) -> None:
# Deprecated since 2.1
print_and_exit("Volatile command is replaced by rapydo run --debug {}", service)<|fim▁end|> | "--user",
"-u",
help="User existing in selected service", |
<|file_name|>test_eval_power.py<|end_file_name|><|fim▁begin|>from sympy.core import *
def test_rational():
a = Rational(1, 5)
assert a**Rational(1, 2) == a**Rational(1, 2)
assert 2 * a**Rational(1, 2) == 2 * a**Rational(1, 2)
assert a**Rational(3, 2) == a * a**Rational(1, 2)
assert 2 * a**Rational(3, 2) == 2*a * a**Rational(1, 2)
assert a**Rational(17, 3) == a**5 * a**Rational(2, 3)
assert 2 * a**Rational(17, 3) == 2*a**5 * a**Rational(2, 3)
def test_large_rational():
e = (Rational(123712**12-1,7)+Rational(1,7))**Rational(1,3)
assert e == 234232585392159195136 * (Rational(1,7)**Rational(1,3))
def test_negative_real():
def feq(a,b):
return abs(a - b) < 1E-10
assert feq(Basic.One() / Real(-0.5), -Integer(2))
def test_expand():
x = Symbol('x')
assert (2**(-1-x)).expand() == Rational(1,2)*2**(-x)
def test_issue153():
#test that is runs:
a = Basic.sqrt(2*(1+Basic.sqrt(2)))
def test_issue350():
#test if powers are simplified correctly
a = Symbol('a')
assert ((a**Rational(1,3))**Rational(2)) == a**Rational(2,3)
assert ((a**Rational(3))**Rational(2,5)) != a**Rational(6,5)
a = Symbol('a', real = True)
assert (a**Rational(3))**Rational(2,5) == a**Rational(6,5)
#assert Number(5)**Rational(2,3)==Number(25)**Rational(1,3)
<|fim▁hole|><|fim▁end|> |
test_issue350() |
<|file_name|>spotcheck.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from builtins import zip
import pycrfsuite
def compareTaggers(model1, model2, string_list, module_name):
"""
Compare two models. Given a list of strings, prints out tokens & tags
whenever the two taggers parse a string differently. This is for spot-checking models
:param tagger1: a .crfsuite filename
:param tagger2: another .crfsuite filename
:param string_list: a list of strings to be checked
:param module_name: name of a parser module
"""<|fim▁hole|> module = __import__(module_name)
tagger1 = pycrfsuite.Tagger()
tagger1.open(module_name+'/'+model1)
tagger2 = pycrfsuite.Tagger()
tagger2.open(module_name+'/'+model2)
count_discrepancies = 0
for string in string_list:
tokens = module.tokenize(string)
if tokens:
features = module.tokens2features(tokens)
tags1 = tagger1.tag(features)
tags2 = tagger2.tag(features)
if tags1 != tags2:
count_discrepancies += 1
print('\n')
print("%s. %s" %(count_discrepancies, string))
print('-'*75)
print_spaced('token', model1, model2)
print('-'*75)
for token in zip(tokens, tags1, tags2):
print_spaced(token[0], token[1], token[2])
print("\n\n%s of %s strings were labeled differently"%(count_discrepancies, len(string_list)))
def print_spaced(s1, s2, s3):
n = 25
print(s1 + " "*(n-len(s1)) + s2 + " "*(n-len(s2)) + s3)
def validateTaggers(model1, model2, labeled_string_list, module_name):
module = __import__(module_name)
tagger1 = pycrfsuite.Tagger()
tagger1.open(module_name+'/'+model1)
tagger2 = pycrfsuite.Tagger()
tagger2.open(module_name+'/'+model2)
wrong_count_1 = 0
wrong_count_2 = 0
wrong_count_both = 0
correct_count = 0
for labeled_string in labeled_string_list:
unlabeled_string, components = labeled_string
tokens = module.tokenize(unlabeled_string)
if tokens:
features = module.tokens2features(tokens)
_, tags_true = list(zip(*components))
tags_true = list(tags_true)
tags1 = tagger1.tag(features)
tags2 = tagger2.tag(features)
if (tags1 != tags_true) and (tags2 != tags_true):
print("\nSTRING: ", unlabeled_string)
print("TRUE: ", tags_true)
print("*%s: "%model1, tags1)
print("*%s: "%model2, tags2)
wrong_count_both += 1
elif (tags1 != tags_true):
print("\nSTRING: ", unlabeled_string)
print("TRUE: ", tags_true)
print("*%s: "%model1, tags1)
print("%s: "%model2, tags2)
wrong_count_1 += 1
elif (tags2 != tags_true):
print("\nSTRING: ", unlabeled_string)
print("TRUE: ", tags_true)
print("%s: "%model1, tags1)
print("*%s: "%model2, tags2)
wrong_count_2 += 1
else:
correct_count += 1
print("\n\nBOTH WRONG: ", wrong_count_both)
print("%s WRONG: %s" %(model1, wrong_count_1))
print("%s WRONG: %s" %(model2, wrong_count_2))
print("BOTH CORRECT: ", correct_count)<|fim▁end|> | |
<|file_name|>sprites.rs<|end_file_name|><|fim▁begin|>use sdl2::rect::Rect;
use sdl2::video::Window;
use sdl2::render::{Texture, Canvas};
pub struct Sprite<'a> {
rect: Rect,
pub size: Rect,
texture: &'a Texture,
}
impl<'a> Sprite<'a> {
pub fn draw(&self, x: i32, y: i32, canvas: &mut Canvas<Window>) {
let pos_rect = Rect::new(x, y, self.size.width(), self.size.height());<|fim▁hole|> _ => {}
}
}
}
pub struct SpriteSheet {
pub sprite_width: u32,
pub sprite_height: u32,
padding: u32,
pub texture: Texture,
}
impl SpriteSheet {
pub fn new(texture: Texture, sprite_width: u32, sprite_height: u32, padding: u32) -> Self {
SpriteSheet {
sprite_width,
sprite_height,
padding,
texture: texture,
}
}
// Creates a sprite object
pub fn get_sprite(&self, index: usize) -> Sprite {
let texture_query = self.texture.query();
let sheet_width = texture_query.width;
let columns = sheet_width / (self.sprite_width + self.padding);
let sheet_x = index as u32 % columns;
let sheet_y = index as u32 / columns;
let px = sheet_x * (self.sprite_width + self.padding);
let py = sheet_y * (self.sprite_height + self.padding);
Sprite {
rect: Rect::new(px as i32, py as i32, self.sprite_width, self.sprite_height),
size: Rect::new(0, 0, self.sprite_width, self.sprite_height),
texture: &self.texture,
}
}
}<|fim▁end|> | match canvas.copy(&self.texture, Some(self.rect), Some(pos_rect)) {
Err(e) => println!("canvas copy error: {}", e), |
<|file_name|>lastsent_test.go<|end_file_name|><|fim▁begin|>// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package logfwd_test
import (
"github.com/juju/errors"
"github.com/juju/names/v4"
"github.com/juju/testing"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
apiservererrors "github.com/juju/juju/apiserver/errors"
"github.com/juju/juju/apiserver/facades/controller/logfwd"
"github.com/juju/juju/apiserver/params"
apiservertesting "github.com/juju/juju/apiserver/testing"
"github.com/juju/juju/state"
)
type LastSentSuite struct {
testing.IsolationSuite
stub *testing.Stub
state *stubState
authorizer apiservertesting.FakeAuthorizer
}
var _ = gc.Suite(&LastSentSuite{})
func (s *LastSentSuite) SetUpTest(c *gc.C) {
s.IsolationSuite.SetUpTest(c)
s.stub = &testing.Stub{}
s.state = &stubState{stub: s.stub}
s.authorizer = apiservertesting.FakeAuthorizer{
Tag: names.NewMachineTag("99"),
Controller: true,
}
}
func (s *LastSentSuite) TestAuthRefusesUser(c *gc.C) {
anAuthorizer := apiservertesting.FakeAuthorizer{
Tag: names.NewUserTag("bob"),
}
_, err := logfwd.NewLogForwardingAPI(s.state, anAuthorizer)
c.Check(err, gc.ErrorMatches, "permission denied")
}
func (s *LastSentSuite) TestAuthRefusesNonController(c *gc.C) {
anAuthorizer := apiservertesting.FakeAuthorizer{
Tag: names.NewMachineTag("99"),
}
_, err := logfwd.NewLogForwardingAPI(s.state, anAuthorizer)
c.Check(err, gc.ErrorMatches, "permission denied")
}
func (s *LastSentSuite) TestGetLastSentOne(c *gc.C) {
tracker := s.state.addTracker()
tracker.ReturnGet = 10
api, err := logfwd.NewLogForwardingAPI(s.state, s.authorizer)
c.Assert(err, jc.ErrorIsNil)
model := "deadbeef-2f18-4fd2-967d-db9663db7bea"
modelTag := names.NewModelTag(model)
res := api.GetLastSent(params.LogForwardingGetLastSentParams{
IDs: []params.LogForwardingID{{
ModelTag: modelTag.String(),
Sink: "spam",
}},
})
c.Check(res, jc.DeepEquals, params.LogForwardingGetLastSentResults{
Results: []params.LogForwardingGetLastSentResult{{
RecordID: 10,
RecordTimestamp: 100,
}},
})
s.stub.CheckCallNames(c, "NewLastSentTracker", "Get", "Close")
s.stub.CheckCall(c, 0, "NewLastSentTracker", modelTag, "spam")
}
func (s *LastSentSuite) TestGetLastSentBulk(c *gc.C) {
trackerSpam := s.state.addTracker()
trackerSpam.ReturnGet = 10
trackerEggs := s.state.addTracker()
trackerEggs.ReturnGet = 20
s.state.addTracker() // ham
s.stub.SetErrors(nil, nil, nil, nil, state.ErrNeverForwarded)
api, err := logfwd.NewLogForwardingAPI(s.state, s.authorizer)
c.Assert(err, jc.ErrorIsNil)
model := "deadbeef-2f18-4fd2-967d-db9663db7bea"
modelTag := names.NewModelTag(model)
res := api.GetLastSent(params.LogForwardingGetLastSentParams{
IDs: []params.LogForwardingID{{
ModelTag: modelTag.String(),
Sink: "spam",
}, {
ModelTag: modelTag.String(),
Sink: "eggs",
}, {
ModelTag: modelTag.String(),
Sink: "ham",
}},
})
c.Check(res, jc.DeepEquals, params.LogForwardingGetLastSentResults{
Results: []params.LogForwardingGetLastSentResult{{
RecordID: 10,
RecordTimestamp: 100,
}, {
RecordID: 20,
RecordTimestamp: 200,
}, {
Error: ¶ms.Error{
Message: `cannot find ID of the last forwarded record`,
Code: params.CodeNotFound,
},
}},
})
s.stub.CheckCallNames(c,
"NewLastSentTracker", "Get", "Close",
"NewLastSentTracker", "Get", "Close",
"NewLastSentTracker", "Get", "Close",
)
s.stub.CheckCall(c, 0, "NewLastSentTracker", modelTag, "spam")
s.stub.CheckCall(c, 3, "NewLastSentTracker", modelTag, "eggs")
s.stub.CheckCall(c, 6, "NewLastSentTracker", modelTag, "ham")
}
func (s *LastSentSuite) TestSetLastSentOne(c *gc.C) {
s.state.addTracker()
api, err := logfwd.NewLogForwardingAPI(s.state, s.authorizer)
c.Assert(err, jc.ErrorIsNil)
model := "deadbeef-2f18-4fd2-967d-db9663db7bea"
modelTag := names.NewModelTag(model)
res := api.SetLastSent(params.LogForwardingSetLastSentParams{
Params: []params.LogForwardingSetLastSentParam{{
LogForwardingID: params.LogForwardingID{
ModelTag: modelTag.String(),
Sink: "spam",
},<|fim▁hole|> }},
})
c.Check(res, jc.DeepEquals, params.ErrorResults{
Results: []params.ErrorResult{{
Error: nil,
}},
})
s.stub.CheckCallNames(c, "NewLastSentTracker", "Set", "Close")
s.stub.CheckCall(c, 0, "NewLastSentTracker", modelTag, "spam")
s.stub.CheckCall(c, 1, "Set", int64(10), int64(100))
}
func (s *LastSentSuite) TestSetLastSentBulk(c *gc.C) {
s.state.addTracker() // spam
s.state.addTracker() // eggs
s.state.addTracker() // ham
failure := errors.New("<failed>")
s.stub.SetErrors(nil, nil, failure)
api, err := logfwd.NewLogForwardingAPI(s.state, s.authorizer)
c.Assert(err, jc.ErrorIsNil)
model := "deadbeef-2f18-4fd2-967d-db9663db7bea"
modelTag := names.NewModelTag(model)
res := api.SetLastSent(params.LogForwardingSetLastSentParams{
Params: []params.LogForwardingSetLastSentParam{{
LogForwardingID: params.LogForwardingID{
ModelTag: modelTag.String(),
Sink: "spam",
},
RecordID: 10,
RecordTimestamp: 100,
}, {
LogForwardingID: params.LogForwardingID{
ModelTag: modelTag.String(),
Sink: "eggs",
},
RecordID: 20,
RecordTimestamp: 200,
}, {
LogForwardingID: params.LogForwardingID{
ModelTag: modelTag.String(),
Sink: "ham",
},
RecordID: 15,
RecordTimestamp: 150,
}},
})
c.Check(res, jc.DeepEquals, params.ErrorResults{
Results: []params.ErrorResult{{
Error: nil,
}, {
Error: apiservererrors.ServerError(failure),
}, {
Error: nil,
}},
})
s.stub.CheckCallNames(c,
"NewLastSentTracker", "Set", "Close",
"NewLastSentTracker", "Set", "Close",
"NewLastSentTracker", "Set", "Close",
)
s.stub.CheckCall(c, 0, "NewLastSentTracker", modelTag, "spam")
s.stub.CheckCall(c, 1, "Set", int64(10), int64(100))
s.stub.CheckCall(c, 3, "NewLastSentTracker", modelTag, "eggs")
s.stub.CheckCall(c, 4, "Set", int64(20), int64(200))
s.stub.CheckCall(c, 6, "NewLastSentTracker", modelTag, "ham")
s.stub.CheckCall(c, 7, "Set", int64(15), int64(150))
}
type stubState struct {
stub *testing.Stub
ReturnNewLastSentTracker []logfwd.LastSentTracker
}
func (s *stubState) addTracker() *stubTracker {
tracker := &stubTracker{stub: s.stub}
s.ReturnNewLastSentTracker = append(s.ReturnNewLastSentTracker, tracker)
return tracker
}
func (s *stubState) NewLastSentTracker(tag names.ModelTag, sink string) logfwd.LastSentTracker {
s.stub.AddCall("NewLastSentTracker", tag, sink)
if len(s.ReturnNewLastSentTracker) == 0 {
panic("ran out of trackers")
}
tracker := s.ReturnNewLastSentTracker[0]
s.ReturnNewLastSentTracker = s.ReturnNewLastSentTracker[1:]
return tracker
}
type stubTracker struct {
stub *testing.Stub
ReturnGet int64
}
func (s *stubTracker) Get() (int64, int64, error) {
s.stub.AddCall("Get")
if err := s.stub.NextErr(); err != nil {
return 0, 0, err
}
return s.ReturnGet, s.ReturnGet * 10, nil
}
func (s *stubTracker) Set(recID int64, recTimestamp int64) error {
s.stub.AddCall("Set", recID, recTimestamp)
if err := s.stub.NextErr(); err != nil {
return err
}
return nil
}
func (s *stubTracker) Close() error {
s.stub.AddCall("Close")
if err := s.stub.NextErr(); err != nil {
return err
}
return nil
}<|fim▁end|> | RecordID: 10,
RecordTimestamp: 100, |
<|file_name|>telecoms.rs<|end_file_name|><|fim▁begin|>#![feature(unboxed_closures)]
extern crate synthrs;
use synthrs::synthesizer::{ make_samples, quantize_samples };
use synthrs::wave::SineWave;
use synthrs::writer::write_wav;
fn main() {
write_wav("out/dialtone.wav", 44100,<|fim▁hole|> 0.5 * (SineWave(350.0)(t) + SineWave(440.0)(t))
})
)
).ok().expect("failed");
write_wav("out/busysignal.wav", 44100,
quantize_samples::<i16>(
make_samples(8.0, 44100, |t: f64| -> f64 {
if t % 1.0 < 0.5 {
0.5 * (SineWave(480.0)(t) + SineWave(620.0)(t))
} else {
0.0
}
})
)
).ok().expect("failed");
write_wav("out/fastbusysignal.wav", 44100,
quantize_samples::<i16>(
make_samples(15.0, 44100, |t: f64| -> f64 {
if t % 0.5 < 0.25 {
0.5 * (SineWave(480.0)(t) + SineWave(620.0)(t))
} else {
0.0
}
})
)
).ok().expect("failed");
write_wav("out/offhook.wav", 44100,
quantize_samples::<i16>(
make_samples(15.0, 44100, |t: f64| -> f64 {
if t % 0.2 < 0.1 {
0.25 * (
SineWave(1400.0)(t) + SineWave(2060.0)(t) +
SineWave(2450.0)(t) + SineWave(2600.0)(t))
} else {
0.0
}
})
)
).ok().expect("failed");
write_wav("out/ring.wav", 44100,
quantize_samples::<i16>(
make_samples(15.0, 44100, |t: f64| -> f64 {
if t % 6.0 < 2.0 {
0.50 * (SineWave(440.0)(t) + SineWave(480.0)(t))
} else {
0.0
}
})
)
).ok().expect("failed");
}<|fim▁end|> | quantize_samples::<i16>(
make_samples(15.0, 44100, |t: f64| -> f64 { |
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>"""
WSGI config for model_advanced project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application<|fim▁hole|><|fim▁end|> |
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "model_advanced.settings")
application = get_wsgi_application() |
<|file_name|>test_gateway.py<|end_file_name|><|fim▁begin|>"""Test deCONZ gateway."""
from unittest.mock import Mock, patch
import pytest
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.components.deconz import errors, gateway
from tests.common import mock_coro
import pydeconz
ENTRY_CONFIG = {
"host": "1.2.3.4",
"port": 80,
"api_key": "1234567890ABCDEF",
"bridgeid": "0123456789ABCDEF",
"allow_clip_sensor": True,
"allow_deconz_groups": True,
}
async def test_gateway_setup():
"""Successful setup."""
hass = Mock()
entry = Mock()
entry.data = ENTRY_CONFIG
api = Mock()
api.async_add_remote.return_value = Mock()
api.sensors = {}
deconz_gateway = gateway.DeconzGateway(hass, entry)
with patch.object(gateway, 'get_gateway', return_value=mock_coro(api)), \
patch.object(
gateway, 'async_dispatcher_connect', return_value=Mock()):
assert await deconz_gateway.async_setup() is True
assert deconz_gateway.api is api
assert len(hass.config_entries.async_forward_entry_setup.mock_calls) == 7
assert hass.config_entries.async_forward_entry_setup.mock_calls[0][1] == \
(entry, 'binary_sensor')
assert hass.config_entries.async_forward_entry_setup.mock_calls[1][1] == \
(entry, 'climate')
assert hass.config_entries.async_forward_entry_setup.mock_calls[2][1] == \
(entry, 'cover')
assert hass.config_entries.async_forward_entry_setup.mock_calls[3][1] == \
(entry, 'light')
assert hass.config_entries.async_forward_entry_setup.mock_calls[4][1] == \
(entry, 'scene')
assert hass.config_entries.async_forward_entry_setup.mock_calls[5][1] == \
(entry, 'sensor')
assert hass.config_entries.async_forward_entry_setup.mock_calls[6][1] == \
(entry, 'switch')
assert len(api.start.mock_calls) == 1
async def test_gateway_retry():
"""Retry setup."""
hass = Mock()
entry = Mock()
entry.data = ENTRY_CONFIG
deconz_gateway = gateway.DeconzGateway(hass, entry)
with patch.object(
gateway, 'get_gateway', side_effect=errors.CannotConnect), \
pytest.raises(ConfigEntryNotReady):
await deconz_gateway.async_setup()
async def test_gateway_setup_fails():
"""Retry setup."""
hass = Mock()
entry = Mock()
entry.data = ENTRY_CONFIG
deconz_gateway = gateway.DeconzGateway(hass, entry)
with patch.object(gateway, 'get_gateway', side_effect=Exception):
result = await deconz_gateway.async_setup()
assert not result
async def test_connection_status(hass):
"""Make sure that connection status triggers a dispatcher send."""
entry = Mock()
entry.data = ENTRY_CONFIG
deconz_gateway = gateway.DeconzGateway(hass, entry)
with patch.object(gateway, 'async_dispatcher_send') as mock_dispatch_send:
deconz_gateway.async_connection_status_callback(True)
await hass.async_block_till_done()
assert len(mock_dispatch_send.mock_calls) == 1
assert len(mock_dispatch_send.mock_calls[0]) == 3
async def test_add_device(hass):
"""Successful retry setup."""
entry = Mock()
entry.data = ENTRY_CONFIG
deconz_gateway = gateway.DeconzGateway(hass, entry)
with patch.object(gateway, 'async_dispatcher_send') as mock_dispatch_send:
deconz_gateway.async_add_device_callback('sensor', Mock())
await hass.async_block_till_done()
assert len(mock_dispatch_send.mock_calls) == 1
assert len(mock_dispatch_send.mock_calls[0]) == 3
async def test_add_remote():
"""Successful add remote."""
hass = Mock()
entry = Mock()
entry.data = ENTRY_CONFIG
remote = Mock()
remote.name = 'name'
remote.type = 'ZHASwitch'
remote.register_async_callback = Mock()
deconz_gateway = gateway.DeconzGateway(hass, entry)
deconz_gateway.async_add_remote([remote])
assert len(deconz_gateway.events) == 1
async def test_shutdown():
"""Successful shutdown."""
hass = Mock()
entry = Mock()
entry.data = ENTRY_CONFIG
deconz_gateway = gateway.DeconzGateway(hass, entry)
deconz_gateway.api = Mock()
deconz_gateway.shutdown(None)
assert len(deconz_gateway.api.close.mock_calls) == 1
async def test_reset_after_successful_setup():
"""Verify that reset works on a setup component."""
hass = Mock()
entry = Mock()
entry.data = ENTRY_CONFIG
api = Mock()
api.async_add_remote.return_value = Mock()
api.sensors = {}
deconz_gateway = gateway.DeconzGateway(hass, entry)
with patch.object(gateway, 'get_gateway', return_value=mock_coro(api)), \
patch.object(
gateway, 'async_dispatcher_connect', return_value=Mock()):
assert await deconz_gateway.async_setup() is True
listener = Mock()
deconz_gateway.listeners = [listener]
event = Mock()
event.async_will_remove_from_hass = Mock()
deconz_gateway.events = [event]
deconz_gateway.deconz_ids = {'key': 'value'}
hass.config_entries.async_forward_entry_unload.return_value = \
mock_coro(True)
assert await deconz_gateway.async_reset() is True
assert len(hass.config_entries.async_forward_entry_unload.mock_calls) == 7
assert len(listener.mock_calls) == 1
assert len(deconz_gateway.listeners) == 0
assert len(event.async_will_remove_from_hass.mock_calls) == 1<|fim▁hole|>
async def test_get_gateway(hass):
"""Successful call."""
with patch('pydeconz.DeconzSession.async_load_parameters',
return_value=mock_coro(True)):
assert await gateway.get_gateway(hass, ENTRY_CONFIG, Mock(), Mock())
async def test_get_gateway_fails_unauthorized(hass):
"""Failed call."""
with patch('pydeconz.DeconzSession.async_load_parameters',
side_effect=pydeconz.errors.Unauthorized), \
pytest.raises(errors.AuthenticationRequired):
assert await gateway.get_gateway(
hass, ENTRY_CONFIG, Mock(), Mock()) is False
async def test_get_gateway_fails_cannot_connect(hass):
"""Failed call."""
with patch('pydeconz.DeconzSession.async_load_parameters',
side_effect=pydeconz.errors.RequestError), \
pytest.raises(errors.CannotConnect):
assert await gateway.get_gateway(
hass, ENTRY_CONFIG, Mock(), Mock()) is False
async def test_create_event():
"""Successfully created a deCONZ event."""
hass = Mock()
remote = Mock()
remote.name = 'Name'
event = gateway.DeconzEvent(hass, remote)
assert event._id == 'name'
async def test_update_event():
"""Successfully update a deCONZ event."""
hass = Mock()
remote = Mock()
remote.name = 'Name'
event = gateway.DeconzEvent(hass, remote)
remote.changed_keys = {'state': True}
event.async_update_callback()
assert len(hass.bus.async_fire.mock_calls) == 1
async def test_remove_event():
"""Successfully update a deCONZ event."""
hass = Mock()
remote = Mock()
remote.name = 'Name'
event = gateway.DeconzEvent(hass, remote)
event.async_will_remove_from_hass()
assert event._device is None<|fim▁end|> | assert len(deconz_gateway.events) == 0
assert len(deconz_gateway.deconz_ids) == 0 |
<|file_name|>inject.ts<|end_file_name|><|fim▁begin|>/// <reference path="refs.d.ts" />
interface IInjectFn {
invoker(locals: any);
}
var $InjectProvider = [<any>
function () {
'use strict';
this.$get = [<any> '$injector',
function ($injector: ng.auto.IInjectorService): dotjem.routing.IInjectService {
function createInvoker(fn): dotjem.routing.IInvoker {
if (isInjectable(fn)) {
var injector = new InjectFn(fn, $injector);
return function (locals?: any) {
return injector.invoker(locals);
};
}
return null;
}
return {
//Note: Rerouting of injector functions in cases where those are move convinient.
get: $injector.get ,
annotate: $injector.annotate,
instantiate: $injector.instantiate,
invoke: $injector.invoke,
accepts: isInjectable,
create: createInvoker
};
}];
}];
angular.module('dotjem.routing').provider('$inject', $InjectProvider);
//Note: All parts that has been commented out here is purpously left there as they are for a later optimization.
// of all internal inject handlers.
class InjectFn implements IInjectFn {
private static FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
private static FN_ARG_SPLIT = /,/;
private static FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
private static STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
//private dependencies: string[];
private func: any;
//private invokerFn: dotjem.routing.IInvoker;
constructor(private fn: any, private $inject: ng.auto.IInjectorService) {
//var last;
if (isArray(fn)) {
//last = fn.length - 1;
//this.func = fn[last];
this.func = fn[fn.length - 1];
//this.dependencies = fn.slice(0, last);
} else if (isFunction(fn)) {
this.func = fn;
//if (fn.$inject) {
// this.dependencies = fn.$inject;
//} else {
// this.dependencies = this.extractDependencies(fn);
//}
}
}
//private extractDependencies(fn: any) {
// var fnText,
// argDecl,
// deps = [];
// if (fn.length) {
// fnText = fn.toString().replace(InjectFn.STRIP_COMMENTS, '');
// argDecl = fnText.match(InjectFn.FN_ARGS);
// forEach(argDecl[1].split(InjectFn.FN_ARG_SPLIT), function (arg) {
// arg.replace(InjectFn.FN_ARG, function (all, underscore, name) {
// deps.push(name);
// });
// });
// }
// return deps;
//}
public invoker(locals: any): any {
return this.$inject.invoke(this.fn, this.func, locals);
//Note: This part does not work, nor is it optimized as it should.
// generally when creating a handler through here locals are static meaning we can predict how the arg
// array should be resolved, therefore we can cache all services we require from the injector and just
// patch in locals on calls.
//<|fim▁hole|> // var i = 0, key;
// for (; i < length; i++) {
// key = this.dependencies[i];
// args.push(
// locals && locals.hasOwnProperty(key)
// ? locals[key]
// : this.$inject.get(key)
// );
// }
// return this.func.apply(self, args);
// };
//}
//return this.invokerFn(locals);
}
}<|fim▁end|> | //if (this.invokerFn == null) {
// this.invokerFn = (locals?: any) => {
// var args = [];
// var l = this.dependencies.length; |
<|file_name|>CoursesView.js<|end_file_name|><|fim▁begin|>;
define('views/courses/CoursesView', ['appframework', 'mustache', 'controllers/Courses', 'i18n!nls/courses', 'routers/coursesrouter'],
(function ($, mustache, controller, courses, router) {
var courseTemplate, currentSearch;
var $coursesSearch, $courses;
var doInit = function (data) {
router.init();
$coursesSearch = $('#user-courses-search');
$courses = $('#user-courses');
controller.init(this);
require([
'text!../tpl/course-tpl.html'
], function (tpl) {
courseTemplate = tpl;
controller.updateMyCourses(data);
/*
if($('#afui').get(0).className === 'ios7'){
$('body').removeClass('moveDown');
setTimeout(function(){
$('body').addClass('moveDown');
}, 150);
}
*/
});
};
var doShowError = function (msg) {
if (msg) {
$.ui.popup(msg);
}
};
var doShowCourse = function (data) {
var html = mustache.to_html(courseTemplate, data);
$courses.html($courses.html() + html);
};
var doClearCourses = function () {
$courses.html('');
};
var onCourseSearch = function (evt) {
var filter = this.value;
if (currentSearch) {
clearTimeout(currentSearch);
}
currentSearch = setTimeout(function () {
$courses.find('li').each(function (i, e) {
var sel = $(e).find('div strong').text().toLowerCase().trim();
var query = filter.toLowerCase();
if (sel.indexOf(query) === -1) {
$(e).hide();
} else {
$(e).show();
}
});
}, 300);
};
var doInitCoursesInteraction = function (status) {
if (status) {
$courses.bind('tap', onCourseSelection);
$coursesSearch.bind('input', onCourseSearch);
} else {
$courses.unbind('tap', onCourseSelection);
$coursesSearch.unbind('input', onCourseSearch);
}
};
var doShowLoader = function (status, message) {
if (status) {
$.ui.showMask(message || courses.loading);
} else {
$.ui.hideMask();<|fim▁hole|> };
var onCourseSelection = function (evt) {
evt.preventDefault();
var target = $(evt.target).parents('li');
var url = target.attr('data-url'),
idCourse = url.match(/course_id=([^&]*)/)[1],
thumb = target.find('img').css('background-image'),
name = target.find('strong').text(),
canAccess = target.attr('data-can'),
courseDescription = target.find('.detail-disclosure').html();
// if(canAccess != true)return;
thumb = /^url\((['"]?)(.*)\1\)$/.exec(thumb);
thumb = thumb ? thumb[2] : '';
localStorage.setItem('currentCourseName', name);
localStorage.setItem('currentCourseThumb', thumb);
localStorage.setItem('currentCourseDescription', courseDescription);
controller.getCourseDetails(idCourse);
};
return {
init: doInit,
showError: doShowError,
showCourse: doShowCourse,
clearCourses: doClearCourses,
showLoader: doShowLoader,
initCoursesInteraction: doInitCoursesInteraction
}
}));<|fim▁end|> | } |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*-<|fim▁hole|>""" EOSS catalog system
external catalog management package
"""
__author__ = "Thilo Wehrmann, Steffen Gebhardt"
__copyright__ = "Copyright 2016, EOSS GmbH"
__credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Thilo Wehrmann"
__email__ = "[email protected]"
__status__ = "Production"
from abc import ABCMeta, abstractmethod
from utilities import with_metaclass
@with_metaclass(ABCMeta)
class ICatalog(object):
"""
Simple catalog interface class
"""
def __init__(self):
pass
@abstractmethod
def find(self):
pass
@abstractmethod
def register(self, ds):
pass<|fim▁end|> | |
<|file_name|>groups_list.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-<|fim▁hole|>/***************************************************************************
QuickMapServices
A QGIS plugin
Collection of internet map services
-------------------
begin : 2014-11-21
git sha : $Format:%H$
copyright : (C) 2014 by NextGIS
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
from __future__ import absolute_import
import codecs
import os
import sys
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QMenu
from qgis.core import QgsMessageLog
from .config_reader_helper import ConfigReaderHelper
from . import extra_sources
from .custom_translator import CustomTranslator
from .group_info import GroupInfo, GroupCategory
from .plugin_locale import Locale
from .compat import configparser, get_file_dir
from .compat2qgis import message_log_levels
CURR_PATH = get_file_dir(__file__)
INTERNAL_GROUP_PATHS = [os.path.join(CURR_PATH, extra_sources.GROUPS_DIR_NAME), ]
CONTRIBUTE_GROUP_PATHS = [os.path.join(extra_sources.CONTRIBUTE_DIR_PATH, extra_sources.GROUPS_DIR_NAME), ]
USER_GROUP_PATHS = [os.path.join(extra_sources.USER_DIR_PATH, extra_sources.GROUPS_DIR_NAME), ]
ALL_GROUP_PATHS = INTERNAL_GROUP_PATHS + CONTRIBUTE_GROUP_PATHS + USER_GROUP_PATHS
ROOT_MAPPING = {
INTERNAL_GROUP_PATHS[0]: GroupCategory.BASE,
CONTRIBUTE_GROUP_PATHS[0]: GroupCategory.CONTRIB,
USER_GROUP_PATHS[0]: GroupCategory.USER
}
class GroupsList(object):
def __init__(self, group_paths=ALL_GROUP_PATHS):
self.locale = Locale.get_locale()
self.translator = CustomTranslator()
self.paths = group_paths
self.groups = {}
self._fill_groups_list()
def _fill_groups_list(self):
self.groups = {}
for gr_path in self.paths:
if gr_path in ROOT_MAPPING.keys():
category = ROOT_MAPPING[gr_path]
else:
category = GroupCategory.USER
for root, dirs, files in os.walk(gr_path):
for ini_file in [f for f in files if f.endswith('.ini')]:
self._read_ini_file(root, ini_file, category)
def _read_ini_file(self, root, ini_file_path, category):
try:
ini_full_path = os.path.join(root, ini_file_path)
parser = configparser.ConfigParser()
with codecs.open(ini_full_path, 'r', 'utf-8') as ini_file:
if hasattr(parser, "read_file"):
parser.read_file(ini_file)
else:
parser.readfp(ini_file)
#read config
group_id = parser.get('general', 'id')
group_alias = parser.get('ui', 'alias')
icon_file = ConfigReaderHelper.try_read_config(parser, 'ui', 'icon')
group_icon_path = os.path.join(root, icon_file) if icon_file else None
#try read translations
posible_trans = parser.items('ui')
for key, val in posible_trans:
if type(key) is unicode and key == 'alias[%s]' % self.locale:
self.translator.append(group_alias, val)
break
#create menu
group_menu = QMenu(self.tr(group_alias))
group_menu.setIcon(QIcon(group_icon_path))
#append to all groups
# set contrib&user
self.groups[group_id] = GroupInfo(group_id, group_alias, group_icon_path, ini_full_path, group_menu, category)
except Exception as e:
error_message = self.tr('Group INI file can\'t be parsed: ') + e.message
QgsMessageLog.logMessage(error_message, level=message_log_levels["Critical"])
def get_group_menu(self, group_id):
if group_id in self.groups:
return self.groups[group_id].menu
else:
info = GroupInfo(group_id=group_id, menu=QMenu(group_id))
self.groups[group_id] = info
return info.menu
# noinspection PyMethodMayBeStatic
def tr(self, message):
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return self.translator.translate('QuickMapServices', message)<|fim▁end|> | """ |
<|file_name|>test_isodownload.py<|end_file_name|><|fim▁begin|>"""Test class for ISO downloads UI
:Requirement: Isodownload
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from robottelo.decorators import run_only_on, stubbed, tier1
from robottelo.test import UITestCase
class ISODownloadTestCase(UITestCase):
"""Test class for iso download feature"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_download(self):
"""Downloading ISO from export
:id: 47f20df7-f6f3-422b-b57b-3a5ef9cf62ad
:Steps:
1. find out the location where all iso's are kept
2. check whether a valid iso can be downloaded
:expectedresults: iso file is properly downloaded on your satellite
6 system
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_upload(self):
"""Uploadng the iso successfully to the sat6 system
:id: daf87a68-7c61-46f1-b4cc-021476080b6b
:Steps:
1. download the iso
2. upload it to sat6 system
:expectedresults: uploading iso to satellite6 is successful
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_mount(self):
"""Mounting iso to directory accessible to satellite6 works
:id: 44d3c8fa-c01f-438c-b83e-8f6894befbbf
:Steps:
1. download the iso
2. upload it to sat6 system
3. mount it a local sat6 directory
:expectedresults: iso is mounted to sat6 local directory
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_validate_cdn_url(self):
"""Validate that cdn url to file path works
:id: 00157f61-1557-48a7-b7c9-6dac726eff94
:Steps:
1. after mounting the iso locally try to update the cdn url
2. the path should be validated
:expectedresults: cdn url path is validated
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_check_message(self):
"""Check if proper message is displayed after successful upload
:id: 5ed31a26-b902-4352-900f-bb38eac95511
:Steps:
1. mount the iso to sat6
2. update the cdn url with file path
3. check if proper message is displayed
:expectedresults: Asserting the message after successful upload
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_enable_repo(self):
"""Enable the repositories
:id: e33e2796-0554-419f-b5a1-3e2c8e23e950
:Steps:
1. mount iso to directory
2. update cdn url
3. upload manifest
4. try to enable redhat repositories
:expectedresults: Redhat repositories are enabled
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_validate_checkboxes(self):
"""Check if enabling the checkbox works
:id: 10b19405-f82e-4f95-869d-28d91cac1e6f
:Steps:
1. mount iso to directory
2. update cdn url
3. upload manifest
4. Click the checkbox to enable redhat repositories
5. redhat repository enabled
:expectedresults: Checkbox functionality works
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_sync_repos(self):
"""Sync repos to local iso's
:id: 96266438-4a52-4222-b573-96bd7cde1700
:Steps:
1. mount iso to directory
2. update cdn url
3. upload manifest
4. try to enable redhat repositories
5. sync the repos
:expectedresults: Repos are synced after upload
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_disable_repo(self):
"""Disabling the repo works
:id: 075700a7-fda0-41db-b9b7-3d6b29f63784
<|fim▁hole|> :Steps:
1. mount iso to directory
2. update cdn url
3. upload manifest
4. try to enable redhat repositories
5. sync the contents
6. try disabling the repository
:expectedresults: Assert disabling the repo
:caseautomation: notautomated
:CaseImportance: Critical
"""<|fim▁end|> | |
<|file_name|>sns.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""This module contains AWS SNS hook"""
import json
import warnings
from typing import Dict, Optional, Union
from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook
def _get_message_attribute(o):
if isinstance(o, bytes):
return {'DataType': 'Binary', 'BinaryValue': o}<|fim▁hole|> if isinstance(o, str):
return {'DataType': 'String', 'StringValue': o}
if isinstance(o, (int, float)):
return {'DataType': 'Number', 'StringValue': str(o)}
if hasattr(o, '__iter__'):
return {'DataType': 'String.Array', 'StringValue': json.dumps(o)}
raise TypeError(
f'Values in MessageAttributes must be one of bytes, str, int, float, or iterable; got {type(o)}'
)
class SnsHook(AwsBaseHook):
"""
Interact with Amazon Simple Notification Service.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.
.. seealso::
:class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
"""
def __init__(self, *args, **kwargs):
super().__init__(client_type='sns', *args, **kwargs)
def publish_to_target(
self,
target_arn: str,
message: str,
subject: Optional[str] = None,
message_attributes: Optional[dict] = None,
):
"""
Publish a message to a topic or an endpoint.
:param target_arn: either a TopicArn or an EndpointArn
:param message: the default message you want to send
:param message: str
:param subject: subject of message
:param message_attributes: additional attributes to publish for message filtering. This should be
a flat dict; the DataType to be sent depends on the type of the value:
- bytes = Binary
- str = String
- int, float = Number
- iterable = String.Array
"""
publish_kwargs: Dict[str, Union[str, dict]] = {
'TargetArn': target_arn,
'MessageStructure': 'json',
'Message': json.dumps({'default': message}),
}
# Construct args this way because boto3 distinguishes from missing args and those set to None
if subject:
publish_kwargs['Subject'] = subject
if message_attributes:
publish_kwargs['MessageAttributes'] = {
key: _get_message_attribute(val) for key, val in message_attributes.items()
}
return self.get_conn().publish(**publish_kwargs)
class AwsSnsHook(SnsHook):
"""
This hook is deprecated.
Please use :class:`airflow.providers.amazon.aws.hooks.sns.SnsHook`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(
"This hook is deprecated. " "Please use :class:`airflow.providers.amazon.aws.hooks.sns.SnsHook`.",
DeprecationWarning,
stacklevel=2,
)
super().__init__(*args, **kwargs)<|fim▁end|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.