text
stringlengths
3
1.05M
module.exports = { plugins:[ require("autoprefixer") ] }
# coding: utf-8 """ Pure Storage FlashBlade REST 1.0 Python SDK Pure Storage FlashBlade REST 1.0 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/). OpenAPI spec version: 1.0 Contact: info@purestorage.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class ErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'error': 'list[PureError]' } attribute_map = { 'error': 'error' } def __init__(self, error=None): """ ErrorResponse - a model defined in Swagger """ self._error = None if error is not None: self.error = error @property def error(self): """ Gets the error of this ErrorResponse. a list of error objects :return: The error of this ErrorResponse. :rtype: list[PureError] """ return self._error @error.setter def error(self, error): """ Sets the error of this ErrorResponse. a list of error objects :param error: The error of this ErrorResponse. :type: list[PureError] """ self._error = error def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, ErrorResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
// api_key 获取方式:登录 [Dashboard](https://dashboard.pay.lucfish.com)->点击管理平台右上角公司名称->开发信息-> Secret Key var API_KEY = 'sk_test_ibbTe5jLGCi5rzfH4OqPW9KC'; // 设置 api_key var xpay = require('../../lib/xpay')(API_KEY); var path = require('path'); xpay.setPrivateKeyPath(path.join(__dirname, '../your_rsa_private_key.pem')); /* 取消 */ xpay.transfers.cancel( 'tr_uHWX58DanDOGCKOynHvPirfT', function (err, transfer) { if (err != null) { console.log('xpay.transfers.cancel failed: ', err); } else { console.log(transfer); } // YOUR CODE } );
var searchData= [ ['detach_0',['detach',['../class_ground_mission_control.html#ae5ffb37c3e088247b939ccc6d6239ecb',1,'GroundMissionControl']]], ['dragon_1',['Dragon',['../class_dragon.html',1,'Dragon'],['../class_dragon.html#a79b87e0d47c37113663005bd6d3ec06e',1,'Dragon::Dragon()']]] ];
import pandas as pd from game import Game from player import Player def get_players_and_games(): # CSV file with all the players and every game they've played in gl = pd.read_csv('data/GameLineupNBA.csv') # Makes dictionary with key = game_id, value = Game object games = get_all_games(gl) # Makes dictionary with key = player_id, value = Player object players = get_all_players(gl) # Loops through all 240 players for player_id in players: # Populates all the games the player has played by updating the "ratings" dictionary in each Player # object with key = game_id, value = dictionary { "off": 0, "def": 0 } where "off" is the offensive # rating and "def" is the defensive rating of the player in that particular game players = populate_player_games(gl, players, player_id) # Populates all the starting lineups in a game by updating the "teams" dictionary # in each Game object, with key = team_id, value = [list of player_ids on that team] # Every "teams" dictionary has two keys because two teams play in a game # Each key in the "teams" dictionary has a list of 5 players (starting lineup) games = populate_game_starting_lineups(gl, games, player_id) return games, players def populate_game_starting_lineups(gl, games, player_id): """ Populates all the starting lineups in a game by updating the "teams" dictionary in each Game object, with key = team_id, value = [list of player_ids on that team] Every "teams" dictionary has two keys because two teams play in a game Each key in the "teams" dictionary has a list of 5 players (starting lineup) :param gl: Dataframe of GameLineupNBA.csv :param games: Dictionary mapping game_id's to Game objects :param player_id: the unique id string of a player :return: updated games dictionary which maps game_id's to Game objects """ # Filters the dataframe to find all players with the specified player_id and the starting # lineup denoted by period 1 df = gl[(gl["Person_id"] == player_id) & (gl["Period"] == 1)] # Loop through each row of the df for index, row in df.iterrows(): game_id = row["Game_id"] team_id = row["Team_id"] if team_id in games[game_id].teams: # If the team_id already exists in the "teams" dictionary # then just append the current player_id to the list of players # on the team games[game_id].teams[team_id]["players"].append(player_id) else: # If the team_id does not exist yet in the "teams" dictionary # then just create a new team_id key and set its value to be a new list with # the first player id on the team games[game_id].teams[team_id] = { "is_off": False, "players": [player_id] } # Returns the updated dictionary of games return games def populate_player_games(gl, players, player_id): """ Populates all the games the player has played by updating the "ratings" dictionary in each Player object with key = game_id, value = dictionary { "off": 0, "def": 0 } where "off" is the offensive rating and "def" is the defensive rating of the player in that particular game :param gl: Dataframe of GameLineupNBA.csv :param players: Dictionary mapping player_id's to Player objects :param player_id: the unique id string of a player :return: updated players dictionary which maps player_id's to Player objects """ # Get rid of all the game_id duplicates because we're just looking for the one player with # the specified player_id. The player might have played in multiple Periods, # so that's why we have to get rid of the duplicate rows. df = gl[gl["Person_id"] == player_id].drop_duplicates(subset="Game_id") # Loop through the filtered dataframe for index, row in df.iterrows(): game_id = row["Game_id"] # Find the player object for the specified player_id and update the ratings dictionary # by setting the key to the game_id the player participated in and set the value # to a default dictionary of { "off": 0, "def": 0 } players[player_id].ratings[game_id] = { "off_pos": 0,"off_pts": 0, "def_pos": 0,"def_pts": 0 } # Returns the updated dictionary of players return players def get_all_players(gl): """Takes in a game lineup dataframe and outputs dictionary of player ids mapped to Player objects :param gl: Dataframe of GameLineupNBA.csv :return: players dictionary which maps player_id's to Player objects """ players = {} # Getting all the unique players in the csv for index, row in gl.drop_duplicates(subset ="Person_id").iterrows(): players[row["Person_id"]] = Player(row['Person_id'], row["Team_id"]) return players def get_all_games(gl): """Takes in a game lineup dataframe and outputs dictionary of game ids mapped to Game objects :param gl: Dataframe of GameLineupNBA.csv :return: games dictionary which maps game_id's to Game objects """ games = {} # Getting all the unique games in the csv for index, game_id in gl.drop_duplicates(subset ="Game_id")["Game_id"].iteritems(): games[game_id] = Game(game_id) return games
#coding: utf-8 import json import requests from .exceptions import WrongPhoneCompanyError class CompropagoCharge(object): """ order_id = "SMGCURL1", order_price = 10000.0, order_name = "SAMSUNG GOLD CURL", customer_name = "Alejandra Leyva", customer_email = "noreply@compropago.com", payment_type = "OXXO" """ def __init__(self, order_id, order_price, order_name, customer_name, customer_email, payment_type): self.order_id = order_id self.order_price = order_price self.order_name = order_name self.customer_name = customer_name self.customer_email = customer_email self.payment_type = payment_type # Last update to CP API expects data with these names self.product_id = order_id self.product_price = order_price self.product_name = order_name def to_dict(self): return { 'order_id': self.order_id, 'order_price': self.order_price, 'order_name': self.order_name, 'customer_name': self.customer_name, 'customer_email': self.customer_email, 'payment_type': self.payment_type, #Compatibility for new API changes (Jun 16, 2015) 'product_id': self.product_id, 'product_price': self.product_price, 'product_name': self.product_name, } class CompropagoAPI(object): errores = { 4001: u'Llave no encontrada', 5001: u'ID de pago no encontrado', 5002: u'Tienda no encontrada', 5003: u'El precio del producto excede el límite por transacción en el establecimiento seleccionado', 6001: u'Hubo un problema con el proveedor de SMS y el mensaje no se envío', 6002: u'Se ha superado el número de envios SMS, máximo 2 mensajes por orden de pago', 6003: u'Compañia celular inválida, soportamos: TELCEL, MOVISTAR, IUSACELL, UNEFON y NEXTEL', 6004: u'Número de celular no válido, probablemente el número contiene menos o más de 10 dígitos', } def __init__(self, api_key, url_base='https://api.compropago.com/v1'): self.api_key = api_key self.url_base = url_base @property def auth(self): return (self.api_key, '') @property def headers(self): return { 'Accept': 'application/compropago', 'Content-Type': 'application/json', 'User-Agent': 'Django LFS - http://www.getlfs.com/' } def charge(self, charge): if not isinstance(charge, CompropagoCharge): raise TypeError('%s no es una instancia de CompropagoCharge.' % str(charge)) return requests.post( '/'.join((self.url_base, 'charges')), headers = self.headers, json = charge.to_dict(), auth = self.auth ).json() def verify_charge(self, payment_id): return requests.get( '/'.join((self.url_base, 'charges', payment_id)), auth = self.auth, headers = self.headers ).json() def send_sms(self, payment_id, phone, company): """ Ofrece a tus usuarios la posibilidad de recibir las instrucciones de pago directo en su telefono celular. Los unicos campos requeridos son el numero de celular y su compania telefonica. """ if company.upper() not in ('TELCEL' 'MOVISTAR' 'IUSACELL' 'NEXTEL'): raise WrongPhoneCompanyError( 'Las unicas companias soportadas son TELCEL, IUSACELL y MOVISTAR y NEXTEL' ) payload = json.dumps({'customer_phone': phone, 'customer_company_phone': company}) return requests.post( '/'.join((self.url_base, 'charges', payment_id, 'sms')), data = payload, auth = self.auth, headers = self.headers ).json()
import * as types from './actionTypes'; import * as API from '../../api'; import * as reduxHelper from '../../helpers/reduxHelper'; export const setProvinces = (provinces) => reduxHelper.action(types.SET_PROVINCES, provinces); export const startSetProvinces = () => (dispatch) => { return API.getProvinces().then((res) => { if (res.data.status === true) { dispatch(setProvinces(res.data.payload)); } }); };
# Test interfaces to fortran blas. # # The tests are more of interface than they are of the underlying blas. # Only very small matrices checked -- N=3 or so. # # !! Complex calculations really aren't checked that carefully. # !! Only real valued complex numbers are used in tests. from __future__ import division, print_function, absolute_import from numpy import zeros, transpose, newaxis, shape, float32, float64, \ complex64, complex128, arange, array, common_type, conjugate from numpy.testing import assert_equal, assert_array_almost_equal, \ run_module_suite, TestCase from scipy.lib.six.moves import xrange from scipy.lib.blas import fblas # decimal accuracy to require between Python and LAPACK/BLAS calculations accuracy = 5 # Since numpy.dot likely uses the same blas, use this routine # to check. def matrixmultiply(a, b): if len(b.shape) == 1: b_is_vector = True b = b[:,newaxis] else: b_is_vector = False assert_equal(a.shape[1], b.shape[0]) c = zeros((a.shape[0], b.shape[1]), common_type(a, b)) for i in xrange(a.shape[0]): for j in xrange(b.shape[1]): s = 0 for k in xrange(a.shape[1]): s += a[i,k] * b[k, j] c[i,j] = s if b_is_vector: c = c.reshape((a.shape[0],)) return c ################################################## ### Test blas ?axpy class BaseAxpy(object): # Mixin class to test dtypes def test_default_a(self): x = arange(3.,dtype=self.dtype) y = arange(3.,dtype=x.dtype) real_y = x*1.+y self.blas_func(x,y) assert_array_almost_equal(real_y,y) def test_simple(self): x = arange(3.,dtype=self.dtype) y = arange(3.,dtype=x.dtype) real_y = x*3.+y self.blas_func(x,y,a=3.) assert_array_almost_equal(real_y,y) def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) y = arange(3.,dtype=x.dtype) real_y = x[::2]*3.+y self.blas_func(x,y,a=3.,n=3,incx=2) assert_array_almost_equal(real_y,y) def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) real_y = x*3.+y[::2] self.blas_func(x,y,a=3.,n=3,incy=2) assert_array_almost_equal(real_y,y[::2]) def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) real_y = x[::4]*3.+y[::2] self.blas_func(x,y,a=3.,n=3,incx=4,incy=2) assert_array_almost_equal(real_y,y[::2]) def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: self.blas_func(x,y,n=4,incx=5) except: # what kind of error should be caught? return # should catch error and never get here assert_(0) def test_y_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: self.blas_func(x,y,n=3,incy=5) except: # what kind of error should be caught? return # should catch error and never get here assert_(0) try: class TestSaxpy(TestCase, BaseAxpy): blas_func = fblas.saxpy dtype = float32 except AttributeError: class TestSaxpy: pass class TestDaxpy(TestCase, BaseAxpy): blas_func = fblas.daxpy dtype = float64 try: class TestCaxpy(TestCase, BaseAxpy): blas_func = fblas.caxpy dtype = complex64 except AttributeError: class TestCaxpy: pass class TestZaxpy(TestCase, BaseAxpy): blas_func = fblas.zaxpy dtype = complex128 ################################################## ### Test blas ?scal class BaseScal(object): # Mixin class for testing particular dtypes def test_simple(self): x = arange(3.,dtype=self.dtype) real_x = x*3. self.blas_func(3.,x) assert_array_almost_equal(real_x,x) def test_x_stride(self): x = arange(6.,dtype=self.dtype) real_x = x.copy() real_x[::2] = x[::2]*array(3.,self.dtype) self.blas_func(3.,x,n=3,incx=2) assert_array_almost_equal(real_x,x) def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) try: self.blas_func(2.,x,n=4,incx=5) except: # what kind of error should be caught? return # should catch error and never get here assert_(0) try: class TestSscal(TestCase, BaseScal): blas_func = fblas.sscal dtype = float32 except AttributeError: class TestSscal: pass class TestDscal(TestCase, BaseScal): blas_func = fblas.dscal dtype = float64 try: class TestCscal(TestCase, BaseScal): blas_func = fblas.cscal dtype = complex64 except AttributeError: class TestCscal: pass class TestZscal(TestCase, BaseScal): blas_func = fblas.zscal dtype = complex128 ################################################## ### Test blas ?copy class BaseCopy(object): # Mixin class for testing dtypes def test_simple(self): x = arange(3.,dtype=self.dtype) y = zeros(shape(x),x.dtype) self.blas_func(x,y) assert_array_almost_equal(x,y) def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) self.blas_func(x,y,n=3,incx=2) assert_array_almost_equal(x[::2],y) def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) self.blas_func(x,y,n=3,incy=2) assert_array_almost_equal(x,y[::2]) def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) self.blas_func(x,y,n=3,incx=4,incy=2) assert_array_almost_equal(x[::4],y[::2]) def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: self.blas_func(x,y,n=4,incx=5) except: # what kind of error should be caught? return # should catch error and never get here assert_(0) def test_y_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: self.blas_func(x,y,n=3,incy=5) except: # what kind of error should be caught? return # should catch error and never get here assert_(0) # def test_y_bad_type(self): ## Hmmm. Should this work? What should be the output. # x = arange(3.,dtype=self.dtype) # y = zeros(shape(x)) # self.blas_func(x,y) # assert_array_almost_equal(x,y) try: class TestScopy(TestCase, BaseCopy): blas_func = fblas.scopy dtype = float32 except AttributeError: class TestScopy: pass class TestDcopy(TestCase, BaseCopy): blas_func = fblas.dcopy dtype = float64 try: class TestCcopy(TestCase, BaseCopy): blas_func = fblas.ccopy dtype = complex64 except AttributeError: class TestCcopy: pass class TestZcopy(TestCase, BaseCopy): blas_func = fblas.zcopy dtype = complex128 ################################################## ### Test blas ?swap class BaseSwap(object): # Mixin class to implement test objects def test_simple(self): x = arange(3.,dtype=self.dtype) y = zeros(shape(x),x.dtype) desired_x = y.copy() desired_y = x.copy() self.blas_func(x,y) assert_array_almost_equal(desired_x,x) assert_array_almost_equal(desired_y,y) def test_x_stride(self): x = arange(6.,dtype=self.dtype) y = zeros(3,x.dtype) desired_x = y.copy() desired_y = x.copy()[::2] self.blas_func(x,y,n=3,incx=2) assert_array_almost_equal(desired_x,x[::2]) assert_array_almost_equal(desired_y,y) def test_y_stride(self): x = arange(3.,dtype=self.dtype) y = zeros(6,x.dtype) desired_x = y.copy()[::2] desired_y = x.copy() self.blas_func(x,y,n=3,incy=2) assert_array_almost_equal(desired_x,x) assert_array_almost_equal(desired_y,y[::2]) def test_x_and_y_stride(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) desired_x = y.copy()[::2] desired_y = x.copy()[::4] self.blas_func(x,y,n=3,incx=4,incy=2) assert_array_almost_equal(desired_x,x[::4]) assert_array_almost_equal(desired_y,y[::2]) def test_x_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: self.blas_func(x,y,n=4,incx=5) except: # what kind of error should be caught? return # should catch error and never get here assert_(0) def test_y_bad_size(self): x = arange(12.,dtype=self.dtype) y = zeros(6,x.dtype) try: self.blas_func(x,y,n=3,incy=5) except: # what kind of error should be caught? return # should catch error and never get here assert_(0) try: class TestSswap(TestCase, BaseSwap): blas_func = fblas.sswap dtype = float32 except AttributeError: class TestSswap: pass class TestDswap(TestCase, BaseSwap): blas_func = fblas.dswap dtype = float64 try: class TestCswap(TestCase, BaseSwap): blas_func = fblas.cswap dtype = complex64 except AttributeError: class TestCswap: pass class TestZswap(TestCase, BaseSwap): blas_func = fblas.zswap dtype = complex128 ################################################## ### Test blas ?gemv ### This will be a mess to test all cases. class BaseGemv(object): # Mixin class to test dtypes def get_data(self,x_stride=1,y_stride=1): mult = array(1, dtype=self.dtype) if self.dtype in [complex64, complex128]: mult = array(1+1j, dtype=self.dtype) from numpy.random import normal alpha = array(1., dtype=self.dtype) * mult beta = array(1.,dtype=self.dtype) * mult a = normal(0.,1.,(3,3)).astype(self.dtype) * mult x = arange(shape(a)[0]*x_stride,dtype=self.dtype) * mult y = arange(shape(a)[1]*y_stride,dtype=self.dtype) * mult return alpha,beta,a,x,y def test_simple(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(a,x)+beta*y y = self.blas_func(alpha,a,x,beta,y) assert_array_almost_equal(desired_y,y) def test_default_beta_y(self): alpha,beta,a,x,y = self.get_data() desired_y = matrixmultiply(a,x) y = self.blas_func(1,a,x) assert_array_almost_equal(desired_y,y) def test_simple_transpose(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(transpose(a),x)+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=1) assert_array_almost_equal(desired_y,y) def test_simple_transpose_conj(self): alpha,beta,a,x,y = self.get_data() desired_y = alpha*matrixmultiply(transpose(conjugate(a)),x)+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=2) assert_array_almost_equal(desired_y,y) def test_x_stride(self): alpha,beta,a,x,y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(a,x[::2])+beta*y y = self.blas_func(alpha,a,x,beta,y,incx=2) assert_array_almost_equal(desired_y,y) def test_x_stride_transpose(self): alpha,beta,a,x,y = self.get_data(x_stride=2) desired_y = alpha*matrixmultiply(transpose(a),x[::2])+beta*y y = self.blas_func(alpha,a,x,beta,y,trans=1,incx=2) assert_array_almost_equal(desired_y,y) def test_x_stride_assert(self): # What is the use of this test? alpha,beta,a,x,y = self.get_data(x_stride=2) try: y = self.blas_func(1,a,x,1,y,trans=0,incx=3) assert_(0) except: pass try: y = self.blas_func(1,a,x,1,y,trans=1,incx=3) assert_(0) except: pass def test_y_stride(self): alpha,beta,a,x,y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(a,x)+beta*y[::2] y = self.blas_func(alpha,a,x,beta,y,incy=2) assert_array_almost_equal(desired_y,y) def test_y_stride_transpose(self): alpha,beta,a,x,y = self.get_data(y_stride=2) desired_y = y.copy() desired_y[::2] = alpha*matrixmultiply(transpose(a),x)+beta*y[::2] y = self.blas_func(alpha,a,x,beta,y,trans=1,incy=2) assert_array_almost_equal(desired_y,y) def test_y_stride_assert(self): # What is the use of this test? alpha,beta,a,x,y = self.get_data(y_stride=2) try: y = self.blas_func(1,a,x,1,y,trans=0,incy=3) assert_(0) except: pass try: y = self.blas_func(1,a,x,1,y,trans=1,incy=3) assert_(0) except: pass try: class TestSgemv(TestCase, BaseGemv): blas_func = fblas.sgemv dtype = float32 except AttributeError: class TestSgemv: pass class TestDgemv(TestCase, BaseGemv): blas_func = fblas.dgemv dtype = float64 try: class TestCgemv(TestCase, BaseGemv): blas_func = fblas.cgemv dtype = complex64 except AttributeError: class TestCgemv: pass class TestZgemv(TestCase, BaseGemv): blas_func = fblas.zgemv dtype = complex128 """ ################################################## ### Test blas ?ger ### This will be a mess to test all cases. class BaseGer(TestCase): def get_data(self,x_stride=1,y_stride=1): from numpy.random import normal alpha = array(1., dtype = self.dtype) a = normal(0.,1.,(3,3)).astype(self.dtype) x = arange(shape(a)[0]*x_stride,dtype=self.dtype) y = arange(shape(a)[1]*y_stride,dtype=self.dtype) return alpha,a,x,y def test_simple(self): alpha,a,x,y = self.get_data() # tranpose takes care of Fortran vs. C(and Python) memory layout desired_a = alpha*transpose(x[:,newaxis]*y) + a self.blas_func(x,y,a) assert_array_almost_equal(desired_a,a) def test_x_stride(self): alpha,a,x,y = self.get_data(x_stride=2) desired_a = alpha*transpose(x[::2,newaxis]*y) + a self.blas_func(x,y,a,incx=2) assert_array_almost_equal(desired_a,a) def test_x_stride_assert(self): alpha,a,x,y = self.get_data(x_stride=2) try: self.blas_func(x,y,a,incx=3) assert(0) except: pass def test_y_stride(self): alpha,a,x,y = self.get_data(y_stride=2) desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a self.blas_func(x,y,a,incy=2) assert_array_almost_equal(desired_a,a) def test_y_stride_assert(self): alpha,a,x,y = self.get_data(y_stride=2) try: self.blas_func(a,x,y,incy=3) assert(0) except: pass class TestSger(BaseGer): blas_func = fblas.sger dtype = float32 class TestDger(BaseGer): blas_func = fblas.dger dtype = float64 """ ################################################## ### Test blas ?gerc ### This will be a mess to test all cases. """ class BaseGerComplex(BaseGer): def get_data(self,x_stride=1,y_stride=1): from numpy.random import normal alpha = array(1+1j, dtype = self.dtype) a = normal(0.,1.,(3,3)).astype(self.dtype) a = a + normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype) x = normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype) x = x + x * array(1j, dtype = self.dtype) y = normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype) y = y + y * array(1j, dtype = self.dtype) return alpha,a,x,y def test_simple(self): alpha,a,x,y = self.get_data() # tranpose takes care of Fortran vs. C(and Python) memory layout a = a * array(0.,dtype = self.dtype) #desired_a = alpha*transpose(x[:,newaxis]*self.transform(y)) + a desired_a = alpha*transpose(x[:,newaxis]*y) + a #self.blas_func(x,y,a,alpha = alpha) fblas.cgeru(x,y,a,alpha = alpha) assert_array_almost_equal(desired_a,a) #def test_x_stride(self): # alpha,a,x,y = self.get_data(x_stride=2) # desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a # self.blas_func(x,y,a,incx=2) # assert_array_almost_equal(desired_a,a) #def test_y_stride(self): # alpha,a,x,y = self.get_data(y_stride=2) # desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a # self.blas_func(x,y,a,incy=2) # assert_array_almost_equal(desired_a,a) class TestCgeru(BaseGerComplex): blas_func = fblas.cgeru dtype = complex64 def transform(self,x): return x class TestZgeru(BaseGerComplex): blas_func = fblas.zgeru dtype = complex128 def transform(self,x): return x class TestCgerc(BaseGerComplex): blas_func = fblas.cgerc dtype = complex64 def transform(self,x): return conjugate(x) class TestZgerc(BaseGerComplex): blas_func = fblas.zgerc dtype = complex128 def transform(self,x): return conjugate(x) """ if __name__ == "__main__": run_module_suite()
export const inBrowser = typeof window !== 'undefined'; export const debounce = (callback, wait) => { let timeout; // eslint-disable-next-line func-names return function () { const context = this; // eslint-disable-next-line prefer-rest-params const args = arguments; // eslint-disable-next-line func-names const later = function () { timeout = null; callback.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; }; export const parseSemver = (version) => { const fragments = version.split('.'); const major = parseInt(fragments[0], 10); return { major: typeof major === 'number' ? major : 1, minor: parseInt(fragments[1], 10) || 0, patch: parseInt(fragments[2], 10) || 0, }; }; export const checkVersion = (current, required) => { const currentVersion = parseSemver(current); const requiredVersion = parseSemver(required); return ( currentVersion.major > requiredVersion.major || ( currentVersion.major === requiredVersion.major && currentVersion.minor > requiredVersion.minor ) || ( currentVersion.major === requiredVersion.major && currentVersion.minor === requiredVersion.minor && currentVersion.patch >= requiredVersion.patch ) ); };
# Generated by Django 2.2.3 on 2019-08-13 20:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0005_product_offerprice'), ] operations = [ migrations.AddField( model_name='product', name='express', field=models.BooleanField(default=False), ), ]
"use strict"; var PioneerInfrastructureTablesView = Backbone.View.extend({ initialize: function() { _.bindAll(this, "render"); var self = this; self.render(); }, template: JST['ooiui/static/js/partials/landing/pioneer_array/PioneerInfrastructureTables.html'], render: function() { this.$el.html(this.template()); }  });
import datetime from collections import defaultdict from lbrynet import utils # Do not create this object except through PeerManager class Peer: def __init__(self, host, port): self.host = host self.port = port # If a peer is reported down, we wait till this time till reattempting connection self.attempt_connection_at = None # Number of times this Peer has been reported to be down, resets to 0 when it is up self.down_count = 0 # Number of successful connections (with full protocol completion) to this peer self.success_count = 0 self.score = 0 self.stats = defaultdict(float) # {string stat_type, float count} def is_available(self): if self.attempt_connection_at is None or utils.today() > self.attempt_connection_at: return True return False def report_up(self): self.down_count = 0 self.attempt_connection_at = None def report_success(self): self.success_count += 1 def report_down(self): self.down_count += 1 timeout_time = datetime.timedelta(seconds=60 * self.down_count) self.attempt_connection_at = utils.today() + timeout_time def update_score(self, score_change): self.score += score_change def update_stats(self, stat_type, count): self.stats[stat_type] += count def __str__(self): return f'{self.host}:{self.port}' def __repr__(self): return f'Peer({self.host!r}, {self.port!r})'
import argparse import logging import os import os.path import sys from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings class NewlineRemovingFormatter(logging.Formatter): def __init__(self, log_format, log_date_format): super(NewlineRemovingFormatter, self).__init__(fmt=log_format, datefmt=log_date_format) def format(self, record: logging.LogRecord) -> str: default_log = super(NewlineRemovingFormatter, self).format(record) return default_log.replace('\n', '') def parse_args(args): parser = argparse.ArgumentParser('Running a crawl') subparsers = parser.add_subparsers(help='running modes') add_simple_spider_parser(subparsers) add_queued_parser(subparsers) add_calibration_parser(subparsers) add_pointer_parser(subparsers) arguments = parser.parse_args(args) return arguments def add_simple_spider_parser(subparsers): simple_spider_parser = subparsers.add_parser('simple', help='the simple crawler spider') simple_spider_parser.set_defaults(func=run_simple) simple_spider_parser.add_argument('URL', type=str, help='The URL to start the crawl from') add_settings_parser(simple_spider_parser) return simple_spider_parser def add_queued_parser(subparsers): queued_parser = subparsers.add_parser('queued', help='process a queue entry') queued_parser.set_defaults(func=run_queued) queued_parser.add_argument('id', type=int, help='The ID of the queue entry to process') add_settings_parser(queued_parser) return queued_parser def add_calibration_parser(subparsers): queued_parser = subparsers.add_parser('calibration', help='perform a calibration run') queued_parser.set_defaults(func=run_calibration) queued_parser.add_argument('id', type=int, help='The ID of the queue entry to process') add_settings_parser(queued_parser) return queued_parser def add_pointer_parser(subparsers): pointer_spider_parser = subparsers.add_parser('pointer', help='the pointer crawler spider') pointer_spider_parser.set_defaults(func=run_pointer) pointer_spider_parser.add_argument('URL', type=str, help='The URL to start the crawl from') add_settings_parser(pointer_spider_parser) return pointer_spider_parser def add_settings_parser(parser): parser.add_argument('-s', type=str, nargs='*', dest='settings', metavar='KEY=VALUE', help='scrapy settings') def merge_settings_with_args(settings_args): settings = get_project_settings() for setting in settings_args: key, value = setting.split('=') settings.set(key, value) return settings def get_logging_target(): try: return os.environ['CRAWL_LOGGING_TARGET'] except KeyError: return 'STDOUT' def get_handler(): try: target = get_logging_target() if target == 'STDOUT': return logging.StreamHandler() return logging.FileHandler(filename=target, mode='a') except FileNotFoundError: os.makedirs('/tmp/log/scrapy/', mode=0o777) return logging.FileHandler(filename='/tmp/log/scrapy/crawl.log', mode='a') def configure_logging(settings, log_format=None): if log_format is None: log_format = settings.get('LOG_FORMAT') log_level = settings.get('LOG_LEVEL') handler = get_handler() handler.setFormatter(NewlineRemovingFormatter(log_format, settings.get('LOG_DATEFORMAT'))) handler.setLevel(log_level) logging.basicConfig(handlers=[handler], level=settings.get('LOG_LEVEL')) def run_simple(args): settings = merge_settings_with_args(args.settings) configure_logging(settings) process = CrawlerProcess(settings=settings, install_root_handler=False) process.crawl('simple', url=args.URL) process.start() # the script will block here until the crawling is finished def run_queued(args): settings = merge_settings_with_args(args.settings) configured_log_format = str(settings.get('LOG_FORMAT')) queued_log_format = configured_log_format.replace('%(asctime)s', '%(asctime)s [queue-entry-{}]'.format(args.id)) configure_logging(settings, queued_log_format) process = CrawlerProcess(settings=settings, install_root_handler=False) process.crawl('queued', queue_id=args.id) process.start() # the script will block here until the crawling is finished def run_calibration(args): settings = merge_settings_with_args(args.settings) configured_log_format = str(settings.get('LOG_FORMAT')) queued_log_format = configured_log_format.replace( '%(asctime)s', '%(asctime)s [calibration-queue-entry-{}]'.format(args.id) ) configure_logging(settings, queued_log_format) process = CrawlerProcess(settings=settings, install_root_handler=False) process.crawl('calibration', queue_id=args.id) process.start() def run_pointer(args): settings = merge_settings_with_args(args.settings) configure_logging(settings) process = CrawlerProcess(settings=settings, install_root_handler=False) process.crawl('pointer', url=args.URL) process.start() # the script will block here until the crawling is finished if __name__ == '__main__': parsed_args = parse_args(sys.argv[1:]) parsed_args.func(parsed_args)
import React, { useContext, useEffect, useState } from 'react'; import { getTransactions } from './explorer-api'; import { FluxContext, connect } from '../FluxProvider'; import formatData from './formatData'; import allTxLatest from './allTxLatest'; import { LineChart, Line, YAxis, XAxis, Tooltip } from 'recharts'; import styled from 'styled-components'; const ChartContainer = styled.div` padding: 0 5%; ` const Title = styled.h1` ` function Dashboard() { const [flux, dispatch] = useContext(FluxContext); const [charts, setCharts] = useState([]); const [loadingState, setLoadingState] = useState("fetching"); const fetchData = async () => { const allData = await getTransactions("flux-protocol-dev"); return JSON.stringify(allData); } const formatToolTip = (value, name, outcomeTags) => { if (outcomeTags.length > 0) { name = outcomeTags[name]; } else { name = name === "0" ? "NO" : "YES"; } return [value, name] } useEffect(() => { fetchData().then(tx => { setLoadingState("formatting"); const data = formatData(JSON.parse(tx)); mapOutcomeTagsToOutcomes(data).then(mappedData => { const elems = Object.keys(mappedData).map((marketId, i) => { const marketData = data[marketId]; let lines = [] const colors = [ "red", "blue", "purple", ] marketData.data.forEach(entry => { const keys = Object.keys(entry); for (let i = 0; i < keys.length -1; i++) { const outcome = keys[i]; if (!lines[outcome]) lines[outcome] = <Line type="monotone" dataKey={outcome} key={i} stroke={colors[i]}/> } }) if (marketData.description !== "new market") { return ( <ChartContainer key={i} > <Title>{marketData.description}</Title> <LineChart width={400} height={400} data={marketData.data}> {lines} <Tooltip formatter={(value, name) => formatToolTip(value, name, marketData.outcomeTags)} /> <XAxis dataKey="date"/> <YAxis /> </LineChart> </ChartContainer> ) } else { return null } }) setCharts(elems); setLoadingState(null); }); }) }, []) const mapOutcomeTagsToOutcomes = async (data) => { const fluxInstance = await connect(); const allMarkets= await fluxInstance.getAllMarkets(); Object.keys(data).forEach(marketId => { const market = allMarkets[marketId]; data[marketId]["outcomeTags"] = market.outcome_tags; }) return data; } if (loadingState === "fetching") { return ( <div> fetching latest order data from NEAR explorer... </div> ) } else if (loadingState === "formatting") { return <div> formatting data... </div> } else { return ( <div> {charts} </div> ); } } export default Dashboard;
"""Define word-based embedders.""" import abc import collections import os import numpy as np import tensorflow as tf from tensorboard.plugins import projector from google.protobuf import text_format from opennmt import constants, tokenizers from opennmt.data import text from opennmt.data.vocab import Vocab from opennmt.inputters.inputter import Inputter from opennmt.layers import common from opennmt.utils import misc def save_embeddings_metadata(log_dir, variable_name, vocabulary_file, num_oov_buckets=1): """Registers an embedding variable for visualization in TensorBoard. This function registers :obj:`variable_name` in the ``projector_config.pbtxt`` file and generates metadata from :obj:`vocabulary_file` to attach a label to each word ID. Args: log_dir: The active log directory. variable_name: The variable name in the checkpoint. vocabulary_file: The associated vocabulary file. num_oov_buckets: The number of additional unknown tokens. """ # Assume it ends with /.ATTRIBUTES/VALUE filename = "%s.txt" % "_".join(variable_name.split("/")[:-2]) metadata_path = os.path.join(log_dir, filename) with tf.io.gfile.GFile(vocabulary_file, mode="rb") as src, \ tf.io.gfile.GFile(metadata_path, mode="wb") as dst: ws_index = 0 for line in src: # The TensorBoard code checks line.trim().length == 0 when loading the # metadata file so make sure lines are not dropped. if not line.decode("utf-8").replace(u"\uFEFF", u"").strip(): dst.write(tf.compat.as_bytes("<whitespace%d>\n" % ws_index)) ws_index += 1 else: dst.write(line) if num_oov_buckets == 1: dst.write(b"<unk>\n") else: for i in range(num_oov_buckets): dst.write(tf.compat.as_bytes("<unk%d>\n" % i)) config = projector.ProjectorConfig() # If the projector file exists, load it. config_path = os.path.join(log_dir, "projector_config.pbtxt") if tf.io.gfile.exists(config_path): with tf.io.gfile.GFile(config_path, mode="rb") as config_file: text_format.Merge(config_file.read(), config) # If this embedding is already registered, just update the metadata path. exists = False for meta in config.embeddings: if meta.tensor_name == variable_name: meta.metadata_path = filename exists = True break if not exists: embedding = config.embeddings.add() embedding.tensor_name = variable_name embedding.metadata_path = filename with tf.io.gfile.GFile(config_path, "w") as config_file: config_file.write(text_format.MessageToString(config)) def load_pretrained_embeddings(embedding_file, vocabulary_file, num_oov_buckets=1, with_header=True, case_insensitive_embeddings=True): """Returns pretrained embeddings relative to the vocabulary. The :obj:`embedding_file` must have the following format: .. code-block:: text N M word1 val1 val2 ... valM word2 val1 val2 ... valM ... wordN val1 val2 ... valM or if :obj:`with_header` is ``False``: .. code-block:: text word1 val1 val2 ... valM word2 val1 val2 ... valM ... wordN val1 val2 ... valM This function will iterate on each embedding in :obj:`embedding_file` and assign the pretrained vector to the associated word in :obj:`vocabulary_file` if found. Otherwise, the embedding is ignored. If :obj:`case_insensitive_embeddings` is ``True``, word embeddings are assumed to be trained on lowercase data. In that case, word alignments are case insensitive meaning the pretrained word embedding for "the" will be assigned to "the", "The", "THE", or any other case variants included in :obj:`vocabulary_file`. Args: embedding_file: Path the embedding file. Entries will be matched against :obj:`vocabulary_file`. vocabulary_file: The vocabulary file containing one word per line. num_oov_buckets: The number of additional unknown tokens. with_header: ``True`` if the embedding file starts with a header line like in GloVe embedding files. case_insensitive_embeddings: ``True`` if embeddings are trained on lowercase data. Returns: A Numpy array of shape ``[vocabulary_size + num_oov_buckets, embedding_size]``. """ # Map words to ids from the vocabulary. word_to_id = collections.defaultdict(list) with tf.io.gfile.GFile(vocabulary_file, mode="rb") as vocabulary: count = 0 for word in vocabulary: word = word.strip() if case_insensitive_embeddings: word = word.lower() word_to_id[word].append(count) count += 1 # Fill pretrained embedding matrix. with tf.io.gfile.GFile(embedding_file, mode="rb") as embedding: pretrained = None if with_header: next(embedding) for line in embedding: fields = line.strip().split() word = fields[0] if pretrained is None: pretrained = np.random.normal( size=(count + num_oov_buckets, len(fields) - 1)) # Lookup word in the vocabulary. if word in word_to_id: ids = word_to_id[word] for index in ids: pretrained[index] = np.asarray(fields[1:]) return pretrained def add_sequence_controls(ids, length, start_id=None, end_id=None): """Adds sequence control tokens. Args: ids: Sequence of ids as 1D or 2D (batch) tensor. length: Sequence length as 0D or 1D (batch) tensor. start_id: Id to prepend to the sequence (set ``None`` to disable). end_id: Id to append to the sequence (set ``None`` to disable). Returns: A tuple ``(ids, length)``. """ rank = ids.shape.rank if rank not in (1, 2): raise ValueError("Unsupported rank %d (expected 1 or 2)" % rank) batch_size = tf.shape(ids)[0] if rank == 2 else None def _make_column(value): value = tf.constant(value, dtype=ids.dtype) if batch_size is not None: value = tf.fill([batch_size], value) return tf.expand_dims(value, -1) if start_id is not None: start_ids = _make_column(constants.START_OF_SENTENCE_ID) ids = tf.concat([start_ids, ids], axis=-1) length += 1 if end_id is not None: end_ids = _make_column(constants.END_OF_SENTENCE_ID) if batch_size is not None: # Run concat on RaggedTensor to handle sequences with variable length. ids = tf.RaggedTensor.from_tensor(ids, lengths=length) ids = tf.concat([ids, end_ids], axis=-1) if batch_size is not None: ids = ids.to_tensor() length += 1 return ids, length def _get_field(config, key, prefix=None, default=None, required=False): if prefix: key = "%s%s" % (prefix, key) value = config.get(key, default) if value is None and required: raise ValueError("Missing field '%s' in the data configuration" % key) return value def _create_vocabulary_tables(vocabulary_file, num_oov_buckets, as_asset=True): vocabulary = Vocab.from_file(vocabulary_file) vocabulary_size = len(vocabulary) if as_asset: tokens_to_ids_initializer = tf.lookup.TextFileInitializer( vocabulary_file, tf.string, tf.lookup.TextFileIndex.WHOLE_LINE, tf.int64, tf.lookup.TextFileIndex.LINE_NUMBER, vocab_size=vocabulary_size) ids_to_tokens_initializer = tf.lookup.TextFileInitializer( vocabulary_file, tf.int64, tf.lookup.TextFileIndex.LINE_NUMBER, tf.string, tf.lookup.TextFileIndex.WHOLE_LINE, vocab_size=vocabulary_size) else: tokens = tf.constant(vocabulary.words, dtype=tf.string) ids = tf.constant(list(range(vocabulary_size)), dtype=tf.int64) tokens_to_ids_initializer = tf.lookup.KeyValueTensorInitializer(tokens, ids) ids_to_tokens_initializer = tf.lookup.KeyValueTensorInitializer(ids, tokens) if num_oov_buckets > 0: tokens_to_ids = tf.lookup.StaticVocabularyTable(tokens_to_ids_initializer, num_oov_buckets) else: tokens_to_ids = tf.lookup.StaticHashTable(tokens_to_ids_initializer, 0) ids_to_tokens = tf.lookup.StaticHashTable(ids_to_tokens_initializer, constants.UNKNOWN_TOKEN) return vocabulary_size + num_oov_buckets, tokens_to_ids, ids_to_tokens class TextInputter(Inputter): """An abstract inputter that processes text.""" def __init__(self, num_oov_buckets=1, **kwargs): super(TextInputter, self).__init__(**kwargs) self.num_oov_buckets = num_oov_buckets self.noiser = None self.in_place_noise = False self.noise_probability = None def initialize(self, data_config, asset_prefix=""): self.vocabulary_file = _get_field( data_config, "vocabulary", prefix=asset_prefix, required=True) self.vocabulary_size, self.tokens_to_ids, self.ids_to_tokens = _create_vocabulary_tables( self.vocabulary_file, self.num_oov_buckets, as_asset=data_config.get("export_vocabulary_assets", True)) tokenizer_config = _get_field(data_config, "tokenization", prefix=asset_prefix) self.tokenizer = tokenizers.make_tokenizer(tokenizer_config) def set_noise(self, noiser, in_place=True, probability=None): """Enables noise to be applied to the input features. Args: noiser: A :class:`opennmt.data.WordNoiser` instance. in_place: If ``False``, the noisy version of the input will be stored as a separate feature prefixed with "noisy_". probability: When :obj:`in_place` is enabled, the probability to apply the noise. Raises: ValueError: if :obj:`in_place` is enabled but a :obj:`probability` is not set. """ if in_place and probability is None: raise ValueError("In-place noise requires a probability") self.noiser = noiser self.in_place_noise = in_place self.noise_probability = probability def export_assets(self, asset_dir, asset_prefix=""): return self.tokenizer.export_assets(asset_dir, asset_prefix=asset_prefix) def make_dataset(self, data_file, training=None): return tf.data.TextLineDataset( data_file, compression_type="GZIP" if misc.is_gzip_file(data_file) else None) def make_features(self, element=None, features=None, training=None): """Tokenizes raw text.""" if features is None: features = {} if "tokens" in features: return features if "text" in features: element = features.pop("text") tokens = self.tokenizer.tokenize(element) if isinstance(tokens, tf.RaggedTensor): length = tokens.row_lengths() tokens = tokens.to_tensor() else: length = tf.shape(tokens)[0] if training and self.noiser is not None: noisy_tokens, noisy_length = self.noiser(tokens, keep_shape=False) if self.in_place_noise: tokens, length = tf.cond( tf.random.uniform([]) < self.noise_probability, true_fn=lambda: (noisy_tokens, noisy_length), false_fn=lambda: (tokens, length)) else: # Call make_features again to fill the remaining noisy features. noisy_features = dict(tokens=noisy_tokens, length=noisy_length) noisy_features = self.make_features(features=noisy_features, training=training) for key, value in noisy_features.items(): features["noisy_%s" % key] = value features["length"] = length features["tokens"] = tokens return features def input_signature(self): if self.tokenizer.in_graph: return { "text": tf.TensorSpec([None], tf.string) } else: return { "tokens": tf.TensorSpec([None, None], tf.string), "length": tf.TensorSpec([None], tf.int32) } class WordEmbedder(TextInputter): """Simple word embedder.""" def __init__(self, embedding_size=None, dropout=0.0, **kwargs): """Initializes the parameters of the word embedder. Args: embedding_size: The size of the resulting embedding. If ``None``, an embedding file must be provided. dropout: The probability to drop units in the embedding. **kwargs: Additional layer keyword arguments. """ super(WordEmbedder, self).__init__(**kwargs) self.embedding_size = embedding_size self.embedding_file = None self.dropout = dropout self.decoder_mode = False self.mark_start = None self.mark_end = None def set_decoder_mode(self, enable=True, mark_start=None, mark_end=None): """Make this inputter produce sequences for a decoder. In this mode, the returned "ids_out" feature is the decoder output sequence and "ids" is the decoder input sequence. Args: enable: Enable the decoder mode. mark_start: Mark the sequence start. If ``None``, keep the current value. mark_end: Mark the sequence end. If ``None``, keep the current value. """ self.decoder_mode = enable if mark_start is not None: self.mark_start = mark_start if mark_end is not None: self.mark_end = mark_end def get_length(self, features, ignore_special_tokens=False): length = features["length"] if ignore_special_tokens: # Decoder mode shifts the sequences by one timesteps. num_special_tokens = -1 if self.decoder_mode else 0 if self.mark_start: num_special_tokens += 1 if self.mark_end: num_special_tokens += 1 length -= num_special_tokens return length def initialize(self, data_config, asset_prefix=""): super(WordEmbedder, self).initialize(data_config, asset_prefix=asset_prefix) embedding = _get_field(data_config, "embedding", prefix=asset_prefix) if embedding is None and self.embedding_size is None: raise ValueError("embedding_size must be set") if embedding is not None: self.embedding_file = embedding["path"] self.trainable = embedding.get("trainable", True) self.embedding_file_with_header = embedding.get("with_header", True) self.case_insensitive_embeddings = embedding.get("case_insensitive", True) sequence_controls = _get_field(data_config, "sequence_controls", prefix=asset_prefix) if sequence_controls: self.mark_start = sequence_controls["start"] self.mark_end = sequence_controls["end"] def make_features(self, element=None, features=None, training=None): """Converts words tokens to ids.""" features = super(WordEmbedder, self).make_features( element=element, features=features, training=training) if "ids" not in features: features["ids"] = self.tokens_to_ids.lookup(features["tokens"]) if self.mark_start or self.mark_end: features["ids"], features["length"] = add_sequence_controls( features["ids"], features["length"], start_id=constants.START_OF_SENTENCE_ID if self.mark_start else None, end_id=constants.END_OF_SENTENCE_ID if self.mark_end else None) if self.decoder_mode: features["ids_out"] = features["ids"][1:] features["ids"] = features["ids"][:-1] features["length"] -= 1 return features def build(self, input_shape): if self.embedding_file: pretrained = load_pretrained_embeddings( self.embedding_file, self.vocabulary_file, num_oov_buckets=self.num_oov_buckets, with_header=self.embedding_file_with_header, case_insensitive_embeddings=self.case_insensitive_embeddings) self.embedding_size = pretrained.shape[-1] initializer = tf.constant_initializer(value=pretrained.astype(self.dtype)) else: initializer = None self.embedding = self.add_weight( "embedding", [self.vocabulary_size, self.embedding_size], initializer=initializer, trainable=self.trainable) super(WordEmbedder, self).build(input_shape) def call(self, features, training=None): outputs = tf.nn.embedding_lookup(self.embedding, features["ids"]) outputs = common.dropout(outputs, self.dropout, training=training) return outputs def visualize(self, model_root, log_dir): save_embeddings_metadata( log_dir, misc.get_variable_name(self.embedding, model_root), self.vocabulary_file, num_oov_buckets=self.num_oov_buckets) def map_v1_weights(self, weights): return [(self.embedding, weights["w_embs"])] class CharEmbedder(TextInputter): """Base class for character-aware inputters.""" def __init__(self, embedding_size, dropout=0.0, **kwargs): """Initializes the parameters of the character embedder. Args: embedding_size: The size of the character embedding. dropout: The probability to drop units in the embedding. **kwargs: Additional layer keyword arguments. """ super(CharEmbedder, self).__init__(**kwargs) self.embedding_size = embedding_size self.embedding = None self.dropout = dropout def make_features(self, element=None, features=None, training=None): """Converts words to characters.""" if features is None: features = {} if "char_ids" in features: return features if "chars" in features: chars = features["chars"] else: features = super(CharEmbedder, self).make_features( element=element, features=features, training=training) chars = text.tokens_to_chars(features["tokens"]) chars = chars.to_tensor(default_value=constants.PADDING_TOKEN) features["char_ids"] = self.tokens_to_ids.lookup(chars) return features def build(self, input_shape): self.embedding = self.add_weight( "char_embedding", [self.vocabulary_size, self.embedding_size]) super(CharEmbedder, self).build(input_shape) @abc.abstractmethod def call(self, features, training=None): raise NotImplementedError() def visualize(self, model_root, log_dir): save_embeddings_metadata( log_dir, misc.get_variable_name(self.embedding, model_root), self.vocabulary_file, num_oov_buckets=self.num_oov_buckets) def _embed(self, inputs, training): mask = tf.math.not_equal(inputs, 0) outputs = tf.nn.embedding_lookup(self.embedding, inputs) outputs = common.dropout(outputs, self.dropout, training=training) return outputs, mask class CharConvEmbedder(CharEmbedder): """An inputter that applies a convolution on characters embeddings.""" def __init__(self, embedding_size, num_outputs, kernel_size=5, stride=3, dropout=0.0, **kwargs): """Initializes the parameters of the character convolution embedder. Args: embedding_size: The size of the character embedding. num_outputs: The dimension of the convolution output space. kernel_size: Length of the convolution window. stride: Length of the convolution stride. dropout: The probability to drop units in the embedding. **kwargs: Additional layer keyword arguments. """ super(CharConvEmbedder, self).__init__( embedding_size, dropout=dropout, **kwargs) self.output_size = num_outputs self.conv = tf.keras.layers.Conv1D( num_outputs, kernel_size, strides=stride, padding="same") def call(self, features, training=None): inputs = features["char_ids"] flat_inputs = tf.reshape(inputs, [-1, tf.shape(inputs)[-1]]) outputs, _ = self._embed(flat_inputs, training) outputs = self.conv(outputs) outputs = tf.reduce_max(outputs, axis=1) outputs = tf.reshape(outputs, [-1, tf.shape(inputs)[1], self.output_size]) return outputs class CharRNNEmbedder(CharEmbedder): """An inputter that runs a single RNN layer over character embeddings.""" def __init__(self, embedding_size, num_units, dropout=0.2, cell_class=None, **kwargs): """Initializes the parameters of the character RNN embedder. Args: embedding_size: The size of the character embedding. num_units: The number of units in the RNN layer. dropout: The probability to drop units in the embedding and the RNN outputs. cell_class: The inner cell class or a callable taking :obj:`num_units` as argument and returning a cell. Defaults to a LSTM cell. **kwargs: Additional layer keyword arguments. Raises: ValueError: if :obj:`encoding` is invalid. """ super(CharRNNEmbedder, self).__init__( embedding_size, dropout=dropout, **kwargs) if cell_class is None: cell_class = tf.keras.layers.LSTMCell self.rnn = tf.keras.layers.RNN(cell_class(num_units)) self.num_units = num_units def call(self, features, training=None): inputs = features["char_ids"] flat_inputs = tf.reshape(inputs, [-1, tf.shape(inputs)[-1]]) embeddings, mask = self._embed(flat_inputs, training) outputs = self.rnn(embeddings, mask=mask, training=training) outputs = tf.reshape(outputs, [-1, tf.shape(inputs)[1], self.num_units]) return outputs
/********************************************************************** *< FILE: IGameObject.h DESCRIPTION: Object interfaces for IGame CREATED BY: Neil Hazzard, Discreet HISTORY: created 02/02/02 IGame Version: 1.122 *> Copyright (c) 2002, All Rights Reserved. **********************************************************************/ /*!\file IGameObject.h \brief IGame supported Object Interfaces. */ #ifndef __IGAMEOBJECT__H #define __IGAMEOBJECT__H #pragma once #include "maxheap.h" #include "Max.h" #include "IGameProperty.h" #include "IGameStd.h" class IGameNode; class IGameModifier; class IGameSkin; //!Simple wrapper for 3ds Max objects /*! This is heart of the interaction with 3ds Max objects. 3ds Max objects are converted to IGame objects to provide simpler interfaces. Specific support is given to Meshes, Splines, Helper (including bones) and Cameras. Any object that is not supported by IGame directly is supported as a generic object, so that properties can be extracted easily. At the present time IGame only supports Geom Objects that can be converted to a Tri Object. \n A note about XRef items. IGame will search out XRef Objects and store them as IGameXrefObject. External file names and proxies can be accessed by casting IGameObject* to IGameXrefObject* \n Some of the interfaces returned by IGameObject require that the nodes be parsed by IGame first. \sa IGameNode, IGameMesh, IGameLight, IGameCamera, IGameSupportObject \sa IExportEntity */ class IGameObject : public IExportEntity { Tab <IGameModifier *> gameModTab; protected: INode * gameNode; Object * gameObject; void SetNode (INode * n); public: //!Default constructor IGameObject(); //! Various IGame Object types /*! These are the objects supported by IGame */ enum ObjectTypes{ IGAME_UNKNOWN, /*!< An unknown object*/ IGAME_LIGHT, /*!< A Light Object */ IGAME_MESH, /*!< A Mesh Object */ IGAME_SPLINE, /*!< A Spline Object */ IGAME_CAMERA, /*!< A Camera Object */ IGAME_HELPER, /*!< A Helper Object */ IGAME_BONE, /*!< A Bone Object */ IGAME_IKCHAIN, /*!< An IK Chain Object*/ IGAME_XREF /*!< A XRef Object*/ }; //! Various 3ds Max Object types /*! These are 3ds Max object - Developers can use this to cast the Object pointer to one of the relevent 3ds Max classes */ enum MaxType{ IGAME_MAX_UNKNOWN, /*!< An unknown object*/ IGAME_MAX_GEOM, /*!< A Geom Object*/ IGAME_MAX_SHAPE, /*!< A Shape Object*/ IGAME_MAX_LIGHT, /*!< A Light Object*/ IGAME_MAX_CAMERA, /*!< A Camera Object*/ IGAME_MAX_BONE, /*!< A Bone Object*/ IGAME_MAX_HELPER, /*!< A Helper Object*/ }; //! The bounding box of the object /*! \param bb The Box3 to receive the value */ IGAMEEXPORT void GetBoundingBox(Box3 & bb); //!Check if object renderable /*! \return TRUE if it is renderable */ IGAMEEXPORT bool IsRenderable(); //! The IGame object type /*! Return the Type of IGameObject it represents \return The object type. Returned value corresponds to IGameObject::ObjectTypes Enum */ virtual ObjectTypes GetIGameType() =0; //! Access to the actual 3ds Max object /*! Access to the actual 3ds Max object, if further direct access needed \return A pointer to a max Object class */ IGAMEEXPORT Object * GetMaxObject(); //! The 3ds Max object type /*! This lets the developer know what type of object - Light, Geom, Helper etc... This is different from the IGame types, as these may group more than one type of 3ds Max object together. The information can be used to cast Object returned from IGameObject::GetMaxObject to the appropriate class. \return The type of max object. This is defined as the IGameObject::MaxType enum */ IGAMEEXPORT MaxType GetMaxType() ; //!The number of modifiers active on the object /*! \return The number of modifiers */ IGAMEEXPORT int GetNumModifiers(); //!Access to IGame modifier /*! Get a pointer to the IGame representation of the modifier \param index The index of the modifier to return \return A pointer to the IGameModifier */ IGAMEEXPORT IGameModifier * GetIGameModifier(int index); //! The IGameObject constructor /*! \param *node The 3ds Max node to initialise */ IGAMEEXPORT IGameObject(INode * node); //!Check if Object casts shadows /*! \return TRUE if object casts shadows */ IGAMEEXPORT bool CastShadows(); //!Check if object skinned /*!Is object skinned with either Physique of Skin \return TRUE if skinned */ IGAMEEXPORT bool IsObjectSkinned(); //!Access to the Skin interface /*! \return A pointer to IGameSkin or NULL if not present */ IGAMEEXPORT IGameSkin * GetIGameSkin(); //!Check if XRef object /*! Indentify XRef objects \return TRUE if it is an XRef Object */ IGAMEEXPORT bool IsObjectXRef(); //! Access to the ObjectTM /*! Get the ObjectTM. This is the matrix needed to calculate world space \return A matrix containing the Object TM. Used to calculate world space. */ IGAMEEXPORT GMatrix GetIGameObjectTM(); //! Extract the 3ds Max data into IGame data /*! Some extraction processes are time and memory consuming. This method allows the developer to specify when they want the data to be converted - this prevents any unwanted data being converted. This is important for IGameMesh class - if you are just after parameter data, you don't want the whole vertex array being sorted. Calling this tells the object that you want the data be converted. \return It will return FALSE when data has not been converted, this object should not be exported. Usually this is due to a standin or in the case of a GeomObject, it can't be converted to a Tri Object. */ virtual bool InitializeData(){return false;} virtual ~IGameObject() = 0; }; //!Simple wrapper for light objects /*! An IGame Wrapper around 3ds Max's lights. This is a generic interface for all the lights */ class IGameLight : public IGameObject { public: //! Various Light types used by 3ds Max enum LightType{ IGAME_OMNI, /*!< Omnidirectional Light*/ IGAME_TSPOT, /*!< Targeted Spot Light*/ IGAME_DIR, /*!< Directional Light*/ IGAME_FSPOT, /*!< Free spot Light*/ IGAME_TDIR, /*!< Targeted Directional Light*/ IGAME_UNKNOWN, /*!< An unknown light type*/ }; //! Get the Light Color Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetLightColor()=0; //! Get the Light Multiplier Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetLightMultiplier()=0; //! Get the Light Attenuation End Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetLightAttenEnd()=0; //! Get the Light Attenuation Start Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetLightAttenStart()=0; //! Get the Light Falloff Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetLightFallOff()=0; //! Get the Light Hot spot Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetLightHotSpot()=0; //! Get the Light Aspect Ratio Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetLightAspectRatio()=0; //! Get the Light Decay Start Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetLightDecayStart()=0; //! Get the Light type as defined in the UI /*! \return The Light Type. Returned value corresponds to IGameLight::LightType Enum */ virtual LightType GetLightType()=0; //! Get the Light overshoot /*! \return TRUE if the Light supports overshoot */ virtual int GetLightOvershoot()=0; //! Get the Decay Type of the Light /*! \return The Decay Type as integer \n 0 - None\n 1 - Inverse\n 2 - Inverse Square\n */ virtual int GetLightDecayType()=0; //! Get the shape of the Light /*! \return The shape can be one of the following \n RECT_LIGHT\n CIRCLE_LIGHT\n */ virtual int GetSpotLightShape()=0; //! Get the Target of the Light /*! If the light is of type Spot light then this provides access to the target \return A pointer to IGameNode for the target. Return NULL for non target lights */ virtual IGameNode * GetLightTarget()=0; //! Check if Light is On /*! \return True if the Light is on */ virtual bool IsLightOn() = 0; //! Check Exclude List /*! Determines whether the exclude list actually maintains a list that is infact included by the light \return TRUE if the light maintains an included list */ virtual bool IsExcludeListReversed()=0; //! Get the number of excluded nodes from the Light /*! This list contains nodes that should not be included in lighting calculations. It can also contain a list of only those lights that SHOULD be included. This all depends on the state of IsExcludedListReversed. \return The total number of excluded nodes */ virtual int GetExcludedNodesCount() = 0; //!Get the excluded node based on the index pass in /*! \param index The index of the node to access \return An IGameNode pointer for the excluded node */ virtual IGameNode * GetExcludedNode(int index) = 0; }; //!Simple wrapper for camera objects /*! An IGame Wrapper around 3ds Max's cameras. This is a generic interface for all the cameras */ class IGameCamera : public IGameObject { public: //! Get the Camera Field of View Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetCameraFOV()=0; //! Get the Camera Far Clip plane Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetCameraFarClip()=0; //! Get the Camera Near Clip plane Data /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetCameraNearClip()=0; //! Get the Camera Target Distance /*! \return A pointer to IGameProperty */ virtual IGameProperty * GetCameraTargetDist()=0; //! Get the Camera Target /*! If the camera is target camera then this provides access to the target \return a pointer to IGameNode for the target. Return NULL for non target cameras */ virtual IGameNode * GetCameraTarget()=0; }; //!Simple extension to the 3ds Max Face class /*!Simple class to store extended data about the face. The indexing works as a regular 3ds Max Face but mirroring has been taken account of, in the construction. */ class FaceEx: public MaxHeapOperators { public: //! Index into the vertex array DWORD vert[3]; //! Index into the standard mapping channel DWORD texCoord[3]; //! Index into the normal array DWORD norm[3]; //! Index into the vertex color array DWORD color[3]; //! Index into the vertex illumination array DWORD illum[3]; //! Index into the vertex alpha array DWORD alpha[3]; //! The smoothing group DWORD smGrp; //! The material ID of the face int matID; //! Additional flags DWORD flags; //! Index of corresponding face in the original mesh int meshFaceIndex; //! Index into edge visibility array. /*! 1 for visible, 0 if the edge is invisible.*/ DWORD edgeVis[3]; }; //!Simple wrapper for tri mesh objects /*! An IGame wrapper around the standard 3ds Max Mesh class. It provides unified support for Vertex colors and normals Mirroring is taken into account so the data you retrieve is swapped.\n Many of the geometry lookups used by IGameObject use the 3ds Max Template Class Tab. You can use the Tab returned to find out whether the call was successful as the Tab count would be greater then zero.\n In 3ds Max 6.0 and above version of IGame, Tangent space is calculated. For this to work, each face <b>must</b> be a member of a smoothing group. */ class IGameMesh: public IGameObject { public: //! Initialize Binormal and Tangents data <b><i> NEW for 3DXI V 2.2 </i></b> /*! Binormal and Tangents can be initialized and accessed separately from other mesh data see IGameObject::InitializeData() for more details To initialize entire mesh data (including Binormals and Tangents) IGameObject::InitializeData() should be called \return true if successful, false otherwise */ virtual bool InitializeBinormalData()=0; //! Get number of Vertices /*! The total number of vertices found in the mesh \return The number of Vertices */ virtual int GetNumberOfVerts()=0; //! Get number of Texture Vertices /*! The total number of Texture vertices found in the mesh \return The number of TextureVertices */ virtual int GetNumberOfTexVerts()=0; //!Get the actual Vertex /*! Get the vertex at the specified index. This is in the World Space Coordinate System \param index The index of the vertex \param ObjectSpace Defines what space the vertex is in. This defaults to World space to be compatible with previous versions \return A Point3 representing the position of the vertex */ virtual Point3 GetVertex(int index, bool ObjectSpace = false)=0; //!Get the actual Vertex /*! Get the vertex at the specified index. This is in the World Space Coordinate System \param index The index of the vertex \param &vert A Point3 to receive the data \param ObjectSpace Defines what space the vertex is in. This defaults to World space to be compatible with previous versions \return TRUE if successful */ virtual bool GetVertex(int index, Point3 & vert, bool ObjectSpace = false) = 0; //!Get the actual Texture Vertex /*! Get the Texture vertex at the specified index \param index The index of the Texture vertex \return A Point2 representing the Texture vertex */ virtual Point2 GetTexVertex(int index)=0; //!Get the actual Texture Vertex /*! Get the Texture vertex at the specified index \param index The index of the Texture vertex \param &tex A Point2 to receive the data. \return TRUE if successful */ virtual bool GetTexVertex(int index, Point2 & tex) = 0; //! [METHOD IS RETIRED] Specify whether normals are calculated based on face angles /*! To tell IGame to calculate normals based on a weight made from the angle of the edges at the vertex, the developer needs to call this <b>before</b> IGameObject::InitializeData() is called. The default is not to use weighted normals which is also the default in 3ds Max 4.0 */ virtual void SetUseWeightedNormals() = 0; //! Get number of normals /*! The total number of normals found in the mesh \return The number of normals */ virtual int GetNumberOfNormals()=0; //!Get the Vertex Index associated with the Normal <b><i> NEW for 3DXI V 2.2 </i></b> /*! Get the Vertex Index associated with the Normal index. \param index The index of the normal in the flat list \return Vertex Index associated with the Normal inex */ virtual int GetNormalVertexIndex (int index)=0; //!Get the actual normal /*! Get the normal at the specified index. \param index The index of the normal in the flat list \param ObjectSpace defines what space the normal is in. This defaults to World space to be compatible with previous versions \return A Point3 representing the normal */ virtual Point3 GetNormal(int index, bool ObjectSpace = false)=0; //!Get the actual normal /*! Get the normal at the specified index in the flat list \param index The index of the normal \param &norm A Point3 to receive the data. \param ObjectSpace Defines what space the normal is in. This defaults to World space to be compatible with previous versions \return TRUE if successful */ virtual bool GetNormal(int index, Point3 & norm, bool ObjectSpace = false) = 0; //!Get the normal based on face and corner /*! \param faceIndex The index into the face array \param corner The vertex whose normal is requested \param &norm A point3 to receive the data \param ObjectSpace Defines what space the normal is in. This defaults to World space to be compatible with previous versions \return TRUE if successful */ virtual bool GetNormal(int faceIndex, int corner, Point3 & norm, bool ObjectSpace = false) = 0; //!Get the normal based on face and corner /*! \param face The pointer of the face whose normals are to be accessed \param corner The vertex whose normal is requested \param ObjectSpace Defines what space the normal is in. This defaults to World space to be compatible with previous versions \return A Point3 containing the normal */ virtual Point3 GetNormal ( FaceEx * face, int corner, bool ObjectSpace = false) = 0; //!Get the normal based on face and corner /*! \param face The pointer of the face whose normals are to be accessed \param corner The vertex whose normal is requested \param &norm A point3 to receive the data \param ObjectSpace Defines what space the normal is in. This defaults to World space to be compatible with previous versions \return TRUE if successful */ virtual bool GetNormal(FaceEx * face, int corner, Point3 &norm, bool ObjectSpace = false) =0; //!Get the normal based on face and corner /*! \param faceIndex The index into the face array \param corner The vertex whose normal is requested \return A Point3 containing the normal \param ObjectSpace Defines what space the normal is in. This defaults to World space to be compatible with previous versions */ virtual Point3 GetNormal(int faceIndex, int corner, bool ObjectSpace = false) = 0; //! Get number of Illuminated Vertices /*! The total number of Illuminated Vertices found in the mesh \return The number of Illuminated Vertices */ virtual int GetNumberOfIllumVerts()=0; //! Get number of Alpha Vertices /*! The total number of Alpha Vertices found in the mesh \return The number of Alpha Vertices */ virtual int GetNumberOfAlphaVerts()=0; //! Get number of Vertex Colors /*! The total number of Vertex Colors found in the mesh \return The number of Vertex Colors */ virtual int GetNumberOfColorVerts()=0; //!Get the actual Color Vertex /*! Get the color vertex at the specified index \param index The index of the color vertex \return A Point3 representing the color of the vertex. Return Point3(-1,-1,-1) if the index is invalid */ virtual Point3 GetColorVertex(int index)=0; //!Get the actual Color Vertex /*! Get the color vertex at the specified index \param index The index of the color vertex \param &col A Point3 to receive the color data \return TRUE if successful */ virtual bool GetColorVertex(int index, Point3 & col) = 0; //!Get the actual Alpha Vertex /*! Get the Alpha vertex at the specified index \param index The index of the Alpha vertex \return A float representing the Alpha value of the vertex. Return -1 if the index is invalid */ virtual float GetAlphaVertex(int index)=0; //!Get the actual Alpha Vertex /*! Get the Alpha vertex at the specified index \param index The index of the Alpha vertex \param &alpha A float to receive the value \return TRUE if successful */ virtual bool GetAlphaVertex(int index, float & alpha) = 0; //!Get the actual Illuminated Vertex /*! Get the Illuminated vertex at the specified index \param index The index of the Illuminated vertex \return A float representing the Illuminated value of the vertex. Return -1 if the index is invalid */ virtual float GetIllumVertex(int index)=0; //!Get the actual Illuminated Vertex /*! Get the Illuminated vertex at the specified index \param index The index of the Illuminated vertex \param &illum A float to receive the data \return TRUE if successful */ virtual bool GetIllumVertex(int index, float &illum) = 0; //! Get the number of faces in the mesh /*! The total number of faces contained in the mesh \return The number of faces */ virtual int GetNumberOfFaces()=0; //! Get the actual face /*! The face represented by the index. The data in FaceEx can be used to lookup into the various arrays \param index The index of the face to return \return A pointer to FaceEx, or NULL if an invalid index is passed in */ virtual FaceEx * GetFace(int index)=0; //!The number of verts in a mapping channel /*! Get the number of the vertices for a particular mapping channel \param ch The mapping channel to use \return The number of verts */ virtual int GetNumberOfMapVerts(int ch) = 0; //! Get the mapping vertex /*! Get the actual mapping vertex for the channel \param ch The channel to query \param index The vertex index \return The actual mapping data. This will be 0 if the Mapping channel is not found */ virtual Point3 GetMapVertex(int ch, int index) = 0; //! Get the mapping vertex /*! Get the actual mapping vertex for the channel \param ch The channel to query \param index The vertex index \param &mVert A Point3 to receive the data \return TRUE if successful */ virtual bool GetMapVertex(int ch, int index, Point3 & mVert) = 0; //!The number of Binormals <b><i>This function is only available in 3ds Max 6.0 and above</i></b> /*! Get the number of the binormals \param mapChannel The valid MESH MAP channel, range (-2...99), default - Texture Coordinates \return The number of binormals for specified map channel */ virtual int GetNumberOfBinormals(int mapChannel = 1) = 0; //!Get the actual Binormal <b><i>This function is only available in 3ds Max 6.0 and above</i></b> /*! Get the Binormal at the specified index \param index The index of the Binormal \param mapChannel The valid MESH MAP channel, range (-2...99), default - Texture Coordinates \return A Point3 representing the Binormal for specified map channel */ virtual Point3 GetBinormal(int index, int mapChannel = 1)=0; //!Get the actual Binormal <b><i>This function is only available in 3ds Max 6.0 and above</i></b> /*! Get the Binormal at the specified index \param index The index of the Binormal \param biNormal A point3 to receive the Binormal for specified map channel \param mapChannel The valid MESH MAP channel, range (-2...99), default - Texture Coordinates \return TRUE if successful */ virtual bool GetBinormal(int index, Point3 & biNormal, int mapChannel = 1) = 0; //!The number of Tangents <b><i>This function is only available in 3ds Max 6.0 and above</i></b> /*! Get the number of the Tangents \param mapChannel The valid MESH MAP channel, range (-2...99), default - Texture Coordinates \return The number of Tangents for specified map channel */ virtual int GetNumberOfTangents(int mapChannel = 1) = 0; //!Get the actual Tangent <b><i>This function is only available in 3ds Max 6.0 and above</i></b> /*! Get the Tangent at the specified index \param index The index of the Tangent \param mapChannel The valid MESH MAP channel, range (-2...99), default - Texture Coordinates \return A Point3 representing the Tangent for specified map channel */ virtual Point3 GetTangent(int index, int mapChannel = 1) = 0; //!Get the actual Tangent <b><i>This function is only available in 3ds Max 6.0 and above</i></b> /*! Get the Tangent at the specified index \param index The index of the Tangent \param Tangent A point3 to receive the Tangent for specified map channel \param mapChannel The valid MESH MAP channel, range (-2...99), default - Texture Coordinates \return TRUE if successful */ virtual bool GetTangent(int index, Point3 & Tangent, int mapChannel = 1) = 0; //! Get the active mapping channels /*! Extracts the active mapping channels in use by the object. Starting with 3DXI V2.0 this returns all active channels including the standard ones such as Texture Coordinates, Vertex Colors, Illum, and Alpha. \return A tab containing the active Mapping channels. */ virtual Tab<int> GetActiveMapChannelNum() = 0; //! Get the face index into the mapping channel array /*! Get the actual index into the mapping channel for the supplied face. \param ch The mapping channel to use \param faceNum The face to use \param index An array of three indices to receive the indexing into the vertices \return TRUE if the channel was accessed correctly. False will mean that the channel was not present. */ virtual bool GetMapFaceIndex(int ch, int faceNum, DWORD *index) = 0; //!Get all the smoothing groups found on a mesh /*! \return A tab containing the smoothing groups. If the count is zero it means that no smoothing groups were found */ virtual Tab<DWORD> GetActiveSmgrps() = 0; //!Get all the material IDs found on a mesh /*! \return A tab containing the Material IDs */ virtual Tab<int> GetActiveMatIDs() = 0; //!Get the face for a particular smoothing group /*! Get all the faces belonging to a particular smoothing group \param smgrp The smoothing group to use \return A tab containing all the faces */ virtual Tab<FaceEx *> GetFacesFromSmgrp(DWORD smgrp) = 0; //!Get the face index for a particular smoothing group /*! Get all the faces belonging to a particular smoothing group as a set of indexes into the main face list \param smgrp The smoothing group to use \return A tab containing all the indexes */ virtual Tab<int> GetFaceIndexFromSmgrp(DWORD smgrp)=0; //! Get the faces for a particular Material ID /*! Get all the faces belonging to a particular material ID \param matID The material ID to use \return A tab containing all the faces */ virtual Tab<FaceEx *> GetFacesFromMatID(int matID) = 0; //!The actual material used by the Face /*!This will provide access to the material used by the Face whose index is passed in. This means the mesh can be broken down into smaller meshes if the material is a subObject material. This can be used in conjunction with IGameMesh::GetFacesFromMatID to rebuild a face with the material assigned via a material ID. \param FaceNum The index of the face whose material is needed. \return A pointer to a material. The is the actual material, so in the case of the SubObject material the material whose mat ID matches. */ virtual IGameMaterial * GetMaterialFromFace(int FaceNum) = 0; //!The actual material used by the Face /*!This will provide access to the material used by the Face. This means the mesh can be broken down into smaller meshes if the material is a subObject material. This can be used in conjunction with IGameMesh::GetFacesFromMatID to rebuild a face with the material assigned via a material ID. \param face A pointer to the face whose material is needed. \return A pointer to a material. The is the actual material, so in the case of the SubObject material the material whose mat ID matches. */ virtual IGameMaterial * GetMaterialFromFace(FaceEx * face) = 0; //! The actual 3ds Max Mesh representation /*! The Mesh pointer used by 3ds Max. This allows the developer further access if required to the mesh or data structures \return A Mesh pointer */ virtual Mesh * GetMaxMesh()=0; //! \name As alternative to FaceEx structure, separate channels can be accessed directly //@{ //!Get Vertex Index for specified face and corner /*! \param faceIndex The face ID to use \param corner The face corner to use \return Vertex Index */ virtual int GetFaceVertex (int faceIndex, int corner)=0; //!Get Map Vertex Index for specified face and corner /*! Texture Vertex by default Should be used to get vertex index for Vertex Color, Alpha, Illum, etc \param faceIndex The face ID to use \param corner The face corner to use \param mapChannel The valid MESH MAP channel, range (-2...99), default - Texture Coordinates \return Map Vertex Index */ virtual int GetFaceTextureVertex (int faceIndex, int corner, int mapChannel = 1)=0; //! Get Normal Vertex Index for specified face and corner /*! \param faceIndex The face ID to use \param corner The face corner to use \return Normal Vertex Index */ virtual int GetFaceVertexNormal (int faceIndex, int corner)=0; //! Get Tangent and Binormal Vertex Index for specified face and corner /*! \param faceIndex The face ID to use \param corner The face corner to use \param mapChannel The valid MESH MAP channel, range (-2...99), default - Texture Coordinates \return Tangent and Binormal Vertex Index if successful, -1 otherwise */ virtual int GetFaceVertexTangentBinormal (int faceIndex, int corner, int mapChannel = 1)=0; //! Get Smoothing Group for specified face /*! \param faceIndex The face ID to use \return Smoothing Group value */ virtual DWORD GetFaceSmoothingGroup (int faceIndex)=0; //! Get Material ID for specified face. /*! \param faceIndex The face ID to use \return Material ID value */ virtual int GetFaceMaterialID (int faceIndex)=0; //! Get Edge Visibility value for specified face and edge. /*! \param faceIndex The face ID to use \param edge The edge to use \return 1 if edge visible, 0 otherwise */ virtual int GetFaceEdgeVisibility (int faceIndex, int edge)=0; //@} //! Access the color data for the face specified. /*! The surface color can be obtained from the RenderedSurface interface. Before this function can be used the Surface data needs to be initialised before hand. Please see the IGameRenderedSurface for more information \param FaceIndex The face index whose color is being evaluated \param *result A pointer to a Color Array that receives the 3 vertices for the face. This should initialised as Color res[3] \return TRUE is successful. Possible errors include the object not being renderable or is hidden. \sa IGameRenderedSurface */ virtual bool EvaluateSurface(int FaceIndex, Color * result) = 0; //! [METHOD IS RETIRED] Tell IGame to create a flattened Normals Array <b><i>This function is only available in 3ds Max 6.0 and above</i></b> /*!IGame can create a flattened list of normals for export much like Vertices and Texture Coordinates. However this operation can be expensive especially on large objects with mixed smoothing groups. This method determines whether this is available for use. <b>If it is not set, then vertex normals can only be looked up on a per face basis </b>.<br><br> Due to some internal changes, this method is not really needed. However some builds of IGame did require it so it has been kept in. */ virtual void SetCreateOptimizedNormalList() = 0; //! N-Polygon support //@{ //! Get the number of polygons in the EPoly /*! The total number of polygons contained in the EPoly \return The number of polygons, zero if mesh can not be converted to EPoly */ virtual int GetNumberOfPolygons()=0; //! Get the number of Normals in the EPoly <b><i> NEW for 3DXI V 2.2 </i></b> /*! The total number of Normalscontained in the EPoly \return The number of Normals, zero if mesh can not be converted to EPoly */ virtual int GetNumberOfPolygonNormals()=0; //! Get Polygon polygon corners /*! The degree (corners) for given polygon in the EPoly \param PolyIndex The polygon index is being evaluated \return The degree (corners) for polygon, zero if mesh can not be converted to EPoly */ virtual int GetNumberOfPolygonCorners(int PolyIndex)=0; //! Get Polygon vertices /*! The vertices ID's for given polygon in the EPoly \param PolyIndex The polygon index is being evaluated \return The vertices ID's as an array, empty if mesh can not be converted to EPoly */ virtual Tab<INT> GetPolygonVertices(int PolyIndex)=0; //! Get Polygon normals /*! The normals ID's for given polygon in the EPoly \param PolyIndex The polygon index is being evaluated \return The normals ID's as an array, empty if mesh can not be converted to EPoly */ virtual Tab<INT> GetPolygonNormals(int PolyIndex)=0; //! Get Polygon normals array <b><i> NEW for 3DXI V 2.2 </i></b> /*! The normals array \param PolyIndex The polygon index is being evaluated. Default is -1, returning all normals for EPoly If parameter defined (other than -1) returns normals for provided polygon only. \return The normals as an array, empty if mesh can not be converted to EPoly */ virtual Tab<Point3> GetPolygonNormalsArray(int PolyIndex = -1)=0; //! Get Polygon map vertices /*! The map vetrices ID's for given polygon in the EPoly \param PolyIndex The polygon index is being evaluated \param MapChannel The map channel is being evaluated \return The map vertices ID's as an array, empty if mesh can not be converted to EPoly */ virtual Tab<INT> GetPolygonMapVertices(int PolyIndex, int MapChannel)=0; //! Get Polygon Edges Visibility /*! The Edges Visibility values for given polygon in the EPoly \param PolyIndex The polygon index is being evaluated \return The Edges Visibility array (1 if edge visible, 0 otherwise), empty if mesh can not be converted to EPoly */ virtual Tab<INT> GetPolygonEgdesVisibility(int PolyIndex)=0; //! Get Smoothing Group for specified Polygon /*! \param PolyIndex The polygon index is being evaluated \return Smoothing Group value */ virtual DWORD GetPolygonSmoothingGroup (int PolyIndex)=0; //! Get Material ID for specified Polygon. /*! \param PolyIndex The polygon index is being evaluated \return Material ID value */ virtual int GetPolygonMaterialID (int PolyIndex)=0; //! Get Polygon Indices based on Material ID /*! The Polygon ID's for given Material ID in the EPoly \param MatID The face index is being evaluated \return The vertices ID's as an array, empty if mesh can not be converted to EPoly */ virtual Tab<INT> GetPolygonIndexFromMatID(int MatID)=0; //! Get Polygon Material /*! The Material for given polygon in the EPoly \param PolyIndex The polygon index is being evaluated \return The Polygon Material, NULL if not exists */ virtual IGameMaterial* GetMaterialFromPolygon(int PolyIndex)= 0; //@} }; //!Simple wrapper for spline knots /*! An IGame wrapper for Knot information */ class IGameKnot: public MaxHeapOperators { public: //! Knot types enum KnotType{ KNOT_AUTO, /*!< Auto generate Knot*/ KNOT_CORNER, /*!< A corner knot*/ KNOT_BEZIER, /*!< A bezier knot*/ KNOT_BEZIER_CORNER, /*!< A bezier corner knot*/ }; //! Knot data enum KnotData{ KNOT_INVEC, /*!< The in vector*/ KNOT_OUTVEC, /*!< The out vector*/ KNOT_POINT, /*!< The actual knot position*/ }; //! \brief Destructor virtual ~IGameKnot() {;} //! Get the in vector /*! \return The in vector */ virtual Point3 GetInVec()=0; //! Get the out vector /*! \return The out vector */ virtual Point3 GetOutVec()=0; //! Get actual knot position /*! \return The knot position */ virtual Point3 GetKnotPoint()=0; //! Get the type of knot /*! \return The knot as a IGameKnot::KnotType */ virtual KnotType GetKnotType()=0; //! Get the knot controller /*! Get the actual IGameController for the knot - this provides access to any animated data \param kd The knot to access \return The controller for the specified knot */ virtual IGameControl * GetKnotControl(KnotData kd)=0; }; //! A wrapper class for splines /*! This provides information about the actual splines making up the spline object in 3ds Max. Access to the knot data is provided with this class */ class IGameSpline3D: public MaxHeapOperators { public: //! \brief Destructor virtual ~IGameSpline3D() {;} //! Access the individual knot /*! \return The knot for the index passed in */ virtual IGameKnot * GetIGameKnot(int index) = 0; //! The knot count /*! \return The total number of knots in the spline */ virtual int GetIGameKnotCount()=0; }; //!Simple wrapper for Splines /*! An IGame wrapper around the standard 3ds Max spline object. IGameSpline acts as a container for all the individual splines that make up the object */ class IGameSpline : public IGameObject { public: //! Get the number of splines /*! The number of splines that make up this object \return The total number of splines */ virtual int GetNumberOfSplines()=0; //! Get an individual Spline /*! Get a spline based on the index. \param index The index of the spline to access \return A pointer to the spline. */ virtual IGameSpline3D * GetIGameSpline3D(int index) =0; //! Get the Max object /*! \return The ShapeObject used by 3ds Max */ virtual ShapeObject * GetMaxShape()=0; }; //!Simple wrapper for IKChains /*! An IGame wrapper around the IKChain object. \n This object be used as a basis for character export. All nodes used in the chain are maintained by the IGameIKChain interface. This allows animation to be exported based on whether it is in IK or FK mode. If the IK is enabled then the IGameControl retrieved from the IGameNode will be that of the End Effector for the chain. If it is in FK mode then the IGameControl from the nodes in the chain would be used for the FK calculation. */ class IGameIKChain : public IGameObject { public: //! Get the number of nodes that make up the chain /*! \return The number of nodes in the chain */ virtual int GetNumberofBonesinChain() =0; //! Access to the n'th node in the chain /*! \param index The index of the node to access \return An IGameNode representation of the node */ virtual IGameNode * GetIGameNodeInChain(int index) =0; //! Get the swivel data /*! The swivel data used in the IK calculation \return The IGameProperty for the swivel data */ virtual IGameProperty * GetSwivelData() = 0; //! Get the controller for the IK enable /*! Access to the Enabled controller - this defines whether IK or FK are used. When IK the end effector is used to control the transforms, in FK the individual nodes can be positioned independent of the effector \return An IGameControl pointer for the Enabled controller. This controller does not have direct access, so should be sampled using IGameControlType::IGAME_FLOAT */ virtual IGameControl * GetIKEnabledController() = 0; }; //! Base class for "support" objects, such as bone, helpers dummies etc.. /*!These types of objects are really supported for their parameter access. However a pointer to the Mesh representation is provided if for example bone geometry is needed. This class can be used to check for BONES, DUMMYS etc.. */ class IGameSupportObject : public IGameObject { public: //! Access to the mesh /*! If required, access to the mesh is provided \return A pointer to an IGameMesh object */ virtual IGameMesh * GetMeshObject() = 0; //!Check for 3ds Max 4.0 version of bone /*! \return TRUE if it is an 3ds Max 4.0 bone. */ virtual bool PreR4Bone() = 0; }; //! An interface for an XRef Object class IGameXRefObject : public IGameObject { public: //!Retrieve XRef File Name /*! \return The name of XRef File */ virtual const MCHAR * GetOriginalFileName() = 0; }; //! A Generic Object for IGame /*! This object represents any object that is unknown to IGame - this could be a new pipeline object for example. It return IGAME_UNKOWN for its IGameObject::ObjectTypes */ class IGameGenObject : public IGameObject { public: //!Retrieve the Property Container /*! \return The PropertyContainer for this entity. */ virtual IPropertyContainer * GetIPropertyContainer()=0; }; #endif //__IGAMEOBJECT__H
var classnd_ray_cast_callback = [ [ "ndRayCastCallback", "classnd_ray_cast_callback.html#a587f680ca496c7f5449cb1ab95297a27", null ], [ "OnRayCastAction", "classnd_ray_cast_callback.html#a25363460d140a2037262ca58df095d7e", null ], [ "OnRayPrecastAction", "classnd_ray_cast_callback.html#ada131d19ad09e1a1662a90a723a7a88d", null ], [ "m_filter", "classnd_ray_cast_callback.html#a94a73db9a304c42bb7a46e3a7d550b65", null ], [ "m_prefilter", "classnd_ray_cast_callback.html#ab272aacbf8aed8c86357265116df17b3", null ], [ "m_userdata", "classnd_ray_cast_callback.html#a88fc1a333745d1130f38052c76695f31", null ] ];
# encoding: utf-8 import datetime __all__ = [ 'info', ] def info(): return { 'birthday': datetime.date(1988, 3, 14), 'class': 4, 'family_name_en': u'deguchi', 'family_name_kana': u'でぐち', 'first_name_en': u'aki', 'first_name_kana': u'あき', 'graduate_date': datetime.date(2007, 11, 26), 'hometown': u'三重', 'name_en': u'Deguchi Aki', 'name_ja': u'出口陽', 'name_kana': u'でぐち あき', 'nick': u'でっぴ', 'team': None, }
import textwrap import unittest from typing import Dict, Any import hypothesis import icontract_hypothesis from icontract import require from correct_programs.ethz_eprog_2019.exercise_12 import problem_01, problem_03 class TestWithIcontractHypothesis(unittest.TestCase): def test_functions(self) -> None: for func in [ problem_03.compile_program, problem_03._execute_const, problem_03._execute_store, problem_03._execute_unary_operation, # NOTE: uncomment once icontract-hypothesis is powerful enough # problem_03._execute_load, ]: try: icontract_hypothesis.test_with_inferred_strategy(func) # type: ignore except Exception as error: raise Exception( f"Automatically testing {func} with icontract-hypothesis failed " f"(please see the original error above)" ) from error def test_binary_operation(self) -> None: strategy = icontract_hypothesis.infer_strategy( problem_03._execute_binary_operation ) @hypothesis.given(strategy) def execute(kwargs: Dict[str, Any]) -> None: try: problem_03._execute_binary_operation(**kwargs) except (OverflowError, ZeroDivisionError): pass execute() def test_call(self) -> None: func_to_execute = problem_03._execute_call strategy = icontract_hypothesis.infer_strategy(func_to_execute) @hypothesis.given(strategy) def execute(kwargs: Dict[str, Any]) -> None: try: func_to_execute(**kwargs) except (OverflowError, ZeroDivisionError, ValueError): pass execute() def test_compile_and_execute_binary_operation_without_variables(self) -> None: @require(lambda left: left >= 0) @require(lambda right: right >= 0) def restricted(operator: problem_01.BinOp, left: float, right: float) -> None: stmt = problem_01.Assign( target=problem_01.Identifier("x"), expr=problem_01.BinaryOperation( left=problem_01.Constant(left), operator=operator, right=problem_01.Constant(right), ), ) program = problem_01.Program(body=[stmt]) try: problem_03.compile_and_execute(program) except (ValueError, OverflowError): pass icontract_hypothesis.test_with_inferred_strategy(restricted) class TestManually(unittest.TestCase): def test_compile(self) -> None: text = "a = (b + 1) / sin(2 * c);" tokens = problem_01.tokenize(text=text) program = problem_01.parse_program(tokens=tokens) instructions = problem_03.compile_program(program) self.assertEqual( "[" "Load('b'), " "Const(1.0), " "BinaryOperation(<BinOp.ADD: '+'>), " "Const(2.0), " "Load('c'), " "BinaryOperation(<BinOp.MUL: '*'>), " "Call(<Function.SIN: 'sin'>), " "BinaryOperation(<BinOp.DIV: '/'>), " "Store('a')" "]", repr(instructions), ) def test_compile_and_execute(self) -> None: table = [ "PI = 3.14159265359;", "x = 3; a = -x; b = x + 3; c = sin(x);", "b = 1; c = 2; a = (b + 1) / sin(2 * c);" "x = 1 / 6.05;", textwrap.dedent( """\ i = 1; t = 2; PI = 3.14159265359; alpha = i * ((2*PI) * (1 / 6.05)); """ ), ] for text in table: tokens = problem_01.tokenize(text=text) program = problem_01.parse_program(tokens=tokens) problem_03.compile_and_execute(program) if __name__ == "__main__": unittest.main()
/** * Auto-generated action file for "Power BI Embedded Management Client" API. * * Generated at: 2019-05-07T14:38:37.453Z * Mass generator version: 1.1.0 * * flowground :- Telekom iPaaS / azure-com-powerbiembedded-connector * Copyright © 2019, Deutsche Telekom AG * contact: flowground@telekom.de * * All files of this connector are licensed under the Apache 2.0 License. For details * see the file LICENSE on the toplevel directory. * * * Operation: 'getAvailableOperations' * Endpoint Path: '/providers/Microsoft.PowerBI/operations' * Method: 'get' * */ const Swagger = require('swagger-client'); const processWrapper = require('../services/process-wrapper'); const spec = require('../spec.json'); // this wrapers offers a simplified emitData(data) function module.exports.process = processWrapper(processAction); // parameter names for this call const PARAMETERS = [ "api-version" ]; // mappings from connector field names to API field names const FIELD_MAP = { "api_version": "api-version" }; function processAction(msg, cfg) { var isVerbose = process.env.debug || cfg.verbose; if (isVerbose) { console.log(`---MSG: ${JSON.stringify(msg)}`); console.log(`---CFG: ${JSON.stringify(cfg)}`); console.log(`---ENV: ${JSON.stringify(process.env)}`); } const contentType = undefined; const body = msg.body; mapFieldNames(body); let parameters = {}; for(let param of PARAMETERS) { parameters[param] = body[param]; } // credentials for this operation let securities = {}; let callParams = { spec: spec, operationId: 'getAvailableOperations', pathName: '/providers/Microsoft.PowerBI/operations', method: 'get', parameters: parameters, requestContentType: contentType, requestBody: body.requestBody, securities: {authorized: securities}, server: spec.servers[cfg.server] || cfg.otherServer, }; if (isVerbose) { let out = Object.assign({}, callParams); out.spec = '[omitted]'; console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`); } // Call operation via Swagger client return Swagger.execute(callParams).then(data => { // emit a single message with data this.emitData(data); // if the response contains an array of entities, you can emit them one by one: // data.obj.someItems.forEach((item) => { // this.emitData(item); // } }); } function mapFieldNames(obj) { if(Array.isArray(obj)) { obj.forEach(mapFieldNames); } else if(typeof obj === 'object' && obj) { Object.keys(obj).forEach(key => { mapFieldNames(obj[key]); let goodKey = FIELD_MAP[key]; if(goodKey && goodKey !== key) { obj[goodKey] = obj[key]; delete obj[key]; } }); } }
/* * Copyright © 2006-2009 Simon Thum * Copyright © 2012 Jonas Ådahl * Copyright © 2014-2015 Red Hat, Inc. * * 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 (including the next * paragraph) 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. */ #include "config.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <limits.h> #include <math.h> #include "filter.h" #include "libinput-util.h" #include "filter-private.h" /* Trackpoint acceleration for the Lenovo x230. DO NOT TOUCH. * This code is only invoked on the X230 and is quite flimsy, * custom-designed to make this touchpad less terrible than the * out-of-the-box experience. The x230 was released in 2013, it's * not worth trying to optimize the code or de-duplicate the various * copy-pastes. */ /* * Default parameters for pointer acceleration profiles. */ #define DEFAULT_THRESHOLD v_ms2us(0.4) /* in units/us */ #define MINIMUM_THRESHOLD v_ms2us(0.2) /* in units/us */ #define DEFAULT_ACCELERATION 2.0 /* unitless factor */ #define DEFAULT_INCLINE 1.1 /* unitless factor */ /* for the Lenovo x230 custom accel. do not touch */ #define X230_THRESHOLD v_ms2us(0.4) /* in units/us */ #define X230_ACCELERATION 2.0 /* unitless factor */ #define X230_INCLINE 1.1 /* unitless factor */ #define X230_MAGIC_SLOWDOWN 0.4 /* unitless */ #define X230_TP_MAGIC_LOW_RES_FACTOR 4.0 /* unitless */ struct pointer_accelerator_x230 { struct motion_filter base; accel_profile_func_t profile; double velocity; /* units/us */ double last_velocity; /* units/us */ struct pointer_trackers trackers; double threshold; /* units/us */ double accel; /* unitless factor */ double incline; /* incline of the function */ int dpi; }; /** * Apply the acceleration profile to the given velocity. * * @param accel The acceleration filter * @param data Caller-specific data * @param velocity Velocity in device-units per µs * @param time Current time in µs * * @return A unitless acceleration factor, to be applied to the delta */ static double acceleration_profile(struct pointer_accelerator_x230 *accel, void *data, double velocity, uint64_t time) { return accel->profile(&accel->base, data, velocity, time); } /** * Calculate the acceleration factor for our current velocity, averaging * between our current and the most recent velocity to smoothen out changes. * * @param accel The acceleration filter * @param data Caller-specific data * @param velocity Velocity in device-units per µs * @param last_velocity Previous velocity in device-units per µs * @param time Current time in µs * * @return A unitless acceleration factor, to be applied to the delta */ static double calculate_acceleration(struct pointer_accelerator_x230 *accel, void *data, double velocity, double last_velocity, uint64_t time) { double factor; /* Use Simpson's rule to calculate the avarage acceleration between * the previous motion and the most recent. */ factor = acceleration_profile(accel, data, velocity, time); factor += acceleration_profile(accel, data, last_velocity, time); factor += 4.0 * acceleration_profile(accel, data, (last_velocity + velocity) / 2, time); factor = factor / 6.0; return factor; /* unitless factor */ } /** * Calculate the acceleration factor for the given delta with the timestamp. * * @param accel The acceleration filter * @param unaccelerated The raw delta in the device's dpi * @param data Caller-specific data * @param time Current time in µs * * @return A unitless acceleration factor, to be applied to the delta */ static inline double calculate_acceleration_factor(struct pointer_accelerator_x230 *accel, const struct device_float_coords *unaccelerated, void *data, uint64_t time) { double velocity; /* units/us in device-native dpi*/ double accel_factor; trackers_feed(&accel->trackers, unaccelerated, time); velocity = trackers_velocity(&accel->trackers, time); accel_factor = calculate_acceleration(accel, data, velocity, accel->last_velocity, time); accel->last_velocity = velocity; return accel_factor; } static struct normalized_coords accelerator_filter_x230(struct motion_filter *filter, const struct device_float_coords *raw, void *data, uint64_t time) { struct pointer_accelerator_x230 *accel = (struct pointer_accelerator_x230 *) filter; double accel_factor; /* unitless factor */ struct normalized_coords accelerated; struct device_float_coords delta_normalized; struct normalized_coords unaccelerated; double velocity; /* units/us */ /* This filter is a "do not touch me" filter. So the hack here is * just to replicate the old behavior before filters switched to * device-native dpi: * 1) convert from device-native to 1000dpi normalized * 2) run all calculation on 1000dpi-normalized data * 3) apply accel factor no normalized data */ unaccelerated = normalize_for_dpi(raw, accel->dpi); delta_normalized.x = unaccelerated.x; delta_normalized.y = unaccelerated.y; trackers_feed(&accel->trackers, &delta_normalized, time); velocity = trackers_velocity(&accel->trackers, time); accel_factor = calculate_acceleration(accel, data, velocity, accel->last_velocity, time); accel->last_velocity = velocity; accelerated.x = accel_factor * delta_normalized.x; accelerated.y = accel_factor * delta_normalized.y; return accelerated; } static struct normalized_coords accelerator_filter_constant_x230(struct motion_filter *filter, const struct device_float_coords *unaccelerated, void *data, uint64_t time) { struct pointer_accelerator_x230 *accel = (struct pointer_accelerator_x230 *) filter; struct normalized_coords normalized; const double factor = X230_MAGIC_SLOWDOWN/X230_TP_MAGIC_LOW_RES_FACTOR; normalized = normalize_for_dpi(unaccelerated, accel->dpi); normalized.x = factor * normalized.x; normalized.y = factor * normalized.y; return normalized; } static void accelerator_restart_x230(struct motion_filter *filter, void *data, uint64_t time) { struct pointer_accelerator_x230 *accel = (struct pointer_accelerator_x230 *) filter; unsigned int offset; struct pointer_tracker *tracker; for (offset = 1; offset < accel->trackers.ntrackers; offset++) { tracker = trackers_by_offset(&accel->trackers, offset); tracker->time = 0; tracker->dir = 0; tracker->delta.x = 0; tracker->delta.y = 0; } tracker = trackers_by_offset(&accel->trackers, 0); tracker->time = time; tracker->dir = UNDEFINED_DIRECTION; } static void accelerator_destroy_x230(struct motion_filter *filter) { struct pointer_accelerator_x230 *accel = (struct pointer_accelerator_x230 *) filter; free(accel->trackers.trackers); free(accel); } static bool accelerator_set_speed_x230(struct motion_filter *filter, double speed_adjustment) { struct pointer_accelerator_x230 *accel_filter = (struct pointer_accelerator_x230 *)filter; assert(speed_adjustment >= -1.0 && speed_adjustment <= 1.0); /* Note: the numbers below are nothing but trial-and-error magic, don't read more into them other than "they mostly worked ok" */ /* delay when accel kicks in */ accel_filter->threshold = DEFAULT_THRESHOLD - v_ms2us(0.25) * speed_adjustment; if (accel_filter->threshold < MINIMUM_THRESHOLD) accel_filter->threshold = MINIMUM_THRESHOLD; /* adjust max accel factor */ accel_filter->accel = DEFAULT_ACCELERATION + speed_adjustment * 1.5; /* higher speed -> faster to reach max */ accel_filter->incline = DEFAULT_INCLINE + speed_adjustment * 0.75; filter->speed_adjustment = speed_adjustment; return true; } double touchpad_lenovo_x230_accel_profile(struct motion_filter *filter, void *data, double speed_in, /* 1000dpi-units/µs */ uint64_t time) { /* Those touchpads presents an actual lower resolution that what is * advertised. We see some jumps from the cursor due to the big steps * in X and Y when we are receiving data. * Apply a factor to minimize those jumps at low speed, and try * keeping the same feeling as regular touchpads at high speed. * It still feels slower but it is usable at least */ double factor; /* unitless */ struct pointer_accelerator_x230 *accel_filter = (struct pointer_accelerator_x230 *)filter; double f1, f2; /* unitless */ const double max_accel = accel_filter->accel * X230_TP_MAGIC_LOW_RES_FACTOR; /* unitless factor */ const double threshold = accel_filter->threshold / X230_TP_MAGIC_LOW_RES_FACTOR; /* units/us */ const double incline = accel_filter->incline * X230_TP_MAGIC_LOW_RES_FACTOR; /* Note: the magic values in this function are obtained by * trial-and-error. No other meaning should be interpreted. * The calculation is a compressed form of * pointer_accel_profile_linear(), look at the git history of that * function for an explanation of what the min/max/etc. does. */ speed_in *= X230_MAGIC_SLOWDOWN / X230_TP_MAGIC_LOW_RES_FACTOR; f1 = min(1, v_us2ms(speed_in) * 5); f2 = 1 + (v_us2ms(speed_in) - v_us2ms(threshold)) * incline; factor = min(max_accel, f2 > 1 ? f2 : f1); return factor * X230_MAGIC_SLOWDOWN / X230_TP_MAGIC_LOW_RES_FACTOR; } struct motion_filter_interface accelerator_interface_x230 = { .type = LIBINPUT_CONFIG_ACCEL_PROFILE_ADAPTIVE, .filter = accelerator_filter_x230, .filter_constant = accelerator_filter_constant_x230, .restart = accelerator_restart_x230, .destroy = accelerator_destroy_x230, .set_speed = accelerator_set_speed_x230, }; /* The Lenovo x230 has a bad touchpad. This accel method has been * trial-and-error'd, any changes to it will require re-testing everything. * Don't touch this. */ struct motion_filter * create_pointer_accelerator_filter_lenovo_x230(int dpi, bool use_velocity_averaging) { struct pointer_accelerator_x230 *filter; filter = zalloc(sizeof *filter); filter->base.interface = &accelerator_interface_x230; filter->profile = touchpad_lenovo_x230_accel_profile; filter->last_velocity = 0.0; trackers_init(&filter->trackers, use_velocity_averaging ? 16 : 2); filter->threshold = X230_THRESHOLD; filter->accel = X230_ACCELERATION; /* unitless factor */ filter->incline = X230_INCLINE; /* incline of the acceleration function */ filter->dpi = dpi; return &filter->base; }
from random import choice, sample, shuffle import unittest class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = list(range(10)) def test_shuffle(self): shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, list(range(10))) self.assertRaises(TypeError, shuffle, (1,2,3)) def test_choice(self): element = choice(self.seq) self.assertTrue(element in self.seq) def test_sample(self): with self.assertRaises(ValueError): sample(self.seq, 20) for element in sample(self.seq, 5): self.assertTrue(element in self.seq) if __name__ == '__main__': unittest.main()
"""Test the Amber Electric Sensors.""" from typing import AsyncGenerator, List from unittest.mock import Mock, patch from amberelectric.model.current_interval import CurrentInterval from amberelectric.model.range import Range import pytest from homeassistant.components.amberelectric.const import ( CONF_API_TOKEN, CONF_SITE_ID, CONF_SITE_NAME, DOMAIN, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry from tests.components.amberelectric.helpers import ( CONTROLLED_LOAD_CHANNEL, FEED_IN_CHANNEL, GENERAL_AND_CONTROLLED_SITE_ID, GENERAL_AND_FEED_IN_SITE_ID, GENERAL_CHANNEL, GENERAL_ONLY_SITE_ID, ) MOCK_API_TOKEN = "psk_0000000000000000" @pytest.fixture async def setup_general(hass) -> AsyncGenerator: """Set up general channel.""" MockConfigEntry( domain="amberelectric", data={ CONF_SITE_NAME: "mock_title", CONF_API_TOKEN: MOCK_API_TOKEN, CONF_SITE_ID: GENERAL_ONLY_SITE_ID, }, ).add_to_hass(hass) instance = Mock() with patch( "amberelectric.api.AmberApi.create", return_value=instance, ) as mock_update: instance.get_current_price = Mock(return_value=GENERAL_CHANNEL) assert await async_setup_component(hass, DOMAIN, {}) await hass.async_block_till_done() yield mock_update.return_value @pytest.fixture async def setup_general_and_controlled_load(hass) -> AsyncGenerator: """Set up general channel and controller load channel.""" MockConfigEntry( domain="amberelectric", data={ CONF_API_TOKEN: MOCK_API_TOKEN, CONF_SITE_ID: GENERAL_AND_CONTROLLED_SITE_ID, }, ).add_to_hass(hass) instance = Mock() with patch( "amberelectric.api.AmberApi.create", return_value=instance, ) as mock_update: instance.get_current_price = Mock( return_value=GENERAL_CHANNEL + CONTROLLED_LOAD_CHANNEL ) assert await async_setup_component(hass, DOMAIN, {}) await hass.async_block_till_done() yield mock_update.return_value @pytest.fixture async def setup_general_and_feed_in(hass) -> AsyncGenerator: """Set up general channel and feed in channel.""" MockConfigEntry( domain="amberelectric", data={ CONF_API_TOKEN: MOCK_API_TOKEN, CONF_SITE_ID: GENERAL_AND_FEED_IN_SITE_ID, }, ).add_to_hass(hass) instance = Mock() with patch( "amberelectric.api.AmberApi.create", return_value=instance, ) as mock_update: instance.get_current_price = Mock( return_value=GENERAL_CHANNEL + FEED_IN_CHANNEL ) assert await async_setup_component(hass, DOMAIN, {}) await hass.async_block_till_done() yield mock_update.return_value async def test_general_price_sensor(hass: HomeAssistant, setup_general: Mock) -> None: """Test the General Price sensor.""" assert len(hass.states.async_all()) == 4 price = hass.states.get("sensor.mock_title_general_price") assert price assert price.state == "0.08" attributes = price.attributes assert attributes["duration"] == 30 assert attributes["date"] == "2021-09-21" assert attributes["per_kwh"] == 0.08 assert attributes["nem_date"] == "2021-09-21T08:30:00+10:00" assert attributes["spot_per_kwh"] == 0.01 assert attributes["start_time"] == "2021-09-21T08:00:00+10:00" assert attributes["end_time"] == "2021-09-21T08:30:00+10:00" assert attributes["renewables"] == 51 assert attributes["estimate"] is True assert attributes["spike_status"] == "none" assert attributes["channel_type"] == "general" assert attributes["attribution"] == "Data provided by Amber Electric" assert attributes.get("range_min") is None assert attributes.get("range_max") is None with_range: List[CurrentInterval] = GENERAL_CHANNEL with_range[0].range = Range(7.8, 12.4) setup_general.get_current_price.return_value = with_range config_entry = hass.config_entries.async_entries(DOMAIN)[0] await hass.config_entries.async_reload(config_entry.entry_id) await hass.async_block_till_done() price = hass.states.get("sensor.mock_title_general_price") assert price attributes = price.attributes assert attributes.get("range_min") == 0.08 assert attributes.get("range_max") == 0.12 async def test_general_and_controlled_load_price_sensor( hass: HomeAssistant, setup_general_and_controlled_load: Mock ) -> None: """Test the Controlled Price sensor.""" assert len(hass.states.async_all()) == 6 price = hass.states.get("sensor.mock_title_controlled_load_price") assert price assert price.state == "0.08" attributes = price.attributes assert attributes["duration"] == 30 assert attributes["date"] == "2021-09-21" assert attributes["per_kwh"] == 0.08 assert attributes["nem_date"] == "2021-09-21T08:30:00+10:00" assert attributes["spot_per_kwh"] == 0.01 assert attributes["start_time"] == "2021-09-21T08:00:00+10:00" assert attributes["end_time"] == "2021-09-21T08:30:00+10:00" assert attributes["renewables"] == 51 assert attributes["estimate"] is True assert attributes["spike_status"] == "none" assert attributes["channel_type"] == "controlledLoad" assert attributes["attribution"] == "Data provided by Amber Electric" async def test_general_and_feed_in_price_sensor( hass: HomeAssistant, setup_general_and_feed_in: Mock ) -> None: """Test the Feed In sensor.""" assert len(hass.states.async_all()) == 6 price = hass.states.get("sensor.mock_title_feed_in_price") assert price assert price.state == "-0.08" attributes = price.attributes assert attributes["duration"] == 30 assert attributes["date"] == "2021-09-21" assert attributes["per_kwh"] == -0.08 assert attributes["nem_date"] == "2021-09-21T08:30:00+10:00" assert attributes["spot_per_kwh"] == 0.01 assert attributes["start_time"] == "2021-09-21T08:00:00+10:00" assert attributes["end_time"] == "2021-09-21T08:30:00+10:00" assert attributes["renewables"] == 51 assert attributes["estimate"] is True assert attributes["spike_status"] == "none" assert attributes["channel_type"] == "feedIn" assert attributes["attribution"] == "Data provided by Amber Electric" async def test_general_forecast_sensor( hass: HomeAssistant, setup_general: Mock ) -> None: """Test the General Forecast sensor.""" assert len(hass.states.async_all()) == 4 price = hass.states.get("sensor.mock_title_general_forecast") assert price assert price.state == "0.09" attributes = price.attributes assert attributes["channel_type"] == "general" assert attributes["attribution"] == "Data provided by Amber Electric" first_forecast = attributes["forecasts"][0] assert first_forecast["duration"] == 30 assert first_forecast["date"] == "2021-09-21" assert first_forecast["per_kwh"] == 0.09 assert first_forecast["nem_date"] == "2021-09-21T09:00:00+10:00" assert first_forecast["spot_per_kwh"] == 0.01 assert first_forecast["start_time"] == "2021-09-21T08:30:00+10:00" assert first_forecast["end_time"] == "2021-09-21T09:00:00+10:00" assert first_forecast["renewables"] == 50 assert first_forecast["spike_status"] == "none" assert first_forecast.get("range_min") is None assert first_forecast.get("range_max") is None with_range: List[CurrentInterval] = GENERAL_CHANNEL with_range[1].range = Range(7.8, 12.4) setup_general.get_current_price.return_value = with_range config_entry = hass.config_entries.async_entries(DOMAIN)[0] await hass.config_entries.async_reload(config_entry.entry_id) await hass.async_block_till_done() price = hass.states.get("sensor.mock_title_general_forecast") assert price attributes = price.attributes first_forecast = attributes["forecasts"][0] assert first_forecast.get("range_min") == 0.08 assert first_forecast.get("range_max") == 0.12 async def test_controlled_load_forecast_sensor( hass: HomeAssistant, setup_general_and_controlled_load: Mock ) -> None: """Test the Controlled Load Forecast sensor.""" assert len(hass.states.async_all()) == 6 price = hass.states.get("sensor.mock_title_controlled_load_forecast") assert price assert price.state == "0.09" attributes = price.attributes assert attributes["channel_type"] == "controlledLoad" assert attributes["attribution"] == "Data provided by Amber Electric" first_forecast = attributes["forecasts"][0] assert first_forecast["duration"] == 30 assert first_forecast["date"] == "2021-09-21" assert first_forecast["per_kwh"] == 0.09 assert first_forecast["nem_date"] == "2021-09-21T09:00:00+10:00" assert first_forecast["spot_per_kwh"] == 0.01 assert first_forecast["start_time"] == "2021-09-21T08:30:00+10:00" assert first_forecast["end_time"] == "2021-09-21T09:00:00+10:00" assert first_forecast["renewables"] == 50 assert first_forecast["spike_status"] == "none" async def test_feed_in_forecast_sensor( hass: HomeAssistant, setup_general_and_feed_in: Mock ) -> None: """Test the Feed In Forecast sensor.""" assert len(hass.states.async_all()) == 6 price = hass.states.get("sensor.mock_title_feed_in_forecast") assert price assert price.state == "-0.09" attributes = price.attributes assert attributes["channel_type"] == "feedIn" assert attributes["attribution"] == "Data provided by Amber Electric" first_forecast = attributes["forecasts"][0] assert first_forecast["duration"] == 30 assert first_forecast["date"] == "2021-09-21" assert first_forecast["per_kwh"] == -0.09 assert first_forecast["nem_date"] == "2021-09-21T09:00:00+10:00" assert first_forecast["spot_per_kwh"] == 0.01 assert first_forecast["start_time"] == "2021-09-21T08:30:00+10:00" assert first_forecast["end_time"] == "2021-09-21T09:00:00+10:00" assert first_forecast["renewables"] == 50 assert first_forecast["spike_status"] == "none" def test_renewable_sensor(hass: HomeAssistant, setup_general) -> None: """Testing the creation of the Amber renewables sensor.""" assert len(hass.states.async_all()) == 4 sensor = hass.states.get("sensor.mock_title_renewables") assert sensor assert sensor.state == "51"
import jovialengine from monster import Monster from .modefight import ModeFight from .modetalkwin2 import ModeTalkWin2 from .modeconvo import ModeConvo class ModeTalkElse2(ModeConvo): def _handleButton(self, prev_convo_key: str, index: int): if prev_convo_key == "2": self._stopMixer() self.next_mode = ModeFight( jovialengine.shared.state.protag_mon, Monster.atLevel(2), lambda: ModeTalkWin2() if jovialengine.shared.state.fight_results[-1] == 1 else ModeTalkElse2() ) return True return False
import * as types from '../../common/constants/ActionTypes'; import shop from '../../shared/shop.js'; const myInfoInitDip = (data) => ({ type:types.MY_INIT, data:data }) export const myInfoInit = () => dispatch =>{ shop.myInfoInit(info => { dispatch(myInfoInitDip(info)) }) }
''' Сумма последовательности ''' def sum(): a = int(input()) if (a == 0): return 0 return a + sum() print(sum())
# # 2021-03-15 # created by hong joon # import os from subprocess import check_output import argparse import sys import os import lxml.etree as ET import subprocess import math sys.path.append("") from testlibs import utils, test_result def exec_shell_cmd(cmd): if os.system(cmd) != 0: print("error while executing '%s'" % cmd) exit(-1) def simulation_test_result(condition_count, node_count, test_name): if condition_count == node_count: print("Success %s ... " %test_name) print("test result : %d/%d " %(condition_count,node_count)) else: print("Fail %s ..." %test_name) print("test result : %d/%d " %(condition_count,node_count)) sys.exit(1) # -------------------------------------------------------------------------------------------------------------- # Regression test-01 - xmlGenerate test # -------------------------------------------------------------------------------------------------------------- # xml existence test - If there is no file in the path, return fail def test_xml_existence(output): path = os.path.abspath(".") target_folder = path + "/" + output if os.path.isfile(target_folder): print("Success xml existence test ...") return target_folder else: print("Fail xml existence test ...") sys.exit(1) # -------------------------------------------------------------------------------------------------------------- # Regression test-02-1 - shadow test # -------------------------------------------------------------------------------------------------------------- def test_shadow_output_file_existence(condition_number, node_id_list): # plugin output check for i in range(0,len(node_id_list)): path_ = os.path.abspath(".") path_ = path_ + "/shadow.data/hosts/" + node_id_list[i] if os.path.isdir(path_): pass else: print("%s file not existence shadow output file ... " %node_id_list[i]) # shadow output.txt if condition_number == "regtest": path = os.path.abspath(".") else: path = os.path.abspath("./shadow.data") target_folder_file = path + "/output.txt" if os.path.isfile(target_folder_file): return target_folder_file else: print("Fail not existence shadow output file ... ") # -------------------------------------------------------------------------------------------------------------- # Regression test-02-2 - shadow test # -------------------------------------------------------------------------------------------------------------- # test1 : whether runtime setting worked or not # test2 : whether plugin(node_id) worked or not def test_shadow(output_file, runtime, node_id_list, shadow_output): f = open(output_file, "r") # result_count more than 3 means success. result_count = 0 return_count = 0 condition_runtime = 0 return_time = utils.get_time_form(runtime) while True: line = f.readline() if not line: break result = line.find("has set up the main pth thread") if result != -1: result = line.find("_process_start") if result != -1: for i in range(0,len(node_id_list)): result = line.find(node_id_list[i]) if result != -1: result_count += 1 break # 설정한 runtime 동작 확인. if condition_runtime == 0: result = line.find(runtime) if result != -1: condition_runtime = 1 if result_count == len(node_id_list): f.close() print("Success shadow test ...") return_count = 1 sys.exit(0) else: f.close() print("shadow plugin error...") sys.exit(1) if return_count == 0: f.close() if result_count == len(node_id_list): print("[shadow test] - runtime over ... ") pass else: print("shadow runtime error .... ") utils.filter_fail_shadow_test(shadow_output) sys.exit(1) else: if condition_runtime != 1: print("Fail shadow test - runtime fail ... ") sys.exit(1) pass # -------------------------------------------------------------------------------------------------------------- # Regression test-02-2 - shadow test (emulation ver) # -------------------------------------------------------------------------------------------------------------- # test1 : whether runtime setting worked or not # test2 : whether plugin(node_id) worked or not' def emul_test_shadow(output_file, runtime, node_id_list, shadow_output): complete_node = [] f = open(output_file, "r") # result_count more than 3 means success. result_count = 0 return_time = utils.get_time_form(runtime) while True: line = f.readline() if not line: break result = line.find("_process_start") if result != -1: result = line.find("has set up the main pth thread") if result != -1: result = line.find("bitcoind") if result != -1: complete_node.append(line.split(" ")[4].split("~")[1][:-1]) for i in range(0,len(node_id_list)): result = line.find(node_id_list[i]) if result != -1: result_count = 1 result = line.find(return_time) if result != -1: if result_count == 1: f.close() print("Success shadow test ...") return complete_node, runtime else: f.close() print("Fail shadow test] - runtime error ...") utils.filter_fail_shadow_test(shadow_output) sys.exit(1) f.close() print("[Fail shadow test] - plugin does not run ...") sys.exit(1) # -------------------------------------------------------------------------------------------------------------- # Regression test-03-1 - bitcoinApplication file existence test. # -------------------------------------------------------------------------------------------------------------- # After shadow, check output data def test_file_existence(node_id_list, plugin_list): if len(node_id_list) != len(plugin_list): sys.exit(1) path = os.path.abspath(".") target_folder_list = [] target_error_list = [] error_list = [] for i in range(0,len(node_id_list)): target_path = path + "/shadow.data/hosts/" + node_id_list[i] + "/stdout-" + node_id_list[i] + "." + plugin_list[i] + ".1000.log" target_folder_list.append(target_path) target_path = path + "/shadow.data/hosts/" + node_id_list[i] + "/stderr-" + node_id_list[i] + "." + plugin_list[i] + ".1000.log" target_error_list.append(target_path) for i in range(0,len(target_folder_list)): if os.path.isfile(target_folder_list[i]) == False: print("Fail not existence shadow plugin output file - %s" %(target_folder_list[i])) sys.exit(1) # 에러 파일이 존재하면 그 파일의 path를 error_list에 append. if os.path.isfile(target_error_list[i]) == True: error_list.append(target_error_list[i]) # 에러 파일이 존재하는 경우 if len(error_list) != 0: print("Fail shadow plugin running ...") print("-------------- shadow plugin error contents --------------") for i in range(0,len(error_list)): f = open(error_list[i], "r") while True: line = f.readline().strip() print(line) if not line: break f.close() sys.exit(1) print("Success blockchain test output file existence ...") return target_folder_list # -------------------------------------------------------------------------------------------------------------- # Regression test-03-2 - bitcoinApplication test # -------------------------------------------------------------------------------------------------------------- # This test compares the shadow result log with standard args, # and succeeds if all of the args are in the shadow result log. def test_bitcoinApplication(output_file, args_standard, node_count): j = 0 condition_count = 0 for z in range(0,int(node_count)): f = open(output_file[z], "r") while True: line = f.readline() if not line: break for i in range(j,len(args_standard)): result = line.find(args_standard[i]) if result != -1: j += 1 f.close() if j == len(args_standard): condition_count += 1 simulation_test_result(condition_count, node_count, "test_bitcoinApplication") sys.exit(0) # -------------------------------------------------------------------------------------------------------------- # Regression test-04 - bitcoin difficulty test # -------------------------------------------------------------------------------------------------------------- # 설정한 난이도와 시뮬레이션된 비트코인 난이도가 일치한지 테스트 def test_difficulty_compare(bitcoin_log, xml_difficulty, node_count): condition_count = 0 for z in range(0,node_count): difficulty = "" f = open(bitcoin_log[z + node_count], "r") while True: line = f.readline() if not line: break result = line.find("difficulty") if result != -1: split_list = line.split(",")[4] difficulty = split_list.split(":")[1] break f.close() if str(xml_difficulty) == "1": if difficulty == "1": condition_count += 1 elif str(xml_difficulty) == "2": if difficulty == "0.00390625": condition_count += 1 elif str(xml_difficulty) == "3": if difficulty == "0.0002441371325370145": condition_count += 1 simulation_test_result(condition_count, node_count, "test_difficulty_compare test") sys.exit(0) # -------------------------------------------------------------------------------------------------------------- # Regression test-05 - wallet address test # -------------------------------------------------------------------------------------------------------------- # bitcoin-cli validateaddress call # Return information about the given bitcoin address. def test_walletAddress(simulation_output_file, node_count): condition_count = 0 for z in range(0,node_count): f = open(simulation_output_file[z+node_count], "r") while True: line = f.readline() if not line: break result = line.find("isvalid") if result != -1: the_wallet_validation = line.split(",")[0].split('"')[4].split(":")[1] if the_wallet_validation == "true": condition_count += 1 continue simulation_test_result(condition_count, node_count, "test_walletAddress ") # -------------------------------------------------------------------------------------------------------------- # Regression test-06 - mining test # -------------------------------------------------------------------------------------------------------------- # "height>0" means mining is activated and works good. # If "height>0" is found at bitcoin log, mining works. def test_mining(shadow_output_file, node_count): condition_count = 0 for z in range(0,node_count): f = open(shadow_output_file[z], "r") while True: line = f.readline() if not line: break # height=1 means mining activated. result = line.find("height=8") if result != -1: condition_count += 1 break simulation_test_result(condition_count, node_count, "mining test") sys.exit(0) # -------------------------------------------------------------------------------------------------------------- # Regression test-07 - bitcoin mainchain test # -------------------------------------------------------------------------------------------------------------- # Get "bestblockchash" value info using rpc.output_file then check for the same value in bitcoin output log. def test_MainChainInfo(shadow_output_file, rpc_output_file, node_count): pork_count = 0 while True: condition_count = utils.get_last_hashValue(shadow_output_file, rpc_output_file, node_count, pork_count) if condition_count == node_count: break else: pork_count += 1 if pork_count > 6: print("Fail mainchain test ... (network separation) ") elif pork_count == 0: pass else: print("There is a fork ...") condition_count = node_count simulation_test_result(condition_count, node_count, "mainchain test") sys.exit(0) # -------------------------------------------------------------------------------------------------------------- # Regression test-08 - transaction test # -------------------------------------------------------------------------------------------------------------- # If rpc output file has error log, the transaction is not created properlys def test_transaction_existence(simulation_output_file, node_count): condition_count = 0 for z in range(0,node_count): f = open(simulation_output_file[z+node_count], "r") while True: line = f.readline() if not line: break result = line.find('"error":null') if result != -1: condition_count += 1 break f.close() simulation_test_result(condition_count, node_count, "transaction test") # -------------------------------------------------------------------------------------------------------------- # Regression test-09 - transaction count test (emulation ver) # -------------------------------------------------------------------------------------------------------------- # 설정한 트랜잭션의 개수와 생성되 트랜잭션의 개수를 비교하는 테스트 def test_transaction_count(simulation_output_file): txs_bitcoind = 0 blocks_count = 0 f = open(simulation_output_file[0], "r") for line in f.readlines()[::-1]: result = line.find("UpdateTip") if result != -1: split_list = line.split(" ") for i in range(0,len(split_list)): result = split_list[i].find("height=") if result != -1: blocks_count = int(split_list[i].split("=")[1]) continue result = split_list[i].find("tx=") if result != -1: txs_bitcoind = int(split_list[i].split("=")[1]) break if txs_bitcoind != 0: break f.close() return txs_bitcoind # -------------------------------------------------------------------------------------------------------------- # Regression test-09 - transaction count test (regtest ver) # -------------------------------------------------------------------------------------------------------------- # count "sendtoaddress" rpc request in bitcoin log and get transaction counts in tx injector log. # If the two are the same, true def test_transaction_count_regtest(simulation_output_file): txs_bitcoind = 0 blocks_count = 0 mempool_size = 0 condition_count = 0 f = open(simulation_output_file[0], "r") for line in f.readlines()[::-1]: result = line.find("UpdateTip") if result != -1: split_list = line.split(" ") for i in range(0,len(split_list)): result = split_list[i].find("height=") if result != -1: blocks_count = int(split_list[i].split("=")[1]) continue result = split_list[i].find("tx=") if result != -1: txs_bitcoind = int(split_list[i].split("=")[1]) break if txs_bitcoind != 0: break f.close() # -------------------------------------------------------------------------------------------------------------- # Regression test-10 - initial coin test # -------------------------------------------------------------------------------------------------------------- # initial coin이 생성된지 확인하기 위한 테스트. def test_initialCoin(simulation_output_file): f = open(simulation_output_file, "r") block_count = 0 for line in f.readlines()[::-1]: result = line.find("bestblockhash") if result != -1: f.close() split_list = line.split(",") for i in range(0,len(split_list)): result = split_list[i].find("blocks") if result != -1: block_count = int(split_list[i].split(":")[1]) break if block_count != 0: f.close() break if block_count > 0: print("Success InitalCoin test ...") sys.exit(0) else: print("Fail InitalCoin test ...") sys.exit(1) # -------------------------------------------------------------------------------------------------------------- # Regression test-11 - peer connection test # -------------------------------------------------------------------------------------------------------------- # bitcoin 기준으로 테스트를 한다고 할 경우, xml에 "addnode" 플래그 값으로 connection할 peer를 설정을 해주고, 설정해준 ip주소와 # "getpeerinfo"를 통해 시뮬레이션 상에서 connection된 peer ip와 일치하는지 확인하는 테스트. def test_peer_connection(plugin_output_files, IP_list, xml_file): addnode_list = utils.get_addnode_list(IP_list, xml_file) getpeerinfo_list = utils.get_peerinfo(plugin_output_files, IP_list) result_count = 0 con_count = 0 for i in range(0,len(addnode_list)): for j in range(0,len(addnode_list[i])): if addnode_list[i][j] in getpeerinfo_list[i]: con_count += 1 if len(addnode_list[i]) == con_count: result_count += 1 con_count = 0 if result_count == len(addnode_list): print("Success peer connection test ...") sys.exit(0) else: print("fail peer connection test ...") sys.exit(1) # -------------------------------------------------------------------------------------------------------------- # Regression test-12 - load data file test # -------------------------------------------------------------------------------------------------------------- # 1. 플러그인 로그에서 "Reindexing finished" 로그가 없으면 test 실패 # 2. coinlip_hash.txt 파일에서 블록 hash 값들을 읽어서, 플러그인의 로그에서 1~7번의 블록 hash 값과 비교 def test_dumpfile_load(plugin_output_files, abs_path, difficulty): print("dump test start ... ") condition_count = 0 the_path = "" ready_hash_list = [] f = open(plugin_output_files, "r") while True: line = f.readline() if not line: break result = line.find("Reindexing finished") if result != -1: condition_count = 1 f.close() break # check pork event_value = 0 if condition_count == 1: f = open(plugin_output_files, "r") while True: line = f.readline() if not line: break result = line.find("Disconnect block") if result != -1: event_value = 1 continue if event_value == 1: result = line.find("height=6") if result != -1: print("Fail dump file load ... ") print("There are problems about initial block hashes ... ") f.close() sys.exit(1) condition_count = 2 f.close() if condition_count == 2: the_path = utils.get_datadirDumpfile_path(abs_path, difficulty) the_path = the_path + "/coinflip_hash.txt" f = open(the_path, "r") while True: line = f.readline() if not line: break ready_hash_list.append(line.strip()) f.close() i = 0 result_hash_list = [] f = open(plugin_output_files, "r") while True: line = f.readline() if not line:break result = line.find("UpdateTip") if result != -1: if ready_hash_list[i] == line.split(" ")[3].split("=")[1]: i += 1 pass # 0번째는 제네시스 블록이라 스킵. elif i == 0: continue else: print("Fail test dump file load ... ") f.close() sys.exit(1) if i == 7: print("Success test dump file load test ... ") f.close() break else: print("Fail load data file test ... (Not Reindexing finished)") f.close() sys.exit(1) # -------------------------------------------------------------------------------------------------------------- # Regression test-13 - monitor node connection test # -------------------------------------------------------------------------------------------------------------- # 이 테스트를 통해 실행될 플러그인 중에 monitor node 플러그인에 대한 테스트임. # monitor 노드는 시뮬레이션되는 블록체인의 모든 노드의 블록 전파를 관장함. # 현재 테스트에서는 시뮬레이션되는 블록체인의 노드와 monitor node와의 conncetion test임. def monitor_connection_test(plugin_output_files, abs_path, node_count): condition_count = 0 # 실행되는 node 수 + node_count = int(node_count) + 1 for i in range(0,len(plugin_output_files)): result = plugin_output_files[i].find("monitor") if result != -1: f = open(plugin_output_files[i], "r") while True: line = f.readline() if not line: break result = line.find("Socket is successfully connected") if result != -1: condition_count += 1 if condition_count == node_count: f.close() break f.close() if condition_count == node_count: print("Success monitor connection test ... ") sys.exit(0) print("Fail monitor conncetion test ... ") print("only %d node connection ... " %condition_count) sys.exit(1) # -------------------------------------------------------------------------------------------------------------- # Regression test-14 monitor node block propagation test # -------------------------------------------------------------------------------------------------------------- # Monitor 노드는 비트코인 노드로 부터 블록을 전파받음. 이렇게 전파 받은 블록의 해시 값들과, # 비트코인 실행 결과 로그 값에 기록된 블록 해시 값들을 비교하여, Monitor 노드가 제대로 전파를 받았나 확인을 하는 테스트 def Mointor_block_propagation_test(plugin_output_files, node_count, target_path): each_node_block_list = utils.filter_block_hash(plugin_output_files, node_count) monitor_result_path = target_path + "/shadow.data/monitor_result.txt" f = open(monitor_result_path, "w") for i in range(len(each_node_block_list)): f.write("\t\t ---------- %d node monitor result ---------- \n\n" %i) for j in range(len(each_node_block_list[i])): f.write("Num %d block - %s\n" %(j, each_node_block_list[i][j])) f.write("\n") f.close() node_blocklist = [] for i in range(node_count): line = [] node_blocklist.append(line) for i in range(0,len(plugin_output_files)): result = plugin_output_files[i].find("stdout-bcdnode") if result != -1: node_blocklist[i] = test_result.filter_overlap_height(plugin_output_files[i]) for i in range(0,len(node_blocklist)): for j in range(0,len(node_blocklist[i])-1): # 모니터 노드에는 제네시스 블록이 등록이 안되어 있기에, (전파된 블록만 컨트롤) if node_blocklist[i][j+1][0] in each_node_block_list[i]: pass else: print("Fail Monitor block propagation test ... ") print("There is no block (%s) " %node_blocklist[i][j+1][0]) sys.exit(1) print("Success Monitor block propagation test ... ") sys.exit(0) # -------------------------------------------------------------------------------------------------------------- # Regression test-15 - TxGenerator connection test # -------------------------------------------------------------------------------------------------------------- # TxGenerator 가 node connection 과정에서 xml파일로부터 정의된 노드의 IP 주소를 기준으로 필터링 시작. def TxGenerator_connection_test(plugin_output_files, xmlfile, node_count): IP_list = utils.get_address_list(xmlfile) condition_count = 0 for i in range(0,len(plugin_output_files)): result = plugin_output_files[i].find("txgenerator/stdout-txgenerator.BITCOINTPS_TESTER.1000.log") if result != -1: f = open(plugin_output_files[i], "r") while True: line = f.readline() if not line: break result = line.find("addTarget") if result != -1: for i in range(0,len(IP_list)): result = line.find(IP_list[i]) if result != -1: condition_count += 1 if condition_count == 2: f.close() print("Success txGenrator connection test ...") sys.exit(0) else: break f.close() print(condition_count) print("Fail txGenerator connection test ... ") sys.exit(1)
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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. //========================================================================= #ifndef __ELASTOS_UTILITY_TIMER_H__ #define __ELASTOS_UTILITY_TIMER_H__ #include "Elastos.CoreLibrary.Utility.h" #include "Thread.h" using Elastos::Core::Thread; using Elastos::Core::IClassLoader; using Elastos::Core::IRunnable; using Elastos::Core::IThread; namespace Elastos { namespace Utility { class Timer : public Object , public ITimer { private: class TimerImpl : public Thread { friend class Timer; private: class TimerHeap : public ElRefBase { friend class Timer; public: TimerHeap(); ~TimerHeap(); CARAPI_(AutoPtr<ITimerTask>) Minimum(); CARAPI_(Boolean) IsEmpty(); CARAPI_(void) Insert( /* [in] */ ITimerTask* task); CARAPI_(void) Delete( /* [in] */ Int32 pos); CARAPI_(void) Reset(); CARAPI_(void) AdjustMinimum(); CARAPI_(void) DeleteIfCancelled(); private: CARAPI_(void) UpHeap(); CARAPI_(void) DownHeap( /* [in] */ Int32 pos); CARAPI_(Int32) GetTask( /* [in] */ ITimerTask* task); private: Int32 DEFAULT_HEAP_SIZE; AutoPtr< ArrayOf<ITimerTask*> > mTimers; Int32 mSize; Int32 mDeletedCancelledNumber; }; public: TimerImpl( /* [in] */ const String& name, /* [in] */ Boolean isDaemon); ~TimerImpl(); CARAPI Run(); CARAPI_(void) Cancel(); CARAPI_(Int32) Purge(); private: CARAPI_(void) InsertTask( /* [in] */ ITimerTask* newTask); public: /** * True if the method cancel() of the Timer was called or the !!!stop() * method was invoked */ Boolean mCancelled; /** * True if the Timer has become garbage */ Boolean mFinished; /** * Contains scheduled events, sorted according to * {@code when} field of TaskScheduled object. */ AutoPtr<TimerHeap> mTasks; }; class FinalizerHelper : public ElRefBase { public: FinalizerHelper( /* [in] */ TimerImpl* impl); ~FinalizerHelper(); private: AutoPtr<TimerImpl> mImpl; }; public: CAR_INTERFACE_DECL() /** * Creates a new named {@code Timer} which may be specified to be run as a * daemon thread. * * @param name the name of the {@code Timer}. * @param isDaemon true if {@code Timer}'s thread should be a daemon thread. * @throws NullPointerException is {@code name} is {@code null} */ Timer( /* [in] */ const String& name, /* [in] */ Boolean isDaemon); /** * Creates a new named {@code Timer} which does not run as a daemon thread. * * @param name the name of the Timer. * @throws NullPointerException is {@code name} is {@code null} */ Timer( /* [in] */ const String& name); /** * Creates a new {@code Timer} which may be specified to be run as a daemon thread. * * @param isDaemon {@code true} if the {@code Timer}'s thread should be a daemon thread. */ Timer( /* [in] */ Boolean isDaemon); /** * Creates a new non-daemon {@code Timer}. */ Timer(); virtual ~Timer(); /** * Cancels the {@code Timer} and all scheduled tasks. If there is a * currently running task it is not affected. No more tasks may be scheduled * on this {@code Timer}. Subsequent calls do nothing. */ CARAPI Cancel(); /** * Removes all canceled tasks from the task queue. If there are no * other references on the tasks, then after this call they are free * to be garbage collected. * * @return the number of canceled tasks that were removed from the task * queue. */ CARAPI Purge( /* [out] */ Int32* number); /** * Schedule a task for single execution. If {@code when} is less than the * current time, it will be scheduled to be executed as soon as possible. * * @param task * the task to schedule. * @param when * time of execution. * @throws IllegalArgumentException * if {@code when.getTime() < 0}. * @throws IllegalStateException * if the {@code Timer} has been canceled, or if the task has been * scheduled or canceled. */ CARAPI Schedule( /* [in] */ ITimerTask* task, /* [in] */ IDate* when); /** * Schedule a task for single execution after a specified delay. * * @param task * the task to schedule. * @param delay * amount of time in milliseconds before execution. * @throws IllegalArgumentException * if {@code delay < 0}. * @throws IllegalStateException * if the {@code Timer} has been canceled, or if the task has been * scheduled or canceled. */ CARAPI Schedule( /* [in] */ ITimerTask* task, /* [in] */ Int64 delay); /** * Schedule a task for repeated fixed-delay execution after a specific delay. * * @param task * the task to schedule. * @param delay * amount of time in milliseconds before first execution. * @param period * amount of time in milliseconds between subsequent executions. * @throws IllegalArgumentException * if {@code delay < 0} or {@code period < 0}. * @throws IllegalStateException * if the {@code Timer} has been canceled, or if the task has been * scheduled or canceled. */ CARAPI Schedule( /* [in] */ ITimerTask* task, /* [in] */ Int64 delay, /* [in] */ Int64 period); /** * Schedule a task for repeated fixed-delay execution after a specific time * has been reached. * * @param task * the task to schedule. * @param when * time of first execution. * @param period * amount of time in milliseconds between subsequent executions. * @throws IllegalArgumentException * if {@code when.getTime() < 0} or {@code period < 0}. * @throws IllegalStateException * if the {@code Timer} has been canceled, or if the task has been * scheduled or canceled. */ CARAPI Schedule( /* [in] */ ITimerTask* task, /* [in] */ IDate* when, /* [in] */ Int64 period); /** * Schedule a task for repeated fixed-rate execution after a specific delay * has passed. * * @param task * the task to schedule. * @param delay * amount of time in milliseconds before first execution. * @param period * amount of time in milliseconds between subsequent executions. * @throws IllegalArgumentException * if {@code delay < 0} or {@code period < 0}. * @throws IllegalStateException * if the {@code Timer} has been canceled, or if the task has been * scheduled or canceled. */ CARAPI ScheduleAtFixedRate( /* [in] */ ITimerTask* task, /* [in] */ Int64 delay, /* [in] */ Int64 period); /** * Schedule a task for repeated fixed-rate execution after a specific time * has been reached. * * @param task * the task to schedule. * @param when * time of first execution. * @param period * amount of time in milliseconds between subsequent executions. * @throws IllegalArgumentException * if {@code when.getTime() < 0} or {@code period < 0}. * @throws IllegalStateException * if the {@code Timer} has been canceled, or if the task has been * scheduled or canceled. */ CARAPI ScheduleAtFixedRate( /* [in] */ ITimerTask* task, /* [in] */ IDate* when, /* [in] */ Int64 period); public: /** * Creates a new named {@code Timer} which may be specified to be run as a * daemon thread. * * @param name the name of the {@code Timer}. * @param isDaemon true if {@code Timer}'s thread should be a daemon thread. * @throws NullPointerException is {@code name} is {@code null} */ CARAPI constructor( /* [in] */ const String& name, /* [in] */ Boolean isDaemon); CARAPI constructor( /* [in] */ const String& name); /** * Creates a new {@code Timer} which may be specified to be run as a daemon thread. * * @param isDaemon {@code true} if the {@code Timer}'s thread should be a daemon thread. */ CARAPI constructor( /* [in] */ Boolean isDaemon); /** * Creates a new non-daemon {@code Timer}. */ CARAPI constructor(); private: static CARAPI_(Int64) NextId(); /* * Schedule a task. */ CARAPI ScheduleImpl( /* [in] */ ITimerTask* task, /* [in] */ Int64 delay, /* [in] */ Int64 period, /* [in] */ Boolean fixed); private: static Int64 sTimerId; static Object sTimerIdLock; /* This object will be used in synchronization purposes */ AutoPtr<TimerImpl> mImpl; // Used to finalize thread AutoPtr<FinalizerHelper> mFinalizer; }; } // namespace Utility } // namespace Elastos #endif //__ELASTOS_UTILITY_TIMER_H__
# Copyright 2022 The Flax Authors. # # 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. """ImageNet example. This script trains a ResNet-50 on the ImageNet dataset. The data is loaded using tensorflow_datasets. """ import functools import time from typing import Any import alpa from absl import logging from clu import metric_writers from clu import periodic_actions import flax from flax import jax_utils from flax import optim from flax.training import checkpoints from flax.training import common_utils from flax.training import train_state import jax from jax import lax import jax.numpy as jnp from jax import random import ml_collections import optax import ray import tensorflow as tf import tensorflow_datasets as tfds import input_pipeline import models NUM_CLASSES = 1000 def create_model(*, model_cls, half_precision, **kwargs): platform = jax.local_devices()[0].platform if half_precision: if platform == 'tpu': model_dtype = jnp.bfloat16 else: model_dtype = jnp.float16 else: model_dtype = jnp.float32 return model_cls(num_classes=NUM_CLASSES, dtype=model_dtype, **kwargs) def initialized(key, image_size, model): input_shape = (1, image_size, image_size, 3) @jax.jit def init(*args): return model.init(*args) variables = init({'params': key}, jnp.ones(input_shape, model.dtype)) return variables['params'], variables['batch_stats'] def cross_entropy_loss(logits, labels): one_hot_labels = common_utils.onehot(labels, num_classes=NUM_CLASSES) xentropy = optax.softmax_cross_entropy(logits=logits, labels=one_hot_labels) return jnp.mean(xentropy) def compute_metrics(logits, labels): loss = cross_entropy_loss(logits, labels) accuracy = jnp.mean(jnp.argmax(logits, -1) == labels) metrics = { 'loss': loss, 'accuracy': accuracy, } return metrics def create_learning_rate_fn( config: ml_collections.ConfigDict, base_learning_rate: float, steps_per_epoch: int): """Create learning rate schedule.""" warmup_fn = optax.linear_schedule( init_value=0., end_value=base_learning_rate, transition_steps=config.warmup_epochs * steps_per_epoch) cosine_epochs = max(config.num_epochs - config.warmup_epochs, 1) cosine_fn = optax.cosine_decay_schedule( init_value=base_learning_rate, decay_steps=cosine_epochs * steps_per_epoch) schedule_fn = optax.join_schedules( schedules=[warmup_fn, cosine_fn], boundaries=[config.warmup_epochs * steps_per_epoch]) return schedule_fn def train_step(state, batch, learning_rate_fn): """Perform a single training step.""" def loss_fn(params): """loss function used for training.""" logits, new_model_state = state.apply_fn( {'params': params, 'batch_stats': state.batch_stats}, batch['image'], mutable=['batch_stats']) loss = cross_entropy_loss(logits, batch['label']) weight_penalty_params = jax.tree_leaves(params) weight_decay = 0.0001 weight_l2 = sum([jnp.sum(x ** 2) for x in weight_penalty_params if x.ndim > 1]) weight_penalty = weight_decay * 0.5 * weight_l2 loss = loss + weight_penalty return loss, (new_model_state, logits) step = state.step dynamic_scale = state.dynamic_scale lr = learning_rate_fn(step) if dynamic_scale: grad_fn = dynamic_scale.value_and_grad( loss_fn, has_aux=True) dynamic_scale, is_fin, aux, grads = grad_fn(state.params) # dynamic loss takes care of averaging gradients across replicas else: grad_fn = jax.value_and_grad(loss_fn, has_aux=True) aux, grads = grad_fn(state.params) new_model_state, logits = aux[1] metrics = compute_metrics(logits, batch['label']) metrics['learning_rate'] = lr new_state = state.apply_gradients( grads=grads, batch_stats=new_model_state['batch_stats']) if dynamic_scale: # if is_fin == False the gradients contain Inf/NaNs and optimizer state and # params should be restored (= skip this step). new_state = new_state.replace( opt_state=jax.tree_multimap( functools.partial(jnp.where, is_fin), new_state.opt_state, state.opt_state), params=jax.tree_multimap( functools.partial(jnp.where, is_fin), new_state.params, state.params)) metrics['scale'] = dynamic_scale.scale return new_state, metrics def eval_step(state, batch): variables = {'params': state.params, 'batch_stats': state.batch_stats} logits = state.apply_fn( variables, batch['image'], train=False, mutable=False) return compute_metrics(logits, batch['label']) def create_input_iter(dataset_builder, batch_size, image_size, dtype, sharding_specs, physical_mesh, train, cache): ds = input_pipeline.create_split( dataset_builder, batch_size, image_size=image_size, dtype=dtype, train=train, cache=cache) it = map(lambda xs: jax.tree_map(lambda x: x._numpy(), xs), ds) it = alpa.DataLoader(it, sharding_specs, physical_mesh=physical_mesh, prefetch_size=4) return it class TrainState(train_state.TrainState): batch_stats: Any dynamic_scale: flax.optim.DynamicScale def restore_checkpoint(state, workdir): return checkpoints.restore_checkpoint(workdir, state) def save_checkpoint(state, workdir): if jax.process_index() == 0: # get train state from the first replica state = jax.device_get(jax.tree_map(lambda x: x[0], state)) step = int(state.step) checkpoints.save_checkpoint(workdir, state, step, keep=3) # pmean only works inside pmap because it needs an axis name. # This function will average the inputs across all devices. cross_replica_mean = jax.pmap(lambda x: lax.pmean(x, 'x'), 'x') def sync_batch_stats(state): """Sync the batch statistics across replicas.""" # Each device has its own version of the running average batch statistics and # we sync them before evaluation. return state.replace(batch_stats=cross_replica_mean(state.batch_stats)) def create_train_state(rng, config: ml_collections.ConfigDict, model, image_size, learning_rate_fn): """Create initial training state.""" dynamic_scale = None platform = jax.local_devices()[0].platform if config.half_precision and platform == 'gpu': dynamic_scale = optim.DynamicScale() else: dynamic_scale = None params, batch_stats = initialized(rng, image_size, model) tx = optax.sgd( learning_rate=learning_rate_fn, momentum=config.momentum, nesterov=True, ) state = TrainState.create( apply_fn=model.apply, params=params, tx=tx, batch_stats=batch_stats, dynamic_scale=dynamic_scale) return state def train_and_evaluate(config: ml_collections.ConfigDict, workdir: str) -> TrainState: """Execute model training and evaluation loop. Args: config: Hyperparameter configuration for training and evaluation. workdir: Directory where the tensorboard summaries are written to. Returns: Final TrainState. """ #ray.init(address="auto") #physical_mesh = alpa.DeviceCluster().get_physical_mesh() physical_mesh = alpa.LocalPhysicalDeviceMesh() alpa.set_parallelize_options(physical_mesh) writer = metric_writers.create_default_writer( logdir=workdir, just_logging=jax.process_index() != 0) rng = random.PRNGKey(0) image_size = 224 if config.batch_size % jax.device_count() > 0: raise ValueError('Batch size must be divisible by the number of devices') local_batch_size = config.batch_size // jax.process_count() platform = jax.local_devices()[0].platform if config.half_precision: if platform == 'tpu': input_dtype = tf.bfloat16 else: input_dtype = tf.float16 else: input_dtype = tf.float32 dataset_builder = tfds.builder(config.dataset) steps_per_epoch = ( dataset_builder.info.splits['train'].num_examples // config.batch_size ) if config.num_train_steps == -1: num_steps = int(steps_per_epoch * config.num_epochs) else: num_steps = config.num_train_steps if config.steps_per_eval == -1: num_validation_examples = dataset_builder.info.splits[ 'validation'].num_examples steps_per_eval = num_validation_examples // config.batch_size else: steps_per_eval = config.steps_per_eval steps_per_checkpoint = steps_per_epoch * 10 base_learning_rate = config.learning_rate * config.batch_size / 256. model_cls = getattr(models, config.model) model = create_model( model_cls=model_cls, half_precision=config.half_precision) learning_rate_fn = create_learning_rate_fn( config, base_learning_rate, steps_per_epoch) state = create_train_state(rng, config, model, image_size, learning_rate_fn) state = restore_checkpoint(state, workdir) # step_offset > 0 if restarting from checkpoint step_offset = int(state.step) p_train_step = alpa.parallelize( functools.partial(train_step, learning_rate_fn=learning_rate_fn)) p_eval_step = alpa.parallelize(eval_step) logging.info('Initial compilation, this might take some minutes...') batch = { "image": jax.core.ShapedArray( (config.batch_size, image_size, image_size, 3), jnp.float32), "label": jax.core.ShapedArray((config.batch_size,), jnp.int32), } executable = p_train_step.get_executable(state, batch) logging.info('Initial compilation completed.') sharding_specs = executable.input_sharding_specs[-2:] train_iter = create_input_iter( dataset_builder, local_batch_size, image_size, input_dtype, sharding_specs, physical_mesh, train=True, cache=config.cache) eval_iter = create_input_iter( dataset_builder, local_batch_size, image_size, input_dtype, sharding_specs, physical_mesh, train=False, cache=config.cache) train_metrics = [] hooks = [] #if jax.process_index() == 0: # hooks += [periodic_actions.Profile(num_profile_steps=5, logdir=workdir)] train_metrics_last_t = time.time() for step, batch in zip(range(step_offset, num_steps), train_iter): state, metrics = p_train_step(state, batch) for h in hooks: h(step) if config.get('log_every_steps'): train_metrics.append(metrics) if (step + 1) % config.log_every_steps == 0: train_metrics = common_utils.stack_forest(train_metrics) summary = { f'train_{k}': v for k, v in jax.tree_map(lambda x: x.mean(), train_metrics).items() } summary['ips'] = config.batch_size * config.log_every_steps / ( time.time() - train_metrics_last_t) writer.write_scalars(step + 1, summary) train_metrics = [] train_metrics_last_t = time.time() # Currently, evaluation and model saving are not optimized in alpa # TODO: support the logic below continue if (step + 1) % steps_per_epoch == 0: epoch = step // steps_per_epoch eval_metrics = [] # sync batch statistics across replicas state = sync_batch_stats(state) for _ in range(steps_per_eval): eval_batch = next(eval_iter) metrics = p_eval_step(state, eval_batch) eval_metrics.append(metrics) eval_metrics = common_utils.get_metrics(eval_metrics) summary = jax.tree_map(lambda x: x.mean(), eval_metrics) logging.info('eval epoch: %d, loss: %.4f, accuracy: %.2f', epoch, summary['loss'], summary['accuracy'] * 100) writer.write_scalars( step + 1, {f'eval_{key}': val for key, val in summary.items()}) writer.flush() if (step + 1) % steps_per_checkpoint == 0 or step + 1 == num_steps: state = sync_batch_stats(state) save_checkpoint(state, workdir) # Wait until computations are done before exiting jax.random.normal(jax.random.PRNGKey(0), ()).block_until_ready() return state
# Copyright 2020-2022 Cambridge Quantum Computing # # 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. """Backends for processing pytket circuits with the Microsoft QDK """ from .simulator import QsharpSimulatorBackend from .estimator import QsharpEstimatorBackend from .toffoli import QsharpToffoliSimulatorBackend from .azure_quantum import AzureBackend
from datetime import datetime from lxml import etree import re import iso8601 import pytz import xml2json from corehq.apps.tzmigration.api import phone_timezones_should_be_processed from corehq.form_processor.interfaces.processor import XFormQuestionValueIterator from corehq.form_processor.models import Attachment from corehq.form_processor.exceptions import XFormQuestionValueNotFound from dimagi.ext import jsonobject from dimagi.utils.parsing import json_format_datetime # The functionality below to create a simple wrapped XForm is used in production code (repeaters) and so is # not in the test utils SIMPLE_FORM = """<?xml version='1.0' ?> <data uiVersion="1" version="17" name="{form_name}" xmlns:jrm="http://dev.commcarehq.org/jr/xforms" xmlns="{xmlns}"> {form_properties} <n1:meta xmlns:n1="http://openrosa.org/jr/xforms"> <n1:deviceID>{device_id}</n1:deviceID> <n1:timeStart>{time_start}</n1:timeStart> <n1:timeEnd>{time_end}</n1:timeEnd> <n1:username>{username}</n1:username> <n1:userID>{user_id}</n1:userID> <n1:instanceID>{uuid}</n1:instanceID> <n2:appVersion xmlns:n2="http://commcarehq.org/xforms"></n2:appVersion> </n1:meta> {case_block} </data>""" # this is like jsonobject.api.re_datetime, # but without the "time" parts being optional # i.e. I just removed (...)? surrounding the second two lines # This is used to in our form processor so we detect what strings are datetimes. RE_DATETIME_MATCH = re.compile(r""" ^ (\d{4}) # year \D? (0[1-9]|1[0-2]) # month \D? ([12]\d|0[1-9]|3[01]) # day [ T] ([01]\d|2[0-3]) # hour \D? ([0-5]\d) # minute \D? ([0-5]\d)? # second \D? (\d{3,6})? # millisecond ([zZ]|([\+-])([01]\d|2[0-3])\D?([0-5]\d)?)? # timezone $ """, re.VERBOSE) class TestFormMetadata(jsonobject.JsonObject): domain = jsonobject.StringProperty(required=False) xmlns = jsonobject.StringProperty(default='http://openrosa.org/formdesigner/form-processor') app_id = jsonobject.StringProperty(default='123') form_name = jsonobject.StringProperty(default='New Form') device_id = jsonobject.StringProperty(default='DEV IL') user_id = jsonobject.StringProperty(default='cruella_deville') username = jsonobject.StringProperty(default='eve') time_end = jsonobject.DateTimeProperty(default=datetime(2013, 4, 19, 16, 52, 2)) time_start = jsonobject.DateTimeProperty(default=datetime(2013, 4, 19, 16, 53, 2)) # Set this property to fake the submission time received_on = jsonobject.DateTimeProperty(default=datetime.utcnow) class FormSubmissionBuilder(object): """ Utility/helper object for building a form submission """ def __init__(self, form_id, metadata=None, case_blocks=None, form_properties=None, form_template=SIMPLE_FORM): self.form_id = form_id self.metadata = metadata or TestFormMetadata() self.case_blocks = case_blocks or [] self.form_template = form_template self.form_properties = form_properties or {} def as_xml_string(self): case_block_xml = ''.join(cb.as_text() for cb in self.case_blocks) form_properties_xml = build_form_xml_from_property_dict(self.form_properties) form_xml = self.form_template.format( uuid=self.form_id, form_properties=form_properties_xml, case_block=case_block_xml, **self.metadata.to_json() ) if not self.metadata.user_id: form_xml = form_xml.replace('<n1:userID>{}</n1:userID>'.format(self.metadata.user_id), '') return form_xml def _build_node_list_from_dict(form_properties, separator=''): elements = [] for key, values in form_properties.items(): if not isinstance(values, list): values = [values] for value in values: node = etree.Element(key) if isinstance(value, dict): children = _build_node_list_from_dict(value, separator=separator) for child in children: node.append(child) else: node.text = value elements.append(node) return elements def build_form_xml_from_property_dict(form_properties, separator=''): return separator.join( etree.tostring(e).decode('utf-8') for e in _build_node_list_from_dict(form_properties, separator) ) def get_simple_form_xml(form_id, case_id=None, metadata=None, simple_form=SIMPLE_FORM): from casexml.apps.case.mock import CaseBlock case_blocks = [CaseBlock.deprecated_init(create=True, case_id=case_id)] if case_id else [] return FormSubmissionBuilder( form_id=form_id, metadata=metadata, case_blocks=case_blocks, form_template=simple_form, ).as_xml_string() def get_simple_wrapped_form(form_id, metadata=None, save=True, simple_form=SIMPLE_FORM): from corehq.form_processor.interfaces.processor import FormProcessorInterface from corehq.form_processor.interfaces.dbaccessors import FormAccessors metadata = metadata or TestFormMetadata() xml = get_simple_form_xml(form_id=form_id, metadata=metadata, simple_form=simple_form) form_json = convert_xform_to_json(xml) interface = FormProcessorInterface(domain=metadata.domain) wrapped_form = interface.new_xform(form_json) wrapped_form.domain = metadata.domain wrapped_form.received_on = metadata.received_on interface.store_attachments(wrapped_form, [Attachment('form.xml', xml, 'text/xml')]) if save: interface.save_processed_models([wrapped_form]) wrapped_form = FormAccessors(metadata.domain).get_form(wrapped_form.form_id) return wrapped_form def extract_meta_instance_id(form): """Takes form json (as returned by xml2json)""" if form.get('Meta'): # bhoma, 0.9 commcare meta = form['Meta'] elif form.get('meta'): # commcare 1.0 meta = form['meta'] else: return None if meta.get('uid'): # bhoma return meta['uid'] elif meta.get('instanceID'): # commcare 0.9, commcare 1.0 return meta['instanceID'] else: return None def extract_meta_user_id(form): user_id = None if form.get('meta'): user_id = form.get('meta').get('userID', None) elif form.get('Meta'): user_id = form.get('Meta').get('user_id', None) return user_id def convert_xform_to_json(xml_string): """ takes xform payload as xml_string and returns the equivalent json i.e. the json that will show up as xform.form """ try: name, json_form = xml2json.xml2json(xml_string) except xml2json.XMLSyntaxError as e: from couchforms import XMLSyntaxError raise XMLSyntaxError('Invalid XML: %s' % e) json_form['#type'] = name return json_form def adjust_text_to_datetime(text, process_timezones=None): matching_datetime = iso8601.parse_date(text) if process_timezones or phone_timezones_should_be_processed(): return matching_datetime.astimezone(pytz.utc).replace(tzinfo=None) else: return matching_datetime.replace(tzinfo=None) def adjust_datetimes(data, parent=None, key=None, process_timezones=None): """ find all datetime-like strings within data (deserialized json) and format them uniformly, in place. this only processes timezones correctly if the call comes from a request with domain information otherwise it will default to not processing timezones. to force timezone processing, it can be called as follows >>> from corehq.apps.tzmigration.api import force_phone_timezones_should_be_processed >>> with force_phone_timezones_should_be_processed(): >>> adjust_datetimes(form_json) """ process_timezones = process_timezones or phone_timezones_should_be_processed() # this strips the timezone like we've always done # todo: in the future this will convert to UTC if isinstance(data, str) and RE_DATETIME_MATCH.match(data): try: parent[key] = str(json_format_datetime( adjust_text_to_datetime(data, process_timezones=process_timezones) )) except (iso8601.ParseError, ValueError): pass elif isinstance(data, dict): for key, value in data.items(): adjust_datetimes(value, parent=data, key=key, process_timezones=process_timezones) elif isinstance(data, list): for i, value in enumerate(data): adjust_datetimes(value, parent=data, key=i, process_timezones=process_timezones) # return data, just for convenience in testing # this is the original input, modified, not a new data structure return data def resave_form(domain, form): from corehq.form_processor.utils import should_use_sql_backend from corehq.form_processor.change_publishers import publish_form_saved from couchforms.models import XFormInstance if should_use_sql_backend(domain): publish_form_saved(form) else: XFormInstance.get_db().save_doc(form.to_json()) def get_node(root, question, xmlns=''): ''' Given an xml element, find the node corresponding to a question path. See XFormQuestionValueIterator for question path format. Throws XFormQuestionValueNotFound if question is not present. ''' def _next_node(node, xmlns, id, index=None): try: return node.findall("{{{}}}{}".format(xmlns, id))[index or 0] except (IndexError, KeyError): raise XFormQuestionValueNotFound() node = root i = XFormQuestionValueIterator(question) for (qid, index) in i: node = _next_node(node, xmlns, qid, index) node = _next_node(node, xmlns, i.last()) if node is None: raise XFormQuestionValueNotFound() return node def update_response(root, question, response, xmlns=None): ''' Given a form submission's xml root, updates the response for an individual question. Question and response are both strings; see XFormQuestionValueIterator for question format. ''' node = get_node(root, question, xmlns) if node.text != response: node.text = response return True return False
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports.tip = tip; exports.Tooltip = void 0; var _react = _interopRequireWildcard(require("react")); var _reactDom = _interopRequireDefault(require("react-dom")); var _propTypes = _interopRequireDefault(require("prop-types")); var _ClassNames = require("../utils/ClassNames"); var _DomHandler = _interopRequireDefault(require("../utils/DomHandler")); var _ConnectedOverlayScrollHandler = _interopRequireDefault(require("../utils/ConnectedOverlayScrollHandler")); var _Portal = require("../portal/Portal"); var _ZIndexUtils = require("../utils/ZIndexUtils"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function tip(props) { var appendTo = props.appendTo || document.body; var tooltipWrapper = document.createDocumentFragment(); _DomHandler.default.appendChild(tooltipWrapper, appendTo); props = _objectSpread(_objectSpread({}, props), props.options); var tooltipEl = /*#__PURE__*/_react.default.createElement(Tooltip, props); _reactDom.default.render(tooltipEl, tooltipWrapper); var updateTooltip = function updateTooltip(newProps) { props = _objectSpread(_objectSpread({}, props), newProps); _reactDom.default.render( /*#__PURE__*/_react.default.cloneElement(tooltipEl, props), tooltipWrapper); }; return { destroy: function destroy() { _reactDom.default.unmountComponentAtNode(tooltipWrapper); }, updateContent: function updateContent(newContent) { console.warn("The 'updateContent' method has been deprecated on Tooltip. Use update(newProps) method."); updateTooltip({ content: newContent }); }, update: function update(newProps) { updateTooltip(newProps); } }; } var Tooltip = /*#__PURE__*/function (_Component) { _inherits(Tooltip, _Component); var _super = _createSuper(Tooltip); function Tooltip(props) { var _this; _classCallCheck(this, Tooltip); _this = _super.call(this, props); _this.state = { visible: false, position: _this.props.position }; _this.show = _this.show.bind(_assertThisInitialized(_this)); _this.hide = _this.hide.bind(_assertThisInitialized(_this)); _this.onMouseEnter = _this.onMouseEnter.bind(_assertThisInitialized(_this)); _this.onMouseLeave = _this.onMouseLeave.bind(_assertThisInitialized(_this)); return _this; } _createClass(Tooltip, [{ key: "isTargetContentEmpty", value: function isTargetContentEmpty(target) { return !(this.props.content || this.getTargetOption(target, 'tooltip')); } }, { key: "isContentEmpty", value: function isContentEmpty(target) { return !(this.props.content || this.getTargetOption(target, 'tooltip') || this.props.children); } }, { key: "isMouseTrack", value: function isMouseTrack(target) { return this.getTargetOption(target, 'mousetrack') || this.props.mouseTrack; } }, { key: "isDisabled", value: function isDisabled(target) { return this.getTargetOption(target, 'disabled') === 'true' || this.hasTargetOption(target, 'disabled') || this.props.disabled; } }, { key: "isAutoHide", value: function isAutoHide() { return this.getTargetOption(this.currentTarget, 'autohide') || this.props.autoHide; } }, { key: "getTargetOption", value: function getTargetOption(target, option) { if (this.hasTargetOption(target, "data-pr-".concat(option))) { return target.getAttribute("data-pr-".concat(option)); } return null; } }, { key: "hasTargetOption", value: function hasTargetOption(target, option) { return target && target.hasAttribute(option); } }, { key: "getEvents", value: function getEvents(target) { var showEvent = this.getTargetOption(target, 'showevent') || this.props.showEvent; var hideEvent = this.getTargetOption(target, 'hideevent') || this.props.hideEvent; if (this.isMouseTrack(target)) { showEvent = 'mousemove'; hideEvent = 'mouseleave'; } else { var event = this.getTargetOption(target, 'event') || this.props.event; if (event === 'focus') { showEvent = 'focus'; hideEvent = 'blur'; } } return { showEvent: showEvent, hideEvent: hideEvent }; } }, { key: "getPosition", value: function getPosition(target) { return this.getTargetOption(target, 'position') || this.state.position; } }, { key: "getMouseTrackPosition", value: function getMouseTrackPosition(target) { var top = this.getTargetOption(target, 'mousetracktop') || this.props.mouseTrackTop; var left = this.getTargetOption(target, 'mousetrackleft') || this.props.mouseTrackLeft; return { top: top, left: left }; } }, { key: "updateText", value: function updateText(target, callback) { if (this.tooltipTextEl) { var content = this.getTargetOption(target, 'tooltip') || this.props.content; if (content) { this.tooltipTextEl.innerHTML = ''; // remove children this.tooltipTextEl.appendChild(document.createTextNode(content)); callback(); } else if (this.props.children) { callback(); } } } }, { key: "show", value: function show(e) { var _this2 = this; this.currentTarget = e.currentTarget; if (this.isContentEmpty(this.currentTarget) || this.isDisabled(this.currentTarget)) { return; } var updateTooltipState = function updateTooltipState() { _this2.updateText(_this2.currentTarget, function () { if (_this2.props.autoZIndex && !_ZIndexUtils.ZIndexUtils.get(_this2.containerEl)) { _ZIndexUtils.ZIndexUtils.set('tooltip', _this2.containerEl, _this2.props.baseZIndex); } _this2.containerEl.style.left = ''; _this2.containerEl.style.top = ''; _this2.align(_this2.currentTarget, { x: e.pageX, y: e.pageY }); }); }; if (this.state.visible) { this.applyDelay('updateDelay', updateTooltipState); } else { this.sendCallback(this.props.onBeforeShow, { originalEvent: e, target: this.currentTarget }); this.applyDelay('showDelay', function () { _this2.setState({ visible: true, position: _this2.getPosition(_this2.currentTarget) }, function () { updateTooltipState(); _this2.sendCallback(_this2.props.onShow, { originalEvent: e, target: _this2.currentTarget }); }); _this2.bindDocumentResizeListener(); _this2.bindScrollListener(); _DomHandler.default.addClass(_this2.currentTarget, _this2.getTargetOption(_this2.currentTarget, 'classname')); }); } } }, { key: "hide", value: function hide(e) { var _this3 = this; this.clearTimeouts(); if (this.state.visible) { _DomHandler.default.removeClass(this.currentTarget, this.getTargetOption(this.currentTarget, 'classname')); this.sendCallback(this.props.onBeforeHide, { originalEvent: e, target: this.currentTarget }); this.applyDelay('hideDelay', function () { _ZIndexUtils.ZIndexUtils.clear(_this3.containerEl); _DomHandler.default.removeClass(_this3.containerEl, 'p-tooltip-active'); if (!_this3.isAutoHide() && _this3.allowHide === false) { return; } _this3.setState({ visible: false, position: _this3.props.position }, function () { if (_this3.tooltipTextEl) { _reactDom.default.unmountComponentAtNode(_this3.tooltipTextEl); } _this3.unbindDocumentResizeListener(); _this3.unbindScrollListener(); _this3.currentTarget = null; _this3.scrollHandler = null; _this3.allowHide = true; _this3.sendCallback(_this3.props.onHide, { originalEvent: e, target: _this3.currentTarget }); }); }); } } }, { key: "align", value: function align(target, coordinate) { var _this4 = this; var left = 0, top = 0; if (this.isMouseTrack(target) && coordinate) { var container = { width: _DomHandler.default.getOuterWidth(this.containerEl), height: _DomHandler.default.getOuterHeight(this.containerEl) }; left = coordinate.x; top = coordinate.y; var _this$getMouseTrackPo = this.getMouseTrackPosition(target), mouseTrackTop = _this$getMouseTrackPo.top, mouseTrackLeft = _this$getMouseTrackPo.left; switch (this.state.position) { case 'left': left -= container.width + mouseTrackLeft; top -= container.height / 2 - mouseTrackTop; break; case 'right': left += mouseTrackLeft; top -= container.height / 2 - mouseTrackTop; break; case 'top': left -= container.width / 2 - mouseTrackLeft; top -= container.height + mouseTrackTop; break; case 'bottom': left -= container.width / 2 - mouseTrackLeft; top += mouseTrackTop; break; default: break; } this.containerEl.style.left = left + 'px'; this.containerEl.style.top = top + 'px'; _DomHandler.default.addClass(this.containerEl, 'p-tooltip-active'); } else { var pos = _DomHandler.default.findCollisionPosition(this.state.position); var my = this.getTargetOption(target, 'my') || this.props.my || pos.my; var at = this.getTargetOption(target, 'at') || this.props.at || pos.at; _DomHandler.default.flipfitCollision(this.containerEl, target, my, at, function (currentPosition) { var _currentPosition$at = currentPosition.at, x = _currentPosition$at.x, y = _currentPosition$at.y; var position = _this4.props.at ? x !== 'center' ? x : y : currentPosition.at["".concat(pos.axis)]; _this4.setState({ position: position }, function () { return _DomHandler.default.addClass(_this4.containerEl, 'p-tooltip-active'); }); }); } } }, { key: "onMouseEnter", value: function onMouseEnter() { if (!this.isAutoHide()) { this.allowHide = false; } } }, { key: "onMouseLeave", value: function onMouseLeave(e) { if (!this.isAutoHide()) { this.allowHide = true; this.hide(e); } } }, { key: "bindDocumentResizeListener", value: function bindDocumentResizeListener() { var _this5 = this; this.documentResizeListener = function (e) { _this5.hide(e); }; window.addEventListener('resize', this.documentResizeListener); } }, { key: "unbindDocumentResizeListener", value: function unbindDocumentResizeListener() { if (this.documentResizeListener) { window.removeEventListener('resize', this.documentResizeListener); this.documentResizeListener = null; } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this6 = this; if (!this.scrollHandler) { this.scrollHandler = new _ConnectedOverlayScrollHandler.default(this.currentTarget, function (e) { if (_this6.state.visible) { _this6.hide(e); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "bindTargetEvent", value: function bindTargetEvent(target) { if (target) { var _this$getEvents = this.getEvents(target), showEvent = _this$getEvents.showEvent, hideEvent = _this$getEvents.hideEvent; target.addEventListener(showEvent, this.show); target.addEventListener(hideEvent, this.hide); } } }, { key: "unbindTargetEvent", value: function unbindTargetEvent(target) { if (target) { var _this$getEvents2 = this.getEvents(target), showEvent = _this$getEvents2.showEvent, hideEvent = _this$getEvents2.hideEvent; target.removeEventListener(showEvent, this.show); target.removeEventListener(hideEvent, this.hide); } } }, { key: "applyDelay", value: function applyDelay(delayProp, callback) { this.clearTimeouts(); var delay = this.getTargetOption(this.currentTarget, delayProp.toLowerCase()) || this.props[delayProp]; if (!!delay) { this["".concat(delayProp, "Timeout")] = setTimeout(function () { return callback(); }, delay); } else { callback(); } } }, { key: "sendCallback", value: function sendCallback(callback) { if (callback) { for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } callback.apply(void 0, params); } } }, { key: "clearTimeouts", value: function clearTimeouts() { clearTimeout(this.showDelayTimeout); clearTimeout(this.updateDelayTimeout); clearTimeout(this.hideDelayTimeout); } }, { key: "updateTargetEvents", value: function updateTargetEvents(target) { this.unloadTargetEvents(target); this.loadTargetEvents(target); } }, { key: "loadTargetEvents", value: function loadTargetEvents(target) { this.setTargetEventOperations(target || this.props.target, 'bindTargetEvent'); } }, { key: "unloadTargetEvents", value: function unloadTargetEvents(target) { this.setTargetEventOperations(target || this.props.target, 'unbindTargetEvent'); } }, { key: "setTargetEventOperations", value: function setTargetEventOperations(target, operation) { var _this7 = this; if (target) { if (_DomHandler.default.isElement(target)) { this[operation](target); } else { var setEvent = function setEvent(target) { var element = _DomHandler.default.find(document, target); element.forEach(function (el) { _this7[operation](el); }); }; if (target instanceof Array) { target.forEach(function (t) { setEvent(t); }); } else { setEvent(target); } } } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.props.target) { this.loadTargetEvents(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { var _this8 = this; if (prevProps.target !== this.props.target) { this.unloadTargetEvents(prevProps.target); this.loadTargetEvents(); } if (this.state.visible) { if (prevProps.content !== this.props.content) { this.applyDelay('updateDelay', function () { _this8.updateText(_this8.currentTarget, function () { _this8.align(_this8.currentTarget); }); }); } if (this.currentTarget && this.isDisabled(this.currentTarget)) { this.hide(); } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.clearTimeouts(); this.unbindDocumentResizeListener(); this.unloadTargetEvents(); if (this.scrollHandler) { this.scrollHandler.destroy(); this.scrollHandler = null; } _ZIndexUtils.ZIndexUtils.clear(this.containerEl); } }, { key: "renderElement", value: function renderElement() { var _this9 = this; var tooltipClassName = (0, _ClassNames.classNames)('p-tooltip p-component', _defineProperty({}, "p-tooltip-".concat(this.state.position), true), this.props.className); var isTargetContentEmpty = this.isTargetContentEmpty(this.currentTarget); return /*#__PURE__*/_react.default.createElement("div", { id: this.props.id, ref: function ref(el) { return _this9.containerEl = el; }, className: tooltipClassName, style: this.props.style, role: "tooltip", "aria-hidden": this.state.visible, onMouseEnter: this.onMouseEnter, onMouseLeave: this.onMouseLeave }, /*#__PURE__*/_react.default.createElement("div", { className: "p-tooltip-arrow" }), /*#__PURE__*/_react.default.createElement("div", { ref: function ref(el) { return _this9.tooltipTextEl = el; }, className: "p-tooltip-text" }, isTargetContentEmpty && this.props.children)); } }, { key: "render", value: function render() { if (this.state.visible) { var element = this.renderElement(); return /*#__PURE__*/_react.default.createElement(_Portal.Portal, { element: element, appendTo: this.props.appendTo, visible: true }); } return null; } }]); return Tooltip; }(_react.Component); exports.Tooltip = Tooltip; _defineProperty(Tooltip, "defaultProps", { id: null, target: null, content: null, disabled: false, className: null, style: null, appendTo: null, position: 'right', my: null, at: null, event: null, showEvent: 'mouseenter', hideEvent: 'mouseleave', autoZIndex: true, baseZIndex: 0, mouseTrack: false, mouseTrackTop: 5, mouseTrackLeft: 5, showDelay: 0, updateDelay: 0, hideDelay: 0, autoHide: true, onBeforeShow: null, onBeforeHide: null, onShow: null, onHide: null }); _defineProperty(Tooltip, "propTypes", { id: _propTypes.default.string, target: _propTypes.default.oneOfType([_propTypes.default.object, _propTypes.default.string, _propTypes.default.array]), content: _propTypes.default.string, disabled: _propTypes.default.bool, className: _propTypes.default.string, style: _propTypes.default.object, appendTo: _propTypes.default.oneOfType([_propTypes.default.object, _propTypes.default.string]), position: _propTypes.default.string, my: _propTypes.default.string, at: _propTypes.default.string, event: _propTypes.default.string, showEvent: _propTypes.default.string, hideEvent: _propTypes.default.string, autoZIndex: _propTypes.default.bool, baseZIndex: _propTypes.default.number, mouseTrack: _propTypes.default.bool, mouseTrackTop: _propTypes.default.number, mouseTrackLeft: _propTypes.default.number, showDelay: _propTypes.default.number, updateDelay: _propTypes.default.number, hideDelay: _propTypes.default.number, autoHide: _propTypes.default.bool, onBeforeShow: _propTypes.default.func, onBeforeHide: _propTypes.default.func, onShow: _propTypes.default.func, onHide: _propTypes.default.func });
export const SHCOOLINTRODUCE = 1 export const LEADERCARE = 2
import React from "react"; import { getCommonContainer, getCommonHeader } from "egov-ui-framework/ui-config/screens/specs/utils"; import MyApplicationIcon from "../../../../ui-atoms-local/Icons/MyApplicationIcon"; import { getRequiredDocData } from "../utils"; import get from "lodash/get"; import set from "lodash/set"; import { getRequiredDocuments } from "./requiredDocuments/reqDocs"; import { pbkdf2 } from "crypto"; export const header = getCommonContainer({ header: getCommonHeader({ labelName: "EMAIL SMS COntent", //later use getFinancialYearDates labelKey: "EMAIL_SMS_CONTENT" }) }); const PRSCPSearchAndResult = { uiFramework: "material-ui", name: "EmailSmsContent", beforeInitScreen: (action, state, dispatch) => { getRequiredDocData(action, state, dispatch).then(() => { let documents = get( state, "screenConfiguration.preparedFinalObject.searchScreenMdmsData.PublicRelation.Documents", [] ); set( action, "screenConfig.components.adhocDialog.children.popup", getRequiredDocuments(documents) ); }); return action; }, components: { div: { uiFramework: "custom-atoms", componentPath: "Div", children: { header: header, richTextEditor: { uiFramework: "custom-molecules-local", moduleName: "egov-pr", componentPath: "RichTextEditor", props: {} } } } }, adhocDialog: { uiFramework: "custom-containers-local", moduleName: "egov-pr", componentPath: "DialogContainer", props: { open: false, maxWidth: false, screenKey: "home" }, children: { popup: {} } } }; export default PRSCPSearchAndResult;
(window.webpackJsonp=window.webpackJsonp||[]).push([[9],{400:function(t,s,a){t.exports=a.p+"assets/img/BrowserClient-instance.021e3251.png"},401:function(t,s,a){t.exports=a.p+"assets/img/Hub-instance-new.34d42e08.png"},402:function(t,s,a){t.exports=a.p+"assets/img/captureMessageCallStack.e64fe48b.png"},479:function(t,s,a){"use strict";a.r(s);var n=a(25),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,n=t._self._c||s;return n("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[n("h1",{attrs:{id:"no-5-学习-sentry-源码整体架构-打造属于自己的前端异常监控sdk"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#no-5-学习-sentry-源码整体架构-打造属于自己的前端异常监控sdk"}},[t._v("#")]),t._v(" No.5 学习 sentry 源码整体架构,打造属于自己的前端异常监控SDK")]),t._v(" "),n("h2",{attrs:{id:"_1-前言"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_1-前言"}},[t._v("#")]),t._v(" 1. 前言")]),t._v(" "),n("p",[t._v("源码类文章,一般阅读量不高。已经有能力看懂的,自己就看了。不想看,不敢看的就不会去看源码。"),n("br"),t._v("\n所以我的文章,尽量写得让想看源码又不知道怎么看的读者能看懂。")]),t._v(" "),n("p",[n("strong",[t._v("导读")]),n("br"),t._v("\n本文通过梳理前端错误监控知识、介绍"),n("code",[t._v("sentry")]),t._v("错误监控原理、"),n("code",[t._v("sentry")]),t._v("初始化、"),n("code",[t._v("Ajax")]),t._v("上报、"),n("code",[t._v("window.onerror、window.onunhandledrejection")]),t._v("几个方面来学习"),n("code",[t._v("sentry")]),t._v("的源码。")]),t._v(" "),n("p",[t._v("开发微信小程序,想着搭建小程序错误监控方案。最近用了丁香园 开源的"),n("code",[t._v("Sentry")]),t._v(" 小程序 "),n("code",[t._v("SDK")]),n("a",{attrs:{href:"https://github.com/lizhiyao/sentry-miniapp",target:"_blank",rel:"noopener noreferrer"}},[t._v("sentry-miniapp"),n("OutboundLink")],1),t._v("。\n顺便研究下"),n("a",{attrs:{href:"https://github.com/getsentry/sentry-javascript",target:"_blank",rel:"noopener noreferrer"}},[n("code",[t._v("sentry-javascript")]),t._v("仓库"),n("OutboundLink")],1),t._v(" 的源码整体架构,于是有了这篇文章。")]),t._v(" "),n("p",[t._v("本文分析的是打包后未压缩的源码,源码总行数五千余行,链接地址是:"),n("a",{attrs:{href:"https://browser.sentry-cdn.com/5.7.1/bundle.js",target:"_blank",rel:"noopener noreferrer"}},[t._v("https://browser.sentry-cdn.com/5.7.1/bundle.js"),n("OutboundLink")],1),t._v(", 版本是"),n("code",[t._v("v5.7.1")]),t._v("。")]),t._v(" "),n("p",[t._v("本文示例等源代码在这我的"),n("code",[t._v("github")]),t._v("博客中"),n("a",{attrs:{href:"https://github.com/lxchuan12/blog/blob/master/docs/sentry/README.md",target:"_blank",rel:"noopener noreferrer"}},[t._v("github blog sentry"),n("OutboundLink")],1),t._v(",需要的读者可以点击查看,如果觉得不错,可以顺便"),n("code",[t._v("star")]),t._v("一下。")]),t._v(" "),n("p",[t._v("看源码前先来梳理下前端错误监控的知识。")]),t._v(" "),n("h2",{attrs:{id:"_2-前端错误监控知识"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-前端错误监控知识"}},[t._v("#")]),t._v(" 2. 前端错误监控知识")]),t._v(" "),n("p",[t._v("摘抄自 "),n("a",{attrs:{href:"https://coding.imooc.com/class/129.html",target:"_blank",rel:"noopener noreferrer"}},[t._v("慕课网视频教程:前端跳槽面试必备技巧"),n("OutboundLink")],1),n("br"),t._v(" "),n("a",{attrs:{href:"https://articles.jerryshi.com/learning/fe/js-interview-skill.html#_4-4-%E9%94%99%E8%AF%AF%E7%9B%91%E6%8E%A7%E7%B1%BB",target:"_blank",rel:"noopener noreferrer"}},[t._v("别人做的笔记:前端跳槽面试必备技巧-4-4 错误监控类"),n("OutboundLink")],1)]),t._v(" "),n("h3",{attrs:{id:"_2-1-前端错误的分类"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-前端错误的分类"}},[t._v("#")]),t._v(" 2.1 前端错误的分类")]),t._v(" "),n("blockquote",[n("p",[n("strong",[t._v("1.即时运行错误:代码错误")])])]),t._v(" "),n("p",[n("code",[t._v("try...catch")])]),t._v(" "),n("p",[n("code",[t._v("window.onerror")]),t._v(" (也可以用"),n("code",[t._v("DOM2")]),t._v("事件监听)")]),t._v(" "),n("blockquote",[n("p",[n("strong",[t._v("2.资源加载错误")])])]),t._v(" "),n("p",[n("code",[t._v("object.onerror")]),t._v(": "),n("code",[t._v("dom")]),t._v("对象的"),n("code",[t._v("onerror")]),t._v("事件")]),t._v(" "),n("p",[n("code",[t._v("performance.getEntries()")])]),t._v(" "),n("p",[n("code",[t._v("Error")]),t._v("事件捕获")]),t._v(" "),n("blockquote",[n("p",[t._v("3."),n("strong",[t._v("使用"),n("code",[t._v("performance.getEntries()")]),t._v("获取网页图片加载错误")])])]),t._v(" "),n("p",[n("code",[t._v("var allImgs = document.getElementsByTagName('image')")])]),t._v(" "),n("p",[n("code",[t._v("var loadedImgs = performance.getEntries().filter(i => i.initiatorType === 'img')")])]),t._v(" "),n("p",[t._v("最后"),n("code",[t._v("allIms")]),t._v("和"),n("code",[t._v("loadedImgs")]),t._v("对比即可找出图片资源未加载项目")]),t._v(" "),n("h3",{attrs:{id:"_2-2-error事件捕获代码示例"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-2-error事件捕获代码示例"}},[t._v("#")]),t._v(" 2.2 Error事件捕获代码示例")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[t._v("window"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("addEventListener")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'error'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("e")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n console"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("log")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'捕获'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" e"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 这里只有捕获才能触发事件,冒泡是不能触发")]),t._v("\n")])])]),n("h3",{attrs:{id:"_2-3-上报错误的基本原理"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_2-3-上报错误的基本原理"}},[t._v("#")]),t._v(" 2.3 上报错误的基本原理")]),t._v(" "),n("p",[t._v("1.采用"),n("code",[t._v("Ajax")]),t._v("通信的方式上报")]),t._v(" "),n("p",[t._v("2.利用"),n("code",[t._v("Image")]),t._v("对象上报 (主流方式)")]),t._v(" "),n("p",[n("code",[t._v("Image")]),t._v("上报错误方式:\n"),n("code",[t._v("(new Image()).src = 'https://lxchuan12.cn/error?name=若川'")])]),t._v(" "),n("h2",{attrs:{id:"_3-sentry-前端异常监控基本原理"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3-sentry-前端异常监控基本原理"}},[t._v("#")]),t._v(" 3. Sentry 前端异常监控基本原理")]),t._v(" "),n("blockquote",[n("p",[t._v("1.重写 "),n("code",[t._v("window.onerror")]),t._v(" 方法、重写 "),n("code",[t._v("window.onunhandledrejection")]),t._v(" 方法")])]),t._v(" "),n("p",[t._v("如果不了解"),n("code",[t._v("onerror和onunhandledrejection")]),t._v("方法的读者,可以看相关的"),n("code",[t._v("MDN")]),t._v("文档。这里简要介绍一下:")]),t._v(" "),n("p",[n("a",{attrs:{href:"https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalEventHandlers/onerror",target:"_blank",rel:"noopener noreferrer"}},[t._v("MDN GlobalEventHandlers.onerror"),n("OutboundLink")],1)]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[t._v("window"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("onerror")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" source"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" lineno"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" colno"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" error")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\tconsole"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("log")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'message, source, lineno, colno, error'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" source"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" lineno"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" colno"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" error"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("blockquote",[n("p",[t._v("参数:"),n("br"),t._v(" "),n("code",[t._v("message")]),t._v(":错误信息(字符串)。可用于"),n("code",[t._v('HTML onerror=""')]),t._v("处理程序中的"),n("code",[t._v("event")]),t._v("。"),n("br"),t._v(" "),n("code",[t._v("source")]),t._v(":发生错误的脚本"),n("code",[t._v("URL")]),t._v("(字符串)"),n("br"),t._v(" "),n("code",[t._v("lineno")]),t._v(":发生错误的行号(数字)"),n("br"),t._v(" "),n("code",[t._v("colno")]),t._v(":发生错误的列号(数字)"),n("br"),t._v(" "),n("code",[t._v("error")]),t._v(":"),n("code",[t._v("Error")]),t._v("对象(对象)"),n("br")])]),t._v(" "),n("p",[n("a",{attrs:{href:"https://developer.mozilla.org/zh-CN/docs/Web/Events/unhandledrejection",target:"_blank",rel:"noopener noreferrer"}},[t._v("MDN unhandledrejection"),n("OutboundLink")],1)]),t._v(" "),n("blockquote",[n("p",[t._v("当 "),n("code",[t._v("Promise")]),t._v(" 被 "),n("code",[t._v("reject")]),t._v(" 且没有 "),n("code",[t._v("reject")]),t._v(" 处理器的时候,会触发 "),n("code",[t._v("unhandledrejection")]),t._v(" 事件;这可能发生在 "),n("code",[t._v("window")]),t._v(" 下,但也可能发生在 "),n("code",[t._v("Worker")]),t._v(" 中。 这对于调试回退错误处理非常有用。")])]),t._v(" "),n("p",[n("code",[t._v("Sentry")]),t._v(" 源码可以搜索 "),n("code",[t._v("global.onerror")]),t._v(" 定位到具体位置")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("GlobalHandlers")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("_installGlobalOnErrorHandler")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 代码有删减")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 这里的 this._global 在浏览器中就是 window")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_oldOnErrorHandler "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_global"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("onerror"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_global"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("onerror")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("msg"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" url"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" line"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" column"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" error")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// code ...")]),t._v("\n "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("同样,可以搜索"),n("code",[t._v("global.onunhandledrejection")]),t._v(" 定位到具体位置")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("GlobalHandlers")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("_installGlobalOnUnhandledRejectionHandler")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 代码有删减")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_oldOnUnhandledRejectionHandler "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_global"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("onunhandledrejection"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_global"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("onunhandledrejection")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("e")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("blockquote",[n("p",[t._v("2.采用"),n("code",[t._v("Ajax")]),t._v("上传")])]),t._v(" "),n("p",[t._v("支持 "),n("code",[t._v("fetch")]),t._v(" 使用 "),n("code",[t._v("fetch")]),t._v(",否则使用 "),n("code",[t._v("XHR")]),t._v("。")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("BrowserBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("_setupTransport")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 代码有删减")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("supportsFetch")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("FetchTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("transportOptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("XHRTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("transportOptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("blockquote",[n("p",[t._v("2.1 "),n("code",[t._v("fetch")])])]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("FetchTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("sendEvent")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("event")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" defaultOptions "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tbody"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("JSON")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("stringify")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t\tmethod"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'POST'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t\treferrerPolicy"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("supportsReferrerPolicy")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'origin'")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("''")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_buffer"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("add")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("global$"),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("2.")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("fetch")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("url"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" defaultOptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("then")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("response")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tstatus"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" exports"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("Status"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("fromHttpCode")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("response"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("status"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("blockquote",[n("p",[t._v("2.2 "),n("code",[t._v("XMLHttpRequest")])])]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("XHRTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("sendEvent")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("event")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" _this "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_buffer"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("add")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("SyncPromise")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("resolve"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" reject")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 熟悉的 XMLHttpRequest")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" request "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("XMLHttpRequest")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\trequest"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("onreadystatechange")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("request"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("readyState "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!==")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("4")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("request"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("status "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("200")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("resolve")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t\t\tstatus"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" exports"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("Status"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("fromHttpCode")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("request"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("status"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t\t\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("reject")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("request"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\trequest"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("open")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'POST'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" _this"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("url"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\trequest"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("send")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("JSON")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("stringify")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("接下来主要通过Sentry初始化、如何"),n("code",[t._v("Ajax上报")]),t._v("和"),n("code",[t._v("window.onerror、window.onunhandledrejection")]),t._v("三条主线来学习源码。")]),t._v(" "),n("blockquote",[n("p",[t._v("如果看到这里,暂时不想关注后面的源码细节,直接看后文小结1和2的两张图。或者可以点赞或收藏这篇文章,后续想看了再看。")])]),t._v(" "),n("h2",{attrs:{id:"_4-sentry-源码入口和出口"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_4-sentry-源码入口和出口"}},[t._v("#")]),t._v(" 4. Sentry 源码入口和出口")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" Sentry "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("exports")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// code ...")]),t._v("\n\n "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SDK_NAME")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'sentry.javascript.browser'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SDK_VERSION")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'5.7.1'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// code ...")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 省略了导出的Sentry的若干个方法和属性")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 只列出了如下几个")]),t._v("\n exports"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SDK_NAME")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SDK_NAME")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n exports"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SDK_VERSION")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SDK_VERSION")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 重点关注 captureMessage")]),t._v("\n exports"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("captureMessage "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" captureMessage"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 重点关注 init")]),t._v("\n exports"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("init "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" init"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" exports"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("h2",{attrs:{id:"_5-sentry-init-初始化-之-init-函数"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_5-sentry-init-初始化-之-init-函数"}},[t._v("#")]),t._v(" 5. Sentry.init 初始化 之 init 函数")]),t._v(" "),n("p",[t._v("初始化")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 这里的dsn,是sentry.io网站会生成的。")]),t._v("\nSentry"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("init")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" dsn"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'xxx'")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// options 是 {dsn: '...'}")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("init")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("options")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 如果options 是undefined,则赋值为 空对象")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("void")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" options "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 如果没传 defaultIntegrations 则赋值默认的")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("defaultIntegrations "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("undefined")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\toptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("defaultIntegrations "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" defaultIntegrations"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 初始化语句")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("release "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("undefined")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" window_1 "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getGlobalObject")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 这是给 sentry-webpack-plugin 插件提供的,webpack插件注入的变量。这里没用这个插件,所以这里不深究。")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// This supports the variable that sentry-webpack-plugin injects")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("window_1"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SENTRY_RELEASE")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" window_1"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SENTRY_RELEASE")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("id"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\toptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("release "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" window_1"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("SENTRY_RELEASE")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("id"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 初始化并且绑定")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("initAndBind")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("BrowserClient"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("h3",{attrs:{id:"_5-1-getglobalobject、innodeenv-函数"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_5-1-getglobalobject、innodeenv-函数"}},[t._v("#")]),t._v(" 5.1 getGlobalObject、inNodeEnv 函数")]),t._v(" "),n("p",[t._v("很多地方用到这个函数"),n("code",[t._v("getGlobalObject")]),t._v("。其实做的事情也比较简单,就是获取全局对象。浏览器中是"),n("code",[t._v("window")]),t._v("。")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n * 判断是否是node环境\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("isNodeEnv")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// tslint:disable:strict-type-predicates")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Object")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("toString")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("call")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("typeof")]),t._v(" process "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!==")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'undefined'")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" process "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'[object process]'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" fallbackGlobalObject "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n * Safely get global scope object\n *\n * @returns Global scope object\n */")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getGlobalObject")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("isNodeEnv")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 是 node 环境 赋值给 global")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" global\n\t\t"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("typeof")]),t._v(" window "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!==")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'undefined'")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" window\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 不是 window self 不是undefined 说明是 Web Worker 环境")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("typeof")]),t._v(" self "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!==")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'undefined'")]),t._v("\n\t\t\t\t"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" self\n\t\t\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 都不是,赋值给空对象。")]),t._v("\n\t\t\t\t"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" fallbackGlobalObject"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("继续看 "),n("code",[t._v("initAndBind")]),t._v(" 函数")]),t._v(" "),n("h2",{attrs:{id:"_6-initandbind-函数之-new-browserclient-options"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_6-initandbind-函数之-new-browserclient-options"}},[t._v("#")]),t._v(" 6. initAndBind 函数之 new BrowserClient(options)")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("initAndBind")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("clientClass"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" options")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 这里没有开启debug模式,logger.enable() 这句不会执行")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("debug "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tlogger"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("enable")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getCurrentHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("bindClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("clientClass")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("可以看出 "),n("code",[t._v("initAndBind()")]),t._v(",第一个参数是 "),n("code",[t._v("BrowserClient")]),t._v(" 构造函数,第二个参数是初始化后的"),n("code",[t._v("options")]),t._v("。\n接着先看 构造函数 "),n("code",[t._v("BrowserClient")]),t._v("。\n另一条线 "),n("code",[t._v("getCurrentHub().bindClient()")]),t._v(" 先不看。")]),t._v(" "),n("h3",{attrs:{id:"_6-1-browserclient-构造函数"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_6-1-browserclient-构造函数"}},[t._v("#")]),t._v(" 6.1 BrowserClient 构造函数")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" BrowserClient "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/** @class */")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("_super")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// `BrowserClient` 继承自`BaseClient`")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("__extends")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("BrowserClient"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" _super"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n\t * Creates a new Browser SDK instance.\n\t *\n\t * @param options Configuration options for this SDK.\n\t */")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("BrowserClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("options")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("void")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" options "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 把`BrowserBackend`,`options`传参给`BaseClient`调用。")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_super")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("call")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" BrowserBackend"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("||")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" BrowserClient"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("BaseClient"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[n("code",[t._v("从代码中可以看出")]),t._v(":\n"),n("code",[t._v("BrowserClient")]),t._v(" 继承自"),n("code",[t._v("BaseClient")]),t._v(",并且把"),n("code",[t._v("BrowserBackend")]),t._v(","),n("code",[t._v("options")]),t._v("传参给"),n("code",[t._v("BaseClient")]),t._v("调用。")]),t._v(" "),n("p",[t._v("先看 "),n("code",[t._v("BrowserBackend")]),t._v(",这里的"),n("code",[t._v("BaseClient")]),t._v(",暂时不看。")]),t._v(" "),n("p",[t._v("看"),n("code",[t._v("BrowserBackend")]),t._v("之前,先提一下继承、继承静态属性和方法。")]),t._v(" "),n("h3",{attrs:{id:"_6-2-extends、extendstatics-打包代码实现的继承"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_6-2-extends、extendstatics-打包代码实现的继承"}},[t._v("#")]),t._v(" 6.2 __extends、extendStatics 打包代码实现的继承")]),t._v(" "),n("p",[t._v("未打包的源码是使用"),n("code",[t._v("ES6 extends")]),t._v("实现的。这是打包后的对"),n("code",[t._v("ES6")]),t._v("的"),n("code",[t._v("extends")]),t._v("的一种实现。")]),t._v(" "),n("p",[t._v("如果对继承还不是很熟悉的读者,可以参考我之前写的文章。"),n("a",{attrs:{href:"https://juejin.im/post/5c433e216fb9a049c15f841b",target:"_blank",rel:"noopener noreferrer"}},[t._v("面试官问:JS的继承"),n("OutboundLink")],1)]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 继承静态方法和属性")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("extendStatics")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" b")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 如果支持 Object.setPrototypeOf 这个函数,直接使用")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 不支持,则使用原型__proto__ 属性,")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 如何还不支持(但有可能__proto__也不支持,毕竟是浏览器特有的方法。)")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 则使用for in 遍历原型链上的属性,从而达到继承的目的。")]),t._v("\n\textendStatics "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" Object"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("setPrototypeOf "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("||")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" __proto__"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("instanceof")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Array")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" b")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__proto__ "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" b"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("||")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" b")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("for")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" p "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("in")]),t._v(" b"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("b"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("hasOwnProperty")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("p"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("p"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" b"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("p"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("extendStatics")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" b"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("__extends")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" b")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("extendStatics")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" b"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 申明构造函数__ 并且把 d 赋值给 constructor")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("__")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("constructor "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" d"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// (__.prototype = b.prototype, new __()) 这种逗号形式的代码,最终返回是后者,也就是 new __()")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 比如 (typeof null, 1) 返回的是1")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 如果 b === null 用Object.create(b) 创建 ,也就是一个不含原型链等信息的空对象 {}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 否则使用 new __() 返回")]),t._v("\n\td"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" b "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("null")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" Object"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("create")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("b"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("__")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" b"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("__")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("不得不说这打包后的代码十分严谨,上面说的我的文章《面试官问:"),n("code",[t._v("JS")]),t._v("的继承》中没有提到不支持"),n("code",[t._v("__proto__")]),t._v("的情况。看来这文章可以进一步严谨修正了。\n让我想起"),n("code",[t._v("Vue")]),t._v("源码中对数组检测代理判断是否支持"),n("code",[t._v("__proto__")]),t._v("的判断。")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// vuejs 源码:https://github.com/vuejs/vue/blob/dev/dist/vue.js#L526-L527")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// can we use __proto__?")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" hasProto "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'__proto__'")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("in")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("看完打包代码实现的继承,继续看 "),n("code",[t._v("BrowserBackend")]),t._v(" 构造函数")]),t._v(" "),n("h3",{attrs:{id:"_6-3-browserbackend-构造函数-浏览器后端"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_6-3-browserbackend-构造函数-浏览器后端"}},[t._v("#")]),t._v(" 6.3 BrowserBackend 构造函数 (浏览器后端)")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" BrowserBackend "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/** @class */")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("_super")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("__extends")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("BrowserBackend"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" _super"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("BrowserBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" _super "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!==")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("null")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_super")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("apply")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" arguments"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("||")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n\t * 设置请求\n\t */")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("BrowserBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("_setupTransport")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("dsn"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// We return the noop transport here in case there is no Dsn.")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 没有设置dsn,调用BaseBackend.prototype._setupTransport 返回空函数")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("_super")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_setupTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("call")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" transportOptions "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("__assign")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("transportOptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" dsn"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("dsn "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("transport"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("this"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("transport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("transportOptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 支持Fetch则返回 FetchTransport 实例,否则返回 XHRTransport实例,")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 这两个构造函数具体代码在开头已有提到。")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("supportsFetch")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("FetchTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("transportOptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("XHRTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("transportOptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// code ...")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" BrowserBackend"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("BaseBackend"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[n("code",[t._v("BrowserBackend")]),t._v(" 又继承自 "),n("code",[t._v("BaseBackend")]),t._v("。")]),t._v(" "),n("h4",{attrs:{id:"_6-3-1-basebackend-构造函数-基础后端"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_6-3-1-basebackend-构造函数-基础后端"}},[t._v("#")]),t._v(" 6.3.1 BaseBackend 构造函数 (基础后端)")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n * This is the base implemention of a Backend.\n * @hidden\n */")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" BaseBackend "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/** @class */")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/** Creates a new backend instance. */")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("BaseBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("options")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("dsn"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\tlogger"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("warn")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'No DSN provided, backend will not do anything.'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 调用设置请求函数")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_transport "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_setupTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n\t * Sets up the transport so it can be used later to send requests.\n\t * 设置发送请求空函数\n\t */")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("BaseBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("_setupTransport")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("NoopTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// code ...")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("BaseBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("sendEvent")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("event")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_transport"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("sendEvent")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("then")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("null")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("reason")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\tlogger"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("error")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v('"Error while sending event: "')]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),t._v(" reason"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("BaseBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("getTransport")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_transport"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" BaseBackend"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("通过一系列的继承后,回过头来看 "),n("code",[t._v("BaseClient")]),t._v(" 构造函数。")]),t._v(" "),n("h4",{attrs:{id:"_6-3-2-baseclient-构造函数-基础客户端"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_6-3-2-baseclient-构造函数-基础客户端"}},[t._v("#")]),t._v(" 6.3.2 BaseClient 构造函数(基础客户端)")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" BaseClient "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/** @class */")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n\t * Initializes this client instance.\n\t *\n\t * @param backendClass A constructor function to create the backend.\n\t * @param options Options for the client.\n\t */")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("BaseClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("backendClass"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" options")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/** Array of used integrations. */")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_integrations "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/** Is the client still processing a call? */")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_processing "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_backend "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("backendClass")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("dsn"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_dsn "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Dsn")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("dsn"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_isEnabled")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_integrations "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("setupIntegrations")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// code ...")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" BaseClient"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("h3",{attrs:{id:"_6-4-小结1-new-browerclient-经过一系列的继承和初始化"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_6-4-小结1-new-browerclient-经过一系列的继承和初始化"}},[t._v("#")]),t._v(" 6.4 小结1. new BrowerClient 经过一系列的继承和初始化")]),t._v(" "),n("p",[t._v("可以输出下具体"),n("code",[t._v("new clientClass(options)")]),t._v("之后的结果:")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("initAndBind")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("clientClass"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" options")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("debug "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tlogger"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("enable")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" client "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("clientClass")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\tconsole"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("log")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'new clientClass(options)'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" client"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getCurrentHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("bindClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("client"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 原来的代码")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// getCurrentHub().bindClient(new clientClass(options));")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("最终输出得到这样的数据。我画了一张图表示。重点关注的原型链用颜色标注了,其他部分收缩了。")]),t._v(" "),n("p",[n("img",{attrs:{src:a(400),alt:"sentry new BrowserClient 实例图 By@若川"}})]),t._v(" "),n("h2",{attrs:{id:"_7-initandbind-函数之-getcurrenthub-bindclient"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_7-initandbind-函数之-getcurrenthub-bindclient"}},[t._v("#")]),t._v(" 7. initAndBind 函数之 getCurrentHub().bindClient()")]),t._v(" "),n("p",[t._v("继续看 "),n("code",[t._v("initAndBind")]),t._v(" 的另一条线。")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("initAndBind")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("clientClass"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" options")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("debug "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tlogger"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("enable")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getCurrentHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("bindClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("clientClass")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("获取当前的控制中心 "),n("code",[t._v("Hub")]),t._v(",再把"),n("code",[t._v("new BrowserClient()")]),t._v(" 的实例对象绑定在"),n("code",[t._v("Hub")]),t._v("上。")]),t._v(" "),n("h3",{attrs:{id:"_7-1-getcurrenthub-函数"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_7-1-getcurrenthub-函数"}},[t._v("#")]),t._v(" 7.1 getCurrentHub 函数")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 获取当前Hub 控制中心")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getCurrentHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Get main carrier (global for every environment)")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" registry "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getMainCarrier")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 如果没有控制中心在载体上,或者它的版本是老版本,就设置新的。")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// If there's no hub, or its an old API, assign a new one")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("hasHubOnCarrier")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("registry"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("||")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getHubFromCarrier")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("registry"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("isOlderThan")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("API_VERSION")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("setHubOnCarrier")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("registry"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Hub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// node 才执行")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Prefer domains over global if they are there (applicable only to Node environment)")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("isNodeEnv")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getHubFromActiveDomain")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("registry"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 返回当前控制中心来自载体上。")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Return hub that lives on a global object")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getHubFromCarrier")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("registry"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("h3",{attrs:{id:"_7-2-衍生的函数-getmaincarrier、gethubfromcarrier"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_7-2-衍生的函数-getmaincarrier、gethubfromcarrier"}},[t._v("#")]),t._v(" 7.2 衍生的函数 getMainCarrier、getHubFromCarrier")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getMainCarrier")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 载体 这里是window")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 通过一系列new BrowerClient() 一系列的初始化")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 挂载在 carrier.__SENTRY__ 已经有了三个属性,globalEventProcessors, hub, logger")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" carrier "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getGlobalObject")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\tcarrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__ "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" carrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__ "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("||")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\thub"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("undefined")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" carrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 获取控制中心 hub 从载体上")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getHubFromCarrier")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("carrier")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 已经有了则返回,没有则new Hub")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("carrier "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" carrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__ "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" carrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("hub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" carrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("hub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\tcarrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__ "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" carrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__ "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("||")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\tcarrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("hub "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Hub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" carrier"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("__SENTRY__"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("hub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("h3",{attrs:{id:"_7-3-bindclient-绑定客户端在当前控制中心上"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_7-3-bindclient-绑定客户端在当前控制中心上"}},[t._v("#")]),t._v(" 7.3 bindClient 绑定客户端在当前控制中心上")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Hub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("bindClient")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("client")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 获取最后一个")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" top "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getStackTop")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 把 new BrowerClient() 实例 绑定到top上")]),t._v("\n\ttop"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("client "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" client"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Hub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("getStackTop")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 获取最后一个")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_stack"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_stack"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("length "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("-")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("h3",{attrs:{id:"_7-4-小结2-经过一系列的继承和初始化"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_7-4-小结2-经过一系列的继承和初始化"}},[t._v("#")]),t._v(" 7.4 小结2. 经过一系列的继承和初始化")]),t._v(" "),n("p",[t._v("再回过头来看 "),n("code",[t._v("initAndBind")]),t._v("函数")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("initAndBind")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("clientClass"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" options")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("debug "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tlogger"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("enable")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" client "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("clientClass")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\tconsole"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("log")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("client"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" options"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'client, options'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" currentHub "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getCurrentHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\tcurrentHub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("bindClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("client"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\tconsole"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("log")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'currentHub'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" currentHub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 源代码")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// getCurrentHub().bindClient(new clientClass(options));")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("最终会得到这样的"),n("code",[t._v("Hub")]),t._v("实例对象。笔者画了一张图表示,便于查看理解。")]),t._v(" "),n("p",[n("img",{attrs:{src:a(401),alt:"Hub 实例关系图"}})]),t._v(" "),n("p",[t._v("初始化完成后,再来看具体例子。\n具体 "),n("code",[t._v("captureMessage")]),t._v(" 函数的实现。")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[t._v("Sentry"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("captureMessage")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Hello, 若川!'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("h2",{attrs:{id:"_8-capturemessage-函数"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_8-capturemessage-函数"}},[t._v("#")]),t._v(" 8. captureMessage 函数")]),t._v(" "),n("p",[t._v("通过之前的阅读代码,知道会最终会调用"),n("code",[t._v("Fetch")]),t._v("接口,所以直接断点调试即可,得出如下调用栈。\n接下来描述调用栈的主要流程。")]),t._v(" "),n("p",[n("img",{attrs:{src:a(402),alt:"captureMessage 断点调试图"}})]),t._v(" "),n("blockquote",[n("p",[t._v("调用栈主要流程:")])]),t._v(" "),n("p",[t._v("captureMessage")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("captureMessage")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" level")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" syntheticException"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("try")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("throw")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Error")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("catch")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("exception"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tsyntheticException "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" exception"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 调用 callOnHub 方法")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("callOnHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'captureMessage'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" level"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\toriginalException"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t\tsyntheticException"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" syntheticException"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("=> callOnHub")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n * This calls a function on the current hub.\n * @param method function to call on hub.\n * @param args to pass to function.\n */")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("callOnHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("method")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 这里method 传进来的是 'captureMessage'")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 把method除外的其他参数放到args数组中")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" args "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("for")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" _i "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" _i "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" arguments"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("length"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" _i"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("++")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\targs"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("_i "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("-")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" arguments"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("_i"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 获取当前控制中心 hub")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" hub "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getCurrentHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 有这个方法 把args 数组展开,传递给 hub[method] 执行")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("hub "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" hub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("method"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// tslint:disable-next-line:no-unsafe-any")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" hub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("method"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("apply")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("hub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("__spread")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("args"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("throw")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Error")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v('"No hub defined or "')]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),t._v(" method "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v('" was not found on the hub, please open a bug report."')]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),n("p",[t._v("=> Hub.prototype.captureMessage")]),t._v(" "),n("p",[t._v("接着看"),n("code",[t._v("Hub.prototype")]),t._v(" 上定义的 "),n("code",[t._v("captureMessage")]),t._v(" 方法")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Hub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("captureMessage")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" level"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" hint")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" eventId "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_lastEventId "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("uuid4")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" finalHint "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" hint"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 代码有删减")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_invokeClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'captureMessage'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" level"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("__assign")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" finalHint"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" event_id"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" eventId "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" eventId"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("=> Hub.prototype._invokeClient")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Hub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("_invokeClient")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("method")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 同样:这里method 传进来的是 'captureMessage'")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 把method除外的其他参数放到args数组中")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" _a"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" args "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("for")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" _i "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" _i "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" arguments"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("length"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" _i"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("++")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\targs"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("_i "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("-")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" arguments"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("_i"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" top "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getStackTop")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 获取控制中心的 hub,调用客户端也就是new BrowerClient () 实例中继承自 BaseClient 的 captureMessage 方法")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 有这个方法 把args 数组展开,传递给 hub[method] 执行")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("top "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" top"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("client "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" top"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("client"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("method"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("_a "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" top"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("client"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("method"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("apply")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("_a"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("__spread")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("args"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("top"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("scope"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("=> BaseClient.prototype.captureMessage")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("BaseClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("captureMessage")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" level"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" hint"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" scope")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" _this "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" eventId "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" hint "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" hint"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("event_id"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_processing "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" promisedEvent "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("isPrimitive")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_getBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("eventFromMessage")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v('""')]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),t._v(" message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" level"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" hint"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_getBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("eventFromException")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("message"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" hint"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 代码有删减")]),t._v("\n\tpromisedEvent\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("then")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("event")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" _this"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_processEvent")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" hint"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" scope"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 代码有删减")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" eventId"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("最后会调用 "),n("code",[t._v("_processEvent")]),t._v(" 也就是")]),t._v(" "),n("p",[t._v("=> BaseClient.prototype._processEvent")]),t._v(" "),n("p",[t._v("这个函数最终会调用")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[t._v("_this"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_getBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("sendEvent")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("finalEvent"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("也就是")]),t._v(" "),n("p",[t._v("=> BaseBackend.prototype.sendEvent")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("BaseBackend")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("sendEvent")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("event")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_transport"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("sendEvent")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("then")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("null")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("reason")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tlogger"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("error")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v('"Error while sending event: "')]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("+")]),t._v(" reason"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("=> FetchTransport.prototype.sendEvent 最终发送了请求")]),t._v(" "),n("h3",{attrs:{id:"_8-1-fetchtransport-prototype-sendevent"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_8-1-fetchtransport-prototype-sendevent"}},[t._v("#")]),t._v(" 8.1 FetchTransport.prototype.sendEvent")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("FetchTransport")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("sendEvent")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("event")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" defaultOptions "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tbody"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token constant"}},[t._v("JSON")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("stringify")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t\tmethod"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'POST'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// https://caniuse.com/#feat=referrer-policy")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// It doesn't. And it throw exception instead of ignoring this parameter...")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// REF: https://github.com/getsentry/raven-js/issues/1233")]),t._v("\n\t\treferrerPolicy"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("supportsReferrerPolicy")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'origin'")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("''")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// global$2.fetch(this.url, defaultOptions) 使用fetch发送请求")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_buffer"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("add")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("global$"),n("span",{pre:!0,attrs:{class:"token number"}},[t._v("2.")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("fetch")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("url"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" defaultOptions"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("then")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("response")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\tstatus"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" exports"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("Status"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("fromHttpCode")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("response"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("status"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("看完 "),n("code",[t._v("Ajax 上报")]),t._v(" 主线,再看本文的另外一条主线 "),n("code",[t._v("window.onerror")]),t._v(" 捕获。")]),t._v(" "),n("h2",{attrs:{id:"_9-window-onerror-和-window-onunhandledrejection-捕获-错误"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_9-window-onerror-和-window-onunhandledrejection-捕获-错误"}},[t._v("#")]),t._v(" 9. window.onerror 和 window.onunhandledrejection 捕获 错误")]),t._v(" "),n("p",[t._v("例子:调用一个未申明的变量。")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token function"}},[t._v("func")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[n("code",[t._v("Promise")]),t._v(" 不捕获错误")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Promise")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("fun")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("then")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("res")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\tconsole"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("log")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'then'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),n("h3",{attrs:{id:"_9-1-captureevent"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_9-1-captureevent"}},[t._v("#")]),t._v(" 9.1 captureEvent")]),t._v(" "),n("blockquote",[n("p",[t._v("调用栈主要流程:")])]),t._v(" "),n("blockquote",[n("p",[t._v("window.onerror")])]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("GlobalHandlers")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("_installGlobalOnErrorHandler")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_onErrorHandlerInstalled"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" self "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// tslint:disable-line:no-this-assignment")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 浏览器中这里的 this._global. 就是window")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_oldOnErrorHandler "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_global"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("onerror"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_global"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("onerror")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("msg"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" url"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" line"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" column"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" error")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" currentHub "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getCurrentHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 代码有删减")]),t._v("\n\t\tcurrentHub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("captureEvent")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\toriginalException"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" error"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("self"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_oldOnErrorHandler"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" self"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_oldOnErrorHandler")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("apply")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" arguments"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_onErrorHandlerInstalled "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("blockquote",[n("p",[t._v("window.onunhandledrejection")])]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("GlobalHandlers")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("_installGlobalOnUnhandledRejectionHandler")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_onUnhandledRejectionHandlerInstalled"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" self "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// tslint:disable-line:no-this-assignment")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_oldOnUnhandledRejectionHandler "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_global"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("onunhandledrejection"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_global"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("onunhandledrejection")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("e")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 代码有删减")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" currentHub "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("getCurrentHub")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\tcurrentHub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("captureEvent")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\toriginalException"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" error"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("self"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_oldOnUnhandledRejectionHandler"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\t\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" self"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_oldOnUnhandledRejectionHandler")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("apply")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" arguments"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\t\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("false")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\t"),n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("_onUnhandledRejectionHandlerInstalled "),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("共同点:都会调用"),n("code",[t._v("currentHub.captureEvent")])]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[t._v("currentHub"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("captureEvent")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("event"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n\toriginalException"),n("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" error"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n"),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),n("p",[t._v("=> Hub.prototype.captureEvent")]),t._v(" "),n("p",[t._v("最终又是调用 "),n("code",[t._v("_invokeClient")]),t._v(" ,调用流程跟 "),n("code",[t._v("captureMessage")]),t._v(" 类似,这里就不再赘述。")]),t._v(" "),n("div",{staticClass:"language-js extra-class"},[n("pre",{pre:!0,attrs:{class:"language-js"}},[n("code",[n("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),n("span",{pre:!0,attrs:{class:"token function"}},[t._v("_invokeClient")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),n("span",{pre:!0,attrs:{class:"token string"}},[t._v("'captureEvent'")]),n("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),n("p",[t._v("=> Hub.prototype._invokeClient")]),t._v(" "),n("p",[t._v("=> BaseClient.prototype.captureEvent")]),t._v(" "),n("p",[t._v("=> BaseClient.prototype._processEvent")]),t._v(" "),n("p",[t._v("=> BaseBackend.prototype.sendEvent")]),t._v(" "),n("p",[t._v("=> FetchTransport.prototype.sendEvent")]),t._v(" "),n("p",[t._v("最终同样是调用了这个函数发送了请求。")]),t._v(" "),n("p",[t._v("可谓是殊途同归,行文至此就基本已经结束,最后总结一下。")]),t._v(" "),n("h2",{attrs:{id:"_10-总结"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_10-总结"}},[t._v("#")]),t._v(" 10. 总结")]),t._v(" "),n("p",[n("code",[t._v("Sentry-JavaScript")]),t._v("源码高效利用了"),n("code",[t._v("JS")]),t._v("的原型链机制。可谓是惊艳,值得学习。")]),t._v(" "),n("p",[t._v("本文通过梳理前端错误监控知识、介绍"),n("code",[t._v("sentry")]),t._v("错误监控原理、"),n("code",[t._v("sentry")]),t._v("初始化、"),n("code",[t._v("Ajax")]),t._v("上报、"),n("code",[t._v("window.onerror、window.onunhandledrejection")]),t._v("几个方面来学习"),n("code",[t._v("sentry")]),t._v("的源码。还有很多细节和构造函数没有分析。")]),t._v(" "),n("p",[t._v("总共的构造函数(类)有25个,提到的主要有9个,分别是:"),n("code",[t._v("Hub、BaseClient、BaseBackend、BaseTransport、FetchTransport、XHRTransport、BrowserBackend、BrowserClient、GlobalHandlers")]),t._v("。")]),t._v(" "),n("p",[t._v("其他没有提到的分别是 "),n("code",[t._v("SentryError、Logger、Memo、SyncPromise、PromiseBuffer、Span、Scope、Dsn、API、NoopTransport、FunctionToString、InboundFilters、TryCatch、Breadcrumbs、LinkedErrors、UserAgent")]),t._v("。")]),t._v(" "),n("p",[t._v("这些构造函数(类)中还有很多值得学习,比如同步的"),n("code",[t._v("Promise")]),t._v("(SyncPromise)。\n有兴趣的读者,可以看这一块官方仓库中采用"),n("code",[t._v("typescript")]),t._v("写的源码"),n("a",{attrs:{href:"https://github.com/getsentry/sentry-javascript/blob/master/packages/utils/src/syncpromise.ts",target:"_blank",rel:"noopener noreferrer"}},[t._v("SyncPromise"),n("OutboundLink")],1),t._v(",也可以看打包后出来未压缩的代码。")]),t._v(" "),n("p",[t._v("读源码比较耗费时间,写文章记录下来更加费时间(比如写这篇文章跨度十几天...),但收获一般都比较大。")]),t._v(" "),n("p",[t._v("如果读者发现有不妥或可改善之处,再或者哪里没写明白的地方,欢迎评论指出。另外觉得写得不错,对您有些许帮助,可以点赞、评论、转发分享,也是对笔者的一种支持。万分感谢。")])])}),[],!1,null,null,null);s.default=e.exports}}]);
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/anyex/anyex/blob/master/CONTRIBUTING.md#how-to-contribute-code from anyex.base.exchange import Exchange # ----------------------------------------------------------------------------- try: basestring # Python 3 except NameError: basestring = str # Python 2 import hashlib from anyex.base.errors import ExchangeError class gateio (Exchange): def describe(self): return self.deep_extend(super(gateio, self).describe(), { 'id': 'gateio', 'name': 'Gate.io', 'countries': 'CN', 'version': '2', 'rateLimit': 1000, 'has': { 'CORS': False, 'createMarketOrder': False, 'fetchTickers': True, 'withdraw': True, 'createDepositAddress': True, 'fetchDepositAddress': True, }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/31784029-0313c702-b509-11e7-9ccc-bc0da6a0e435.jpg', 'api': { 'public': 'https://data.gate.io/api', 'private': 'https://data.gate.io/api', }, 'www': 'https://gate.io/', 'doc': 'https://gate.io/api2', 'fees': [ 'https://gate.io/fee', 'https://support.gate.io/hc/en-us/articles/115003577673', ], }, 'api': { 'public': { 'get': [ 'pairs', 'marketinfo', 'marketlist', 'tickers', 'ticker/{id}', 'orderBook/{id}', 'trade/{id}', 'tradeHistory/{id}', 'tradeHistory/{id}/{tid}', ], }, 'private': { 'post': [ 'balances', 'depositAddress', 'newAddress', 'depositsWithdrawals', 'buy', 'sell', 'cancelOrder', 'cancelAllOrders', 'getOrder', 'openOrders', 'tradeHistory', 'withdraw', ], }, }, 'fees': { 'trading': { 'tierBased': True, 'percentage': True, 'maker': 0.002, 'taker': 0.002, }, }, }) def fetch_markets(self): response = self.publicGetMarketinfo() markets = self.safe_value(response, 'pairs') if not markets: raise ExchangeError(self.id + ' fetchMarkets got an unrecognized response') result = [] for i in range(0, len(markets)): market = markets[i] keys = list(market.keys()) id = keys[0] details = market[id] base, quote = id.split('_') base = base.upper() quote = quote.upper() base = self.common_currency_code(base) quote = self.common_currency_code(quote) symbol = base + '/' + quote precision = { 'amount': details['decimal_places'], 'price': details['decimal_places'], } amountLimits = { 'min': details['min_amount'], 'max': None, } priceLimits = { 'min': None, 'max': None, } limits = { 'amount': amountLimits, 'price': priceLimits, } result.append({ 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'info': market, 'maker': details['fee'] / 100, 'taker': details['fee'] / 100, 'precision': precision, 'limits': limits, }) return result def fetch_balance(self, params={}): self.load_markets() balance = self.privatePostBalances() result = {'info': balance} currencies = list(self.currencies.keys()) for i in range(0, len(currencies)): currency = currencies[i] code = self.common_currency_code(currency) account = self.account() if 'available' in balance: if currency in balance['available']: account['free'] = float(balance['available'][currency]) if 'locked' in balance: if currency in balance['locked']: account['used'] = float(balance['locked'][currency]) account['total'] = self.sum(account['free'], account['used']) result[code] = account return self.parse_balance(result) def fetch_order_book(self, symbol, limit=None, params={}): self.load_markets() orderbook = self.publicGetOrderBookId(self.extend({ 'id': self.market_id(symbol), }, params)) return self.parse_order_book(orderbook) def parse_ticker(self, ticker, market=None): timestamp = self.milliseconds() symbol = None if market: symbol = market['symbol'] last = float(ticker['last']) return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'high': float(ticker['high24hr']), 'low': float(ticker['low24hr']), 'bid': float(ticker['highestBid']), 'bidVolume': None, 'ask': float(ticker['lowestAsk']), 'askVolume': None, 'vwap': None, 'open': None, 'close': last, 'last': last, 'previousClose': None, 'change': float(ticker['percentChange']), 'percentage': None, 'average': None, 'baseVolume': float(ticker['quoteVolume']), 'quoteVolume': float(ticker['baseVolume']), 'info': ticker, } def fetch_tickers(self, symbols=None, params={}): self.load_markets() tickers = self.publicGetTickers(params) result = {} ids = list(tickers.keys()) for i in range(0, len(ids)): id = ids[i] baseId, quoteId = id.split('_') base = baseId.upper() quote = quoteId.upper() base = self.common_currency_code(base) quote = self.common_currency_code(quote) symbol = base + '/' + quote ticker = tickers[id] market = None if symbol in self.markets: market = self.markets[symbol] if id in self.markets_by_id: market = self.markets_by_id[id] result[symbol] = self.parse_ticker(ticker, market) return result def fetch_ticker(self, symbol, params={}): self.load_markets() market = self.market(symbol) ticker = self.publicGetTickerId(self.extend({ 'id': market['id'], }, params)) return self.parse_ticker(ticker, market) def parse_trade(self, trade, market): # exchange reports local time(UTC+8) timestamp = self.parse8601(trade['date']) - 8 * 60 * 60 * 1000 return { 'id': trade['tradeID'], 'info': trade, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': market['symbol'], 'type': None, 'side': trade['type'], 'price': float(trade['rate']), 'amount': self.safe_float(trade, 'amount'), } def fetch_trades(self, symbol, since=None, limit=None, params={}): self.load_markets() market = self.market(symbol) response = self.publicGetTradeHistoryId(self.extend({ 'id': market['id'], }, params)) return self.parse_trades(response['data'], market, since, limit) def create_order(self, symbol, type, side, amount, price=None, params={}): if type == 'market': raise ExchangeError(self.id + ' allows limit orders only') self.load_markets() method = 'privatePost' + self.capitalize(side) order = { 'currencyPair': self.market_id(symbol), 'rate': price, 'amount': amount, } response = getattr(self, method)(self.extend(order, params)) return { 'info': response, 'id': response['orderNumber'], } def cancel_order(self, id, symbol=None, params={}): self.load_markets() return self.privatePostCancelOrder({'orderNumber': id}) def query_deposit_address(self, method, currency, params={}): method = 'privatePost' + method + 'Address' response = getattr(self, method)(self.extend({ 'currency': currency, }, params)) address = None if 'addr' in response: address = self.safe_string(response, 'addr') return { 'currency': currency, 'address': address, 'status': 'ok' if (address is not None) else 'none', 'info': response, } def create_deposit_address(self, currency, params={}): return self.query_deposit_address('New', currency, params) def fetch_deposit_address(self, currency, params={}): return self.query_deposit_address('Deposit', currency, params) def withdraw(self, currency, amount, address, tag=None, params={}): self.check_address(address) self.load_markets() response = self.privatePostWithdraw(self.extend({ 'currency': currency.lower(), 'amount': amount, 'address': address, # Address must exist in you AddressBook in security settings }, params)) return { 'info': response, 'id': None, } def sign(self, path, api='public', method='GET', params={}, headers=None, body=None): prefix = (api + '/') if (api == 'private') else '' url = self.urls['api'][api] + self.version + '/1/' + prefix + self.implode_params(path, params) query = self.omit(params, self.extract_params(path)) if api == 'public': if query: url += '?' + self.urlencode(query) else: self.check_required_credentials() nonce = self.nonce() request = {'nonce': nonce} body = self.urlencode(self.extend(request, query)) signature = self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512) headers = { 'Key': self.apiKey, 'Sign': signature, 'Content-Type': 'application/x-www-form-urlencoded', } return {'url': url, 'method': method, 'body': body, 'headers': headers} def request(self, path, api='public', method='GET', params={}, headers=None, body=None): response = self.fetch2(path, api, method, params, headers, body) if 'result' in response: result = response['result'] message = self.id + ' ' + self.json(response) if result is None: raise ExchangeError(message) if isinstance(result, basestring): if result != 'true': raise ExchangeError(message) elif not result: raise ExchangeError(message) return response
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import yaml from maro.cli.utils.params import GlobalPaths class DetailsReader: @staticmethod def load_cluster_details(cluster_name: str) -> dict: with open(f"{GlobalPaths.ABS_MARO_CLUSTERS}/{cluster_name}/cluster_details.yml", "r") as fr: cluster_details = yaml.safe_load(fr) return cluster_details @staticmethod def load_default_user_details(cluster_name: str) -> dict: with open(file=f"{GlobalPaths.ABS_MARO_CLUSTERS}/{cluster_name}/users/default_user", mode="r") as fr: user_id = fr.read() with open( file=f"{GlobalPaths.ABS_MARO_CLUSTERS}/{cluster_name}/users/{user_id}/user_details", mode="r" ) as fr: user_details = yaml.safe_load(stream=fr) return user_details
import time from datetime import datetime from enum import Enum from mongoengine import ( StringField, IntField, FloatField, EmbeddedDocument, Document, BooleanField, ListField, EmbeddedDocumentField, EmbeddedDocumentListField, DynamicField, ObjectIdField, ReferenceField, ) from mongoengine import ValidationError def valid_status(status): try: Status(status) except Exception: raise ValidationError( f"{status} is not a valid status {vars(Status)['_member_names_']}" ) def valid_authstrat(strat): if strat is None: pass try: AuthStrat(strat) except Exception: raise ValidationError( f"{strat} is not a valid Authentication strategy {vars(AuthStrat)['_member_names_']}" ) def valid_termination_code(code): if code is None: pass try: TerminatedCode(code) except Exception: raise ValidationError( f"{code} is not a valid TerminatedCode strategy {vars(TerminatedCode)['_member_names_']}" ) def valid_errorcode(code): if code is None: pass try: ErrorCode(code) except Exception: raise ValidationError( f"{code} is not a valid ErrorCode strategy {vars(ErrorCode)['_member_names_']}" ) # TODO Make sure Datetime is correct format # TODO Use ReferenceField to create a mapping between WSID and JOB IDS? """ "created": ISODate("2019-02-19T23:00:57.119Z"), "updated": ISODate("2019-02-19T23:01:32.132Z"), """ class LogLines(EmbeddedDocument): """ Log lines contain the content, whether or not to display the content as an error message, the position of the line, and the timestamp """ line = StringField(required=True) linepos = IntField(required=True) error = BooleanField(default=False) ts = FloatField(default=time.time) class JobLog(Document): """ As a job runs, it saves its STDOUT and STDERR here """ primary_key = ObjectIdField(primary_key=True, required=True) updated = FloatField(default=time.time) original_line_count = IntField() stored_line_count = IntField() lines = ListField() meta = {"collection": "ee2_logs"} def save(self, *args, **kwargs): self.updated = time.time() return super(JobLog, self).save(*args, **kwargs) class Meta(EmbeddedDocument): """ Information about from the cell where this job was run """ run_id = StringField() token_id = StringField() tag = StringField() cell_id = StringField() status = StringField() class CondorResourceUsage(EmbeddedDocument): """ Storing stats about a job's usage """ cpu = ListField() memory = ListField() timestamp = ListField() # Maybe remove this if we always want to make timestamp required def save(self, *args, **kwargs): self.timestamp.append(datetime.utcnow().timestamp()) return super(CondorResourceUsage, self).save(*args, **kwargs) class Estimate(EmbeddedDocument): """ Estimator function output goes here """ cpu = IntField() memory = StringField() class JobRequirements(EmbeddedDocument): """ To be populated by ee2 during init of a job record """ clientgroup = StringField() cpu = IntField() memory = IntField() disk = IntField() estimate = EmbeddedDocumentField(Estimate) class JobInput(EmbeddedDocument): """ To be created from the Narrative """ wsid = IntField(required=False, default=None) method = StringField(required=True) requested_release = StringField() params = DynamicField() service_ver = StringField(required=True) app_id = StringField(required=True) source_ws_objects = ListField() parent_job_id = StringField() requirements = EmbeddedDocumentField(JobRequirements) narrative_cell_info = EmbeddedDocumentField(Meta, required=True) class JobOutput(EmbeddedDocument): """ To be created from the successful and possibly also failure run of a job """ version = StringField(required=True) id = ObjectIdField(required=True) result = DynamicField(required=True) class ErrorCode(Enum): """ Reasons why the job was marked as error """ unknown_error = 0 job_crashed = 1 job_terminated_by_automation = 2 job_over_timelimit = 3 job_missing_output = 4 token_expired = 5 condor_submit_issue = 6 class Error(EmbeddedDocument): """ Storing detailed error information. Possibly coming from the JobRunner """ message = StringField() code = IntField() name = StringField() error = StringField() class TerminatedCode(Enum): """ Reasons for why the job was cancelled """ terminated_by_user = 0 terminated_by_admin = 1 terminated_by_automation = 2 terminated_by_batch_abort = 3 class Status(Enum): """ A job begins at created, then can either be estimating """ created = "created" estimating = "estimating" queued = "queued" running = "running" # finished = "finished" # Successful termination legacy code completed = "completed" # Successful termination error = "error" # Something went wrong and job failed # Possible Reasons are (ErrorCodes) terminated = "terminated" # Canceled by user, admin, or script # Possible Reasons are (TerminatedCodes) class AuthStrat(Enum): """ The strings to be passed to the auth service when checking to see if a given token has access to the workspace """ DEFAULT = "DEFAULT" kbaseworkspace = "kbaseworkspace" execution_engine = "execution_engine" class JobInputFile(EmbeddedDocument): # TODO USE THIS # TODO VERIFY UPA WITH REGEX or special function [0-9]+/[0-9]+/*[0-9]* upa = StringField() filename = StringField() filesize_mb = IntField() # Provenance? class JobInputAttributes(Document): # TODO USE THIS job_input_filesizes = EmbeddedDocumentListField(JobInputFile) class JobUsageAttributes(Document): # TODO USE THIS job_peak_cpu_usage = FloatField(default=0) job_peak_memory_usage_mb = IntField(default=0) job_peak_disk_usage_mb = IntField(default=0) class JobResourceAttributes(Document): """ Should be partially populated by the JobRunner at run time Can be periodically populated by the JobRunner during the lifecycle of the job Can be populated at the end of """ client_group = StringField(required=True) request_cpus = IntField(required=True) request_memory = IntField(required=True) request_disk = IntField(required=True) class Job(Document): """ A job is created the execution engine service and it's updated from the job and the portal process for the rest of the time """ # id.generation_time = created user = StringField(required=True) authstrat = StringField( required=True, default="kbaseworkspace", validation=valid_authstrat ) wsid = IntField(required=False, default=None) status = StringField(required=True, validation=valid_status) updated = FloatField(default=time.time) # id.generation_time = created queued = FloatField( default=None ) # Time when job was submitted to the queue to be run estimating = FloatField( default=None ) # Time when job was submitted to begin estimating running = FloatField(default=None) # Time when job started # Time when job finished, errored out, or was terminated by the user/admin finished = FloatField(default=None) errormsg = StringField() msg = StringField() error = DynamicField() terminated_code = IntField(validation=valid_termination_code) error_code = IntField(validation=valid_errorcode) scheduler_type = StringField() scheduler_id = StringField() scheduler_estimator_id = StringField() job_input = EmbeddedDocumentField(JobInput, required=True) job_output = DynamicField() condor_job_ads = DynamicField() child_jobs = ListField() batch_job = BooleanField(default=False) meta = {"collection": "ee2_jobs"} def save(self, *args, **kwargs): self.updated = time.time() return super(Job, self).save(*args, **kwargs) def __repr__(self): return self.to_json() # Unused for now class HeldJob(Document): job_id = ReferenceField(Job) used_cpu = IntField(required=True) used_memory = FloatField(required=True) used_memory_raw = FloatField(required=True) used_disk_raw = FloatField(required=True) over_memory = BooleanField(required=True) over_cpu = BooleanField(required=True) check_time = FloatField(required=True) node_jobs = IntField(required=True) node_cpu = FloatField(required=True) node_memory = FloatField(required=True) node_disk = FloatField(required=True) node_name = StringField(required=True) def save(self, *args, **kwargs): self.updated = time.time() return super(HeldJob, self).save(*args, **kwargs) ### ### Unused fields that we might want ### result_example = { "shocknodes": [], "shockurl": "https://ci.kbase.us/services/shock-api/", "workspaceids": [], "workspaceurl": "https://ci.kbase.us/services/ws/", "results": [ { "servtype": "Workspace", "url": "https://ci.kbase.us/services/ws/", "id": "psnovichkov:1450397093052/QQ", "desc": "description", } ], "prog": 0, "maxprog": None, "other": { "estcompl": None, "service": "bsadkhin", "desc": "Execution engine job for simpleapp.simple_add", "progtype": None, }, } #### #### Unused Stuff to look at #### class Results(EmbeddedDocument): run_id = StringField() shockurl = StringField() workspaceids = ListField() workspaceurl = StringField() shocknodes = ListField()
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resetAttributes = void 0; var resetAttributes = target => { var properties = { length: 0, type: null }; properties.type = target.constructor.name; switch (properties.type) { case "Array": properties.length = target.length; break; case "Object": properties.length = Object.keys(target).length; case "Map": properties.length = target.size; break; case "Set": properties.length = target.size; break; case "String": properties.length = target.length; break; case "Date": properties.length = target.toString().length; break; case "RegExp": properties.length = target.toString().length; break; case "Function": properties.length = target.toString().length; break; } return properties; }; exports.resetAttributes = resetAttributes;
import Main from '@/views/Main.vue'; const commentMap = { path: '/comment', name: 'comment', icon: 'comment', title: '评论', component: Main, children: [ { path: 'index', title: '评论', name: 'comment_index', component: () => import('@/views/comment/index.vue') } ] }; export default commentMap;
#pragma once #include <fstream> #include <iostream> #include <string> #include "IGraphReader.h" namespace graphpp { template <class Graph, class Vertex> class WeightedGraphReader : public IGraphReader<Graph, Vertex> { public: // this typedefs are also present in the superclass. Any way to remove it? typedef unsigned int LineNumber; virtual void read(Graph& g, std::string source) { std::ifstream sourceFile; double weight; sourceFile.open(source.c_str(), std::ios_base::in); if (!sourceFile) throw FileNotFoundException(source); std::string line; currentLineNumber = 1; while (getline(sourceFile, line)) { std::string tree_str = line; character = tree_str.c_str(); if (!isEmptyLine()) { consume_whitespace(); Vertex* sourceNode = loadVertex(g); consume_whitespace(); if (*character != '\0') { Vertex* destinationNode = loadVertex(g); consume_whitespace(); weight = consume_weigth(); consume_whitespace(); if (*character != '\0') throw MalformedLineException(getLineNumberText()); try { g.addEdge(sourceNode, destinationNode, weight); } catch (const DuplicateEdge& ex) { throw DuplicatedEdgeLoading(getLineNumberText()); } } } ++currentLineNumber; } sourceFile.close(); } private: std::string getLineNumberText() const { std::stringstream s; s << "Line: " << currentLineNumber; return s.str(); } Vertex* loadVertex(Graph& g) { Vertex* vertex = new Vertex(readUnsignedInt()); Vertex* vertexAux = vertex; if ((vertex = g.getVertexById(vertex->getVertexId())) != nullptr) delete vertexAux; else { vertex = vertexAux; g.addVertex(vertex); } return vertex; } unsigned int readUnsignedInt() { unsigned int ret = 0; if (!in_range(*character, '0', '9')) throw UnsignedIntegerMalformedException(getLineNumberText()); else { std::string branchLenStr; while (in_range(*character, '0', '9')) { branchLenStr += *character; ++character; } if (!from_string<unsigned int>(branchLenStr, ret)) throw UnsignedIntegerMalformedException(getLineNumberText()); } return ret; } // TODO this method should be const bool isEmptyLine() { bool ret = false; consume_whitespace(); if (*character == '\0') ret = true; return ret; } void consume_whitespace() { while (*character == ' ' || *character == '\t') ++character; } double consume_weigth() { consume_whitespace(); bool positive = false, hasExponent = false; unsigned int exponent = 0; double ret = 0.0; std::string branchLenStr; while (in_range(*character, '0', '9') || *character == '.') { branchLenStr += *character; ++character; } if (*character == 'E' || *character == 'e') { ++character; if (*character == '+') positive = true; else if (in_range(*character, '0', '9')) { --character; positive = true; } else if (*character == '-') positive = false; else throw MalformedDoubleException(getLineNumberText()); ++character; exponent = readUnsignedInt(); hasExponent = true; } if (!from_string<double>(branchLenStr, ret)) throw MalformedDoubleException(getLineNumberText()); if (hasExponent) ret = positive ? ret * pow(10.0, exponent) : ret / ((double)(pow(10.0, exponent))); return ret; } LineNumber currentLineNumber; const char* character; }; } // namespace graphpp
#include "data_structs/sparse_matrix.h" #include <greatest.h> #include "lang/memory.h" static void matrix_put_int(Matrix_T* p_matrix, int row, int col, int value) { int* p_i; /* No place for zeros in sparse matrix. */ if (value == 0) { if (Matrix_get(p_matrix, row, col, (Object_T*) &p_i)) { Matrix_clear(p_matrix, row, col); FREE(p_i); } } p_i = ALLOC(sizeof(*p_i)); *p_i = value; Matrix_put(p_matrix, row, col, (Object_T) p_i); } static void matrix_get_int(Matrix_T* p_matrix, int row, int col, int* p_value__) { int *p_i; if (!Matrix_get(p_matrix, row, col, (Object_T*) &p_i)) *p_value__ = 0; else *p_value__ = *p_i; } /* ______________________________________________________________________________ */ TEST simple_test(void) { Matrix_T matrix = Matrix_new(); int value = 42; matrix_put_int(&matrix, 5, 5, value); int saved; matrix_get_int(&matrix, 5, 5, &saved); ASSERT_EQ(value, saved); PASS(); } GREATEST_MAIN_DEFS(); int main(int argc, char** argv) { GREATEST_MAIN_BEGIN(); RUN_TEST(simple_test); GREATEST_MAIN_END(); }
#!/usr/bin/python -tt # -*- coding: utf-8 -*- """ Imports """ from lxml import html import requests import json import datetime import os import time import sys """ Set UTF-8 for everything. """ reload(sys) sys.setdefaultencoding("utf-8") # Establish Base URL. base_url = 'https://obamawhitehouse.archives.gov' # Establish all pages to scrape. pages = { "/briefing-room/speeches-and-remarks": "Speeches and Remarks", "/briefing-room/press-briefings": "Press Briefings", "/briefing-room/statements-and-releases": "Statements and Releases", "/briefing-room/presidential-actions/executive-orders": "Executive Orders", "/briefing-room/presidential-actions/presidential-memoranda": "Presidential Memoranda", "/briefing-room/presidential-actions/proclamations": "Proclamations", "/briefing-room/presidential-actions/related-omb-material": "Related OMB Material", "/briefing-room/pending-legislation": "Pending Legislation", "/briefing-room/signed-legislation": "Signed Legislation", "/briefing-room/vetoed-legislation": "Vetoed Legislation", "/briefing-room/statements-administration-policy": "Statements of Administration Policy", "/briefing-room/weekly-address": "Your Weekly Address" } # Scrape each page. for key, value in pages.iteritems(): # Make request and transform into tree. page_url = base_url + key response = requests.get(page_url) tree = html.document_fromstring(response.text) # Deterimine number of total pages. pagecount = int(tree.xpath('//li[@class="pager-current"]')[0].text_content().split(' of ')[1]) if len(tree.xpath('//li[@class="pager-current"]')) > 0 else 1 # Keep iterating through pages until you reach a page that has been fully scraped. Then stop. for i in range(0, pagecount): # Use ?page= parameter to scrape, starting with page 0. response = requests.get(page_url) tree = html.document_fromstring(response.text) # Build the resulting dictionary objects for each document on that page. try: objects = [{ "document_date": (x.xpath('div[contains(@class, "views-field-created")]')[0].text_content().strip(" ") if len(x.xpath('div[contains(@class, "views-field-created")]')) > 0 else (x.xpath('div')[0].text_content().split(' on ')[1] if len(x.xpath('div')) > 0 else None)), "title": x.xpath('div[contains(@class, "views-field-title")]')[0].text_content().strip(), # "uri": x.xpath('div[contains(@class, "views-field-title")]')[0].xpath('h3')[0].xpath('a')[0].attrib['href'].strip(), "category_slug": key, "category_name": value, "url": base_url + x.xpath('div[contains(@class, "views-field-title")]')[0].xpath('h3')[0].xpath('a')[0].attrib['href'].strip() } for x in tree.xpath('//div[contains(@class, "views-row")]')] except Exception as e: pass for element in objects: try: response = requests.get(element['url']) ctree = html.document_fromstring(response.text) content = ctree.xpath('//div[@id="content-start"]')[0].xpath('div')[-1] element['content'] = content.text_content().decode('utf-8').replace("\n", " ").replace("\t", "").replace(u"\u00a0", "").strip() # [x.strip().replace(" ", " ") for x in tree.xpath('//div[@id="content-start"]')[0].xpath('div')[-1].text_content().decode('utf-8').replace("\n", " ").replace("\t", "").replace(u"\u00a0", "").strip().split(" ") if len(x) > 0] if len(tree.xpath('//div[@id="content-start"]')) > 0 else None except Exception as e: element['content'] = None print json.dumps(element) pager = tree.xpath('//li[contains(@class, "pager-next")]') try: page_url = base_url + pager[0].xpath('a')[0].attrib['href'] except Exception as e: pass
const j = require('jscodeshift').withParser('babylon') const isChildJSXElement = require('./isChildJSXElement') module.exports = function wrapWithJSXElement({ root, filter = () => true }) { const element = root .find(j.JSXElement) .filter(filter) .at(0) const path = element.paths()[0] const { node } = path if (!isChildJSXElement(path) && node.children.length > 1) { node.openingElement = j.jsxOpeningElement( j.jsxMemberExpression( j.jsxIdentifier('React'), j.jsxIdentifier('Fragment') ), [], false ) node.closingElement = j.jsxClosingElement( j.jsxMemberExpression( j.jsxIdentifier('React'), j.jsxIdentifier('Fragment') ) ) } else { element.replaceWith(path => path.node.children) } }
/// <reference types="Cypress" /> var opensphere = require('../../support/selectors/opensphere.js'); var dialogs = require('../../support/selectors/dialogs.js'); var imports = require('../../support/selectors/imports.js'); var layers = require('../../support/selectors/layers.js'); var shared = require('../../support/selectors/shared.js'); describe('Import state file', function() { before('Login', function() { cy.login(); cy.server(); cy.route('**/geoserver/wfs?SERVICE=WFS**', 'fx:/smoke-tests/load-state-file-geoserver/wfsservice.stub.xml') .as('getLayer'); cy.route('POST', '**/geoserver/wfs', 'fx:/smoke-tests/load-state-file-geoserver/wfs.stub.json') .as('getFeatures'); }); it('Load data from state file', function() { // Setup cy.get(opensphere.Toolbar.Date.INPUT).should('not.have.value', '2019-01-27'); cy.get(opensphere.Map.MAP_MODE_BUTTON).should('contain', '2D'); cy.get(opensphere.statusBar.COORDINATES_TEXT).should('contain', 'No coordinate'); cy.get(layers.Dialog.DIALOG).should('not.contain', 'VIIRS Detection Features'); cy.get(layers.Dialog.DIALOG).should('not.contain', 'VIIRS Detection Tiles'); cy.get(layers.areasTab.TAB).click(); cy.get(layers.Dialog.DIALOG).should('not.contain', 'test exclude area'); cy.get(layers.Dialog.DIALOG).should('not.contain', 'test include area'); cy.get(layers.filtersTab.TAB).click(); cy.get(layers.Dialog.DIALOG).should('contain', 'No results'); cy.get(layers.layersTab.TAB).click(); // Test cy.get(opensphere.Toolbar.addData.OPEN_FILE_BUTTON).click(); cy.get(imports.importDataDialog.DIALOG).should('be.visible'); cy.upload('smoke-tests/load-state-file-geoserver/test-state-geoserver_state.xml'); cy.get(imports.importDataDialog.NEXT_BUTTON).click(); cy.get(imports.importStateDialog.DIALOG).should('be.visible'); cy.get(imports.importStateDialog.CLEAR_CHECKBOX).check(); cy.get(imports.importStateDialog.OK_BUTTON).click(); cy.get(opensphere.Toolbar.Date.INPUT).should('have.value', '2019-01-27'); cy.get(opensphere.Map.MAP_MODE_BUTTON).should('contain', '2D'); cy.get(opensphere.Application.PAGE).trigger('mouseenter').trigger('mousemove'); cy.get(opensphere.statusBar.COORDINATES_TEXT).should('contain', '+016'); cy.get(shared.Tree.ROW_4) .should('contain', 'VIIRS Detection Features (19)'); cy.imageComparison('features loaded'); cy.get(shared.Tree.ROW_4).rightClick(); cy.get(layers.layersTab.Tree.contextMenu.FEATURE_ACTIONS).click(); cy.get(dialogs.featureActionsDialog.DIALOG).should('be.visible'); cy.get(dialogs.featureActionsDialog.DIALOG).should('contain', 'high confidence'); cy.get(dialogs.featureActionsDialog.DIALOG_CLOSE).click(); cy.get(layers.areasTab.TAB).click(); cy.get(shared.Tree.ROW_1).should('contain', 'test exclude area'); cy.get(shared.Tree.ROW_2).should('contain', 'test include area'); }); });
# Generated by Django 2.2.5 on 2019-10-27 18:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('neigh1', '0016_auto_20191027_2027'), ] operations = [ migrations.AddField( model_name='bussines', name='bussiness_photo', field=models.ImageField(default='bussiness_pics/no-photo.jpg', upload_to='bussiness_pics/'), ), ]
OC.L10N.register( "comments", { "Cancel" : "Batal" }, "nplurals=1; plural=0;");
import { SimpleIntervalJob, Task } from 'toad-scheduler'; import datalayer from '../datalayer'; import dotenv from 'dotenv'; import cliSpinner from 'cli-spinner'; import { assertDataLayerAvailable, assertWalletIsSynced, } from '../utils/data-assertions'; import { logger } from '../config/logger.cjs'; const Spinner = cliSpinner.Spinner; dotenv.config(); logger.info('climate-warehouse:task:sync-datalayer'); const spinner = new Spinner('Waiting for Updates %s'); spinner.setSpinnerString('|/-\\'); spinner.setSpinnerDelay(500); const task = new Task('sync-datalayer', async () => { try { await assertDataLayerAvailable(); await assertWalletIsSynced(); spinner.stop(); spinner.start(); datalayer.startDataLayerUpdatePolling(); } catch (error) { logger.error('Retrying in 60 seconds', error); } }); let seconds = 5; if (process.env.NODE_ENV !== 'test') { seconds = 60; } const job = new SimpleIntervalJob( { seconds, runImmediately: true }, task, 'sync-datalayer', ); export default job;
import fetch from '../utils/fetch'; const rawUploadFile = process.browser ? require('./adapters/browser').default : require('./adapters/node').default; const wait = ms => new Promise(r => setTimeout(r, ms)); const imageFormats = ['png', 'jpg', 'jpeg', 'gif']; const retryOperation = (operation, delay, times) => new Promise((resolve, reject) => { return operation() .then(resolve) .catch((reason) => { if (times - 1 > 0) { return wait(delay) .then(retryOperation.bind(null, operation, delay, times - 1)) .then(resolve) .catch(reject); } return reject(reason); }); }); const fetchJson = url => fetch(url).then((res) => { if (res.status === 200) { return res.json(); } throw res.status; }); export default function uploadFile(client, source) { return rawUploadFile(client, source) .then((hash) => { if (imageFormats.indexOf(hash.format) < 0) { return Promise.resolve( Object.assign({ width: null, height: null }, hash), ); } return retryOperation( fetchJson.bind(null, `https://www.datocms-assets.com${hash.path}?fm=json`), 500, 5, ).then(({ PixelHeight, PixelWidth }) => { return Object.assign( { height: PixelHeight, width: PixelWidth }, hash, ); }); }).then((attributes) => { return client.uploads.create( Object.assign( { alt: '', title: '' }, attributes, ), ); }).then((upload) => { return Promise.resolve(upload.id); }); }
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import argparse import json import logging import mock import os import requests import tempfile import yaml from tests import base from st2client import shell LOG = logging.getLogger(__name__) KEYVALUE = { 'id': 'kv_name', 'name': 'kv_name.', 'value': 'super cool value', 'scope': 'system' } KEYVALUE_USER = { 'id': 'kv_name', 'name': 'kv_name.', 'value': 'super cool value', 'scope': 'system', 'user': 'stanley' } KEYVALUE_SECRET = { 'id': 'kv_name', 'name': 'kv_name.', 'value': 'super cool value', 'scope': 'system', 'secret': True } KEYVALUE_PRE_ENCRYPTED = { 'id': 'kv_name', 'name': 'kv_name.', 'value': 'AAABBBCCC1234', 'scope': 'system', 'encrypted': True, 'secret': True } KEYVALUE_TTL = { 'id': 'kv_name', 'name': 'kv_name.', 'value': 'super cool value', 'scope': 'system', 'ttl': 100 } KEYVALUE_OBJECT = { 'id': 'kv_name', 'name': 'kv_name.', 'value': {'obj': [1, True, 23.4, 'abc']}, 'scope': 'system', } KEYVALUE_ALL = { 'id': 'kv_name', 'name': 'kv_name.', 'value': 'AAAAABBBBBCCCCCCDDDDD11122345', 'scope': 'system', 'user': 'stanley', 'secret': True, 'encrypted': True, 'ttl': 100 } KEYVALUE_MISSING_NAME = { 'id': 'kv_name', 'value': 'super cool value' } KEYVALUE_MISSING_VALUE = { 'id': 'kv_name', 'name': 'kv_name.' } class TestKeyValueBase(base.BaseCLITestCase): """Base class for "key" CLI tests """ capture_output = True def __init__(self, *args, **kwargs): super(TestKeyValueBase, self).__init__(*args, **kwargs) self.parser = argparse.ArgumentParser() self.parser.add_argument('-t', '--token', dest='token') self.parser.add_argument('--api-key', dest='api_key') self.shell = shell.Shell() def setUp(self): super(TestKeyValueBase, self).setUp() def tearDown(self): super(TestKeyValueBase, self).tearDown() class TestKeyValueSet(TestKeyValueBase): @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_PRE_ENCRYPTED), 200, 'OK'))) def test_set_keyvalue(self): """Test setting key/value pair with optional pre_encrypted field """ args = ['key', 'set', '--encrypted', 'kv_name', 'AAABBBCCC1234'] retcode = self.shell.run(args) self.assertEqual(retcode, 0) def test_encrypt_and_encrypted_flags_are_mutually_exclusive(self): args = ['key', 'set', '--encrypt', '--encrypted', 'kv_name', 'AAABBBCCC1234'] self.assertRaisesRegexp(SystemExit, '2', self.shell.run, args) self.stderr.seek(0) stderr = self.stderr.read() expected_msg = ('error: argument --encrypted: not allowed with argument -e/--encrypt') self.assertIn(expected_msg, stderr) class TestKeyValueLoad(TestKeyValueBase): @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE), 200, 'OK'))) def test_load_keyvalue_json(self): """Test loading of key/value pair in JSON format """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE, indent=4)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE), 200, 'OK'))) def test_load_keyvalue_yaml(self): """Test loading of key/value pair in YAML format """ fd, path = tempfile.mkstemp(suffix='.yaml') try: with open(path, 'a') as f: f.write(yaml.safe_dump(KEYVALUE)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_USER), 200, 'OK'))) def test_load_keyvalue_user(self): """Test loading of key/value pair with the optional user field """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_USER, indent=4)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_SECRET), 200, 'OK'))) def test_load_keyvalue_secret(self): """Test loading of key/value pair with the optional secret field """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_SECRET, indent=4)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_PRE_ENCRYPTED), 200, 'OK'))) def test_load_keyvalue_already_encrypted(self): """Test loading of key/value pair with the pre-encrypted value """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_PRE_ENCRYPTED, indent=4)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_TTL), 200, 'OK'))) def test_load_keyvalue_ttl(self): """Test loading of key/value pair with the optional ttl field """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_TTL, indent=4)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_OBJECT), 200, 'OK'))) def test_load_keyvalue_object(self): """Test loading of key/value pair where the value is an object """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_OBJECT, indent=4)) # test converting with short option args = ['key', 'load', '-c', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) # test converting with long option args = ['key', 'load', '--convert', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_OBJECT), 200, 'OK'))) def test_load_keyvalue_object_fail(self): """Test failure to load key/value pair where the value is an object and the -c/--convert option is not passed """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_OBJECT, indent=4)) # test converting with short option args = ['key', 'load', path] retcode = self.shell.run(args) self.assertNotEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_ALL), 200, 'OK'))) def test_load_keyvalue_all(self): """Test loading of key/value pair with all optional fields """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_ALL, indent=4)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) @mock.patch.object( requests, 'put', mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE_ALL), 200, 'OK'))) def test_load_keyvalue_array(self): """Test loading an array of key/value pairs """ fd, path = tempfile.mkstemp(suffix='.json') try: array = [KEYVALUE, KEYVALUE_ALL] json_str = json.dumps(array, indent=4) LOG.info(json_str) with open(path, 'a') as f: f.write(json_str) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path) def test_load_keyvalue_missing_name(self): """Test loading of a key/value pair with the required field 'name' missing """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_MISSING_NAME, indent=4)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 1) finally: os.close(fd) os.unlink(path) def test_load_keyvalue_missing_value(self): """Test loading of a key/value pair with the required field 'value' missing """ fd, path = tempfile.mkstemp(suffix='.json') try: with open(path, 'a') as f: f.write(json.dumps(KEYVALUE_MISSING_VALUE, indent=4)) args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 1) finally: os.close(fd) os.unlink(path) def test_load_keyvalue_missing_file(self): """Test loading of a key/value pair with a missing file """ path = '/some/file/that/doesnt/exist.json' args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 1) def test_load_keyvalue_bad_file_extension(self): """Test loading of a key/value pair with a bad file extension """ fd, path = tempfile.mkstemp(suffix='.badext') try: args = ['key', 'load', path] retcode = self.shell.run(args) self.assertEqual(retcode, 1) finally: os.close(fd) os.unlink(path) def test_load_keyvalue_empty_file(self): """ Loading K/V from an empty file shouldn't throw an error """ fd, path = tempfile.mkstemp(suffix='.yaml') try: args = ['key', 'load', path] retcode = self.shell.run(args) self.assertIn('No matching items found', self.stdout.getvalue()) self.assertEqual(retcode, 0) finally: os.close(fd) os.unlink(path)
""" Task pool is responsible for receiving tasks and grouping them together for processing (but not processing itself) """ import ctypes import multiprocessing as mp import os import threading import time from abc import ABCMeta, abstractmethod from collections import namedtuple from concurrent.futures import Future from queue import Empty from typing import List, Tuple, Dict, Any, Generator import torch from hivemind.utils import MPFuture, get_logger, FutureStateError logger = get_logger(__name__) Task = namedtuple("Task", ("future", "args")) class TaskPoolBase(mp.context.ForkProcess, metaclass=ABCMeta): """ A pool that accepts tasks and forms batches for parallel processing, interacts with Runtime """ def __init__(self, process_func: callable, daemon=True, **kwargs): super().__init__(daemon=daemon, **kwargs) self.process_func = process_func self._priority = mp.Value(ctypes.c_double, 1.0) # higher priority = the more urgent to process this pool @abstractmethod def run(self): pass @abstractmethod def submit_task(self, *args: torch.Tensor) -> Future: pass @abstractmethod def iterate_minibatches(self, *args, **kwargs) -> Generator[List[Task], None, None]: pass @property def priority(self): return self._priority.value @priority.setter def priority(self, value): self._priority.value = float(value) @property @abstractmethod def empty(self): pass class TaskPool(TaskPoolBase): """ Request aggregator that accepts processing requests, groups them into batches, waits for Runtime to process these batches and dispatches results back to request sources. Operates as a background process. :param process_func: function to be applied to every formed batch; called by Runtime Note that process_func should accept only positional args (Tensors) and return a flat tuple of Tensors :param max_batch_size: process at most this many inputs in a batch (task contains have one or several inputs) :param name: pool name :param min_batch_size: process at least this many inputs in a batch, otherwise wait for more :param timeout: wait for a subsequent task for at most this many seconds :param pool_size: store at most this many unprocessed tasks in a queue :param prefetch_batches: prepare up to this many *batches* in background for faster off-loading to runtime :param start: if True, start automatically at the end of __init__ """ def __init__(self, process_func: callable, max_batch_size: int, name: str, min_batch_size=1, timeout=None, pool_size=None, prefetch_batches=1, daemon=True, start=False): super().__init__(process_func, daemon=daemon, name=name) self.min_batch_size, self.max_batch_size, self.timeout = min_batch_size, max_batch_size, timeout self.prefetch_batches = prefetch_batches # interaction with ConnectionHandlers self.tasks = mp.Queue(maxsize=pool_size or 0) self.undispatched_task_timestamps = mp.SimpleQueue() # interaction with Runtime self.batch_receiver, self.batch_sender = mp.Pipe(duplex=False) # send/recv arrays that contain batch inputs self.outputs_receiver, self.outputs_sender = mp.Pipe(duplex=False) # send/recv arrays that contain outputs if start: self.start() def submit_task(self, *args: torch.Tensor) -> Future: """ Add task to this pool's queue, return Future for its output """ future1, future2 = MPFuture.make_pair() task = Task(future1, args) if self.get_task_size(task) > self.max_batch_size: exc = ValueError(f"Task size greater than max_batch_size ({self.max_batch_size}), it can't be processed") future2.set_exception(exc) else: self.tasks.put(task) self.undispatched_task_timestamps.put(time.time()) return future2 def iterate_minibatches(self, *args, **kwargs): """ Form minibatches by grouping one or more tasks together up to self.max_batch_size """ batch = [] total_size = 0 while True: if total_size >= self.min_batch_size and self.tasks.empty(): yield batch batch = [] total_size = 0 try: logger.debug(f"{self.name} getting next task") task = self.tasks.get(timeout=self.timeout) except Empty: logger.warning(f"Timeout reached but batch doesn't contain >={self.min_batch_size} elements yet") continue task_size = self.get_task_size(task) if total_size + task_size > self.max_batch_size: yield batch batch = [] total_size = 0 try: if task.future.set_running_or_notify_cancel(): batch.append(task) total_size += task_size except FutureStateError as e: logger.debug(f"Failed to add task to batch: {task.future} raised {e}") def run(self, *args, **kwargs): torch.set_num_threads(1) logger.info(f'{self.name} starting, pid={os.getpid()}') pending_batches = {} # Dict[batch uuid, List[MPFuture]] for each batch currently in runtime output_thread = threading.Thread(target=self._pool_output_loop, args=[pending_batches], name=f'{self.name}_output', daemon=True) try: output_thread.start() self._pool_input_loop(pending_batches, *args, **kwargs) except KeyboardInterrupt: logger.debug('Caught KeyboardInterrupt, shutting down') finally: output_thread.join() def _pool_input_loop(self, pending_batches: Dict[Any, List[Task]], *args, **kwargs): """ Infinite loop: aggregate tasks into batches and send them to runtime """ prev_num_tasks = 0 # number of tasks currently in shared buffer batch_index = max(pending_batches.keys(), default=0) batch_iterator = self.iterate_minibatches(*args, **kwargs) while True: # SIDE-EFFECT - compute pool priority from timestamp of earliest undispatched task # assumes that tasks are processed in the same order as they are created for skip_i in range(prev_num_tasks): finished_task_timestamp = self.undispatched_task_timestamps.get() # earlier timestamp = higher priority if skip_i == prev_num_tasks - 1: self.priority = finished_task_timestamp logger.debug(f"{self.name} getting next batch") batch_tasks = next(batch_iterator) # save batch futures, _output_loop will deliver on them later pending_batches[batch_index] = batch_tasks logger.debug(f"{self.name}, batch {batch_index}: aggregating inputs") # find or create shared arrays for current batch size batch_inputs = [torch.cat([task.args[i] for task in batch_tasks]) for i in range(len(batch_tasks[0].args))] batch_inputs = [inp.detach().requires_grad_(inp.requires_grad).share_memory_() for inp in batch_inputs] logger.debug(f"{self.name}, batch {batch_index}: sending to runtime") self.batch_sender.send((batch_index, batch_inputs)) logger.debug(f"{self.name}, batch {batch_index}: sent to runtime") prev_num_tasks = len(batch_tasks) batch_index += 1 def _pool_output_loop(self, pending_batches: Dict[Any, List[Task]]): """ Infinite loop: receive results from runtime and dispatch them to task Futures """ while True: logger.debug(f"{self.name} waiting for results from runtime") batch_index, batch_outputs = self.outputs_receiver.recv() logger.debug(f"{self.name}, batch {batch_index}: got results") # split batch into partitions for individual tasks batch_tasks = pending_batches.pop(batch_index) task_sizes = [self.get_task_size(task) for task in batch_tasks] outputs_per_task = zip(*(torch.split_with_sizes(tensor, task_sizes, dim=0) for tensor in batch_outputs)) logger.debug(f"{self.name}, batch {batch_index}: sending outputs to handlers") # dispatch results to futures for task, task_outputs in zip(batch_tasks, outputs_per_task): try: task.future.set_result(tuple(task_outputs)) except FutureStateError as e: logger.debug(f"Failed to send task result due to an exception: {e}") @property def empty(self): return not self.batch_receiver.poll() def load_batch_to_runtime(self, timeout=None, device=None) -> Tuple[Any, List[torch.Tensor]]: """ receive next batch of numpy arrays """ if not self.batch_receiver.poll(timeout): raise TimeoutError() batch_index, batch_inputs = self.batch_receiver.recv() batch_inputs = [tensor.to(device, non_blocking=True) for tensor in batch_inputs] return batch_index, batch_inputs def send_outputs_from_runtime(self, batch_index: int, batch_outputs: List[torch.Tensor]): """ send results for a processed batch, previously loaded through load_batch_to_runtime """ batch_outputs = [tensor.to(device='cpu').share_memory_().detach().requires_grad_(tensor.requires_grad) for tensor in batch_outputs] self.outputs_sender.send((batch_index, batch_outputs)) def get_task_size(self, task: Task) -> int: """ compute task processing complexity (used for batching); defaults to batch size """ return len(task.args[0]) if task.args else 1
/** * @Package: Ultra Admin HTML Theme * @Since: Ultra 1.0 * This file is part of Ultra Admin Theme HTML package. */ jQuery(function($) { 'use strict'; var ULTRA_SETTINGS = window.ULTRA_SETTINGS || {}; /*-------------------------------- Sparkline Chart --------------------------------*/ ULTRA_SETTINGS.chartSparkline = function() { if ($.isFunction($.fn.sparkline)) { var myvalues = [10, 8, 5, 7, 4, 4, 7, 5, 2, 8, 3, 4, 5]; var sidebargraph1 = [7, 6, 4, 7, 5, 3, 5, 7, 3, 4]; var sidebargraph2 = [4, 7, 5, 5, 7, 3, 5, 7, 4, 2]; $('.inlinesparkline').sparkline(myvalues, { type: 'line', width: '100%', height: '200', lineWidth: 2, lineColor: '#1fb5ac', fillColor: 'rgba(31,181,172,0.5)', highlightSpotColor: '#fa8564', highlightLineColor: '#9972b5', spotRadius: 4, }); /* The second argument gives options such as specifying you want a bar chart */ $('.dynamicbar').sparkline(myvalues, { type: 'bar', barColor: '#1fb5ac', height: '200', barWidth: '18', barSpacing: 2 }); // Bar charts using inline values $('.negativebar').sparkline([8, 4, 3, 0, -2, -6, -3, 3, -2, 4, 6, -4, 4], { type: 'bar', barColor: '#1fb5ac', height: '200', barWidth: '18', barSpacing: 2, zeroAxis: true, negBarColor: '#fa8564', zeroColor: '#9972b5' }); // Bar charts using inline values $('.stackedbar').sparkline([ [1, 2, 2], [2, 4, 3], [4, 2, 4], [4, 5, 1], [4, 1, 2], [6, 6, 4], [2, 3, 2], [3, 2, 6], [2, 0, 2], [6, 2, 4], [7, 4, 2], [3, 4, 1], [3, 7, 4] ], { type: 'bar', barColor: '#1fb5ac', height: '200', barWidth: '18', barSpacing: 2, zeroAxis: true, negBarColor: '#fa8564', zeroColor: '#9972b5', stackedBarColor: ['#9972b5', '#1fb5ac', '#fa8564'], }); // sidebar bottom graphs $('.sidebar_orders').sparkline(sidebargraph1, { type: 'bar', barColor: '#1fb5ac', height: '20', barWidth: '4', barSpacing: 1, }); $('.sidebar_visitors').sparkline(sidebargraph2, { type: 'bar', barColor: '#fa8564', height: '20', barWidth: '4', barSpacing: 1, }); $('.playlist_song1').sparkline(sidebargraph1, { type: 'bar', barColor: '#9972b5', height: '20', barWidth: '4', barSpacing: 1, }); $('.playlist_song2').sparkline(sidebargraph2, { type: 'bar', barColor: '#fa8564', height: '20', barWidth: '4', barSpacing: 1, }); $('.playlist_song3').sparkline(sidebargraph1, { type: 'bar', barColor: '#1fb5ac', height: '20', barWidth: '4', barSpacing: 1, }); $('.playlist_song4').sparkline(sidebargraph2, { type: 'bar', barColor: '#9972b5', height: '20', barWidth: '4', barSpacing: 1, }); $('.playlist_song5').sparkline(sidebargraph1, { type: 'bar', barColor: '#1fb5ac', height: '20', barWidth: '4', barSpacing: 1, }); $('.playlist_song6').sparkline(sidebargraph2, { type: 'bar', barColor: '#fa8564', height: '20', barWidth: '4', barSpacing: 1, }); $('.playlist_song7').sparkline(sidebargraph1, { type: 'bar', barColor: '#1fb5ac', height: '20', barWidth: '4', barSpacing: 1, }); // Bar + line composite charts $('#compositebar').sparkline([4, 6, 7, 7, 4, 3, 2, 3, 1, 4, 6, 5, 9], { type: 'bar', barColor: '#1fb5ac', height: '200', barWidth: '18', barSpacing: 2, }); $('#compositebar').sparkline([4, 1, 5, 7, 9, 9, 8, 8, 4, 2, 5, 6, 7], { composite: true, fillColor: 'rgba(153,114,181,0.3)', type: 'line', width: '100%', height: '200', lineWidth: 2, lineColor: '#9972b5', highlightSpotColor: '#fa8564', highlightLineColor: '#9972b5', spotRadius: 4, }); // Line charts taking their values from the tag $('.sparkline').sparkline(); // Larger line charts for the docs $('.largeline').sparkline('html', { type: 'line', height: '2.5em', width: '4em' }); // Customized line chart $('#linecustom').sparkline('html', { height: '1.5em', width: '8em', lineColor: '#f00', fillColor: '#ffa', minSpotColor: false, maxSpotColor: false, spotColor: '#77f', spotRadius: 3 }); $('.barformat').sparkline([1, 3, 5, 3, 8], { type: 'bar', tooltipFormat: '{{value:levels}} - {{value}}', tooltipValueLookups: { levels: $.range_map({ ':2': 'Low', '3:6': 'Medium', '7:': 'High' }) } }); // Tri-state charts using inline values $('.sparktristate').sparkline([1, 1, 0, 1, -1, -1, 1, -1, 0, 0, 1, 1], { type: 'tristate', height: '200', posBarColor: '#1fb5ac', negBarColor: '#fa8564', zeroBarColor: '#9972b5', barWidth: 20, barSpacing: 2, zeroAxis: true }); // Composite line charts, the second using values supplied via javascript $('#compositeline').sparkline([8, 4, 1, 2, 6, 7, 1, 6, 2, 4, 3, 5, 6, 0, 3, 0, 4, 6, 5, 7, 6], { fillColor: false, changeRangeMin: 0, chartRangeMax: 10, type: 'line', width: '100%', height: '200', lineWidth: 2, lineColor: '#1fb5ac', highlightSpotColor: '#fa8564', highlightLineColor: '#9972b5', spotRadius: 4, }); $('#compositeline').sparkline([4, 1, 5, 4, 6, 7, 3, 5, 6, 6, 4, 2, 6, 4, 3, 2, 2, 5, 6, 3], { composite: true, fillColor: false, changeRangeMin: 0, chartRangeMax: 10, type: 'line', width: '100%', height: '200', lineWidth: 2, lineColor: '#9972b5', highlightSpotColor: '#fa8564', highlightLineColor: '#9972b5', spotRadius: 4, }); // Line charts with normal range marker $('#normalline').sparkline([5, 4, 0, 0, 0, 0, 1, 4, 4, 10, 10, 10, 10, 0, 0, 0, 4, 6, 5, 9, 10], { fillColor: false, normalRangeMin: -1, normalRangeMax: 8, type: 'line', width: '100%', height: '200', lineWidth: 2, lineColor: '#9972b5', highlightSpotColor: '#fa8564', highlightLineColor: '#9972b5', normalRangeColor: '#eaeaea', spotRadius: 4, }); $('#normalExample').sparkline('html', { fillColor: false, normalRangeMin: 80, normalRangeMax: 95, normalRangeColor: '#4f4' }); // Discrete charts $('.discrete1').sparkline([4, 6, 7, 7, 4, 3, 2, 1, 4, 4, 5, 6, 7, 6, 6, 2, 4, 5, 4, 4, 5, 6, 7, 6, 6, 2, 4, 5, 2, 1, 4, 4], { type: 'discrete', width: '280', height: '200', lineColor: '#1fb5ac', lineHeight: 60, thresholdValue: 5, thresholdColor: '#fa8564', }); // Bullet charts $('.sparkbullet').sparkline([10, 12, 12, 9, 7], { type: 'bullet', height: '200', width: '100%', targetWidth: 10, targetColor: '#FDB45C', performanceColor: '#eaeaea', rangeColors: ['#1fb5ac', '#9972b5', '#fa8564 '] }); // Pie charts $('.sparkpie').sparkline([3, 4, 1, 2], { type: 'pie', width: '100%', height: '200', sliceColors: ['#1fb5ac', '#9972b5', '#fa8564', '#FDB45C'], offset: 0, borderWidth: 0, borderColor: '#00007f' }); $(".sparkboxplot").sparkline([4, 27, 34, 52, 54, 59, 61, 68, 78, 82, 85, 87, 91, 93, 100], { type: 'box', width: '100%', height: '200', raw: false, target: 27, minValue: 34, boxLineColor: '#9972b5', boxFillColor: '#1fb5ac', whiskerColor: '#fa8564', medianColor: '#fa8564', targetColor: '#fa8564' }); } }; /****************************** initialize respective scripts *****************************/ $(document).ready(function() { ULTRA_SETTINGS.chartSparkline(); }); $(window).resize(function() {}); $(window).load(function() {}); });
from mujoco_py import load_model_from_path, MjSim, MjViewer import os import gym import time import numpy as np from world import World import car import dynamics import visualize import lane class Simulation(object): def __init__(self, name, total_time=1000, recording_time=[0,1000]): self.name = name.lower() self.total_time = total_time self.recording_time = [max(0,recording_time[0]), min(total_time,recording_time[1])] self.frame_delay_ms = 0 def reset(self): self.trajectory = [] self.alreadyRun = False self.ctrl_array = [[0]*self.input_size]*self.total_time @property def ctrl(self): return self.ctrl_array @ctrl.setter def ctrl(self, value): self.reset() self.ctrl_array = value.copy() self.run(reset=False) class MujocoSimulation(Simulation): def __init__(self, name, total_time=1000, recording_time=[0,1000]): super(MujocoSimulation, self).__init__(name, total_time=total_time, recording_time=recording_time) self.model = load_model_from_path('mujoco_xmls/' + name + '.xml') self.sim = MjSim(self.model) self.initial_state = self.sim.get_state() self.input_size = len(self.sim.data.ctrl) self.reset() self.viewer = None def reset(self): super(MujocoSimulation, self).reset() self.sim.set_state(self.initial_state) def run(self, reset=True): if reset: self.reset() self.sim.set_state(self.initial_state) for i in range(self.total_time): self.sim.data.ctrl[:] = self.ctrl_array[i] self.sim.step() self.trajectory.append(self.sim.get_state()) self.alreadyRun = True def get_trajectory(self, all_info=True): if not self.alreadyRun: self.run() if all_info: return self.trajectory.copy() else: return [x.qpos for x in self.trajectory] def get_recording(self, all_info=True): traj = self.get_trajectory(all_info=all_info) return traj[self.recording_time[0]:self.recording_time[1]] def watch(self, repeat_count=4): if self.viewer is None: self.viewer = MjViewer(self.sim) for _ in range(repeat_count): self.sim.set_state(self.initial_state) for i in range(self.total_time): self.sim.data.ctrl[:] = self.ctrl_array[i] self.sim.step() self.viewer.render() self.run(reset=False) # so that the trajectory will be compatible with what user watches class GymSimulation(Simulation): def __init__(self, name, total_time=200, recording_time=[0,200]): super(GymSimulation, self).__init__(name, total_time=total_time, recording_time=recording_time) self.sim = gym.make(name) self.seed_value = 0 self.reset_seed() self.sim.reset() self.done = False self.initial_state = None self.input_size = len(self.sim.action_space.low) self.effective_total_time = total_time self.effective_recording_time = recording_time.copy() # child class will call reset(), because it knows what state_size is def reset(self): super(GymSimulation, self).reset() self.state = self.initial_state def run(self, reset=False): # I keep reset variable for the compatilibity with mujoco wrapper self.state = self.initial_state self.trajectory = [] for i in range(self.total_time): temp = self.sim.step(np.array(self.ctrl_array[i])) self.done = temp[2] self.trajectory.append(self.state) if self.done: break self.effective_total_time = len(self.trajectory) self.effective_recording_time[1] = min(self.effective_total_time, self.recording_time[1]) self.alreadyRun = True # I keep all_info variable for the compatibility with mujoco wrapper def get_trajectory(self, all_info=True): if not self.alreadyRun: self.run() return self.trajectory.copy() def get_recording(self, all_info=True): traj = self.get_trajectory(all_info=all_info) return traj[self.effective_recording_time[0]:self.effective_recording_time[1]] def watch(self, repeat_count=4): for _ in range(repeat_count): self.state = self.initial_state for i in range(self.total_time): temp = self.sim.step(np.array(self.ctrl_array[i])) self.sim.render() time.sleep(self.frame_delay_ms/1000.0) self.done = temp[2] if self.done: break self.run() # so that the trajectory will be compatible with what user watches #self.sim.close() # this thing prevents any further viewing, pff. def close(self): # run only when you dont need the simulation anymore self.sim.close() @property def seed(self): return self.seed_value @seed.setter def seed(self, value=0): self.seed_value = value self.sim.seed(self.seed_value) def reset_seed(self): self.sim.seed(self.seed_value) class DrivingSimulation(Simulation): def __init__(self, name, total_time=50, recording_time=[0,50]): super(DrivingSimulation, self).__init__(name, total_time=total_time, recording_time=recording_time) self.world = World() clane = lane.StraightLane([0., -1.], [0., 1.], 0.17) self.world.lanes += [clane, clane.shifted(1), clane.shifted(-1)] self.world.roads += [clane] self.world.fences += [clane.shifted(2), clane.shifted(-2)] self.dyn = dynamics.CarDynamics(0.1) self.robot = car.Car(self.dyn, [0., -0.3, np.pi/2., 0.4], color='orange') self.human = car.Car(self.dyn, [0.17, 0., np.pi/2., 0.41], color='white') self.world.cars.append(self.robot) self.world.cars.append(self.human) self.initial_state = [self.robot.x, self.human.x] self.input_size = 2 self.reset() self.viewer = None def initialize_positions(self): self.robot_history_x = [] self.robot_history_u = [] self.human_history_x = [] self.human_history_u = [] self.robot.x = self.initial_state[0] self.human.x = self.initial_state[1] def reset(self): super(DrivingSimulation, self).reset() self.initialize_positions() def run(self, reset=False): if reset: self.reset() else: self.initialize_positions() for i in range(self.total_time): self.robot.u = self.ctrl_array[i] if i < self.total_time//5: self.human.u = [0, self.initial_state[1][3]] elif i < 2*self.total_time//5: self.human.u = [1., self.initial_state[1][3]] elif i < 3*self.total_time//5: self.human.u = [-1., self.initial_state[1][3]] elif i < 4*self.total_time//5: self.human.u = [0, self.initial_state[1][3]*1.3] else: self.human.u = [0, self.initial_state[1][3]*1.3] self.robot_history_x.append(self.robot.x) self.robot_history_u.append(self.robot.u) self.human_history_x.append(self.human.x) self.human_history_u.append(self.human.u) self.robot.move() self.human.move() self.trajectory.append([self.robot.x, self.human.x]) self.alreadyRun = True # I keep all_info variable for the compatibility with mujoco wrapper def get_trajectory(self, all_info=True): if not self.alreadyRun: self.run() return self.trajectory.copy() def get_recording(self, all_info=True): traj = self.get_trajectory(all_info=all_info) return traj[self.recording_time[0]:self.recording_time[1]] def watch(self, repeat_count=1): self.robot.x = self.initial_state[0] self.human.x = self.initial_state[1] if self.viewer is None: self.viewer = visualize.Visualizer(0.1, magnify=1.2) self.viewer.main_car = self.robot self.viewer.use_world(self.world) self.viewer.paused = True for _ in range(repeat_count): self.viewer.run_modified(history_x=[self.robot_history_x, self.human_history_x], history_u=[self.robot_history_u, self.human_history_u]) self.viewer.window.close() self.viewer = None
# %% [code] import numpy as np #import tensorflow as tf #import keras as k import pandas as pd import matplotlib.pyplot as plt import cv2 import math import os # %% [code] fps = 30 title = 'normal speed video' delay = int(100/ fps) # %% [code] X = [] count = 0 for i in range (1,1000): videoFile = "C:/Users/pratt/Desktop/RealLifeViolenceDataset/Violence/V_%d.mp4" % i cap = cv2.VideoCapture(videoFile) # capturing the video from the given path frameRate = cap.get(5) #print(frameRate) #print(cap.isOpened()) while(cap.isOpened()): #print(1) frameId = cap.get(1) #current frame number ret, frame = cap.read() if (ret != True): break if (frameId % math.floor(frameRate) == 0): X_temp = cv2.resize(frame, (64,64)) X.append(X_temp) cap.release() print(X) # %% [code] #1 for violence X = np.reshape(X, (5827, 64*64*3)) print(np.shape(X)) X = np.concatenate((X,np.ones((5827,1))), axis = 1) print(np.shape(X)) # %% [code] X2 = [] count = 0 for i in range (1,1000): videoFile = "C:/Users/pratt/Desktop/RealLifeViolenceDataset/NonViolence/NV_%d.mp4" % i cap = cv2.VideoCapture(videoFile) # capturing the video from the given path frameRate = cap.get(5) #frame rate #print(frameRate) while(cap.isOpened()): frameId = cap.get(1) #current frame number ret, frame = cap.read() if (ret != True): break if (frameId % math.floor(frameRate) == 0): X_temp = cv2.resize(frame, (64,64)) X2.append(X_temp) cap.release() # %% [code] print(np.shape(X2)) # %% [code] #0 for non-violence X2 = np.reshape(X2, (4980, 64*64*3)) print(np.shape(X2)) X2 = np.concatenate((X2,np.zeros((4980,1))), axis = 1) print(np.shape(X2)) # %% [code] X_true = np.concatenate((X,X2), axis = 0) print(np.shape(X_true)) # %% [code] np.random.shuffle(X_true) X_true = X_true.astype(int) #print(X_true) # %% [code] y_true = X_true[:, -1] print(y_true) X_true = np.delete(X_true, -1, 1) # %% [code] from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras import optimizers import keras as K from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score seed = 78 test_size = 0.33 # %% [code] X_train, X_test, y_train, y_test = train_test_split(X_true, y_true, test_size=test_size, random_state=seed) # %% [code] X_train = X_train/255 X_test = X_test/255 # %% [code] np.savetxt('C:/Users/pratt/Desktop/Y_train.csv', y_train, delimiter=',') # %% [code] from numpy import loadtxt from xgboost import XGBClassifier # %% [code] model = XGBClassifier() model.fit(X_train, y_train) # %% [code] y_pred = model.predict(X_test) predictions = [round(value) for value in y_pred] y_pred = model.predict(X_test).round() # %% [code] # evaluate predictions accuracy = accuracy_score(y_test, predictions) print("Accuracy: %.2f%%" % (accuracy * 100.0)) # %% [code] import cv2 from PIL import Image, ImageDraw, ImageFont import time ImageFont.load_default() font = ImageFont.load_default() # %% [code] videoFile = "C:/Users/pratt/Downloads/test.mp4" cap = cv2.VideoCapture(videoFile) # capturing the video from the given path frameRate = cap.get(5) i = 0 y_temp= [] deno = 0 while(cap.isOpened()): #print(1) frameId = cap.get(1) #current frame number ret, frame = cap.read() if (ret != True): break if (frameId % math.floor(frameRate) == 0): X_temp = cv2.resize(frame, (64,64)) #im = Image.fromarray(frame) #plt.figure() #plt.imshow(im) X_temp = np.reshape(X_temp, (1, 64*64*3)) X_temp = X_temp/255 y_temp.append(model.predict(X_temp)) sum = y_temp[i]#.astype(float) for k in range (1,7): if (i-k) > 0: sum = sum + ( y_temp[i-k] / (k+1)) #print(i-k) else: #print(y_temp[i]) deno = deno + (1/(k+1)) break sum = sum/deno if sum<0.5 : y_temp[i] = 0 #message = "NON-VIOLENT" else: y_temp[i] = 1 #message = "VIOLENT" #draw = ImageDraw.Draw(im) #draw.text((50, 50), message, fill=(255,255,255,128), font = font) #plt.imshow(im) i = i+1 cap.release() print(y_temp) # %% [code] from sklearn import model_selection from sklearn.linear_model import LogisticRegression import pickle #filename = 'C:/Users/pratt/Desktop/finalized_model.sav' #pickle.dump(model, open(filename, 'wb')) # some time later... # load the model from disk #loaded_model = pickle.load(open(filename, 'rb')) #result = loaded_model.score(X_test, y_test) #print(result) # %% [code] #np.savetxt('/kaggle/output/working/Y_true.csv', y_true, delimiter=',') import cv2 import numpy as np # Create a VideoCapture object and read from input file cap = cv2.VideoCapture('C:/Users/pratt/Downloads/test.mp4') # Check if camera opened successfully if (cap.isOpened()== False): print("Error opening video file") i =0 # Read until video is completed while(cap.isOpened()): # Capture frame-by-frame ret, frame = cap.read() if ret == True: font = cv2.FONT_HERSHEY_SIMPLEX # Use putText() method for # inserting text on video if (y_temp[1] == 0): cv2.putText(frame, 'NON VIOLENCE', (50, 50), font, 1, (0, 255, 255), 2, cv2.LINE_4) if (y_temp[1] == 1): cv2.putText(frame, 'VIOLENCE', (50, 50), font, 1, (0, 255, 255), 2, cv2.LINE_4) # Display the resulting frame cv2.imshow('Frame', frame) i = i+1 # Press Q on keyboard to exit if cv2.waitKey(25) & 0xFF == ord('q'): break # Break the loop else: break # When everything done, release # the video capture object cap.release() # Closes all the frames cv2.destroyAllWindows() # %% [code] #np.savetxt('/kaggle/output/working/X_true.csv', X_true, delimiter=',') import pickle pickle.dump(model, open('C:/Users/pratt/Desktop/ViolenceNonviolence.dat', 'wb'))
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from . import outputs from ._enums import * from ._inputs import * __all__ = ['NotificationChannel'] class NotificationChannel(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, description: Optional[pulumi.Input[str]] = None, email_recipient: Optional[pulumi.Input[str]] = None, events: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EventArgs']]]]] = None, lab_name: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, notification_locale: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, web_hook_url: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): """ A notification. API Version: 2018-09-15. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] description: Description of notification. :param pulumi.Input[str] email_recipient: The email recipient to send notifications to (can be a list of semi-colon separated email addresses). :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['EventArgs']]]] events: The list of event for which this notification is enabled. :param pulumi.Input[str] lab_name: The name of the lab. :param pulumi.Input[str] location: The location of the resource. :param pulumi.Input[str] name: The name of the notification channel. :param pulumi.Input[str] notification_locale: The locale to use when sending a notification (fallback for unsupported languages is EN). :param pulumi.Input[str] resource_group_name: The name of the resource group. :param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: The tags of the resource. :param pulumi.Input[str] web_hook_url: The webhook URL to send notifications to. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['description'] = description __props__['email_recipient'] = email_recipient __props__['events'] = events if lab_name is None and not opts.urn: raise TypeError("Missing required property 'lab_name'") __props__['lab_name'] = lab_name __props__['location'] = location __props__['name'] = name __props__['notification_locale'] = notification_locale if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['tags'] = tags __props__['web_hook_url'] = web_hook_url __props__['created_date'] = None __props__['provisioning_state'] = None __props__['type'] = None __props__['unique_identifier'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:devtestlab/latest:NotificationChannel"), pulumi.Alias(type_="azure-nextgen:devtestlab/v20160515:NotificationChannel"), pulumi.Alias(type_="azure-nextgen:devtestlab/v20180915:NotificationChannel")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(NotificationChannel, __self__).__init__( 'azure-nextgen:devtestlab:NotificationChannel', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'NotificationChannel': """ Get an existing NotificationChannel resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() return NotificationChannel(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="createdDate") def created_date(self) -> pulumi.Output[str]: """ The creation date of the notification channel. """ return pulumi.get(self, "created_date") @property @pulumi.getter def description(self) -> pulumi.Output[Optional[str]]: """ Description of notification. """ return pulumi.get(self, "description") @property @pulumi.getter(name="emailRecipient") def email_recipient(self) -> pulumi.Output[Optional[str]]: """ The email recipient to send notifications to (can be a list of semi-colon separated email addresses). """ return pulumi.get(self, "email_recipient") @property @pulumi.getter def events(self) -> pulumi.Output[Optional[Sequence['outputs.EventResponse']]]: """ The list of event for which this notification is enabled. """ return pulumi.get(self, "events") @property @pulumi.getter def location(self) -> pulumi.Output[Optional[str]]: """ The location of the resource. """ return pulumi.get(self, "location") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ The name of the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="notificationLocale") def notification_locale(self) -> pulumi.Output[Optional[str]]: """ The locale to use when sending a notification (fallback for unsupported languages is EN). """ return pulumi.get(self, "notification_locale") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning status of the resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]: """ The tags of the resource. """ return pulumi.get(self, "tags") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ The type of the resource. """ return pulumi.get(self, "type") @property @pulumi.getter(name="uniqueIdentifier") def unique_identifier(self) -> pulumi.Output[str]: """ The unique immutable identifier of a resource (Guid). """ return pulumi.get(self, "unique_identifier") @property @pulumi.getter(name="webHookUrl") def web_hook_url(self) -> pulumi.Output[Optional[str]]: """ The webhook URL to send notifications to. """ return pulumi.get(self, "web_hook_url") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
#ifndef CARD_H #define CARD_H #include <map> #include <exception> #include <string> class Card { public: enum Suit { VOID, BASTONI, COPPE, SPADE, DENARI }; // subclass to throw exceptions class exception : public std::exception { public: constexpr static const char* exceptionName = "Card::exception"; enum errcode { VOID }; private: enum errcode type; static const char *Reason[1]; public: exception( enum errcode x ) : type(x) {}; const char *what() const throw() { return (std::string(exceptionName) + ": " + Reason[type]).c_str(); } }; Suit suit; unsigned int value; public: Card(Suit nsuit, unsigned int nvalue); // operators friend bool operator==(const Card& lc, const Card& rc); friend bool operator!=(const Card& lc, const Card& rc); friend bool operator< (const Card& lc, const Card& rc); friend bool operator<=(const Card& lc, const Card& rc); friend bool operator> (const Card& lc, const Card& rc); friend bool operator>=(const Card& lc, const Card& rc); // encoding and deconding static unsigned int encode(Card card); static Card decode(unsigned int val); }; #endif // CARD_H
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from collections import OrderedDict import threading from ceilometerclient import client as ceilometer_client from django.conf import settings from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon.utils.memoized import memoized # noqa from openstack_dashboard.api import base from openstack_dashboard.api import keystone def is_iterable(var): """Return True if the given is list or tuple.""" return (isinstance(var, (list, tuple)) or issubclass(var.__class__, (list, tuple))) def make_query(user_id=None, tenant_id=None, resource_id=None, user_ids=None, tenant_ids=None, resource_ids=None): """Returns query built from given parameters. This query can be then used for querying resources, meters and statistics. :Parameters: - `user_id`: user_id, has a priority over list of ids - `tenant_id`: tenant_id, has a priority over list of ids - `resource_id`: resource_id, has a priority over list of ids - `user_ids`: list of user_ids - `tenant_ids`: list of tenant_ids - `resource_ids`: list of resource_ids """ user_ids = user_ids or [] tenant_ids = tenant_ids or [] resource_ids = resource_ids or [] query = [] if user_id: user_ids = [user_id] for u_id in user_ids: query.append({"field": "user_id", "op": "eq", "value": u_id}) if tenant_id: tenant_ids = [tenant_id] for t_id in tenant_ids: query.append({"field": "project_id", "op": "eq", "value": t_id}) if resource_id: resource_ids = [resource_id] for r_id in resource_ids: query.append({"field": "resource_id", "op": "eq", "value": r_id}) return query class Meter(base.APIResourceWrapper): """Represents one Ceilometer meter.""" _attrs = ['name', 'type', 'unit', 'resource_id', 'user_id', 'project_id'] def __init__(self, apiresource): super(Meter, self).__init__(apiresource) self._label = self.name self._description = "" def augment(self, label=None, description=None): if label: self._label = label if description: self._description = description @property def description(self): return self._description @property def label(self): return self._label class Resource(base.APIResourceWrapper): """Represents one Ceilometer resource.""" _attrs = ['resource_id', 'source', 'user_id', 'project_id', 'metadata', 'links'] def __init__(self, apiresource, ceilometer_usage=None): super(Resource, self).__init__(apiresource) # Save empty strings to IDs rather than None, so it gets # serialized correctly. We don't want 'None' strings. self.project_id = self.project_id or "" self.user_id = self.user_id or "" self.resource_id = self.resource_id or "" self._id = "%s__%s__%s" % (self.project_id, self.user_id, self.resource_id) # Meters with statistics data self._meters = {} # TODO(lsmola) make parallel obtaining of tenant and user # make the threading here, thread join into resource_list if ceilometer_usage and self.project_id: self._tenant = ceilometer_usage.get_tenant(self.project_id) else: self._tenant = None if ceilometer_usage and self.user_id: self._user = ceilometer_usage.get_user(self.user_id) else: self._user = None self._query = make_query(tenant_id=self.project_id, user_id=self.user_id, resource_id=self.resource_id) @property def name(self): name = self.metadata.get("name", None) display_name = self.metadata.get("display_name", None) return name or display_name or "" @property def id(self): return self._id @property def tenant(self): return self._tenant @property def user(self): return self._user @property def resource(self): return self.resource_id @property def query(self): return self._query @property def meters(self): return self._meters def get_meter(self, meter_name): return self._meters.get(meter_name, None) def set_meter(self, meter_name, value): self._meters[meter_name] = value class ResourceAggregate(Resource): """Represents aggregate of more resources together. Aggregate of resources can be obtained by specifying multiple ids in one parameter or by not specifying one parameter. It can also be specified by query directly. Example: We can obtain an aggregate of resources by specifying multiple resource_ids in resource_id parameter in init. Or we can specify only tenant_id, which will return all resources of that tenant. """ def __init__(self, tenant_id=None, user_id=None, resource_id=None, tenant_ids=None, user_ids=None, resource_ids=None, ceilometer_usage=None, query=None, identifier=None): self._id = identifier self.tenant_id = None self.user_id = None self.resource_id = None # Meters with statistics data self._meters = {} if query: self._query = query else: # TODO(lsmola) make parallel obtaining of tenant and user # make the threading here, thread join into resource_list if ceilometer_usage and tenant_id: self.tenant_id = tenant_id self._tenant = ceilometer_usage.get_tenant(tenant_id) else: self._tenant = None if ceilometer_usage and user_id: self.user_id = user_id self._user = ceilometer_usage.get_user(user_id) else: self._user = None if resource_id: self.resource_id = resource_id self._query = make_query(tenant_id=tenant_id, user_id=user_id, resource_id=resource_id, tenant_ids=tenant_ids, user_ids=user_ids, resource_ids=resource_ids) @property def id(self): return self._id class Sample(base.APIResourceWrapper): """Represents one Ceilometer sample.""" _attrs = ['counter_name', 'user_id', 'resource_id', 'timestamp', 'resource_metadata', 'source', 'counter_unit', 'counter_volume', 'project_id', 'counter_type', 'resource_metadata'] @property def instance(self): display_name = self.resource_metadata.get('display_name', None) instance_id = self.resource_metadata.get('instance_id', None) return display_name or instance_id @property def name(self): name = self.resource_metadata.get("name", None) display_name = self.resource_metadata.get("display_name", None) return name or display_name or "" class Statistic(base.APIResourceWrapper): """Represents one Ceilometer statistic.""" _attrs = ['period', 'period_start', 'period_end', 'count', 'min', 'max', 'sum', 'avg', 'duration', 'duration_start', 'duration_end'] class Alarm(base.APIResourceWrapper): """Represents one Ceilometer alarm.""" _attrs = ['alarm_actions', 'ok_actions', 'name', 'timestamp', 'description', 'time_constraints', 'enabled', 'state_timestamp', 'alarm_id', 'state', 'insufficient_data_actions', 'repeat_actions', 'user_id', 'project_id', 'type', 'severity', 'threshold_rule', 'period', 'query', 'evaluation_periods', 'statistic', 'meter_name', 'threshold', 'comparison_operator', 'exclude_outliers'] def __init__(self, apiresource, ceilometer_usage=None): super(Alarm, self).__init__(apiresource) self._tenant = None self._user = None if ceilometer_usage and self.project_id: self._tenant = ceilometer_usage.get_tenant(self.project_id) if ceilometer_usage and self.user_id: self._user = ceilometer_usage.get_user(self.user_id) @property def id(self): return self.alarm_id @property def tenant(self): return self._tenant @property def user(self): return self._user @memoized def ceilometerclient(request): """Initialization of Ceilometer client.""" endpoint = base.url_for(request, 'metering') insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False) cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None) return ceilometer_client.Client('2', endpoint, token=(lambda: request.user.token.id), insecure=insecure, cacert=cacert) def alarm_list(request, query=None, ceilometer_usage=None): """List alarms.""" alarms = ceilometerclient(request).alarms.list(q=query) return [Alarm(alarm, ceilometer_usage) for alarm in alarms] def alarm_get(request, alarm_id, ceilometer_usage=None): """Get an alarm.""" alarm = ceilometerclient(request).alarms.get(alarm_id) return Alarm(alarm, ceilometer_usage) def alarm_update(request, alarm_id, ceilometer_usage=None, **kwargs): """Update an alarm.""" alarm = ceilometerclient(request).alarms.update(alarm_id, **kwargs) return Alarm(alarm, ceilometer_usage) def alarm_delete(request, alarm_id): """Delete an alarm.""" ceilometerclient(request).alarms.delete(alarm_id) def alarm_create(request, ceilometer_usage=None, **kwargs): """Create an alarm.""" alarm = ceilometerclient(request).alarms.create(**kwargs) return Alarm(alarm, ceilometer_usage) def resource_list(request, query=None, ceilometer_usage_object=None): """List the resources.""" resources = ceilometerclient(request).resources.list(q=query) return [Resource(r, ceilometer_usage_object) for r in resources] def sample_list(request, meter_name, query=None, limit=None): """List the samples for this meters.""" samples = ceilometerclient(request).samples.list(meter_name=meter_name, q=query, limit=limit) return [Sample(s) for s in samples] def meter_list(request, query=None): """List the user's meters.""" meters = ceilometerclient(request).meters.list(query) return [Meter(m) for m in meters] def statistic_list(request, meter_name, query=None, period=None): """List of statistics.""" statistics = ceilometerclient(request).\ statistics.list(meter_name=meter_name, q=query, period=period) return [Statistic(s) for s in statistics] class ThreadedUpdateResourceWithStatistics(threading.Thread): """Multithread wrapper for update_with_statistics method of resource_usage. A join logic is placed in process_list class method. All resources will have its statistics attribute filled in separate threads. The resource_usage object is shared between threads. Each thread is updating one Resource. :Parameters: - `resource`: Resource or ResourceAggregate object, that will be filled by statistic data. - `resources`: List of Resource or ResourceAggregate object, that will be filled by statistic data. - `resource_usage`: Wrapping resource usage object, that holds all statistics data. - `meter_names`: List of meter names of the statistics we want. - `period`: In seconds. If no period is given, only one aggregate statistic is returned. If given, a faceted result will be returned, divided into given periods. Periods with no data are ignored. - `stats_attr`: String representing the attribute name of the stats. E.g. (avg, max, min...) If None is given, whole statistic object is returned, - `additional_query`: Additional query for the statistics. E.g. timespan, etc. """ # TODO(lsmola) Can be removed once Ceilometer supports sample-api # and group-by, so all of this optimization will not be necessary. # It is planned somewhere to I. def __init__(self, resource_usage, resource, meter_names=None, period=None, filter_func=None, stats_attr=None, additional_query=None): super(ThreadedUpdateResourceWithStatistics, self).__init__() self.resource_usage = resource_usage self.resource = resource self.meter_names = meter_names self.period = period self.stats_attr = stats_attr self.additional_query = additional_query def run(self): # Run the job self.resource_usage.update_with_statistics( self.resource, meter_names=self.meter_names, period=self.period, stats_attr=self.stats_attr, additional_query=self.additional_query) @classmethod def process_list(cls, resource_usage, resources, meter_names=None, period=None, filter_func=None, stats_attr=None, additional_query=None): threads = [] for resource in resources: # add statistics data into resource thread = cls(resource_usage, resource, meter_names=meter_names, period=period, stats_attr=stats_attr, additional_query=additional_query) thread.start() threads.append(thread) for thread in threads: thread.join() class CeilometerUsage(object): """Represents wrapper of any Ceilometer queries. One instance of this class should be shared between resources as this class provides a place where users and tenants are cached. So there are no duplicate queries to API. This class also wraps Ceilometer API calls and provides parallel HTTP calls to API. This class should also serve as reasonable abstraction, that will cover huge amount of optimization due to optimization of Ceilometer service, without changing of the interface. """ def __init__(self, request): self._request = request # Cached users and tenants. self._users = {} self._tenants = {} def get_user(self, user_id): """Returns user fetched from API. Caching the result, so it doesn't contact API twice with the same query. """ user = self._users.get(user_id, None) if not user: user = keystone.user_get(self._request, user_id) # caching the user, for later use self._users[user_id] = user return user def preload_all_users(self): """Preloads all users into dictionary. It's more effective to preload all users, rather than fetching many users by separate API get calls. """ users = keystone.user_list(self._request) # Cache all users on right indexes, this is more effective than to # obtain large number of users one by one by keystone.user_get for u in users: self._users[u.id] = u def get_tenant(self, tenant_id): """Returns tenant fetched from API. Caching the result, so it doesn't contact API twice with the same query. """ tenant = self._tenants.get(tenant_id, None) if not tenant: tenant = keystone.tenant_get(self._request, tenant_id) # caching the tenant for later use self._tenants[tenant_id] = tenant return tenant def preload_all_tenants(self): """Preloads all tenants into dictionary. It's more effective to preload all tenants, rather than fetching each tenant by separate API get calls. """ tenants, more = keystone.tenant_list(self._request) # Cache all tenants on right indexes, this is more effective than to # obtain large number of tenants one by one by keystone.tenant_get for t in tenants: self._tenants[t.id] = t def global_data_get(self, used_cls=None, query=None, with_statistics=False, additional_query=None, with_users_and_tenants=True): """Obtaining a resources for table view. It obtains resources with statistics data according to declaration in used_cls class. :Parameters: - `user_cls`: Class wrapper for usage data. It acts as wrapper for settings needed. See the call of this method for details. - `query`: Explicit query definition for fetching the resources. If no query is provided, it takes a default_query from used_cls. If no default query is provided, it fetches all the resources and filters them by meters defined in used_cls. - `with_statistic`: Define whether statistics data from the meters defined in used_cls should be fetched. Can be used to first obtain only the pure resources, then with the statistics data by AJAX. - `additional_query`: Additional query for the statistics. E.g. timespan, etc. - `with_users_and_tenants`: If true a user and a tenant object will be added to each resource object. """ default_query = used_cls.default_query query = query or default_query filter_func = None def filter_resources(resource): """Method for filtering resources by their links.rel attr. The links.rel attributes contain all meters the resource has. """ for link in resource.links: if link['rel'] in used_cls.meters: return True return False if not query: # Not all resource types can be obtained by query, if there is not # a query, we are filtering all resources by this function. filter_func = filter_resources if with_statistics: # Will add statistic data into resources. resources = self.resources_with_statistics( query, used_cls.meters, filter_func=filter_func, stats_attr=used_cls.stats_attr, additional_query=additional_query, with_users_and_tenants=with_users_and_tenants) else: # Will load only resources without statistical data. resources = self.resources( query, filter_func=filter_func, with_users_and_tenants=with_users_and_tenants) return [used_cls(resource) for resource in resources] def query_from_object_id(self, object_id): """Obtaining a query from resource id. Query can be then used to identify a resource in resources or meters API calls. ID is being built in the Resource initializer, or returned by Datatable into UpdateRow functionality. """ try: tenant_id, user_id, resource_id = object_id.split("__") except ValueError: return [] return make_query(tenant_id=tenant_id, user_id=user_id, resource_id=resource_id) def update_with_statistics(self, resource, meter_names=None, period=None, stats_attr=None, additional_query=None): """Adding statistical data into one Resource or ResourceAggregate. It adds each statistic of each meter_names into the resource attributes. Attribute name is the meter name with replaced '.' to '_'. :Parameters: - `resource`: Resource or ResourceAggregate object, that will be filled by statistic data. - `meter_names`: List of meter names of which we want the statistics. - `period`: In seconds. If no period is given, only one aggregate statistic is returned. If given a faceted result will be returned, dividend into given periods. Periods with no data are ignored. - `stats_attr`: String representing the specific name of the stats. E.g. (avg, max, min...) If defined, meter attribute will contain just the one value. If None is given, meter attribute will contain the whole Statistic object. - `additional_query`: Additional query for the statistics. E.g. timespan, etc. """ if not meter_names: raise ValueError("meter_names and resources must be defined to be " "able to obtain the statistics.") # query for identifying one resource in meters query = resource.query if additional_query: if not is_iterable(additional_query): raise ValueError("Additional query must be list of" " conditions. See the docs for format.") query = query + additional_query # TODO(lsmola) thread for each meter will be probably overkill # but I should test lets say thread pool with 100 of threads # and apply it only to this code. # Though I do expect Ceilometer will support bulk requests, # so all of this optimization will not be necessary. for meter in meter_names: statistics = statistic_list(self._request, meter, query=query, period=period) meter = meter.replace(".", "_") if statistics: if stats_attr: # I want to load only a specific attribute resource.set_meter( meter, getattr(statistics[0], stats_attr, None)) else: # I want a dictionary of all statistics resource.set_meter(meter, statistics) else: resource.set_meter(meter, None) return resource def resources(self, query=None, filter_func=None, with_users_and_tenants=False): """Obtaining resources with the query or filter_func. Obtains resources and also fetch tenants and users associated with those resources if with_users_and_tenants flag is true. :Parameters: - `query`: Query for fetching the Ceilometer Resources. - `filter_func`: Callable for filtering of the obtained resources. - `with_users_and_tenants`: If true a user and a tenant object will be added to each resource object. """ if with_users_and_tenants: ceilometer_usage_object = self else: ceilometer_usage_object = None resources = resource_list( self._request, query=query, ceilometer_usage_object=ceilometer_usage_object) if filter_func: resources = [resource for resource in resources if filter_func(resource)] return resources def resources_with_statistics(self, query=None, meter_names=None, period=None, filter_func=None, stats_attr=None, additional_query=None, with_users_and_tenants=False): """Obtaining resources with statistics data inside. :Parameters: - `query`: Query for fetching the Ceilometer Resources. - `filter_func`: Callable for filtering of the obtained resources. - `meter_names`: List of meter names of which we want the statistics. - `period`: In seconds. If no period is given, only one aggregate statistic is returned. If given, a faceted result will be returned, divided into given periods. Periods with no data are ignored. - `stats_attr`: String representing the specific name of the stats. E.g. (avg, max, min...) If defined, meter attribute will contain just the one value. If None is given, meter attribute will contain the whole Statistic object. - `additional_query`: Additional query for the statistics. E.g. timespan, etc. - `with_users_and_tenants`: If true a user and a tenant object will be added to each resource object. """ resources = self.resources( query, filter_func=filter_func, with_users_and_tenants=with_users_and_tenants) ThreadedUpdateResourceWithStatistics.process_list( self, resources, meter_names=meter_names, period=period, stats_attr=stats_attr, additional_query=additional_query) return resources def resource_aggregates(self, queries=None): """Obtaining resource aggregates with queries. Representing a resource aggregate by query is a most general way how to obtain a resource aggregates. :Parameters: - `queries`: Dictionary of named queries that defines a bulk of resource aggregates. """ resource_aggregates = [] for identifier, query in queries.items(): resource_aggregates.append(ResourceAggregate(query=query, ceilometer_usage=None, identifier=identifier)) return resource_aggregates def resource_aggregates_with_statistics(self, queries=None, meter_names=None, period=None, filter_func=None, stats_attr=None, additional_query=None): """Obtaining resource aggregates with statistics data inside. :Parameters: - `queries`: Dictionary of named queries that defines a bulk of resource aggregates. - `meter_names`: List of meter names of which we want the statistics. - `period`: In seconds. If no period is given, only one aggregate statistic is returned. If given, a faceted result will be returned, divided into given periods. Periods with no data are ignored. - `stats_attr`: String representing the specific name of the stats. E.g. (avg, max, min...) If defined, meter attribute will contain just the one value. If None is given, meter attribute will contain the whole Statistic object. - `additional_query`: Additional query for the statistics. E.g. timespan, etc. """ resource_aggregates = self.resource_aggregates(queries) ThreadedUpdateResourceWithStatistics.process_list( self, resource_aggregates, meter_names=meter_names, period=period, stats_attr=stats_attr, additional_query=additional_query) return resource_aggregates def diff_lists(a, b): if not a: return [] elif not b: return a else: return list(set(a) - set(b)) class Meters(object): """Class for listing of available meters. It is listing meters defined in this class that are available in Ceilometer meter_list. It is storing information that is not available in Ceilometer, i.e. label, description. """ def __init__(self, request=None, ceilometer_meter_list=None): # Storing the request. self._request = request # Storing the Ceilometer meter list if ceilometer_meter_list: self._ceilometer_meter_list = ceilometer_meter_list else: try: self._ceilometer_meter_list = meter_list(request) except Exception: self._ceilometer_meter_list = [] exceptions.handle(self._request, _('Unable to retrieve Ceilometer meter ' 'list.')) # Storing the meters info categorized by their services. self._nova_meters_info = self._get_nova_meters_info() self._neutron_meters_info = self._get_neutron_meters_info() self._glance_meters_info = self._get_glance_meters_info() self._cinder_meters_info = self._get_cinder_meters_info() self._swift_meters_info = self._get_swift_meters_info() self._kwapi_meters_info = self._get_kwapi_meters_info() self._ipmi_meters_info = self._get_ipmi_meters_info() # Storing the meters info of all services together. all_services_meters = (self._nova_meters_info, self._neutron_meters_info, self._glance_meters_info, self._cinder_meters_info, self._swift_meters_info, self._kwapi_meters_info, self._ipmi_meters_info) self._all_meters_info = {} for service_meters in all_services_meters: self._all_meters_info.update(dict([(meter_name, meter_info) for meter_name, meter_info in service_meters.items()])) # Here will be the cached Meter objects, that will be reused for # repeated listing. self._cached_meters = {} def list_all(self, only_meters=None, except_meters=None): """Returns a list of meters based on the meters names. :Parameters: - `only_meters`: The list of meter names we want to show. - `except_meters`: The list of meter names we don't want to show. """ return self._list(only_meters=only_meters, except_meters=except_meters) def list_nova(self, except_meters=None): """Returns a list of meters tied to nova. :Parameters: - `except_meters`: The list of meter names we don't want to show. """ return self._list(only_meters=self._nova_meters_info.keys(), except_meters=except_meters) def list_neutron(self, except_meters=None): """Returns a list of meters tied to neutron. :Parameters: - `except_meters`: The list of meter names we don't want to show. """ return self._list(only_meters=self._neutron_meters_info.keys(), except_meters=except_meters) def list_glance(self, except_meters=None): """Returns a list of meters tied to glance. :Parameters: - `except_meters`: The list of meter names we don't want to show. """ return self._list(only_meters=self._glance_meters_info.keys(), except_meters=except_meters) def list_cinder(self, except_meters=None): """Returns a list of meters tied to cinder. :Parameters: - `except_meters`: The list of meter names we don't want to show. """ return self._list(only_meters=self._cinder_meters_info.keys(), except_meters=except_meters) def list_swift(self, except_meters=None): """Returns a list of meters tied to swift. :Parameters: - `except_meters`: The list of meter names we don't want to show. """ return self._list(only_meters=self._swift_meters_info.keys(), except_meters=except_meters) def list_kwapi(self, except_meters=None): """Returns a list of meters tied to kwapi. :Parameters: - `except_meters`: The list of meter names we don't want to show. """ return self._list(only_meters=self._kwapi_meters_info.keys(), except_meters=except_meters) def list_ipmi(self, except_meters=None): """Returns a list of meters tied to ipmi :Parameters: - `except_meters`: The list of meter names we don't want to show """ return self._list(only_meters=self._ipmi_meters_info.keys(), except_meters=except_meters) def _list(self, only_meters=None, except_meters=None): """Returns a list of meters based on the meters names. :Parameters: - `only_meters`: The list of meter names we want to show. - `except_meters`: The list of meter names we don't want to show. """ # Get all wanted meter names. if only_meters: meter_names = only_meters else: meter_names = [meter_name for meter_name in self._all_meters_info.keys()] meter_names = diff_lists(meter_names, except_meters) # Collect meters for wanted meter names. return self._get_meters(meter_names) def _get_meters(self, meter_names): """Obtain meters based on meter_names. The meters that do not exist in Ceilometer meter list are left out. :Parameters: - `meter_names`: A list of meter names we want to fetch. """ meters = [] for meter_name in meter_names: meter = self._get_meter(meter_name) if meter: meters.append(meter) return meters def _get_meter(self, meter_name): """Obtains a meter. Obtains meter either from cache or from Ceilometer meter list joined with statically defined meter info like label and description. :Parameters: - `meter_name`: A meter name we want to fetch. """ meter = self._cached_meters.get(meter_name, None) if not meter: meter_candidates = [m for m in self._ceilometer_meter_list if m.name == meter_name] if meter_candidates: meter_info = self._all_meters_info.get(meter_name, None) if meter_info: label = meter_info["label"] description = meter_info["description"] else: label = "" description = "" meter = meter_candidates[0] meter.augment(label=label, description=description) self._cached_meters[meter_name] = meter return meter def _get_nova_meters_info(self): """Returns additional info for each meter. That will be used for augmenting the Ceilometer meter. """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. meters_info = OrderedDict([ ("instance", { 'label': '', 'description': _("Existence of instance"), }), ("instance:<type>", { 'label': '', 'description': _("Existence of instance <type> " "(openstack types)"), }), ("memory", { 'label': '', 'description': _("Volume of RAM"), }), ("memory.usage", { 'label': '', 'description': _("Volume of RAM used"), }), ("cpu", { 'label': '', 'description': _("CPU time used"), }), ("cpu_util", { 'label': '', 'description': _("Average CPU utilization"), }), ("vcpus", { 'label': '', 'description': _("Number of VCPUs"), }), ("disk.read.requests", { 'label': '', 'description': _("Number of read requests"), }), ("disk.write.requests", { 'label': '', 'description': _("Number of write requests"), }), ("disk.read.bytes", { 'label': '', 'description': _("Volume of reads"), }), ("disk.write.bytes", { 'label': '', 'description': _("Volume of writes"), }), ("disk.read.requests.rate", { 'label': '', 'description': _("Average rate of read requests"), }), ("disk.write.requests.rate", { 'label': '', 'description': _("Average rate of write requests"), }), ("disk.read.bytes.rate", { 'label': '', 'description': _("Average rate of reads"), }), ("disk.write.bytes.rate", { 'label': '', 'description': _("Average volume of writes"), }), ("disk.root.size", { 'label': '', 'description': _("Size of root disk"), }), ("disk.ephemeral.size", { 'label': '', 'description': _("Size of ephemeral disk"), }), ("network.incoming.bytes", { 'label': '', 'description': _("Number of incoming bytes " "on the network for a VM interface"), }), ("network.outgoing.bytes", { 'label': '', 'description': _("Number of outgoing bytes " "on the network for a VM interface"), }), ("network.incoming.packets", { 'label': '', 'description': _("Number of incoming " "packets for a VM interface"), }), ("network.outgoing.packets", { 'label': '', 'description': _("Number of outgoing " "packets for a VM interface"), }), ("network.incoming.bytes.rate", { 'label': '', 'description': _("Average rate per sec of incoming " "bytes on a VM network interface"), }), ("network.outgoing.bytes.rate", { 'label': '', 'description': _("Average rate per sec of outgoing " "bytes on a VM network interface"), }), ("network.incoming.packets.rate", { 'label': '', 'description': _("Average rate per sec of incoming " "packets on a VM network interface"), }), ("network.outgoing.packets.rate", { 'label': '', 'description': _("Average rate per sec of outgoing " "packets on a VM network interface"), }), ]) # TODO(lsmola) allow to set specific in local_settings. For all meters # because users can have their own agents and meters. return meters_info def _get_neutron_meters_info(self): """Returns additional info for each meter. That will be used for augmenting the Ceilometer meter. """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return OrderedDict([ ('network', { 'label': '', 'description': _("Existence of network"), }), ('network.create', { 'label': '', 'description': _("Creation requests for this network"), }), ('network.update', { 'label': '', 'description': _("Update requests for this network"), }), ('subnet', { 'label': '', 'description': _("Existence of subnet"), }), ('subnet.create', { 'label': '', 'description': _("Creation requests for this subnet"), }), ('subnet.update', { 'label': '', 'description': _("Update requests for this subnet"), }), ('port', { 'label': '', 'description': _("Existence of port"), }), ('port.create', { 'label': '', 'description': _("Creation requests for this port"), }), ('port.update', { 'label': '', 'description': _("Update requests for this port"), }), ('router', { 'label': '', 'description': _("Existence of router"), }), ('router.create', { 'label': '', 'description': _("Creation requests for this router"), }), ('router.update', { 'label': '', 'description': _("Update requests for this router"), }), ('ip.floating', { 'label': '', 'description': _("Existence of floating ip"), }), ('ip.floating.create', { 'label': '', 'description': _("Creation requests for this floating ip"), }), ('ip.floating.update', { 'label': '', 'description': _("Update requests for this floating ip"), }), ]) def _get_glance_meters_info(self): """Returns additional info for each meter. That will be used for augmenting the Ceilometer meter. """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return OrderedDict([ ('image', { 'label': '', 'description': _("Image existence check"), }), ('image.size', { 'label': '', 'description': _("Uploaded image size"), }), ('image.update', { 'label': '', 'description': _("Number of image updates"), }), ('image.upload', { 'label': '', 'description': _("Number of image uploads"), }), ('image.delete', { 'label': '', 'description': _("Number of image deletions"), }), ('image.download', { 'label': '', 'description': _("Image is downloaded"), }), ('image.serve', { 'label': '', 'description': _("Image is served out"), }), ]) def _get_cinder_meters_info(self): """Returns additional info for each meter. That will be used for augmenting the Ceilometer meter. """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return OrderedDict([ ('volume', { 'label': '', 'description': _("Existence of volume"), }), ('volume.size', { 'label': '', 'description': _("Size of volume"), }), ]) def _get_swift_meters_info(self): """Returns additional info for each meter. That will be used for augmenting the Ceilometer meter. """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return OrderedDict([ ('storage.objects', { 'label': '', 'description': _("Number of objects"), }), ('storage.objects.size', { 'label': '', 'description': _("Total size of stored objects"), }), ('storage.objects.containers', { 'label': '', 'description': _("Number of containers"), }), ('storage.objects.incoming.bytes', { 'label': '', 'description': _("Number of incoming bytes"), }), ('storage.objects.outgoing.bytes', { 'label': '', 'description': _("Number of outgoing bytes"), }), ('storage.api.request', { 'label': '', 'description': _("Number of API requests against swift"), }), ]) def _get_kwapi_meters_info(self): """Returns additional info for each meter. That will be used for augmenting the Ceilometer meter. """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return OrderedDict([ ('energy', { 'label': '', 'description': _("Amount of energy"), }), ('power', { 'label': '', 'description': _("Power consumption"), }), ]) def _get_ipmi_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return OrderedDict([ ('hardware.ipmi.node.power', { 'label': '', 'description': _("System Current Power"), }), ('hardware.ipmi.fan', { 'label': '', 'description': _("Fan RPM"), }), ('hardware.ipmi.temperature', { 'label': '', 'description': _("Sensor Temperature Reading"), }), ('hardware.ipmi.current', { 'label': '', 'description': _("Sensor Current Reading"), }), ('hardware.ipmi.voltage', { 'label': '', 'description': _("Sensor Voltage Reading"), }), ('hardware.ipmi.node.temperature', { 'label': '', 'description': _("System Temperature Reading"), }), ('hardware.ipmi.node.outlet_temperature', { 'label': '', 'description': _("System Outlet Temperature Reading"), }), ('hardware.ipmi.node.airflow', { 'label': '', 'description': _("System Airflow Reading"), }), ('hardware.ipmi.node.cups', { 'label': '', 'description': _("System CUPS Reading"), }), ('hardware.ipmi.node.cpu_util', { 'label': '', 'description': _("System CPU Utility Reading"), }), ('hardware.ipmi.node.mem_util', { 'label': '', 'description': _("System Memory Utility Reading"), }), ('hardware.ipmi.node.io_util', { 'label': '', 'description': _("System IO Utility Reading"), }), ])
#pragma once #include "RE/B/BSTList.h" #include "RE/F/FormTypes.h" #include "RE/N/NiColor.h" #include "RE/N/NiPoint2.h" #include "RE/T/TESForm.h" namespace RE { struct TESRegionDataList; class TESRegionPoint { public: NiPoint2 point; // 00 }; static_assert(sizeof(TESRegionPoint) == 0x8); class TESRegionPointList : public BSSimpleList<TESRegionPoint*> // RPLD { public: struct ScaleResult { TESRegionPoint point; // 00 float dist; // 08 float scale; // 0C }; static_assert(sizeof(ScaleResult) == 0x10); ScaleResult* lastScaleResult; // 10 bool ownsPointMemory; // 18 std::uint8_t pad19; // 19 std::uint16_t pad1A; // 1A NiPoint2 minimums; // 1C NiPoint2 maximums; // 24 std::uint32_t distanceInsideAtMax; // 2C - RPLI std::uint32_t count; // 30 std::uint32_t pad34; // 34 }; static_assert(sizeof(TESRegionPointList) == 0x38); class TESRegion : public TESForm { public: inline static constexpr auto RTTI = RTTI_TESRegion; inline static constexpr auto FORMTYPE = FormType::Region; struct RecordFlags { enum RecordFlag : std::uint32_t { kDeleted = 1 << 5, kBorderRegion = 1 << 6, kIgnored = 1 << 12 }; }; virtual ~TESRegion(); // 00 // override (TESForm) virtual void ClearData(void) override; // 05 virtual bool Load(TESFile* a_mod) override; // 06 virtual void InitItemImpl() override; // 13 // add virtual bool Validate(); // 3B // members TESRegionDataList* dataList; // 20 BSSimpleList<TESRegionPointList*>* pointLists; // 28 TESWorldSpace* worldSpace; // 30 - WNAM TESWeather* currentWeather; // 38 NiColor emittanceColor; // 40 std::uint32_t pad4C; // 4C }; static_assert(sizeof(TESRegion) == 0x50); }
import pdb import os import time from generate_questions.episode import Episode import random import numpy as np import h5py import multiprocessing from utils import game_util from utils import py_util from graph import graph_obj from generate_questions.questions import ExistenceQuestion import constants all_object_classes = constants.QUESTION_OBJECT_CLASS_LIST DEBUG = True if DEBUG: PARALLEL_SIZE = 1 else: PARALLEL_SIZE = 8 def main(dataset_type): if dataset_type == 'val/unseen_scenes': num_questions_per_scene = round(100.0 / PARALLEL_SIZE) scene_numbers = constants.TEST_SCENE_NUMBERS num_samples_per_scene = 20 elif dataset_type == 'val/seen_scenes': num_questions_per_scene = round(8.0 / PARALLEL_SIZE) scene_numbers = constants.TRAIN_SCENE_NUMBERS num_samples_per_scene = 4 elif dataset_type == 'train': num_questions_per_scene = round(1000.0 / PARALLEL_SIZE) scene_numbers = constants.TRAIN_SCENE_NUMBERS num_samples_per_scene = 16 else: raise Exception('No test set found') num_record = int(num_samples_per_scene * np.ceil(num_questions_per_scene * 1.0 / num_samples_per_scene) * len(scene_numbers)) num_record = 300 assert(num_samples_per_scene % 4 == 0) def create_dump(): time_str = py_util.get_time_str() prefix = 'questions/' if not os.path.exists(prefix + dataset_type + '/data_existence'): os.makedirs(prefix + dataset_type + '/data_existence') h5 = h5py.File(prefix + dataset_type + '_single/data_existence/Existence_Questions_' + time_str + '.h5', 'w') h5.create_dataset('questions/question', (num_record, 4), dtype=np.int32) print('--------------------------------------') print('Generating %d existence questions' % num_record) print('--------------------------------------') # Generate existence questions data_ind = 0 episode = Episode() scene_number = -1 while data_ind < num_record: k = 0 scene_number += 1 scene_num = scene_numbers[scene_number % len(scene_numbers)] scene_seed = random.randint(0, 999999999) scene_name = 'FloorPlan%d' % scene_num #scene_num = 1 #scene_name = 'FloorPlan%d' % scene_num episode.initialize_scene(scene_name) num_tries = 0 #while k < num_samples_per_scene and num_tries < 10 * num_samples_per_scene: # randomly pick a pickable object in the scene for object_class in all_object_classes: question = ExistenceQuestion(object_class) # randomly generate a general existence question generated_no, generated_yes = False, False temp_data = [] num_tries += 1 grid_file = 'layouts/%s-layout.npy' % scene_name xray_graph = graph_obj.Graph(grid_file, use_gt=True, construct_graph=False) scene_bounds = [xray_graph.xMin, xray_graph.yMin, xray_graph.xMax - xray_graph.xMin + 1, xray_graph.yMax - xray_graph.yMin + 1] for i in range(20): # try 20 times #scene_seed = random.randint(0, 999999999) episode.initialize_episode(scene_seed=scene_seed) # randomly initialize the scene answer = question.get_answer(episode) object_target = constants.OBJECT_CLASS_TO_ID[object_class] if answer:# and not generated_yes: event = episode.event xray_graph.memory[:, :, 1:] = 0 objs = {obj['objectId']: obj for obj in event.metadata['objects'] if obj['objectType'] == object_class} for obj in objs.values(): if DEBUG: print(object_class, 'is in', obj['parentReceptacle']) if obj['objectType'] != object_class: continue obj_point = game_util.get_object_point(obj, scene_bounds) xray_graph.memory[obj_point[1], obj_point[0], constants.OBJECT_CLASS_TO_ID[obj['objectType']] + 1] = 1 # Make sure findable try: graph_points = xray_graph.points.copy() graph_points = graph_points[np.random.permutation(graph_points.shape[0]), :] num_checked_points = 0 for start_point in graph_points: headings = np.random.permutation(4) for heading in headings: start_point = (start_point[0], start_point[1], heading) patch = xray_graph.get_graph_patch(start_point)[0] if patch[:, :, object_target + 1].max() > 0: action = {'action': 'TeleportFull', 'x': start_point[0] * constants.AGENT_STEP_SIZE, 'y': episode.agent_height, 'z': start_point[1] * constants.AGENT_STEP_SIZE, 'rotateOnTeleport': True, 'rotation': start_point[2] * 90, 'horizon': -30, } event = episode.env.step(action) num_checked_points += 1 if num_checked_points > 1000: answer = None raise AssertionError for jj in range(4): open_success = True opened_objects = set() parents = [game_util.get_object(obj['parentReceptacle'], event.metadata) for obj in objs.values()] openable_parents = [parent for parent in parents if parent['visible'] and parent['openable'] and not parent['isopen']] while open_success: if object_class in event.class_detections2D: for bounds in event.class_detections2D[object_class]: if game_util.check_object_size(bounds): raise AssertionError if len(openable_parents) > 0: action = {'action': 'OpenObject'} game_util.set_open_close_object(action, event) event = episode.env.step(action) open_success = event.metadata['lastActionSuccess'] if open_success: opened_objects.add(episode.env.last_action['objectId']) else: open_success = False for opened in opened_objects: event = episode.env.step({ 'action': 'CloseObject', 'objectId': opened, 'forceVisible': True}) if not event.metadata['lastActionSuccess']: answer = None raise AssertionError if jj < 3: event = episode.env.step({'action': 'LookDown'}) answer = None except AssertionError: pass print(str(question), answer) if answer == None: break #if answer == False and not generated_no: # generated_no = True # temp_data.append([scene_num, scene_seed, constants.OBJECT_CLASS_TO_ID[object_class], answer]) #elif answer == True and not generated_yes: # generated_yes = True # temp_data.append([scene_num, scene_seed, constants.OBJECT_CLASS_TO_ID[object_class], answer]) temp_data.append([scene_num, scene_seed, constants.OBJECT_CLASS_TO_ID[object_class], answer]) print (temp_data) """ if generated_no and generated_yes: h5['questions/question'][data_ind, :] = np.array(temp_data[0]) h5['questions/question'][data_ind + 1, :] = np.array(temp_data[1]) h5.flush() data_ind += 2 k += 2 break """ h5['questions/question'][data_ind, :] = np.array(temp_data[0]) h5.flush() data_ind += 1 k += 1 break print("# generated samples: {}".format(data_ind)) h5.close() episode.env.stop_unity() if True: create_dump() else: procs = [] for ps in range(PARALLEL_SIZE): proc = multiprocessing.Process(target=create_dump) proc.start() procs.append(proc) time.sleep(1) for proc in procs: proc.join() if __name__ == '__main__': #main('train') main('val/unseen_scenes') #main('val/seen_scenes')
/* Simple DirectMedia Layer Copyright (C) 1997-2015 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../SDL_internal.h" /* General mouse handling code for SDL */ #include "SDL_assert.h" #include "SDL_hints.h" #include "SDL_timer.h" #include "SDL_events.h" #include "SDL_events_c.h" #include "default_cursor.h" #include "../video/SDL_sysvideo.h" /* #define DEBUG_MOUSE */ /* The mouse state */ static SDL_Mouse SDL_mouse; static Uint32 SDL_double_click_time = 500; static int SDL_double_click_radius = 1; static int SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y); /* Public functions */ int SDL_MouseInit(void) { SDL_Mouse *mouse = SDL_GetMouse(); mouse->cursor_shown = SDL_TRUE; return (0); } void SDL_SetDefaultCursor(SDL_Cursor * cursor) { SDL_Mouse *mouse = SDL_GetMouse(); mouse->def_cursor = cursor; if (!mouse->cur_cursor) { SDL_SetCursor(cursor); } } SDL_Mouse * SDL_GetMouse(void) { return &SDL_mouse; } void SDL_SetDoubleClickTime(Uint32 interval) { SDL_double_click_time = interval; } SDL_Window * SDL_GetMouseFocus(void) { SDL_Mouse *mouse = SDL_GetMouse(); return mouse->focus; } void SDL_ResetMouse(void) { SDL_Mouse *mouse = SDL_GetMouse(); Uint8 i; #ifdef DEBUG_MOUSE printf("Resetting mouse\n"); #endif for (i = 1; i <= sizeof(mouse->buttonstate)*8; ++i) { if (mouse->buttonstate & SDL_BUTTON(i)) { SDL_SendMouseButton(mouse->focus, mouse->mouseID, SDL_RELEASED, i); } } SDL_assert(mouse->buttonstate == 0); } void SDL_SetMouseFocus(SDL_Window * window) { SDL_Mouse *mouse = SDL_GetMouse(); if (mouse->focus == window) { return; } /* Actually, this ends up being a bad idea, because most operating systems have an implicit grab when you press the mouse button down so you can drag things out of the window and then get the mouse up when it happens. So, #if 0... */ #if 0 if (mouse->focus && !window) { /* We won't get anymore mouse messages, so reset mouse state */ SDL_ResetMouse(); } #endif /* See if the current window has lost focus */ if (mouse->focus) { SDL_SendWindowEvent(mouse->focus, SDL_WINDOWEVENT_LEAVE, 0, 0); } mouse->focus = window; if (mouse->focus) { SDL_SendWindowEvent(mouse->focus, SDL_WINDOWEVENT_ENTER, 0, 0); } /* Update cursor visibility */ SDL_SetCursor(NULL); } /* Check to see if we need to synthesize focus events */ static SDL_bool SDL_UpdateMouseFocus(SDL_Window * window, int x, int y, Uint32 buttonstate) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_bool inWindow = SDL_TRUE; if (window && ((window->flags & SDL_WINDOW_MOUSE_CAPTURE) == 0)) { int w, h; SDL_GetWindowSize(window, &w, &h); if (x < 0 || y < 0 || x >= w || y >= h) { inWindow = SDL_FALSE; } } /* Linux doesn't give you mouse events outside your window unless you grab the pointer. Windows doesn't give you mouse events outside your window unless you call SetCapture(). Both of these are slightly scary changes, so for now we'll punt and if the mouse leaves the window you'll lose mouse focus and reset button state. */ #ifdef SUPPORT_DRAG_OUTSIDE_WINDOW if (!inWindow && !buttonstate) { #else if (!inWindow) { #endif if (window == mouse->focus) { #ifdef DEBUG_MOUSE printf("Mouse left window, synthesizing move & focus lost event\n"); #endif SDL_PrivateSendMouseMotion(window, mouse->mouseID, 0, x, y); SDL_SetMouseFocus(NULL); } return SDL_FALSE; } if (window != mouse->focus) { #ifdef DEBUG_MOUSE printf("Mouse entered window, synthesizing focus gain & move event\n"); #endif SDL_SetMouseFocus(window); SDL_PrivateSendMouseMotion(window, mouse->mouseID, 0, x, y); } return SDL_TRUE; } int SDL_SendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y) { if (window && !relative) { SDL_Mouse *mouse = SDL_GetMouse(); if (!SDL_UpdateMouseFocus(window, x, y, mouse->buttonstate)) { return 0; } } return SDL_PrivateSendMouseMotion(window, mouseID, relative, x, y); } static int SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y) { SDL_Mouse *mouse = SDL_GetMouse(); int posted; int xrel; int yrel; if (mouse->relative_mode_warp) { int center_x = 0, center_y = 0; SDL_GetWindowSize(window, &center_x, &center_y); center_x /= 2; center_y /= 2; if (x == center_x && y == center_y) { mouse->last_x = center_x; mouse->last_y = center_y; return 0; } SDL_WarpMouseInWindow(window, center_x, center_y); } if (relative) { xrel = x; yrel = y; x = (mouse->last_x + xrel); y = (mouse->last_y + yrel); } else { xrel = x - mouse->last_x; yrel = y - mouse->last_y; } /* Drop events that don't change state */ if (!xrel && !yrel) { #ifdef DEBUG_MOUSE printf("Mouse event didn't change state - dropped!\n"); #endif return 0; } /* Update internal mouse coordinates */ if (!mouse->relative_mode) { mouse->x = x; mouse->y = y; } else { mouse->x += xrel; mouse->y += yrel; } /* make sure that the pointers find themselves inside the windows, unless we have the mouse captured. */ if (window && ((window->flags & SDL_WINDOW_MOUSE_CAPTURE) == 0)) { int x_max = 0, y_max = 0; // !!! FIXME: shouldn't this be (window) instead of (mouse->focus)? SDL_GetWindowSize(mouse->focus, &x_max, &y_max); --x_max; --y_max; if (mouse->x > x_max) { mouse->x = x_max; } if (mouse->x < 0) { mouse->x = 0; } if (mouse->y > y_max) { mouse->y = y_max; } if (mouse->y < 0) { mouse->y = 0; } } mouse->xdelta += xrel; mouse->ydelta += yrel; /* Move the mouse cursor, if needed */ if (mouse->cursor_shown && !mouse->relative_mode && mouse->MoveCursor && mouse->cur_cursor) { mouse->MoveCursor(mouse->cur_cursor); } /* Post the event, if desired */ posted = 0; if (SDL_GetEventState(SDL_MOUSEMOTION) == SDL_ENABLE) { SDL_Event event; event.motion.type = SDL_MOUSEMOTION; event.motion.windowID = mouse->focus ? mouse->focus->id : 0; event.motion.which = mouseID; event.motion.state = mouse->buttonstate; event.motion.x = mouse->x; event.motion.y = mouse->y; event.motion.xrel = xrel; event.motion.yrel = yrel; posted = (SDL_PushEvent(&event) > 0); } if (relative) { mouse->last_x = mouse->x; mouse->last_y = mouse->y; } else { /* Use unclamped values if we're getting events outside the window */ mouse->last_x = x; mouse->last_y = y; } return posted; } static SDL_MouseClickState *GetMouseClickState(SDL_Mouse *mouse, Uint8 button) { if (button >= mouse->num_clickstates) { int i, count = button + 1; SDL_MouseClickState *clickstate = (SDL_MouseClickState *)SDL_realloc(mouse->clickstate, count * sizeof(*mouse->clickstate)); if (!clickstate) { return NULL; } mouse->clickstate = clickstate; for (i = mouse->num_clickstates; i < count; ++i) { SDL_zero(mouse->clickstate[i]); } mouse->num_clickstates = count; } return &mouse->clickstate[button]; } int SDL_SendMouseButton(SDL_Window * window, SDL_MouseID mouseID, Uint8 state, Uint8 button) { SDL_Mouse *mouse = SDL_GetMouse(); int posted; Uint32 type; Uint32 buttonstate = mouse->buttonstate; SDL_MouseClickState *clickstate = GetMouseClickState(mouse, button); Uint8 click_count; /* Figure out which event to perform */ switch (state) { case SDL_PRESSED: type = SDL_MOUSEBUTTONDOWN; buttonstate |= SDL_BUTTON(button); break; case SDL_RELEASED: type = SDL_MOUSEBUTTONUP; buttonstate &= ~SDL_BUTTON(button); break; default: /* Invalid state -- bail */ return 0; } /* We do this after calculating buttonstate so button presses gain focus */ if (window && state == SDL_PRESSED) { SDL_UpdateMouseFocus(window, mouse->x, mouse->y, buttonstate); } if (buttonstate == mouse->buttonstate) { /* Ignore this event, no state change */ return 0; } mouse->buttonstate = buttonstate; if (clickstate) { if (state == SDL_PRESSED) { Uint32 now = SDL_GetTicks(); if (SDL_TICKS_PASSED(now, clickstate->last_timestamp + SDL_double_click_time) || SDL_abs(mouse->x - clickstate->last_x) > SDL_double_click_radius || SDL_abs(mouse->y - clickstate->last_y) > SDL_double_click_radius) { clickstate->click_count = 0; } clickstate->last_timestamp = now; clickstate->last_x = mouse->x; clickstate->last_y = mouse->y; if (clickstate->click_count < 255) { ++clickstate->click_count; } } click_count = clickstate->click_count; } else { click_count = 1; } /* Post the event, if desired */ posted = 0; if (SDL_GetEventState(type) == SDL_ENABLE) { SDL_Event event; event.type = type; event.button.windowID = mouse->focus ? mouse->focus->id : 0; event.button.which = mouseID; event.button.state = state; event.button.button = button; event.button.clicks = click_count; event.button.x = mouse->x; event.button.y = mouse->y; posted = (SDL_PushEvent(&event) > 0); } /* We do this after dispatching event so button releases can lose focus */ if (window && state == SDL_RELEASED) { SDL_UpdateMouseFocus(window, mouse->x, mouse->y, buttonstate); } return posted; } int SDL_SendMouseWheel(SDL_Window * window, SDL_MouseID mouseID, int x, int y, SDL_MouseWheelDirection direction) { SDL_Mouse *mouse = SDL_GetMouse(); int posted; if (window) { SDL_SetMouseFocus(window); } if (!x && !y) { return 0; } /* Post the event, if desired */ posted = 0; if (SDL_GetEventState(SDL_MOUSEWHEEL) == SDL_ENABLE) { SDL_Event event; event.type = SDL_MOUSEWHEEL; event.wheel.windowID = mouse->focus ? mouse->focus->id : 0; event.wheel.which = mouseID; event.wheel.x = x; event.wheel.y = y; event.wheel.direction = (Uint32)direction; posted = (SDL_PushEvent(&event) > 0); } return posted; } void SDL_MouseQuit(void) { SDL_Cursor *cursor, *next; SDL_Mouse *mouse = SDL_GetMouse(); if (mouse->CaptureMouse) { SDL_CaptureMouse(SDL_FALSE); } SDL_SetRelativeMouseMode(SDL_FALSE); SDL_ShowCursor(1); cursor = mouse->cursors; while (cursor) { next = cursor->next; SDL_FreeCursor(cursor); cursor = next; } if (mouse->def_cursor && mouse->FreeCursor) { mouse->FreeCursor(mouse->def_cursor); } if (mouse->clickstate) { SDL_free(mouse->clickstate); } SDL_zerop(mouse); } Uint32 SDL_GetMouseState(int *x, int *y) { SDL_Mouse *mouse = SDL_GetMouse(); if (x) { *x = mouse->x; } if (y) { *y = mouse->y; } return mouse->buttonstate; } Uint32 SDL_GetRelativeMouseState(int *x, int *y) { SDL_Mouse *mouse = SDL_GetMouse(); if (x) { *x = mouse->xdelta; } if (y) { *y = mouse->ydelta; } mouse->xdelta = 0; mouse->ydelta = 0; return mouse->buttonstate; } Uint32 SDL_GetGlobalMouseState(int *x, int *y) { SDL_Mouse *mouse = SDL_GetMouse(); int tmpx, tmpy; /* make sure these are never NULL for the backend implementations... */ if (!x) { x = &tmpx; } if (!y) { y = &tmpy; } *x = *y = 0; if (!mouse->GetGlobalMouseState) { SDL_assert(0 && "This should really be implemented for every target."); return 0; } return mouse->GetGlobalMouseState(x, y); } void SDL_WarpMouseInWindow(SDL_Window * window, int x, int y) { SDL_Mouse *mouse = SDL_GetMouse(); if (window == NULL) { window = mouse->focus; } if (window == NULL) { return; } if (mouse->WarpMouse) { mouse->WarpMouse(window, x, y); } else { SDL_SendMouseMotion(window, mouse->mouseID, 0, x, y); } } void SDL_WarpMouseGlobal(int x, int y) { SDL_Mouse *mouse = SDL_GetMouse(); if (mouse->WarpMouseGlobal) { mouse->WarpMouseGlobal(x, y); } } static SDL_bool ShouldUseRelativeModeWarp(SDL_Mouse *mouse) { const char *hint; if (!mouse->SetRelativeMouseMode) { return SDL_TRUE; } hint = SDL_GetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP); if (hint) { if (*hint == '0') { return SDL_FALSE; } else { return SDL_TRUE; } } return SDL_FALSE; } int SDL_SetRelativeMouseMode(SDL_bool enabled) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_Window *focusWindow = SDL_GetKeyboardFocus(); if (enabled == mouse->relative_mode) { return 0; } if (enabled && focusWindow) { /* Center it in the focused window to prevent clicks from going through * to background windows. */ SDL_SetMouseFocus(focusWindow); SDL_WarpMouseInWindow(focusWindow, focusWindow->w/2, focusWindow->h/2); } /* Set the relative mode */ if (!enabled && mouse->relative_mode_warp) { mouse->relative_mode_warp = SDL_FALSE; } else if (enabled && ShouldUseRelativeModeWarp(mouse)) { mouse->relative_mode_warp = SDL_TRUE; } else if (mouse->SetRelativeMouseMode(enabled) < 0) { if (enabled) { /* Fall back to warp mode if native relative mode failed */ mouse->relative_mode_warp = SDL_TRUE; } } mouse->relative_mode = enabled; if (mouse->focus) { SDL_UpdateWindowGrab(mouse->focus); /* Put the cursor back to where the application expects it */ if (!enabled) { SDL_WarpMouseInWindow(mouse->focus, mouse->x, mouse->y); } } /* Flush pending mouse motion - ideally we would pump events, but that's not always safe */ SDL_FlushEvent(SDL_MOUSEMOTION); /* Update cursor visibility */ SDL_SetCursor(NULL); return 0; } SDL_bool SDL_GetRelativeMouseMode() { SDL_Mouse *mouse = SDL_GetMouse(); return mouse->relative_mode; } int SDL_CaptureMouse(SDL_bool enabled) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_Window *focusWindow; SDL_bool isCaptured; if (!mouse->CaptureMouse) { return SDL_Unsupported(); } focusWindow = SDL_GetKeyboardFocus(); isCaptured = focusWindow && (focusWindow->flags & SDL_WINDOW_MOUSE_CAPTURE); if (isCaptured == enabled) { return 0; /* already done! */ } if (enabled) { if (!focusWindow) { return SDL_SetError("No window has focus"); } else if (mouse->CaptureMouse(focusWindow) == -1) { return -1; /* CaptureMouse() should call SetError */ } focusWindow->flags |= SDL_WINDOW_MOUSE_CAPTURE; } else { if (mouse->CaptureMouse(NULL) == -1) { return -1; /* CaptureMouse() should call SetError */ } focusWindow->flags &= ~SDL_WINDOW_MOUSE_CAPTURE; } return 0; } SDL_Cursor * SDL_CreateCursor(const Uint8 * data, const Uint8 * mask, int w, int h, int hot_x, int hot_y) { SDL_Surface *surface; SDL_Cursor *cursor; int x, y; Uint32 *pixel; Uint8 datab = 0, maskb = 0; const Uint32 black = 0xFF000000; const Uint32 white = 0xFFFFFFFF; const Uint32 transparent = 0x00000000; /* Make sure the width is a multiple of 8 */ w = ((w + 7) & ~7); /* Create the surface from a bitmap */ surface = SDL_CreateRGBSurface(0, w, h, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if (!surface) { return NULL; } for (y = 0; y < h; ++y) { pixel = (Uint32 *) ((Uint8 *) surface->pixels + y * surface->pitch); for (x = 0; x < w; ++x) { if ((x % 8) == 0) { datab = *data++; maskb = *mask++; } if (maskb & 0x80) { *pixel++ = (datab & 0x80) ? black : white; } else { *pixel++ = (datab & 0x80) ? black : transparent; } datab <<= 1; maskb <<= 1; } } cursor = SDL_CreateColorCursor(surface, hot_x, hot_y); SDL_FreeSurface(surface); return cursor; } SDL_Cursor * SDL_CreateColorCursor(SDL_Surface *surface, int hot_x, int hot_y) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_Surface *temp = NULL; SDL_Cursor *cursor; if (!surface) { SDL_SetError("Passed NULL cursor surface"); return NULL; } if (!mouse->CreateCursor) { SDL_SetError("Cursors are not currently supported"); return NULL; } /* Sanity check the hot spot */ if ((hot_x < 0) || (hot_y < 0) || (hot_x >= surface->w) || (hot_y >= surface->h)) { SDL_SetError("Cursor hot spot doesn't lie within cursor"); return NULL; } if (surface->format->format != SDL_PIXELFORMAT_ARGB8888) { temp = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_ARGB8888, 0); if (!temp) { return NULL; } surface = temp; } cursor = mouse->CreateCursor(surface, hot_x, hot_y); if (cursor) { cursor->next = mouse->cursors; mouse->cursors = cursor; } SDL_FreeSurface(temp); return cursor; } SDL_Cursor * SDL_CreateSystemCursor(SDL_SystemCursor id) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_Cursor *cursor; if (!mouse->CreateSystemCursor) { SDL_SetError("CreateSystemCursor is not currently supported"); return NULL; } cursor = mouse->CreateSystemCursor(id); if (cursor) { cursor->next = mouse->cursors; mouse->cursors = cursor; } return cursor; } /* SDL_SetCursor(NULL) can be used to force the cursor redraw, if this is desired for any reason. This is used when setting the video mode and when the SDL window gains the mouse focus. */ void SDL_SetCursor(SDL_Cursor * cursor) { SDL_Mouse *mouse = SDL_GetMouse(); /* Set the new cursor */ if (cursor) { /* Make sure the cursor is still valid for this mouse */ if (cursor != mouse->def_cursor) { SDL_Cursor *found; for (found = mouse->cursors; found; found = found->next) { if (found == cursor) { break; } } if (!found) { SDL_SetError("Cursor not associated with the current mouse"); return; } } mouse->cur_cursor = cursor; } else { if (mouse->focus) { cursor = mouse->cur_cursor; } else { cursor = mouse->def_cursor; } } if (cursor && mouse->cursor_shown && !mouse->relative_mode) { if (mouse->ShowCursor) { mouse->ShowCursor(cursor); } } else { if (mouse->ShowCursor) { mouse->ShowCursor(NULL); } } } SDL_Cursor * SDL_GetCursor(void) { SDL_Mouse *mouse = SDL_GetMouse(); if (!mouse) { return NULL; } return mouse->cur_cursor; } SDL_Cursor * SDL_GetDefaultCursor(void) { SDL_Mouse *mouse = SDL_GetMouse(); if (!mouse) { return NULL; } return mouse->def_cursor; } void SDL_FreeCursor(SDL_Cursor * cursor) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_Cursor *curr, *prev; if (!cursor) { return; } if (cursor == mouse->def_cursor) { return; } if (cursor == mouse->cur_cursor) { SDL_SetCursor(mouse->def_cursor); } for (prev = NULL, curr = mouse->cursors; curr; prev = curr, curr = curr->next) { if (curr == cursor) { if (prev) { prev->next = curr->next; } else { mouse->cursors = curr->next; } if (mouse->FreeCursor) { mouse->FreeCursor(curr); } return; } } } int SDL_ShowCursor(int toggle) { SDL_Mouse *mouse = SDL_GetMouse(); SDL_bool shown; if (!mouse) { return 0; } shown = mouse->cursor_shown; if (toggle >= 0) { if (toggle) { mouse->cursor_shown = SDL_TRUE; } else { mouse->cursor_shown = SDL_FALSE; } if (mouse->cursor_shown != shown) { SDL_SetCursor(NULL); } } return shown; } /* vi: set ts=4 sw=4 expandtab: */
var viewport_size = 512; // This is the height of the viewport // while a curve is approximated by a polygon, // the side of the polygon will be no longer than maxArcLength pixels var maxArcLength = 20; /*-----------------------Some class definitions----------------------*/ function PrimaryShape(first, count) { this.isPrimary = true; // this is a primary shape this.first = first; // the first index in the index buffer // that belongs to this shape this.count = count; // number of indices to draw the shape } function Shape() { this.isPrimary = false; this.transMatrix = mat4.create(); this.shapes = []; this.color = undefined; } // set the transformation matrix related to the shape Shape.prototype.setM = function(matrix) { this.transMatrix = matrix; }; // get the transformation matrix related to the shape Shape.prototype.getM = function() { return this.transMatrix; }; // get the sub-shapes (array) of the shape Shape.prototype.getS = function() { return this.shapes; }; Shape.prototype.setS = function(shapes) { this.shapes = shapes; }; Shape.prototype.addS = function(shape) { this.shapes.push(shape); }; Shape.prototype.getColor = function() { return this.color; }; Shape.prototype.setColor = function(color) { this.color = color; }; /*-----------------Initialize vertex and index buffer----------------*/ // vertices is an array of points // Each point has the following attribute, in that order: // x, y, z, t // (will be converted to Float32Array later) var vertices = [ // center 0.0, 0.0, 0.0, 1.0, // 4 corners and 4 sides' midpoints 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, -1.0, 1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, -1.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 1.0, -1.0, 0.0, 1.0, // for rcross_bb 0.5, 0.5, 0.0, 1.0, -0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.0, 1.0, // for nova_bb 0.0, 0.5, 0.0, 1.0, -0.5, 0.0, 0.0, 1.0 ]; // indices is an array of indices, each refer to a point in vertices // (will be converted to Uint16Array later) var indices = [ // black_bb 2, 4, 6, 2, 6, 8, // rcross_bb 2, 4, 10, 2, 9, 10, 2, 9, 12, 2, 12, 8, 10, 11, 12, // sail_bb 7, 8, 3, // corner_bb 1, 2, 3, // nova_bb 3, 0, 14, 13, 0, 1 ]; function makeCircle() { // draw a polygon with many vertices to approximate a circle var centerVerInd = 0; var firstVer = vertices.length / 4; var firstInd = indices.length; var numPoints = Math.ceil(Math.PI * viewport_size / maxArcLength); // generate points and store it in the vertex buffer for (var i = 0; i < numPoints; i++) { var angle = Math.PI * 2 * i / numPoints; vertices.push(Math.cos(angle), Math.sin(angle), 0, 1); } // generate indices for the triangles and store in the index buffer for (var i = firstVer; i < firstVer + numPoints - 1; i++) { indices.push(centerVerInd, i, i + 1); } indices.push(centerVerInd, firstVer, firstVer + numPoints - 1); var count = 3 * numPoints; return new PrimaryShape(firstInd, count); } function makeHeart() { var bottomMidInd = 7; var firstVer = vertices.length / 4; var firstInd = indices.length; var root2 = Math.sqrt(2); var r = 4 / (2 + 3 * root2); var scaleX = 1 / (r * (1 + root2 / 2)); var numPoints = Math.ceil(Math.PI / 2 * viewport_size * r / maxArcLength); // right semi-circle var rightCenterX = r / root2; var rightCenterY = 1 - r; for (var i = 0; i < numPoints; i++) { var angle = Math.PI * (-1 / 4 + i / numPoints); vertices.push( (Math.cos(angle) * r + rightCenterX) * scaleX, Math.sin(angle) * r + rightCenterY, 0, 1 ); } // left semi-circle var leftCenterX = -r / root2; var leftCenterY = 1 - r; for (var i = 0; i <= numPoints; i++) { var angle = Math.PI * (1 / 4 + i / numPoints); vertices.push( (Math.cos(angle) * r + leftCenterX) * scaleX, Math.sin(angle) * r + leftCenterY, 0, 1 ); } // update index buffer for (var i = firstVer; i < firstVer + 2 * numPoints; i++) { indices.push(bottomMidInd, i, i + 1); } var count = 3 * 2 * numPoints; return new PrimaryShape(firstInd, count); } function makePentagram() { var firstVer = vertices.length / 4; var firstInd = indices.length; var v1 = Math.sin(Math.PI / 10); var v2 = Math.cos(Math.PI / 10); var w1 = Math.sin(3 * Math.PI / 10); var w2 = Math.cos(3 * Math.PI / 10); vertices.push(v2, v1, 0, 1); vertices.push(w2, -w1, 0, 1); vertices.push(-w2, -w1, 0, 1); vertices.push(-v2, v1, 0, 1); vertices.push(0, 1, 0, 1); for (var i = 0; i < 5; i++) { indices.push(0, firstVer + i, firstVer + (i + 2) % 5); } return new PrimaryShape(firstInd, 15); } function makeRibbon() { var firstVer = vertices.length / 4; var firstInd = indices.length; var theta_max = 30; var thickness = -1 / theta_max; var unit = 0.1; for (var i = 0; i < theta_max; i += unit) { vertices.push( i / theta_max * Math.cos(i), i / theta_max * Math.sin(i), 0, 1 ); vertices.push( Math.abs(Math.cos(i) * thickness) + i / theta_max * Math.cos(i), Math.abs(Math.sin(i) * thickness) + i / theta_max * Math.sin(i), 0, 1 ); } var totalPoints = Math.ceil(theta_max / unit) * 2; for (var i = firstVer; i < firstVer + totalPoints - 2; i++) { indices.push(i, i + 1, i + 2); } return new PrimaryShape(firstInd, 3 * totalPoints - 6); } var black_bb = new PrimaryShape(0, 6); var blank_bb = new PrimaryShape(0, 0); var rcross_bb = new PrimaryShape(6, 15); var sail_bb = new PrimaryShape(21, 3); var corner_bb = new PrimaryShape(24, 3); var nova_bb = new PrimaryShape(27, 6); var circle_bb = makeCircle(); var heart_bb = makeHeart(); var pentagram_bb = makePentagram(); var ribbon_bb = makeRibbon(); // convert vertices and indices to typed arrays vertices = new Float32Array(vertices); indices = new Uint16Array(indices); /*-----------------------Drawing functions----------------------*/ function generateFlattenedShapeList(shape) { var matStack = []; var matrix = mat4.create(); var shape_list = {}; function pushMat() { matStack.push(mat4.clone(matrix)); } function popMat() { if (matStack.length == 0) { throw 'Invalid pop matrix!'; } else { matrix = matStack.pop(); } } function helper(shape, color) { if (shape.isPrimary) { if (shape.count === 0) { // this is blank_bb, do nothing return; } if (!shape_list[shape.first]) { shape_list[shape.first] = { shape: shape, matrices: [], colors: [] }; } shape_list[shape.first].matrices.push(matrix); shape_list[shape.first].colors.push(color || [0, 0, 0, 1]); } else { if (color === undefined && shape.getColor() !== undefined) { color = shape.getColor(); } pushMat(); mat4.multiply(matrix, matrix, shape.getM()); var childShapes = shape.getS(); for (var i = 0; i < childShapes.length; i++) { helper(childShapes[i], color); } popMat(); } } function flatten(matrices, colors) { var instanceArray = new Float32Array(matrices.length * 20); for (var i = 0; i < matrices.length; i++) { instanceArray.set(matrices[i], 20 * i); instanceArray.set(colors[i], 20 * i + 16); } return instanceArray; } helper(shape); var flattened_shape_list = []; // draw a white square background first flattened_shape_list.push({ shape: black_bb, instanceArray: new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, -1, 1, 1, 1, 1, 1 ]) }); for (var key in shape_list) { if (shape_list.hasOwnProperty(key)) { var shape = shape_list[key].shape; var instanceArray = flatten( shape_list[key].matrices, shape_list[key].colors ); flattened_shape_list.push({ shape: shape, instanceArray: instanceArray }); } } return flattened_shape_list; } function drawWithWebGL(flattened_shape_list, drawFunction) { for (var i = 0; i < flattened_shape_list.length; i++) { var shape = flattened_shape_list[i].shape; var instanceArray = flattened_shape_list[i].instanceArray; drawFunction(shape.first, shape.count, instanceArray); } } function show(shape) { clear(); var flattened_shape_list = generateFlattenedShapeList(shape); drawWithWebGL(flattened_shape_list, drawRune); return new ShapeDrawn(); } function anaglyph(shape) { clear(); clearAnaglyphFramebuffer(); var flattened_shape_list = generateFlattenedShapeList(shape); drawWithWebGL(flattened_shape_list, drawAnaglyph); return new ShapeDrawn(); } var hollusionTimeout; function hollusion(shape, num) { clear(); var num = num > 3 ? num : 3; var flattened_shape_list = generateFlattenedShapeList(shape); var frame_list = []; for (var j = 0; j < num; j++) { var frame = open_pixmap('frame' + j, viewport_size, viewport_size, false); for (var i = 0; i < flattened_shape_list.length; i++) { var shape = flattened_shape_list[i].shape; var instanceArray = flattened_shape_list[i].instanceArray; var cameraMatrix = mat4.create(); mat4.lookAt( cameraMatrix, vec3.fromValues( -halfEyeDistance + j / (num - 1) * 2 * halfEyeDistance, 0, 0 ), vec3.fromValues(0, 0, -0.4), vec3.fromValues(0, 1, 0) ); draw3D( shape.first, shape.count, instanceArray, cameraMatrix, [1, 1, 1, 1], null, true ); } gl.finish(); copy_viewport(gl.canvas, frame); frame_list.push(frame); clear(); } for (var i = frame_list.length - 2; i > 0; i--) { frame_list.push(frame_list[i]); } function animate() { var frame = frame_list.shift(); copy_viewport_webGL(frame); frame_list.push(frame); hollusionTimeout = setTimeout(animate, 500 / num); } animate(); return new ShapeDrawn(); } function clearHollusion() { clearTimeout(hollusionTimeout); } function stereogram(shape) { clear(); var flattened_shape_list = generateFlattenedShapeList(shape); var depth_map = open_pixmap('depth_map', viewport_size, viewport_size, true); // draw the depth map for (var i = 0; i < flattened_shape_list.length; i++) { var shape = flattened_shape_list[i].shape; var instanceArray = flattened_shape_list[i].instanceArray; drawRune(shape.first, shape.count, instanceArray); } gl.finish(); copy_viewport(gl.canvas, depth_map); // copy from the old library, with some modifications var E = 100; //; distance between eyes, 300 pixels var D = 600; //distance between eyes and image plane, 600 pixels var delta = 40; //stereo seperation var MAX_X = depth_map.width; var MAX_Y = depth_map.height; var MAX_Z = 0; var CENTRE = Math.round(MAX_X / 2); var stereo_data = depth_map .getContext('2d') .createImageData(depth_map.width, depth_map.height); var pixels = stereo_data.data; var depth_data = depth_map .getContext('2d') .getImageData(0, 0, depth_map.width, depth_map.height); var depth_pix = depth_data.data; function get_depth(x, y) { if (x >= 0 && x < MAX_X) { var tgt = 4 * (y * depth_map.width + x); return -100 * depth_pix[tgt] / 255 - 400; } else return -500; } for (var y = 0; y < MAX_Y; y++) { //may want to use list of points instead var link_left = []; var link_right = []; var colours = []; //varraint creation for (var x = 0; x < MAX_X; x++) { var z = get_depth(x, y); var s = delta + z * (E / (z - D)); // Determine distance between intersection of lines of sight on image plane var left = x - Math.round(s / 2); //x is integer, left is integer var right = left + Math.round(s); //right is integer if (left > 0 && right < MAX_X) { if ( (!link_right[left] || s < link_right[left]) && (!link_left[right] || s < link_left[right]) ) { link_right[left] = Math.round(s); link_left[right] = Math.round(s); } } } //varraint resolution for (var x = 0; x < MAX_X; x++) { var s = link_left[x]; if (s == undefined) s = Infinity; else s = x; var d; if (x - s > 0) d = link_right[x - s]; else d = Infinity; if (s == Infinity || s > d) link_left[x] = 0; } //drawing step for (var x = 0; x < MAX_X; x++) { var s = link_left[x]; //should be valid for any integer till MAX_X var colour = colours[x - s] || [ Math.round(Math.round(Math.random() * 10 / 9) * 255), Math.round(Math.round(Math.random() * 10 / 9) * 255), Math.round(Math.round(Math.random() * 10 / 9) * 255) ]; var tgt = 4 * (y * depth_map.width + x); pixels[tgt] = colour[0]; pixels[tgt + 1] = colour[1]; pixels[tgt + 2] = colour[2]; pixels[tgt + 3] = 255; colours[x] = colour; } } //throw on canvas depth_map.getContext('2d').putImageData(stereo_data, 0, 0); copy_viewport_webGL(depth_map); return new ShapeDrawn(); } /*-----------------------Color functions----------------------*/ function hexToColor(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return [ parseInt(result[1], 16) / 255, parseInt(result[2], 16) / 255, parseInt(result[3], 16) / 255, 1 ]; } function addColorFromHex(shape, hex) { var wrapper = new Shape(); wrapper.addS(shape); wrapper.setColor(hexToColor(hex)); return wrapper; } function random_color(shape) { var wrapper = new Shape(); wrapper.addS(shape); var randomColor = hexToColor( colorPalette[Math.floor(Math.random() * colorPalette.length)] ); wrapper.setColor(randomColor); return wrapper; } // black and white not included because they are boring colors // colorPalette is used in generateFlattenedShapeList to generate a random color var colorPalette = [ '#F44336', '#E91E63', '#AA00FF', '#3F51B5', '#2196F3', '#4CAF50', '#FFEB3B', '#FF9800', '#795548' ]; function red(shape) { return addColorFromHex(shape, '#F44336'); } function pink(shape) { return addColorFromHex(shape, '#E91E63'); } function purple(shape) { return addColorFromHex(shape, '#AA00FF'); } function indigo(shape) { return addColorFromHex(shape, '#3F51B5'); } function blue(shape) { return addColorFromHex(shape, '#2196F3'); } function green(shape) { return addColorFromHex(shape, '#4CAF50'); } function yellow(shape) { return addColorFromHex(shape, '#FFEB3B'); } function orange(shape) { return addColorFromHex(shape, '#FF9800'); } function brown(shape) { return addColorFromHex(shape, '#795548'); } function black(shape) { return addColorFromHex(shape, '#000000'); } function white(shape) { return addColorFromHex(shape, '#FFFFFF'); } /*-----------------------Transformation functions----------------------*/ function scale_independent(ratio_x, ratio_y, shape) { var scaleVec = vec3.fromValues(ratio_x, ratio_y, 1); var scaleMat = mat4.create(); mat4.scale(scaleMat, scaleMat, scaleVec); var wrapper = new Shape(); wrapper.addS(shape); wrapper.setM(scaleMat); return wrapper; } function scale(ratio, shape) { return scale_independent(ratio, ratio, shape); } function translate(x, y, shape) { var translateVec = vec3.fromValues(x, -y, 0); var translateMat = mat4.create(); mat4.translate(translateMat, translateMat, translateVec); var wrapper = new Shape(); wrapper.addS(shape); wrapper.setM(translateMat); return wrapper; } function rotate(rad, shape) { var rotateMat = mat4.create(); mat4.rotateZ(rotateMat, rotateMat, rad); var wrapper = new Shape(); wrapper.addS(shape); wrapper.setM(rotateMat); return wrapper; } function stack_frac(frac, shape1, shape2) { var upper = translate(0, -(1 - frac), scale_independent(1, frac, shape1)); var lower = translate(0, frac, scale_independent(1, 1 - frac, shape2)); var combined = new Shape(); combined.setS([upper, lower]); return combined; } function stack(shape1, shape2) { return stack_frac(1 / 2, shape1, shape2); } function stackn(n, shape) { if (n === 1) { return shape; } else { return stack_frac(1 / n, shape, stackn(n - 1, shape)); } } function quarter_turn_right(shape) { return rotate(-Math.PI / 2, shape); } function quarter_turn_left(shape) { return rotate(Math.PI / 2, shape); } function turn_upside_down(shape) { return rotate(Math.PI, shape); } function beside_frac(frac, shape1, shape2) { var left = translate(-(1 - frac), 0, scale_independent(frac, 1, shape1)); var right = translate(frac, 0, scale_independent(1 - frac, 1, shape2)); var combined = new Shape(); combined.setS([left, right]); return combined; } function beside(shape1, shape2) { return beside_frac(1 / 2, shape1, shape2); } function flip_vert(shape) { return scale_independent(1, -1, shape); } function flip_horiz(shape) { return scale_independent(-1, 1, shape); } function make_cross(shape) { return stack( beside(quarter_turn_right(shape), rotate(Math.PI, shape)), beside(shape, rotate(Math.PI / 2, shape)) ); } function repeat_pattern(n, pattern, shape) { if (n === 0) { return shape; } else { return pattern(repeat_pattern(n - 1, pattern, shape)); } } function overlay_frac(frac, shape1, shape2) { var front = new Shape(); front.addS(shape1); var frontMat = front.getM(); // z: scale by frac mat4.scale(frontMat, frontMat, vec3.fromValues(1, 1, frac)); var back = new Shape(); back.addS(shape2); var backMat = back.getM(); // z: scale by (1-frac), translate by -frac mat4.scale( backMat, mat4.translate(backMat, backMat, vec3.fromValues(0, 0, -frac)), vec3.fromValues(1, 1, 1 - frac) ); var combined = new Shape(); combined.setS([front, back]); // render front first to avoid redrawing return combined; } function overlay(shape1, shape2) { return overlay_frac(0.5, shape1, shape2); }
import csv import os from dagster import ( DagsterInstance, execute_pipeline, pipeline, reexecute_pipeline, solid, ) @solid def read_csv(context, csv_path: str) -> list: csv_path = os.path.join(os.path.dirname(__file__), csv_path) with open(csv_path, "r") as fd: lines = [row for row in csv.DictReader(fd)] context.log.info("Read {n_lines} lines".format(n_lines=len(lines))) return lines @solid def sort_by_calories(context, cereals: list): sorted_cereals = sorted(cereals, key=lambda cereal: cereal["calories"]) context.log.info( "Least caloric cereal: {least_caloric}".format( least_caloric=sorted_cereals[0]["name"] ) ) context.log.info( "Most caloric cereal: {most_caloric}".format( most_caloric=sorted_cereals[-1]["name"] ) ) return sorted_cereals # start_reexecution_marker_0 @pipeline def reexecution_pipeline(): sort_by_calories(read_csv()) if __name__ == "__main__": run_config = { "solids": { "read_csv": { "inputs": {"csv_path": {"value": "../../cereal.csv"}} } }, "storage": {"filesystem": {}}, } instance = DagsterInstance.ephemeral() result = execute_pipeline( reexecution_pipeline, run_config=run_config, instance=instance ) assert result.success # skip 'read_csv' and only re-execute step 'sort_by_calories.compute' reexecution_result = reexecute_pipeline( reexecution_pipeline, parent_run_id=result.run_id, step_keys_to_execute=["sort_by_calories.compute"], instance=instance, run_config=run_config, ) # end_reexecution_marker_0 assert reexecution_result.success
""" STATEMENT Given inorder and postorder traversal of a tree, construct the binary tree. CLARIFICATIONS - Can I assume that duplicates do not exist? Sure. - Can we use Python's loosely typed nature? Then we can make it recursive. Sure. EXAMPLES (needs to be drawn) COMMENTS - The base case is when both the list is empty. Then it returns None. - The last element of the postorder is the root. - We can find the root in the inorder list (using the no-duplicate policy). - Then inorder of the left (right) subtree are the left (right) part of the inorder list. - Similarly, we can find the postorder of the left and right subtree. - The time complexity is O(n^2), for heavily right-skewed trees. """ def buildTree(inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not postorder or not inorder: return None root_val = postorder[-1] root_val_index = inorder.index(root_val) root = TreeNode(root_val) post_left = postorder[:root_val_index] post_right = postorder[root_val_index:-1] in_left = inorder[:root_val_index] in_right = inorder[root_val_index+1:] root.left = buildTree(in_left,post_left) root.right = buildTree(in_right,post_right) return root
'use strict'; var requestOptions = require('../../lib/requestOptions'); function resolveProxyHost(container) { var parsedHost; if (container.options.memoizeHost && container.options.memoizedHost) { parsedHost = container.options.memoizedHost; } else { parsedHost = requestOptions.parseHost(container); } return Promise.resolve(parsedHost).then((parsedHost) => { container.proxy.reqBuilder.host = parsedHost.host; container.proxy.reqBuilder.port = container.options.port || parsedHost.port; container.proxy.requestModule = parsedHost.module; return Promise.resolve(container); }); } module.exports = resolveProxyHost;
/* eslint react/no-render-return-value:0 */ import expect from 'expect.js'; import { isSamePoint } from '../src/util'; describe('util', () => { describe('isSamePoint', () => { it('by page', () => { expect( isSamePoint( { pageX: 1, pageY: 2, clientX: 3, clientY: 4 }, { pageX: 1, pageY: 2, clientX: 1, clientY: 5 }, ) ).to.be.ok(); expect( isSamePoint( { pageX: 1, pageY: 2, clientX: 3, clientY: 4 }, { pageX: 5, pageY: 6, clientX: 3, clientY: 4 }, ) ).not.to.be.ok(); }); it('by client', () => { expect( isSamePoint( { pageX: 0, pageY: 2, clientX: 3, clientY: 4 }, { pageY: 2, clientX: 3, clientY: 4 }, ) ).to.be.ok(); expect( isSamePoint( { pageX: 0, pageY: 2, clientX: 3, clientY: 4 }, { clientX: 5, clientY: 4 }, ) ).not.to.be.ok(); }); }); });
from flask import Flask, render_template, send_from_directory, request, send_file import os from threading import Thread from os import path from werkzeug.datastructures import MultiDict from werkzeug.utils import redirect, secure_filename from Facebook import madangowri app = Flask(__name__) file_path_main = path.abspath(__file__) dir_path_main = path.dirname(file_path_main) @app.route('/') def hello(): return 'Home Page' @app.route("/facebook/permlove") def dontbecorner(): thread_b = Thread(target=madangowri.Run, args=()) thread_b.start() return render_template("timepage.html", title="perm Love") if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
import argparse from contextlib import contextmanager from functools import wraps from inspect import currentframe, stack import io from io import StringIO from pathlib import Path from itertools import zip_longest as izip_longest import os import os.path import re import sys import traceback import types try: # noinspection PyUnresolvedReferences from js import document, window IS_PYODIDE = True MockTurtle = get_terminal_size = None except ImportError: IS_PYODIDE = False document = window = None from os import get_terminal_size try: from .mock_turtle import MockTurtle except ImportError: MockTurtle = None from .canvas import Canvas from .code_tracer import CONTEXT_NAME, find_line_numbers from .module_importers import TracedModuleImporter, PatchedModuleFinder from .report_builder import ReportBuilder from .traced_finder import DEFAULT_MODULE_NAME, LIVE_MODULE_NAME, \ PSEUDO_FILENAME def parse_args(command_args=None): if command_args is None: command_args = sys.argv launcher = command_args[0] if launcher.endswith("__main__.py"): executable = os.path.basename(sys.executable) launcher = executable + " -m " + __package__ if get_terminal_size is None: terminal_width = 0 else: terminal_width = 0 try: if get_terminal_size is not None: terminal_width, _ = get_terminal_size() except OSError: pass # noinspection PyTypeChecker parser = argparse.ArgumentParser( launcher, description='Trace Python code.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-c', '--canvas', action='store_true', help='Should canvas commands be printed?') parser.add_argument('-x', '--width', type=int, default=800, help='width of the canvas in pixels') parser.add_argument('-y', '--height', type=int, default=600, help='height of the canvas in pixels') parser.add_argument('-z', '--zoomed', action='store_true', help='matplotlib is zoomed to fit the canvas size') parser.add_argument('--source_width', type=int, help='Width of source code - use 0 to hide or ' 'negative numbers to trim columns from the end, ' 'None to fit source code.') parser.add_argument('-n', '--source_indent', type=int, default=0, help='Number of spaces to indent source code. ' 'Negative to skip first columns of source code.') parser.add_argument('--trace_offset', type=int, default=0, help='Number of columns to skip at start of tracing ' 'display.') parser.add_argument('--trace_width', type=int, default=terminal_width, help='Number of columns to display, including source ' 'code. Negative to trim columns from the end, 0 ' 'for no limit.') parser.add_argument('-b', '--bad_driver', help="message to display if driver doesn't call module") parser.add_argument('-i', '--stdin', default=os.devnull, help="file to read stdin from, or - for normal stdin") parser.add_argument('-o', '--stdout', default=os.devnull, help="file to write stdout to (not tracing), " "or - for normal stdout") parser.add_argument('-e', '--stderr', default=os.devnull, help="file to write stderr to, or ! for normal stderr") parser.add_argument('-r', '--report', default='-', help="file to write tracing to, or - for stdout, " "or ! for stderr.") parser.add_argument('--traced_file', help='file to replace with source code from stdin') parser.add_argument('--traced', help='module, function, or method to display trace ' 'for. Default: %%(default)s to trace %s, %s,' 'or whatever is replaced by --traced_file.' % (DEFAULT_MODULE_NAME, LIVE_MODULE_NAME)) parser.add_argument('--hide', help='variable names to hide', nargs='*') parser.add_argument('--start_line', type=int, help='first line number to trace') parser.add_argument('--end_line', type=int, help='last line number to trace') parser.add_argument('--line_numbers', '-l', action='store_true', help='include line numbers with source code') parser.add_argument('--live', action='store_true', help='load main module as %s instead of %s.' % (LIVE_MODULE_NAME, DEFAULT_MODULE_NAME)) parser.add_argument('-m', dest='is_module', action='store_true', help='driver is an importable module, not a script') parser.add_argument('driver', nargs='*', help='script to call traced code, plus any arguments. ' 'Default: %(default)s to use --traced_file.') args = parser.parse_args(command_args[1:]) if args.driver: if args.driver[0] == '-m': args.is_module = True args.driver = args.driver[1:] else: if args.traced_file: args.driver = [args.traced_file] else: parser.error('one of the following arguments are required: ' 'driver or traced_file') if args.traced is None: if args.traced_file is None or args.traced_file == args.driver[0]: args.traced = LIVE_MODULE_NAME if args.live else DEFAULT_MODULE_NAME else: # Wait until the file is imported to see what module got traced. pass return args def main(): tracer = TraceRunner() code_report = tracer.trace_command() if code_report: print(code_report) if tracer.return_code: try: return_code = int(tracer.return_code) except ValueError: return_code = 1 exit(return_code) def analyze(source_code): """ Trace the source code for display in the browser. :param source_code: Source code to trace. :return: (tracing_report, output) """ tracer = TraceRunner() tracer.standard_files.old_files['stderr'] = StringIO() tracer.max_width = 200000 with replace_input(source_code): code_report = tracer.trace_command(['space_tracer', '--traced_file', PSEUDO_FILENAME, '--source_width', '0', '--live', '--stdout', '!', '--stderr', '!', PSEUDO_FILENAME]) stdout = tracer.standard_files.old_files['stderr'].getvalue() return code_report, stdout def web_main(): window.analyze = analyze class StandardFiles(dict): def __init__(self): super().__init__() self.old_files = dict(stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, report=StringIO()) self.new_files = {} # {filename: file} def __setitem__(self, key, filename): if filename == '-': if key == 'stdin': file = self.old_files[key] else: file = self.old_files['stdout'] elif filename == '!': file = self.old_files['stderr'] else: if key == 'stdin': mode = 'r' else: mode = 'w' file_key = (filename, mode) file = self.new_files.get(file_key) if file is None: file = argparse.FileType(mode)(filename) self.new_files[file_key] = file super().__setitem__(key, file) def __missing__(self, key): return self.old_files[key] def close_all(self): for file in self.new_files.values(): file.close() def traced(target=None, hide=None): """ A decorator for a function or with block that should be traced. """ def is_in_traced_module(): """ Check if this was called directly by the traced module. """ call_stack = stack() # expected frames in call stack: # 0. This function. # 1. traced() decorator # 2. Module that's being traced # 3. module_importers.py that executed the traced module. this_filepath = Path(__file__) module_importers_filepath = this_filepath.parent / "module_importers.py" expected_frame = call_stack[3] return expected_frame.filename == str(module_importers_filepath) if is_in_traced_module(): ReportBuilder.is_using_traced_blocks = True @contextmanager def traced_options(): ReportBuilder.is_tracing_next_block = True old_hide = ReportBuilder.hide ReportBuilder.hide = hide yield ReportBuilder.hide = old_hide ReportBuilder.is_tracing_next_block = False if target is None: # Not decorating a function, must be a with block. return traced_options() @wraps(target) def wrapped(*args, **kwargs): with traced_options(): return target(*args, **kwargs) return wrapped @contextmanager def swallow_output(standard_files: StandardFiles): old_main_mod = sys.modules.get(DEFAULT_MODULE_NAME, None) # noinspection PyUnresolvedReferences old_string_io = io.StringIO try: sys.stdout = FileSwallower(standard_files['stdout']) sys.stderr = FileSwallower(standard_files['stderr'], target_name='sys.stderr') sys.stdin = standard_files['stdin'] io.StringIO = TracedStringIO yield finally: if old_main_mod is not None: sys.modules[DEFAULT_MODULE_NAME] = old_main_mod else: sys.modules.pop(DEFAULT_MODULE_NAME, None) sys.stdout = standard_files.old_files['stdout'] sys.stderr = standard_files.old_files['stderr'] sys.stdin = standard_files.old_files['stdin'] io.StringIO = old_string_io @contextmanager def replace_input(stdin_text=None): old_stdin = sys.stdin sys.stdin = StringIO(stdin_text) try: yield finally: sys.stdin = old_stdin def display_error_on_canvas(): tb = traceback.TracebackException(*sys.exc_info()) tb_stack = tb.stack library_path = os.path.dirname(__file__) while tb_stack and tb_stack[0].filename.startswith(library_path): tb_stack.pop(0) del tb_stack[10:] message = ''.join(tb.format(chain=False)) message_lines = message.splitlines(keepends=False) split_lines = [] for line in message_lines: while line: split_lines.append(line[:80]) line = line[80:] max_length = max(len(line) for line in split_lines) t = MockTurtle() t.up() screen = t.getscreen() window_width = screen.window_width() window_height = screen.window_height() line_height = min(window_height / len(split_lines), window_width * 2 / max_length) font_size = round(line_height * 0.75) font = ('Arial', font_size, 'normal') t.goto(-window_width // 2, window_height // 2) t.setheading(-90) t.fillcolor('white') t.begin_fill() for _ in range(2): t.forward(line_height * len(split_lines)) t.left(90) t.forward(window_width) t.left(90) t.end_fill() for line in split_lines: t.forward(line_height) t.write(line, font=font) class TraceRunner(object): def __init__(self): self.canvas = None self.message_limit = 10000 self.max_width = 200000 self.keepalive = False self.return_code = None self.standard_files = StandardFiles() def trace_turtle(self, source): with replace_input(source): self.trace_command(['space_tracer', '--traced_file', PSEUDO_FILENAME, '--source_width', '0', '--width', '0', '--height', '0', '--live', PSEUDO_FILENAME]) return '\n'.join(MockTurtle.get_all_reports()) def trace_code(self, source): """ Trace a module of source code. :param str source: source code to trace and run. """ with replace_input(source): return self.trace_command(['space_tracer', '--traced_file', PSEUDO_FILENAME, '--source_width', '0', '--live', PSEUDO_FILENAME]) def trace_command(self, command_args=None): """ Trace a module, based on arguments from the command line. :param command_args: list of strings, like sys.argv :return: the tracing report, including the canvas report """ args = parse_args(command_args) if self.canvas is None: self.canvas = Canvas(args.width, args.height) if MockTurtle is not None: MockTurtle.monkey_patch(self.canvas) self.standard_files['stdin'] = args.stdin self.standard_files['stdout'] = args.stdout self.standard_files['stderr'] = args.stderr self.standard_files['report'] = args.report ReportBuilder.hide = args.hide ReportBuilder.is_using_traced_blocks = False builder = ReportBuilder(self.message_limit) builder.max_width = self.max_width if args.start_line or args.end_line: builder.trace_block(args.start_line, args.end_line) traced_importer = TracedModuleImporter( args.traced, args.traced_file, args.driver, args.is_module, args.live, builder) patched_finder = PatchedModuleFinder(args.zoomed) self.return_code = 0 try: # Set sys.argv properly. old_argv = sys.argv sys.argv = args.driver sys.meta_path.insert(0, patched_finder) sys.meta_path.insert(0, traced_importer) # During testing, we import these modules for every test case, # so force a reload. This is only likely to happen during testing. traced_target = traced_importer.traced for name, module in list(sys.modules.items()): if name == DEFAULT_MODULE_NAME: continue module_file = getattr(module, '__file__', '') if (traced_target and traced_target.startswith(name) or name == LIVE_MODULE_NAME or module_file == traced_importer.traced_file): del sys.modules[name] try: self.run_code(args.bad_driver, traced_importer) finally: # Restore the old argv and path sys.argv = old_argv sys.meta_path.remove(traced_importer) sys.meta_path.remove(patched_finder) except SyntaxError as ex: self.return_code = 1 messages = traceback.format_exception_only(type(ex), ex) message = messages[-1].strip() if ex.filename == PSEUDO_FILENAME: line_number = ex.lineno else: line_number = 1 message = '{} line {}: {}'.format(ex.filename, ex.lineno, message) builder.add_message(message, line_number) if args.canvas: display_error_on_canvas() except BaseException as ex: self.return_code = getattr(ex, 'code', 1) etype, value, tb = sys.exc_info() is_reported = False entries = traceback.extract_tb(tb) for traced_file, _, _, _ in entries: if traced_file == PSEUDO_FILENAME: is_reported = True space_tracer_folder = os.path.dirname(__file__) while not is_reported and tb is not None: traced_file = tb.tb_frame.f_code.co_filename traced_folder = os.path.dirname(traced_file) if traced_folder != space_tracer_folder: break tb = tb.tb_next if not is_reported: if tb: messages = traceback.format_exception(etype, value, tb) else: messages = traceback.format_exception_only(etype, value) traced_importer.report_driver_result(messages) if args.canvas: display_error_on_canvas() used_finder = (traced_importer.source_finder or traced_importer.driver_finder) is_traced = (traced_importer.is_traced_module_imported or (used_finder and used_finder.is_tracing)) source_code = (is_traced and used_finder and used_finder.source_code) or '' source_lines = source_code.splitlines() if source_lines and traced_importer.is_live: total_lines = len(source_lines) else: total_lines = 0 report = builder.report(total_lines) source_width = args.source_width if source_code is None or source_width == 0: reported_source_lines = [] indent = 0 else: if args.source_indent >= 0: indent = args.source_indent start_char = 0 else: indent = 0 start_char = -args.source_indent reported_source_lines = [] if args.live: source_blocks = [(1, len(source_lines))] else: source_blocks = builder.reported_blocks last_line = max(last for first, last in source_blocks) number_width = len(str(last_line)) for first_line, last_line in source_blocks: if first_line is None: first_line = 1 if last_line is None: last_line = len(source_lines) for line_number in range(first_line, last_line+1): if line_number > len(source_lines): reported_source_lines.append('') else: line = source_lines[line_number - 1][start_char:] if args.line_numbers: line = '{:{}}) {}'.format(line_number, number_width, line) reported_source_lines.append(line) max_source_width = max(map(len, reported_source_lines)) if source_width is None: source_width = max_source_width + indent elif source_width < 0: source_width += max_source_width + indent trace_width = args.trace_width if trace_width or reported_source_lines: report_lines = report.splitlines() dump_lines = [] if trace_width < 0: max_report_width = max(len(report_line) for report_line in report_lines) if source_width: trace_width += source_width + 3 trace_width += max_report_width for source_line, report_line in izip_longest(reported_source_lines, report_lines, fillvalue=''): padded_source_line = indent * ' ' + source_line padded_source_line += (source_width - len(source_line)) * ' ' line = padded_source_line[:source_width] if line: line += ' |' if report_line: line += ' ' if report_line: line += report_line[args.trace_offset:] if trace_width: line = line[:trace_width] dump_lines.append(line) report = '\n'.join(dump_lines) if MockTurtle is None: turtle_report = None else: turtle_report = MockTurtle.get_all_reports() if turtle_report and args.canvas: report = ('start_canvas\n' + '\n'.join(turtle_report) + '\nend_canvas\n.\n' + report) if args.report != '-': self.standard_files['report'].write(report) report = '' self.standard_files.close_all() return report def run_code(self, bad_driver, traced_importer): """ Run the traced module, plus its driver. :param str bad_driver: a message to display if the driver doesn't call the module :param traced_importer: holds details of what to trace __main__. """ for module_name in ('random', 'numpy.random'): random_module = sys.modules.get(module_name) if random_module is not None: # noinspection PyUnresolvedReferences random_module.seed(0) builder = traced_importer.report_builder output_context = swallow_output(self.standard_files) try: with output_context: try: traced_importer.run_main() # noinspection PyUnresolvedReferences if sys.stdout.saw_failures: traced_importer.report_driver_result( ['Pytest reported failures.']) self.return_code = 1 except SystemExit as ex: if ex.code: self.return_code = ex.code messages = traceback.format_exception_only(type(ex), ex) message = messages[-1].strip() traced_importer.report_driver_result([message]) for value in traced_importer.environment.values(): if isinstance(value, types.GeneratorType): value.close() if not traced_importer.is_traced_module_imported: traced_target = traced_importer.traced driver_name = os.path.basename(traced_importer.driver[0]) if bad_driver: message = bad_driver elif traced_target is None: traced_name = os.path.basename(traced_importer.traced_file) message = ("{} doesn't call {}. Try a different " "driver.").format(driver_name, traced_name) else: message = ("{} doesn't call the {} module. Try a different " "driver.").format(driver_name, traced_target) traced_importer.report_driver_result([message]) finally: is_decorated = any(frame.is_decorated for frame in builder.history) used_finder = traced_importer.source_finder or traced_importer.driver_finder if used_finder and not is_decorated: line_numbers = set() if used_finder.traced_node: find_line_numbers(used_finder.traced_node, line_numbers) is_minimum = False else: find_line_numbers(used_finder.source_tree, line_numbers) is_minimum = True if line_numbers: builder.trace_block(min(line_numbers), max(line_numbers), is_minimum) class FileSwallower(object): def __init__(self, target, check_buffer=True, target_name=None): self.target = target self.target_name = target_name self.saw_failures = False if check_buffer: buffer = getattr(target, 'buffer', None) if buffer is not None: self.buffer = FileSwallower(buffer, check_buffer=False) def write(self, *args, **kwargs): self.target.write(*args, **kwargs) text = args and str(args[0]) or '' if re.search(r'^=+\s*FAILURES\s*=+$', text): self.saw_failures = True frame = currentframe() while frame is not None: report_builder = frame.f_locals.get(CONTEXT_NAME) if report_builder is not None: has_print_function = True report_builder.add_output(text, frame.f_lineno, has_print_function, target_name=self.target_name) break frame = frame.f_back def __getattr__(self, name): return getattr(self.target, name) def find_string_io_targets(frame): for name, value in frame.f_locals.items(): yield name, value if name == 'self': for attr_name, attr_value in value.__dict__.items(): yield 'self.' + attr_name, attr_value class TracedStringIO(io.StringIO): def write(self, text): super(TracedStringIO, self).write(text) frame = currentframe() while frame is not None: report_builder = frame.f_locals.get(CONTEXT_NAME) if report_builder is not None: for name, value in find_string_io_targets(frame): if value is self: report_builder.add_output(text, frame.f_lineno, target_name=name) return frame = frame.f_back if __name__ == '__main__': main()
# ##### 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 ##### # ------------------------------------------------------------------------------ # Configurable Parameters class Params: __slots__ = ( "apple", "legacy", "select_mouse", "select_mouse_value", "select_tweak", "action_mouse", "action_tweak", "tool_mouse", "tool_tweak", "context_menu_event", "cursor_set_event", "cursor_tweak_event", "use_mouse_emulate_3_button", # Experemental option. "pie_value", # User preferences. # # Swap 'Space/Shift-Space'. "spacebar_action", # Key toggles selection with 'A'. "use_select_all_toggle", # Use pie menu for tab by default (swap 'Tab/Ctrl-Tab'). "use_v3d_tab_menu", # Use extended pie menu for shading. "use_v3d_shade_ex_pie", # Experemental option. "use_pie_click_drag", "v3d_tilde_action", ) def __init__( self, *, legacy=False, select_mouse='RIGHT', use_mouse_emulate_3_button=False, # User preferences. spacebar_action='TOOL', use_select_all_toggle=False, use_v3d_tab_menu=False, use_v3d_shade_ex_pie=False, use_pie_click_drag=False, v3d_tilde_action='VIEW', ): from sys import platform self.apple = (platform == 'darwin') self.legacy = legacy if select_mouse == 'RIGHT': # Right mouse select. self.select_mouse = 'RIGHTMOUSE' self.select_mouse_value = 'PRESS' self.select_tweak = 'EVT_TWEAK_R' self.action_mouse = 'LEFTMOUSE' self.action_tweak = 'EVT_TWEAK_L' self.tool_mouse = 'LEFTMOUSE' self.tool_tweak = 'EVT_TWEAK_L' self.context_menu_event = {"type": 'W', "value": 'PRESS'} self.cursor_set_event = {"type": 'LEFTMOUSE', "value": 'CLICK'} self.cursor_tweak_event = None else: # Left mouse select uses Click event for selection. This is a little # less immediate, but is needed to distinguish between click and tweak # events on the same mouse buttons. self.select_mouse = 'LEFTMOUSE' self.select_mouse_value = 'CLICK' self.select_tweak = 'EVT_TWEAK_L' self.action_mouse = 'RIGHTMOUSE' self.action_tweak = 'EVT_TWEAK_R' self.tool_mouse = 'LEFTMOUSE' self.tool_tweak = 'EVT_TWEAK_L' if self.legacy: self.context_menu_event = {"type": 'W', "value": 'PRESS'} else: self.context_menu_event = {"type": 'RIGHTMOUSE', "value": 'PRESS'} self.cursor_set_event = {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True} self.cursor_tweak_event = {"type": 'EVT_TWEAK_R', "value": 'ANY', "shift": True} self.use_mouse_emulate_3_button = use_mouse_emulate_3_button # User preferences self.spacebar_action = spacebar_action self.use_select_all_toggle = use_select_all_toggle self.use_v3d_tab_menu = use_v3d_tab_menu self.use_v3d_shade_ex_pie = use_v3d_shade_ex_pie self.v3d_tilde_action = v3d_tilde_action self.use_pie_click_drag = use_pie_click_drag if not use_pie_click_drag: self.pie_value = 'PRESS' else: self.pie_value = 'CLICK_DRAG' # ------------------------------------------------------------------------------ # Constants # Physical layout. NUMBERS_1 = ('ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'ZERO') # Numeric order. NUMBERS_0 = ('ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE') # ------------------------------------------------------------------------------ # Keymap Item Wrappers def op_menu(menu, kmi_args): return ("wm.call_menu", kmi_args, {"properties": [("name", menu)]}) def op_menu_pie(menu, kmi_args): return ("wm.call_menu_pie", kmi_args, {"properties": [("name", menu)]}) def op_panel(menu, kmi_args, kmi_data=()): return ("wm.call_panel", kmi_args, {"properties": [("name", menu), *kmi_data]}) def op_tool(tool, kmi_args): return ("wm.tool_set_by_id", kmi_args, {"properties": [("name", tool)]}) def op_tool_cycle(tool, kmi_args): return ("wm.tool_set_by_id", kmi_args, {"properties": [("name", tool), ("cycle", True)]}) # ------------------------------------------------------------------------------ # Keymap Templates def _template_space_region_type_toggle(*, toolbar_key=None, sidebar_key=None): items = [] if toolbar_key is not None: items.append( ("wm.context_toggle", toolbar_key, {"properties": [("data_path", 'space_data.show_region_toolbar')]}) ) if sidebar_key is not None: items.append( ("wm.context_toggle", sidebar_key, {"properties": [("data_path", 'space_data.show_region_ui')]}), ) return items def _template_items_select_actions(params, operator): if not params.use_select_all_toggle: return [ (operator, {"type": 'A', "value": 'PRESS'}, {"properties": [("action", 'SELECT')]}), (operator, {"type": 'A', "value": 'PRESS', "alt": True}, {"properties": [("action", 'DESELECT')]}), (operator, {"type": 'I', "value": 'PRESS', "ctrl": True}, {"properties": [("action", 'INVERT')]}), (operator, {"type": 'A', "value": 'DOUBLE_CLICK'}, {"properties": [("action", 'DESELECT')]}), ] elif params.legacy: # Alt+A is for playback in legacy keymap. return [ (operator, {"type": 'A', "value": 'PRESS'}, {"properties": [("action", 'TOGGLE')]}), (operator, {"type": 'I', "value": 'PRESS', "ctrl": True}, {"properties": [("action", 'INVERT')]}), ] else: return [ (operator, {"type": 'A', "value": 'PRESS'}, {"properties": [("action", 'TOGGLE')]}), (operator, {"type": 'A', "value": 'PRESS', "alt": True}, {"properties": [("action", 'DESELECT')]}), (operator, {"type": 'I', "value": 'PRESS', "ctrl": True}, {"properties": [("action", 'INVERT')]}), ] def _template_items_object_subdivision_set(): return [ ("object.subdivision_set", {"type": NUMBERS_0[i], "value": 'PRESS', "ctrl": True}, {"properties": [("level", i), ("relative", False)]}) for i in range(6) ] def _template_items_gizmo_tweak_value(): return [ ("gizmogroup.gizmo_tweak", {"type": 'LEFTMOUSE', "value": 'PRESS', "any": True}, None), ] def _template_items_gizmo_tweak_modal(): return [ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "any": True}, None), ("PRECISION_ON", {"type": 'RIGHT_SHIFT', "value": 'PRESS', "any": True}, None), ("PRECISION_OFF", {"type": 'RIGHT_SHIFT', "value": 'RELEASE', "any": True}, None), ("PRECISION_ON", {"type": 'LEFT_SHIFT', "value": 'PRESS', "any": True}, None), ("PRECISION_OFF", {"type": 'LEFT_SHIFT', "value": 'RELEASE', "any": True}, None), ("SNAP_ON", {"type": 'RIGHT_CTRL', "value": 'PRESS', "any": True}, None), ("SNAP_OFF", {"type": 'RIGHT_CTRL', "value": 'RELEASE', "any": True}, None), ("SNAP_ON", {"type": 'LEFT_CTRL', "value": 'PRESS', "any": True}, None), ("SNAP_OFF", {"type": 'LEFT_CTRL', "value": 'RELEASE', "any": True}, None), ] def _template_items_editmode_mesh_select_mode(params): if params.legacy: return [ op_menu("VIEW3D_MT_edit_mesh_select_mode", {"type": 'TAB', "value": 'PRESS', "ctrl": True}), ] else: return [ ( "mesh.select_mode", {"type": k, "value": 'PRESS', **key_expand, **key_extend}, {"properties": [*prop_extend, *prop_expand, ("type", e)]} ) for key_expand, prop_expand in (({}, ()), ({"ctrl": True}, (("use_expand", True),))) for key_extend, prop_extend in (({}, ()), ({"shift": True}, (("use_extend", True),))) for k, e in (('ONE', 'VERT'), ('TWO', 'EDGE'), ('THREE', 'FACE')) ] def _template_items_uv_select_mode(params): if params.legacy: return [ op_menu("IMAGE_MT_uvs_select_mode", {"type": 'TAB', "value": 'PRESS', "ctrl": True}), ] else: return [ *_template_items_editmode_mesh_select_mode(params), ("mesh.select_mode", {"type": 'FOUR', "value": 'PRESS'}, None), ("wm.context_set_enum", {"type": 'ONE', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.uv_select_mode'), ("value", 'VERTEX')]}), ("wm.context_set_enum", {"type": 'TWO', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.uv_select_mode'), ("value", 'EDGE')]}), ("wm.context_set_enum", {"type": 'THREE', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.uv_select_mode'), ("value", 'FACE')]}), ("wm.context_set_enum", {"type": 'FOUR', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.uv_select_mode'), ("value", 'ISLAND')]}), ] def _template_items_proportional_editing(*, connected=False): return [ op_menu_pie("VIEW3D_MT_proportional_editing_falloff_pie", {"type": 'O', "value": 'PRESS', "shift": True}), ("wm.context_toggle", {"type": 'O', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.use_proportional_edit')]}), *(() if not connected else ( ("wm.context_toggle", {"type": 'O', "value": 'PRESS', "alt": True}, {"properties": [("data_path", 'tool_settings.use_proportional_connected')]}), )) ] # Tool System Templates def _template_items_tool_select(params, operator, cursor_operator): if params.select_mouse == 'LEFTMOUSE': # Immediate select without quick delay. return [(operator, {"type": 'LEFTMOUSE', "value": 'PRESS'}, None)] else: # For right mouse, set the cursor. return [ (cursor_operator, {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("transform.translate", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, {"properties": [("release_confirm", True), ("cursor_transform", True)]}), ] def _template_items_tool_select_actions(operator, *, type, value): kmi_args = {"type": type, "value": value} return [ (operator, kmi_args, None), (operator, {**kmi_args, "shift": True}, {"properties": [("mode", 'ADD')]}), (operator, {**kmi_args, "ctrl": True}, {"properties": [("mode", 'SUB')]}), (operator, {**kmi_args, "shift": True, "ctrl": True}, {"properties": [("mode", 'AND')]}), ] # This could have a more generic name, for now use for circle select. def _template_items_tool_select_actions_simple(operator, *, type, value, properties=[]): kmi_args = {"type": type, "value": value} return [ # Don't define 'SET' here, take from the tool options. (operator, kmi_args, {"properties": properties}), (operator, {**kmi_args, "shift": True}, {"properties": [*properties, ("mode", 'ADD')]}), (operator, {**kmi_args, "ctrl": True}, {"properties": [*properties, ("mode", 'SUB')]}), ] # ------------------------------------------------------------------------------ # Window, Screen, Areas, Regions def km_window(params): items = [] keymap = ( "Window", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) if params.legacy: # Old shorctus items.extend([ ("wm.save_homefile", {"type": 'U', "value": 'PRESS', "ctrl": True}, None), ("wm.open_mainfile", {"type": 'F1', "value": 'PRESS'}, None), ("wm.link", {"type": 'O', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("wm.append", {"type": 'F1', "value": 'PRESS', "shift": True}, None), ("wm.save_mainfile", {"type": 'W', "value": 'PRESS', "ctrl": True}, None), ("wm.save_as_mainfile", {"type": 'F2', "value": 'PRESS'}, None), ("wm.save_as_mainfile", {"type": 'S', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("copy", True)]}), ("wm.window_new", {"type": 'W', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("wm.window_fullscreen_toggle", {"type": 'F11', "value": 'PRESS', "alt": True}, None), ("wm.doc_view_manual_ui_context", {"type": 'F1', "value": 'PRESS', "alt": True}, None), ("wm.search_menu", {"type": 'SPACE', "value": 'PRESS'}, None), ("wm.redraw_timer", {"type": 'T', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("wm.debug_menu", {"type": 'D', "value": 'PRESS', "ctrl": True, "alt": True}, None), ]) items.extend([ # File operations ("wm.read_homefile", {"type": 'N', "value": 'PRESS', "ctrl": True}, None), op_menu("TOPBAR_MT_file_open_recent", {"type": 'O', "value": 'PRESS', "shift": True, "ctrl": True}), ("wm.open_mainfile", {"type": 'O', "value": 'PRESS', "ctrl": True}, None), ("wm.save_mainfile", {"type": 'S', "value": 'PRESS', "ctrl": True}, None), ("wm.save_as_mainfile", {"type": 'S', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("wm.quit_blender", {"type": 'Q', "value": 'PRESS', "ctrl": True}, None), # Quick menu and toolbar # op_menu("SCREEN_MT_user_menu", {"type": 'Q', "value": 'PRESS'}), #temp remove # NDOF settings op_menu("USERPREF_MT_ndof_settings", {"type": 'NDOF_BUTTON_MENU', "value": 'PRESS'}), ("wm.context_scale_float", {"type": 'NDOF_BUTTON_PLUS', "value": 'PRESS'}, {"properties": [("data_path", 'preferences.inputs.ndof_sensitivity'), ("value", 1.1)]}), ("wm.context_scale_float", {"type": 'NDOF_BUTTON_MINUS', "value": 'PRESS'}, {"properties": [("data_path", 'preferences.inputs.ndof_sensitivity'), ("value", 1.0 / 1.1)]}), ("wm.context_scale_float", {"type": 'NDOF_BUTTON_PLUS', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'preferences.inputs.ndof_sensitivity'), ("value", 1.5)]}), ("wm.context_scale_float", {"type": 'NDOF_BUTTON_MINUS', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'preferences.inputs.ndof_sensitivity'), ("value", 2.0 / 3.0)]}), ("info.reports_display_update", {"type": 'TIMER_REPORT', "value": 'ANY', "any": True}, None), ]) if not params.legacy: # New shortcuts items.extend([ ("wm.doc_view_manual_ui_context", {"type": 'F1', "value": 'PRESS'}, None), op_panel("TOPBAR_PT_name", {"type": 'F2', "value": 'PRESS'}, [("keep_open", False)]), ("wm.search_menu", {"type": 'F3', "value": 'PRESS'}, None), op_menu("TOPBAR_MT_file_context_menu", {"type": 'F4', "value": 'PRESS'}), ]) if params.spacebar_action == 'TOOL': items.append( ("wm.toolbar", {"type": 'SPACE', "value": 'PRESS'}, None), ) elif params.spacebar_action == 'PLAY': items.append( ("wm.toolbar", {"type": 'SPACE', "value": 'PRESS', "shift": True}, None), ) elif params.spacebar_action == 'SEARCH': items.append( ("wm.search_menu", {"type": 'SPACE', "value": 'PRESS'}, None), ) else: assert False return keymap def km_screen(params): items = [] keymap = ( "Screen", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Animation ("screen.animation_step", {"type": 'TIMER0', "value": 'ANY', "any": True}, None), ("screen.region_blend", {"type": 'TIMERREGION', "value": 'ANY', "any": True}, None), # Full screen and cycling ("screen.screen_full_area", {"type": 'SPACE', "value": 'PRESS', "ctrl": True}, None), ("screen.screen_full_area", {"type": 'SPACE', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("use_hide_panels", True)]}), ("screen.space_context_cycle", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, {"properties": [("direction", 'NEXT')]}), ("screen.space_context_cycle", {"type": 'TAB', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("direction", 'PREV')]}), ("screen.workspace_cycle", {"type": 'PAGE_DOWN', "value": 'PRESS', "ctrl": True}, {"properties": [("direction", 'NEXT')]}), ("screen.workspace_cycle", {"type": 'PAGE_UP', "value": 'PRESS', "ctrl": True}, {"properties": [("direction", 'PREV')]}), # Quad view ("screen.region_quadview", {"type": 'Q', "value": 'PRESS', "ctrl": True, "alt": True}, None), # Repeat last ("screen.repeat_last", {"type": 'R', "value": 'PRESS', "shift": True}, None), # Files ("file.execute", {"type": 'RET', "value": 'PRESS'}, None), ("file.execute", {"type": 'NUMPAD_ENTER', "value": 'PRESS'}, None), ("file.cancel", {"type": 'ESC', "value": 'PRESS'}, None), # Undo ("ed.undo", {"type": 'Z', "value": 'PRESS', "ctrl": True}, None), ("ed.redo", {"type": 'Z', "value": 'PRESS', "shift": True, "ctrl": True}, None), # Render ("render.render", {"type": 'F12', "value": 'PRESS'}, {"properties": [("use_viewport", True)]}), ("render.render", {"type": 'F12', "value": 'PRESS', "ctrl": True}, {"properties": [("animation", True), ("use_viewport", True)]}), ("render.view_cancel", {"type": 'ESC', "value": 'PRESS'}, None), ("render.view_show", {"type": 'F11', "value": 'PRESS'}, None), ("render.play_rendered_anim", {"type": 'F11', "value": 'PRESS', "ctrl": True}, None), ]) if not params.legacy: items.extend([ ("screen.redo_last", {"type": 'F9', "value": 'PRESS'}, None), ]) else: # Old keymap items.extend([ ("ed.undo_history", {"type": 'Z', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("screen.screen_set", {"type": 'RIGHT_ARROW', "value": 'PRESS', "ctrl": True}, {"properties": [("delta", 1)]}), ("screen.screen_set", {"type": 'LEFT_ARROW', "value": 'PRESS', "ctrl": True}, {"properties": [("delta", -1)]}), ("screen.screenshot", {"type": 'F3', "value": 'PRESS', "ctrl": True}, None), ("screen.repeat_history", {"type": 'R', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("screen.region_flip", {"type": 'F5', "value": 'PRESS'}, None), ("screen.redo_last", {"type": 'F6', "value": 'PRESS'}, None), ("script.reload", {"type": 'F8', "value": 'PRESS'}, None), ("screen.userpref_show", {"type": 'U', "value": 'PRESS', "ctrl": True, "alt": True}, None), ]) if params.apple: # Apple undo and user prefs items.extend([ ("screen.userpref_show", {"type": 'COMMA', "value": 'PRESS', "oskey": True}, None), ]) return keymap def km_screen_editing(params): items = [] keymap = ("Screen Editing", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}) items.extend([ # Action zones ("screen.actionzone", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("modifier", 0)]}), ("screen.actionzone", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("modifier", 1)]}), ("screen.actionzone", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("modifier", 2)]}), # Screen tools ("screen.area_split", {"type": 'ACTIONZONE_AREA', "value": 'ANY'}, None), ("screen.area_join", {"type": 'ACTIONZONE_AREA', "value": 'ANY'}, None), ("screen.area_dupli", {"type": 'ACTIONZONE_AREA', "value": 'ANY', "shift": True}, None), ("screen.area_swap", {"type": 'ACTIONZONE_AREA', "value": 'ANY', "ctrl": True}, None), ("screen.region_scale", {"type": 'ACTIONZONE_REGION', "value": 'ANY'}, None), ("screen.screen_full_area", {"type": 'ACTIONZONE_FULLSCREEN', "value": 'ANY'}, {"properties": [("use_hide_panels", True)]}), # Area move after action zones ("screen.area_move", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("screen.area_options", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, None), ]) if params.legacy: items.extend([ ("wm.context_toggle", {"type": 'F9', "value": 'PRESS', "alt": True}, {"properties": [("data_path", 'space_data.show_region_header')]}) ]) return keymap def km_screen_region_context_menu(_params): items = [] keymap = ( "Region Context Menu", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("screen.region_context_menu", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, None), ]) return keymap def km_view2d(_params): items = [] keymap = ( "View2D", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Scrollbars ("view2d.scroller_activate", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("view2d.scroller_activate", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), # Pan/scroll ("view2d.pan", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("view2d.pan", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "shift": True}, None), ("view2d.pan", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ("view2d.scroll_right", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "ctrl": True}, None), ("view2d.scroll_left", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "ctrl": True}, None), ("view2d.scroll_down", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "shift": True}, None), ("view2d.scroll_up", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "shift": True}, None), ("view2d.ndof", {"type": 'NDOF_MOTION', "value": 'ANY'}, None), # Zoom with single step ("view2d.zoom_out", {"type": 'WHEELOUTMOUSE', "value": 'PRESS'}, None), ("view2d.zoom_in", {"type": 'WHEELINMOUSE', "value": 'PRESS'}, None), ("view2d.zoom_out", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, None), ("view2d.zoom_in", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, None), ("view2d.zoom", {"type": 'TRACKPADPAN', "value": 'ANY', "ctrl": True}, None), ("view2d.smoothview", {"type": 'TIMER1', "value": 'ANY', "any": True}, None), # Scroll up/down, only when zoom is not available. ("view2d.scroll_down", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS'}, None), ("view2d.scroll_up", {"type": 'WHEELUPMOUSE', "value": 'PRESS'}, None), ("view2d.scroll_right", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS'}, None), ("view2d.scroll_left", {"type": 'WHEELUPMOUSE', "value": 'PRESS'}, None), # Zoom with drag and border ("view2d.zoom", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "ctrl": True}, None), ("view2d.zoom", {"type": 'TRACKPADZOOM', "value": 'ANY'}, None), ("view2d.zoom_border", {"type": 'B', "value": 'PRESS', "shift": True}, None), ]) return keymap def km_view2d_buttons_list(_params): items = [] keymap = ( "View2D Buttons List", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Scrollbars ("view2d.scroller_activate", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("view2d.scroller_activate", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), # Pan scroll ("view2d.pan", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("view2d.pan", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ("view2d.scroll_down", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS'}, None), ("view2d.scroll_up", {"type": 'WHEELUPMOUSE', "value": 'PRESS'}, None), ("view2d.scroll_down", {"type": 'PAGE_DOWN', "value": 'PRESS'}, {"properties": [("page", True)]}), ("view2d.scroll_up", {"type": 'PAGE_UP', "value": 'PRESS'}, {"properties": [("page", True)]}), # Zoom ("view2d.zoom", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "ctrl": True}, None), ("view2d.zoom", {"type": 'TRACKPADZOOM', "value": 'ANY'}, None), ("view2d.zoom", {"type": 'TRACKPADPAN', "value": 'ANY', "ctrl": True}, None), ("view2d.zoom_out", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, None), ("view2d.zoom_in", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, None), ("view2d.reset", {"type": 'HOME', "value": 'PRESS'}, None), ]) return keymap def km_user_interface(_params): items = [] keymap = ( "User Interface", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Eyedroppers all have the same event, and pass it through until # a suitable eyedropper handles it. ("ui.eyedropper_color", {"type": 'E', "value": 'PRESS'}, None), ("ui.eyedropper_colorramp", {"type": 'E', "value": 'PRESS'}, None), ("ui.eyedropper_colorramp_point", {"type": 'E', "value": 'PRESS', "alt": True}, None), ("ui.eyedropper_id", {"type": 'E', "value": 'PRESS'}, None), ("ui.eyedropper_depth", {"type": 'E', "value": 'PRESS'}, None), # Copy data path ("ui.copy_data_path_button", {"type": 'C', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("ui.copy_data_path_button", {"type": 'C', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, {"properties": [("full_path", True)]}), # Keyframes and drivers ("anim.keyframe_insert_button", {"type": 'I', "value": 'PRESS'}, None), ("anim.keyframe_delete_button", {"type": 'I', "value": 'PRESS', "alt": True}, None), ("anim.keyframe_clear_button", {"type": 'I', "value": 'PRESS', "shift": True, "alt": True}, None), ("anim.driver_button_add", {"type": 'D', "value": 'PRESS', "ctrl": True}, None), ("anim.driver_button_remove", {"type": 'D', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("anim.keyingset_button_add", {"type": 'K', "value": 'PRESS'}, None), ("anim.keyingset_button_remove", {"type": 'K', "value": 'PRESS', "alt": True}, None), ]) return keymap # ------------------------------------------------------------------------------ # Editors def km_property_editor(_params): items = [] keymap = ( "Property Editor", {"space_type": 'PROPERTIES', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("buttons.context_menu", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, None), ("screen.space_context_cycle", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("direction", 'PREV'), ], },), ("screen.space_context_cycle", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("direction", 'NEXT'), ], },), ]) return keymap def km_outliner(params): items = [] keymap = ( "Outliner", {"space_type": 'OUTLINER', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("outliner.highlight_update", {"type": 'MOUSEMOVE', "value": 'ANY', "any": True}, None), ("outliner.item_rename", {"type": 'LEFTMOUSE', "value": 'DOUBLE_CLICK'}, None), ("outliner.item_activate", {"type": 'LEFTMOUSE', "value": 'CLICK'}, {"properties": [("extend", False), ("recursive", False), ("deselect_all", not params.legacy)]}), ("outliner.item_activate", {"type": 'LEFTMOUSE', "value": 'CLICK', "shift": True}, {"properties": [("extend", True), ("recursive", False)]}), ("outliner.item_activate", {"type": 'LEFTMOUSE', "value": 'CLICK', "ctrl": True}, {"properties": [("extend", False), ("recursive", True)]}), ("outliner.item_activate", {"type": 'LEFTMOUSE', "value": 'CLICK', "shift": True, "ctrl": True}, {"properties": [("extend", True), ("recursive", True)]}), ("outliner.select_box", {"type": 'B', "value": 'PRESS'}, None), ("outliner.item_openclose", {"type": 'RET', "value": 'PRESS'}, {"properties": [("all", False)]}), ("outliner.item_openclose", {"type": 'RET', "value": 'PRESS', "shift": True}, {"properties": [("all", True)]}), ("outliner.item_rename", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, None), ("outliner.operation", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, None), ("outliner.item_drag_drop", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, None), ("outliner.item_drag_drop", {"type": 'EVT_TWEAK_L', "value": 'ANY', "shift": True}, None), ("outliner.show_hierarchy", {"type": 'HOME', "value": 'PRESS'}, None), ("outliner.show_active", {"type": 'PERIOD', "value": 'PRESS'}, None), ("outliner.show_active", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, None), ("outliner.scroll_page", {"type": 'PAGE_DOWN', "value": 'PRESS'}, {"properties": [("up", False)]}), ("outliner.scroll_page", {"type": 'PAGE_UP', "value": 'PRESS'}, {"properties": [("up", True)]}), ("outliner.show_one_level", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, None), ("outliner.show_one_level", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, {"properties": [("open", False)]}), *_template_items_select_actions(params, "outliner.select_all"), ("outliner.expanded_toggle", {"type": 'A', "value": 'PRESS', "shift": True}, None), ("outliner.keyingset_add_selected", {"type": 'K', "value": 'PRESS'}, None), ("outliner.keyingset_remove_selected", {"type": 'K', "value": 'PRESS', "alt": True}, None), ("anim.keyframe_insert", {"type": 'I', "value": 'PRESS'}, None), ("anim.keyframe_delete", {"type": 'I', "value": 'PRESS', "alt": True}, None), ("outliner.drivers_add_selected", {"type": 'D', "value": 'PRESS', "ctrl": True}, None), ("outliner.drivers_delete_selected", {"type": 'D', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("outliner.collection_new", {"type": 'C', "value": 'PRESS'}, None), ("outliner.collection_delete", {"type": 'X', "value": 'PRESS'}, None), ("outliner.collection_delete", {"type": 'DEL', "value": 'PRESS'}, None), ("object.move_to_collection", {"type": 'M', "value": 'PRESS'}, None), ("object.link_to_collection", {"type": 'M', "value": 'PRESS', "shift": True}, None), ("outliner.collection_exclude_set", {"type": 'E', "value": 'PRESS'}, None), ("outliner.collection_exclude_clear", {"type": 'E', "value": 'PRESS', "alt": True}, None), ("outliner.hide", {"type": 'H', "value": 'PRESS'}, None), ("outliner.unhide_all", {"type": 'H', "value": 'PRESS', "alt": True}, None), # Copy/paste. ("outliner.id_copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("outliner.id_paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_uv_editor(params): items = [] keymap = ( "UV Editor", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Selection modes. *_template_items_uv_select_mode(params), ("uv.mark_seam", {"type": 'E', "value": 'PRESS', "ctrl": True}, None), ("uv.select", {"type": params.select_mouse, "value": params.select_mouse_value}, {"properties": [("extend", False), ("deselect_all", not params.legacy)]}), ("uv.select", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True}, {"properties": [("extend", True)]}), ("uv.select_loop", {"type": params.select_mouse, "value": params.select_mouse_value, "alt": True}, {"properties": [("extend", False)]}), ("uv.select_loop", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True, "alt": True}, {"properties": [("extend", True)]}), ("uv.select_split", {"type": 'Y', "value": 'PRESS'}, None), ("uv.select_box", {"type": 'B', "value": 'PRESS'}, {"properties": [("pinned", False)]}), ("uv.select_box", {"type": 'B', "value": 'PRESS', "ctrl": True}, {"properties": [("pinned", True)]}), ("uv.select_circle", {"type": 'C', "value": 'PRESS'}, None), ("uv.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True}, {"properties": [("mode", 'ADD')]}), ("uv.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True}, {"properties": [("mode", 'SUB')]}), ("uv.select_linked", {"type": 'L', "value": 'PRESS', "ctrl": True}, None), ("uv.select_linked_pick", {"type": 'L', "value": 'PRESS'}, {"properties": [("extend", True), ("deselect", False)]}), ("uv.select_linked_pick", {"type": 'L', "value": 'PRESS', "shift": True}, {"properties": [("extend", False), ("deselect", True)]}), ("uv.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("uv.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), *_template_items_select_actions(params, "uv.select_all"), ("uv.select_pinned", {"type": 'P', "value": 'PRESS', "shift": True}, None), op_menu("IMAGE_MT_uvs_weldalign", {"type": 'W', "value": 'PRESS', "shift": True}), ("uv.stitch", {"type": 'V', "value": 'PRESS'}, None), ("uv.pin", {"type": 'P', "value": 'PRESS'}, {"properties": [("clear", False)]}), ("uv.pin", {"type": 'P', "value": 'PRESS', "alt": True}, {"properties": [("clear", True)]}), ("uv.unwrap", {"type": 'U', "value": 'PRESS'}, None), ("uv.hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("uv.hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("uv.reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), op_menu_pie("IMAGE_MT_uvs_snap_pie", {"type": 'S', "value": 'PRESS', "shift": True}), op_menu("IMAGE_MT_uvs_select_mode", {"type": 'TAB', "value": 'PRESS', "ctrl": True}), *_template_items_proportional_editing(connected=False), ("transform.translate", {"type": 'G', "value": 'PRESS'}, None), ("transform.translate", {"type": params.select_tweak, "value": 'ANY'}, None), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ("transform.shear", {"type": 'S', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("transform.mirror", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ("wm.context_toggle", {"type": 'TAB', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'tool_settings.use_snap')]}), ("wm.context_menu_enum", {"type": 'TAB', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("data_path", 'tool_settings.snap_uv_element')]}), op_menu("IMAGE_MT_uvs_context_menu", params.context_menu_event), ]) # Fallback for MMB emulation if params.use_mouse_emulate_3_button and params.select_mouse == 'LEFTMOUSE': items.extend([ ("uv.select_loop", {"type": params.select_mouse, "value": 'DOUBLE_CLICK'}, {"properties": [("extend", False)]}), ("uv.select_loop", {"type": params.select_mouse, "value": 'DOUBLE_CLICK', "alt": True}, {"properties": [("extend", True)]}), ]) # 3D cursor if params.cursor_tweak_event: items.extend([ ("uv.cursor_set", params.cursor_set_event, None), ("transform.translate", params.cursor_tweak_event, {"properties": [("release_confirm", True), ("cursor_transform", True)]}), ]) else: items.extend([ ("uv.cursor_set", params.cursor_set_event, None), ]) if params.legacy: items.extend([ ("uv.minimize_stretch", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ("uv.pack_islands", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), ("uv.average_islands_scale", {"type": 'A', "value": 'PRESS', "ctrl": True}, None), ]) if params.select_mouse == 'LEFTMOUSE' and not params.legacy: # Quick switch to select tool, since left select can't easily # select with any tool active. items.extend([ op_tool_cycle("builtin.select_box", {"type": 'W', "value": 'PRESS'}), ]) return keymap # 3D View: all regions. def km_view3d_generic(_params): items = [] keymap = ( "3D View Generic", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_space_region_type_toggle( toolbar_key={"type": 'T', "value": 'PRESS'}, sidebar_key={"type": 'N', "value": 'PRESS'}, ) ]) return keymap # 3D View: main region. def km_view3d(params): items = [] keymap = ( "3D View", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": items}, ) # 3D cursor if params.cursor_tweak_event: items.extend([ ("view3d.cursor3d", params.cursor_set_event, None), ("transform.translate", params.cursor_tweak_event, {"properties": [("release_confirm", True), ("cursor_transform", True)]}), ]) else: items.extend([ ("view3d.cursor3d", params.cursor_set_event, None), ]) items.extend([ # Visibility. ("view3d.localview", {"type": 'NUMPAD_SLASH', "value": 'PRESS'}, None), ("view3d.localview", {"type": 'SLASH', "value": 'PRESS'}, None), ("view3d.localview_remove_from", {"type": 'M', "value": 'PRESS'}, None), # Navigation. ("view3d.rotate", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("view3d.move", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "shift": True}, None), ("view3d.zoom", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "ctrl": True}, None), ("view3d.dolly", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("view3d.view_selected", {"type": 'NUMPAD_PERIOD', "value": 'PRESS', "ctrl": True}, {"properties": [("use_all_regions", True)]}), ("view3d.view_selected", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, {"properties": [("use_all_regions", False)]}), ("view3d.smoothview", {"type": 'TIMER1', "value": 'ANY', "any": True}, None), ("view3d.rotate", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ("view3d.rotate", {"type": 'MOUSEROTATE', "value": 'ANY'}, None), ("view3d.move", {"type": 'TRACKPADPAN', "value": 'ANY', "shift": True}, None), ("view3d.zoom", {"type": 'TRACKPADZOOM', "value": 'ANY'}, None), ("view3d.zoom", {"type": 'TRACKPADPAN', "value": 'ANY', "ctrl": True}, None), ("view3d.zoom", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, {"properties": [("delta", 1)]}), ("view3d.zoom", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, {"properties": [("delta", -1)]}), ("view3d.zoom", {"type": 'EQUAL', "value": 'PRESS', "ctrl": True}, {"properties": [("delta", 1)]}), ("view3d.zoom", {"type": 'MINUS', "value": 'PRESS', "ctrl": True}, {"properties": [("delta", -1)]}), ("view3d.zoom", {"type": 'WHEELINMOUSE', "value": 'PRESS'}, {"properties": [("delta", 1)]}), ("view3d.zoom", {"type": 'WHEELOUTMOUSE', "value": 'PRESS'}, {"properties": [("delta", -1)]}), ("view3d.dolly", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "shift": True}, {"properties": [("delta", 1)]}), ("view3d.dolly", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "shift": True}, {"properties": [("delta", -1)]}), ("view3d.dolly", {"type": 'EQUAL', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("delta", 1)]}), ("view3d.dolly", {"type": 'MINUS', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("delta", -1)]}), ("view3d.view_center_camera", {"type": 'HOME', "value": 'PRESS'}, None), ("view3d.view_center_lock", {"type": 'HOME', "value": 'PRESS'}, None), ("view3d.view_all", {"type": 'HOME', "value": 'PRESS'}, {"properties": [("center", False)]}), ("view3d.view_all", {"type": 'HOME', "value": 'PRESS', "ctrl": True}, {"properties": [("use_all_regions", True), ("center", False)]}), ("view3d.view_all", {"type": 'C', "value": 'PRESS', "shift": True}, {"properties": [("center", True)]}), op_menu_pie( "VIEW3D_MT_view_pie" if params.v3d_tilde_action == 'VIEW' else "VIEW3D_MT_transform_gizmo_pie", {"type": 'ACCENT_GRAVE', "value": params.pie_value}, ), *(() if not params.use_pie_click_drag else (("view3d.navigate", {"type": 'ACCENT_GRAVE', "value": 'CLICK'}, None),)), ("view3d.navigate", {"type": 'ACCENT_GRAVE', "value": 'PRESS', "shift": True}, None), # Numpad views. ("view3d.view_camera", {"type": 'NUMPAD_0', "value": 'PRESS'}, None), ("view3d.view_axis", {"type": 'NUMPAD_1', "value": 'PRESS'}, {"properties": [("type", 'FRONT')]}), ("view3d.view_orbit", {"type": 'NUMPAD_2', "value": 'PRESS'}, {"properties": [("type", 'ORBITDOWN')]}), ("view3d.view_axis", {"type": 'NUMPAD_3', "value": 'PRESS'}, {"properties": [("type", 'RIGHT')]}), ("view3d.view_orbit", {"type": 'NUMPAD_4', "value": 'PRESS'}, {"properties": [("type", 'ORBITLEFT')]}), ("view3d.view_persportho", {"type": 'NUMPAD_5', "value": 'PRESS'}, None), ("view3d.view_orbit", {"type": 'NUMPAD_6', "value": 'PRESS'}, {"properties": [("type", 'ORBITRIGHT')]}), ("view3d.view_axis", {"type": 'NUMPAD_7', "value": 'PRESS'}, {"properties": [("type", 'TOP')]}), ("view3d.view_orbit", {"type": 'NUMPAD_8', "value": 'PRESS'}, {"properties": [("type", 'ORBITUP')]}), ("view3d.view_axis", {"type": 'NUMPAD_1', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'BACK')]}), ("view3d.view_axis", {"type": 'NUMPAD_3', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'LEFT')]}), ("view3d.view_axis", {"type": 'NUMPAD_7', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'BOTTOM')]}), ("view3d.view_pan", {"type": 'NUMPAD_2', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PANDOWN')]}), ("view3d.view_pan", {"type": 'NUMPAD_4', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PANLEFT')]}), ("view3d.view_pan", {"type": 'NUMPAD_6', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PANRIGHT')]}), ("view3d.view_pan", {"type": 'NUMPAD_8', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PANUP')]}), ("view3d.view_roll", {"type": 'NUMPAD_4', "value": 'PRESS', "shift": True}, {"properties": [("type", 'LEFT')]}), ("view3d.view_roll", {"type": 'NUMPAD_6', "value": 'PRESS', "shift": True}, {"properties": [("type", 'RIGHT')]}), ("view3d.view_orbit", {"type": 'NUMPAD_9', "value": 'PRESS'}, {"properties": [("angle", 3.1415927), ("type", 'ORBITRIGHT')]}), ("view3d.view_axis", {"type": 'NUMPAD_1', "value": 'PRESS', "shift": True}, {"properties": [("type", 'FRONT'), ("align_active", True)]}), ("view3d.view_axis", {"type": 'NUMPAD_3', "value": 'PRESS', "shift": True}, {"properties": [("type", 'RIGHT'), ("align_active", True)]}), ("view3d.view_axis", {"type": 'NUMPAD_7', "value": 'PRESS', "shift": True}, {"properties": [("type", 'TOP'), ("align_active", True)]}), ("view3d.view_axis", {"type": 'NUMPAD_1', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'BACK'), ("align_active", True)]}), ("view3d.view_axis", {"type": 'NUMPAD_3', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'LEFT'), ("align_active", True)]}), ("view3d.view_axis", {"type": 'NUMPAD_7', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'BOTTOM'), ("align_active", True)]}), ("view3d.view_axis", {"type": 'EVT_TWEAK_M', "value": 'NORTH', "alt": True}, {"properties": [("type", 'TOP'), ("relative", True)]}), ("view3d.view_axis", {"type": 'EVT_TWEAK_M', "value": 'SOUTH', "alt": True}, {"properties": [("type", 'BOTTOM'), ("relative", True)]}), ("view3d.view_axis", {"type": 'EVT_TWEAK_M', "value": 'EAST', "alt": True}, {"properties": [("type", 'RIGHT'), ("relative", True)]}), ("view3d.view_axis", {"type": 'EVT_TWEAK_M', "value": 'WEST', "alt": True}, {"properties": [("type", 'LEFT'), ("relative", True)]}), ("view3d.view_center_pick", {"type": 'MIDDLEMOUSE', "value": 'CLICK', "alt": True}, None), ("view3d.ndof_orbit_zoom", {"type": 'NDOF_MOTION', "value": 'ANY'}, None), ("view3d.ndof_orbit", {"type": 'NDOF_MOTION', "value": 'ANY', "ctrl": True}, None), ("view3d.ndof_pan", {"type": 'NDOF_MOTION', "value": 'ANY', "shift": True}, None), ("view3d.ndof_all", {"type": 'NDOF_MOTION', "value": 'ANY', "shift": True, "ctrl": True}, None), ("view3d.view_selected", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, {"properties": [("use_all_regions", False)]}), ("view3d.view_roll", {"type": 'NDOF_BUTTON_ROLL_CCW', "value": 'PRESS'}, {"properties": [("type", 'LEFT')]}), ("view3d.view_roll", {"type": 'NDOF_BUTTON_ROLL_CCW', "value": 'PRESS'}, {"properties": [("type", 'RIGHT')]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_FRONT', "value": 'PRESS'}, {"properties": [("type", 'FRONT')]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_BACK', "value": 'PRESS'}, {"properties": [("type", 'BACK')]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_LEFT', "value": 'PRESS'}, {"properties": [("type", 'LEFT')]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_RIGHT', "value": 'PRESS'}, {"properties": [("type", 'RIGHT')]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_TOP', "value": 'PRESS'}, {"properties": [("type", 'TOP')]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_BOTTOM', "value": 'PRESS'}, {"properties": [("type", 'BOTTOM')]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_FRONT', "value": 'PRESS', "shift": True}, {"properties": [("type", 'FRONT'), ("align_active", True)]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_RIGHT', "value": 'PRESS', "shift": True}, {"properties": [("type", 'RIGHT'), ("align_active", True)]}), ("view3d.view_axis", {"type": 'NDOF_BUTTON_TOP', "value": 'PRESS', "shift": True}, {"properties": [("type", 'TOP'), ("align_active", True)]}), # Selection. *((operator, {"type": params.select_mouse, "value": params.select_mouse_value, **{m: True for m in mods}}, {"properties": [(c, True) for c in props]}, ) for operator, props, mods in ( ("view3d.select", ("deselect_all",) if not params.legacy else (), ()), ("view3d.select", ("toggle",), ("shift",)), ("view3d.select", ("center", "object"), ("ctrl",)), ("view3d.select", ("enumerate",), ("alt",)), ("view3d.select", ("extend", "toggle", "center"), ("shift", "ctrl")), ("view3d.select", ("center", "enumerate"), ("ctrl", "alt")), ("view3d.select", ("toggle", "enumerate"), ("shift", "alt")), ("view3d.select", ("toggle", "center", "enumerate"), ("shift", "ctrl", "alt")), )), ("view3d.select_box", {"type": 'B', "value": 'PRESS'}, None), ("view3d.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True}, {"properties": [("mode", 'ADD')]}), ("view3d.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True}, {"properties": [("mode", 'SUB')]}), ("view3d.select_circle", {"type": 'C', "value": 'PRESS'}, None), # Borders. ("view3d.clip_border", {"type": 'B', "value": 'PRESS', "alt": True}, None), ("view3d.zoom_border", {"type": 'B', "value": 'PRESS', "shift": True}, None), ("view3d.render_border", {"type": 'B', "value": 'PRESS', "ctrl": True}, None), ("view3d.clear_render_border", {"type": 'B', "value": 'PRESS', "ctrl": True, "alt": True}, None), # Cameras. ("view3d.camera_to_view", {"type": 'NUMPAD_0', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("view3d.object_as_camera", {"type": 'NUMPAD_0', "value": 'PRESS', "ctrl": True}, None), # Copy/paste. ("view3d.copybuffer", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("view3d.pastebuffer", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), # Transform. ("transform.translate", {"type": 'G', "value": 'PRESS'}, None), ("transform.translate", {"type": params.select_tweak, "value": 'ANY'}, None), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ("transform.bend", {"type": 'W', "value": 'PRESS', "shift": True}, None), ("transform.tosphere", {"type": 'S', "value": 'PRESS', "shift": True, "alt": True}, None), ("transform.shear", {"type": 'S', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("transform.mirror", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ("wm.context_toggle", {"type": 'TAB', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'tool_settings.use_snap')]}), op_panel("VIEW3D_PT_snapping", {"type": 'TAB', "value": 'PRESS', "shift": True, "ctrl": True}, [("keep_open", False)]), ("object.transform_axis_target", {"type": 'T', "value": 'PRESS', "shift": True}, None), ("transform.skin_resize", {"type": 'A', "value": 'PRESS', "ctrl": True}, None), ]) if not params.legacy: # New pie menus. items.extend([ op_menu_pie("VIEW3D_MT_snap_pie", {"type": 'S', "value": 'PRESS', "shift": True}), ("wm.context_toggle", {"type": 'ACCENT_GRAVE', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.show_gizmo_context')]}), op_menu_pie("VIEW3D_MT_pivot_pie", {"type": 'PERIOD', "value": 'PRESS'}), op_menu_pie("VIEW3D_MT_orientations_pie", {"type": 'COMMA', "value": 'PRESS'}), op_menu_pie( "VIEW3D_MT_shading_pie" if not params.use_v3d_shade_ex_pie else "VIEW3D_MT_shading_ex_pie", {"type": 'Z', "value": params.pie_value}), *(() if not params.use_pie_click_drag else (("view3d.toggle_shading", {"type": 'Z', "value": 'CLICK'}, {"properties": [("type", 'WIREFRAME')]}),)), ("view3d.toggle_shading", {"type": 'Z', "value": 'PRESS', "shift": True}, {"properties": [("type", 'WIREFRAME')]}), ("view3d.toggle_xray", {"type": 'Z', "value": 'PRESS', "alt": True}, None), ("wm.context_toggle", {"type": 'Z', "value": 'PRESS', "alt": True, "shift": True}, {"properties": [("data_path", "space_data.overlay.show_overlays")]}), ]) else: items.extend([ # Old navigation. op_menu("VIEW3D_MT_snap", {"type": 'S', "value": 'PRESS', "shift": True}), ("view3d.view_lock_to_active", {"type": 'NUMPAD_PERIOD', "value": 'PRESS', "shift": True}, None), ("view3d.view_lock_clear", {"type": 'NUMPAD_PERIOD', "value": 'PRESS', "alt": True}, None), ("view3d.navigate", {"type": 'F', "value": 'PRESS', "shift": True}, None), ("view3d.zoom_camera_1_to_1", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "shift": True}, None), ("view3d.view_center_cursor", {"type": 'HOME', "value": 'PRESS', "alt": True}, None), ("view3d.view_center_pick", {"type": 'F', "value": 'PRESS', "alt": True}, None), ("view3d.view_pan", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PANRIGHT')]}), ("view3d.view_pan", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PANLEFT')]}), ("view3d.view_pan", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PANUP')]}), ("view3d.view_pan", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PANDOWN')]}), ("view3d.view_orbit", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("type", 'ORBITLEFT')]}), ("view3d.view_orbit", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("type", 'ORBITRIGHT')]}), ("view3d.view_orbit", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("type", 'ORBITUP')]}), ("view3d.view_orbit", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("type", 'ORBITDOWN')]}), ("view3d.view_roll", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'LEFT')]}), ("view3d.view_roll", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'RIGHT')]}), ("transform.create_orientation", {"type": 'SPACE', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("use", True)]}), ("transform.translate", {"type": 'T', "value": 'PRESS', "shift": True}, {"properties": [("texture_space", True)]}), ("transform.resize", {"type": 'T', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("texture_space", True)]}), # Old pivot. ("wm.context_set_enum", {"type": 'COMMA', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.transform_pivot_point'), ("value", 'BOUNDING_BOX_CENTER')]}), ("wm.context_set_enum", {"type": 'COMMA', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'tool_settings.transform_pivot_point'), ("value", 'MEDIAN_POINT')]}), ("wm.context_toggle", {"type": 'COMMA', "value": 'PRESS', "alt": True}, {"properties": [("data_path", 'tool_settings.use_transform_pivot_point_align')]}), ("wm.context_toggle", {"type": 'SPACE', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.show_gizmo_context')]}), ("wm.context_set_enum", {"type": 'PERIOD', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.transform_pivot_point'), ("value", 'CURSOR')]}), ("wm.context_set_enum", {"type": 'PERIOD', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'tool_settings.transform_pivot_point'), ("value", 'INDIVIDUAL_ORIGINS')]}), ("wm.context_set_enum", {"type": 'PERIOD', "value": 'PRESS', "alt": True}, {"properties": [("data_path", 'tool_settings.transform_pivot_point'), ("value", 'ACTIVE_ELEMENT')]}), # Old shading. ("wm.context_toggle_enum", {"type": 'Z', "value": 'PRESS'}, {"properties": [("data_path", 'space_data.shading.type'), ("value_1", 'WIREFRAME'), ("value_2", 'SOLID')]}), ("wm.context_toggle_enum", {"type": 'Z', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'space_data.shading.type'), ("value_1", 'RENDERED'), ("value_2", 'SOLID')]}), ("wm.context_toggle_enum", {"type": 'Z', "value": 'PRESS', "alt": True}, {"properties": [("data_path", 'space_data.shading.type'), ("value_1", 'MATERIAL'), ("value_2", 'SOLID')]}), ]) if params.select_mouse == 'LEFTMOUSE' and not params.legacy: # Quick switch to select tool, since left select can't easily # select with any tool active. items.extend([ op_tool_cycle("builtin.select_box", {"type": 'W', "value": 'PRESS'}), ]) return keymap def km_mask_editing(params): items = [] keymap = ( "Mask Editing", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("mask.new", {"type": 'N', "value": 'PRESS', "alt": True}, None), op_menu("MASK_MT_add", {"type": 'A', "value": 'PRESS', "shift": True}), op_menu_pie("VIEW3D_MT_proportional_editing_falloff_pie", {"type": 'O', "value": 'PRESS', "shift": True}), ("wm.context_toggle", {"type": 'O', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.use_proportional_edit_mask')]}), ("mask.add_vertex_slide", {"type": params.action_mouse, "value": 'PRESS', "ctrl": True}, None), ("mask.add_feather_vertex_slide", {"type": params.action_mouse, "value": 'PRESS', "shift": True, "ctrl": True}, None), ("mask.delete", {"type": 'X', "value": 'PRESS'}, None), ("mask.delete", {"type": 'DEL', "value": 'PRESS'}, None), ("mask.select", {"type": params.select_mouse, "value": params.select_mouse_value}, {"properties": [("extend", False), ("deselect", False), ("toggle", False), ("deselect_all", not params.legacy)]}), ("mask.select", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True}, {"properties": [("extend", False), ("deselect", False), ("toggle", True)]}), *_template_items_select_actions(params, "mask.select_all"), ("mask.select_linked", {"type": 'L', "value": 'PRESS', "ctrl": True}, None), ("mask.select_linked_pick", {"type": 'L', "value": 'PRESS'}, {"properties": [("deselect", False)]}), ("mask.select_linked_pick", {"type": 'L', "value": 'PRESS', "shift": True}, {"properties": [("deselect", True)]}), ("mask.select_box", {"type": 'B', "value": 'PRESS'}, None), ("mask.select_circle", {"type": 'C', "value": 'PRESS'}, None), ("mask.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, {"properties": [("mode", 'ADD')]}), ("mask.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True, "alt": True}, {"properties": [("mode", 'SUB')]}), ("mask.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("mask.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("mask.hide_view_clear", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("mask.hide_view_set", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("mask.hide_view_set", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("clip.select", {"type": params.select_mouse, "value": params.select_mouse_value, "ctrl": True}, {"properties": [("extend", False)]}), ("mask.cyclic_toggle", {"type": 'C', "value": 'PRESS', "alt": True}, None), ("mask.slide_point", {"type": params.action_mouse, "value": 'PRESS'}, None), ("mask.slide_spline_curvature", {"type": params.action_mouse, "value": 'PRESS'}, None), ("mask.handle_type_set", {"type": 'V', "value": 'PRESS'}, None), ("mask.normals_make_consistent", {"type": 'N', "value": 'PRESS', "ctrl" if params.legacy else "shift": True}, None), ("mask.parent_set", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), ("mask.parent_clear", {"type": 'P', "value": 'PRESS', "alt": True}, None), ("mask.shape_key_insert", {"type": 'I', "value": 'PRESS'}, None), ("mask.shape_key_clear", {"type": 'I', "value": 'PRESS', "alt": True}, None), ("mask.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), ("mask.copy_splines", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("mask.paste_splines", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ("transform.translate", {"type": 'G', "value": 'PRESS'}, None), ("transform.translate", {"type": params.select_tweak, "value": 'ANY'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ("transform.transform", {"type": 'S', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'MASK_SHRINKFATTEN')]}), ]) # 3D cursor if params.cursor_tweak_event: items.extend([ ("uv.cursor_set", params.cursor_set_event, None), ("transform.translate", params.cursor_tweak_event, {"properties": [("release_confirm", True), ("cursor_transform", True)]}), ]) else: items.extend([ ("uv.cursor_set", params.cursor_set_event, None), ]) return keymap def km_markers(params): items = [] keymap = ( "Markers", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("marker.add", {"type": 'M', "value": 'PRESS'}, None), ("marker.move", {"type": params.select_tweak, "value": 'ANY'}, None), ("marker.duplicate", {"type": 'D', "value": 'PRESS', "shift": True}, None), ("marker.select", {"type": params.select_mouse, "value": 'PRESS'}, None), ("marker.select", {"type": params.select_mouse, "value": 'PRESS', "shift": True}, {"properties": [("extend", True)]}), ("marker.select", {"type": params.select_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("extend", False), ("camera", True)]}), ("marker.select", {"type": params.select_mouse, "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("extend", True), ("camera", True)]}), ("marker.select_box", {"type": 'B', "value": 'PRESS'}, None), *_template_items_select_actions(params, "marker.select_all"), ("marker.delete", {"type": 'X', "value": 'PRESS'}, None), ("marker.delete", {"type": 'DEL', "value": 'PRESS'}, None), ("marker.rename", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ("marker.move", {"type": 'G', "value": 'PRESS'}, None), ("marker.camera_bind", {"type": 'B', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_scrubbing(params): items = [] keymap = ( "Scrubbing", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("anim.change_frame", {"type": "LEFTMOUSE", "value": 'PRESS'}, None), ("graph.cursor_set", {"type": "LEFTMOUSE", "value": 'PRESS'}, None), ]) return keymap def km_scrubbing_clip(params): items = [] keymap = ( "Clip Scrubbing", {"space_type": 'CLIP_EDITOR', "region_type": 'PREVIEW'}, {"items": items}, ) items.extend([ ("clip.change_frame", {"type": "LEFTMOUSE", "value": 'PRESS'}, None), ]) return keymap def km_graph_editor_generic(_params): items = [] keymap = ( "Graph Editor Generic", {"space_type": 'GRAPH_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_space_region_type_toggle( sidebar_key={"type": 'N', "value": 'PRESS'}, ), ("graph.extrapolation_type", {"type": 'E', "value": 'PRESS', "shift": True}, None), ("anim.channels_find", {"type": 'F', "value": 'PRESS', "ctrl": True}, None), ("graph.hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("graph.hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("graph.reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("wm.context_set_enum", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'area.type'), ("value", 'DOPESHEET_EDITOR')]}), ]) return keymap def km_graph_editor(params): items = [] keymap = ( "Graph Editor", {"space_type": 'GRAPH_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("wm.context_toggle", {"type": 'H', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.show_handles')]}), ("graph.clickselect", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("extend", False), ("deselect_all", not params.legacy), ("column", False), ("curves", False)]}), ("graph.clickselect", {"type": params.select_mouse, "value": 'PRESS', "alt": True}, {"properties": [("extend", False), ("column", True), ("curves", False)]}), ("graph.clickselect", {"type": params.select_mouse, "value": 'CLICK', "shift": True}, {"properties": [("extend", True), ("column", False), ("curves", False)]}), ("graph.clickselect", {"type": params.select_mouse, "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("extend", True), ("column", True), ("curves", False)]}), ("graph.clickselect", {"type": params.select_mouse, "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("extend", False), ("column", False), ("curves", True)]}), ("graph.clickselect", {"type": params.select_mouse, "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, {"properties": [("extend", True), ("column", False), ("curves", True)]}), ("graph.select_leftright", {"type": params.select_mouse, "value": 'CLICK', "ctrl": True}, {"properties": [("mode", 'CHECK'), ("extend", False)]}), ("graph.select_leftright", {"type": params.select_mouse, "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("mode", 'CHECK'), ("extend", True)]}), ("graph.select_leftright", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("mode", 'LEFT'), ("extend", False)]}), ("graph.select_leftright", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("mode", 'RIGHT'), ("extend", False)]}), *_template_items_select_actions(params, "graph.select_all"), ("graph.select_box", {"type": 'B', "value": 'PRESS'}, {"properties": [("axis_range", False), ("include_handles", False)]}), ("graph.select_box", {"type": 'B', "value": 'PRESS', "alt": True}, {"properties": [("axis_range", True), ("include_handles", False)]}), ("graph.select_box", {"type": 'B', "value": 'PRESS', "ctrl": True}, {"properties": [("axis_range", False), ("include_handles", True)]}), ("graph.select_box", {"type": 'B', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("axis_range", True), ("include_handles", True)]}), ("graph.select_box", {"type": params.select_tweak, "value": 'ANY'}, {"properties":[("axis_range", False), ("include_handles", False), ("wait_for_input", False), ("mode", 'SET')]}), ("graph.select_box", {"type": params.select_tweak, "value": 'ANY', "shift": True}, {"properties":[("axis_range", False), ("include_handles", False), ("wait_for_input", False), ("mode", 'ADD')]}), ("graph.select_box", {"type": params.select_tweak, "value": 'ANY', "ctrl": True}, {"properties":[("axis_range", False),("include_handles", False), ("wait_for_input", False), ("mode", 'SUB')]}), ("graph.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True}, {"properties": [("mode", 'ADD')]}), ("graph.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True}, {"properties": [("mode", 'SUB')]}), ("graph.select_circle", {"type": 'C', "value": 'PRESS'}, None), ("graph.select_column", {"type": 'K', "value": 'PRESS'}, {"properties": [("mode", 'KEYS')]}), ("graph.select_column", {"type": 'K', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'CFRA')]}), ("graph.select_column", {"type": 'K', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'MARKERS_COLUMN')]}), ("graph.select_column", {"type": 'K', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'MARKERS_BETWEEN')]}), ("graph.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("graph.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("graph.select_linked", {"type": 'L', "value": 'PRESS'}, None), ("graph.frame_jump", {"type": 'G', "value": 'PRESS', "ctrl": True}, None), op_menu_pie("GRAPH_MT_snap_pie", {"type": 'S', "value": 'PRESS', "shift": True}), ("graph.mirror", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ("graph.handle_type", {"type": 'V', "value": 'PRESS'}, None), ("graph.interpolation_type", {"type": 'T', "value": 'PRESS'}, None), ("graph.easing_type", {"type": 'E', "value": 'PRESS', "ctrl": True}, None), ("graph.smooth", {"type": 'O', "value": 'PRESS', "alt": True}, None), ("graph.sample", {"type": 'O', "value": 'PRESS', "shift": True, "alt": True}, None), ("graph.bake", {"type": 'C', "value": 'PRESS', "alt": True}, None), op_menu("GRAPH_MT_delete", {"type": 'X', "value": 'PRESS'}), op_menu("GRAPH_MT_delete", {"type": 'DEL', "value": 'PRESS'}), op_menu("GRAPH_MT_context_menu", params.context_menu_event), ("graph.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), ("graph.keyframe_insert", {"type": 'I', "value": 'PRESS'}, None), ("graph.click_insert", {"type": params.action_mouse, "value": 'CLICK', "ctrl": True}, {"properties": [("extend", False)]}), ("graph.click_insert", {"type": params.action_mouse, "value": 'CLICK', "shift": True, "ctrl": True}, {"properties": [("extend", True)]}), ("graph.copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("graph.paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ("graph.paste", {"type": 'V', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("flipped", True)]}), ("graph.previewrange_set", {"type": 'P', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("graph.view_all", {"type": 'HOME', "value": 'PRESS'}, None), ("graph.view_all", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, None), ("graph.view_selected", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, None), ("graph.view_frame", {"type": 'NUMPAD_0', "value": 'PRESS'}, None), ("graph.fmodifier_add", {"type": 'M', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("only_active", False)]}), ("anim.channels_editable_toggle", {"type": 'TAB', "value": 'PRESS'}, None), ("transform.translate", {"type": 'G', "value": 'PRESS'}, None), ("transform.translate", {"type": params.select_mouse, "value": 'PRESS'}, None), ("transform.transform", {"type": 'E', "value": 'PRESS'}, {"properties": [("mode", 'TIME_EXTEND')]}), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ("wm.context_toggle", {"type": 'O', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.use_proportional_fcurve')]}), op_menu_pie("VIEW3D_MT_proportional_editing_falloff_pie", {"type": 'O', "value": 'PRESS', "shift": True}), op_menu_pie("GRAPH_MT_pivot_pie", {"type": 'PERIOD', "value": 'PRESS'}), ("marker.add", {"type": 'M', "value": 'PRESS'}, None), ("marker.rename", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ("anim.start_frame_set", {"type": 'HOME', "value": 'PRESS', "ctrl": True}, None), ("anim.end_frame_set", {"type": 'END', "value": 'PRESS', "ctrl": True}, None), ]) if params.select_mouse == 'LEFTMOUSE' and not params.legacy: items.extend([ ("graph.cursor_set", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True}, None), ]) else: items.extend([ ("graph.cursor_set", {"type": params.action_mouse, "value": 'PRESS'}, None), ]) return keymap def km_image_generic(_params): items = [] keymap = ( "Image Generic", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_space_region_type_toggle( toolbar_key={"type": 'T', "value": 'PRESS'}, sidebar_key={"type": 'N', "value": 'PRESS'}, ), ("image.new", {"type": 'N', "value": 'PRESS', "alt": True}, None), ("image.open", {"type": 'O', "value": 'PRESS', "alt": True}, None), ("image.reload", {"type": 'R', "value": 'PRESS', "alt": True}, None), ("image.read_viewlayers", {"type": 'R', "value": 'PRESS', "ctrl": True}, None), ("image.save", {"type": 'S', "value": 'PRESS', "alt": True}, None), ("image.save_as", {"type": 'S', "value": 'PRESS', "shift": True}, None), ("image.cycle_render_slot", {"type": 'J', "value": 'PRESS'}, None), ("image.cycle_render_slot", {"type": 'J', "value": 'PRESS', "alt": True}, {"properties": [("reverse", True)]}), ]) return keymap def km_image(params): items = [] keymap = ( "Image", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("image.view_all", {"type": 'HOME', "value": 'PRESS'}, None), ("image.view_all", {"type": 'HOME', "value": 'PRESS', "shift": True}, {"properties": [("fit_view", True)]}), ("image.view_selected", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, None), ("image.view_pan", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("image.view_pan", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "shift": True}, None), ("image.view_pan", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ("image.view_all", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, None), ("image.view_ndof", {"type": 'NDOF_MOTION', "value": 'ANY'}, None), ("image.view_zoom_in", {"type": 'WHEELINMOUSE', "value": 'PRESS'}, None), ("image.view_zoom_out", {"type": 'WHEELOUTMOUSE', "value": 'PRESS'}, None), ("image.view_zoom_in", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, None), ("image.view_zoom_out", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, None), ("image.view_zoom", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "ctrl": True}, None), ("image.view_zoom", {"type": 'TRACKPADZOOM', "value": 'ANY'}, None), ("image.view_zoom", {"type": 'TRACKPADPAN', "value": 'ANY', "ctrl": True}, None), ("image.view_zoom_border", {"type": 'B', "value": 'PRESS', "shift": True}, None), ("image.view_zoom_ratio", {"type": 'NUMPAD_8', "value": 'PRESS', "ctrl": True}, {"properties": [("ratio", 8.0)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_4', "value": 'PRESS', "ctrl": True}, {"properties": [("ratio", 4.0)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_2', "value": 'PRESS', "ctrl": True}, {"properties": [("ratio", 2.0)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_8', "value": 'PRESS', "shift": True}, {"properties": [("ratio", 8.0)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_4', "value": 'PRESS', "shift": True}, {"properties": [("ratio", 4.0)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_2', "value": 'PRESS', "shift": True}, {"properties": [("ratio", 2.0)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_1', "value": 'PRESS'}, {"properties": [("ratio", 1.0)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_2', "value": 'PRESS'}, {"properties": [("ratio", 0.5)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_4', "value": 'PRESS'}, {"properties": [("ratio", 0.25)]}), ("image.view_zoom_ratio", {"type": 'NUMPAD_8', "value": 'PRESS'}, {"properties": [("ratio", 0.125)]}), ("image.change_frame", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("image.sample", {"type": params.action_mouse, "value": 'PRESS'}, None), ("image.curves_point_set", {"type": params.action_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("point", 'BLACK_POINT')]}), ("image.curves_point_set", {"type": params.action_mouse, "value": 'PRESS', "shift": True}, {"properties": [("point", 'WHITE_POINT')]}), ("object.mode_set", {"type": 'TAB', "value": 'PRESS'}, {"properties": [("mode", 'EDIT'), ("toggle", True)]}), *( (("wm.context_set_int", {"type": NUMBERS_1[i], "value": 'PRESS'}, {"properties": [("data_path", 'space_data.image.render_slots.active_index'), ("value", i)]}) for i in range(9) ) ), op_menu_pie("IMAGE_MT_pivot_pie", {"type": 'PERIOD', "value": 'PRESS'}), ("image.render_border", {"type": 'B', "value": 'PRESS', "ctrl": True}, None), ("image.clear_render_border", {"type": 'B', "value": 'PRESS', "ctrl": True, "alt": True}, None), ]) return keymap def km_node_generic(_params): items = [] keymap = ( "Node Generic", {"space_type": 'NODE_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_space_region_type_toggle( toolbar_key={"type": 'T', "value": 'PRESS'}, sidebar_key={"type": 'N', "value": 'PRESS'}, ), ]) return keymap def km_node_editor(params): items = [] keymap = ( "Node Editor", {"space_type": 'NODE_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) def node_select_ops(select_mouse): return [ ("node.select", {"type": select_mouse, "value": 'PRESS'}, {"properties": [("extend", False)]}), ("node.select", {"type": select_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("extend", False)]}), ("node.select", {"type": select_mouse, "value": 'PRESS', "alt": True}, {"properties": [("extend", False)]}), ("node.select", {"type": select_mouse, "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("extend", False)]}), ("node.select", {"type": select_mouse, "value": 'PRESS', "shift": True}, {"properties": [("extend", True)]}), ("node.select", {"type": select_mouse, "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("extend", True)]}), ("node.select", {"type": select_mouse, "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("extend", True)]}), ("node.select", {"type": select_mouse, "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, {"properties": [("extend", True)]}), ] # Allow node selection with both for RMB select if params.select_mouse == 'RIGHTMOUSE': items.extend(node_select_ops('LEFTMOUSE')) items.extend(node_select_ops('RIGHTMOUSE')) else: items.extend(node_select_ops('LEFTMOUSE')) items.extend([ ("node.select_box", {"type": params.select_tweak, "value": 'ANY'}, {"properties": [("tweak", True)]}), ("node.select_lasso", {"type": 'EVT_TWEAK_L', "value": 'ANY', "ctrl": True, "alt": True}, {"properties": [("mode", 'ADD')]}), ("node.select_lasso", {"type": 'EVT_TWEAK_L', "value": 'ANY', "shift": True, "ctrl": True, "alt": True}, {"properties": [("mode", 'SUB')]}), ("node.select_circle", {"type": 'C', "value": 'PRESS'}, None), ("node.link", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, {"properties": [("detach", False)]}), ("node.link", {"type": 'EVT_TWEAK_L', "value": 'ANY', "ctrl": True}, {"properties": [("detach", True)]}), ("node.resize", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, None), ("node.add_reroute", {"type": params.action_tweak, "value": 'ANY', "shift": True}, None), ("node.links_cut", {"type": params.action_tweak, "value": 'ANY', "ctrl": True}, None), ("node.select_link_viewer", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("node.backimage_move", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "alt": True}, None), ("node.backimage_zoom", {"type": 'V', "value": 'PRESS'}, {"properties": [("factor", 1.0 / 1.2)]}), ("node.backimage_zoom", {"type": 'V', "value": 'PRESS', "alt": True}, {"properties": [("factor", 1.2)]}), ("node.backimage_fit", {"type": 'HOME', "value": 'PRESS', "alt": True}, None), ("node.backimage_sample", {"type": params.action_mouse, "value": 'PRESS', "alt": True}, None), op_menu("NODE_MT_context_menu", params.context_menu_event), ("node.link_make", {"type": 'F', "value": 'PRESS'}, {"properties": [("replace", False)]}), ("node.link_make", {"type": 'F', "value": 'PRESS', "shift": True}, {"properties": [("replace", True)]}), op_menu("NODE_MT_add", {"type": 'A', "value": 'PRESS', "shift": True}), ("node.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), ("node.duplicate_move_keep_inputs", {"type": 'D', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("node.parent_set", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), ("node.detach", {"type": 'P', "value": 'PRESS', "alt": True}, None), ("node.join", {"type": 'J', "value": 'PRESS', "ctrl": True}, None), ("node.hide_toggle", {"type": 'H', "value": 'PRESS'}, None), ("node.mute_toggle", {"type": 'M', "value": 'PRESS'}, None), ("node.preview_toggle", {"type": 'H', "value": 'PRESS', "shift": True}, None), ("node.hide_socket_toggle", {"type": 'H', "value": 'PRESS', "ctrl": True}, None), ("node.view_all", {"type": 'HOME', "value": 'PRESS'}, None), ("node.view_all", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, None), ("node.view_selected", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, None), ("node.select_box", {"type": 'B', "value": 'PRESS'}, {"properties": [("tweak", False)]}), ("node.delete", {"type": 'X', "value": 'PRESS'}, None), ("node.delete", {"type": 'DEL', "value": 'PRESS'}, None), ("node.delete_reconnect", {"type": 'X', "value": 'PRESS', "ctrl": True}, None), ("node.delete_reconnect", {"type": 'DEL', "value": 'PRESS', "ctrl": True}, None), *_template_items_select_actions(params, "node.select_all"), ("node.select_linked_to", {"type": 'L', "value": 'PRESS', "shift": True}, None), ("node.select_linked_from", {"type": 'L', "value": 'PRESS'}, None), ("node.select_grouped", {"type": 'G', "value": 'PRESS', "shift": True}, {"properties": [("extend", False)]}), ("node.select_grouped", {"type": 'G', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("extend", True)]}), ("node.select_same_type_step", {"type": 'RIGHT_BRACKET', "value": 'PRESS', "shift": True}, {"properties": [("prev", False)]}), ("node.select_same_type_step", {"type": 'LEFT_BRACKET', "value": 'PRESS', "shift": True}, {"properties": [("prev", True)]}), ("node.find_node", {"type": 'F', "value": 'PRESS', "ctrl": True}, None), ("node.group_make", {"type": 'G', "value": 'PRESS', "ctrl": True}, None), ("node.group_ungroup", {"type": 'G', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("node.group_separate", {"type": 'P', "value": 'PRESS'}, None), ("node.group_edit", {"type": 'TAB', "value": 'PRESS'}, {"properties": [("exit", False)]}), ("node.group_edit", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, {"properties": [("exit", True)]}), ("node.read_viewlayers", {"type": 'R', "value": 'PRESS', "ctrl": True}, None), ("node.render_changed", {"type": 'Z', "value": 'PRESS'}, None), ("node.clipboard_copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("node.clipboard_paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ("node.viewer_border", {"type": 'B', "value": 'PRESS', "ctrl": True}, None), ("node.clear_viewer_border", {"type": 'B', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("node.translate_attach", {"type": 'G', "value": 'PRESS'}, None), ("node.translate_attach", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, None), ("node.translate_attach", {"type": params.select_tweak, "value": 'ANY'}, None), ("transform.translate", {"type": 'G', "value": 'PRESS'}, {"properties": [("release_confirm", True)]}), ("transform.translate", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ("transform.translate", {"type": params.select_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ("node.move_detach_links", {"type": 'D', "value": 'PRESS', "alt": True}, None), ("node.move_detach_links_release", {"type": params.action_tweak, "value": 'ANY', "alt": True}, None), ("node.move_detach_links", {"type": params.select_tweak, "value": 'ANY', "alt": True}, None), ("wm.context_toggle", {"type": 'TAB', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'tool_settings.use_snap')]}), ("wm.context_menu_enum", {"type": 'TAB', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("data_path", 'tool_settings.snap_node_element')]}), ]) return keymap def km_info(params): items = [] keymap = ( "Info", {"space_type": 'INFO', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("info.select_pick", {"type": 'LEFTMOUSE', "value": 'CLICK'}, None), ("info.select_pick", {"type": 'LEFTMOUSE', "value": 'CLICK', "shift": True}, {"properties": [("extend", True)]}), ("info.select_box", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, {"properties": [("wait_for_input", False)]}), *_template_items_select_actions(params, "info.select_all"), ("info.select_box", {"type": 'B', "value": 'PRESS'}, None), ("info.report_replay", {"type": 'R', "value": 'PRESS'}, None), ("info.report_delete", {"type": 'X', "value": 'PRESS'}, None), ("info.report_delete", {"type": 'DEL', "value": 'PRESS'}, None), ("info.report_copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_partslist(params): items = [] keymap = ( "Partslist", {"space_type": 'PARTSLIST_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("partslist.select_pick", {"type": 'LEFTMOUSE', "value": 'CLICK'}, None), ("partslist.select_pick", {"type": 'LEFTMOUSE', "value": 'CLICK', "shift": True}, {"properties": [("extend", True)]}), ("partslist.select_box", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, {"properties": [("wait_for_input", False)]}), *_template_items_select_actions(params, "partslist.select_all"), ("partslist.select_box", {"type": 'B', "value": 'PRESS'}, None), ("partslist.report_replay", {"type": 'R', "value": 'PRESS'}, None), ("partslist.report_delete", {"type": 'X', "value": 'PRESS'}, None), ("partslist.report_delete", {"type": 'DEL', "value": 'PRESS'}, None), ("partslist.report_copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_file_browser(_params): items = [] keymap = ( "File Browser", {"space_type": 'FILE_BROWSER', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("file.parent", {"type": 'UP_ARROW', "value": 'PRESS', "alt": True}, None), ("file.previous", {"type": 'LEFT_ARROW', "value": 'PRESS', "alt": True}, None), ("file.next", {"type": 'RIGHT_ARROW', "value": 'PRESS', "alt": True}, None), ("file.refresh", {"type": 'R', "value": 'PRESS'}, None), ("file.parent", {"type": 'P', "value": 'PRESS'}, None), ("file.previous", {"type": 'BACK_SPACE', "value": 'PRESS'}, None), ("file.next", {"type": 'BACK_SPACE', "value": 'PRESS', "shift": True}, None), ("wm.context_toggle", {"type": 'H', "value": 'PRESS'}, {"properties": [("data_path", 'space_data.params.show_hidden')]}), ("file.directory_new", {"type": 'I', "value": 'PRESS'}, None), ("file.smoothscroll", {"type": 'TIMER1', "value": 'ANY', "any": True}, None), ("file.bookmark_toggle", {"type": 'T', "value": 'PRESS'}, None), ("file.bookmark_add", {"type": 'B', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_file_browser_main(_params): items = [] keymap = ( "File Browser Main", {"space_type": 'FILE_BROWSER', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("file.execute", {"type": 'LEFTMOUSE', "value": 'DOUBLE_CLICK'}, {"properties": [("need_active", True)]}), ("file.refresh", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, None), ("file.select", {"type": 'LEFTMOUSE', "value": 'CLICK'}, None), ("file.select", {"type": 'LEFTMOUSE', "value": 'CLICK', "shift": True}, {"properties": [("extend", True)]}), ("file.select", {"type": 'LEFTMOUSE', "value": 'CLICK', "shift": True, "ctrl": True}, {"properties": [("extend", True), ("fill", True)]}), ("file.select", {"type": 'RIGHTMOUSE', "value": 'CLICK'}, {"properties": [("open", False)]}), ("file.select", {"type": 'RIGHTMOUSE', "value": 'CLICK', "shift": True}, {"properties": [("extend", True), ("open", False)]}), ("file.select", {"type": 'RIGHTMOUSE', "value": 'CLICK', "alt": True}, {"properties": [("extend", True), ("fill", True), ("open", False)]}), ("file.select_walk", {"type": 'UP_ARROW', "value": 'PRESS'}, {"properties": [("direction", 'UP')]}), ("file.select_walk", {"type": 'UP_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'UP'), ("extend", True)]}), ("file.select_walk", {"type": 'UP_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("direction", 'UP'), ("extend", True), ("fill", True)]}), ("file.select_walk", {"type": 'DOWN_ARROW', "value": 'PRESS'}, {"properties": [("direction", 'DOWN')]}), ("file.select_walk", {"type": 'DOWN_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'DOWN'), ("extend", True)]}), ("file.select_walk", {"type": 'DOWN_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("direction", 'DOWN'), ("extend", True), ("fill", True)]}), ("file.select_walk", {"type": 'LEFT_ARROW', "value": 'PRESS'}, {"properties": [("direction", 'LEFT')]}), ("file.select_walk", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'LEFT'), ("extend", True)]}), ("file.select_walk", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("direction", 'LEFT'), ("extend", True), ("fill", True)]}), ("file.select_walk", {"type": 'RIGHT_ARROW', "value": 'PRESS'}, {"properties": [("direction", 'RIGHT')]}), ("file.select_walk", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'RIGHT'), ("extend", True)]}), ("file.select_walk", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("direction", 'RIGHT'), ("extend", True), ("fill", True)]}), ("file.previous", {"type": 'BUTTON4MOUSE', "value": 'CLICK'}, None), ("file.next", {"type": 'BUTTON5MOUSE', "value": 'CLICK'}, None), ("file.select_all", {"type": 'A', "value": 'PRESS'}, None), ("file.select_box", {"type": 'B', "value": 'PRESS'}, None), ("file.select_box", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, None), ("file.select_box", {"type": 'EVT_TWEAK_L', "value": 'ANY', "shift": True}, {"properties": [("mode", 'ADD')]}), ("file.rename", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, None), ("file.highlight", {"type": 'MOUSEMOVE', "value": 'ANY', "any": True}, None), ("file.filenum", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, {"properties": [("increment", 1)]}), ("file.filenum", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "shift": True}, {"properties": [("increment", 10)]}), ("file.filenum", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, {"properties": [("increment", 100)]}), ("file.filenum", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, {"properties": [("increment", -1)]}), ("file.filenum", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "shift": True}, {"properties": [("increment", -10)]}), ("file.filenum", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, {"properties": [("increment", -100)]}), ]) return keymap def km_file_browser_buttons(_params): items = [] keymap = ( "File Browser Buttons", {"space_type": 'FILE_BROWSER', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("file.filenum", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, {"properties": [("increment", 1)]}), ("file.filenum", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "shift": True}, {"properties": [("increment", 10)]}), ("file.filenum", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, {"properties": [("increment", 100)]}), ("file.filenum", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, {"properties": [("increment", -1)]}), ("file.filenum", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "shift": True}, {"properties": [("increment", -10)]}), ("file.filenum", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, {"properties": [("increment", -100)]}), ]) return keymap def km_dopesheet_generic(_params): items = [] keymap = ( "Dopesheet Generic", {"space_type": 'DOPESHEET_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_space_region_type_toggle( sidebar_key={"type": 'N', "value": 'PRESS'}, ), ("wm.context_set_enum", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'area.type'), ("value", 'GRAPH_EDITOR')]}) ]) return keymap def km_dopesheet(params): items = [] keymap = ( "Dopesheet", {"space_type": 'DOPESHEET_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("action.clickselect", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("extend", False), ("deselect_all", not params.legacy), ("column", False), ("channel", False)]}), ("action.clickselect", {"type": params.select_mouse, "value": 'PRESS', "alt": True}, {"properties": [("extend", False), ("column", True), ("channel", False)]}), ("action.clickselect", {"type": params.select_mouse, "value": 'CLICK', "shift": True}, {"properties": [("extend", True), ("column", False), ("channel", False)]}), ("action.clickselect", {"type": params.select_mouse, "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("extend", True), ("column", True), ("channel", False)]}), ("action.clickselect", {"type": params.select_mouse, "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("extend", False), ("column", False), ("channel", True)]}), ("action.clickselect", {"type": params.select_mouse, "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, {"properties": [("extend", True), ("column", False), ("channel", True)]}), ("action.select_leftright", {"type": params.select_mouse, "value": 'CLICK', "ctrl": True}, {"properties": [("mode", 'CHECK'), ("extend", False)]}), ("action.select_leftright", {"type": params.select_mouse, "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("mode", 'CHECK'), ("extend", True)]}), ("action.select_leftright", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("mode", 'LEFT'), ("extend", False)]}), ("action.select_leftright", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("mode", 'RIGHT'), ("extend", False)]}), *_template_items_select_actions(params, "action.select_all"), ("action.select_box", {"type": 'B', "value": 'PRESS'}, {"properties": [("axis_range", False)]}), ("action.select_box", {"type": 'B', "value": 'PRESS', "alt": True}, {"properties": [("axis_range", True)]}), ("action.select_box", {"type": params.select_tweak, "value": 'ANY'}, {"properties":[("axis_range", False), ("wait_for_input", False), ("mode", 'SET')]}), ("action.select_box", {"type": params.select_tweak, "value": 'ANY', "shift": True}, {"properties":[("axis_range", False), ("wait_for_input", False), ("mode", 'ADD')]}), ("action.select_box", {"type": params.select_tweak, "value": 'ANY', "ctrl": True}, {"properties":[("axis_range", False), ("wait_for_input", False), ("mode", 'SUB')]}), ("action.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True}, {"properties": [("mode", 'ADD')]}), ("action.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True}, {"properties": [("mode", 'SUB')]}), ("action.select_circle", {"type": 'C', "value": 'PRESS'}, None), ("action.select_column", {"type": 'K', "value": 'PRESS'}, {"properties": [("mode", 'KEYS')]}), ("action.select_column", {"type": 'K', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'CFRA')]}), ("action.select_column", {"type": 'K', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'MARKERS_COLUMN')]}), ("action.select_column", {"type": 'K', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'MARKERS_BETWEEN')]}), ("action.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("action.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("action.select_linked", {"type": 'L', "value": 'PRESS'}, None), ("action.frame_jump", {"type": 'G', "value": 'PRESS', "ctrl": True}, None), op_menu_pie("DOPESHEET_MT_snap_pie", {"type": 'S', "value": 'PRESS', "shift": True}), ("action.mirror", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ("action.handle_type", {"type": 'V', "value": 'PRESS'}, None), ("action.interpolation_type", {"type": 'T', "value": 'PRESS'}, None), ("action.extrapolation_type", {"type": 'E', "value": 'PRESS', "shift": True}, None), ("action.keyframe_type", {"type": 'R', "value": 'PRESS'}, None), op_menu("DOPESHEET_MT_context_menu", params.context_menu_event), ("action.sample", {"type": 'O', "value": 'PRESS', "shift": True, "alt": True}, None), op_menu("DOPESHEET_MT_delete", {"type": 'X', "value": 'PRESS'}), op_menu("DOPESHEET_MT_delete", {"type": 'DEL', "value": 'PRESS'}), ("action.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), ("action.keyframe_insert", {"type": 'I', "value": 'PRESS'}, None), ("action.copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("action.paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ("action.paste", {"type": 'V', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("flipped", True)]}), ("action.previewrange_set", {"type": 'P', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("action.view_all", {"type": 'HOME', "value": 'PRESS'}, None), ("action.view_all", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, None), ("action.view_selected", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, None), ("action.view_frame", {"type": 'NUMPAD_0', "value": 'PRESS'}, None), ("anim.channels_editable_toggle", {"type": 'TAB', "value": 'PRESS'}, None), ("anim.channels_find", {"type": 'F', "value": 'PRESS', "ctrl": True}, None), ("transform.transform", {"type": 'G', "value": 'PRESS'}, {"properties": [("mode", 'TIME_TRANSLATE')]}), ("transform.transform", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("mode", 'TIME_TRANSLATE')]}), ("transform.transform", {"type": 'E', "value": 'PRESS'}, {"properties": [("mode", 'TIME_EXTEND')]}), ("transform.transform", {"type": 'S', "value": 'PRESS'}, {"properties": [("mode", 'TIME_SCALE')]}), ("transform.transform", {"type": 'T', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'TIME_SLIDE')]}), ("wm.context_toggle", {"type": 'O', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.use_proportional_action')]}), op_menu_pie("VIEW3D_MT_proportional_editing_falloff_pie", {"type": 'O', "value": 'PRESS', "shift": True}), ("marker.add", {"type": 'M', "value": 'PRESS'}, None), ("marker.rename", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ("anim.start_frame_set", {"type": 'HOME', "value": 'PRESS', "ctrl": True}, None), ("anim.end_frame_set", {"type": 'END', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_nla_generic(_params): items = [] keymap = ( "NLA Generic", {"space_type": 'NLA_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_space_region_type_toggle( sidebar_key={"type": 'N', "value": 'PRESS'}, ), ("nla.tweakmode_enter", {"type": 'TAB', "value": 'PRESS'}, None), ("nla.tweakmode_exit", {"type": 'TAB', "value": 'PRESS'}, None), ("nla.tweakmode_enter", {"type": 'TAB', "value": 'PRESS', "shift": True}, {"properties": [("isolate_action", True)]}), ("nla.tweakmode_exit", {"type": 'TAB', "value": 'PRESS', "shift": True}, {"properties": [("isolate_action", True)]}), ("anim.channels_find", {"type": 'F', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_nla_channels(params): items = [] keymap = ( "NLA Channels", {"space_type": 'NLA_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("nla.channels_click", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("extend", False)]}), ("nla.channels_click", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("extend", True)]}), ("nla.tracks_add", {"type": 'A', "value": 'PRESS', "shift": True}, {"properties": [("above_selected", False)]}), ("nla.tracks_add", {"type": 'A', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("above_selected", True)]}), ("nla.tracks_delete", {"type": 'X', "value": 'PRESS'}, None), ("nla.tracks_delete", {"type": 'DEL', "value": 'PRESS'}, None), op_menu("NLA_MT_channel_context_menu", params.context_menu_event), ]) return keymap def km_nla_editor(params): items = [] keymap = ( "NLA Editor", {"space_type": 'NLA_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("nla.click_select", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("extend", False), ("deselect_all", not params.legacy)]}), ("nla.click_select", {"type": params.select_mouse, "value": 'PRESS', "shift": True}, {"properties": [("extend", True)]}), ("nla.select_leftright", {"type": params.select_mouse, "value": 'CLICK', "ctrl": True}, {"properties": [("mode", 'CHECK'), ("extend", False)]}), ("nla.select_leftright", {"type": params.select_mouse, "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("mode", 'CHECK'), ("extend", True)]}), ("nla.select_leftright", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("mode", 'LEFT'), ("extend", False)]}), ("nla.select_leftright", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("mode", 'RIGHT'), ("extend", False)]}), *_template_items_select_actions(params, "nla.select_all"), ("nla.select_box", {"type": 'B', "value": 'PRESS'}, {"properties": [("axis_range", False)]}), ("nla.select_box", {"type": 'B', "value": 'PRESS', "alt": True}, {"properties": [("axis_range", True)]}), ("nla.select_box", {"type": params.select_tweak, "value": 'ANY'}, {"properties":[("wait_for_input", False), ("mode", 'SET')]}), ("nla.select_box", {"type": params.select_tweak, "value": 'ANY', "shift": True}, {"properties":[("wait_for_input", False), ("mode", 'ADD')]}), ("nla.select_box", {"type": params.select_tweak, "value": 'ANY', "ctrl": True}, {"properties":[("wait_for_input", False), ("mode", 'SUB')]}), ("nla.previewrange_set", {"type": 'P', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("nla.view_all", {"type": 'HOME', "value": 'PRESS'}, None), ("nla.view_all", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, None), ("nla.view_selected", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, None), ("nla.view_frame", {"type": 'NUMPAD_0', "value": 'PRESS'}, None), ("nla.actionclip_add", {"type": 'A', "value": 'PRESS', "shift": True}, None), ("nla.transition_add", {"type": 'T', "value": 'PRESS', "shift": True}, None), ("nla.soundclip_add", {"type": 'K', "value": 'PRESS', "shift": True}, None), ("nla.meta_add", {"type": 'G', "value": 'PRESS', "ctrl": True}, None), ("nla.meta_remove", {"type": 'G', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("nla.duplicate", {"type": 'D', "value": 'PRESS', "shift": True}, {"properties": [("linked", False)]}), ("nla.duplicate", {"type": 'D', "value": 'PRESS', "alt": True}, {"properties": [("linked", True)]}), ("nla.make_single_user", {"type": 'U', "value": 'PRESS'}, None), ("nla.delete", {"type": 'X', "value": 'PRESS'}, None), ("nla.delete", {"type": 'DEL', "value": 'PRESS'}, None), ("nla.split", {"type": 'Y', "value": 'PRESS'}, None), ("nla.mute_toggle", {"type": 'H', "value": 'PRESS'}, None), ("nla.swap", {"type": 'F', "value": 'PRESS', "alt": True}, None), ("nla.move_up", {"type": 'PAGE_UP', "value": 'PRESS'}, None), ("nla.move_down", {"type": 'PAGE_DOWN', "value": 'PRESS'}, None), ("nla.apply_scale", {"type": 'A', "value": 'PRESS', "ctrl": True}, None), ("nla.clear_scale", {"type": 'S', "value": 'PRESS', "alt": True}, None), op_menu_pie("NLA_MT_snap_pie", {"type": 'S', "value": 'PRESS', "shift": True}), op_menu("NLA_MT_context_menu", params.context_menu_event), ("nla.fmodifier_add", {"type": 'M', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("transform.transform", {"type": 'G', "value": 'PRESS'}, {"properties": [("mode", 'TRANSLATION')]}), ("transform.transform", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("mode", 'TRANSLATION')]}), ("transform.transform", {"type": 'E', "value": 'PRESS'}, {"properties": [("mode", 'TIME_EXTEND')]}), ("transform.transform", {"type": 'S', "value": 'PRESS'}, {"properties": [("mode", 'TIME_SCALE')]}), ("marker.add", {"type": 'M', "value": 'PRESS'}, None), ("marker.rename", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_text_generic(params): items = [] keymap = ( "Text Generic", {"space_type": 'TEXT_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_space_region_type_toggle( sidebar_key={"type": 'T', "value": 'PRESS', "ctrl": True}, ), ("text.start_find", {"type": 'F', "value": 'PRESS', "ctrl": True}, None), ("text.jump", {"type": 'J', "value": 'PRESS', "ctrl": True}, None), ("text.find", {"type": 'G', "value": 'PRESS', "ctrl": True}, None), ("text.replace", {"type": 'H', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_text(params): items = [] keymap = ( "Text", {"space_type": 'TEXT_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("text.move", {"type": 'LEFT_ARROW', "value": 'PRESS', "alt": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("text.move", {"type": 'RIGHT_ARROW', "value": 'PRESS', "alt": True}, {"properties": [("type", 'NEXT_WORD')]}), ("wm.context_cycle_int", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.font_size'), ("reverse", False)]}), ("wm.context_cycle_int", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.font_size'), ("reverse", True)]}), ("wm.context_cycle_int", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.font_size'), ("reverse", False)]}), ("wm.context_cycle_int", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.font_size'), ("reverse", True)]}), ]) if not params.legacy: items.extend([ ("text.new", {"type": 'N', "value": 'PRESS', "alt": True}, None), ]) else: items.extend([ ("text.new", {"type": 'N', "value": 'PRESS', "ctrl": True}, None), ]) items.extend([ ("text.open", {"type": 'O', "value": 'PRESS', "alt": True}, None), ("text.reload", {"type": 'R', "value": 'PRESS', "alt": True}, None), ("text.save", {"type": 'S', "value": 'PRESS', "alt": True}, None), ("text.save_as", {"type": 'S', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("text.run_script", {"type": 'P', "value": 'PRESS', "alt": True}, None), ("text.cut", {"type": 'X', "value": 'PRESS', "ctrl": True}, None), ("text.copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("text.paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ("text.cut", {"type": 'DEL', "value": 'PRESS', "shift": True}, None), ("text.copy", {"type": 'INSERT', "value": 'PRESS', "ctrl": True}, None), ("text.paste", {"type": 'INSERT', "value": 'PRESS', "shift": True}, None), ("text.duplicate_line", {"type": 'D', "value": 'PRESS', "ctrl": True}, None), ("text.select_all", {"type": 'A', "value": 'PRESS', "ctrl": True}, None), ("text.select_line", {"type": 'A', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("text.select_word", {"type": 'LEFTMOUSE', "value": 'DOUBLE_CLICK'}, None), ("text.move_lines", {"type": 'UP_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("direction", 'UP')]}), ("text.move_lines", {"type": 'DOWN_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("direction", 'DOWN')]}), ("text.indent", {"type": 'TAB', "value": 'PRESS'}, None), ("text.unindent", {"type": 'TAB', "value": 'PRESS', "shift": True}, None), ("text.uncomment", {"type": 'D', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("text.move", {"type": 'HOME', "value": 'PRESS'}, {"properties": [("type", 'LINE_BEGIN')]}), ("text.move", {"type": 'END', "value": 'PRESS'}, {"properties": [("type", 'LINE_END')]}), ("text.move", {"type": 'E', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'LINE_END')]}), ("text.move", {"type": 'E', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'LINE_END')]}), ("text.move", {"type": 'LEFT_ARROW', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("text.move", {"type": 'RIGHT_ARROW', "value": 'PRESS'}, {"properties": [("type", 'NEXT_CHARACTER')]}), ("text.move", {"type": 'LEFT_ARROW', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("text.move", {"type": 'RIGHT_ARROW', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'NEXT_WORD')]}), ("text.move", {"type": 'UP_ARROW', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_LINE')]}), ("text.move", {"type": 'DOWN_ARROW', "value": 'PRESS'}, {"properties": [("type", 'NEXT_LINE')]}), ("text.move", {"type": 'PAGE_UP', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_PAGE')]}), ("text.move", {"type": 'PAGE_DOWN', "value": 'PRESS'}, {"properties": [("type", 'NEXT_PAGE')]}), ("text.move", {"type": 'HOME', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'FILE_TOP')]}), ("text.move", {"type": 'END', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'FILE_BOTTOM')]}), ("text.move_select", {"type": 'HOME', "value": 'PRESS', "shift": True}, {"properties": [("type", 'LINE_BEGIN')]}), ("text.move_select", {"type": 'END', "value": 'PRESS', "shift": True}, {"properties": [("type", 'LINE_END')]}), ("text.move_select", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("text.move_select", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("type", 'NEXT_CHARACTER')]}), ("text.move_select", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("text.move_select", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'NEXT_WORD')]}), ("text.move_select", {"type": 'UP_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_LINE')]}), ("text.move_select", {"type": 'DOWN_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("type", 'NEXT_LINE')]}), ("text.move_select", {"type": 'PAGE_UP', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_PAGE')]}), ("text.move_select", {"type": 'PAGE_DOWN', "value": 'PRESS', "shift": True}, {"properties": [("type", 'NEXT_PAGE')]}), ("text.move_select", {"type": 'HOME', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'FILE_TOP')]}), ("text.move_select", {"type": 'END', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'FILE_BOTTOM')]}), ("text.delete", {"type": 'DEL', "value": 'PRESS'}, {"properties": [("type", 'NEXT_CHARACTER')]}), ("text.delete", {"type": 'BACK_SPACE', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("text.delete", {"type": 'BACK_SPACE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("text.delete", {"type": 'DEL', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'NEXT_WORD')]}), ("text.delete", {"type": 'BACK_SPACE', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("text.overwrite_toggle", {"type": 'INSERT', "value": 'PRESS'}, None), ("text.scroll_bar", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("text.scroll_bar", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("text.scroll", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("text.scroll", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ("text.selection_set", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, None), ("text.cursor_set", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("text.selection_set", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("select", True)]}), ("text.scroll", {"type": 'WHEELUPMOUSE', "value": 'PRESS'}, {"properties": [("lines", -1)]}), ("text.scroll", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS'}, {"properties": [("lines", 1)]}), ("text.line_break", {"type": 'RET', "value": 'PRESS'}, None), ("text.line_break", {"type": 'NUMPAD_ENTER', "value": 'PRESS'}, None), op_menu("TEXT_MT_toolbox", {"type": 'RIGHTMOUSE', "value": 'PRESS', "any": True}), ("text.autocomplete", {"type": 'SPACE', "value": 'PRESS', "ctrl": True}, None), ("text.line_number", {"type": 'TEXTINPUT', "value": 'ANY', "any": True}, None), ("text.insert", {"type": 'TEXTINPUT', "value": 'ANY', "any": True}, None), ]) return keymap def km_console(params): items = [] keymap = ( "Console", {"space_type": 'CONSOLE', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("console.move", {"type": 'LEFT_ARROW', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("console.move", {"type": 'RIGHT_ARROW', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'NEXT_WORD')]}), ("console.move", {"type": 'HOME', "value": 'PRESS'}, {"properties": [("type", 'LINE_BEGIN')]}), ("console.move", {"type": 'END', "value": 'PRESS'}, {"properties": [("type", 'LINE_END')]}), ("wm.context_cycle_int", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.font_size'), ("reverse", False)]}), ("wm.context_cycle_int", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.font_size'), ("reverse", True)]}), ("wm.context_cycle_int", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.font_size'), ("reverse", False)]}), ("wm.context_cycle_int", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.font_size'), ("reverse", True)]}), ("console.move", {"type": 'LEFT_ARROW', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("console.move", {"type": 'RIGHT_ARROW', "value": 'PRESS'}, {"properties": [("type", 'NEXT_CHARACTER')]}), ("console.history_cycle", {"type": 'UP_ARROW', "value": 'PRESS'}, {"properties": [("reverse", True)]}), ("console.history_cycle", {"type": 'DOWN_ARROW', "value": 'PRESS'}, {"properties": [("reverse", False)]}), ("console.delete", {"type": 'DEL', "value": 'PRESS'}, {"properties": [("type", 'NEXT_CHARACTER')]}), ("console.delete", {"type": 'BACK_SPACE', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("console.delete", {"type": 'BACK_SPACE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("console.delete", {"type": 'DEL', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'NEXT_WORD')]}), ("console.delete", {"type": 'BACK_SPACE', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("console.clear_line", {"type": 'RET', "value": 'PRESS', "shift": True}, None), ("console.clear_line", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "shift": True}, None), ("console.execute", {"type": 'RET', "value": 'PRESS'}, {"properties": [("interactive", True)]}), ("console.execute", {"type": 'NUMPAD_ENTER', "value": 'PRESS'}, {"properties": [("interactive", True)]}), ("console.autocomplete", {"type": 'SPACE', "value": 'PRESS', "ctrl": True}, None), ("console.copy_as_script", {"type": 'C', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("console.copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("console.paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ("console.select_set", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("console.select_word", {"type": 'LEFTMOUSE', "value": 'DOUBLE_CLICK'}, None), ("console.insert", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, {"properties": [("text", '\t')]}), ("console.indent", {"type": 'TAB', "value": 'PRESS'}, None), ("console.unindent", {"type": 'TAB', "value": 'PRESS', "shift": True}, None), ("console.insert", {"type": 'TEXTINPUT', "value": 'ANY', "any": True}, None), ]) return keymap def km_clip(_params): items = [] keymap = ( "Clip", {"space_type": 'CLIP_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_space_region_type_toggle( toolbar_key={"type": 'T', "value": 'PRESS'}, sidebar_key={"type": 'N', "value": 'PRESS'}, ), ("clip.open", {"type": 'O', "value": 'PRESS', "alt": True}, None), ("clip.track_markers", {"type": 'LEFT_ARROW', "value": 'PRESS', "alt": True}, {"properties": [("backwards", True), ("sequence", False)]}), ("clip.track_markers", {"type": 'RIGHT_ARROW', "value": 'PRESS', "alt": True}, {"properties": [("backwards", False), ("sequence", False)]}), ("clip.track_markers", {"type": 'T', "value": 'PRESS', "ctrl": True}, {"properties": [("backwards", False), ("sequence", True)]}), ("clip.track_markers", {"type": 'T', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("backwards", True), ("sequence", True)]}), ("wm.context_toggle_enum", {"type": 'TAB', "value": 'PRESS'}, {"properties": [("data_path", 'space_data.mode'), ("value_1", 'TRACKING'), ("value_2", 'MASK')]}), ("clip.prefetch", {"type": 'P', "value": 'PRESS'}, None), op_menu_pie("CLIP_MT_tracking_pie", {"type": 'E', "value": 'PRESS'}), op_menu_pie("CLIP_MT_solving_pie", {"type": 'S', "value": 'PRESS', "shift": True}), op_menu_pie("CLIP_MT_marker_pie", {"type": 'E', "value": 'PRESS', "shift": True}), op_menu_pie("CLIP_MT_reconstruction_pie", {"type": 'W', "value": 'PRESS', "shift": True}), ]) return keymap def km_clip_editor(params): items = [] keymap = ( "Clip Editor", {"space_type": 'CLIP_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("clip.view_pan", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("clip.view_pan", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "shift": True}, None), ("clip.view_pan", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ("clip.view_zoom", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "ctrl": True}, None), ("clip.view_zoom", {"type": 'TRACKPADZOOM', "value": 'ANY'}, None), ("clip.view_zoom", {"type": 'TRACKPADPAN', "value": 'ANY', "ctrl": True}, None), ("clip.view_zoom_in", {"type": 'WHEELINMOUSE', "value": 'PRESS'}, None), ("clip.view_zoom_out", {"type": 'WHEELOUTMOUSE', "value": 'PRESS'}, None), ("clip.view_zoom_in", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, None), ("clip.view_zoom_out", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, None), ("clip.view_zoom_ratio", {"type": 'NUMPAD_8', "value": 'PRESS', "ctrl": True}, {"properties": [("ratio", 8.0)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_4', "value": 'PRESS', "ctrl": True}, {"properties": [("ratio", 4.0)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_2', "value": 'PRESS', "ctrl": True}, {"properties": [("ratio", 2.0)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_8', "value": 'PRESS', "shift": True}, {"properties": [("ratio", 8.0)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_4', "value": 'PRESS', "shift": True}, {"properties": [("ratio", 4.0)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_2', "value": 'PRESS', "shift": True}, {"properties": [("ratio", 2.0)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_1', "value": 'PRESS'}, {"properties": [("ratio", 1.0)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_2', "value": 'PRESS'}, {"properties": [("ratio", 0.5)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_4', "value": 'PRESS'}, {"properties": [("ratio", 0.25)]}), ("clip.view_zoom_ratio", {"type": 'NUMPAD_8', "value": 'PRESS'}, {"properties": [("ratio", 0.125)]}), ("clip.view_all", {"type": 'HOME', "value": 'PRESS'}, None), ("clip.view_all", {"type": 'F', "value": 'PRESS'}, {"properties": [("fit_view", True)]}), ("clip.view_selected", {"type": 'NUMPAD_PERIOD', "value": 'PRESS'}, None), ("clip.view_all", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, None), ("clip.view_ndof", {"type": 'NDOF_MOTION', "value": 'ANY'}, None), ("clip.frame_jump", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("position", 'PATHSTART')]}), ("clip.frame_jump", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("position", 'PATHEND')]}), ("clip.frame_jump", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("position", 'FAILEDPREV')]}), ("clip.frame_jump", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("position", 'PATHSTART')]}), ("clip.change_frame", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("clip.select", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("extend", False), ("deselect_all", not params.legacy)]}), ("clip.select", {"type": params.select_mouse, "value": 'PRESS', "shift": True}, {"properties": [("extend", True)]}), *_template_items_select_actions(params, "clip.select_all"), ("clip.select_box", {"type": 'B', "value": 'PRESS'}, None), ("clip.select_circle", {"type": 'C', "value": 'PRESS'}, None), op_menu("CLIP_MT_select_grouped", {"type": 'G', "value": 'PRESS', "shift": True}), ("clip.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, {"properties": [("mode", 'ADD')]}), ("clip.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True, "alt": True}, {"properties": [("mode", 'SUB')]}), ("clip.add_marker_slide", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, None), ("clip.delete_marker", {"type": 'X', "value": 'PRESS', "shift": True}, None), ("clip.delete_marker", {"type": 'DEL', "value": 'PRESS', "shift": True}, None), ("clip.slide_marker", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("clip.disable_markers", {"type": 'D', "value": 'PRESS', "shift": True}, {"properties": [("action", 'TOGGLE')]}), ("clip.delete_track", {"type": 'X', "value": 'PRESS'}, None), ("clip.delete_track", {"type": 'DEL', "value": 'PRESS'}, None), ("clip.lock_tracks", {"type": 'L', "value": 'PRESS', "ctrl": True}, {"properties": [("action", 'LOCK')]}), ("clip.lock_tracks", {"type": 'L', "value": 'PRESS', "alt": True}, {"properties": [("action", 'UNLOCK')]}), ("clip.hide_tracks", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("clip.hide_tracks", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("clip.hide_tracks_clear", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("clip.slide_plane_marker", {"type": params.action_mouse, "value": 'PRESS'}, None), ("clip.keyframe_insert", {"type": 'I', "value": 'PRESS'}, None), ("clip.keyframe_delete", {"type": 'I', "value": 'PRESS', "alt": True}, None), ("clip.join_tracks", {"type": 'J', "value": 'PRESS', "ctrl": True}, None), op_menu("CLIP_MT_tracking_context_menu", params.context_menu_event), ("wm.context_toggle", {"type": 'L', "value": 'PRESS'}, {"properties": [("data_path", 'space_data.lock_selection')]}), ("wm.context_toggle", {"type": 'D', "value": 'PRESS', "alt": True}, {"properties": [("data_path", 'space_data.show_disabled')]}), ("wm.context_toggle", {"type": 'S', "value": 'PRESS', "alt": True}, {"properties": [("data_path", 'space_data.show_marker_search')]}), ("wm.context_toggle", {"type": 'M', "value": 'PRESS'}, {"properties": [("data_path", 'space_data.use_mute_footage')]}), ("transform.translate", {"type": 'G', "value": 'PRESS'}, None), ("transform.translate", {"type": params.select_tweak, "value": 'ANY'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ("clip.clear_track_path", {"type": 'T', "value": 'PRESS', "alt": True}, {"properties": [("action", 'REMAINED'), ("clear_active", False)]}), ("clip.clear_track_path", {"type": 'T', "value": 'PRESS', "shift": True}, {"properties": [("action", 'UPTO'), ("clear_active", False)]}), ("clip.clear_track_path", {"type": 'T', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("action", 'ALL'), ("clear_active", False)]}), ("clip.cursor_set", params.cursor_set_event, None), op_menu_pie("CLIP_MT_pivot_pie", {"type": 'PERIOD', "value": 'PRESS'}), ("clip.copy_tracks", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("clip.paste_tracks", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_clip_graph_editor(params): items = [] keymap = ( "Clip Graph Editor", {"space_type": 'CLIP_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("clip.graph_select", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("extend", False)]}), ("clip.graph_select", {"type": params.select_mouse, "value": 'PRESS', "shift": True}, {"properties": [("extend", True)]}), *_template_items_select_actions(params, "clip.graph_select_all_markers"), ("clip.graph_select_box", {"type": 'B', "value": 'PRESS'}, None), ("clip.graph_delete_curve", {"type": 'X', "value": 'PRESS'}, None), ("clip.graph_delete_curve", {"type": 'DEL', "value": 'PRESS'}, None), ("clip.graph_delete_knot", {"type": 'X', "value": 'PRESS', "shift": True}, None), ("clip.graph_delete_knot", {"type": 'DEL', "value": 'PRESS', "shift": True}, None), ("clip.graph_view_all", {"type": 'HOME', "value": 'PRESS'}, None), ("clip.graph_view_all", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, None), ("clip.graph_center_current_frame", {"type": 'NUMPAD_0', "value": 'PRESS'}, None), ("wm.context_toggle", {"type": 'L', "value": 'PRESS'}, {"properties": [("data_path", 'space_data.lock_time_cursor')]}), ("clip.clear_track_path", {"type": 'T', "value": 'PRESS', "alt": True}, {"properties": [("action", 'REMAINED'), ("clear_active", True)]}), ("clip.clear_track_path", {"type": 'T', "value": 'PRESS', "shift": True}, {"properties": [("action", 'UPTO'), ("clear_active", True)]}), ("clip.clear_track_path", {"type": 'T', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("action", 'ALL'), ("clear_active", True)]}), ("clip.graph_disable_markers", {"type": 'D', "value": 'PRESS', "shift": True}, {"properties": [("action", 'TOGGLE')]}), ("transform.translate", {"type": 'G', "value": 'PRESS'}, None), ("transform.translate", {"type": params.select_tweak, "value": 'ANY'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ]) if params.select_mouse == 'LEFTMOUSE' and not params.legacy: items.extend([ ("clip.change_frame", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True}, None), ]) else: items.extend([ ("clip.change_frame", {"type": params.action_mouse, "value": 'PRESS'}, None), ]) return keymap def km_clip_dopesheet_editor(_params): items = [] keymap = ( "Clip Dopesheet Editor", {"space_type": 'CLIP_EDITOR', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("clip.dopesheet_select_channel", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("extend", True)]}), ("clip.dopesheet_view_all", {"type": 'HOME', "value": 'PRESS'}, None), ("clip.dopesheet_view_all", {"type": 'NDOF_BUTTON_FIT', "value": 'PRESS'}, None), ]) return keymap # ------------------------------------------------------------------------------ # Animation def km_frames(params): items = [] keymap = ( "Frames", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Frame offsets ("screen.frame_offset", {"type": 'LEFT_ARROW', "value": 'PRESS'}, {"properties": [("delta", -1)]}), ("screen.frame_offset", {"type": 'RIGHT_ARROW', "value": 'PRESS'}, {"properties": [("delta", 1)]}), ("screen.frame_jump", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("end", True)]}), ("screen.frame_jump", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("end", False)]}), ("screen.keyframe_jump", {"type": 'UP_ARROW', "value": 'PRESS'}, {"properties": [("next", True)]}), ("screen.keyframe_jump", {"type": 'DOWN_ARROW', "value": 'PRESS'}, {"properties": [("next", False)]}), ("screen.keyframe_jump", {"type": 'MEDIA_LAST', "value": 'PRESS'}, {"properties": [("next", True)]}), ("screen.keyframe_jump", {"type": 'MEDIA_FIRST', "value": 'PRESS'}, {"properties": [("next", False)]}), ("screen.frame_offset", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("delta", 1)]}), ("screen.frame_offset", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("delta", -1)]}), ]) if not params.legacy: # New playback if params.spacebar_action in {'TOOL', 'SEARCH'}: items.append( ("screen.animation_play", {"type": 'SPACE', "value": 'PRESS', "shift": True}, None), ) elif params.spacebar_action == 'PLAY': items.append( ("screen.animation_play", {"type": 'SPACE', "value": 'PRESS'}, None), ) else: assert False items.extend([ ("screen.animation_play", {"type": 'SPACE', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("reverse", True)]}), ]) else: # Old playback items.extend([ ("screen.frame_offset", {"type": 'UP_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("delta", 10)]}), ("screen.frame_offset", {"type": 'DOWN_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("delta", -10)]}), ("screen.frame_jump", {"type": 'UP_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("end", True)]}), ("screen.frame_jump", {"type": 'DOWN_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("end", False)]}), ("screen.animation_play", {"type": 'A', "value": 'PRESS', "alt": True}, None), ("screen.animation_play", {"type": 'A', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("reverse", True)]}), ]) items.extend([ ("screen.animation_cancel", {"type": 'ESC', "value": 'PRESS'}, None), ("screen.animation_play", {"type": 'MEDIA_PLAY', "value": 'PRESS'}, None), ("screen.animation_cancel", {"type": 'MEDIA_STOP', "value": 'PRESS'}, None), ]) return keymap def km_animation(params): items = [] keymap = ( "Animation", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Frame management. ("wm.context_toggle", {"type": 'T', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'space_data.show_seconds')]}), # Preview range. ("anim.previewrange_set", {"type": 'P', "value": 'PRESS'}, None), ("anim.previewrange_clear", {"type": 'P', "value": 'PRESS', "alt": True}, None), ]) if params.select_mouse == 'LEFTMOUSE' and not params.legacy: items.extend([ ("anim.change_frame", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True}, None), ("anim.change_frame", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True}, None), ]) else: items.extend([ ("anim.change_frame", {"type": params.action_mouse, "value": 'PRESS'}, None), ]) return keymap def km_animation_channels(params): items = [] keymap = ( "Animation Channels", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Click select. ("anim.channels_click", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("anim.channels_click", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("extend", True)]}), ("anim.channels_click", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("children_only", True)]}), # Rename. ("anim.channels_rename", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, None), ("anim.channels_rename", {"type": 'LEFTMOUSE', "value": 'DOUBLE_CLICK'}, None), # Select keys. ("anim.channel_select_keys", {"type": 'LEFTMOUSE', "value": 'DOUBLE_CLICK'}, None), ("anim.channel_select_keys", {"type": 'LEFTMOUSE', "value": 'DOUBLE_CLICK', "shift": True}, {"properties": [("extend", True)]}), # Find (setting the name filter). ("anim.channels_find", {"type": 'F', "value": 'PRESS', "ctrl": True}, None), # Selection. *_template_items_select_actions(params, "anim.channels_select_all"), ("anim.channels_select_box", {"type": 'B', "value": 'PRESS'}, None), ("anim.channels_select_box", {"type": 'EVT_TWEAK_L', "value": 'ANY'}, None), # Delete. ("anim.channels_delete", {"type": 'X', "value": 'PRESS'}, None), ("anim.channels_delete", {"type": 'DEL', "value": 'PRESS'}, None), # Settings. ("anim.channels_setting_toggle", {"type": 'W', "value": 'PRESS', "shift": True}, None), ("anim.channels_setting_enable", {"type": 'W', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("anim.channels_setting_disable", {"type": 'W', "value": 'PRESS', "alt": True}, None), ("anim.channels_editable_toggle", {"type": 'TAB', "value": 'PRESS'}, None), # Expand/collapse. ("anim.channels_expand", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, None), ("anim.channels_collapse", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, None), ("anim.channels_expand", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, {"properties": [("all", False)]}), ("anim.channels_collapse", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, {"properties": [("all", False)]}), # Move. ("anim.channels_move", {"type": 'PAGE_UP', "value": 'PRESS'}, {"properties": [("direction", 'UP')]}), ("anim.channels_move", {"type": 'PAGE_DOWN', "value": 'PRESS'}, {"properties": [("direction", 'DOWN')]}), ("anim.channels_move", {"type": 'PAGE_UP', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'TOP')]}), ("anim.channels_move", {"type": 'PAGE_DOWN', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'BOTTOM')]}), # Group. ("anim.channels_group", {"type": 'G', "value": 'PRESS', "ctrl": True}, None), ("anim.channels_ungroup", {"type": 'G', "value": 'PRESS', "ctrl": True, "alt": True}, None), # Menus. op_menu("DOPESHEET_MT_channel_context_menu", params.context_menu_event), ]) return keymap # ------------------------------------------------------------------------------ # Modes def km_grease_pencil(_params): items = [] keymap = ( "Grease Pencil", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Draw ("gpencil.annotate", {"type": 'LEFTMOUSE', "value": 'PRESS', "key_modifier": 'D'}, {"properties": [("mode", 'DRAW'), ("wait_for_input", False)]}), # Draw - straight lines ("gpencil.annotate", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True, "key_modifier": 'D'}, {"properties": [("mode", 'DRAW_STRAIGHT'), ("wait_for_input", False)]}), # Draw - poly lines ("gpencil.annotate", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True, "alt": True, "key_modifier": 'D'}, {"properties": [("mode", 'DRAW_POLY'), ("wait_for_input", False)]}), # Erase ("gpencil.annotate", {"type": 'RIGHTMOUSE', "value": 'PRESS', "key_modifier": 'D'}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), # Add blank frame (B because it's easy to reach from D). ("gpencil.blank_frame_add", {"type": 'B', "value": 'PRESS', "key_modifier": 'D'}, None), # Delete active frame - for easier video tutorials/review sessions. # This works even when not in edit mode. ("gpencil.active_frames_delete_all", {"type": 'X', "value": 'PRESS', "key_modifier": 'D'}, None), ("gpencil.active_frames_delete_all", {"type": 'DEL', "value": 'PRESS', "key_modifier": 'D'}, None), ]) return keymap def _grease_pencil_selection(params): return [ # Select all *_template_items_select_actions(params, "gpencil.select_all"), # Circle select ("gpencil.select_circle", {"type": 'C', "value": 'PRESS'}, None), # Box select ("gpencil.select_box", {"type": 'B', "value": 'PRESS'}, None), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True}, {"properties": [("mode", 'ADD')]}), ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True}, {"properties": [("mode", 'SUB')]}), # In the Node Editor, lasso select needs ALT modifier too # (as somehow CTRL+LMB drag gets taken for "cut" quite early). # There probably isn't too much harm adding this for other editors too # as part of standard GP editing keymap. This hotkey combo doesn't seem # to see much use under standard scenarios? ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, {"properties": [("mode", 'ADD')]}), ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True, "alt": True}, {"properties": [("mode", 'SUB')]}), ("gpencil.select", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True}, {"properties": [("extend", True), ("toggle", True)]}), # Whole stroke select ("gpencil.select", {"type": params.select_mouse, "value": params.select_mouse_value, "alt": True}, {"properties": [("entire_strokes", True)]}), ("gpencil.select", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True, "alt": True}, {"properties": [("extend", True), ("entire_strokes", True)]}), # Select linked ("gpencil.select_linked", {"type": 'L', "value": 'PRESS'}, None), ("gpencil.select_linked", {"type": 'L', "value": 'PRESS', "ctrl": True}, None), # Select alternate ("gpencil.select_alternate", {"type": 'L', "value": 'PRESS', "shift": True}, None), # Select grouped ("gpencil.select_grouped", {"type": 'G', "value": 'PRESS', "shift": True}, None), # Select more/less ("gpencil.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("gpencil.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ] def _grease_pencil_display(): return [ ("wm.context_toggle", {"type": 'Q', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'space_data.overlay.use_gpencil_edit_lines')]}), ("wm.context_toggle", {"type": 'Q', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("data_path", 'space_data.overlay.use_gpencil_multiedit_line_only')]}), ] def km_grease_pencil_stroke_edit_mode(params): items = [] keymap = ( "Grease Pencil Stroke Edit Mode", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Interpolation ("gpencil.interpolate", {"type": 'E', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("gpencil.interpolate_sequence", {"type": 'E', "value": 'PRESS', "shift": True, "ctrl": True}, None), # Normal select ("gpencil.select", {"type": params.select_mouse, "value": params.select_mouse_value}, {"properties": [("deselect_all", not params.legacy)]}), # Selection *_grease_pencil_selection(params), # Duplicate and move selected points ("gpencil.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), # Extrude and move selected points ("gpencil.extrude_move", {"type": 'E', "value": 'PRESS'}, None), # Delete op_menu("VIEW3D_MT_edit_gpencil_delete", {"type": 'X', "value": 'PRESS'}), op_menu("VIEW3D_MT_edit_gpencil_delete", {"type": 'DEL', "value": 'PRESS'}), ("gpencil.dissolve", {"type": 'X', "value": 'PRESS', "ctrl": True}, None), ("gpencil.dissolve", {"type": 'DEL', "value": 'PRESS', "ctrl": True}, None), ("gpencil.active_frames_delete_all", {"type": 'X', "value": 'PRESS', "shift": True}, None), ("gpencil.active_frames_delete_all", {"type": 'DEL', "value": 'PRESS', "shift": True}, None), # Context menu op_menu("VIEW3D_MT_gpencil_edit_context_menu", params.context_menu_event), # Separate op_menu("GPENCIL_MT_separate", {"type": 'P', "value": 'PRESS'}), # Split and joint strokes ("gpencil.stroke_split", {"type": 'V', "value": 'PRESS'}, None), ("gpencil.stroke_join", {"type": 'J', "value": 'PRESS', "ctrl": True}, None), ("gpencil.stroke_join", {"type": 'J', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'JOINCOPY')]}), # Copy + paset ("gpencil.copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("gpencil.paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), # Snap op_menu("GPENCIL_MT_snap", {"type": 'S', "value": 'PRESS', "shift": True}), # Show/hide ("gpencil.reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("gpencil.hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("gpencil.hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("gpencil.selection_opacity_toggle", {"type": 'H', "value": 'PRESS', "ctrl": True}, None), # Display *_grease_pencil_display(), # Isolate layer ("gpencil.layer_isolate", {"type": 'NUMPAD_ASTERIX', "value": 'PRESS'}, None), # Move to layer ("gpencil.move_to_layer", {"type": 'M', "value": 'PRESS'}, None), # Transform tools ("transform.translate", {"type": 'G', "value": 'PRESS'}, None), ("transform.translate", {"type": params.select_tweak, "value": 'ANY'}, None), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ("transform.mirror", {"type": 'M', "value": 'PRESS', "ctrl": True}, None), ("transform.bend", {"type": 'W', "value": 'PRESS', "shift": True}, None), ("transform.tosphere", {"type": 'S', "value": 'PRESS', "shift": True, "alt": True}, None), ("transform.shear", {"type": 'S', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("transform.transform", {"type": 'S', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'GPENCIL_SHRINKFATTEN')]}), ("transform.transform", {"type": 'F', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'GPENCIL_OPACITY')]}), # Proportonal editing *_template_items_proportional_editing(connected=True), # Add menu ("object.gpencil_add", {"type": 'A', "value": 'PRESS', "shift": True}, None), # Vertex group menu op_menu("GPENCIL_MT_gpencil_vertex_group", {"type": 'G', "value": 'PRESS', "ctrl": True}), # Select mode ("gpencil.selectmode_toggle", {"type": 'ONE', "value": 'PRESS'}, {"properties": [("mode", 0)]}), ("gpencil.selectmode_toggle", {"type": 'TWO', "value": 'PRESS'}, {"properties": [("mode", 1)]}), ("gpencil.selectmode_toggle", {"type": 'THREE', "value": 'PRESS'}, {"properties": [("mode", 2)]}), ]) if params.legacy: items.extend([ # Convert to geometry ("gpencil.convert", {"type": 'C', "value": 'PRESS', "alt": True}, None), ]) return keymap def km_grease_pencil_stroke_paint_mode(params): items = [] keymap = ( "Grease Pencil Stroke Paint Mode", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Brush strength ("wm.radial_control", {"type": 'F', "value": 'PRESS', "shift": True}, {"properties": [("data_path_primary", 'tool_settings.gpencil_paint.brush.gpencil_settings.pen_strength')]}), # Brush size ("wm.radial_control", {"type": 'F', "value": 'PRESS'}, {"properties": [("data_path_primary", 'tool_settings.gpencil_paint.brush.size')]}), # Draw context menu op_panel("VIEW3D_PT_gpencil_draw_context_menu", params.context_menu_event), # Draw delete menu op_menu("GPENCIL_MT_gpencil_draw_delete", {"type": 'X', "value": 'PRESS'}), ]) return keymap def km_grease_pencil_stroke_paint_draw_brush(params): items = [] keymap = ( "Grease Pencil Stroke Paint (Draw brush)", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Draw ("gpencil.draw", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("mode", 'DRAW'), ("wait_for_input", False)]}), ("gpencil.draw", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'DRAW'), ("wait_for_input", False)]}), # Draw - straight lines ("gpencil.draw", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'DRAW_STRAIGHT'), ("wait_for_input", False)]}), # Draw - poly lines ("gpencil.draw", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("mode", 'DRAW_POLY'), ("wait_for_input", False)]}), # Erase ("gpencil.draw", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), # Constrain Guides Speedlines # Freehand ("gpencil.draw", {"type": 'O', "value": 'PRESS'}, None), ("gpencil.draw", {"type": 'J', "value": 'PRESS'}, None), ("gpencil.draw", {"type": 'J', "value": 'PRESS', "alt": True}, None), ("gpencil.draw", {"type": 'J', "value": 'PRESS', "shift": True}, None), ("gpencil.draw", {"type": 'K', "value": 'PRESS'}, None), ("gpencil.draw", {"type": 'K', "value": 'PRESS', "alt": True}, None), ("gpencil.draw", {"type": 'K', "value": 'PRESS', "shift": True}, None), ("gpencil.draw", {"type": 'L', "value": 'PRESS'}, None), ("gpencil.draw", {"type": 'L', "value": 'PRESS', "alt": True}, None), ("gpencil.draw", {"type": 'L', "value": 'PRESS', "ctrl": True}, None), ("gpencil.draw", {"type": 'V', "value": 'PRESS'}, None), # Mirror or flip ("gpencil.draw", {"type": 'M', "value": 'PRESS'}, None), # Mode ("gpencil.draw", {"type": 'C', "value": 'PRESS'}, None), # Set reference point ("gpencil.draw", {"type": 'C', "value": 'PRESS', "alt": True}, None), # Tablet Mappings for Drawing ------------------ */ # For now, only support direct drawing using the eraser, as most users using a tablet # may still want to use that as their primary pointing device! ("gpencil.draw", {"type": 'ERASER', "value": 'PRESS'}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), # Selected (used by eraser) # Box select ("gpencil.select_box", {"type": 'B', "value": 'PRESS'}, None), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]) return keymap def km_grease_pencil_stroke_paint_erase(params): items = [] keymap = ( "Grease Pencil Stroke Paint (Erase)", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Erase ("gpencil.draw", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), ("gpencil.draw", {"type": 'ERASER', "value": 'PRESS'}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), # Box select (used by eraser) ("gpencil.select_box", {"type": 'B', "value": 'PRESS'}, None), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]) return keymap def km_grease_pencil_stroke_paint_fill(_params): items = [] keymap = ( "Grease Pencil Stroke Paint (Fill)", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Fill ("gpencil.fill", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("on_back", False)]}), ("gpencil.fill", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("on_back", True)]}), # If press alternate key, the brush now it's for drawing areas ("gpencil.draw", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'DRAW'), ("wait_for_input", False), ("disable_straight", True)]}), # If press alternative key, the brush now it's for drawing lines ("gpencil.draw", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'DRAW'), ("wait_for_input", False), ("disable_straight", True), ("disable_fill", True)]}), # Lasso select ("gpencil.select_lasso", {"type": _params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]) return keymap def km_grease_pencil_stroke_sculpt_mode(params): items = [] keymap = ( "Grease Pencil Stroke Sculpt Mode", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items} ) items.extend([ # Selection *_grease_pencil_selection(params), # Painting ("gpencil.sculpt_paint", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("wait_for_input", False)]}), ("gpencil.sculpt_paint", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("wait_for_input", False)]}), ("gpencil.sculpt_paint", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("wait_for_input", False)]}), # Brush strength ("wm.radial_control", {"type": 'F', "value": 'PRESS', "shift": True}, {"properties": [("data_path_primary", 'tool_settings.gpencil_sculpt.brush.strength')]}), # Brush size ("wm.radial_control", {"type": 'F', "value": 'PRESS'}, {"properties": [("data_path_primary", 'tool_settings.gpencil_sculpt.brush.size')]}), # Context menu op_panel("VIEW3D_PT_gpencil_sculpt_context_menu", params.context_menu_event), # Copy ("gpencil.copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), # Display *_grease_pencil_display(), ]) return keymap def km_grease_pencil_stroke_weight_mode(params): items = [] keymap = ( "Grease Pencil Stroke Weight Mode", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Selection *_grease_pencil_selection(params), # Painting ("gpencil.sculpt_paint", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("wait_for_input", False)]}), ("gpencil.sculpt_paint", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("wait_for_input", False)]}), # Brush strength ("wm.radial_control", {"type": 'F', "value": 'PRESS', "shift": True}, {"properties": [("data_path_primary", 'tool_settings.gpencil_sculpt.weight_brush.strength')]}), # Brush sze ("wm.radial_control", {"type": 'F', "value": 'PRESS'}, {"properties": [("data_path_primary", 'tool_settings.gpencil_sculpt.weight_brush.size')]}), # Display *_grease_pencil_display(), ]) return keymap def km_face_mask(params): items = [] keymap = ( "Face Mask", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_items_select_actions(params, "paint.face_select_all"), ("paint.face_select_hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("paint.face_select_hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("paint.face_select_reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("paint.face_select_linked", {"type": 'L', "value": 'PRESS', "ctrl": True}, None), ("paint.face_select_linked_pick", {"type": 'L', "value": 'PRESS'}, {"properties": [("deselect", False)]}), ("paint.face_select_linked_pick", {"type": 'L', "value": 'PRESS', "shift": True}, {"properties": [("deselect", True)]}), ]) return keymap def km_weight_paint_vertex_selection(params): items = [] keymap = ( "Weight Paint Vertex Selection", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_items_select_actions(params, "paint.vert_select_all"), ("view3d.select_box", {"type": 'B', "value": 'PRESS'}, None), ("view3d.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True}, {"properties": [("mode", 'ADD')]}), ("view3d.select_lasso", {"type": params.action_tweak, "value": 'ANY', "shift": True, "ctrl": True}, {"properties": [("mode", 'SUB')]}), ("view3d.select_circle", {"type": 'C', "value": 'PRESS'}, None), ]) return keymap def km_pose(params): items = [] keymap = ( "Pose", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("object.parent_set", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), op_menu("VIEW3D_MT_add", {"type": 'A', "value": 'PRESS', "shift": True}), ("pose.hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("pose.hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("pose.reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), op_menu("VIEW3D_MT_pose_apply", {"type": 'A', "value": 'PRESS', "ctrl": True}), ("pose.rot_clear", {"type": 'R', "value": 'PRESS', "alt": True}, None), ("pose.loc_clear", {"type": 'G', "value": 'PRESS', "alt": True}, None), ("pose.scale_clear", {"type": 'S', "value": 'PRESS', "alt": True}, None), ("pose.quaternions_flip", {"type": 'F', "value": 'PRESS', "alt": True}, None), ("pose.rotation_mode_set", {"type": 'R', "value": 'PRESS', "ctrl": True}, None), ("pose.copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("pose.paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, {"properties": [("flipped", False)]}), ("pose.paste", {"type": 'V', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("flipped", True)]}), *_template_items_select_actions(params, "pose.select_all"), ("pose.select_parent", {"type": 'P', "value": 'PRESS', "shift": True}, None), ("pose.select_hierarchy", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("direction", 'PARENT'), ("extend", False)]}), ("pose.select_hierarchy", {"type": 'LEFT_BRACKET', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'PARENT'), ("extend", True)]}), ("pose.select_hierarchy", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("direction", 'CHILD'), ("extend", False)]}), ("pose.select_hierarchy", {"type": 'RIGHT_BRACKET', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'CHILD'), ("extend", True)]}), ("pose.select_linked", {"type": 'L', "value": 'PRESS'}, None), ("pose.select_grouped", {"type": 'G', "value": 'PRESS', "shift": True}, None), ("pose.select_mirror", {"type": 'M', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("pose.constraint_add_with_targets", {"type": 'C', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("pose.constraints_clear", {"type": 'C', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("pose.ik_add", {"type": 'I', "value": 'PRESS', "shift": True}, None), ("pose.ik_clear", {"type": 'I', "value": 'PRESS', "ctrl": True, "alt": True}, None), op_menu("VIEW3D_MT_pose_group", {"type": 'G', "value": 'PRESS', "ctrl": True}), op_menu("VIEW3D_MT_bone_options_toggle", {"type": 'W', "value": 'PRESS', "shift": True}), op_menu("VIEW3D_MT_bone_options_enable", {"type": 'W', "value": 'PRESS', "shift": True, "ctrl": True}), op_menu("VIEW3D_MT_bone_options_disable", {"type": 'W', "value": 'PRESS', "alt": True}), ("armature.layers_show_all", {"type": 'ACCENT_GRAVE', "value": 'PRESS', "ctrl": True}, None), ("armature.armature_layers", {"type": 'M', "value": 'PRESS', "shift": True}, None), ("pose.bone_layers", {"type": 'M', "value": 'PRESS'}, None), ("transform.transform", {"type": 'S', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("mode", 'BONE_SIZE')]}), ("anim.keyframe_insert_menu", {"type": 'I', "value": 'PRESS'}, None), ("anim.keyframe_delete_v3d", {"type": 'I', "value": 'PRESS', "alt": True}, None), ("anim.keying_set_active_set", {"type": 'I', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("poselib.browse_interactive", {"type": 'L', "value": 'PRESS', "ctrl": True}, None), ("poselib.pose_add", {"type": 'L', "value": 'PRESS', "shift": True}, None), ("poselib.pose_remove", {"type": 'L', "value": 'PRESS', "alt": True}, None), ("poselib.pose_rename", {"type": 'L', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("pose.push", {"type": 'E', "value": 'PRESS', "ctrl": True}, None), ("pose.relax", {"type": 'E', "value": 'PRESS', "alt": True}, None), ("pose.breakdown", {"type": 'E', "value": 'PRESS', "shift": True}, None), op_menu("VIEW3D_MT_pose_context_menu", params.context_menu_event), op_menu("VIEW3D_MT_pose_propagate", {"type": 'P', "value": 'PRESS', "alt": True}), *( (("object.hide_collection", {"type": NUMBERS_1[i], "value": 'PRESS', "any": True}, {"properties": [("collection_index", i + 1)]}) for i in range(10) ) ), ]) return keymap def km_object_mode(params): items = [] keymap = ( "Object Mode", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ op_menu_pie("VIEW3D_MT_proportional_editing_falloff_pie", {"type": 'O', "value": 'PRESS', "shift": True}), ("wm.context_toggle", {"type": 'O', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.use_proportional_edit_objects')]}), *_template_items_select_actions(params, "object.select_all"), ("object.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("object.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("object.select_linked", {"type": 'L', "value": 'PRESS', "shift": True}, None), ("object.select_grouped", {"type": 'G', "value": 'PRESS', "shift": True}, None), ("object.select_hierarchy", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("direction", 'PARENT'), ("extend", False)]}), ("object.select_hierarchy", {"type": 'LEFT_BRACKET', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'PARENT'), ("extend", True)]}), ("object.select_hierarchy", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("direction", 'CHILD'), ("extend", False)]}), ("object.select_hierarchy", {"type": 'RIGHT_BRACKET', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'CHILD'), ("extend", True)]}), ("object.parent_set", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), ("object.parent_clear", {"type": 'P', "value": 'PRESS', "alt": True}, None), ("object.location_clear", {"type": 'G', "value": 'PRESS', "alt": True}, {"properties": [("clear_delta", False)]}), ("object.rotation_clear", {"type": 'R', "value": 'PRESS', "alt": True}, {"properties": [("clear_delta", False)]}), ("object.scale_clear", {"type": 'S', "value": 'PRESS', "alt": True}, {"properties": [("clear_delta", False)]}), ("object.delete", {"type": 'X', "value": 'PRESS'}, {"properties": [("use_global", False)]}), ("object.delete", {"type": 'X', "value": 'PRESS', "shift": True}, {"properties": [("use_global", True)]}), ("object.delete", {"type": 'DEL', "value": 'PRESS'}, {"properties": [("use_global", False), ("confirm", False)]}), ("object.delete", {"type": 'DEL', "value": 'PRESS', "shift": True}, {"properties": [("use_global", True), ("confirm", False)]}), op_menu("VIEW3D_MT_add", {"type": 'A', "value": 'PRESS', "shift": True}), op_menu("VIEW3D_MT_object_apply", {"type": 'A', "value": 'PRESS', "ctrl": True}), op_menu("VIEW3D_MT_make_links", {"type": 'L', "value": 'PRESS', "ctrl": True}), ("object.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), ("object.duplicate_move_linked", {"type": 'D', "value": 'PRESS', "alt": True}, None), ("object.join", {"type": 'J', "value": 'PRESS', "ctrl": True}, None), ("anim.keyframe_insert_menu", {"type": 'I', "value": 'PRESS'}, None), ("anim.keyframe_delete_v3d", {"type": 'I', "value": 'PRESS', "alt": True}, None), ("anim.keying_set_active_set", {"type": 'I', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("collection.create", {"type": 'G', "value": 'PRESS', "ctrl": True}, None), ("collection.objects_remove", {"type": 'G', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("collection.objects_remove_all", {"type": 'G', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("collection.objects_add_active", {"type": 'G', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("collection.objects_remove_active", {"type": 'G', "value": 'PRESS', "shift": True, "alt": True}, None), op_menu("VIEW3D_MT_object_context_menu", params.context_menu_event), *_template_items_object_subdivision_set(), ("object.move_to_collection", {"type": 'M', "value": 'PRESS'}, None), ("object.link_to_collection", {"type": 'M', "value": 'PRESS', "shift": True}, None), ("object.hide_view_clear", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("object.hide_view_set", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("object.hide_view_set", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("object.hide_collection", {"type": 'H', "value": 'PRESS', "ctrl": True}, None), *( (("object.hide_collection", {"type": NUMBERS_1[i], "value": 'PRESS', "any": True}, {"properties": [("collection_index", i + 1)]}) for i in range(10) ) ), ]) if params.legacy: items.extend([ ("object.select_mirror", {"type": 'M', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("object.parent_no_inverse_set", {"type": 'P', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("object.track_set", {"type": 'T', "value": 'PRESS', "ctrl": True}, None), ("object.track_clear", {"type": 'T', "value": 'PRESS', "alt": True}, None), ("object.constraint_add_with_targets", {"type": 'C', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("object.constraints_clear", {"type": 'C', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("object.origin_clear", {"type": 'O', "value": 'PRESS', "alt": True}, None), ("object.duplicates_make_real", {"type": 'A', "value": 'PRESS', "shift": True, "ctrl": True}, None), op_menu("VIEW3D_MT_make_single_user", {"type": 'U', "value": 'PRESS'}), ("object.convert", {"type": 'C', "value": 'PRESS', "alt": True}, None), ("object.proxy_make", {"type": 'P', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("object.make_local", {"type": 'L', "value": 'PRESS'}, None), ("object.data_transfer", {"type": 'T', "value": 'PRESS', "shift": True, "ctrl": True}, None), ]) return keymap def km_paint_curve(params): items = [] keymap = ( "Paint Curve", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("paintcurve.add_point_slide", {"type": params.action_mouse, "value": 'PRESS', "ctrl": True}, None), ("paintcurve.select", {"type": params.select_mouse, "value": params.select_mouse_value}, None), ("paintcurve.select", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True}, {"properties": [("extend", True)]}), ("paintcurve.slide", {"type": params.action_mouse, "value": 'PRESS'}, None), ("paintcurve.slide", {"type": params.action_mouse, "value": 'PRESS', "shift": True}, {"properties": [("align", True)]}), ("paintcurve.select", {"type": 'A', "value": 'PRESS'}, {"properties": [("toggle", True)]}), ("paintcurve.cursor", {"type": params.action_mouse, "value": 'PRESS'}, None), ("paintcurve.delete_point", {"type": 'X', "value": 'PRESS'}, None), ("paintcurve.delete_point", {"type": 'DEL', "value": 'PRESS'}, None), ("paintcurve.draw", {"type": 'RET', "value": 'PRESS'}, None), ("paintcurve.draw", {"type": 'NUMPAD_ENTER', "value": 'PRESS'}, None), ("transform.translate", {"type": 'G', "value": 'PRESS'}, None), ("transform.translate", {"type": params.select_tweak, "value": 'ANY'}, None), ("transform.rotate", {"type": 'R', "value": 'PRESS'}, None), ("transform.resize", {"type": 'S', "value": 'PRESS'}, None), ]) return keymap def km_curve(params): items = [] keymap = ( "Curve", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ op_menu("VIEW3D_MT_curve_add", {"type": 'A', "value": 'PRESS', "shift": True}), ("curve.handle_type_set", {"type": 'V', "value": 'PRESS'}, None), ("curve.vertex_add", {"type": params.action_mouse, "value": 'CLICK', "ctrl": True}, None), *_template_items_select_actions(params, "curve.select_all"), ("curve.select_row", {"type": 'R', "value": 'PRESS', "shift": True}, None), ("curve.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("curve.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("curve.select_linked", {"type": 'L', "value": 'PRESS', "ctrl": True}, None), ("curve.select_similar", {"type": 'G', "value": 'PRESS', "shift": True}, None), ("curve.select_linked_pick", {"type": 'L', "value": 'PRESS'}, {"properties": [("deselect", False)]}), ("curve.select_linked_pick", {"type": 'L', "value": 'PRESS', "shift": True}, {"properties": [("deselect", True)]}), ("curve.shortest_path_pick", {"type": params.select_mouse, "value": 'CLICK', "ctrl": True}, None), ("curve.separate", {"type": 'P', "value": 'PRESS'}, None), ("curve.split", {"type": 'Y', "value": 'PRESS'}, None), ("curve.extrude_move", {"type": 'E', "value": 'PRESS'}, None), ("curve.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), ("curve.make_segment", {"type": 'F', "value": 'PRESS'}, None), ("curve.cyclic_toggle", {"type": 'C', "value": 'PRESS', "alt": True}, None), op_menu("VIEW3D_MT_edit_curve_delete", {"type": 'X', "value": 'PRESS'}), op_menu("VIEW3D_MT_edit_curve_delete", {"type": 'DEL', "value": 'PRESS'}), ("curve.dissolve_verts", {"type": 'X', "value": 'PRESS', "ctrl": True}, None), ("curve.dissolve_verts", {"type": 'DEL', "value": 'PRESS', "ctrl": True}, None), ("curve.tilt_clear", {"type": 'T', "value": 'PRESS', "alt": True}, None), ("transform.tilt", {"type": 'T', "value": 'PRESS', "ctrl": True}, None), ("transform.transform", {"type": 'S', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'CURVE_SHRINKFATTEN')]}), ("curve.reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("curve.hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("curve.hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("curve.normals_make_consistent", {"type": 'N', "value": 'PRESS', "ctrl" if params.legacy else "shift": True}, None), ("object.vertex_parent_set", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), op_menu("VIEW3D_MT_edit_curve_context_menu", params.context_menu_event), op_menu("VIEW3D_MT_hook", {"type": 'H', "value": 'PRESS', "ctrl": True}), *_template_items_proportional_editing(connected=True), ]) return keymap # Radial control setup helpers, this operator has a lot of properties. def radial_control_properties(paint, prop, secondary_prop, secondary_rotation=False, color=False, zoom=False): brush_path = 'tool_settings.' + paint + '.brush' unified_path = 'tool_settings.unified_paint_settings' rotation = 'mask_texture_slot.angle' if secondary_rotation else 'texture_slot.angle' return { "properties": [ ("data_path_primary", brush_path + '.' + prop), ("data_path_secondary", unified_path + '.' + prop if secondary_prop else ''), ("use_secondary", unified_path + '.' + secondary_prop if secondary_prop else ''), ("rotation_path", brush_path + '.' + rotation), ("color_path", brush_path + '.cursor_color_add'), ("fill_color_path", brush_path + '.color' if color else ''), ("fill_color_override_path", unified_path + '.color' if color else ''), ("fill_color_override_test_path", unified_path + '.use_unified_color' if color else ''), ("zoom_path", 'space_data.zoom' if zoom else ''), ("image_id", brush_path + ''), ("secondary_tex", secondary_rotation), ], } # Radial controls for the paint and sculpt modes. def _template_paint_radial_control(paint, rotation=False, secondary_rotation=False, color=False, zoom=False): items = [] items.extend([ ("wm.radial_control", {"type": 'F', "value": 'PRESS'}, radial_control_properties(paint, 'size', 'use_unified_size', secondary_rotation=secondary_rotation, color=color, zoom=zoom)), ("wm.radial_control", {"type": 'F', "value": 'PRESS', "shift": True}, radial_control_properties(paint, 'strength', 'use_unified_strength', secondary_rotation=secondary_rotation, color=color)), ]) if rotation: items.extend([ ("wm.radial_control", {"type": 'F', "value": 'PRESS', "ctrl": True}, radial_control_properties(paint, 'texture_slot.angle', None, color=color)), ]) if secondary_rotation: items.extend([ ("wm.radial_control", {"type": 'F', "value": 'PRESS', "ctrl": True, "alt": True}, radial_control_properties(paint, 'mask_texture_slot.angle', None, secondary_rotation=secondary_rotation, color=color)), ]) return items def km_image_paint(params): items = [] keymap = ( "Image Paint", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("paint.image_paint", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("mode", 'NORMAL')]}), ("paint.image_paint", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'INVERT')]}), ("paint.brush_colors_flip", {"type": 'X', "value": 'PRESS'}, None), ("paint.grab_clone", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, None), ("paint.sample_color", {"type": 'S', "value": 'PRESS'}, None), ("brush.scale_size", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 0.9)]}), ("brush.scale_size", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 1.0 / 0.9)]}), *_template_paint_radial_control("image_paint", color=True, zoom=True, rotation=True, secondary_rotation=True), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, {"properties": [("mode", 'TRANSLATION')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'SCALE')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'ROTATION')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'TRANSLATION'), ("texmode", 'SECONDARY')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("mode", 'SCALE'), ("texmode", 'SECONDARY')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("mode", 'ROTATION'), ("texmode", 'SECONDARY')]}), ("wm.context_toggle", {"type": 'M', "value": 'PRESS'}, {"properties": [("data_path", 'image_paint_object.data.use_paint_mask')]}), ("wm.context_toggle", {"type": 'S', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'tool_settings.image_paint.brush.use_smooth_stroke')]}), op_menu("VIEW3D_MT_angle_control", {"type": 'R', "value": 'PRESS'}), ("wm.context_menu_enum", {"type": 'E', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.image_paint.brush.stroke_method')]}), op_panel("VIEW3D_PT_paint_texture_context_menu", params.context_menu_event), ]) return keymap def km_vertex_paint(params): items = [] keymap = ( "Vertex Paint", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("paint.vertex_paint", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("paint.brush_colors_flip", {"type": 'X', "value": 'PRESS'}, None), ("paint.sample_color", {"type": 'S', "value": 'PRESS'}, None), ("paint.vertex_color_set", {"type": 'K', "value": 'PRESS', "shift": True}, None), ("brush.scale_size", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 0.9)]}), ("brush.scale_size", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 1.0 / 0.9)]}), *_template_paint_radial_control("vertex_paint", color=True, rotation=True), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, {"properties": [("mode", 'TRANSLATION')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'SCALE')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'ROTATION')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'TRANSLATION'), ("texmode", 'SECONDARY')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("mode", 'SCALE'), ("texmode", 'SECONDARY')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("mode", 'ROTATION'), ("texmode", 'SECONDARY')]}), ("wm.context_toggle", {"type": 'M', "value": 'PRESS'}, {"properties": [("data_path", 'vertex_paint_object.data.use_paint_mask')]}), ("wm.context_toggle", {"type": 'S', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'tool_settings.vertex_paint.brush.use_smooth_stroke')]}), op_menu("VIEW3D_MT_angle_control", {"type": 'R', "value": 'PRESS'}), ("wm.context_menu_enum", {"type": 'E', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.vertex_paint.brush.stroke_method')]}), op_panel("VIEW3D_PT_paint_vertex_context_menu", params.context_menu_event), ]) return keymap def km_weight_paint(params): items = [] keymap = ( "Weight Paint", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("paint.weight_paint", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("paint.weight_sample", {"type": params.action_mouse, "value": 'PRESS', "ctrl": True}, None), ("paint.weight_sample_group", {"type": params.action_mouse, "value": 'PRESS', "shift": True}, None), ("paint.weight_gradient", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("type", 'LINEAR')]}), ("paint.weight_gradient", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("type", 'RADIAL')]}), ("paint.weight_set", {"type": 'K', "value": 'PRESS', "shift": True}, None), ("brush.scale_size", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 0.9)]}), ("brush.scale_size", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 1.0 / 0.9)]}), *_template_paint_radial_control("weight_paint"), ("wm.radial_control", {"type": 'F', "value": 'PRESS', "ctrl": True}, radial_control_properties("weight_paint", 'weight', 'use_unified_weight')), ("wm.context_menu_enum", {"type": 'E', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.vertex_paint.brush.stroke_method')]}), ("wm.context_toggle", {"type": 'M', "value": 'PRESS'}, {"properties": [("data_path", 'weight_paint_object.data.use_paint_mask')]}), ("wm.context_toggle", {"type": 'V', "value": 'PRESS'}, {"properties": [("data_path", 'weight_paint_object.data.use_paint_mask_vertex')]}), ("wm.context_toggle", {"type": 'S', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'tool_settings.weight_paint.brush.use_smooth_stroke')]}), op_panel("VIEW3D_PT_paint_weight_context_menu", params.context_menu_event), ]) if params.select_mouse == 'LEFTMOUSE': # Bone selection for combined weight paint + pose mode. items.extend([ ("view3d.select", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, None), ]) return keymap def km_sculpt(params): items = [] keymap = ( "Sculpt", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Brush strokes ("sculpt.brush_stroke", {"type": 'LEFTMOUSE', "value": 'PRESS'}, {"properties": [("mode", 'NORMAL')]}), ("sculpt.brush_stroke", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'INVERT')]}), ("sculpt.brush_stroke", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'SMOOTH')]}), # Partial Visibility Show/hide ("paint.hide_show", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("action", 'SHOW'), ("area", 'INSIDE')]}), ("paint.hide_show", {"type": 'H', "value": 'PRESS'}, {"properties": [("action", 'HIDE'), ("area", 'INSIDE')]}), ("paint.hide_show", {"type": 'H', "value": 'PRESS', "alt": True}, {"properties": [("action", 'SHOW'), ("area", 'ALL')]}), # Subdivision levels *_template_items_object_subdivision_set(), ("object.subdivision_set", {"type": 'PAGE_UP', "value": 'PRESS'}, {"properties": [("level", 1), ("relative", True)]}), ("object.subdivision_set", {"type": 'PAGE_DOWN', "value": 'PRESS'}, {"properties": [("level", -1), ("relative", True)]}), # Mask ("paint.mask_flood_fill", {"type": 'M', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'VALUE'), ("value", 0.0)]}), ("paint.mask_flood_fill", {"type": 'I', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'INVERT')]}), ("paint.mask_lasso_gesture", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("wm.context_toggle", {"type": 'M', "value": 'PRESS', "ctrl": True}, {"properties": [("data_path", 'scene.tool_settings.sculpt.show_mask')]}), # Dynamic topology ("sculpt.dynamic_topology_toggle", {"type": 'D', "value": 'PRESS', "ctrl": True}, None), ("sculpt.set_detail_size", {"type": 'D', "value": 'PRESS', "shift": True}, None), # Brush properties ("brush.scale_size", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 0.9)]}), ("brush.scale_size", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 1.0 / 0.9)]}), *_template_paint_radial_control("sculpt", rotation=True), # Stencil ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, {"properties": [("mode", 'TRANSLATION')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("mode", 'SCALE')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'ROTATION')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'TRANSLATION'), ("texmode", 'SECONDARY')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "shift": True, "alt": True}, {"properties": [("mode", 'SCALE'), ("texmode", 'SECONDARY')]}), ("brush.stencil_control", {"type": 'RIGHTMOUSE', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("mode", 'ROTATION'), ("texmode", 'SECONDARY')]}), # Tools ("paint.brush_select", {"type": 'X', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'DRAW')]}), ("paint.brush_select", {"type": 'S', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'SMOOTH')]}), ("paint.brush_select", {"type": 'P', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'PINCH')]}), ("paint.brush_select", {"type": 'I', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'INFLATE')]}), ("paint.brush_select", {"type": 'G', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'GRAB')]}), ("paint.brush_select", {"type": 'L', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'LAYER')]}), ("paint.brush_select", {"type": 'T', "value": 'PRESS', "shift": True}, {"properties": [("sculpt_tool", 'FLATTEN')]}), ("paint.brush_select", {"type": 'C', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'CLAY')]}), ("paint.brush_select", {"type": 'C', "value": 'PRESS', "shift": True}, {"properties": [("sculpt_tool", 'CREASE')]}), ("paint.brush_select", {"type": 'K', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'SNAKE_HOOK')]}), ("paint.brush_select", {"type": 'M', "value": 'PRESS'}, {"properties": [("sculpt_tool", 'MASK'), ("toggle", True), ("create_missing", True)]}), # Menus ("wm.context_menu_enum", {"type": 'E', "value": 'PRESS'}, {"properties": [("data_path", 'tool_settings.sculpt.brush.stroke_method')]}), ("wm.context_toggle", {"type": 'S', "value": 'PRESS', "shift": True}, {"properties": [("data_path", 'tool_settings.sculpt.brush.use_smooth_stroke')]}), op_menu("VIEW3D_MT_angle_control", {"type": 'R', "value": 'PRESS'}), op_panel("VIEW3D_PT_sculpt_context_menu", params.context_menu_event), ]) return keymap # Mesh edit mode. def km_mesh(params): items = [] keymap = ( "Mesh", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Tools. ("mesh.loopcut_slide", {"type": 'R', "value": 'PRESS', "ctrl": True}, {"properties": [("TRANSFORM_OT_edge_slide", [("release_confirm", False), ],)]}), ("mesh.offset_edge_loops_slide", {"type": 'R', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("TRANSFORM_OT_edge_slide", [("release_confirm", False), ],)]}), ("mesh.inset", {"type": 'I', "value": 'PRESS'}, None), ("mesh.bevel", {"type": 'B', "value": 'PRESS', "ctrl": True}, {"properties": [("vertex_only", False)]}), ("mesh.bevel", {"type": 'B', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("vertex_only", True)]}), # Selection modes. *_template_items_editmode_mesh_select_mode(params), # Loop Select with alt. Double click in case MMB emulation is on (below). ("mesh.loop_select", {"type": params.select_mouse, "value": params.select_mouse_value, "alt": True}, {"properties": [("extend", False), ("deselect", False), ("toggle", False)]}), ("mesh.loop_select", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True, "alt": True}, {"properties": [("extend", False), ("deselect", False), ("toggle", True)]}), # Selection ("mesh.edgering_select", {"type": params.select_mouse, "value": params.select_mouse_value, "ctrl": True, "alt": True}, {"properties": [("extend", False), ("deselect", False), ("toggle", False)]}), ("mesh.edgering_select", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True, "ctrl": True, "alt": True}, {"properties": [("extend", False), ("deselect", False), ("toggle", True)]}), ("mesh.shortest_path_pick", {"type": params.select_mouse, "value": params.select_mouse_value, "ctrl": True}, {"properties": [("use_fill", False)]}), ("mesh.shortest_path_pick", {"type": params.select_mouse, "value": params.select_mouse_value, "shift": True, "ctrl": True}, {"properties": [("use_fill", True)]}), *_template_items_select_actions(params, "mesh.select_all"), ("mesh.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("mesh.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("mesh.select_next_item", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("mesh.select_prev_item", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "shift": True, "ctrl": True}, None), ("mesh.select_linked", {"type": 'L', "value": 'PRESS', "ctrl": True}, None), ("mesh.select_linked_pick", {"type": 'L', "value": 'PRESS'}, {"properties": [("deselect", False)]}), ("mesh.select_linked_pick", {"type": 'L', "value": 'PRESS', "shift": True}, {"properties": [("deselect", True)]}), ("mesh.select_mirror", {"type": 'M', "value": 'PRESS', "shift": True, "ctrl": True}, None), op_menu("VIEW3D_MT_edit_mesh_select_similar", {"type": 'G', "value": 'PRESS', "shift": True}), # Hide/reveal. ("mesh.hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("mesh.hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("mesh.reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), # Tools. ("mesh.normals_make_consistent", {"type": 'N', "value": 'PRESS', "ctrl" if params.legacy else "shift": True}, {"properties": [("inside", False)]}), ("mesh.normals_make_consistent", {"type": 'N', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("inside", True)]}), ("view3d.edit_mesh_extrude_move_normal", {"type": 'E', "value": 'PRESS'}, None), op_menu("VIEW3D_MT_edit_mesh_extrude", {"type": 'E', "value": 'PRESS', "alt": True}), ("transform.edge_crease", {"type": 'E', "value": 'PRESS', "shift": True}, None), ("mesh.fill", {"type": 'F', "value": 'PRESS', "alt": True}, None), ("mesh.quads_convert_to_tris", {"type": 'T', "value": 'PRESS', "ctrl": True}, {"properties": [("quad_method", 'BEAUTY'), ("ngon_method", 'BEAUTY')]}), ("mesh.quads_convert_to_tris", {"type": 'T', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("quad_method", 'FIXED'), ("ngon_method", 'CLIP')]}), ("mesh.tris_convert_to_quads", {"type": 'J', "value": 'PRESS', "alt": True}, None), ("mesh.rip_move", {"type": 'V', "value": 'PRESS'}, {"properties": [("MESH_OT_rip", [("use_fill", False), ],)]}), ("mesh.rip_move", {"type": 'V', "value": 'PRESS', "alt": True}, {"properties": [("MESH_OT_rip", [("use_fill", True), ],)]}), ("mesh.rip_edge_move", {"type": 'D', "value": 'PRESS', "alt": True}, None), op_menu("VIEW3D_MT_edit_mesh_merge", {"type": 'M', "value": 'PRESS', "alt": True}), ("transform.shrink_fatten", {"type": 'S', "value": 'PRESS', "alt": True}, None), ("mesh.edge_face_add", {"type": 'F', "value": 'PRESS'}, None), ("mesh.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), op_menu("VIEW3D_MT_mesh_add", {"type": 'A', "value": 'PRESS', "shift": True}), ("mesh.separate", {"type": 'P', "value": 'PRESS'}, None), ("mesh.split", {"type": 'Y', "value": 'PRESS'}, None), ("mesh.vert_connect_path", {"type": 'J', "value": 'PRESS'}, None), ("mesh.point_normals", {"type": 'L', "value": 'PRESS', "alt": True}, None), ("transform.vert_slide", {"type": 'V', "value": 'PRESS', "shift": True}, None), ("mesh.dupli_extrude_cursor", {"type": params.action_mouse, "value": 'CLICK', "ctrl": True}, {"properties": [("rotate_source", True)]}), ("mesh.dupli_extrude_cursor", {"type": params.action_mouse, "value": 'CLICK', "shift": True, "ctrl": True}, {"properties": [("rotate_source", False)]}), op_menu("VIEW3D_MT_edit_mesh_delete", {"type": 'X', "value": 'PRESS'}), op_menu("VIEW3D_MT_edit_mesh_delete", {"type": 'DEL', "value": 'PRESS'}), ("mesh.dissolve_mode", {"type": 'X', "value": 'PRESS', "ctrl": True}, None), ("mesh.dissolve_mode", {"type": 'DEL', "value": 'PRESS', "ctrl": True}, None), ("mesh.knife_tool", {"type": 'K', "value": 'PRESS'}, {"properties": [("use_occlude_geometry", True), ("only_selected", False)]}), ("object.vertex_parent_set", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), # Menus. op_menu("VIEW3D_MT_edit_mesh_context_menu", params.context_menu_event), op_menu("VIEW3D_MT_edit_mesh_faces", {"type": 'F', "value": 'PRESS', "ctrl": True}), op_menu("VIEW3D_MT_edit_mesh_edges", {"type": 'E', "value": 'PRESS', "ctrl": True}), op_menu("VIEW3D_MT_edit_mesh_vertices", {"type": 'V', "value": 'PRESS', "ctrl": True}), op_menu("VIEW3D_MT_hook", {"type": 'H', "value": 'PRESS', "ctrl": True}), op_menu("VIEW3D_MT_uv_map", {"type": 'U', "value": 'PRESS'}), op_menu("VIEW3D_MT_vertex_group", {"type": 'G', "value": 'PRESS', "ctrl": True}), op_menu("VIEW3D_MT_edit_mesh_normals", {"type": 'N', "value": 'PRESS', "alt" : True}), ("object.vertex_group_remove_from", {"type": 'G', "value": 'PRESS', "ctrl": True, "alt": True}, None), *_template_items_proportional_editing(connected=True), ]) if params.use_mouse_emulate_3_button and params.select_mouse == 'LEFTMOUSE': items.extend([ ("mesh.loop_select", {"type": params.select_mouse, "value": 'DOUBLE_CLICK'}, {"properties": [("extend", False), ("deselect", False), ("toggle", False)]}), ("mesh.loop_select", {"type": params.select_mouse, "value": 'DOUBLE_CLICK', "shift": True}, {"properties": [("extend", True), ("deselect", False), ("toggle", False)]}), ("mesh.loop_select", {"type": params.select_mouse, "value": 'DOUBLE_CLICK', "alt": True}, {"properties": [("extend", False), ("deselect", True), ("toggle", False)]}), ("mesh.edgering_select", {"type": params.select_mouse, "value": 'DOUBLE_CLICK', "ctrl": True}, {"properties": [("extend", False), ("deselect", False), ("toggle", False)]}), ("mesh.edgering_select", {"type": params.select_mouse, "value": 'DOUBLE_CLICK', "shift": True, "ctrl": True}, {"properties": [("extend", False), ("deselect", False), ("toggle", True)]}), ]) if params.legacy: items.extend([ ("mesh.poke", {"type": 'P', "value": 'PRESS', "alt": True}, None), ("mesh.select_non_manifold", {"type": 'M', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("mesh.faces_select_linked_flat", {"type": 'F', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ("mesh.spin", {"type": 'R', "value": 'PRESS', "alt": True}, None), ("mesh.beautify_fill", {"type": 'F', "value": 'PRESS', "shift": True, "alt": True}, None), ("mesh.knife_tool", {"type": 'K', "value": 'PRESS', "shift": True}, {"properties": [("use_occlude_geometry", False), ("only_selected", True)]}), *_template_items_object_subdivision_set(), ]) return keymap # Armature edit mode def km_armature(params): items = [] keymap = ( "Armature", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ # Hide/reveal. ("armature.hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("armature.hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("armature.reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), # Align & roll. ("armature.align", {"type": 'A', "value": 'PRESS', "ctrl": True, "alt": True}, None), ("armature.calculate_roll", {"type": 'N', "value": 'PRESS', "ctrl" if params.legacy else "shift": True}, None), ("armature.roll_clear", {"type": 'R', "value": 'PRESS', "alt": True}, None), ("armature.switch_direction", {"type": 'F', "value": 'PRESS', "alt": True}, None), # Add. ("armature.bone_primitive_add", {"type": 'A', "value": 'PRESS', "shift": True}, None), # Parenting. ("armature.parent_set", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), ("armature.parent_clear", {"type": 'P', "value": 'PRESS', "alt": True}, None), # Selection. *_template_items_select_actions(params, "armature.select_all"), ("armature.select_mirror", {"type": 'M', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("extend", False)]}), ("armature.select_hierarchy", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("direction", 'PARENT'), ("extend", False)]}), ("armature.select_hierarchy", {"type": 'LEFT_BRACKET', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'PARENT'), ("extend", True)]}), ("armature.select_hierarchy", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("direction", 'CHILD'), ("extend", False)]}), ("armature.select_hierarchy", {"type": 'RIGHT_BRACKET', "value": 'PRESS', "shift": True}, {"properties": [("direction", 'CHILD'), ("extend", True)]}), ("armature.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("armature.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("armature.select_similar", {"type": 'G', "value": 'PRESS', "shift": True}, None), ("armature.select_linked", {"type": 'L', "value": 'PRESS'}, {"properties": [("deselect", False)]}), ("armature.select_linked", {"type": 'L', "value": 'PRESS', "shift": True}, {"properties": [("deselect", True)]}), ("armature.shortest_path_pick", {"type": params.select_mouse, "value": params.select_mouse_value, "ctrl": True}, None), # Editing. op_menu("VIEW3D_MT_edit_armature_delete", {"type": 'X', "value": 'PRESS'}), op_menu("VIEW3D_MT_edit_armature_delete", {"type": 'DEL', "value": 'PRESS'}), ("armature.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), ("armature.dissolve", {"type": 'X', "value": 'PRESS', "ctrl": True}, None), ("armature.dissolve", {"type": 'DEL', "value": 'PRESS', "ctrl": True}, None), ("armature.extrude_move", {"type": 'E', "value": 'PRESS'}, None), ("armature.extrude_forked", {"type": 'E', "value": 'PRESS', "shift": True}, None), ("armature.click_extrude", {"type": params.action_mouse, "value": 'CLICK', "ctrl": True}, None), ("armature.fill", {"type": 'F', "value": 'PRESS'}, None), ("armature.merge", {"type": 'M', "value": 'PRESS', "alt": True}, None), ("armature.split", {"type": 'Y', "value": 'PRESS'}, None), ("armature.separate", {"type": 'P', "value": 'PRESS'}, None), # Set flags. op_menu("VIEW3D_MT_bone_options_toggle", {"type": 'W', "value": 'PRESS', "shift": True}), op_menu("VIEW3D_MT_bone_options_enable", {"type": 'W', "value": 'PRESS', "shift": True, "ctrl": True}), op_menu("VIEW3D_MT_bone_options_disable", {"type": 'W', "value": 'PRESS', "alt": True}), # Armature/bone layers. ("armature.layers_show_all", {"type": 'ACCENT_GRAVE', "value": 'PRESS', "ctrl": True}, None), ("armature.armature_layers", {"type": 'M', "value": 'PRESS', "shift": True}, None), ("armature.bone_layers", {"type": 'M', "value": 'PRESS'}, None), # Special transforms. ("transform.transform", {"type": 'S', "value": 'PRESS', "ctrl": True, "alt": True}, {"properties": [("mode", 'BONE_SIZE')]}), ("transform.transform", {"type": 'S', "value": 'PRESS', "alt": True}, {"properties": [("mode", 'BONE_ENVELOPE')]}), ("transform.transform", {"type": 'R', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'BONE_ROLL')]}), # Menus. op_menu("VIEW3D_MT_armature_context_menu", params.context_menu_event), ]) return keymap # Metaball edit mode. def km_metaball(params): items = [] keymap = ( "Metaball", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("object.metaball_add", {"type": 'A', "value": 'PRESS', "shift": True}, None), ("mball.reveal_metaelems", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("mball.hide_metaelems", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("mball.hide_metaelems", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("mball.delete_metaelems", {"type": 'X', "value": 'PRESS'}, None), ("mball.delete_metaelems", {"type": 'DEL', "value": 'PRESS'}, None), ("mball.duplicate_move", {"type": 'D', "value": 'PRESS', "shift": True}, None), *_template_items_select_actions(params, "mball.select_all"), ("mball.select_similar", {"type": 'G', "value": 'PRESS', "shift": True}, None), *_template_items_proportional_editing(connected=True), op_menu("VIEW3D_MT_edit_metaball_context_menu", params.context_menu_event), ]) return keymap # Lattice edit mode. def km_lattice(params): items = [] keymap = ( "Lattice", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_items_select_actions(params, "lattice.select_all"), ("lattice.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("lattice.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("object.vertex_parent_set", {"type": 'P', "value": 'PRESS', "ctrl": True}, None), ("lattice.flip", {"type": 'F', "value": 'PRESS', "alt": True}, None), op_menu("VIEW3D_MT_hook", {"type": 'H', "value": 'PRESS', "ctrl": True}), op_menu("VIEW3D_MT_edit_lattice_context_menu", params.context_menu_event), *_template_items_proportional_editing(connected=False), ]) return keymap # Particle edit mode. def km_particle(params): items = [] keymap = ( "Particle", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ *_template_items_select_actions(params, "particle.select_all"), ("particle.select_more", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "ctrl": True}, None), ("particle.select_less", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "ctrl": True}, None), ("particle.select_linked", {"type": 'L', "value": 'PRESS'}, {"properties": [("deselect", False)]}), ("particle.select_linked", {"type": 'L', "value": 'PRESS', "shift": True}, {"properties": [("deselect", True)]}), ("particle.delete", {"type": 'X', "value": 'PRESS'}, None), ("particle.delete", {"type": 'DEL', "value": 'PRESS'}, None), ("particle.reveal", {"type": 'H', "value": 'PRESS', "alt": True}, None), ("particle.hide", {"type": 'H', "value": 'PRESS'}, {"properties": [("unselected", False)]}), ("particle.hide", {"type": 'H', "value": 'PRESS', "shift": True}, {"properties": [("unselected", True)]}), ("particle.brush_edit", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("particle.brush_edit", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, None), ("wm.radial_control", {"type": 'F', "value": 'PRESS'}, {"properties": [("data_path_primary", 'tool_settings.particle_edit.brush.size')]}), ("wm.radial_control", {"type": 'F', "value": 'PRESS', "shift": True}, {"properties": [("data_path_primary", 'tool_settings.particle_edit.brush.strength')]}), op_menu("VIEW3D_MT_particle_context_menu", params.context_menu_event), ("particle.weight_set", {"type": 'K', "value": 'PRESS', "shift": True}, None), *_template_items_proportional_editing(connected=False), ]) return keymap # Text edit mode. def km_font(params): items = [] keymap = ( "Font", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) items.extend([ ("font.style_toggle", {"type": 'B', "value": 'PRESS', "ctrl": True}, {"properties": [("style", 'BOLD')]}), ("font.style_toggle", {"type": 'I', "value": 'PRESS', "ctrl": True}, {"properties": [("style", 'ITALIC')]}), ("font.style_toggle", {"type": 'U', "value": 'PRESS', "ctrl": True}, {"properties": [("style", 'UNDERLINE')]}), ("font.style_toggle", {"type": 'P', "value": 'PRESS', "ctrl": True}, {"properties": [("style", 'SMALL_CAPS')]}), ("font.delete", {"type": 'DEL', "value": 'PRESS'}, {"properties": [("type", 'NEXT_OR_SELECTION')]}), ("font.delete", {"type": 'DEL', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'NEXT_WORD')]}), ("font.delete", {"type": 'BACK_SPACE', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_OR_SELECTION')]}), ("font.delete", {"type": 'BACK_SPACE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_OR_SELECTION')]}), ("font.delete", {"type": 'BACK_SPACE', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("font.move", {"type": 'HOME', "value": 'PRESS'}, {"properties": [("type", 'LINE_BEGIN')]}), ("font.move", {"type": 'END', "value": 'PRESS'}, {"properties": [("type", 'LINE_END')]}), ("font.move", {"type": 'LEFT_ARROW', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("font.move", {"type": 'RIGHT_ARROW', "value": 'PRESS'}, {"properties": [("type", 'NEXT_CHARACTER')]}), ("font.move", {"type": 'LEFT_ARROW', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("font.move", {"type": 'RIGHT_ARROW', "value": 'PRESS', "ctrl": True}, {"properties": [("type", 'NEXT_WORD')]}), ("font.move", {"type": 'UP_ARROW', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_LINE')]}), ("font.move", {"type": 'DOWN_ARROW', "value": 'PRESS'}, {"properties": [("type", 'NEXT_LINE')]}), ("font.move", {"type": 'PAGE_UP', "value": 'PRESS'}, {"properties": [("type", 'PREVIOUS_PAGE')]}), ("font.move", {"type": 'PAGE_DOWN', "value": 'PRESS'}, {"properties": [("type", 'NEXT_PAGE')]}), ("font.move_select", {"type": 'HOME', "value": 'PRESS', "shift": True}, {"properties": [("type", 'LINE_BEGIN')]}), ("font.move_select", {"type": 'END', "value": 'PRESS', "shift": True}, {"properties": [("type", 'LINE_END')]}), ("font.move_select", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_CHARACTER')]}), ("font.move_select", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("type", 'NEXT_CHARACTER')]}), ("font.move_select", {"type": 'LEFT_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'PREVIOUS_WORD')]}), ("font.move_select", {"type": 'RIGHT_ARROW', "value": 'PRESS', "shift": True, "ctrl": True}, {"properties": [("type", 'NEXT_WORD')]}), ("font.move_select", {"type": 'UP_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_LINE')]}), ("font.move_select", {"type": 'DOWN_ARROW', "value": 'PRESS', "shift": True}, {"properties": [("type", 'NEXT_LINE')]}), ("font.move_select", {"type": 'PAGE_UP', "value": 'PRESS', "shift": True}, {"properties": [("type", 'PREVIOUS_PAGE')]}), ("font.move_select", {"type": 'PAGE_DOWN', "value": 'PRESS', "shift": True}, {"properties": [("type", 'NEXT_PAGE')]}), ("font.change_spacing", {"type": 'LEFT_ARROW', "value": 'PRESS', "alt": True}, {"properties": [("delta", -1)]}), ("font.change_spacing", {"type": 'RIGHT_ARROW', "value": 'PRESS', "alt": True}, {"properties": [("delta", 1)]}), ("font.change_character", {"type": 'UP_ARROW', "value": 'PRESS', "alt": True}, {"properties": [("delta", 1)]}), ("font.change_character", {"type": 'DOWN_ARROW', "value": 'PRESS', "alt": True}, {"properties": [("delta", -1)]}), ("font.select_all", {"type": 'A', "value": 'PRESS', "ctrl": True}, None), ("font.text_copy", {"type": 'C', "value": 'PRESS', "ctrl": True}, None), ("font.text_cut", {"type": 'X', "value": 'PRESS', "ctrl": True}, None), ("font.text_paste", {"type": 'V', "value": 'PRESS', "ctrl": True}, None), ("font.line_break", {"type": 'RET', "value": 'PRESS'}, None), ("font.text_insert", {"type": 'TEXTINPUT', "value": 'ANY', "any": True}, None), ("font.text_insert", {"type": 'BACK_SPACE', "value": 'PRESS', "alt": True}, {"properties": [("accent", True)]}), op_menu("VIEW3D_MT_edit_text_context_menu", params.context_menu_event), ]) return keymap def km_object_non_modal(params): items = [] keymap = ( "Object Non-modal", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": items}, ) if params.legacy: items.extend([ ("object.mode_set", {"type": 'TAB', "value": 'PRESS'}, {"properties": [("mode", 'EDIT'), ("toggle", True)]}), ("object.mode_set", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'POSE'), ("toggle", True)]}), ("object.mode_set", {"type": 'V', "value": 'PRESS'}, {"properties": [("mode", 'VERTEX_PAINT'), ("toggle", True)]}), ("object.mode_set", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'WEIGHT_PAINT'), ("toggle", True)]}), ]) elif params.use_pie_click_drag: items.extend([ ("object.mode_set", {"type": 'TAB', "value": 'CLICK'}, {"properties": [("mode", 'EDIT'), ("toggle", True)]}), op_menu_pie("VIEW3D_MT_object_mode_pie", {"type": 'TAB', "value": 'CLICK_DRAG'}), ("view3d.object_mode_pie_or_toggle", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, None), ]) elif not params.use_v3d_tab_menu: items.extend([ ("object.mode_set", {"type": 'TAB', "value": 'PRESS'}, {"properties": [("mode", 'EDIT'), ("toggle", True)]}), ("view3d.object_mode_pie_or_toggle", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, None), ]) else: # Swap Tab/Ctrl-Tab items.extend([ ("object.mode_set", {"type": 'TAB', "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'EDIT'), ("toggle", True)]}), op_menu_pie("VIEW3D_MT_object_mode_pie", {"type": 'TAB', "value": 'PRESS'}), ]) if params.legacy: items.extend([ ("object.origin_set", {"type": 'C', "value": 'PRESS', "shift": True, "ctrl": True, "alt": True}, None), ]) return keymap # ------------------------------------------------------------------------------ # Modal Maps and Gizmos def km_eyedropper_modal_map(_params): items = [] keymap = ( "Eyedropper Modal Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'PRESS', "any": True}, None), ("SAMPLE_CONFIRM", {"type": 'RET', "value": 'RELEASE', "any": True}, None), ("SAMPLE_CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'RELEASE', "any": True}, None), ("SAMPLE_CONFIRM", {"type": 'LEFTMOUSE', "value": 'RELEASE', "any": True}, None), ("SAMPLE_BEGIN", {"type": 'LEFTMOUSE', "value": 'PRESS', "any": True}, None), ("SAMPLE_RESET", {"type": 'SPACE', "value": 'RELEASE', "any": True}, None), ]) return keymap def km_eyedropper_colorramp_pointsampling_map(_params): items = [] keymap = ( "Eyedropper ColorRamp PointSampling Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'BACK_SPACE', "value": 'PRESS', "any": True}, None), ("SAMPLE_CONFIRM", {"type": 'RIGHTMOUSE', "value": 'PRESS', "any": True}, None), ("SAMPLE_CONFIRM", {"type": 'RET', "value": 'RELEASE', "any": True}, None), ("SAMPLE_CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'RELEASE', "any": True}, None), ("SAMPLE_SAMPLE", {"type": 'LEFTMOUSE', "value": 'PRESS', "any": True}, None), ("SAMPLE_RESET", {"type": 'SPACE', "value": 'RELEASE', "any": True}, None), ]) return keymap def km_transform_modal_map(_params): items = [] keymap = ( "Transform Modal Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CONFIRM", {"type": 'LEFTMOUSE', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("AXIS_X", {"type": 'X', "value": 'PRESS'}, None), ("AXIS_Y", {"type": 'Y', "value": 'PRESS'}, None), ("AXIS_Z", {"type": 'Z', "value": 'PRESS'}, None), ("PLANE_X", {"type": 'X', "value": 'PRESS', "shift": True}, None), ("PLANE_Y", {"type": 'Y', "value": 'PRESS', "shift": True}, None), ("PLANE_Z", {"type": 'Z', "value": 'PRESS', "shift": True}, None), ("CONS_OFF", {"type": 'C', "value": 'PRESS'}, None), ("TRANSLATE", {"type": 'G', "value": 'PRESS'}, None), ("ROTATE", {"type": 'R', "value": 'PRESS'}, None), ("RESIZE", {"type": 'S', "value": 'PRESS'}, None), ("SNAP_TOGGLE", {"type": 'TAB', "value": 'PRESS', "shift": True}, None), ("SNAP_INV_ON", {"type": 'LEFT_CTRL', "value": 'PRESS', "any": True}, None), ("SNAP_INV_OFF", {"type": 'LEFT_CTRL', "value": 'RELEASE', "any": True}, None), ("SNAP_INV_ON", {"type": 'RIGHT_CTRL', "value": 'PRESS', "any": True}, None), ("SNAP_INV_OFF", {"type": 'RIGHT_CTRL', "value": 'RELEASE', "any": True}, None), ("ADD_SNAP", {"type": 'A', "value": 'PRESS'}, None), ("REMOVE_SNAP", {"type": 'A', "value": 'PRESS', "alt": True}, None), ("PROPORTIONAL_SIZE_UP", {"type": 'PAGE_UP', "value": 'PRESS'}, None), ("PROPORTIONAL_SIZE_DOWN", {"type": 'PAGE_DOWN', "value": 'PRESS'}, None), ("PROPORTIONAL_SIZE_UP", {"type": 'PAGE_UP', "value": 'PRESS', "shift": True}, None), ("PROPORTIONAL_SIZE_DOWN", {"type": 'PAGE_DOWN', "value": 'PRESS', "shift": True}, None), ("PROPORTIONAL_SIZE_UP", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS'}, None), ("PROPORTIONAL_SIZE_DOWN", {"type": 'WHEELUPMOUSE', "value": 'PRESS'}, None), ("PROPORTIONAL_SIZE_UP", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "shift": True}, None), ("PROPORTIONAL_SIZE_DOWN", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "shift": True}, None), ("PROPORTIONAL_SIZE", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ("EDGESLIDE_EDGE_NEXT", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "alt": True}, None), ("EDGESLIDE_PREV_NEXT", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "alt": True}, None), ("AUTOIK_CHAIN_LEN_UP", {"type": 'PAGE_UP', "value": 'PRESS', "shift": True}, None), ("AUTOIK_CHAIN_LEN_DOWN", {"type": 'PAGE_DOWN', "value": 'PRESS', "shift": True}, None), ("AUTOIK_CHAIN_LEN_UP", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "shift": True}, None), ("AUTOIK_CHAIN_LEN_DOWN", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "shift": True}, None), ("INSERTOFS_TOGGLE_DIR", {"type": 'T', "value": 'PRESS'}, None), ]) return keymap def km_view3d_gesture_circle(_params): items = [] keymap = ( "View3D Gesture Circle", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ # Note: use 'KM_ANY' for release, so the circle exits on any mouse release, # this is needed when circle select is activated as a tool. ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'ANY', "any": True}, None), ("CONFIRM", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'PRESS'}, None), ("SELECT", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("DESELECT", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, None), ("NOP", {"type": 'LEFTMOUSE', "value": 'RELEASE', "any": True}, None), ("DESELECT", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("NOP", {"type": 'MIDDLEMOUSE', "value": 'RELEASE', "any": True}, None), ("SUBTRACT", {"type": 'WHEELUPMOUSE', "value": 'PRESS'}, None), ("SUBTRACT", {"type": 'NUMPAD_MINUS', "value": 'PRESS'}, None), ("ADD", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS'}, None), ("ADD", {"type": 'NUMPAD_PLUS', "value": 'PRESS'}, None), ("SIZE", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ]) return keymap def km_gesture_border(_params): items = [] keymap = ( "Gesture Box", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'PRESS', "any": True}, None), ("SELECT", {"type": 'RIGHTMOUSE', "value": 'RELEASE', "any": True}, None), ("BEGIN", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, None), ("DESELECT", {"type": 'LEFTMOUSE', "value": 'RELEASE', "shift": True}, None), ("BEGIN", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("SELECT", {"type": 'LEFTMOUSE', "value": 'RELEASE', "any": True}, None), ("BEGIN", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("DESELECT", {"type": 'MIDDLEMOUSE', "value": 'RELEASE'}, None), ]) return keymap def km_gesture_zoom_border(_params): items = [] keymap = ( "Gesture Zoom Border", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'ANY', "any": True}, None), ("BEGIN", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("IN", {"type": 'LEFTMOUSE', "value": 'RELEASE'}, None), ("BEGIN", {"type": 'MIDDLEMOUSE', "value": 'PRESS'}, None), ("OUT", {"type": 'MIDDLEMOUSE', "value": 'RELEASE'}, None), ]) return keymap def km_gesture_straight_line(_params): items = [] keymap = ( "Gesture Straight Line", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'ANY', "any": True}, None), ("BEGIN", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("SELECT", {"type": 'LEFTMOUSE', "value": 'RELEASE', "any": True}, None), ]) return keymap def km_standard_modal_map(_params): items = [] keymap = ( "Standard Modal Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("APPLY", {"type": 'LEFTMOUSE', "value": 'ANY', "any": True}, None), ("APPLY", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("APPLY", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "any": True}, None), ("SNAP", {"type": 'LEFT_CTRL', "value": 'PRESS', "any": True}, None), ("SNAP_OFF", {"type": 'LEFT_CTRL', "value": 'RELEASE', "any": True}, None), ]) return keymap def km_knife_tool_modal_map(_params): items = [] keymap = ( "Knife Tool Modal Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("PANNING", {"type": 'MIDDLEMOUSE', "value": 'ANY', "any": True}, None), ("ADD_CUT_CLOSED", {"type": 'LEFTMOUSE', "value": 'DOUBLE_CLICK', "any": True}, None), ("ADD_CUT", {"type": 'LEFTMOUSE', "value": 'ANY', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'SPACE', "value": 'PRESS', "any": True}, None), ("NEW_CUT", {"type": 'E', "value": 'PRESS'}, None), ("SNAP_MIDPOINTS_ON", {"type": 'LEFT_CTRL', "value": 'PRESS', "any": True}, None), ("SNAP_MIDPOINTS_OFF", {"type": 'LEFT_CTRL', "value": 'RELEASE', "any": True}, None), ("SNAP_MIDPOINTS_ON", {"type": 'RIGHT_CTRL', "value": 'PRESS', "any": True}, None), ("SNAP_MIDPOINTS_OFF", {"type": 'RIGHT_CTRL', "value": 'RELEASE', "any": True}, None), ("IGNORE_SNAP_ON", {"type": 'LEFT_SHIFT', "value": 'PRESS', "any": True}, None), ("IGNORE_SNAP_OFF", {"type": 'LEFT_SHIFT', "value": 'RELEASE', "any": True}, None), ("IGNORE_SNAP_ON", {"type": 'RIGHT_SHIFT', "value": 'PRESS', "any": True}, None), ("IGNORE_SNAP_OFF", {"type": 'RIGHT_SHIFT', "value": 'RELEASE', "any": True}, None), ("ANGLE_SNAP_TOGGLE", {"type": 'C', "value": 'PRESS'}, None), ("CUT_THROUGH_TOGGLE", {"type": 'Z', "value": 'PRESS'}, None), ]) return keymap def km_custom_normals_modal_map(_params): items = [] keymap = ( "Custom Normals Modal Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'PRESS'}, None), ("CONFIRM", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'LEFTMOUSE', "value": 'PRESS'}, None), ("RESET", {"type": 'R', "value": 'PRESS'}, None), ("INVERT", {"type": 'I', "value": 'PRESS'}, None), ("SPHERIZE", {"type": 'S', "value": 'PRESS'}, None), ("ALIGN", {"type": 'A', "value": 'PRESS'}, None), ("USE_MOUSE", {"type": 'M', "value": 'PRESS'}, None), ("USE_PIVOT", {"type": 'L', "value": 'PRESS'}, None), ("USE_OBJECT", {"type": 'O', "value": 'PRESS'}, None), ("SET_USE_3DCURSOR", {"type": 'LEFTMOUSE', "value": 'CLICK', "ctrl": True}, None), ("SET_USE_SELECTED", {"type": 'RIGHTMOUSE', "value": 'CLICK', "ctrl": True}, None), ]) return keymap def km_bevel_modal_map(_params): items = [] keymap = ( "Bevel Modal Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'LEFTMOUSE', "value": 'PRESS', "any": True}, None), ("VALUE_OFFSET", {"type": 'A', "value": 'PRESS', "any": True}, None), ("VALUE_PROFILE", {"type": 'P', "value": 'PRESS', "any": True}, None), ("VALUE_SEGMENTS", {"type": 'S', "value": 'PRESS', "any": True}, None), ("SEGMENTS_UP", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "any": True}, None), ("SEGMENTS_UP", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "any": True}, None), ("SEGMENTS_DOWN", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "any": True}, None), ("SEGMENTS_DOWN", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "any": True}, None), ("OFFSET_MODE_CHANGE", {"type": 'M', "value": 'PRESS', "any": True}, None), ("CLAMP_OVERLAP_TOGGLE", {"type": 'C', "value": 'PRESS', "any": True}, None), ("VERTEX_ONLY_TOGGLE", {"type": 'V', "value": 'PRESS', "any": True}, None), ("HARDEN_NORMALS_TOGGLE", {"type": 'H', "value": 'PRESS', "any": True}, None), ("MARK_SEAM_TOGGLE", {"type": 'U', "value": 'PRESS', "any": True}, None), ("MARK_SHARP_TOGGLE", {"type": 'K', "value": 'PRESS', "any": True}, None), ("OUTER_MITER_CHANGE", {"type": 'O', "value": 'PRESS', "any": True}, None), ("INNER_MITER_CHANGE", {"type": 'I', "value": 'PRESS', "any": True}, None), ]) return keymap def km_view3d_fly_modal(_params): items = [] keymap = ( "View3D Fly Modal", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'ANY', "any": True}, None), ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'LEFTMOUSE', "value": 'ANY', "any": True}, None), ("CONFIRM", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'SPACE', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "any": True}, None), ("ACCELERATE", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "any": True}, None), ("DECELERATE", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "any": True}, None), ("ACCELERATE", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "any": True}, None), ("DECELERATE", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'TRACKPADPAN', "value": 'ANY'}, None), ("PAN_ENABLE", {"type": 'MIDDLEMOUSE', "value": 'PRESS', "any": True}, None), ("PAN_DISABLE", {"type": 'MIDDLEMOUSE', "value": 'RELEASE', "any": True}, None), ("FORWARD", {"type": 'W', "value": 'PRESS'}, None), ("BACKWARD", {"type": 'S', "value": 'PRESS'}, None), ("LEFT", {"type": 'A', "value": 'PRESS'}, None), ("RIGHT", {"type": 'D', "value": 'PRESS'}, None), ("UP", {"type": 'E', "value": 'PRESS'}, None), ("DOWN", {"type": 'Q', "value": 'PRESS'}, None), ("UP", {"type": 'R', "value": 'PRESS'}, None), ("DOWN", {"type": 'F', "value": 'PRESS'}, None), ("FORWARD", {"type": 'UP_ARROW', "value": 'PRESS'}, None), ("BACKWARD", {"type": 'DOWN_ARROW', "value": 'PRESS'}, None), ("LEFT", {"type": 'LEFT_ARROW', "value": 'PRESS'}, None), ("RIGHT", {"type": 'RIGHT_ARROW', "value": 'PRESS'}, None), ("AXIS_LOCK_X", {"type": 'X', "value": 'PRESS'}, None), ("AXIS_LOCK_Z", {"type": 'Z', "value": 'PRESS'}, None), ("PRECISION_ENABLE", {"type": 'LEFT_ALT', "value": 'PRESS', "any": True}, None), ("PRECISION_DISABLE", {"type": 'LEFT_ALT', "value": 'RELEASE', "any": True}, None), ("PRECISION_ENABLE", {"type": 'LEFT_SHIFT', "value": 'PRESS', "any": True}, None), ("PRECISION_DISABLE", {"type": 'LEFT_SHIFT', "value": 'RELEASE', "any": True}, None), ("FREELOOK_ENABLE", {"type": 'LEFT_CTRL', "value": 'PRESS', "any": True}, None), ("FREELOOK_DISABLE", {"type": 'LEFT_CTRL', "value": 'RELEASE', "any": True}, None), ]) return keymap def km_view3d_walk_modal(_params): items = [] keymap = ( "View3D Walk Modal", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'RIGHTMOUSE', "value": 'ANY', "any": True}, None), ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'LEFTMOUSE', "value": 'ANY', "any": True}, None), ("CONFIRM", {"type": 'RET', "value": 'PRESS', "any": True}, None), ("CONFIRM", {"type": 'NUMPAD_ENTER', "value": 'PRESS', "any": True}, None), ("FAST_ENABLE", {"type": 'LEFT_SHIFT', "value": 'PRESS', "any": True}, None), ("FAST_DISABLE", {"type": 'LEFT_SHIFT', "value": 'RELEASE', "any": True}, None), ("SLOW_ENABLE", {"type": 'LEFT_ALT', "value": 'PRESS', "any": True}, None), ("SLOW_DISABLE", {"type": 'LEFT_ALT', "value": 'RELEASE', "any": True}, None), ("FORWARD", {"type": 'W', "value": 'PRESS', "any": True}, None), ("BACKWARD", {"type": 'S', "value": 'PRESS', "any": True}, None), ("LEFT", {"type": 'A', "value": 'PRESS', "any": True}, None), ("RIGHT", {"type": 'D', "value": 'PRESS', "any": True}, None), ("UP", {"type": 'E', "value": 'PRESS', "any": True}, None), ("DOWN", {"type": 'Q', "value": 'PRESS', "any": True}, None), ("FORWARD_STOP", {"type": 'W', "value": 'RELEASE', "any": True}, None), ("BACKWARD_STOP", {"type": 'S', "value": 'RELEASE', "any": True}, None), ("LEFT_STOP", {"type": 'A', "value": 'RELEASE', "any": True}, None), ("RIGHT_STOP", {"type": 'D', "value": 'RELEASE', "any": True}, None), ("UP_STOP", {"type": 'E', "value": 'RELEASE', "any": True}, None), ("DOWN_STOP", {"type": 'Q', "value": 'RELEASE', "any": True}, None), ("FORWARD", {"type": 'UP_ARROW', "value": 'PRESS'}, None), ("BACKWARD", {"type": 'DOWN_ARROW', "value": 'PRESS'}, None), ("LEFT", {"type": 'LEFT_ARROW', "value": 'PRESS'}, None), ("RIGHT", {"type": 'RIGHT_ARROW', "value": 'PRESS'}, None), ("FORWARD_STOP", {"type": 'UP_ARROW', "value": 'RELEASE', "any": True}, None), ("BACKWARD_STOP", {"type": 'DOWN_ARROW', "value": 'RELEASE', "any": True}, None), ("LEFT_STOP", {"type": 'LEFT_ARROW', "value": 'RELEASE', "any": True}, None), ("RIGHT_STOP", {"type": 'RIGHT_ARROW', "value": 'RELEASE', "any": True}, None), ("GRAVITY_TOGGLE", {"type": 'TAB', "value": 'PRESS'}, None), ("GRAVITY_TOGGLE", {"type": 'G', "value": 'PRESS'}, None), ("JUMP", {"type": 'V', "value": 'PRESS', "any": True}, None), ("JUMP_STOP", {"type": 'V', "value": 'RELEASE', "any": True}, None), ("TELEPORT", {"type": 'SPACE', "value": 'PRESS', "any": True}, None), ("TELEPORT", {"type": 'MIDDLEMOUSE', "value": 'ANY', "any": True}, None), ("ACCELERATE", {"type": 'NUMPAD_PLUS', "value": 'PRESS', "any": True}, None), ("DECELERATE", {"type": 'NUMPAD_MINUS', "value": 'PRESS', "any": True}, None), ("ACCELERATE", {"type": 'WHEELUPMOUSE', "value": 'PRESS', "any": True}, None), ("DECELERATE", {"type": 'WHEELDOWNMOUSE', "value": 'PRESS', "any": True}, None), ]) return keymap def km_view3d_rotate_modal(_params): items = [] keymap = ( "View3D Rotate Modal", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CONFIRM", {"type": 'MIDDLEMOUSE', "value": 'RELEASE', "any": True}, None), ("CONFIRM", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ("AXIS_SNAP_ENABLE", {"type": 'LEFT_ALT', "value": 'PRESS', "any": True}, None), ("AXIS_SNAP_DISABLE", {"type": 'LEFT_ALT', "value": 'RELEASE', "any": True}, None), ]) return keymap def km_view3d_move_modal(_params): items = [] keymap = ( "View3D Move Modal", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CONFIRM", {"type": 'MIDDLEMOUSE', "value": 'RELEASE', "any": True}, None), ("CONFIRM", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ]) return keymap def km_view3d_zoom_modal(_params): items = [] keymap = ( "View3D Zoom Modal", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CONFIRM", {"type": 'MIDDLEMOUSE', "value": 'RELEASE', "any": True}, None), ("CONFIRM", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ]) return keymap def km_view3d_dolly_modal(_params): items = [] keymap = ( "View3D Dolly Modal", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CONFIRM", {"type": 'MIDDLEMOUSE', "value": 'RELEASE', "any": True}, None), ("CONFIRM", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ]) return keymap def km_paint_stroke_modal(_params): items = [] keymap = ( "Paint Stroke Modal", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": items}, ) items.extend([ ("CANCEL", {"type": 'ESC', "value": 'PRESS', "any": True}, None), ]) return keymap # Fallback for gizmos that don't have custom a custom key-map. def km_generic_gizmos(_params): keymap = ( "Generic Gizmos", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, {"items": _template_items_gizmo_tweak_value()}, ) return keymap def km_generic_gizmos_tweak_modal_map(_params): keymap = ( "Generic Gizmos Tweak Modal Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": _template_items_gizmo_tweak_modal()}, ) return keymap def km_generic_gizmos_select(_params): keymap = ( "Generic Gizmos Select", {"space_type": 'EMPTY', "region_type": 'WINDOW'}, # TODO, currently in C code. {"items": _template_items_gizmo_tweak_value()}, ) return keymap def km_generic_gizmos_select_tweak_modal_map(_params): keymap = ( "Generic Gizmos Select Tweak Modal Map", {"space_type": 'EMPTY', "region_type": 'WINDOW', "modal": True}, {"items": _template_items_gizmo_tweak_modal()}, ) return keymap # ------------------------------------------------------------------------------ # Popup Keymaps def km_popup_toolbar(_params): return ( "Toolbar Popup", {"space_type": 'EMPTY', "region_type": 'TEMPORARY'}, {"items": [ op_tool("builtin.select", {"type": 'W', "value": 'PRESS'}), op_tool("builtin.select_lasso", {"type": 'L', "value": 'PRESS'}), op_tool("builtin.transform", {"type": 'T', "value": 'PRESS'}), op_tool("builtin.measure", {"type": 'M', "value": 'PRESS'}), ]}, ) # ------------------------------------------------------------------------------ # Tool System Keymaps # # Named are auto-generated based on the tool name and it's toolbar. def km_generic_tool_annotate(params): return ( "Generic Tool: Annotate", {"region_type": 'WINDOW'}, {"items": [ ("gpencil.annotate", {"type": params.tool_mouse, "value": 'PRESS'}, {"properties": [("mode", 'DRAW'), ("wait_for_input", False)]}), ("gpencil.annotate", {"type": params.tool_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), ]}, ) def km_generic_tool_annotate_line(params): return ( "Generic Tool: Annotate Line", {"region_type": 'WINDOW'}, {"items": [ ("gpencil.annotate", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("mode", 'DRAW_STRAIGHT'), ("wait_for_input", False)]}), ("gpencil.annotate", {"type": params.tool_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), ]}, ) def km_generic_tool_annotate_polygon(params): return ( "Generic Tool: Annotate Polygon", {"region_type": 'WINDOW'}, {"items": [ ("gpencil.annotate", {"type": params.tool_mouse, "value": 'PRESS'}, {"properties": [("mode", 'DRAW_POLY'), ("wait_for_input", False)]}), ("gpencil.annotate", {"type": params.tool_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), ]}, ) def km_generic_tool_annotate_eraser(params): return ( "Generic Tool: Annotate Eraser", {"region_type": 'WINDOW'}, {"items": [ ("gpencil.annotate", {"type": params.tool_mouse, "value": 'PRESS'}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), ("gpencil.annotate", {"type": params.tool_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'ERASER'), ("wait_for_input", False)]}), ]}, ) def km_image_editor_tool_generic_sample(params): return ( "Image Editor Tool: Sample", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": [ ("image.sample", {"type": params.tool_mouse, "value": 'PRESS'}, None), ]}, ) def km_image_editor_tool_uv_cursor(params): return ( "Image Editor Tool: Uv, Cursor", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": [ ("uv.cursor_set", {"type": params.tool_mouse, "value": 'PRESS'}, None), ("transform.translate", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True), ("cursor_transform", True)]}), ]}, ) def km_image_editor_tool_uv_select(params): return ( "Image Editor Tool: Uv, Select", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": _template_items_tool_select(params, "uv.select", "uv.cursor_set")}, ) def km_image_editor_tool_uv_select_box(params): return ( "Image Editor Tool: Uv, Select Box", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple("uv.select_box", type=params.tool_tweak, value='ANY')}, ) def km_image_editor_tool_uv_select_circle(params): return ( "Image Editor Tool: Uv, Select Circle", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple( "uv.select_circle", type=params.tool_mouse, value='PRESS', properties=[("wait_for_input", False)], )}, ) def km_image_editor_tool_uv_select_lasso(params): return ( "Image Editor Tool: Uv, Select Lasso", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple("uv.select_lasso", type=params.tool_tweak, value='ANY')}, ) def km_image_editor_tool_uv_sculpt_stroke(params): return ( "Image Editor Tool: Uv, Sculpt Stroke", {"space_type": 'IMAGE_EDITOR', "region_type": 'WINDOW'}, {"items": [ ("sculpt.uv_sculpt_stroke", {"type": params.tool_mouse, "value": 'PRESS'}, None), ("sculpt.uv_sculpt_stroke", {"type": params.tool_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("mode", 'INVERT')]}), ("sculpt.uv_sculpt_stroke", {"type": params.tool_mouse, "value": 'PRESS', "shift": True}, {"properties": [("mode", 'RELAX')]}), ("brush.scale_size", {"type": 'LEFT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 0.9)]}), ("brush.scale_size", {"type": 'RIGHT_BRACKET', "value": 'PRESS'}, {"properties": [("scalar", 1.0 / 0.9)]}), *_template_paint_radial_control("uv_sculpt"), ]}, ) def km_node_editor_tool_select(params): return ( "Node Tool: Select", {"space_type": 'NODE_EDITOR', "region_type": 'WINDOW'}, {"items": [ ("node.select", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("extend", False), ("deselect_all", not params.legacy)]}), ]}, ) def km_node_editor_tool_select_box(params): return ( "Node Tool: Select Box", {"space_type": 'NODE_EDITOR', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple( "node.select_box", type=params.tool_tweak, value='ANY', properties=[("tweak", True)], )}, ) def km_node_editor_tool_select_lasso(params): return ( "Node Tool: Select Lasso", {"space_type": 'NODE_EDITOR', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple( "node.select_lasso", type=params.tool_mouse, value='PRESS', properties=[("tweak", True)], )}, ) def km_node_editor_tool_select_circle(params): return ( "Node Tool: Select Circle", {"space_type": 'NODE_EDITOR', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple( "node.select_circle", type=params.tool_mouse, value='PRESS', properties=[("wait_for_input", False)], )}, ) def km_node_editor_tool_links_cut(params): return ( "Node Tool: Links Cut", {"space_type": 'NODE_EDITOR', "region_type": 'WINDOW'}, {"items": [ ("node.links_cut", {"type": params.tool_mouse, "value": 'PRESS'}, None), ]}, ) def km_3d_view_tool_cursor(params): return ( "3D View Tool: Cursor", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("view3d.cursor3d", {"type": params.tool_mouse, "value": 'PRESS'}, None), ("transform.translate", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True), ("cursor_transform", True)]}), ]}, ) def km_3d_view_tool_select(params): return ( "3D View Tool: Select", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select(params, "view3d.select", "view3d.cursor3d")}, ) def km_3d_view_tool_select_box(params): return ( "3D View Tool: Select Box", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions("view3d.select_box", type=params.tool_tweak, value='ANY')}, ) def km_3d_view_tool_select_circle(params): return ( "3D View Tool: Select Circle", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple( "view3d.select_circle", type=params.tool_mouse, value='PRESS', properties=[("wait_for_input", False)], )}, ) def km_3d_view_tool_select_lasso(params): return ( "3D View Tool: Select Lasso", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions("view3d.select_lasso", type=params.tool_tweak, value='ANY')}, ) def km_3d_view_tool_transform(params): return ( "3D View Tool: Transform", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.from_gizmo", {"type": params.tool_tweak, "value": 'ANY'}, None), ]}, ) def km_3d_view_tool_move(params): return ( "3D View Tool: Move", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.translate", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_rotate(params): return ( "3D View Tool: Rotate", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.rotate", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_scale(params): return ( "3D View Tool: Scale", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.resize", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_measure(params): return ( "3D View Tool: Measure", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("view3d.ruler_add", {"type": params.tool_tweak, "value": 'ANY'}, None), ("view3d.ruler_remove", {"type": 'X', "value": 'PRESS'}, None), ("view3d.ruler_remove", {"type": 'DEL', "value": 'PRESS'}, None), ]}, ) def km_3d_view_tool_pose_breakdowner(params): return ( "3D View Tool: Pose, Breakdowner", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("pose.breakdown", {"type": params.tool_tweak, "value": 'ANY'}, None), ]}, ) def km_3d_view_tool_pose_push(params): return ( "3D View Tool: Pose, Push", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("pose.push", {"type": params.tool_tweak, "value": 'ANY'}, None), ]}, ) def km_3d_view_tool_pose_relax(params): return ( "3D View Tool: Pose, Relax", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("pose.relax", {"type": params.tool_tweak, "value": 'ANY'}, None), ]}, ) def km_3d_view_tool_edit_armature_roll(params): return ( "3D View Tool: Edit Armature, Roll", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.transform", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True), ("mode", 'BONE_ROLL')]}), ]}, ) def km_3d_view_tool_edit_armature_bone_size(params): return ( "3D View Tool: Edit Armature, Bone Size", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.transform", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True), ("mode", 'BONE_SIZE')]}), ]}, ) def km_3d_view_tool_edit_armature_bone_envelope(params): return ( "3D View Tool: Edit Armature, Bone Envelope", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.transform", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True), ("mode", 'BONE_ENVELOPE')]}), ]}, ) def km_3d_view_tool_edit_armature_extrude(params): return ( "3D View Tool: Edit Armature, Extrude", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("armature.extrude_move", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("TRANSFORM_OT_translate", [("release_confirm", True)])]}), ]}, ) def km_3d_view_tool_edit_armature_extrude_to_cursor(params): return ( "3D View Tool: Edit Armature, Extrude to Cursor", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("armature.click_extrude", {"type": params.tool_mouse, "value": 'PRESS'}, None), ]}, ) def km_3d_view_tool_edit_mesh_add_cube(params): return ( "3D View Tool: Edit Mesh, Add Cube", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("view3d.cursor3d", {"type": params.tool_mouse, "value": 'CLICK'}, None), ("mesh.primitive_cube_add_gizmo", {"type": params.tool_tweak, "value": 'ANY'}, None), ]}, ) def km_3d_view_tool_edit_mesh_extrude_region(params): return ( "3D View Tool: Edit Mesh, Extrude Region", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.extrude_context_move", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("TRANSFORM_OT_translate", [("release_confirm", True)])]}), ]}, ) def km_3d_view_tool_edit_mesh_extrude_along_normals(params): return ( "3D View Tool: Edit Mesh, Extrude Along Normals", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.extrude_region_shrink_fatten", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("TRANSFORM_OT_shrink_fatten", [("release_confirm", True)])]}), ]}, ) def km_3d_view_tool_edit_mesh_extrude_individual(params): return ( "3D View Tool: Edit Mesh, Extrude Individual", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.extrude_faces_move", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("TRANSFORM_OT_shrink_fatten", [("release_confirm", True)])]}), ]}, ) def km_3d_view_tool_edit_mesh_extrude_to_cursor(params): return ( "3D View Tool: Edit Mesh, Extrude to Cursor", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.dupli_extrude_cursor", {"type": params.tool_mouse, "value": 'PRESS'}, None), ]}, ) def km_3d_view_tool_edit_mesh_inset_faces(params): return ( "3D View Tool: Edit Mesh, Inset Faces", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.inset", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_bevel(params): return ( "3D View Tool: Edit Mesh, Bevel", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.bevel", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_loop_cut(params): return ( "3D View Tool: Edit Mesh, Loop Cut", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.loopcut_slide", {"type": params.tool_mouse, "value": 'PRESS'}, {"properties": [("TRANSFORM_OT_edge_slide", [("release_confirm", True)])]}), ]}, ) def km_3d_view_tool_edit_mesh_offset_edge_loop_cut(params): return ( "3D View Tool: Edit Mesh, Offset Edge Loop Cut", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.offset_edge_loops_slide", {"type": params.tool_mouse, "value": 'PRESS'}, None), ]}, ) def km_3d_view_tool_edit_mesh_knife(params): return ( "3D View Tool: Edit Mesh, Knife", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.knife_tool", {"type": params.tool_mouse, "value": 'PRESS'}, {"properties": [("wait_for_input", False)]}), ]}, ) def km_3d_view_tool_edit_mesh_bisect(params): return ( "3D View Tool: Edit Mesh, Bisect", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.bisect", {"type": params.tool_tweak, "value": 'ANY'}, None), ]}, ) def km_3d_view_tool_edit_mesh_poly_build(params): return ( "3D View Tool: Edit Mesh, Poly Build", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.polybuild_face_at_cursor_move", {"type": params.tool_mouse, "value": 'PRESS'}, {"properties": [("TRANSFORM_OT_translate", [("release_confirm", True)])]}), ("mesh.polybuild_split_at_cursor_move", {"type": params.tool_mouse, "value": 'PRESS', "ctrl": True}, {"properties": [("TRANSFORM_OT_translate", [("release_confirm", True)])]}), ("mesh.polybuild_dissolve_at_cursor", {"type": params.tool_mouse, "value": 'CLICK', "alt": True}, None), ]}, ) def km_3d_view_tool_edit_mesh_spin(params): return ( "3D View Tool: Edit Mesh, Spin", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.spin", {"type": params.tool_tweak, "value": 'ANY'}, None), ]}, ) def km_3d_view_tool_edit_mesh_spin_duplicate(params): return ( "3D View Tool: Edit Mesh, Spin Duplicates", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.spin", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("dupli", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_smooth(params): return ( "3D View Tool: Edit Mesh, Smooth", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.vertices_smooth", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("factor", 0.0)]}), ]}, ) def km_3d_view_tool_edit_mesh_randomize(params): return ( "3D View Tool: Edit Mesh, Randomize", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.vertex_random", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("offset", 0.0)]}), ]}, ) def km_3d_view_tool_edit_mesh_edge_slide(params): return ( "3D View Tool: Edit Mesh, Edge Slide", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.edge_slide", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_vertex_slide(params): return ( "3D View Tool: Edit Mesh, Vertex Slide", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.vert_slide", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_shrink_fatten(params): return ( "3D View Tool: Edit Mesh, Shrink/Fatten", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.shrink_fatten", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_push_pull(params): return ( "3D View Tool: Edit Mesh, Push/Pull", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.push_pull", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_shear(params): return ( "3D View Tool: Edit Mesh, Shear", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.shear", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_to_sphere(params): return ( "3D View Tool: Edit Mesh, To Sphere", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.tosphere", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_mesh_rip_region(params): return ( "3D View Tool: Edit Mesh, Rip Region", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.rip_move", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("TRANSFORM_OT_translate", [("release_confirm", True)])]}), ]}, ) def km_3d_view_tool_edit_mesh_rip_edge(params): return ( "3D View Tool: Edit Mesh, Rip Edge", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("mesh.rip_edge_move", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("TRANSFORM_OT_translate", [("release_confirm", True)])]}), ]}, ) def km_3d_view_tool_edit_curve_draw(params): return ( "3D View Tool: Edit Curve, Draw", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("curve.draw", {"type": params.tool_mouse, "value": 'PRESS'}, {"properties": [("wait_for_input", False)]}), ]}, ) def km_3d_view_tool_edit_curve_tilt(params): return ( "3D View Tool: Edit Curve, Tilt", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.tilt", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_curve_radius(params): return ( "3D View Tool: Edit Curve, Radius", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.transform", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("mode", 'CURVE_SHRINKFATTEN'), ("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_curve_randomize(params): return ( "3D View Tool: Edit Curve, Randomize", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.vertex_random", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("offset", 0.0)]}), ]}, ) def km_3d_view_tool_edit_curve_extrude(params): return ( "3D View Tool: Edit Curve, Extrude", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("curve.extrude_move", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("TRANSFORM_OT_translate", [("release_confirm", True)])]}), ]}, ) def km_3d_view_tool_edit_curve_extrude_cursor(params): return ( "3D View Tool: Edit Curve, Extrude Cursor", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("curve.vertex_add", {"type": params.tool_mouse, "value": 'PRESS'}, None), ]}, ) def km_3d_view_tool_sculpt_box_hide(params): return ( "3D View Tool: Sculpt, Box Hide", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("paint.hide_show", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("action", 'HIDE')]}), ("paint.hide_show", {"type": params.tool_tweak, "value": 'ANY', "ctrl": True}, {"properties": [("action", 'SHOW')]}), ("paint.hide_show", {"type": params.select_mouse, "value": 'PRESS'}, {"properties": [("action", 'SHOW'), ("area", 'ALL')]}), ]}, ) def km_3d_view_tool_sculpt_box_mask(params): return ( "3D View Tool: Sculpt, Box Mask", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("view3d.select_box", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("mode", 'ADD')]}), ("view3d.select_box", {"type": params.tool_tweak, "value": 'ANY', "ctrl": True}, {"properties": [("mode", 'SUB')]}), ]}, ) def km_3d_view_tool_paint_weight_sample_weight(params): return ( "3D View Tool: Paint Weight, Sample Weight", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("paint.weight_sample", {"type": params.tool_mouse, "value": 'PRESS'}, None), ]}, ) def km_3d_view_tool_paint_weight_sample_vertex_group(params): return ( "3D View Tool: Paint Weight, Sample Vertex Group", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("paint.weight_sample_group", {"type": params.tool_mouse, "value": 'PRESS'}, None), ]}, ) def km_3d_view_tool_paint_weight_gradient(params): return ( "3D View Tool: Paint Weight, Gradient", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("paint.weight_gradient", {"type": params.tool_tweak, "value": 'ANY'}, None), ]}, ) def km_3d_view_tool_paint_gpencil_line(params): return ( "3D View Tool: Paint Gpencil, Line", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("gpencil.primitive", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("type", 'LINE'), ("wait_for_input", False)]}), ("gpencil.primitive", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'LINE'), ("wait_for_input", False)]}), ("gpencil.primitive", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("type", 'LINE'), ("wait_for_input", False)]}), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]}, ) def km_3d_view_tool_paint_gpencil_box(params): return ( "3D View Tool: Paint Gpencil, Box", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("gpencil.primitive", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("type", 'BOX'), ("wait_for_input", False)]}), ("gpencil.primitive", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'BOX'), ("wait_for_input", False)]}), ("gpencil.primitive", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("type", 'BOX'), ("wait_for_input", False)]}), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]}, ) def km_3d_view_tool_paint_gpencil_circle(params): return ( "3D View Tool: Paint Gpencil, Circle", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("gpencil.primitive", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("type", 'CIRCLE'), ("wait_for_input", False)]}), ("gpencil.primitive", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'CIRCLE'), ("wait_for_input", False)]}), ("gpencil.primitive", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("type", 'CIRCLE'), ("wait_for_input", False)]}), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]}, ) def km_3d_view_tool_paint_gpencil_arc(params): return ( "3D View Tool: Paint Gpencil, Arc", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("gpencil.primitive", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("type", 'ARC'), ("wait_for_input", False)]}), ("gpencil.primitive", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True}, {"properties": [("type", 'ARC'), ("wait_for_input", False)]}), ("gpencil.primitive", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True}, {"properties": [("type", 'ARC'), ("wait_for_input", False)]}), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]}, ) def km_3d_view_tool_paint_gpencil_curve(params): return ( "3D View Tool: Paint Gpencil, Curve", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("gpencil.primitive", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("type", 'CURVE'), ("wait_for_input", False)]}), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]}, ) def km_3d_view_tool_paint_gpencil_cutter(params): return ( "3D View Tool: Paint Gpencil, Cutter", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("gpencil.stroke_cutter", {"type": params.tool_mouse, "value": 'PRESS'}, None), # Lasso select ("gpencil.select_lasso", {"type": params.action_tweak, "value": 'ANY', "ctrl": True, "alt": True}, None), ]}, ) def km_3d_view_tool_edit_gpencil_select(params): return ( "3D View Tool: Edit Gpencil, Select", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select(params, "gpencil.select", "view3d.cursor3d")}, ) def km_3d_view_tool_edit_gpencil_select_box(params): return ( "3D View Tool: Edit Gpencil, Select Box", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions("gpencil.select_box", type=params.tool_tweak, value='ANY')}, ) def km_3d_view_tool_edit_gpencil_select_circle(params): return ( "3D View Tool: Edit Gpencil, Select Circle", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple( "gpencil.select_circle", type=params.tool_mouse, value='PRESS', properties=[("wait_for_input", False)], )}, ) def km_3d_view_tool_edit_gpencil_select_lasso(params): return ( "3D View Tool: Edit Gpencil, Select Lasso", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions("gpencil.select_lasso", type=params.tool_tweak, value='ANY')}, ) def km_3d_view_tool_edit_gpencil_radius(params): return ( "3D View Tool: Edit Gpencil, Radius", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.transform", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("mode", 'CURVE_SHRINKFATTEN'), ("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_gpencil_bend(params): return ( "3D View Tool: Edit Gpencil, Bend", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.bend", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_gpencil_shear(params): return ( "3D View Tool: Edit Gpencil, Shear", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.shear", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_edit_gpencil_to_sphere(params): return ( "3D View Tool: Edit Gpencil, To Sphere", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": [ ("transform.tosphere", {"type": params.tool_tweak, "value": 'ANY'}, {"properties": [("release_confirm", True)]}), ]}, ) def km_3d_view_tool_sculpt_gpencil_select(params): return ( "3D View Tool: Sculpt Gpencil, Select", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select(params, "gpencil.select", "view3d.cursor3d")}, ) def km_3d_view_tool_sculpt_gpencil_select_box(params): return ( "3D View Tool: Sculpt Gpencil, Select Box", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions("gpencil.select_box", type=params.tool_tweak, value='ANY')}, ) def km_3d_view_tool_sculpt_gpencil_select_circle(params): return ( "3D View Tool: Sculpt Gpencil, Select Circle", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions_simple( "gpencil.select_circle", type=params.tool_mouse, value='PRESS', properties=[("wait_for_input", False)], )}, ) def km_3d_view_tool_sculpt_gpencil_select_lasso(params): return ( "3D View Tool: Sculpt Gpencil, Select Lasso", {"space_type": 'VIEW_3D', "region_type": 'WINDOW'}, {"items": _template_items_tool_select_actions("gpencil.select_lasso", type=params.tool_tweak, value='ANY')}, ) # ------------------------------------------------------------------------------ # Full Configuration def generate_keymaps(params=None): if params is None: params = Params() return [ # Window, screen, area, region. km_window(params), km_screen(params), km_screen_editing(params), km_screen_region_context_menu(params), km_view2d(params), km_view2d_buttons_list(params), km_user_interface(params), km_property_editor(params), # Editors. km_outliner(params), km_uv_editor(params), km_view3d_generic(params), km_view3d(params), km_mask_editing(params), km_markers(params), km_scrubbing(params), km_scrubbing_clip(params), km_graph_editor_generic(params), km_graph_editor(params), km_image_generic(params), km_image(params), km_node_generic(params), km_node_editor(params), km_info(params), km_partslist(params), km_file_browser(params), km_file_browser_main(params), km_file_browser_buttons(params), km_dopesheet_generic(params), km_dopesheet(params), km_nla_generic(params), km_nla_channels(params), km_nla_editor(params), km_text_generic(params), km_text(params), km_console(params), km_clip(params), km_clip_editor(params), km_clip_graph_editor(params), km_clip_dopesheet_editor(params), # Animation. km_frames(params), km_animation(params), km_animation_channels(params), # Modes. km_grease_pencil(params), km_grease_pencil_stroke_edit_mode(params), km_grease_pencil_stroke_paint_mode(params), km_grease_pencil_stroke_paint_draw_brush(params), km_grease_pencil_stroke_paint_erase(params), km_grease_pencil_stroke_paint_fill(params), km_grease_pencil_stroke_sculpt_mode(params), km_grease_pencil_stroke_weight_mode(params), km_face_mask(params), km_weight_paint_vertex_selection(params), km_pose(params), km_object_mode(params), km_paint_curve(params), km_curve(params), km_image_paint(params), km_vertex_paint(params), km_weight_paint(params), km_sculpt(params), km_mesh(params), km_armature(params), km_metaball(params), km_lattice(params), km_particle(params), km_font(params), km_object_non_modal(params), # Modal maps. km_eyedropper_modal_map(params), km_eyedropper_colorramp_pointsampling_map(params), km_transform_modal_map(params), km_view3d_gesture_circle(params), km_gesture_border(params), km_gesture_zoom_border(params), km_gesture_straight_line(params), km_standard_modal_map(params), km_knife_tool_modal_map(params), km_custom_normals_modal_map(params), km_bevel_modal_map(params), km_view3d_fly_modal(params), km_view3d_walk_modal(params), km_view3d_rotate_modal(params), km_view3d_move_modal(params), km_view3d_zoom_modal(params), km_view3d_dolly_modal(params), km_paint_stroke_modal(params), # Gizmos. km_generic_gizmos(params), km_generic_gizmos_tweak_modal_map(params), km_generic_gizmos_select(params), km_generic_gizmos_select_tweak_modal_map(params), # Pop-Up Keymaps. km_popup_toolbar(params), # Tool System. km_generic_tool_annotate(params), km_generic_tool_annotate_line(params), km_generic_tool_annotate_polygon(params), km_generic_tool_annotate_eraser(params), km_image_editor_tool_generic_sample(params), km_image_editor_tool_uv_cursor(params), km_image_editor_tool_uv_select(params), km_image_editor_tool_uv_select_box(params), km_image_editor_tool_uv_select_circle(params), km_image_editor_tool_uv_select_lasso(params), km_image_editor_tool_uv_sculpt_stroke(params), km_node_editor_tool_select(params), km_node_editor_tool_select_box(params), km_node_editor_tool_select_lasso(params), km_node_editor_tool_select_circle(params), km_node_editor_tool_links_cut(params), km_3d_view_tool_cursor(params), km_3d_view_tool_select(params), km_3d_view_tool_select_box(params), km_3d_view_tool_select_circle(params), km_3d_view_tool_select_lasso(params), km_3d_view_tool_transform(params), km_3d_view_tool_move(params), km_3d_view_tool_rotate(params), km_3d_view_tool_scale(params), km_3d_view_tool_measure(params), km_3d_view_tool_pose_breakdowner(params), km_3d_view_tool_pose_push(params), km_3d_view_tool_pose_relax(params), km_3d_view_tool_edit_armature_roll(params), km_3d_view_tool_edit_armature_bone_size(params), km_3d_view_tool_edit_armature_bone_envelope(params), km_3d_view_tool_edit_armature_extrude(params), km_3d_view_tool_edit_armature_extrude_to_cursor(params), km_3d_view_tool_edit_mesh_add_cube(params), km_3d_view_tool_edit_mesh_extrude_region(params), km_3d_view_tool_edit_mesh_extrude_along_normals(params), km_3d_view_tool_edit_mesh_extrude_individual(params), km_3d_view_tool_edit_mesh_extrude_to_cursor(params), km_3d_view_tool_edit_mesh_inset_faces(params), km_3d_view_tool_edit_mesh_bevel(params), km_3d_view_tool_edit_mesh_loop_cut(params), km_3d_view_tool_edit_mesh_offset_edge_loop_cut(params), km_3d_view_tool_edit_mesh_knife(params), km_3d_view_tool_edit_mesh_bisect(params), km_3d_view_tool_edit_mesh_poly_build(params), km_3d_view_tool_edit_mesh_spin(params), km_3d_view_tool_edit_mesh_spin_duplicate(params), km_3d_view_tool_edit_mesh_smooth(params), km_3d_view_tool_edit_mesh_randomize(params), km_3d_view_tool_edit_mesh_edge_slide(params), km_3d_view_tool_edit_mesh_vertex_slide(params), km_3d_view_tool_edit_mesh_shrink_fatten(params), km_3d_view_tool_edit_mesh_push_pull(params), km_3d_view_tool_edit_mesh_shear(params), km_3d_view_tool_edit_mesh_to_sphere(params), km_3d_view_tool_edit_mesh_rip_region(params), km_3d_view_tool_edit_mesh_rip_edge(params), km_3d_view_tool_edit_curve_draw(params), km_3d_view_tool_edit_curve_radius(params), km_3d_view_tool_edit_curve_tilt(params), km_3d_view_tool_edit_curve_randomize(params), km_3d_view_tool_edit_curve_extrude(params), km_3d_view_tool_edit_curve_extrude_cursor(params), km_3d_view_tool_sculpt_box_hide(params), km_3d_view_tool_sculpt_box_mask(params), km_3d_view_tool_paint_weight_sample_weight(params), km_3d_view_tool_paint_weight_sample_vertex_group(params), km_3d_view_tool_paint_weight_gradient(params), km_3d_view_tool_paint_gpencil_line(params), km_3d_view_tool_paint_gpencil_box(params), km_3d_view_tool_paint_gpencil_circle(params), km_3d_view_tool_paint_gpencil_arc(params), km_3d_view_tool_paint_gpencil_curve(params), km_3d_view_tool_paint_gpencil_cutter(params), km_3d_view_tool_edit_gpencil_select(params), km_3d_view_tool_edit_gpencil_select_box(params), km_3d_view_tool_edit_gpencil_select_circle(params), km_3d_view_tool_edit_gpencil_select_lasso(params), km_3d_view_tool_edit_gpencil_radius(params), km_3d_view_tool_edit_gpencil_bend(params), km_3d_view_tool_edit_gpencil_shear(params), km_3d_view_tool_edit_gpencil_to_sphere(params), km_3d_view_tool_sculpt_gpencil_select(params), km_3d_view_tool_sculpt_gpencil_select_box(params), km_3d_view_tool_sculpt_gpencil_select_circle(params), km_3d_view_tool_sculpt_gpencil_select_lasso(params), ] # ------------------------------------------------------------------------------ # Refactoring (Testing Only) # # Allows running outside of Blender to generate data for diffing # # To compare: # # python3 release/scripts/presets/keyconfig/keymap_data/blender_default.py && \ # diff -u keymap_default.py.orig keymap_default.py && \ # diff -u keymap_legacy.py.orig keymap_legacy.py # # # begin code: # import pprint # for legacy in (False, True): # with open("keymap_default.py" if not legacy else "keymap_legacy.py", 'w') as fh: # fh.write(pprint.pformat(generate_keymaps(Params(legacy=legacy)), indent=2, width=80)) # import sys # sys.exit() # # end code # ------------------------------------------------------------------------------ # PyLint (Testing Only) # # Command to lint: # # pylint release/scripts/presets/keyconfig/keymap_data/blender_default.py --disable=C0111,C0301,C0302,R0902,R0903,R0913
exports.templateData = { renderBody(out, name) { out.beginElement('div'); out.text(name); out.endElement(); } };
# greaseweazle/optimised/__init__.py # # Written & released by Keir Fraser <keir.xen@gmail.com> # # This is free and unencumbered software released into the public domain. # See the file COPYING for more details, or visit <http://unlicense.org>. import os gw_opt = os.environ.get('GW_OPT') enabled = gw_opt is None or gw_opt.lower().startswith('y') if enabled: try: from .optimised import * except ModuleNotFoundError: enabled = False print('*** WARNING: Optimised data routines not found: ' 'Run scripts/setup.sh') else: print('*** WARNING: Optimised data routines disabled (GW_OPT=%s)' % gw_opt) # Local variables: # python-indent: 4 # End:
import React from "react"; import Container from "@material-ui/core/Container"; import Checkbox from "@material-ui/core/Checkbox"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import FormGroup from "@material-ui/core/FormGroup"; import Button from "@material-ui/core/Button"; const DanceMusicTemp = ({ formState, setFormState, navigation }) => { const { ballet, jazz, hiphop, voice, piano, guitar, violin } = formState; return ( <Container maxWidth="xs"> <h3>Dance &amp; Music</h3> <p>Select all the courses you are interested in:</p> <FormGroup> <h4>Dance</h4> <FormControlLabel control={ <Checkbox checked={ballet} onChange={setFormState} name="ballet" color="primary" /> } label="Ballet" /> <FormControlLabel control={ <Checkbox checked={jazz} onChange={setFormState} name="jazz" color="primary" /> } label="Jazz" /> <FormControlLabel control={ <Checkbox checked={hiphop} onChange={setFormState} name="hiphop" color="primary" /> } label="Hiphop" /> </FormGroup> <FormGroup> <h4>Music</h4> <FormControlLabel control={ <Checkbox checked={voice} onChange={setFormState} name="voice" color="primary" /> } label="Voice" /> <FormControlLabel control={ <Checkbox checked={piano} onChange={setFormState} name="piano" color="primary" /> } label="Piano" /> <FormControlLabel control={ <Checkbox checked={guitar} onChange={setFormState} name="guitar" color="primary" /> } label="Guitar" /> <FormControlLabel control={ <Checkbox checked={violin} onChange={setFormState} name="violin" color="primary" /> } label="Violin" /> </FormGroup> <Button variant="contained" color="secondary" onClick={() => navigation.go("courses")} style={{ margin: "1rem 2rem 0 0" }} > Back </Button> <Button variant="contained" color="primary" style={{ marginTop: "1rem" }} onClick={() => navigation.go("send")} > Next </Button> </Container> ); }; export default DanceMusicTemp;
#!/bin/env python import sys, pdb, mutagen.id3, codecs, glob, os # Code located at /usr/lib/python2.7/site-packages/mutagen/id3/ # class ID3 in __init__.py # frames are listed in _frames.py # Songs ripped by iTunes seem to use ID3v2.2 # (song: TT2, artist: TP1, album: TCM, track: TRK) all plain text # iTunes sorts by Artist/Album so each set should have it's own album # So set TP1 to 'Mr Ear', TCM to bname, and TT2 to mname # But I used ID3v2.4 and it's okay. Initially used USLT which is Unicode lf = u'\240a' if __name__ == '__main__': options = ['help', 'pdb', 'log', 'subdirs=' ] def usage(): print "tagmotifs.py <bname>" print "Options:" for word in options: print " ", word sys.exit(0) import getopt def main(): doPdb = False logOnly = False subdirs = 0 opts, pargs = getopt.getopt(sys.argv[1:], '', options) for opt, val in opts: if opt == '--help': usage() elif opt == '--pdb': doPdb = True elif opt == '--log': logOnly = True elif opt == '--subdirs': subdirs = int(val) if len(pargs) < 1: usage() if doPdb: pdb.set_trace() bname = pargs[0] lname = bname + '.log' mp3dir = bname + '_mp3' tname = bname + '.tag' if not glob.glob(mp3dir + '.tar'): print 'you forgot to tar the mp3 directory for safety' sys.exit() log = codecs.open(tname, 'w', 'utf_16') for line in codecs.open(lname, 'r', 'utf_16'): line = line.strip() words = line.split(lf) if words[0].startswith(u'marker'): continue mname, iSeg, start, stop, startFrame, stopFrame = words[0].split() if subdirs: subdir = '_'.join(mname.split('_')[0:0+subdirs]) aname = bname + '_' + subdir # album tname = mname # title mname = subdir + '/' + mname else: aname = bname tname = mname lyric = [] for word in words[1:]: label, content = word.split(u':', 1) lyric.append(content.strip()) lyric = u'\n'.join(lyric) mp3path = "%s/%s.mp3" % (mp3dir, mname) log.write(u'%s\n%s\n\n' % (unicode(mp3path), lyric)) if logOnly: continue tags = mutagen.id3.ID3() tags['TIT2'] = mutagen.id3.TIT2(encoding=3, lang=u'eng', text=tname) tags['TPE2'] = mutagen.id3.TPE2(encoding=0, lang=u'eng', text='Mr Ear') tags['TALB'] = mutagen.id3.TALB(encoding=0, lang=u'eng', text=aname) tags['USLT'] = mutagen.id3.USLT(encoding=3, lang=u'eng', text=lyric) tags.save(mp3path) main()
# inspired by https://gist.github.com/sente/1083506 # The MIT License (MIT) # Copyright (c) 2016 Stuart Powers # 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 re def pretty_print(xmlstr, indent=' ', line_break='\n'): # python2 doesn't have nonlocal current = [0] def indent_line(line): addition = 0 if re.match(r'.+</\w[^>]*>$', line): # single line text element, don't change indentation addition = 0 elif re.match(r'^</\w', line) and current[0] > 0: # end of element and have padding, decrement indentation by one current[0] -= 1 elif re.match(r'^<\w[^>]*[^/]>.*$', line): # start of element, increment indentation by one addition = 1 else: # single line element, don't change indentation addition = 0 # update and store current indentation in outer function current[0] += addition # pad the line and return return (indent * (current[0] - addition)) + line # split the document into lines, indent each line, then rejoin lines return line_break.join( map( indent_line, re.sub('(>)(<)(/*)', r'\1\n\2\3', xmlstr).split('\n') ) )
from smbus import SMBus bus = SMBus(1) address = 0x48 def get_temp(): data = bus.read_i2c_block_data(0x48, 0x00, 2) data[0] = data[0] * 256 temperature = data[0] + data[1] temperature = (temperature >> 4) * 0.0625 return(temperature)
"""Utilites: minify response decorator.""" from htmlmin import minify from functools import wraps from flask import current_app def minify_response(f): """Minify the current output.""" @wraps(f) def wrapped(*args, **kwargs): if current_app.debug: return f(*args, **kwargs) else: return minify(f(*args, **kwargs), remove_optional_attribute_quotes=False) return wrapped
# -*- coding: utf-8 -*- import datetime import os import sys import traceback import uuid from macdaily.cli.cleanup import parse_args from macdaily.cls.cleanup.brew import BrewCleanup # pylint: disable=unused-import from macdaily.cls.cleanup.cask import CaskCleanup # pylint: disable=unused-import from macdaily.cls.cleanup.npm import NpmCleanup # pylint: disable=unused-import from macdaily.cls.cleanup.pip import PipCleanup # pylint: disable=unused-import from macdaily.cmd.archive import make_archive from macdaily.cmd.config import parse_config from macdaily.util.compat import pathlib, subprocess from macdaily.util.const.macro import VERSION as __version__ from macdaily.util.const.term import bold, green, purple, red, reset, under, yellow from macdaily.util.tools.decorators import beholder from macdaily.util.tools.get import get_logfile, get_pass from macdaily.util.tools.make import make_namespace from macdaily.util.tools.misc import record from macdaily.util.tools.print import print_misc, print_term, print_text @beholder def cleanup(argv=None): # parse args & set context redirection flags args = parse_args(argv) quiet = args.quiet verbose = (args.quiet or not args.verbose) # parse config & change environ config = parse_config(quiet, verbose) os.environ['SUDO_ASKPASS'] = config['Miscellaneous']['askpass'] # fetch current time today = datetime.datetime.today() logdate = datetime.date.strftime(today, r'%y%m%d') logtime = datetime.date.strftime(today, r'%H%M%S') # mkdir for logs logpath = pathlib.Path(os.path.join(config['Path']['logdir'], 'cleanup', logdate)) logpath.mkdir(parents=True, exist_ok=True) # prepare command paras filename = os.path.join(logpath, f'{logtime}-{uuid.uuid4()!s}.log') os.environ['MACDAILY_LOGFILE'] = filename confirm = config['Miscellaneous']['confirm'] askpass = config['Miscellaneous']['askpass'] timeout = config['Miscellaneous']['limit'] disk_dir = config['Path']['arcdir'] brew_renew = None # record program status text = f'{bold}{green}|🚨|{reset} {bold}Running MacDaily version {__version__}{reset}' print_term(text, filename, redirect=quiet) record(filename, args, today, config, redirect=verbose) # ask for password text = f'{bold}{purple}|🔑|{reset} {bold}Your {under}sudo{reset}{bold} password may be necessary{reset}' print_term(text, filename, redirect=quiet) password = get_pass(askpass) cmd_list = list() for mode in {'brew', 'cask', 'npm', 'pip'}: # skip disabled commands if (not config['Mode'].get(mode, False)) or getattr(args, f'no_{mode}', False): text = f'macdaily-cleanup: {yellow}{mode}{reset}: command disabled' print_term(text, filename, redirect=verbose) continue # update cleanup specifications namespace = getattr(args, mode, vars(args)) # check master controlling flags if args.quiet: namespace['quiet'] = True if args.verbose: namespace['verbose'] = True # run command cmd_cls = globals()[f'{mode.capitalize()}Cleanup'] command = cmd_cls(make_namespace(namespace), filename, timeout, confirm, askpass, password, disk_dir, brew_renew) # record command cmd_list.append(command) brew_renew = command.time # archive ancient logs archive = make_archive(config, 'cleanup', today, quiet=quiet, verbose=verbose, logfile=filename) text = f'{bold}{green}|📖|{reset} {bold}MacDaily report of cleanup command{reset}' print_term(text, filename, redirect=quiet) for command in cmd_list: text = f'Pruned caches of {under}{command.name}{reset}{bold}' print_misc(text, get_logfile(), redirect=quiet) if archive: formatted_list = f'{reset}{bold}, {under}'.join(archive) text = (f'Archived following ancient logs: {under}{formatted_list}{reset}') print_misc(text, filename, redirect=quiet) if len(cmd_list) == 0: # pylint:disable=len-as-condition text = f'macdaily: {purple}cleanup{reset}: no caches cleanup' print_term(text, get_logfile(), redirect=quiet) if args.show_log: try: subprocess.check_call(['open', '-a', '/Applications/Utilities/Console.app', filename]) except subprocess.CalledProcessError: print_text(traceback.format_exc(), filename, redirect=verbose) print(f'macdaily: {red}cleanup{reset}: cannot show log file {filename!r}', file=sys.stderr) mode_lst = [command.mode for command in cmd_list] mode_str = ', '.join(mode_lst) if mode_lst else 'none' text = (f'{bold}{green}|🍺|{reset} {bold}MacDaily successfully performed cleanup process ' f'for {mode_str} package managers{reset}') print_term(text, get_logfile(), redirect=quiet) if __name__ == '__main__': sys.exit(cleanup())
var webpack = require('webpack'); var PLUGINS = []; if (process.env.NODE_ENV === 'production') { PLUGINS.push(new webpack.optimize.UglifyJsPlugin()); } module.exports = { entry: './src/index.js', output: { path: __dirname, filename: 'build/build.js' }, plugins: PLUGINS, devServer: { contentBase: '.', watchContentBase: true, disableHostCheck: true, open: true } };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TypeChecker = void 0; const visitor_as_1 = require("visitor-as"); const toIgnore = [ "builtin", ".spec", "dataview", "date", "math", "number", "string", "typedarray", "bindings/Date", "bindings/Math", ]; class TypeChecker extends visitor_as_1.BaseVisitor { check(node) { let first = node.text.substring(0, node.text.indexOf("\n")); if (!(first.includes("ignore") || toIgnore.some((n) => node.normalizedPath.includes(n)))) { this.visit(node); } } static check(node) { const typeChecker = new TypeChecker(); for (let i = 0; i < node.sources.length; i++) { typeChecker.check(node.sources[i]); } } visitTypeName(node) { const regex = /f32|f64/; if (regex.test(node.identifier.text)) { let range = node.range; let source = range.source; let line = source.lineAt(range.start); let lineStr = source.text.split("\n")[line - 1]; TypeChecker.floatsFound.push("\n" + " ".repeat(4) + lineStr + "\n" + "in " + source.normalizedPath + "(" + line.toString() + "," + source.columnAt().toString() + ")"); } } static checkBinary(node) { const wat = node.toText(); const regex = /f32|f64/; if (regex.test(wat)) { throw new Error("Floating point numbers are not allowed in smart contracts: Check\n" + TypeChecker.floatsFound.join("\n")); } } } exports.TypeChecker = TypeChecker; TypeChecker.floatsFound = []; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZUNoZWNrZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvdHlwZUNoZWNrZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQ0EsMkNBQXlDO0FBTXpDLE1BQU0sUUFBUSxHQUFHO0lBQ2YsU0FBUztJQUNULE9BQU87SUFDUCxVQUFVO0lBQ1YsTUFBTTtJQUNOLE1BQU07SUFDTixRQUFRO0lBQ1IsUUFBUTtJQUNSLFlBQVk7SUFDWixlQUFlO0lBQ2YsZUFBZTtDQUNoQixDQUFDO0FBRUYsTUFBYSxXQUFZLFNBQVEsd0JBQVc7SUFHMUMsS0FBSyxDQUFDLElBQVk7UUFDaEIsSUFBSSxLQUFLLEdBQUcsSUFBSSxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsQ0FBQyxFQUFFLElBQUksQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUM7UUFDNUQsSUFDRSxDQUFDLENBQ0MsS0FBSyxDQUFDLFFBQVEsQ0FBQyxRQUFRLENBQUM7WUFDeEIsUUFBUSxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsRUFBRSxFQUFFLENBQUMsSUFBSSxDQUFDLGNBQWMsQ0FBQyxRQUFRLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FDdEQsRUFDRDtZQUNBLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7U0FDbEI7SUFDSCxDQUFDO0lBRUQsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFZO1FBQ3ZCLE1BQU0sV0FBVyxHQUFHLElBQUksV0FBVyxFQUFFLENBQUM7UUFDdEMsS0FBSyxJQUFJLENBQUMsR0FBUSxDQUFDLEVBQUUsQ0FBQyxHQUFHLElBQUksQ0FBQyxPQUFPLENBQUMsTUFBTSxFQUFFLENBQUMsRUFBRSxFQUFFO1lBQ2pELFdBQVcsQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO1NBQ3BDO0lBQ0gsQ0FBQztJQUVELGFBQWEsQ0FBQyxJQUFjO1FBQzFCLE1BQU0sS0FBSyxHQUFtQixTQUFTLENBQUM7UUFDeEMsSUFBSSxLQUFLLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLEVBQUU7WUFDcEMsSUFBSSxLQUFLLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQztZQUN2QixJQUFJLE1BQU0sR0FBRyxLQUFLLENBQUMsTUFBTSxDQUFDO1lBQzFCLElBQUksSUFBSSxHQUFHLE1BQU0sQ0FBQyxNQUFNLENBQUMsS0FBSyxDQUFDLEtBQUssQ0FBQyxDQUFDO1lBQ3RDLElBQUksT0FBTyxHQUFHLE1BQU0sQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDLElBQUksR0FBRyxDQUFDLENBQUMsQ0FBQztZQUVoRCxXQUFXLENBQUMsV0FBVyxDQUFDLElBQUksQ0FDMUIsSUFBSTtnQkFDRixHQUFHLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQztnQkFDYixPQUFPO2dCQUNQLElBQUk7Z0JBQ0osS0FBSztnQkFDTCxNQUFNLENBQUMsY0FBYztnQkFDckIsR0FBRztnQkFDSCxJQUFJLENBQUMsUUFBUSxFQUFFO2dCQUNmLEdBQUc7Z0JBQ0gsTUFBTSxDQUFDLFFBQVEsRUFBRSxDQUFDLFFBQVEsRUFBRTtnQkFDNUIsR0FBRyxDQUNOLENBQUM7U0FDSDtJQUNILENBQUM7SUFFRCxNQUFNLENBQUMsV0FBVyxDQUFDLElBQVk7UUFDN0IsTUFBTSxHQUFHLEdBQUcsSUFBSSxDQUFDLE1BQU0sRUFBRSxDQUFDO1FBQzFCLE1BQU0sS0FBSyxHQUFtQixTQUFTLENBQUM7UUFDeEMsSUFBSSxLQUFLLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFO1lBQ25CLE1BQU0sSUFBSSxLQUFLLENBQ2Isb0VBQW9FO2dCQUNsRSxXQUFXLENBQUMsV0FBVyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FDckMsQ0FBQztTQUNIO0lBQ0gsQ0FBQzs7QUF2REgsa0NBd0RDO0FBdkRRLHVCQUFXLEdBQWEsRUFBRSxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHsgVHlwZU5hbWUsIE1vZHVsZSwgU291cmNlLCBQYXJzZXIgfSBmcm9tIFwidmlzaXRvci1hcy9hc1wiO1xuaW1wb3J0IHsgQmFzZVZpc2l0b3IgfSBmcm9tIFwidmlzaXRvci1hc1wiO1xuXG5kZWNsYXJlIGludGVyZmFjZSBSZWdFeHAge1xuICB0ZXN0KHM6IHN0cmluZyk6IGJvb2w7XG59XG5cbmNvbnN0IHRvSWdub3JlID0gW1xuICBcImJ1aWx0aW5cIixcbiAgXCIuc3BlY1wiLFxuICBcImRhdGF2aWV3XCIsXG4gIFwiZGF0ZVwiLFxuICBcIm1hdGhcIixcbiAgXCJudW1iZXJcIixcbiAgXCJzdHJpbmdcIixcbiAgXCJ0eXBlZGFycmF5XCIsXG4gIFwiYmluZGluZ3MvRGF0ZVwiLFxuICBcImJpbmRpbmdzL01hdGhcIixcbl07XG5cbmV4cG9ydCBjbGFzcyBUeXBlQ2hlY2tlciBleHRlbmRzIEJhc2VWaXNpdG9yIHtcbiAgc3RhdGljIGZsb2F0c0ZvdW5kOiBzdHJpbmdbXSA9IFtdO1xuXG4gIGNoZWNrKG5vZGU6IFNvdXJjZSk6IHZvaWQge1xuICAgIGxldCBmaXJzdCA9IG5vZGUudGV4dC5zdWJzdHJpbmcoMCwgbm9kZS50ZXh0LmluZGV4T2YoXCJcXG5cIikpO1xuICAgIGlmIChcbiAgICAgICEoXG4gICAgICAgIGZpcnN0LmluY2x1ZGVzKFwiaWdub3JlXCIpIHx8XG4gICAgICAgIHRvSWdub3JlLnNvbWUoKG4pID0+IG5vZGUubm9ybWFsaXplZFBhdGguaW5jbHVkZXMobikpXG4gICAgICApXG4gICAgKSB7XG4gICAgICB0aGlzLnZpc2l0KG5vZGUpO1xuICAgIH1cbiAgfVxuXG4gIHN0YXRpYyBjaGVjayhub2RlOiBQYXJzZXIpOiB2b2lkIHtcbiAgICBjb25zdCB0eXBlQ2hlY2tlciA9IG5ldyBUeXBlQ2hlY2tlcigpO1xuICAgIGZvciAobGV0IGk6IGkzMiA9IDA7IGkgPCBub2RlLnNvdXJjZXMubGVuZ3RoOyBpKyspIHtcbiAgICAgIHR5cGVDaGVja2VyLmNoZWNrKG5vZGUuc291cmNlc1tpXSk7XG4gICAgfVxuICB9XG5cbiAgdmlzaXRUeXBlTmFtZShub2RlOiBUeXBlTmFtZSk6IHZvaWQge1xuICAgIGNvbnN0IHJlZ2V4OiBSZWdFeHAgPSA8UmVnRXhwPi9mMzJ8ZjY0LztcbiAgICBpZiAocmVnZXgudGVzdChub2RlLmlkZW50aWZpZXIudGV4dCkpIHtcbiAgICAgIGxldCByYW5nZSA9IG5vZGUucmFuZ2U7XG4gICAgICBsZXQgc291cmNlID0gcmFuZ2Uuc291cmNlO1xuICAgICAgbGV0IGxpbmUgPSBzb3VyY2UubGluZUF0KHJhbmdlLnN0YXJ0KTtcbiAgICAgIGxldCBsaW5lU3RyID0gc291cmNlLnRleHQuc3BsaXQoXCJcXG5cIilbbGluZSAtIDFdO1xuXG4gICAgICBUeXBlQ2hlY2tlci5mbG9hdHNGb3VuZC5wdXNoKFxuICAgICAgICBcIlxcblwiICtcbiAgICAgICAgICBcIiBcIi5yZXBlYXQoNCkgK1xuICAgICAgICAgIGxpbmVTdHIgK1xuICAgICAgICAgIFwiXFxuXCIgK1xuICAgICAgICAgIFwiaW4gXCIgK1xuICAgICAgICAgIHNvdXJjZS5ub3JtYWxpemVkUGF0aCArXG4gICAgICAgICAgXCIoXCIgK1xuICAgICAgICAgIGxpbmUudG9TdHJpbmcoKSArXG4gICAgICAgICAgXCIsXCIgK1xuICAgICAgICAgIHNvdXJjZS5jb2x1bW5BdCgpLnRvU3RyaW5nKCkgK1xuICAgICAgICAgIFwiKVwiXG4gICAgICApO1xuICAgIH1cbiAgfVxuXG4gIHN0YXRpYyBjaGVja0JpbmFyeShub2RlOiBNb2R1bGUpIHtcbiAgICBjb25zdCB3YXQgPSBub2RlLnRvVGV4dCgpO1xuICAgIGNvbnN0IHJlZ2V4OiBSZWdFeHAgPSA8UmVnRXhwPi9mMzJ8ZjY0LztcbiAgICBpZiAocmVnZXgudGVzdCh3YXQpKSB7XG4gICAgICB0aHJvdyBuZXcgRXJyb3IoXG4gICAgICAgIFwiRmxvYXRpbmcgcG9pbnQgbnVtYmVycyBhcmUgbm90IGFsbG93ZWQgaW4gc21hcnQgY29udHJhY3RzOiBDaGVja1xcblwiICtcbiAgICAgICAgICBUeXBlQ2hlY2tlci5mbG9hdHNGb3VuZC5qb2luKFwiXFxuXCIpXG4gICAgICApO1xuICAgIH1cbiAgfVxufVxuIl19
import logging from collections import defaultdict from django.conf import settings from django.contrib.auth.backends import ( BaseBackend, ModelBackend, RemoteUserBackend as _RemoteUserBackend, ) from django.contrib.auth.models import Group from django.db.models import Q from nautobot.users.models import ObjectPermission from nautobot.utilities.permissions import ( permission_is_exempt, resolve_permission, resolve_permission_ct, ) logger = logging.getLogger("nautobot.authentication") class ObjectPermissionBackend(ModelBackend): def get_all_permissions(self, user_obj, obj=None): if not user_obj.is_active or user_obj.is_anonymous: return dict() if not hasattr(user_obj, "_object_perm_cache"): user_obj._object_perm_cache = self.get_object_permissions(user_obj) return user_obj._object_perm_cache def get_object_permissions(self, user_obj): """ Return all permissions granted to the user by an ObjectPermission. """ # Retrieve all assigned and enabled ObjectPermissions object_permissions = ObjectPermission.objects.filter( Q(users=user_obj) | Q(groups__user=user_obj), enabled=True ).prefetch_related("object_types") # Create a dictionary mapping permissions to their constraints perms = defaultdict(list) for obj_perm in object_permissions: for object_type in obj_perm.object_types.all(): for action in obj_perm.actions: perm_name = f"{object_type.app_label}.{action}_{object_type.model}" perms[perm_name].extend(obj_perm.list_constraints()) return perms def has_perm(self, user_obj, perm, obj=None): app_label, action, model_name = resolve_permission(perm) # Superusers implicitly have all permissions if user_obj.is_active and user_obj.is_superuser: return True # Permission is exempt from enforcement (i.e. listed in EXEMPT_VIEW_PERMISSIONS) if permission_is_exempt(perm): return True # Handle inactive/anonymous users if not user_obj.is_active or user_obj.is_anonymous: return False # If no applicable ObjectPermissions have been created for this user/permission, deny permission if perm not in self.get_all_permissions(user_obj): return False # If no object has been specified, grant permission. (The presence of a permission in this set tells # us that the user has permission for *some* objects, but not necessarily a specific object.) if obj is None: return True # Sanity check: Ensure that the requested permission applies to the specified object model = obj._meta.model if model._meta.label_lower != ".".join((app_label, model_name)): raise ValueError(f"Invalid permission {perm} for model {model}") # Compile a query filter that matches all instances of the specified model obj_perm_constraints = self.get_all_permissions(user_obj)[perm] constraints = Q() for perm_constraints in obj_perm_constraints: if perm_constraints: constraints |= Q(**perm_constraints) else: # Found ObjectPermission with null constraints; allow model-level access constraints = Q() break # Permission to perform the requested action on the object depends on whether the specified object matches # the specified constraints. Note that this check is made against the *database* record representing the object, # not the instance itself. return model.objects.filter(constraints, pk=obj.pk).exists() class RemoteUserBackend(_RemoteUserBackend): """ Custom implementation of Django's RemoteUserBackend which provides configuration hooks for basic customization. """ @property def create_unknown_user(self): return settings.REMOTE_AUTH_AUTO_CREATE_USER def configure_user(self, request, user): logger = logging.getLogger("nautobot.authentication.RemoteUserBackend") # noqa: F841 # Assign default groups to the user assign_groups_to_user(user, settings.REMOTE_AUTH_DEFAULT_GROUPS) # Assign default object permissions to the user assign_permissions_to_user(user, settings.REMOTE_AUTH_DEFAULT_PERMISSIONS) return user def has_perm(self, user_obj, perm, obj=None): return False class DummyBackend(BaseBackend): """Passthrough backend that does not authenticate or check permissions.""" def has_perm(self, *args, **kwargs): """ This is only for the fallback dummy backend so that it will passthrough. If `has_perm()` returns `True` it indicates that the backend has authorized the user for a permission, which is what we don't want if we're just passing through. This will allow permission checks to fall through to the next backend as well until `True` or a `PermissionDenied` isn't raised. """ return False class LDAPBackend: """ Wrapper for stock `django-auth-ldap` LDAP authentication. This backend that validates usability based on whether the plugin is installed and configured, otherwise it will return a dummy backend to allow authentication to proceed using other configured backends. """ is_usable = False def __new__(cls, *args, **kwargs): try: from django_auth_ldap.backend import ( LDAPBackend as LDAPBackend_, LDAPSettings, ) import ldap except ModuleNotFoundError as e: if getattr(e, "name") == "django_auth_ldap": logging.error("LDAP authentication has been configured, but django-auth-ldap is not installed.") # Try to import `ldap_config.py` # FIXME(jathan): Have this read from `django.conf.settings` instead vs. # another config file that has to be dropped inside of the Nautobot code # deployment. try: from nautobot.core import ldap_config except (ModuleNotFoundError, ImportError) as e: if getattr(e, "name") == "ldap_config": logging.error("LDAP configuration file not found: Check that ldap_config.py has been created.") ldap_config = None # Once we've asserted that imports/settings work, set this backend as # usable. try: getattr(ldap_config, "AUTH_LDAP_SERVER_URI") except AttributeError: logging.error("Required parameter AUTH_LDAP_SERVER_URI is missing from ldap_config.py.") else: cls.is_usable = True # If the LDAP dependencies aren't set/working, just return a dummy # backend and soft fail. if not cls.is_usable: return DummyBackend() # Create a new instance of django-auth-ldap's LDAPBackend obj = LDAPBackend_() # Read LDAP configuration parameters from ldap_config.py instead of settings.py settings = LDAPSettings() for param in dir(ldap_config): if param.startswith(settings._prefix): setattr(settings, param[10:], getattr(ldap_config, param)) obj.settings = settings # Optionally disable strict certificate checking if getattr(ldap_config, "LDAP_IGNORE_CERT_ERRORS", False): ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) return obj def assign_groups_to_user(user, groups=None): """ Assign a specified user a given list of groups. :param user: The user to assign the permissions :param group: A list of group names to add the user to """ if groups is None: groups = [] group_list = [] for name in groups: try: group_list.append(Group.objects.get(name=name)) except Group.DoesNotExist: logging.error(f"Could not assign group {name} to remotely-authenticated user {user}: Group not found") if group_list: user.groups.add(*group_list) logger.debug(f"Assigned groups to remotely-authenticated user {user}: {group_list}") def assign_permissions_to_user(user, permissions=None): """ Assign a specified user a given set of permissions. :param user: The user to assign the permissions :param permissions: A dictionary of permissions, with the permission name <app_label>.<action>_<model> as the key and constraints as values """ if permissions is None: permissions = {} permissions_list = [] for permission_name, constraints in permissions.items(): try: object_type, action = resolve_permission_ct(permission_name) # TODO: Merge multiple actions into a single ObjectPermission per content type obj_perm = ObjectPermission(name=permission_name, actions=[action], constraints=constraints) obj_perm.save() obj_perm.users.add(user) obj_perm.object_types.add(object_type) permissions_list.append(permission_name) except ValueError: logging.error( f"Invalid permission name: '{permission_name}'. Permissions must be in the form " "<app>.<action>_<model>. (Example: dcim.add_site)" ) if permissions_list: logger.debug(f"Assigned permissions to remotely-authenticated user {user}: {permissions_list}")
//routes handling user registration const express = require("express"); const { getAllUsers, getUser, registerUser, updateUser, deleteUser, } = require("../../controllers/users"); //need to go up two folders api & routes, so ../../ const router = express.Router(); router.route("/").get(getAllUsers).post(registerUser); router.route("/:id").get(getUser).put(updateUser).delete(deleteUser); module.exports = router;
from .base import * DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # In production you need to run # ./manage collectstatic to gather all static files # in STATIC_ROOT STATIC_ROOT = '/demo/static/' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'xyz_console': { 'class': 'logging.StreamHandler' } }, 'loggers': { 'land.middleware': { 'handlers': ['xyz_console'], 'level': 'INFO' } } }
/** * Created by George on 2/26/2017. */ 'use strict'; /** * Module dependencies. */ var faqs = require('../controllers/faqs.server.controller'); module.exports = function(app) { app.route('/api/faqs') .get(faqs.list) .post(faqs.create); app.route('/api/faqs/:faqId') .get(faqs.read) .put(faqs.update) .delete(faqs.deleteFaq); app.route('/api/faqs/:faqId/addAnswer') .post(faqs.addAnswer); app.param('faqId', faqs.faqById); };
import debugModule from "debug"; const debug = debugModule("debugger:test:ast"); import { assert } from "chai"; import Ganache from "ganache"; import { prepareContracts } from "./helpers"; import Debugger from "lib/debugger"; import solidity from "lib/solidity/selectors"; import trace from "lib/trace/selectors"; import SourceMapUtils from "@truffle/source-map-utils"; const __VARIABLES = ` pragma solidity ^0.8.0; contract Variables { event Result(uint256 result); uint256 qux; string quux; function stack(uint256 foo) public returns (uint256) { uint256 bar = foo + 1; uint256 baz = innerStack(bar); baz += 4; qux = baz; emit Result(baz); return baz; } function innerStack(uint256 baz) public returns (uint256) { uint256 bar = baz + 2; return bar; } } `; let sources = { "Variables.sol": __VARIABLES }; describe("AST", function () { var provider; var abstractions; var compilations; before("Create Provider", async function () { provider = Ganache.provider({ seed: "debugger", gasLimit: 7000000 }); }); before("Prepare contracts and artifacts", async function () { this.timeout(50000); let prepared = await prepareContracts(provider, sources); abstractions = prepared.abstractions; compilations = prepared.compilations; }); describe("Node pointer", function () { it("traverses", async function () { this.timeout(6000); let instance = await abstractions.Variables.deployed(); let receipt = await instance.stack(4); let txHash = receipt.tx; let bugger = await Debugger.forTx(txHash, { provider, compilations, lightMode: true }); do { let { start, length } = bugger.view(solidity.current.sourceRange); let end = start + length; let node = bugger.view(solidity.current.node); let [nodeStart, nodeLength] = SourceMapUtils.getRange(node); let nodeEnd = nodeStart + nodeLength; let pointer = bugger.view(solidity.current.pointer); assert.isAtMost( nodeStart, start, `Node ${pointer} at should not begin after instruction source range` ); assert.isAtLeast( nodeEnd, end, `Node ${pointer} should not end after source` ); await bugger.stepNext(); } while (!bugger.view(trace.finished)); }); }); });
print('1) проверка числа на простоту (простые числа - это те числа у которых делители единица и они сами);') def prime(n): i = 2 while n > i: if n % i == 0: return (n,'непростое число') i += 1 if i == n: return (n,'простое число') print(prime(51)) print(prime(17)) print('2) функция выводит список всех делителей числа:', 256) def denominator(n): result = [] n = n // 2 for i in range(1,n+1): if n % i == 0: result.append(i) return result print(denominator(256)) print('3) выводит самый большой простой делитель числа') from functools import reduce def max_denominator(n): max_number = denominator(n) max_number = reduce(lambda a,b: a if a>b else b, max_number) return(max_number) print(max_denominator(256))
from .detector3d_template import Detector3DTemplate import time import torch class PartA2Net(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset): super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset) self.module_list = self.build_networks() def forward(self, batch_dict): if self.training: for cur_module in self.module_list: batch_dict = cur_module(batch_dict) loss, tb_dict, disp_dict = self.get_training_loss() ret_dict = { 'loss': loss } return ret_dict, tb_dict, disp_dict else: torch.cuda.synchronize() start_time = time.perf_counter() for cur_module in self.module_list: batch_dict = cur_module(batch_dict) pred_dicts, recall_dicts = self.post_processing(batch_dict) torch.cuda.synchronize() elapsed = time.perf_counter() - start_time recall_dicts.update( {'total_time': elapsed} ) return pred_dicts, recall_dicts def get_training_loss(self): disp_dict = {} loss_rpn, tb_dict = self.dense_head.get_loss() loss_point, tb_dict = self.point_head.get_loss(tb_dict) loss_rcnn, tb_dict = self.roi_head.get_loss(tb_dict) loss = loss_rpn + loss_point + loss_rcnn return loss, tb_dict, disp_dict
import pylab import tables import math import numpy import findpeaks nx = 400 nt = 191 Ex_TX = numpy.zeros((nt+1, nx), numpy.float) for i in range(191): fh = tables.openFile("s74-icw_EM_%d.h5" % i) q = fh.root.StructGridField Ex = q[:,0] Ex_TX[i,:] = Ex
#! /usr/bin/python import math, random # Item prices items = [ 12.95, 18.95, 1.50, 6.50, 2.25, 2.95, 3.95, 4.50 ] random.seed(0) self_id = 0 order_id = 1 for i in range(1, 1560): date_id = random.randint(1,96) customer_id = random.randint(1,999) staff_id = random.randint(1,4) table_number = random.randint(1,5) items_in_order = random.randint(1,3) * [1] items_in_order = [random.randint(0, len(items)-1) for _ in items_in_order] for item in items_in_order: item_id = item+1 price = items[item] self_id += 1 print "%d;%d;%d;%d;%d;%d;%d;%.2f" % ( self_id, order_id, customer_id, staff_id,table_number,date_id, item_id, price) order_id += 1
""" Masked arrays add-ons. A collection of utilities for `numpy.ma`. :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu :version: $Id: extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ from __future__ import division, absolute_import, print_function __all__ = [ 'apply_along_axis', 'apply_over_axes', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'clump_masked', 'clump_unmasked', 'column_stack', 'compress_cols', 'compress_nd', 'compress_rowcols', 'compress_rows', 'count_masked', 'corrcoef', 'cov', 'diagflat', 'dot', 'dstack', 'ediff1d', 'flatnotmasked_contiguous', 'flatnotmasked_edges', 'hsplit', 'hstack', 'in1d', 'intersect1d', 'mask_cols', 'mask_rowcols', 'mask_rows', 'masked_all', 'masked_all_like', 'median', 'mr_', 'notmasked_contiguous', 'notmasked_edges', 'polyfit', 'row_stack', 'setdiff1d', 'setxor1d', 'unique', 'union1d', 'vander', 'vstack', ] import itertools import warnings from . import core as ma from .core import ( MaskedArray, MAError, add, array, asarray, concatenate, filled, count, getmask, getmaskarray, make_mask_descr, masked, masked_array, mask_or, nomask, ones, sort, zeros, getdata, get_masked_subclass, dot, mask_rowcols ) import numpy as np from numpy import ndarray, array as nxarray import numpy.core.umath as umath from numpy.lib.index_tricks import AxisConcatenator def issequence(seq): """ Is seq a sequence (ndarray, list or tuple)? """ if isinstance(seq, (ndarray, tuple, list)): return True return False def count_masked(arr, axis=None): """ Count the number of masked elements along the given axis. Parameters ---------- arr : array_like An array with (possibly) masked elements. axis : int, optional Axis along which to count. If None (default), a flattened version of the array is used. Returns ------- count : int, ndarray The total number of masked elements (axis=None) or the number of masked elements along each slice of the given axis. See Also -------- MaskedArray.count : Count non-masked elements. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(9).reshape((3,3)) >>> a = ma.array(a) >>> a[1, 0] = ma.masked >>> a[1, 2] = ma.masked >>> a[2, 1] = ma.masked >>> a masked_array(data = [[0 1 2] [-- 4 --] [6 -- 8]], mask = [[False False False] [ True False True] [False True False]], fill_value=999999) >>> ma.count_masked(a) 3 When the `axis` keyword is used an array is returned. >>> ma.count_masked(a, axis=0) array([1, 1, 1]) >>> ma.count_masked(a, axis=1) array([0, 2, 1]) """ m = getmaskarray(arr) return m.sum(axis) def masked_all(shape, dtype=float): """ Empty masked array with all elements masked. Return an empty masked array of the given shape and dtype, where all the data are masked. Parameters ---------- shape : tuple Shape of the required MaskedArray. dtype : dtype, optional Data type of the output. Returns ------- a : MaskedArray A masked array with all data masked. See Also -------- masked_all_like : Empty masked array modelled on an existing array. Examples -------- >>> import numpy.ma as ma >>> ma.masked_all((3, 3)) masked_array(data = [[-- -- --] [-- -- --] [-- -- --]], mask = [[ True True True] [ True True True] [ True True True]], fill_value=1e+20) The `dtype` parameter defines the underlying data type. >>> a = ma.masked_all((3, 3)) >>> a.dtype dtype('float64') >>> a = ma.masked_all((3, 3), dtype=np.int32) >>> a.dtype dtype('int32') """ a = masked_array(np.empty(shape, dtype), mask=np.ones(shape, make_mask_descr(dtype))) return a def masked_all_like(arr): """ Empty masked array with the properties of an existing array. Return an empty masked array of the same shape and dtype as the array `arr`, where all the data are masked. Parameters ---------- arr : ndarray An array describing the shape and dtype of the required MaskedArray. Returns ------- a : MaskedArray A masked array with all data masked. Raises ------ AttributeError If `arr` doesn't have a shape attribute (i.e. not an ndarray) See Also -------- masked_all : Empty masked array with all elements masked. Examples -------- >>> import numpy.ma as ma >>> arr = np.zeros((2, 3), dtype=np.float32) >>> arr array([[ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32) >>> ma.masked_all_like(arr) masked_array(data = [[-- -- --] [-- -- --]], mask = [[ True True True] [ True True True]], fill_value=1e+20) The dtype of the masked array matches the dtype of `arr`. >>> arr.dtype dtype('float32') >>> ma.masked_all_like(arr).dtype dtype('float32') """ a = np.empty_like(arr).view(MaskedArray) a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype)) return a #####-------------------------------------------------------------------------- #---- --- Standard functions --- #####-------------------------------------------------------------------------- class _fromnxfunction: """ Defines a wrapper to adapt NumPy functions to masked arrays. An instance of `_fromnxfunction` can be called with the same parameters as the wrapped NumPy function. The docstring of `newfunc` is adapted from the wrapped function as well, see `getdoc`. Parameters ---------- funcname : str The name of the function to be adapted. The function should be in the NumPy namespace (i.e. ``np.funcname``). """ def __init__(self, funcname): self.__name__ = funcname self.__doc__ = self.getdoc() def getdoc(self): """ Retrieve the docstring and signature from the function. The ``__doc__`` attribute of the function is used as the docstring for the new masked array version of the function. A note on application of the function to the mask is appended. .. warning:: If the function docstring already contained a Notes section, the new docstring will have two Notes sections instead of appending a note to the existing section. Parameters ---------- None """ npfunc = getattr(np, self.__name__, None) doc = getattr(npfunc, '__doc__', None) if doc: sig = self.__name__ + ma.get_object_signature(npfunc) locdoc = "Notes\n-----\nThe function is applied to both the _data"\ " and the _mask, if any." return '\n'.join((sig, doc, locdoc)) return def __call__(self, *args, **params): func = getattr(np, self.__name__) if len(args) == 1: x = args[0] if isinstance(x, ndarray): _d = func(x.__array__(), **params) _m = func(getmaskarray(x), **params) return masked_array(_d, mask=_m) elif isinstance(x, tuple) or isinstance(x, list): _d = func(tuple([np.asarray(a) for a in x]), **params) _m = func(tuple([getmaskarray(a) for a in x]), **params) return masked_array(_d, mask=_m) else: _d = func(np.asarray(x), **params) _m = func(getmaskarray(x), **params) return masked_array(_d, mask=_m) else: arrays = [] args = list(args) while len(args) > 0 and issequence(args[0]): arrays.append(args.pop(0)) res = [] for x in arrays: _d = func(np.asarray(x), *args, **params) _m = func(getmaskarray(x), *args, **params) res.append(masked_array(_d, mask=_m)) return res atleast_1d = _fromnxfunction('atleast_1d') atleast_2d = _fromnxfunction('atleast_2d') atleast_3d = _fromnxfunction('atleast_3d') #atleast_1d = np.atleast_1d #atleast_2d = np.atleast_2d #atleast_3d = np.atleast_3d vstack = row_stack = _fromnxfunction('vstack') hstack = _fromnxfunction('hstack') column_stack = _fromnxfunction('column_stack') dstack = _fromnxfunction('dstack') hsplit = _fromnxfunction('hsplit') diagflat = _fromnxfunction('diagflat') #####-------------------------------------------------------------------------- #---- #####-------------------------------------------------------------------------- def flatten_inplace(seq): """Flatten a sequence in place.""" k = 0 while (k != len(seq)): while hasattr(seq[k], '__iter__'): seq[k:(k + 1)] = seq[k] k += 1 return seq def apply_along_axis(func1d, axis, arr, *args, **kwargs): """ (This docstring should be overwritten) """ arr = array(arr, copy=False, subok=True) nd = arr.ndim if axis < 0: axis += nd if (axis >= nd): raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d." % (axis, nd)) ind = [0] * (nd - 1) i = np.zeros(nd, 'O') indlist = list(range(nd)) indlist.remove(axis) i[axis] = slice(None, None) outshape = np.asarray(arr.shape).take(indlist) i.put(indlist, ind) j = i.copy() res = func1d(arr[tuple(i.tolist())], *args, **kwargs) # if res is a number, then we have a smaller output array asscalar = np.isscalar(res) if not asscalar: try: len(res) except TypeError: asscalar = True # Note: we shouldn't set the dtype of the output from the first result # so we force the type to object, and build a list of dtypes. We'll # just take the largest, to avoid some downcasting dtypes = [] if asscalar: dtypes.append(np.asarray(res).dtype) outarr = zeros(outshape, object) outarr[tuple(ind)] = res Ntot = np.product(outshape) k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= outshape[n]) and (n > (1 - nd)): ind[n - 1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args, **kwargs) outarr[tuple(ind)] = res dtypes.append(asarray(res).dtype) k += 1 else: res = array(res, copy=False, subok=True) j = i.copy() j[axis] = ([slice(None, None)] * res.ndim) j.put(indlist, ind) Ntot = np.product(outshape) holdshape = outshape outshape = list(arr.shape) outshape[axis] = res.shape dtypes.append(asarray(res).dtype) outshape = flatten_inplace(outshape) outarr = zeros(outshape, object) outarr[tuple(flatten_inplace(j.tolist()))] = res k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= holdshape[n]) and (n > (1 - nd)): ind[n - 1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) j.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args, **kwargs) outarr[tuple(flatten_inplace(j.tolist()))] = res dtypes.append(asarray(res).dtype) k += 1 max_dtypes = np.dtype(np.asarray(dtypes).max()) if not hasattr(arr, '_mask'): result = np.asarray(outarr, dtype=max_dtypes) else: result = asarray(outarr, dtype=max_dtypes) result.fill_value = ma.default_fill_value(result) return result apply_along_axis.__doc__ = np.apply_along_axis.__doc__ def apply_over_axes(func, a, axes): """ (This docstring will be overwritten) """ val = asarray(a) N = a.ndim if array(axes).ndim == 0: axes = (axes,) for axis in axes: if axis < 0: axis = N + axis args = (val, axis) res = func(*args) if res.ndim == val.ndim: val = res else: res = ma.expand_dims(res, axis) if res.ndim == val.ndim: val = res else: raise ValueError("function is not returning " "an array of the correct shape") return val if apply_over_axes.__doc__ is not None: apply_over_axes.__doc__ = np.apply_over_axes.__doc__[ :np.apply_over_axes.__doc__.find('Notes')].rstrip() + \ """ Examples -------- >>> a = ma.arange(24).reshape(2,3,4) >>> a[:,0,1] = ma.masked >>> a[:,1,:] = ma.masked >>> print(a) [[[0 -- 2 3] [-- -- -- --] [8 9 10 11]] [[12 -- 14 15] [-- -- -- --] [20 21 22 23]]] >>> print(ma.apply_over_axes(ma.sum, a, [0,2])) [[[46] [--] [124]]] Tuple axis arguments to ufuncs are equivalent: >>> print(ma.sum(a, axis=(0,2)).reshape((1,-1,1))) [[[46] [--] [124]]] """ def average(a, axis=None, weights=None, returned=False): """ Return the weighted average of array over the given axis. Parameters ---------- a : array_like Data to be averaged. Masked entries are not taken into account in the computation. axis : int, optional Axis along which the average is computed. The default is to compute the average of the flattened array. weights : array_like, optional The importance that each element has in the computation of the average. The weights array can either be 1-D (in which case its length must be the size of `a` along the given axis) or of the same shape as `a`. If ``weights=None``, then all data in `a` are assumed to have a weight equal to one. If `weights` is complex, the imaginary parts are ignored. returned : bool, optional Flag indicating whether a tuple ``(result, sum of weights)`` should be returned as output (True), or just the result (False). Default is False. Returns ------- average, [sum_of_weights] : (tuple of) scalar or MaskedArray The average along the specified axis. When returned is `True`, return a tuple with the average as the first element and the sum of the weights as the second element. The return type is `np.float64` if `a` is of integer type and floats smaller than `float64`, or the input data-type, otherwise. If returned, `sum_of_weights` is always `float64`. Examples -------- >>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True]) >>> np.ma.average(a, weights=[3, 1, 0, 0]) 1.25 >>> x = np.ma.arange(6.).reshape(3, 2) >>> print(x) [[ 0. 1.] [ 2. 3.] [ 4. 5.]] >>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3], ... returned=True) >>> print(avg) [2.66666666667 3.66666666667] """ a = asarray(a) mask = a.mask ash = a.shape if ash == (): ash = (1,) if axis is None: if mask is nomask: if weights is None: n = a.sum(axis=None) d = float(a.size) else: w = filled(weights, 0.0).ravel() n = umath.add.reduce(a._data.ravel() * w) d = umath.add.reduce(w) del w else: if weights is None: n = a.filled(0).sum(axis=None) d = float(umath.add.reduce((~mask).ravel())) else: w = array(filled(weights, 0.0), float, mask=mask).ravel() n = add.reduce(a.ravel() * w) d = add.reduce(w) del w else: if mask is nomask: if weights is None: d = ash[axis] * 1.0 n = add.reduce(a._data, axis) else: w = filled(weights, 0.0) wsh = w.shape if wsh == (): wsh = (1,) if wsh == ash: w = np.array(w, float, copy=0) n = add.reduce(a * w, axis) d = add.reduce(w, axis) del w elif wsh == (ash[axis],): r = [None] * len(ash) r[axis] = slice(None, None, 1) w = eval("w[" + repr(tuple(r)) + "] * ones(ash, float)") n = add.reduce(a * w, axis) d = add.reduce(w, axis, dtype=float) del w, r else: raise ValueError('average: weights wrong shape.') else: if weights is None: n = add.reduce(a, axis) d = umath.add.reduce((~mask), axis=axis, dtype=float) else: w = filled(weights, 0.0) wsh = w.shape if wsh == (): wsh = (1,) if wsh == ash: w = array(w, dtype=float, mask=mask, copy=0) n = add.reduce(a * w, axis) d = add.reduce(w, axis, dtype=float) elif wsh == (ash[axis],): r = [None] * len(ash) r[axis] = slice(None, None, 1) w = eval("w[" + repr(tuple(r)) + "] * masked_array(ones(ash, float), mask)") n = add.reduce(a * w, axis) d = add.reduce(w, axis, dtype=float) else: raise ValueError('average: weights wrong shape.') del w if n is masked or d is masked: return masked result = n / d del n if isinstance(result, MaskedArray): if ((axis is None) or (axis == 0 and a.ndim == 1)) and \ (result.mask is nomask): result = result._data if returned: if not isinstance(d, MaskedArray): d = masked_array(d) if isinstance(d, ndarray) and (not d.shape == result.shape): d = ones(result.shape, dtype=float) * d if returned: return result, d else: return result def median(a, axis=None, out=None, overwrite_input=False): """ Compute the median along the specified axis. Returns the median of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : int, optional Axis along which the medians are computed. The default (None) is to compute the median along a flattened version of the array. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. overwrite_input : bool, optional If True, then allow use of memory of input array (a) for calculations. The input array will be modified by the call to median. This will save memory when you do not need to preserve the contents of the input array. Treat the input as undefined, but it will probably be fully or partially sorted. Default is False. Note that, if `overwrite_input` is True, and the input is not already an `ndarray`, an error will be raised. Returns ------- median : ndarray A new array holding the result is returned unless out is specified, in which case a reference to out is returned. Return data-type is `float64` for integers and floats smaller than `float64`, or the input data-type, otherwise. See Also -------- mean Notes ----- Given a vector ``V`` with ``N`` non masked values, the median of ``V`` is the middle value of a sorted copy of ``V`` (``Vs``) - i.e. ``Vs[(N-1)/2]``, when ``N`` is odd, or ``{Vs[N/2 - 1] + Vs[N/2]}/2`` when ``N`` is even. Examples -------- >>> x = np.ma.array(np.arange(8), mask=[0]*4 + [1]*4) >>> np.ma.median(x) 1.5 >>> x = np.ma.array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4) >>> np.ma.median(x) 2.5 >>> np.ma.median(x, axis=-1, overwrite_input=True) masked_array(data = [ 2. 5.], mask = False, fill_value = 1e+20) """ if not hasattr(a, 'mask') or np.count_nonzero(a.mask) == 0: return masked_array(np.median(getdata(a, subok=True), axis=axis, out=out, overwrite_input=overwrite_input), copy=False) if overwrite_input: if axis is None: asorted = a.ravel() asorted.sort() else: a.sort(axis=axis) asorted = a else: asorted = sort(a, axis=axis) if axis is None: axis = 0 elif axis < 0: axis += a.ndim if asorted.ndim == 1: idx, odd = divmod(count(asorted), 2) return asorted[idx - (not odd) : idx + 1].mean() counts = asorted.shape[axis] - (asorted.mask).sum(axis=axis) h = counts // 2 # create indexing mesh grid for all but reduced axis axes_grid = [np.arange(x) for i, x in enumerate(asorted.shape) if i != axis] ind = np.meshgrid(*axes_grid, sparse=True, indexing='ij') # insert indices of low and high median ind.insert(axis, h - 1) low = asorted[tuple(ind)] low._sharedmask = False ind[axis] = h high = asorted[tuple(ind)] # duplicate high if odd number of elements so mean does nothing odd = counts % 2 == 1 if asorted.ndim == 1: if odd: low = high else: low[odd] = high[odd] if np.issubdtype(asorted.dtype, np.inexact): # avoid inf / x = masked s = np.ma.sum([low, high], axis=0, out=out) np.true_divide(s.data, 2., casting='unsafe', out=s.data) else: s = np.ma.mean([low, high], axis=0, out=out) return s def compress_nd(x, axis=None): """Supress slices from multiple dimensions which contain masked values. Parameters ---------- x : array_like, MaskedArray The array to operate on. If not a MaskedArray instance (or if no array elements are masked, `x` is interpreted as a MaskedArray with `mask` set to `nomask`. axis : tuple of ints or int, optional Which dimensions to supress slices from can be configured with this parameter. - If axis is a tuple of ints, those are the axes to supress slices from. - If axis is an int, then that is the only axis to supress slices from. - If axis is None, all axis are selected. Returns ------- compress_array : ndarray The compressed array. """ x = asarray(x) m = getmask(x) # Set axis to tuple of ints if isinstance(axis, int): axis = (axis,) elif axis is None: axis = tuple(range(x.ndim)) elif not isinstance(axis, tuple): raise ValueError('Invalid type for axis argument') # Check axis input axis = [ax + x.ndim if ax < 0 else ax for ax in axis] if not all(0 <= ax < x.ndim for ax in axis): raise ValueError("'axis' entry is out of bounds") if len(axis) != len(set(axis)): raise ValueError("duplicate value in 'axis'") # Nothing is masked: return x if m is nomask or not m.any(): return x._data # All is masked: return empty if m.all(): return nxarray([]) # Filter elements through boolean indexing data = x._data for ax in axis: axes = tuple(list(range(ax)) + list(range(ax + 1, x.ndim))) data = data[(slice(None),)*ax + (~m.any(axis=axes),)] return data def compress_rowcols(x, axis=None): """ Suppress the rows and/or columns of a 2-D array that contain masked values. The suppression behavior is selected with the `axis` parameter. - If axis is None, both rows and columns are suppressed. - If axis is 0, only rows are suppressed. - If axis is 1 or -1, only columns are suppressed. Parameters ---------- x : array_like, MaskedArray The array to operate on. If not a MaskedArray instance (or if no array elements are masked), `x` is interpreted as a MaskedArray with `mask` set to `nomask`. Must be a 2D array. axis : int, optional Axis along which to perform the operation. Default is None. Returns ------- compressed_array : ndarray The compressed array. Examples -------- >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0], ... [1, 0, 0], ... [0, 0, 0]]) >>> x masked_array(data = [[-- 1 2] [-- 4 5] [6 7 8]], mask = [[ True False False] [ True False False] [False False False]], fill_value = 999999) >>> np.ma.compress_rowcols(x) array([[7, 8]]) >>> np.ma.compress_rowcols(x, 0) array([[6, 7, 8]]) >>> np.ma.compress_rowcols(x, 1) array([[1, 2], [4, 5], [7, 8]]) """ if asarray(x).ndim != 2: raise NotImplementedError("compress_rowcols works for 2D arrays only.") return compress_nd(x, axis=axis) def compress_rows(a): """ Suppress whole rows of a 2-D array that contain masked values. This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see `extras.compress_rowcols` for details. See Also -------- extras.compress_rowcols """ a = asarray(a) if a.ndim != 2: raise NotImplementedError("compress_rows works for 2D arrays only.") return compress_rowcols(a, 0) def compress_cols(a): """ Suppress whole columns of a 2-D array that contain masked values. This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see `extras.compress_rowcols` for details. See Also -------- extras.compress_rowcols """ a = asarray(a) if a.ndim != 2: raise NotImplementedError("compress_cols works for 2D arrays only.") return compress_rowcols(a, 1) def mask_rows(a, axis=None): """ Mask rows of a 2D array that contain masked values. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0. See Also -------- mask_rowcols : Mask rows and/or columns of a 2D array. masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.zeros((3, 3), dtype=np.int) >>> a[1, 1] = 1 >>> a array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) >>> a = ma.masked_equal(a, 1) >>> a masked_array(data = [[0 0 0] [0 -- 0] [0 0 0]], mask = [[False False False] [False True False] [False False False]], fill_value=999999) >>> ma.mask_rows(a) masked_array(data = [[0 0 0] [-- -- --] [0 0 0]], mask = [[False False False] [ True True True] [False False False]], fill_value=999999) """ return mask_rowcols(a, 0) def mask_cols(a, axis=None): """ Mask columns of a 2D array that contain masked values. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1. See Also -------- mask_rowcols : Mask rows and/or columns of a 2D array. masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.zeros((3, 3), dtype=np.int) >>> a[1, 1] = 1 >>> a array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) >>> a = ma.masked_equal(a, 1) >>> a masked_array(data = [[0 0 0] [0 -- 0] [0 0 0]], mask = [[False False False] [False True False] [False False False]], fill_value=999999) >>> ma.mask_cols(a) masked_array(data = [[0 -- 0] [0 -- 0] [0 -- 0]], mask = [[False True False] [False True False] [False True False]], fill_value=999999) """ return mask_rowcols(a, 1) #####-------------------------------------------------------------------------- #---- --- arraysetops --- #####-------------------------------------------------------------------------- def ediff1d(arr, to_end=None, to_begin=None): """ Compute the differences between consecutive elements of an array. This function is the equivalent of `numpy.ediff1d` that takes masked values into account, see `numpy.ediff1d` for details. See Also -------- numpy.ediff1d : Equivalent function for ndarrays. """ arr = ma.asanyarray(arr).flat ed = arr[1:] - arr[:-1] arrays = [ed] # if to_begin is not None: arrays.insert(0, to_begin) if to_end is not None: arrays.append(to_end) # if len(arrays) != 1: # We'll save ourselves a copy of a potentially large array in the common # case where neither to_begin or to_end was given. ed = hstack(arrays) # return ed def unique(ar1, return_index=False, return_inverse=False): """ Finds the unique elements of an array. Masked values are considered the same element (masked). The output array is always a masked array. See `numpy.unique` for more details. See Also -------- numpy.unique : Equivalent function for ndarrays. """ output = np.unique(ar1, return_index=return_index, return_inverse=return_inverse) if isinstance(output, tuple): output = list(output) output[0] = output[0].view(MaskedArray) output = tuple(output) else: output = output.view(MaskedArray) return output def intersect1d(ar1, ar2, assume_unique=False): """ Returns the unique elements common to both arrays. Masked values are considered equal one to the other. The output is always a masked array. See `numpy.intersect1d` for more details. See Also -------- numpy.intersect1d : Equivalent function for ndarrays. Examples -------- >>> x = array([1, 3, 3, 3], mask=[0, 0, 0, 1]) >>> y = array([3, 1, 1, 1], mask=[0, 0, 0, 1]) >>> intersect1d(x, y) masked_array(data = [1 3 --], mask = [False False True], fill_value = 999999) """ if assume_unique: aux = ma.concatenate((ar1, ar2)) else: # Might be faster than unique( intersect1d( ar1, ar2 ) )? aux = ma.concatenate((unique(ar1), unique(ar2))) aux.sort() return aux[:-1][aux[1:] == aux[:-1]] def setxor1d(ar1, ar2, assume_unique=False): """ Set exclusive-or of 1-D arrays with unique elements. The output is always a masked array. See `numpy.setxor1d` for more details. See Also -------- numpy.setxor1d : Equivalent function for ndarrays. """ if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = ma.concatenate((ar1, ar2)) if aux.size == 0: return aux aux.sort() auxf = aux.filled() # flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0 flag = ma.concatenate(([True], (auxf[1:] != auxf[:-1]), [True])) # flag2 = ediff1d( flag ) == 0 flag2 = (flag[1:] == flag[:-1]) return aux[flag2] def in1d(ar1, ar2, assume_unique=False, invert=False): """ Test whether each element of an array is also present in a second array. The output is always a masked array. See `numpy.in1d` for more details. See Also -------- numpy.in1d : Equivalent function for ndarrays. Notes ----- .. versionadded:: 1.4.0 """ if not assume_unique: ar1, rev_idx = unique(ar1, return_inverse=True) ar2 = unique(ar2) ar = ma.concatenate((ar1, ar2)) # We need this to be a stable sort, so always use 'mergesort' # here. The values from the first array should always come before # the values from the second array. order = ar.argsort(kind='mergesort') sar = ar[order] if invert: bool_ar = (sar[1:] != sar[:-1]) else: bool_ar = (sar[1:] == sar[:-1]) flag = ma.concatenate((bool_ar, [invert])) indx = order.argsort(kind='mergesort')[:len(ar1)] if assume_unique: return flag[indx] else: return flag[indx][rev_idx] def union1d(ar1, ar2): """ Union of two arrays. The output is always a masked array. See `numpy.union1d` for more details. See also -------- numpy.union1d : Equivalent function for ndarrays. """ return unique(ma.concatenate((ar1, ar2))) def setdiff1d(ar1, ar2, assume_unique=False): """ Set difference of 1D arrays with unique elements. The output is always a masked array. See `numpy.setdiff1d` for more details. See Also -------- numpy.setdiff1d : Equivalent function for ndarrays. Examples -------- >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1]) >>> np.ma.setdiff1d(x, [1, 2]) masked_array(data = [3 --], mask = [False True], fill_value = 999999) """ if assume_unique: ar1 = ma.asarray(ar1).ravel() else: ar1 = unique(ar1) ar2 = unique(ar2) return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)] ############################################################################### # Covariance # ############################################################################### def _covhelper(x, y=None, rowvar=True, allow_masked=True): """ Private function for the computation of covariance and correlation coefficients. """ x = ma.array(x, ndmin=2, copy=True, dtype=float) xmask = ma.getmaskarray(x) # Quick exit if we can't process masked data if not allow_masked and xmask.any(): raise ValueError("Cannot process masked data.") # if x.shape[0] == 1: rowvar = True # Make sure that rowvar is either 0 or 1 rowvar = int(bool(rowvar)) axis = 1 - rowvar if rowvar: tup = (slice(None), None) else: tup = (None, slice(None)) # if y is None: xnotmask = np.logical_not(xmask).astype(int) else: y = array(y, copy=False, ndmin=2, dtype=float) ymask = ma.getmaskarray(y) if not allow_masked and ymask.any(): raise ValueError("Cannot process masked data.") if xmask.any() or ymask.any(): if y.shape == x.shape: # Define some common mask common_mask = np.logical_or(xmask, ymask) if common_mask is not nomask: xmask = x._mask = y._mask = ymask = common_mask x._sharedmask = False y._sharedmask = False x = ma.concatenate((x, y), axis) xnotmask = np.logical_not(np.concatenate((xmask, ymask), axis)).astype(int) x -= x.mean(axis=rowvar)[tup] return (x, xnotmask, rowvar) def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None): """ Estimate the covariance matrix. Except for the handling of missing data this function does the same as `numpy.cov`. For more details and examples, see `numpy.cov`. By default, masked values are recognized as such. If `x` and `y` have the same shape, a common mask is allocated: if ``x[i,j]`` is masked, then ``y[i,j]`` will also be masked. Setting `allow_masked` to False will raise an exception if values are missing in either of the input arrays. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `x` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same form as `x`. rowvar : bool, optional If `rowvar` is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : bool, optional Default normalization (False) is by ``(N-1)``, where ``N`` is the number of observations given (unbiased estimate). If `bias` is True, then normalization is by ``N``. This keyword can be overridden by the keyword ``ddof`` in numpy versions >= 1.5. allow_masked : bool, optional If True, masked values are propagated pair-wise: if a value is masked in `x`, the corresponding value is masked in `y`. If False, raises a `ValueError` exception when some values are missing. ddof : {None, int}, optional If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is the number of observations; this overrides the value implied by ``bias``. The default value is ``None``. .. versionadded:: 1.5 Raises ------ ValueError Raised if some values are missing and `allow_masked` is False. See Also -------- numpy.cov """ # Check inputs if ddof is not None and ddof != int(ddof): raise ValueError("ddof must be an integer") # Set up ddof if ddof is None: if bias: ddof = 0 else: ddof = 1 (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked) if not rowvar: fact = np.dot(xnotmask.T, xnotmask) * 1. - ddof result = (dot(x.T, x.conj(), strict=False) / fact).squeeze() else: fact = np.dot(xnotmask, xnotmask.T) * 1. - ddof result = (dot(x, x.T.conj(), strict=False) / fact).squeeze() return result def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, allow_masked=True, ddof=np._NoValue): """ Return Pearson product-moment correlation coefficients. Except for the handling of missing data this function does the same as `numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`. Parameters ---------- x : array_like A 1-D or 2-D array containing multiple variables and observations. Each row of `x` represents a variable, and each column a single observation of all those variables. Also see `rowvar` below. y : array_like, optional An additional set of variables and observations. `y` has the same shape as `x`. rowvar : bool, optional If `rowvar` is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.10.0 allow_masked : bool, optional If True, masked values are propagated pair-wise: if a value is masked in `x`, the corresponding value is masked in `y`. If False, raises an exception. Because `bias` is deprecated, this argument needs to be treated as keyword only to avoid a warning. ddof : _NoValue, optional Has no effect, do not use. .. deprecated:: 1.10.0 See Also -------- numpy.corrcoef : Equivalent function in top-level NumPy module. cov : Estimate the covariance matrix. Notes ----- This function accepts but discards arguments `bias` and `ddof`. This is for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy. """ msg = 'bias and ddof have no effect and are deprecated' if bias is not np._NoValue or ddof is not np._NoValue: # 2015-03-15, 1.10 warnings.warn(msg, DeprecationWarning) # Get the data (x, xnotmask, rowvar) = _covhelper(x, y, rowvar, allow_masked) # Compute the covariance matrix if not rowvar: fact = np.dot(xnotmask.T, xnotmask) * 1. c = (dot(x.T, x.conj(), strict=False) / fact).squeeze() else: fact = np.dot(xnotmask, xnotmask.T) * 1. c = (dot(x, x.T.conj(), strict=False) / fact).squeeze() # Check whether we have a scalar try: diag = ma.diagonal(c) except ValueError: return 1 # if xnotmask.all(): _denom = ma.sqrt(ma.multiply.outer(diag, diag)) else: _denom = diagflat(diag) _denom._sharedmask = False # We know return is always a copy n = x.shape[1 - rowvar] if rowvar: for i in range(n - 1): for j in range(i + 1, n): _x = mask_cols(vstack((x[i], x[j]))).var(axis=1) _denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x)) else: for i in range(n - 1): for j in range(i + 1, n): _x = mask_cols( vstack((x[:, i], x[:, j]))).var(axis=1) _denom[i, j] = _denom[j, i] = ma.sqrt(ma.multiply.reduce(_x)) return c / _denom #####-------------------------------------------------------------------------- #---- --- Concatenation helpers --- #####-------------------------------------------------------------------------- class MAxisConcatenator(AxisConcatenator): """ Translate slice objects to concatenation along an axis. For documentation on usage, see `mr_class`. See Also -------- mr_class """ def __init__(self, axis=0): AxisConcatenator.__init__(self, axis, matrix=False) def __getitem__(self, key): if isinstance(key, str): raise MAError("Unavailable for masked array.") if not isinstance(key, tuple): key = (key,) objs = [] scalars = [] final_dtypedescr = None for k in range(len(key)): scalar = False if isinstance(key[k], slice): step = key[k].step start = key[k].start stop = key[k].stop if start is None: start = 0 if step is None: step = 1 if isinstance(step, complex): size = int(abs(step)) newobj = np.linspace(start, stop, num=size) else: newobj = np.arange(start, stop, step) elif isinstance(key[k], str): if (key[k] in 'rc'): self.matrix = True self.col = (key[k] == 'c') continue try: self.axis = int(key[k]) continue except (ValueError, TypeError): raise ValueError("Unknown special directive") elif type(key[k]) in np.ScalarType: newobj = asarray([key[k]]) scalars.append(k) scalar = True else: newobj = key[k] objs.append(newobj) if isinstance(newobj, ndarray) and not scalar: if final_dtypedescr is None: final_dtypedescr = newobj.dtype elif newobj.dtype > final_dtypedescr: final_dtypedescr = newobj.dtype if final_dtypedescr is not None: for k in scalars: objs[k] = objs[k].astype(final_dtypedescr) res = concatenate(tuple(objs), axis=self.axis) return self._retval(res) class mr_class(MAxisConcatenator): """ Translate slice objects to concatenation along the first axis. This is the masked array version of `lib.index_tricks.RClass`. See Also -------- lib.index_tricks.RClass Examples -------- >>> np.ma.mr_[np.ma.array([1,2,3]), 0, 0, np.ma.array([4,5,6])] array([1, 2, 3, 0, 0, 4, 5, 6]) """ def __init__(self): MAxisConcatenator.__init__(self, 0) mr_ = mr_class() #####-------------------------------------------------------------------------- #---- Find unmasked data --- #####-------------------------------------------------------------------------- def flatnotmasked_edges(a): """ Find the indices of the first and last unmasked values. Expects a 1-D `MaskedArray`, returns None if all values are masked. Parameters ---------- a : array_like Input 1-D `MaskedArray` Returns ------- edges : ndarray or None The indices of first and last non-masked value in the array. Returns None if all values are masked. See Also -------- flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges, clump_masked, clump_unmasked Notes ----- Only accepts 1-D arrays. Examples -------- >>> a = np.ma.arange(10) >>> flatnotmasked_edges(a) [0,-1] >>> mask = (a < 3) | (a > 8) | (a == 5) >>> a[mask] = np.ma.masked >>> np.array(a[~a.mask]) array([3, 4, 6, 7, 8]) >>> flatnotmasked_edges(a) array([3, 8]) >>> a[:] = np.ma.masked >>> print(flatnotmasked_edges(ma)) None """ m = getmask(a) if m is nomask or not np.any(m): return np.array([0, a.size - 1]) unmasked = np.flatnonzero(~m) if len(unmasked) > 0: return unmasked[[0, -1]] else: return None def notmasked_edges(a, axis=None): """ Find the indices of the first and last unmasked values along an axis. If all values are masked, return None. Otherwise, return a list of two tuples, corresponding to the indices of the first and last unmasked values respectively. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- edges : ndarray or list An array of start and end indexes if there are any masked data in the array. If there are no masked data in the array, `edges` is a list of the first and last index. See Also -------- flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous, clump_masked, clump_unmasked Examples -------- >>> a = np.arange(9).reshape((3, 3)) >>> m = np.zeros_like(a) >>> m[1:, 1:] = 1 >>> am = np.ma.array(a, mask=m) >>> np.array(am[~am.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.notmasked_edges(ma) array([0, 6]) """ a = asarray(a) if axis is None or a.ndim == 1: return flatnotmasked_edges(a) m = getmaskarray(a) idx = array(np.indices(a.shape), mask=np.asarray([m] * a.ndim)) return [tuple([idx[i].min(axis).compressed() for i in range(a.ndim)]), tuple([idx[i].max(axis).compressed() for i in range(a.ndim)]), ] def flatnotmasked_contiguous(a): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : narray The input array. Returns ------- slice_list : list A sorted sequence of slices (start index, end index). See Also -------- flatnotmasked_edges, notmasked_contiguous, notmasked_edges, clump_masked, clump_unmasked Notes ----- Only accepts 2-D arrays at most. Examples -------- >>> a = np.ma.arange(10) >>> np.ma.flatnotmasked_contiguous(a) slice(0, 10, None) >>> mask = (a < 3) | (a > 8) | (a == 5) >>> a[mask] = np.ma.masked >>> np.array(a[~a.mask]) array([3, 4, 6, 7, 8]) >>> np.ma.flatnotmasked_contiguous(a) [slice(3, 5, None), slice(6, 9, None)] >>> a[:] = np.ma.masked >>> print(np.ma.flatnotmasked_edges(a)) None """ m = getmask(a) if m is nomask: return slice(0, a.size, None) i = 0 result = [] for (k, g) in itertools.groupby(m.ravel()): n = len(list(g)) if not k: result.append(slice(i, i + n)) i += n return result or None def notmasked_contiguous(a, axis=None): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- endpoints : list A list of slices (start and end indexes) of unmasked indexes in the array. See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, clump_masked, clump_unmasked Notes ----- Only accepts 2-D arrays at most. Examples -------- >>> a = np.arange(9).reshape((3, 3)) >>> mask = np.zeros_like(a) >>> mask[1:, 1:] = 1 >>> ma = np.ma.array(a, mask=mask) >>> np.array(ma[~ma.mask]) array([0, 1, 2, 3, 6]) >>> np.ma.notmasked_contiguous(ma) [slice(0, 4, None), slice(6, 7, None)] """ a = asarray(a) nd = a.ndim if nd > 2: raise NotImplementedError("Currently limited to atmost 2D array.") if axis is None or nd == 1: return flatnotmasked_contiguous(a) # result = [] # other = (axis + 1) % 2 idx = [0, 0] idx[axis] = slice(None, None) # for i in range(a.shape[other]): idx[other] = i result.append(flatnotmasked_contiguous(a[idx]) or None) return result def _ezclump(mask): """ Finds the clumps (groups of data with the same values) for a 1D bool array. Returns a series of slices. """ if mask.ndim > 1: mask = mask.ravel() idx = (mask[1:] ^ mask[:-1]).nonzero() idx = idx[0] + 1 if mask[0]: if len(idx) == 0: return [slice(0, mask.size)] r = [slice(0, idx[0])] r.extend((slice(left, right) for left, right in zip(idx[1:-1:2], idx[2::2]))) else: if len(idx) == 0: return [] r = [slice(left, right) for left, right in zip(idx[:-1:2], idx[1::2])] if mask[-1]: r.append(slice(idx[-1], mask.size)) return r def clump_unmasked(a): """ Return list of slices corresponding to the unmasked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, one for each continuous region of unmasked elements in `a`. Notes ----- .. versionadded:: 1.4.0 See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, notmasked_contiguous, clump_masked Examples -------- >>> a = np.ma.masked_array(np.arange(10)) >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked >>> np.ma.clump_unmasked(a) [slice(3, 6, None), slice(7, 8, None)] """ mask = getattr(a, '_mask', nomask) if mask is nomask: return [slice(0, a.size)] return _ezclump(~mask) def clump_masked(a): """ Returns a list of slices corresponding to the masked clumps of a 1-D array. (A "clump" is defined as a contiguous region of the array). Parameters ---------- a : ndarray A one-dimensional masked array. Returns ------- slices : list of slice The list of slices, one for each continuous region of masked elements in `a`. Notes ----- .. versionadded:: 1.4.0 See Also -------- flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, notmasked_contiguous, clump_unmasked Examples -------- >>> a = np.ma.masked_array(np.arange(10)) >>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked >>> np.ma.clump_masked(a) [slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)] """ mask = ma.getmask(a) if mask is nomask: return [] return _ezclump(mask) ############################################################################### # Polynomial fit # ############################################################################### def vander(x, n=None): """ Masked values in the input array result in rows of zeros. """ _vander = np.vander(x, n) m = getmask(x) if m is not nomask: _vander[m] = 0 return _vander vander.__doc__ = ma.doc_note(np.vander.__doc__, vander.__doc__) def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): """ Any masked values in x is propagated in y, and vice-versa. """ x = asarray(x) y = asarray(y) m = getmask(x) if y.ndim == 1: m = mask_or(m, getmask(y)) elif y.ndim == 2: my = getmask(mask_rows(y)) if my is not nomask: m = mask_or(m, my[:, 0]) else: raise TypeError("Expected a 1D or 2D array for y!") if w is not None: w = asarray(w) if w.ndim != 1: raise TypeError("expected a 1-d array for weights") if w.shape[0] != y.shape[0]: raise TypeError("expected w and y to have the same length") m = mask_or(m, getmask(w)) if m is not nomask: not_m = ~m if w is not None: w = w[not_m] return np.polyfit(x[not_m], y[not_m], deg, rcond, full, w, cov) else: return np.polyfit(x, y, deg, rcond, full, w, cov) polyfit.__doc__ = ma.doc_note(np.polyfit.__doc__, polyfit.__doc__)
'use strict'; var xmpp = require('../index') , assert = require('assert') , Client = require('node-xmpp-client') , Message = require('node-xmpp-core').Stanza.Message var eventChain = [] var c2s = null function startServer(done) { // Sets up the server. c2s = new xmpp.C2SServer({ port: 5222, domain: 'localhost' }) c2s.on('error', function(err) { console.log('c2s error: ' + err.message) }) c2s.on('connect', function(client) { c2s.on('register', function(opts, cb) { cb(new Error('register not supported')) }) // allow anything client.on('authenticate', function(opts, cb) { eventChain.push('authenticate') cb(null, opts) }) client.on('online', function() { eventChain.push('online') }) client.on('stanza', function() { eventChain.push('stanza') client.send( new Message({ type: 'chat' }) .c('body') .t('Hello there, little client.') ) }) client.on('disconnect', function() { eventChain.push('disconnect') }) client.on('end', function() { eventChain.push('end') }) client.on('close', function() { eventChain.push('close') }) client.on('error', function() { eventChain.push('error') }) }) done() } describe('C2Server', function() { var cl = null before(function(done) { startServer(done) }) after(function(done) { c2s.shutdown(done) }) describe('events', function() { it('should be in the right order for connecting', function(done) { eventChain = [] //clientCallback = done cl = new Client({ jid: 'bob@example.com', password: 'alice', host: 'localhost' }) cl.on('online', function() { eventChain.push('clientonline') assert.deepEqual(eventChain, ['authenticate', 'online', 'clientonline']) done() }) cl.on('error', function(e) { done(e) }) }) it('should ping pong stanza', function(done) { eventChain = [] cl.on('stanza', function() { eventChain.push('clientstanza') assert.deepEqual(eventChain, ['stanza', 'clientstanza']) done() }) cl.send( new Message({ type: 'chat' }) .c('body') .t('Hello there, little server.') ) cl.on('error', function(e) { done(e) }) }) it('should close the connection', function(done) { eventChain = [] // end xmpp stream cl.on('end', function() { eventChain.push('clientend') }) // close socket cl.on('close', function() { eventChain.push('clientclose') assert.deepEqual(eventChain, ['end', 'disconnect', 'close', 'clientend', 'clientclose']) done() }) cl.end() }) }) })
class Reg: def __init__(self): """ Entrada: Nada Operacao: Inicia o objeto dos Registradores com todos os campos zerados, Construtor Saida: Objeto dos Registradores """ # h | opc | tos | cpp | lv | sp | pc | mdr | mar | mbr self.registers = [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0] def get_register(self, register): """ Entrada: register: Inteiro ou String => Registrador a ser acessado Operacao: Acessa o registrador especificado Saida: Valor do registrador especificado: Inteiro """ if(type(register) is int): return self.registers[register] if(type(register) is str): reg_names = ["mar", "mdr", "pc", "mbr" , "sp", "lv" , "cpp", "tos", "opc", "h"] return self.registers[reg_names.index(register)] def set_register(self, register, value): """ Entrada: register: Inteiro ou String => Registrador a ser editado value: Inteiro => Valor a ser atribuido ao registrador Operacao: Altera o valor do registrador especificado Saida: Nada """ if(type(register) is int): self.registers[register] = value if(type(register) is str): reg_names = ["mar", "mdr", "pc", "mbr" , "sp", "lv" , "cpp", "tos", "opc", "h"] self.registers[reg_names.index(register)] = value
import { setupServer } from 'msw/node' import { handlers } from './handlers' export const server = setupServer(...handlers)
// Template Code Start "use strict" // Just for Fun! console.log('%c Stop Right There! ', 'background: #222; color: orange;font-size:20px'); console.log('%c You Shall Not Pass! ', 'background: #222; color: red; font-size:40px'); // Template Code End setTimeout(() => { $('#message').hide(); }, 5000); $(window).scroll(function () { let documentHeight = $(document).height(); let windowHeight = $(window).height(); let scrollableDistance = documentHeight - windowHeight; let stepHeight = (scrollableDistance) / 8; // Why divide by 8? Because we have 4 containers in 1 window height and // the division by 8 helps us to calculate the mid of scroll for each container to display on var scroll = Math.ceil($(window).scrollTop()); // Below code is to resolve android chrome issue if (navigator.userAgent.toLocaleLowerCase().toString().indexOf('android') > 0) { scroll += 57; } let activeIndex = Math.floor(scroll / stepHeight); // Below code allows for last element to stay visible when you scroll till end if (activeIndex == $('.container').length) { activeIndex = $('.container').length - 1; } // console.debug( // "documentHeight:",documentHeight, // "windowHeight:",windowHeight, // "scrollableDistance:",scrollableDistance, // "stepHeight:",stepHeight, // "scroll:",scroll, // "activeIndex:",activeIndex, // "Math.floor(scroll / stepHeight):",Math.floor(scroll / stepHeight), // "$('.container').length:",$('.container').length // ); $('.leftcurtain').css({ left: 0 }); $('.leftcurtain:eq(' + activeIndex + ')').css({ left: '-50vw' }); $('.rightcurtain').css({ right: 0 }); $('.rightcurtain:eq(' + activeIndex + ')').css({ right: '-50vw' }); })
(window.webpackJsonp=window.webpackJsonp||[]).push([[22],{418:function(a,t,s){"use strict";s.r(t);var e=s(55),n=Object(e.a)({},(function(){var a=this,t=a.$createElement,s=a._self._c||t;return s("ContentSlotsDistributor",{attrs:{"slot-key":a.$parent.slotKey}},[s("h1",{attrs:{id:"validation"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#validation"}},[a._v("#")]),a._v(" Validation")]),a._v(" "),s("p",[a._v("Caliban provides a little macro called "),s("code",[a._v("gqldoc")]),a._v(" that can check at "),s("strong",[a._v("compile-time")]),a._v(" that a GraphQL query (a "),s("em",[a._v("document")]),a._v(" to be exact) has valid syntax.")]),a._v(" "),s("div",{staticClass:"language-scala extra-class"},[s("pre",{pre:!0,attrs:{class:"language-scala"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[a._v("import")]),a._v(" "),s("span",{pre:!0,attrs:{class:"token namespace"}},[a._v("caliban"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v(".")])]),a._v("Macros"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v(".")]),a._v("gqldoc\n\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[a._v("val")]),a._v(" query "),s("span",{pre:!0,attrs:{class:"token operator"}},[a._v("=")]),a._v(" gqldoc"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v("(")]),s("span",{pre:!0,attrs:{class:"token triple-quoted-string string"}},[a._v('"""\n query test {\n amos: character(name: "Amos Burton") {\n name\n }\n }"""')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v(")")]),a._v("\n")])])]),s("p",[a._v("At "),s("strong",[a._v("runtime")]),a._v(", it is possible to validate a query against your schema by calling the method "),s("code",[a._v("check")]),a._v(" on your API.")]),a._v(" "),s("div",{staticClass:"language-scala extra-class"},[s("pre",{pre:!0,attrs:{class:"language-scala"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[a._v("def")]),a._v(" check"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v("(")]),a._v("query"),s("span",{pre:!0,attrs:{class:"token operator"}},[a._v(":")]),a._v(" "),s("span",{pre:!0,attrs:{class:"token builtin"}},[a._v("String")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v(")")]),s("span",{pre:!0,attrs:{class:"token operator"}},[a._v(":")]),a._v(" IO"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v("[")]),a._v("CalibanError"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v(",")]),a._v(" "),s("span",{pre:!0,attrs:{class:"token builtin"}},[a._v("Unit")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[a._v("]")]),a._v("\n")])])]),s("p",[a._v("It is also possible to skip validation when executing a query by passing "),s("code",[a._v("skipValidation = true")]),a._v(" when calling "),s("code",[a._v("execute")]),a._v(" (also available in the adapters). This will slightly improve performance.")])])}),[],!1,null,null,null);t.default=n.exports}}]);
const baseF = '-__v -created_at -updated_at -password'; const userF = `${baseF} -roles`; const roleF = baseF; const personF = `${baseF} -user`; const arbiterF = `${baseF} -user`; const athleteF = `${baseF} -user -federation`; const tournamentF = `${baseF} -federation -athletes -coaches -arbiters`; const federationF = baseF; const clubF = baseF; function filterDoc(doc, filter) { filter.split(' ').map((item) => { const prop = item.replace('-', ''); delete doc[prop]; }); return doc; } module.exports = { baseF, userF, roleF, personF, arbiterF, athleteF, tournamentF, federationF, clubF, filterDoc, };
from django.db import models # Create your models here. class Category(models.Model): category = models.CharField(max_length = 30, blank = True) def __str__(self): return self.category def save_category(self): self.save() @classmethod def update_category(cls,name,update): Category.objects.filter(category=name).update(category=update) update=Category.objects.get(category=update) return update @classmethod def delete_category(cls,category): Category.objects.get(category=category).delete() class Location(models.Model): location = models.CharField(max_length = 30, null = True) def __str__(self): return self.location def save_location(self): self.save() @classmethod def update_location(cls,name,update): Location.objects.filter(location=name).update(location=update) updated=Location.objects.get(location=update) return updated @classmethod def delete_location(cls,location): deleted=Location.objects.get(location=location).delete() return deleted class Image(models.Model): name = models.CharField(max_length = 30, blank = True) description = models.TextField() image = models.ImageField(upload_to = 'blog/', blank = True) category = models.ForeignKey('Category',on_delete = models.CASCADE,null =True) location = models.ForeignKey('Location',on_delete = models.CASCADE,null = True) def __str__(self): return self.name def save_name(self): self.save() @classmethod def search_by_category(cls,search_term): fine = cls.objects.filter(category__category__icontains=search_term) return fine
/* * Copyright (C) 2021 mod.io Pty Ltd. <https://mod.io> * * This file is part of the mod.io SDK. * * Distributed under the MIT License. (See accompanying file LICENSE or * view online at <https://github.com/modio/modio-sdk/blob/main/LICENSE>) * */ #pragma once #include "modio/core/ModioLogger.h" #include "modio/core/ModioModCollectionEntry.h" #include "modio/core/ModioServices.h" #include "modio/core/ModioStdTypes.h" #include "modio/detail/ops/SaveModCollectionToStorage.h" #include "modio/detail/ops/UnsubscribeFromMod.h" #include "modio/detail/ops/modmanagement/FetchUserSubscriptionsFromServer.h" #include "modio/file/ModioFileService.h" #include "modio/userdata/ModioUserDataService.h" #include <algorithm> #include <asio/coroutine.hpp> #include <asio/yield.hpp> #include <map> namespace Modio { namespace Detail { class FetchExternalUpdatesOp { public: template<typename CoroType> void operator()(CoroType& Self, Modio::ErrorCode ec = {}, Modio::Optional<Modio::ModInfoList> ServerSubscriptionList = {}) { Modio::Detail::UserDataService& UserService = Modio::Detail::Services::GetGlobalService<Modio::Detail::UserDataService>(); reenter(CoroutineState) { if (!Modio::Detail::SDKSessionData::GetAuthenticatedUser()) { Self.complete(Modio::make_error_code(Modio::UserDataError::InvalidUser)); return; } while (Modio::Detail::SDKSessionData::HasDeferredUnsubscriptions()) { CurrentPendingUnsubscribe = Modio::Detail::SDKSessionData::GetDeferredUnsubscription(); yield Modio::Detail::UnsubscribeFromModAsync(CurrentPendingUnsubscribe, std::move(Self)); if (ec) { Self.complete(ec); return; } else { Modio::Detail::SDKSessionData::RemoveDeferredUnsubscription(CurrentPendingUnsubscribe); } } yield FetchUserSubscriptionsFromServerAsync(std::move(Self)); if (ec) { Self.complete(ec); return; } { Modio::UserSubscriptionList ServerSubscriptionModIDs; std::map<Modio::ModID, Modio::ModInfo> ServerSubsModProfiles; if (!ServerSubscriptionList) { Self.complete(ec); return; } for (Modio::ModInfo& Profile : ServerSubscriptionList.value()) { ServerSubscriptionModIDs.AddMod(Profile); ServerSubsModProfiles[Profile.ModId] = Profile; Modio::Detail::SDKSessionData::GetSystemModCollection().AddOrUpdateMod( Profile, Modio::Detail::Services::GetGlobalService<Modio::Detail::FileService>().MakeModPath( Profile.ModId)); } std::map<Modio::ModID, Modio::UserSubscriptionList::ChangeType> ModListDiff = UserSubscriptionList::CalculateChanges( Modio::Detail::SDKSessionData::GetUserSubscriptions(), ServerSubscriptionModIDs); bDirtyState = ModListDiff.size() > 0; for (auto ModChange : ModListDiff) { if (ModChange.second == Modio::UserSubscriptionList::ChangeType::Added) { Modio::Detail::SDKSessionData::GetUserSubscriptions().AddMod( ServerSubsModProfiles.at(ModChange.first)); Modio::Optional<Modio::ModCollectionEntry&> ModEntry = Modio::Detail::SDKSessionData::GetSystemModCollection().GetByModID(ModChange.first); if (ModEntry.has_value()) { ModEntry->AddLocalUserSubscription( Modio::Detail::SDKSessionData::GetAuthenticatedUser()); } Modio::Detail::Logger().Log(LogLevel::Info, LogCategory::ModManagement, "External update adding {} to local user subscriptions", ModChange.first); } else if (ModChange.second == Modio::UserSubscriptionList::ChangeType::Removed) { Modio::Detail::SDKSessionData::GetUserSubscriptions().RemoveMod(ModChange.first); Modio::Optional<Modio::ModCollectionEntry&> ModEntry = Modio::Detail::SDKSessionData::GetSystemModCollection().GetByModID(ModChange.first); if (ModEntry.has_value()) { ModEntry->RemoveLocalUserSubscription( Modio::Detail::SDKSessionData::GetAuthenticatedUser()); } Modio::Detail::Logger().Log(LogLevel::Info, LogCategory::ModManagement, "External update removing {} from local user subscriptions", ModChange.first); } } } if (bDirtyState) { // Only save to storage if we actually have any changes to flush yield UserService.SaveUserDataToStorageAsync(std::move(Self)); bDirtyState = false; } // Always save the mod collection to storage yield Modio::Detail::SaveModCollectionToStorageAsync(std::move(Self)); Self.complete({}); return; } } private: asio::coroutine CoroutineState; Modio::ModID CurrentPendingUnsubscribe; bool bDirtyState = false; }; template<typename FetchDoneCallback> auto FetchExternalUpdatesAsync(FetchDoneCallback&& OnFetchComplete) { return asio::async_compose<FetchDoneCallback, void(Modio::ErrorCode)>( FetchExternalUpdatesOp(), OnFetchComplete, Modio::Detail::Services::GetGlobalContext().get_executor()); } } // namespace Detail } // namespace Modio #include <asio/unyield.hpp>
// -- videPlayer // @license videPlayer v1.0.0 | MIT | Namogo 2017 | https://www.namogo.com // -------------------------------- (function($) { $.audioPlayer = function(element, options) { var defaults = { volume : 0.5, controls : '.ee-player__controls', playlist : '.ee-player__playlist', tracks : '.ee-player__playlist__item', trackDuration : '.ee-player__playlist__item__duration', bar : '.ee-player__controls__bar-wrapper', controlPrevious : '.ee-player__controls__previous', controlPlay : '.ee-player__controls__play', controlNext : '.ee-player__controls__next', controlRewind : '.ee-player__controls__rewind', controlTime : '.ee-player__controls__time', controlDuration : '.ee-player__controls__duration', controlBrowse : '.ee-player__controls__browse', controlProgressBar : '.ee-player__controls__progress', controlProgress : '.ee-player__controls__progress-time', controlVolumeBar : '.ee-player__controls__volume-bar', controlVolume : '.ee-player__controls__volume-bar__amount', controlVolumeIcon : '.ee-player__controls__volume-icon', playOnViewport : false, stopOffViewport : false, loopPlaylist : false, stopOthersOnPlay : true, }; var plugin = this; plugin.opts = {}; var $document = $( document ), $wrapper = $( element ), $audios = $wrapper.find('audio'), $audio = null, $controls = null, $playlist = null, $tracks = null, $bar = null, $controlPlay = null, $controlRewind = null, $controlTime = null, $controlDuration = null, $controlBrowse = null, $controlProgressBar = null, $controlProgress = null, $controlVolumeBar = null, $controlVolume = null, $controlVolumeIcon = null, controlRewind = null, controlPlay = null, audio = null, volume = null, _current = 0, _next = 0, _previous = 0, _total = 0, _is_dragging_time = false, _is_dragging_volume = false, _is_playing = false, _is_loaded = false, _is_ios = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream, _is_ios_played = false, _drag_time_amount = 0; plugin.init = function() { plugin.opts = $.extend({}, defaults, options); plugin._construct(); }; plugin._construct = function() { $controls = $wrapper.find( plugin.opts.controls ); $playlist = $wrapper.find( plugin.opts.playlist ); $tracks = $wrapper.find( plugin.opts.tracks ); $bar = $wrapper.find( plugin.opts.bar ); $controlRewind = $controls.find( plugin.opts.controlRewind ); $controlPrevious = $controls.find( plugin.opts.controlPrevious ); $controlPlay = $controls.find( plugin.opts.controlPlay ); $controlNext = $controls.find( plugin.opts.controlNext ); $controlDuration = $controls.find( plugin.opts.controlDuration ); $controlBrowse = $controls.find( plugin.opts.controlBrowse ); $controlTime = $controls.find( plugin.opts.controlTime ); $controlProgress = $controls.find( plugin.opts.controlProgress); $controlProgressBar = $controls.find( plugin.opts.controlProgressBar); $controlVolume = $controls.find( plugin.opts.controlVolume); $controlVolumeBar = $controls.find( plugin.opts.controlVolumeBar); $controlVolumeIcon = $controls.find( plugin.opts.controlVolumeIcon); volume = plugin.opts.volume; _total = $tracks.length; if ( $controls.length ) { controlPlay = $controlPlay.get(0); if ( $controlRewind.length ) controlRewind = $controlRewind.get(0); } if ( _total === 0 ) { return; } // Bind events plugin.setup(); // Set audio to first trac plugin.setTrack( _current ); // Bind events plugin.events(); // Set audio to first trac plugin.loadTrack(); // Setup progress interactions plugin.initProgressBar(); // Setup volume interactions plugin.initVolumeBar(); }; plugin.events = function() { if ( $controlPlay.length ) $controlPlay.on( 'click', plugin.maybePlay ); if ( _total > 1 ) { if ( $controlPrevious.length ) $controlPrevious.on( 'click', function() { plugin.playTrack( _previous ); }); if ( $controlNext.length ) $controlNext.on( 'click', function() { plugin.playTrack( _next ); }); } if ( $controlRewind.length ) $controlRewind.on( 'click', plugin.restart ); if ( $controlBrowse.length ) $controlBrowse.on( 'click', function() { $playlist.toggle(); }); if ( $playlist.length ) { $tracks.on( 'click', function() { plugin.playTrack( $(this).index() ); }); } }; plugin.setup = function() { $tracks.each( function() { var $track = $(this), $_audio = $track.find( 'audio' ); // Loop through the audios $_audio.each( function() { var _audio = this; // Load each audio file _audio.load(); // When meta data available $(this).on( "loadedmetadata", function( e ) { // Set duration for each audio var $_duration = $track.find( plugin.opts.trackDuration ); $_duration.html( plugin.formatTime( _audio.duration, true ) ); }); }); }); }; plugin.setTrack = function( index ) { _current = index; _next = ( index === _total - 1 ) ? 0 : index + 1; _previous = ( index === 0 ) ? _total : index - 1; $audio = $audios.eq( _current ); audio = $audio.get(0); // Remove and add active classes $tracks .removeClass( 'ee--is-active' ).eq( index ) .addClass( 'ee--is-active' ); }; plugin.loadTrack = function() { // Make sure audio is loaded on iOS audio.load(); audio.addEventListener( "loadedmetadata", plugin.initAudio ); // Update time controls audio.addEventListener( 'timeupdate', plugin.updateTime ); // Check if audio completed laoded audio.addEventListener( 'canplaythrough', plugin.canPlayThrough ); // Stop if audio ended audio.addEventListener( 'ended', plugin.ended ); }; plugin.ended = function( event ) { plugin.reset(); $wrapper.trigger( 'ee:audio-player:ended', [ plugin ] ); if ( plugin.opts.loopPlaylist ) { plugin.playTrack( _next ); } }; plugin.canPlayThrough = function() { _is_loaded = true; }; plugin.playTrack = function( index ) { plugin.reset(); plugin.setTrack( index ); plugin.loadTrack(); plugin.maybePlay(); }; plugin.initAudio = function() { var initialVolume = 'true' === $audio.attr( 'muted' ) ? 0 : volume; plugin.updateVolume( 0, initialVolume ); plugin.updateDuration(); }; plugin.initProgressBar = function() { if ( $controlProgressBar.length ) { $controlProgressBar.on( 'mousedown', function(e) { _is_dragging_time = true; plugin.updateProgress( e.pageX ); }); $document.on( 'mouseup', function(e) { if( _is_dragging_time ) { _is_dragging_time = false; plugin.updateProgress( e.pageX ); } }); $document.on('mousemove', function(e) { if( _is_dragging_time ) { plugin.updateProgress( e.pageX ); } }); } }; plugin.initVolumeBar = function() { if ( $controlVolumeIcon.length ) { $controlVolumeIcon.click( function(e) { e.preventDefault(); if ( audio.volume == 0 ) { // Un-mute // Don't keep 0 volume if ( volume == 0 ) volume = plugin.opts.volume; // Make sure we unmute the audio element audio.muted = false; // Update volume with the last known value plugin.updateVolume( 0, volume ); } else { // Mute var _volume = audio.volume; // Turn volume off plugin.updateVolume( 0, 0 ); // Update volume with last known value to be > 0 volume = _volume; } }); } if ( $controlVolumeBar.length ) { $controlVolumeBar.on( 'mousedown', function(e) { _is_dragging_volume = true; // Make sure it's no longer muted audio.muted = false; plugin.updateVolumeIcon( 1 ); // Update volume plugin.updateVolume( e.pageX ); }); $document.on( 'mouseup', function(e) { if( _is_dragging_volume ) { _is_dragging_volume = false; // Update volume plugin.updateVolume( e.pageX ); } }); $document.on( 'mousemove', function(e) { if( _is_dragging_volume ) { // Update volume plugin.updateVolume( e.pageX ); } }); } }; plugin.maybePlay = function() { if ( ! _is_playing ) { plugin.play(); } else { plugin.pause(); } return false; }; plugin.play = function() { if ( _is_playing ) return; // Adjust button classes $controlPlay.removeClass('nicon-play').addClass('nicon-pause'); $wrapper.trigger( 'ee:audio-player:beforePlay', [ plugin ] ); // Play it audio.play(); // Everything else plugin.afterPlay(); $wrapper.trigger( 'ee:audio-player:afterPlay', [ plugin ] ); }; plugin.afterPlay = function() { // Adjust classes $wrapper.removeClass('paused').addClass('playing'); // Stop all other audios conditionally if ( plugin.opts.stopOthersOnPlay ) { var $players = $('.ee-audio-player').not( element ); $players.each( function() { var instance = $(this).data('audioPlayer'); instance.pause(); }); } // Not playing anymore _is_playing = true; // Make sure overlays are turned off // TweenMax.set( plugin.opts.overlays, { opacity: 0 }); }; plugin.pause = function() { if ( ! _is_playing ) return; // Adjust classes $wrapper.removeClass('playing'); $controlPlay.removeClass('nicon-pause').addClass('nicon-play'); // Add paused classes $wrapper.addClass('paused'); // Pause the audio audio.pause(); _is_playing = false; $wrapper.trigger( 'ee:audio-player:pause', [ plugin ] ); }; plugin.restart = function() { plugin.reset(); plugin.play(); $wrapper.trigger( 'ee:audio-player:restart', [ plugin ] ); }; plugin.reset = function() { // Pause the audio audio.pause(); // Adjust classes $wrapper.removeClass('playing'); $controlPlay.removeClass('nicon-pause').addClass('nicon-play'); // Reset time audio.currentTime = 0; // Reset the progress plugin.updateTime(); _is_playing = false; }; plugin.maybeRewind = function() { audio.currentTime = 0; plugin.play(); }; plugin.updateTime = function() { var position = audio.currentTime, duration = audio.duration, percentage = 100 * position / duration; if ( $controlProgress) $controlProgress.css( 'width', percentage + '%' ); // Update time text if ( $controlTime.length ) $controlTime.html( plugin.formatTime( position ) ); }; plugin.updateDuration = function() { var duration = audio.duration; // Update duration text if ( $controlDuration.length ) $controlDuration.html( plugin.formatTime( duration ) ); }; plugin.updateProgress = function( amount ) { var duration = audio.duration, position = amount - $controlProgressBar.offset().left, percentage = 100 * position / $controlProgressBar.width(); if ( percentage > 100 ) percentage = 100; else if ( percentage < 0 ) percentage = 0; $controlProgress.css( 'width', percentage + '%'); audio.currentTime = duration * percentage / 100; }; plugin.updateVolume = function( amount, volume ) { var percentage; if( volume ) { percentage = volume * 100; } else { var offsetLeft = ( $controlVolumeBar.length ) ? $controlVolumeBar.offset().left : 1, position = amount - offsetLeft, percentage = 100 * position / $controlVolumeBar.width(); } if ( percentage > 100 ) percentage = 100; else if ( percentage < 0 ) percentage = 0; // Update audio volume audio.volume = percentage / 100; plugin.updateVolumeIcon( audio.volume ); // Update volume control position $controlVolume.css( 'width',percentage + '%' ); // Keep value volume = audio.volume; } plugin.updateVolumeIcon = function( vol ) { if ( vol == 0 ) $controlVolumeIcon.addClass('nicon-volume-off').removeClass('nicon-volume'); else $controlVolumeIcon.addClass('nicon-volume').removeClass('nicon-volume-off'); } // ———— // https://stackoverflow.com/a/4605470 // ———— plugin.formatTime = function( seconds, _hours ) { if ( _hours ) { hours = Math.floor(seconds / 3600); hours = (hours >= 10) ? hours : "0" + hours; hours += ":"; } else { hours = ''; } minutes = Math.floor(seconds / 60); minutes = (minutes >= 10) ? minutes : "0" + minutes; seconds = Math.floor(seconds % 60); seconds = (seconds >= 10) ? seconds : "0" + seconds; return hours + minutes + ":" + seconds; }; plugin.init(); }; $.fn.audioPlayer = function(options) { return this.each(function() { if (undefined == $(this).data('audioPlayer')) { var plugin = new $.audioPlayer(this, options); $(this).data('audioPlayer', plugin); } }); }; })(jQuery);
# extract from https://github.com/neo-project/neo-vm pops = 0 pushes = 0 # fee doc - http://docs.neo.org/en-us/sc/systemfees.html default = 0.001 _table = { # opcode:(mnemonic, immediate_operand_size, pops, pushes, gas, description) 0x00: ('PUSH0', 0, 0, 1, 0, 'An empty array of bytes is pushed onto the stack.'), 0x01: ('PUSHBYTES1', 0x01, 0, 0x01, 0, '0x01 byte will be push onto the stack'), 0x02: ('PUSHBYTES2', 0x02, 0, 0x02, 0, '0x02 bytes will be push onto the stack'), 0x03: ('PUSHBYTES3', 0x03, 0, 0x03, 0, '0x03 bytes will be push onto the stack'), 0x04: ('PUSHBYTES4', 0x04, 0, 0x04, 0, '0x04 bytes will be push onto the stack'), 0x05: ('PUSHBYTES5', 0x05, 0, 0x05, 0, '0x05 bytes will be push onto the stack'), 0x06: ('PUSHBYTES6', 0x06, 0, 0x06, 0, '0x06 bytes will be push onto the stack'), 0x07: ('PUSHBYTES7', 0x07, 0, 0x07, 0, '0x07 bytes will be push onto the stack'), 0x08: ('PUSHBYTES8', 0x08, 0, 0x08, 0, '0x08 bytes will be push onto the stack'), 0x09: ('PUSHBYTES9', 0x09, 0, 0x09, 0, '0x09 bytes will be push onto the stack'), 0x0A: ('PUSHBYTES10', 0x0A, 0, 0x0A, 0, '0x0A bytes will be push onto the stack'), 0x0B: ('PUSHBYTES11', 0x0B, 0, 0x0B, 0, '0x0B bytes will be push onto the stack'), 0x0C: ('PUSHBYTES12', 0x0C, 0, 0x0C, 0, '0x0C bytes will be push onto the stack'), 0x0D: ('PUSHBYTES13', 0x0D, 0, 0x0D, 0, '0x0D bytes will be push onto the stack'), 0x0E: ('PUSHBYTES14', 0x0E, 0, 0x0E, 0, '0x0E bytes will be push onto the stack'), 0x0F: ('PUSHBYTES15', 0x0F, 0, 0x0F, 0, '0x0F bytes will be push onto the stack'), 0x10: ('PUSHBYTES16', 0x10, 0, 0x10, 0, '0x10 bytes will be push onto the stack'), 0x11: ('PUSHBYTES17', 0x11, 0, 0x11, 0, '0x11 bytes will be push onto the stack'), 0x12: ('PUSHBYTES18', 0x12, 0, 0x12, 0, '0x12 bytes will be push onto the stack'), 0x13: ('PUSHBYTES19', 0x13, 0, 0x13, 0, '0x13 bytes will be push onto the stack'), 0x14: ('PUSHBYTES20', 0x14, 0, 0x14, 0, '0x14 bytes will be push onto the stack'), 0x15: ('PUSHBYTES21', 0x15, 0, 0x15, 0, '0x15 bytes will be push onto the stack'), 0x16: ('PUSHBYTES22', 0x16, 0, 0x16, 0, '0x16 bytes will be push onto the stack'), 0x17: ('PUSHBYTES23', 0x17, 0, 0x17, 0, '0x17 bytes will be push onto the stack'), 0x18: ('PUSHBYTES24', 0x18, 0, 0x18, 0, '0x18 bytes will be push onto the stack'), 0x19: ('PUSHBYTES25', 0x19, 0, 0x19, 0, '0x19 bytes will be push onto the stack'), 0x1A: ('PUSHBYTES26', 0x1A, 0, 0x1A, 0, '0x1A bytes will be push onto the stack'), 0x1B: ('PUSHBYTES27', 0x1B, 0, 0x1B, 0, '0x1B bytes will be push onto the stack'), 0x1C: ('PUSHBYTES28', 0x1C, 0, 0x1C, 0, '0x1C bytes will be push onto the stack'), 0x1D: ('PUSHBYTES29', 0x1D, 0, 0x1D, 0, '0x1D bytes will be push onto the stack'), 0x1E: ('PUSHBYTES30', 0x1E, 0, 0x1E, 0, '0x1E bytes will be push onto the stack'), 0x1F: ('PUSHBYTES31', 0x1F, 0, 0x1F, 0, '0x1F bytes will be push onto the stack'), 0x20: ('PUSHBYTES32', 0x20, 0, 0x20, 0, '0x20 bytes will be push onto the stack'), 0x21: ('PUSHBYTES33', 0x21, 0, 0x21, 0, '0x21 bytes will be push onto the stack'), 0x22: ('PUSHBYTES34', 0x22, 0, 0x22, 0, '0x22 bytes will be push onto the stack'), 0x23: ('PUSHBYTES35', 0x23, 0, 0x23, 0, '0x23 bytes will be push onto the stack'), 0x24: ('PUSHBYTES36', 0x24, 0, 0x24, 0, '0x24 bytes will be push onto the stack'), 0x25: ('PUSHBYTES37', 0x25, 0, 0x25, 0, '0x25 bytes will be push onto the stack'), 0x26: ('PUSHBYTES38', 0x26, 0, 0x26, 0, '0x26 bytes will be push onto the stack'), 0x27: ('PUSHBYTES39', 0x27, 0, 0x27, 0, '0x27 bytes will be push onto the stack'), 0x28: ('PUSHBYTES40', 0x28, 0, 0x28, 0, '0x28 bytes will be push onto the stack'), 0x29: ('PUSHBYTES41', 0x29, 0, 0x29, 0, '0x29 bytes will be push onto the stack'), 0x2A: ('PUSHBYTES42', 0x2A, 0, 0x2A, 0, '0x2A bytes will be push onto the stack'), 0x2B: ('PUSHBYTES43', 0x2B, 0, 0x2B, 0, '0x2B bytes will be push onto the stack'), 0x2C: ('PUSHBYTES44', 0x2C, 0, 0x2C, 0, '0x2C bytes will be push onto the stack'), 0x2D: ('PUSHBYTES45', 0x2D, 0, 0x2D, 0, '0x2D bytes will be push onto the stack'), 0x2E: ('PUSHBYTES46', 0x2E, 0, 0x2E, 0, '0x2E bytes will be push onto the stack'), 0x2F: ('PUSHBYTES47', 0x2F, 0, 0x2F, 0, '0x2F bytes will be push onto the stack'), 0x30: ('PUSHBYTES48', 0x30, 0, 0x30, 0, '0x30 bytes will be push onto the stack'), 0x31: ('PUSHBYTES49', 0x31, 0, 0x31, 0, '0x31 bytes will be push onto the stack'), 0x32: ('PUSHBYTES50', 0x32, 0, 0x32, 0, '0x32 bytes will be push onto the stack'), 0x33: ('PUSHBYTES51', 0x33, 0, 0x33, 0, '0x33 bytes will be push onto the stack'), 0x34: ('PUSHBYTES52', 0x34, 0, 0x34, 0, '0x34 bytes will be push onto the stack'), 0x35: ('PUSHBYTES53', 0x35, 0, 0x35, 0, '0x35 bytes will be push onto the stack'), 0x36: ('PUSHBYTES54', 0x36, 0, 0x36, 0, '0x36 bytes will be push onto the stack'), 0x37: ('PUSHBYTES55', 0x37, 0, 0x37, 0, '0x37 bytes will be push onto the stack'), 0x38: ('PUSHBYTES56', 0x38, 0, 0x38, 0, '0x38 bytes will be push onto the stack'), 0x39: ('PUSHBYTES57', 0x39, 0, 0x39, 0, '0x39 bytes will be push onto the stack'), 0x3A: ('PUSHBYTES58', 0x3A, 0, 0x3A, 0, '0x3A bytes will be push onto the stack'), 0x3B: ('PUSHBYTES59', 0x3B, 0, 0x3B, 0, '0x3B bytes will be push onto the stack'), 0x3C: ('PUSHBYTES60', 0x3C, 0, 0x3C, 0, '0x3C bytes will be push onto the stack'), 0x3D: ('PUSHBYTES61', 0x3D, 0, 0x3D, 0, '0x3D bytes will be push onto the stack'), 0x3E: ('PUSHBYTES62', 0x3E, 0, 0x3E, 0, '0x3E bytes will be push onto the stack'), 0x3F: ('PUSHBYTES63', 0x3F, 0, 0x3F, 0, '0x3F bytes will be push onto the stack'), 0x40: ('PUSHBYTES64', 0x40, 0, 0x40, 0, '0x40 bytes will be push onto the stack'), 0x41: ('PUSHBYTES65', 0x41, 0, 0x41, 0, '0x41 bytes will be push onto the stack'), 0x42: ('PUSHBYTES66', 0x42, 0, 0x42, 0, '0x42 bytes will be push onto the stack'), 0x43: ('PUSHBYTES67', 0x43, 0, 0x43, 0, '0x43 bytes will be push onto the stack'), 0x44: ('PUSHBYTES68', 0x44, 0, 0x44, 0, '0x44 bytes will be push onto the stack'), 0x45: ('PUSHBYTES69', 0x45, 0, 0x45, 0, '0x45 bytes will be push onto the stack'), 0x46: ('PUSHBYTES70', 0x46, 0, 0x46, 0, '0x46 bytes will be push onto the stack'), 0x47: ('PUSHBYTES71', 0x47, 0, 0x47, 0, '0x47 bytes will be push onto the stack'), 0x48: ('PUSHBYTES72', 0x48, 0, 0x48, 0, '0x48 bytes will be push onto the stack'), 0x49: ('PUSHBYTES73', 0x49, 0, 0x49, 0, '0x49 bytes will be push onto the stack'), 0x4A: ('PUSHBYTES74', 0x4A, 0, 0x4A, 0, '0x4A bytes will be push onto the stack'), 0x4B: ('PUSHBYTES75', 0x4B, 0, 0x4B, 0, '0x4B datas will be push onto the stack'), 0x4C: ('PUSHDATA1', 1, 0, 1, 0, 'The next byte contains the number of bytes to be pushed onto the stack.'), 0x4D: ('PUSHDATA2', 2, 0, 2, 0, 'The next two bytes contain the number of bytes to be pushed onto the stack.'), 0x4E: ('PUSHDATA4', 4, 0, 4, 0, 'The next four bytes contain the number of bytes to be pushed onto the stack.'), 0x4F: ('PUSHM1', 0, 0, 1, 0, 'The number -1 is pushed onto the stack.'), 0x51: ('PUSH1', 0, 0, 1, 0, 'The number 1 is pushed onto the stack.'), 0x52: ('PUSH2', 0, 0, 1, 0, 'The number 2 is pushed onto the stack.'), 0x53: ('PUSH3', 0, 0, 1, 0, 'The number 3 is pushed onto the stack.'), 0x54: ('PUSH4', 0, 0, 1, 0, 'The number 4 is pushed onto the stack.'), 0x55: ('PUSH5', 0, 0, 1, 0, 'The number 5 is pushed onto the stack.'), 0x56: ('PUSH6', 0, 0, 1, 0, 'The number 6 is pushed onto the stack.'), 0x57: ('PUSH7', 0, 0, 1, 0, 'The number 7 is pushed onto the stack.'), 0x58: ('PUSH8', 0, 0, 1, 0, 'The number 8 is pushed onto the stack.'), 0x59: ('PUSH9', 0, 0, 1, 0, 'The number 9 is pushed onto the stack.'), 0x5A: ('PUSH10', 0, 0, 1, 0, 'The number 10 is pushed onto the stack.'), 0x5B: ('PUSH11', 0, 0, 1, 0, 'The number 11 is pushed onto the stack.'), 0x5C: ('PUSH12', 0, 0, 1, 0, 'The number 12 is pushed onto the stack.'), 0x5D: ('PUSH13', 0, 0, 1, 0, 'The number 13 is pushed onto the stack.'), 0x5E: ('PUSH14', 0, 0, 1, 0, 'The number 14 is pushed onto the stack.'), 0x5F: ('PUSH15', 0, 0, 1, 0, 'The number 15 is pushed onto the stack.'), 0x60: ('PUSH16', 0, 0, 1, 0, 'The number 16 is pushed onto the stack.'), # Flow control 0x61: ('NOP', 0, 0, 0, 0, 'Does nothing.'), 0x62: ('JMP', 2, 0, 0, default, 'JUMP'), 0x63: ('JMPIF', 2, 1, 0, default, 'CONDITIONNAL JUMP'), 0x64: ('JMPIFNOT', 2, 1, 0, default, 'NEGATIVE CONDITIONNAL JUMP'), 0x65: ('CALL', 2, 0, pushes, default, 'CALL FUNCTION'), 0x66: ('RET', 0, 0, 0, default, 'RET FUNCTION'), 0x67: ('APPCALL', 20, pops, pushes, 0.01, 'APPCALL'), 0x68: ('SYSCALL', 1, pops, pushes, default, 'SYSCALL'), 0x69: ('TAILCALL', 20, pops, pushes, 0.01, 'TAILCALL'), # Stack 0x6A: ('DUPFROMALTSTACK', 0, 0, 1, default, ''), 0x6B: ('TOALTSTACK', 0, 1, 1, default, 'Puts the input onto the top of the alt stack. Removes it from the main stack.'), 0x6C: ('FROMALTSTACK', 0, 1, 1, default, 'Puts the input onto the top of the main stack. Removes it from the alt stack.'), 0x6D: ('XDROP', 0, pops, pushes, default, ''), 0x72: ('XSWAP', 0, 1, 0, default, ''), 0x73: ('XTUCK', 0, 1, 1, default, ''), 0x74: ('DEPTH', 0, 0, 1, default, 'Puts the number of stack items onto the stack.'), 0x75: ('DROP', 0, 1, 0, default, 'Removes the top stack item.'), 0x76: ('DUP', 0, 0, 1, default, 'Duplicates the top stack item.'), 0x77: ('NIP', 0, 2, 1, default, 'Removes the second-to-top stack item.'), 0x78: ('OVER', 0, 1, 2, default, 'Copies the second-to-top stack item to the top.'), 0x79: ('PICK', 0, 1, 1, default, 'The item n back in the stack is copied to the top.'), 0x7A: ('ROLL', 0, pops, pushes, default, 'The item n back in the stack is moved to the top.'), 0x7B: ('ROT', 0, 3, 3, default, 'The top three items on the stack are rotated to the left.'), 0x7C: ('SWAP', 0, 2, 2, default, 'The top two items on the stack are swapped.'), 0x7D: ('TUCK', 0, 2, 3, default, 'The item at the top of the stack is copied and inserted before the second-to-top item.'), # Splice 0x7E: ('CAT', 0, 2, 1, default, 'Concatenates two strings.'), 0x7F: ('SUBSTR', 0, 3, 1, default, 'Returns a section of a string.'), 0x80: ('LEFT', 0, 2, 1, default, 'Keeps only characters left of the specified point in a string.'), 0x81: ('RIGHT', 0, 2, 1, default, 'Keeps only characters right of the specified point in a string.'), 0x82: ('SIZE', 0, 1, 1, default, 'Returns the length of the input string.'), # Bitwise logic 0x83: ('INVERT', 0, 1, 1, default, 'Flips all of the bits in the input.'), 0x84: ('AND', 0, 2, 1, default, 'Boolean and between each bit in the inputs.'), 0x85: ('OR', 0, 2, 1, default, 'Boolean or between each bit in the inputs.'), 0x86: ('XOR', 0, 2, 1, default, 'Boolean exclusive or between each bit in the inputs.'), 0x87: ('EQUAL', 0, 2, 1, default, 'Returns 1 if the inputs are exactly equal, 0 otherwise.'), 0x88: ('OP_EQUALVERIFY', 0, pops, pushes, default, 'Same as OP_EQUAL, but runs OP_VERIFY afterward.'), 0x89: ('OP_RESERVED1', 0, pops, pushes, default, 'Transaction is invalid unless occuring in an unexecuted OP_IF branch'), 0x8A: ('OP_RESERVED2', 0, pops, pushes, default, 'Transaction is invalid unless occuring in an unexecuted OP_IF branch'), # Arithmetic # Note: Arithmetic inputs are limited to signed 32-bit integers, but may overflow their output. 0x8B: ('INC', 0, 1, 1, default, '1 is added to the input.'), 0x8C: ('DEC', 0, 1, 1, default, '1 is subtracted from the input.'), 0x8D: ('SIGN', 0, 1, 1, default, ''), 0x8F: ('NEGATE', 0, 1, 1, default, 'The sign of the input is flipped.'), 0x90: ('ABS', 0, 1, 1, default, 'The input is made positive.'), 0x91: ('NOT', 0, 1, 1, default, 'If the input is 0 or 1, it is flipped. Otherwise the output will be 0.'), 0x92: ('NZ', 0, 1, 1, default, 'Returns 0 if the input is 0. 1 otherwise.'), 0x93: ('ADD', 0, pops, pushes, default, 'a is added to b.'), 0x94: ('SUB', 0, pops, pushes, default, 'b is subtracted from a.'), 0x95: ('MUL', 0, pops, pushes, default, 'a is multiplied by b.'), 0x96: ('DIV', 0, pops, pushes, default, 'a is divided by b.'), 0x97: ('MOD', 0, pops, pushes, default, 'Returns the remainder after dividing a by b.'), 0x98: ('SHL', 0, pops, pushes, default, 'Shifts a left b bits, preserving sign.'), 0x99: ('SHR', 0, pops, pushes, default, 'Shifts a right b bits, preserving sign.'), 0x9A: ('BOOLAND', 0, pops, pushes, default, 'If both a and b are not 0, the output is 1. Otherwise 0.'), 0x9B: ('BOOLOR', 0, pops, pushes, default, 'If a or b is not 0, the output is 1. Otherwise 0.'), 0x9C: ('NUMEQUAL', 0, pops, pushes, default, 'Returns 1 if the numbers are equal, 0 otherwise.'), 0x9E: ('NUMNOTEQUAL', 0, pops, pushes, default, 'Returns 1 if the numbers are not equal, 0 otherwise.'), 0x9F: ('LT', 0, pops, pushes, default, 'Returns 1 if a is less than b, 0 otherwise.'), 0xA0: ('GT', 0, pops, pushes, default, 'Returns 1 if a is greater than b, 0 otherwise.'), 0xA1: ('LTE', 0, pops, pushes, default, 'Returns 1 if a is less than or equal to b, 0 otherwise.'), 0xA2: ('GTE', 0, pops, pushes, default, 'Returns 1 if a is greater than or equal to b, 0 otherwise.'), 0xA3: ('MIN', 0, pops, pushes, default, 'Returns the smaller of a and b.'), 0xA4: ('MAX', 0, pops, pushes, default, 'Returns the larger of a and b.'), 0xA5: ('WITHIN', 0, pops, pushes, default, 'Returns 1 if x is within the specified range (left-inclusive), 0 otherwise.'), # Crypto #0xA6: ('RIPEMD160', 0, pops, pushes, default, 'The input is hashed using RIPEMD-160.'), 0xA7: ('SHA1', 0, pops, pushes, 0.01, 'The input is hashed using SHA-1.'), 0xA8: ('SHA256', 0, pops, pushes, 0.01, 'The input is hashed using SHA-256.'), 0xA9: ('HASH160', 0, pops, pushes, 0.02, ''), 0xAA: ('HASH256', 0, pops, pushes, 0.02, ''), 0xAC: ('CHECKSIG', 0, pops, pushes, 0.1, ''), 0xAD: ('VERIFY', 0, pops, pushes, 0.1, ''), 0xAE: ('CHECKMULTISIG', 0, pops, pushes, 0.1, ''), # Array 0xC0: ('ARRAYSIZE', 0, pops, pushes, default, ''), 0xC1: ('PACK', 0, pops, pushes, default, ''), 0xC2: ('UNPACK', 0, pops, pushes, default, ''), 0xC3: ('PICKITEM', 0, pops, pushes, default, ''), 0xC4: ('SETITEM', 0, pops, pushes, default, ''), 0xC5: ('NEWARRAY', 0, pops, pushes, default, 'Used as reference type'), 0xC6: ('NEWSTRUCT', 0, pops, pushes, default, 'Used as reference value '), 0xC7: ('NEWMAP', 0, pops, pushes, default, ''), 0xC8: ('APPEND', 0, pops, pushes, default, ''), 0xC9: ('REVERSE', 0, pops, pushes, default, ''), 0xCA: ('REMOVE', 0, pops, pushes, default, ''), 0xCB: ('HASKEY', 0, pops, pushes, default, ''), 0xCC: ('KEYS', 0, pops, pushes, default, ''), 0xCD: ('VALUES', 0, pops, pushes, default, ''), # Exceptions 0xF0: ('THROW', 0, 0, 0, default, ''), 0xF1: ('THROWIFNOT', 0, 1, 0, default, '') } class Avm(object): """Bytecode for NEO VM.""" def __init__(self): self.table = _table self.reverse_table = self._get_reverse_table() def _get_reverse_table(self): """Build an internal table used in the assembler.""" reverse_table = {} for (opcode, (mnemonic, immediate_operand_size, pops, pushes, gas, description)) in self.table.items(): reverse_table[mnemonic] = opcode, mnemonic, immediate_operand_size, \ pops, pushes, gas, description return reverse_table
import pytest from django.urls import reverse from tests.test_app.polls.models import Poll from tests.utils import user_with_permissions, parse_sidemenu @pytest.mark.django_db def test_no_delete_permission(client): """ When our user has no delete permission, they dont see things they are not supposed to """ user = user_with_permissions("polls.view_poll") poll = Poll.objects.create(owner=user, text="question") url = reverse("admin:polls_poll_change", args=(poll.pk,)) delete_url = reverse("admin:polls_poll_delete", args=(poll.pk,)) client.force_login(user) response = client.get(url) assert delete_url not in response.content.decode() @pytest.mark.django_db def test_no_add_permission(client): """ When our user has no add permission, they dont see things they are not supposed to """ user = user_with_permissions("polls.view_poll") url = reverse("admin:polls_poll_changelist") add_url = reverse("admin:polls_poll_add") client.force_login(user) response = client.get(url) assert add_url not in response.content.decode() @pytest.mark.django_db def test_delete_but_no_view_permission(client): """ When our user has delete but no view/change permission, menu items render out, but with no links As in Plain old Django Admin """ user = user_with_permissions("polls.delete_poll") url = reverse("admin:index") client.force_login(user) response = client.get(url) assert parse_sidemenu(response) == {"Global": ['/admin/'], 'Polls': [None]} @pytest.mark.django_db def test_no_permission(client): """ When our user has no permissions at all, they see no menu or dashboard As in Plain old Django Admin """ user = user_with_permissions() url = reverse("admin:index") client.force_login(user) response = client.get(url) assert parse_sidemenu(response) == {"Global": ["/admin/"]}
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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. */ #pragma once #include <folly/functional/Invoke.h> namespace folly { namespace observer { template <typename T> class Observer; } namespace observer_detail { template <typename T> struct NonSharedPtr { using type = typename std::decay<T>::type; }; template <typename T> struct NonSharedPtr<std::shared_ptr<T>> {}; template <typename T> struct NonObserver { using type = typename std::decay<T>::type; }; template <typename T> struct NonObserver<observer::Observer<T>> {}; template <typename T> struct UnwrapSharedPtr {}; template <typename T> struct UnwrapSharedPtr<std::shared_ptr<T>> { using type = typename std::decay<T>::type; }; template <typename T> struct UnwrapObserver {}; template <typename T> struct UnwrapObserver<observer::Observer<T>> { using type = T; }; template <typename F> using ResultOf = typename NonObserver<typename NonSharedPtr<invoke_result_t<F>>::type>::type; template <typename F> using ResultOfNoObserverUnwrap = typename NonSharedPtr<invoke_result_t<F>>::type; template <typename F> using ResultOfUnwrapSharedPtr = typename UnwrapSharedPtr<invoke_result_t<F>>::type; template <typename F> using ResultOfUnwrapObserver = typename UnwrapObserver<invoke_result_t<F>>::type; template <typename T> struct Unwrap { using type = T; }; template <typename T> struct Unwrap<observer::Observer<T>> { using type = T; }; } // namespace observer_detail } // namespace folly