code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
-- -------------------------------------------------------- -- Host: 127.0.0.1 -- Server version: 5.5.40-0ubuntu0.14.04.1 - (Ubuntu) -- Server OS: debian-linux-gnu -- HeidiSQL Version: 8.3.0.4694 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping structure for table violationsg.aplicacion DROP TABLE IF EXISTS `aplicacion`; CREATE TABLE IF NOT EXISTS `aplicacion` ( `apl_id` int(4) NOT NULL AUTO_INCREMENT, `apl_descripcion` varchar(70) NOT NULL, `apl_nombre` varchar(150) NOT NULL, PRIMARY KEY (`apl_id`), UNIQUE KEY `apl_descripcion` (`apl_descripcion`) ) ENGINE=InnoDB AUTO_INCREMENT=100 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.aplicacion: ~94 rows (approximately) DELETE FROM `aplicacion`; /*!40000 ALTER TABLE `aplicacion` DISABLE KEYS */; INSERT INTO `aplicacion` (`apl_id`, `apl_descripcion`, `apl_nombre`) VALUES (1, 'application:index', 'Modulo Application'), (2, 'application:index:index', 'Resetear Pasword (Console)'), (4, 'application:login', 'Modulo Login'), (5, 'application:login:index', 'Login de Usuario'), (6, 'application:login:autenticar', 'Autenticar Usuario'), (7, 'application:login:logout', 'Salir del Sistema'), (8, 'application:login:denied', 'Permiso denegado'), (9, 'parametros:index', 'Modulo de Parametros'), (10, 'parametros:index:index', 'Pagina Inicial'), (11, 'application:error', 'Modulo Error'), (12, 'application:error:denied', 'Permiso denegado'), (13, 'parametros:pais', 'Modulo Pais'), (14, 'parametros:pais:listado', 'Listado de Paises'), (15, 'parametros:estado', 'Modulo Estados'), (16, 'parametros:estado:listado', 'Listado de Estados'), (17, 'parametros:ciudad', 'Modulo Ciudad'), (18, 'parametros:ciudad:listado', 'Listado Ciudades'), (19, 'parametros:sector', 'Modulo Sector'), (20, 'parametros:sector:listado', 'Listado Sectores'), (21, 'parametros:tipoinfraccion', 'Modulo Tipo Infraccion'), (22, 'parametros:tipoinfraccion:listado', 'Listado de Tipos de Infraccion'), (23, 'usuarios:usuarios', 'Modulo Usuarios'), (24, 'usuarios:usuarios:index', 'Listado de Usuarios'), (25, 'usuarios:aplicaciones', 'Modulo Aplicaciones'), (26, 'usuarios:aplicaciones:listado', 'Listado Aplicaciones'), (27, 'usuarios:roles', 'Modulo Roles'), (28, 'usuarios:roles:listado', 'Listado de Roles'), (29, 'usuarios:menu', 'Modulo Menu'), (30, 'usuarios:menu:index', 'Listado Menu'), (31, 'infraccion:infraccion', 'Modulo Infraccion'), (32, 'infraccion:infraccion:index', 'Listado Infracciones'), (33, 'parqueaderos:parqueaderos', 'Modulo Parqueaderos'), (34, 'parqueaderos:parqueaderos:index', 'Busqueda Parqueadero'), (37, 'parametros:sector:sucursalesAjax', 'Sucursales Ajax'), (38, 'parametros:sector:ciudadesAjax', 'Ciudades Ajax'), (39, 'parqueaderos:parqueaderos:sectores', 'Sectores Ajax'), (40, 'parqueaderos:sector', 'Modulo Parqueadero Sector'), (41, 'parqueaderos:sector:index', 'Listado de Parqueaderos por sector'), (42, 'parqueaderos:parqueaderos:ocupados', 'Parqueaderos Ocupados'), (43, 'parqueaderos:parqueaderos:multados', 'Parqueaderos Multados'), (44, 'parqueaderos:parqueaderos:agregar', 'Agregar Parqueadero Ocupado'), (45, 'clientes:index', 'Modulo Clientes'), (46, 'clientes:asignar', 'Modulo Asignar Usuarios a transferencias de dinero'), (47, 'clientes:compras', 'Modulo Compras de parqueadero'), (48, 'clientes:recargas', 'Modulo Recargas'), (49, 'clientes:transferenciasrealizadas', 'Modulo Transferencias Realizadas'), (50, 'clientes:transferenciasrecibidas', 'Modulo Transferencias Recibidas'), (51, 'parametros:parqueadero', 'Modulo Parametros Parqueaderos'), (52, 'parametros:parqueadero:listado', 'Modulo Parametros Parqueaderos'), (53, 'clientes:index:index', 'Modulo Transacciones (SOLO CLIENTE)'), (54, 'parametros:pais:ingresar', 'Ingresar Pais'), (55, 'parametros:pais:validar', 'Validar Formulario Pais'), (56, 'parametros:pais:editar', 'Actualizar Pais'), (57, 'parametros:pais:eliminar', 'Eliminar Pais'), (58, 'parametros:estado:ingresar', 'Ingresar Estado'), (59, 'parametros:estado:validar', 'Validar Formulario Estado'), (60, 'parametros:estado:editar', 'Actualizar Estado'), (61, 'parametros:estado:eliminar', 'Eliminar Estado'), (62, 'parametros:ciudad:ingresar', 'Ingresar Ciudad'), (63, 'parametros:ciudad:validar', 'Validar Formulario Ciudad'), (64, 'parametros:ciudad:editar', 'Actualizar Ciudad'), (65, 'parametros:ciudad:eliminar', 'Eliminar Ciudad'), (66, 'parametros:sector:ingresar', 'Ingresar Sector'), (67, 'parametros:sector:validar', 'Validar Formulario Sector'), (68, 'parametros:sector:editar', 'Actualizar Sector'), (69, 'parametros:sector:eliminar', 'Eliminar Sector'), (70, 'parametros:parqueadero:ingresar', 'Ingresar Parqueadero'), (71, 'parametros:parqueadero:validar', 'Validar Formulario Parqueadero'), (72, 'parametros:parqueadero:editar', 'Actualizar Parqueadero'), (73, 'parametros:parqueadero:eliminar', 'Eliminar Parqueadero'), (74, 'parametros:tipoinfraccion:ingresar', 'Ingresar Tipo Infraccion'), (75, 'parametros:tipoinfraccion:validar', 'Validar Formulario Tipo Infraccion'), (76, 'parametros:tipoinfraccion:editar', 'Actualizar Tipo Infraccion'), (77, 'parametros:tipoinfraccion:eliminar', 'Eliminar Tipo Infraccion'), (78, 'usuarios:usuarios:add', 'Ingresar Usuario'), (79, 'usuarios:usuarios:validar', 'Validar Formulario Usuario'), (80, 'usuarios:usuarios:edit', 'Actualizar Usuario'), (81, 'usuarios:usuarios:asociar', 'Asociar Perfiles a Usuarios'), (82, 'usuarios:usuarios:validarRolUsuario', 'Validar Formulario Asociar Permiso'), (83, 'usuarios:usuarios:eliminar', 'Eliminar Usuario'), (84, 'usuarios:roles:ingresar', 'Ingresar Rol'), (85, 'usuarios:roles:validar', 'Validar Formulario Asignar Aplicaciones a Roles'), (86, 'usuarios:roles:editar', 'Actualizar Rol'), (87, 'usuarios:roles:eliminar', 'Eliminar Rol'), (88, 'usuarios:menu:ingresar', 'Ingresar Menu'), (89, 'usuarios:menu:validar', 'Validar Formulario Menu'), (90, 'usuarios:menu:editar', 'Actualizar Menu'), (91, 'usuarios:menu:eliminar', 'Eliminar Menu'), (93, 'clientes:asignar:index', 'Asignar usuarios para transferir dinero (SOLO CLIENTE)'), (94, 'clientes:compras:index', 'Compras de parqueo (SOLO CLIENTE)'), (96, 'clientes:recargas:index', 'Recargas de dinero (SOLO CLIENTE)'), (97, 'clientes:transferenciasrealizadas:index', 'Transferencias Realizadas (SOLO CLIENTE)'), (98, 'clientes:transferenciasrecibidas:index', 'Transferencias Recibidas (SOLO CLIENTE)'), (99, 'clientes:index:listado', 'Listado de Clientes'); /*!40000 ALTER TABLE `aplicacion` ENABLE KEYS */; -- Dumping structure for table violationsg.automovil DROP TABLE IF EXISTS `automovil`; CREATE TABLE IF NOT EXISTS `automovil` ( `aut_placa` varchar(10) NOT NULL, PRIMARY KEY (`aut_placa`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.automovil: ~44 rows (approximately) DELETE FROM `automovil`; /*!40000 ALTER TABLE `automovil` DISABLE KEYS */; INSERT INTO `automovil` (`aut_placa`) VALUES ('123poi'), ('abc1234'), ('ABCD123'), ('asd344'), ('PBB494'), ('PBJ973'), ('PBL915'), ('PBP973'), ('PBU547'), ('PCQ101'), ('PDC024'), ('PDC456'), ('PDD792'), ('PER591'), ('PFA404'), ('PGB661'), ('PIC010'), ('PJA729'), ('PJI826'), ('PJV800'), ('PLN953'), ('PMD747'), ('PMO328'), ('PNF811'), ('PNR574'), ('PNZ469'), ('POB832'), ('POP213'), ('PRC446'), ('PRO158'), ('PSE524'), ('PTD794'), ('PTI556'), ('PUO661'), ('PVW287'), ('PWS910'), ('PXJ824'), ('PXK045'), ('PXQ787'), ('PYB945'), ('PZG974'), ('PZK373'), ('PZP791'), ('PZY349'); /*!40000 ALTER TABLE `automovil` ENABLE KEYS */; -- Dumping structure for table violationsg.categoria DROP TABLE IF EXISTS `categoria`; CREATE TABLE IF NOT EXISTS `categoria` ( `cat_id` int(11) NOT NULL AUTO_INCREMENT, `cat_nombre` varchar(45) DEFAULT NULL, `cat_descripcion` varchar(45) DEFAULT NULL, PRIMARY KEY (`cat_id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.categoria: ~1 rows (approximately) DELETE FROM `categoria`; /*!40000 ALTER TABLE `categoria` DISABLE KEYS */; INSERT INTO `categoria` (`cat_id`, `cat_nombre`, `cat_descripcion`) VALUES (1, 'Servicios', 'Servicios'); /*!40000 ALTER TABLE `categoria` ENABLE KEYS */; -- Dumping structure for table violationsg.ciudad DROP TABLE IF EXISTS `ciudad`; CREATE TABLE IF NOT EXISTS `ciudad` ( `ciu_id` int(11) NOT NULL AUTO_INCREMENT, `est_id` int(4) DEFAULT NULL, `ciu_nombre_es` varchar(150) NOT NULL, `ciu_nombre_en` varchar(150) NOT NULL, `ciu_codigo_telefono` varchar(5) NOT NULL, PRIMARY KEY (`ciu_id`), KEY `fk_ciu_est_id` (`est_id`), CONSTRAINT `fk_ciu_est_id` FOREIGN KEY (`est_id`) REFERENCES `estado` (`est_id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.ciudad: ~3 rows (approximately) DELETE FROM `ciudad`; /*!40000 ALTER TABLE `ciudad` DISABLE KEYS */; INSERT INTO `ciudad` (`ciu_id`, `est_id`, `ciu_nombre_es`, `ciu_nombre_en`, `ciu_codigo_telefono`) VALUES (1, 1, 'Quito', 'Quito', '02'), (2, 2, 'Santiago', 'Santiago', '02'), (3, 4, 'Guayaquil', 'Guayaquil', '07'); /*!40000 ALTER TABLE `ciudad` ENABLE KEYS */; -- Dumping structure for table violationsg.cliente DROP TABLE IF EXISTS `cliente`; CREATE TABLE IF NOT EXISTS `cliente` ( `cli_id` int(11) NOT NULL AUTO_INCREMENT, `usu_id` int(11) NOT NULL, `cli_saldo` decimal(10,2) NOT NULL, `cli_foto` varchar(100) DEFAULT NULL, PRIMARY KEY (`cli_id`), KEY `fk_cliente_usuario1` (`usu_id`), CONSTRAINT `fk_cliente_usuario1` FOREIGN KEY (`usu_id`) REFERENCES `usuario` (`usu_id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.cliente: ~1 rows (approximately) DELETE FROM `cliente`; /*!40000 ALTER TABLE `cliente` DISABLE KEYS */; INSERT INTO `cliente` (`cli_id`, `usu_id`, `cli_saldo`, `cli_foto`) VALUES (1, 3, 700.00, NULL); /*!40000 ALTER TABLE `cliente` ENABLE KEYS */; -- Dumping structure for table violationsg.compra_saldo DROP TABLE IF EXISTS `compra_saldo`; CREATE TABLE IF NOT EXISTS `compra_saldo` ( `com_sal_id` int(11) NOT NULL AUTO_INCREMENT, `cli_id` int(11) NOT NULL, `punto_recarga_pun_rec_id` int(11) NOT NULL, `com_sal_valor` float DEFAULT NULL, `com_sal_hora` timestamp NULL DEFAULT NULL, PRIMARY KEY (`com_sal_id`), KEY `fk_compra_saldo_parqueadero_cliente1_idx` (`cli_id`), KEY `fk_compra_saldo_parqueadero_punto_recarga1_idx` (`punto_recarga_pun_rec_id`), CONSTRAINT `fk_compra_saldo_parqueadero_cliente1` FOREIGN KEY (`cli_id`) REFERENCES `cliente` (`cli_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_compra_saldo_parqueadero_punto_recarga1` FOREIGN KEY (`punto_recarga_pun_rec_id`) REFERENCES `punto_recarga` (`pun_rec_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.compra_saldo: ~0 rows (approximately) DELETE FROM `compra_saldo`; /*!40000 ALTER TABLE `compra_saldo` DISABLE KEYS */; /*!40000 ALTER TABLE `compra_saldo` ENABLE KEYS */; -- Dumping structure for table violationsg.establecimiento DROP TABLE IF EXISTS `establecimiento`; CREATE TABLE IF NOT EXISTS `establecimiento` ( `eta_id` int(11) NOT NULL AUTO_INCREMENT, `cat_id` int(11) NOT NULL, `eta_nombre` varchar(45) DEFAULT NULL, `eta_descripcion` varchar(45) DEFAULT NULL, PRIMARY KEY (`eta_id`), KEY `fk_establecimientos_categorias_idx` (`cat_id`), CONSTRAINT `fk_establecimientos_categorias` FOREIGN KEY (`cat_id`) REFERENCES `categoria` (`cat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.establecimiento: ~1 rows (approximately) DELETE FROM `establecimiento`; /*!40000 ALTER TABLE `establecimiento` DISABLE KEYS */; INSERT INTO `establecimiento` (`eta_id`, `cat_id`, `eta_nombre`, `eta_descripcion`) VALUES (1, 1, 'Parqueaderos', 'Parqueaderos'); /*!40000 ALTER TABLE `establecimiento` ENABLE KEYS */; -- Dumping structure for table violationsg.estado DROP TABLE IF EXISTS `estado`; CREATE TABLE IF NOT EXISTS `estado` ( `est_id` int(4) NOT NULL AUTO_INCREMENT, `pai_id` int(4) DEFAULT NULL, `est_nombre_es` varchar(150) NOT NULL, `est_nombre_en` varchar(150) NOT NULL, PRIMARY KEY (`est_id`), KEY `fk_est_pai_id` (`pai_id`), CONSTRAINT `fk_est_pai_id` FOREIGN KEY (`pai_id`) REFERENCES `pais` (`pai_id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.estado: ~4 rows (approximately) DELETE FROM `estado`; /*!40000 ALTER TABLE `estado` DISABLE KEYS */; INSERT INTO `estado` (`est_id`, `pai_id`, `est_nombre_es`, `est_nombre_en`) VALUES (1, 63, 'Pichincha', 'Pichincha'), (2, 64, 'Region Metropolitana', 'Region Metropolitana'), (3, 66, 'Buenos aires', 'Buenos aires'), (4, 63, 'Guayas', 'Guayas'); /*!40000 ALTER TABLE `estado` ENABLE KEYS */; -- Dumping structure for table violationsg.infraccion DROP TABLE IF EXISTS `infraccion`; CREATE TABLE IF NOT EXISTS `infraccion` ( `inf_id` int(11) NOT NULL AUTO_INCREMENT, `inf_fecha` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `inf_detalles` text NOT NULL, `usu_id` int(11) NOT NULL, `tip_inf_id` int(4) NOT NULL, `sec_id` int(11) NOT NULL, PRIMARY KEY (`inf_id`), KEY `fk_infraccion_usuario1_idx` (`usu_id`), KEY `fk_infraccion_tipo_infraccion1_idx` (`tip_inf_id`), KEY `fk_infraccion_sector1_idx` (`sec_id`), CONSTRAINT `fk_infraccion_sector1` FOREIGN KEY (`sec_id`) REFERENCES `sector` (`sec_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_infraccion_tipo_infraccion1` FOREIGN KEY (`tip_inf_id`) REFERENCES `tipo_infraccion` (`tip_inf_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_infraccion_usuario1` FOREIGN KEY (`usu_id`) REFERENCES `usuario` (`usu_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.infraccion: ~0 rows (approximately) DELETE FROM `infraccion`; /*!40000 ALTER TABLE `infraccion` DISABLE KEYS */; /*!40000 ALTER TABLE `infraccion` ENABLE KEYS */; -- Dumping structure for table violationsg.log DROP TABLE IF EXISTS `log`; CREATE TABLE IF NOT EXISTS `log` ( `log_id` int(11) NOT NULL AUTO_INCREMENT, `log_hora` datetime DEFAULT NULL, `log_descripcion` varchar(45) DEFAULT NULL, `log_info` text, `cli_id` int(11) NOT NULL, PRIMARY KEY (`log_id`), KEY `fk_logs_clientes1_idx` (`cli_id`), CONSTRAINT `fk_logs_clientes1` FOREIGN KEY (`cli_id`) REFERENCES `cliente` (`cli_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.log: ~0 rows (approximately) DELETE FROM `log`; /*!40000 ALTER TABLE `log` DISABLE KEYS */; /*!40000 ALTER TABLE `log` ENABLE KEYS */; -- Dumping structure for table violationsg.log_parqueadero DROP TABLE IF EXISTS `log_parqueadero`; CREATE TABLE IF NOT EXISTS `log_parqueadero` ( `log_par_id` int(11) NOT NULL AUTO_INCREMENT, `par_id` varchar(10) NOT NULL, `aut_placa` varchar(10) NOT NULL, `log_par_fecha_ingreso` datetime NOT NULL, `log_par_fecha_salida` datetime NOT NULL, `log_par_horas_parqueo` int(11) NOT NULL, `log_par_estado` char(1) NOT NULL, `tra_id` int(11) NOT NULL, PRIMARY KEY (`log_par_id`), KEY `fk_log_parqueadero_par_id` (`par_id`), KEY `fk_log_parqueadero_aut_placa` (`aut_placa`), KEY `fk_log_parqueadero_transaccion1` (`tra_id`), CONSTRAINT `fk_log_parqueadero_aut_placa` FOREIGN KEY (`aut_placa`) REFERENCES `automovil` (`aut_placa`), CONSTRAINT `fk_log_parqueadero_par_id` FOREIGN KEY (`par_id`) REFERENCES `parqueadero` (`par_id`), CONSTRAINT `fk_log_parqueadero_transaccion1` FOREIGN KEY (`tra_id`) REFERENCES `transaccion` (`tra_id`) ) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.log_parqueadero: ~33 rows (approximately) DELETE FROM `log_parqueadero`; /*!40000 ALTER TABLE `log_parqueadero` DISABLE KEYS */; INSERT INTO `log_parqueadero` (`log_par_id`, `par_id`, `aut_placa`, `log_par_fecha_ingreso`, `log_par_fecha_salida`, `log_par_horas_parqueo`, `log_par_estado`, `tra_id`) VALUES (5, 'Q027', 'POB832', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (6, 'Q025', 'PER591', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (7, 'Q022', 'PXQ787', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (8, 'Q021', 'PSE524', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (9, 'Q023', 'PFA404', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (10, 'Q010', 'POP213', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (11, 'Q031', 'PTD794', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (12, 'Q028', 'PWS910', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (13, 'Q026', 'PDD792', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (14, 'Q007', 'PJV800', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (15, 'Q029', 'PRC446', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (16, 'Q012', 'PTI556', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (17, 'Q015', 'PNR574', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (18, 'Q020', 'PBP973', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (19, 'Q030', 'PUO661', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (21, 'Q024', 'PNF811', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (22, 'Q031', 'PBJ973', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (23, 'Q028', 'PMO328', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (24, 'Q016', 'PZG974', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (25, 'Q005', 'PLN953', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (26, 'EC123', 'PBB494', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (27, 'Q033', 'PXJ824', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (28, 'Q005', 'PVW287', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'D', 1), (29, 'Q026', 'PRO158', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 2, 'D', 1), (30, 'Q015', 'PCQ101', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1), (31, 'Q028', 'PZK373', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1), (32, 'Q008', 'PGB661', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1), (33, 'Q011', 'PBU547', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1), (34, 'Q025', 'PJI826', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1), (35, 'Q006', 'PNZ469', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1), (36, 'Q030', 'PJA729', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1), (37, 'Q019', 'PYB945', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1), (38, 'Q027', 'PZP791', '2014-10-20 21:26:37', '0000-00-00 00:00:00', 1, 'O', 1); /*!40000 ALTER TABLE `log_parqueadero` ENABLE KEYS */; -- Dumping structure for table violationsg.menu DROP TABLE IF EXISTS `menu`; CREATE TABLE IF NOT EXISTS `menu` ( `men_id` int(11) NOT NULL AUTO_INCREMENT, `apl_id` int(4) DEFAULT NULL, `men_nombre` varchar(200) NOT NULL, `men_etiqueta` varchar(200) NOT NULL, `men_icon` varchar(100) NOT NULL, `men_padre` int(11) NOT NULL, `men_divisor` char(1) NOT NULL, PRIMARY KEY (`men_id`), KEY `fk_menu_aplicacion1` (`apl_id`), CONSTRAINT `fk_menu_aplicacion1` FOREIGN KEY (`apl_id`) REFERENCES `aplicacion` (`apl_id`) ) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.menu: ~27 rows (approximately) DELETE FROM `menu`; /*!40000 ALTER TABLE `menu` DISABLE KEYS */; INSERT INTO `menu` (`men_id`, `apl_id`, `men_nombre`, `men_etiqueta`, `men_icon`, `men_padre`, `men_divisor`) VALUES (1, 9, 'Parametros', 'Parámetros ', '<i class="fa fa-gears fa-fw"></i>', 0, 'N'), (2, 23, 'Administracion', 'Administración', '<i class="fa fa-users fa-fw"></i>', 0, 'N'), (3, 14, 'Paises', 'Paises', '<i class="fa fa-globe fa-fw"></i>', 1, 'N'), (4, 16, 'Estados', 'Estados', '<i class="fa fa-building fa-fw"></i>', 1, 'N'), (5, 24, 'Usuarios', 'Usuarios', '<i class="fa fa-user fa-fw"></i>', 2, 'N'), (8, 18, 'Ciudades', 'Ciudades', '<i class="fa fa-building-o fa-fw"></i>', 1, 'S'), (9, 20, 'Sector', 'Sector', '<i class="fa fa-map-marker fa-fw"></i>', 1, 'N'), (10, 52, 'Parqueadero', 'Parqueadero', '<i class="fa fa-location-arrow fa-fw"></i>', 1, 'S'), (13, 22, 'TipoInfraccion', 'Tipo Infracción', '<i class="fa fa-ticket fa-fw"></i>', 1, 'S'), (15, NULL, 'Parametros Generales', 'Parametros Generales', '<i class="fa fa-cog fa-fw"></i>', 1, 'N'), (16, 28, 'Roles', 'Roles', '<i class="fa fa-child fa-fw"></i>', 2, 'N'), (17, 26, 'Aplicaciones', 'Aplicaciones', '<i class="fa fa-list fa-fw"></i>', 2, 'N'), (19, 32, 'Infracciones', 'Infracciones', '<i class="fa fa-list-ol fa-fw"></i>', 0, 'N'), (22, 34, 'Parqueaderos', 'Parqueaderos', '<i class="fa fa-road fa-fw"></i>', 0, 'N'), (23, 30, 'Menu', 'Menú', '<i class="fa fa-navicon fa-fw"></i>', 2, 'N'), (24, 53, 'transacciones', 'Mis Transacciones', '<i class="fa fa-search fa-fw"></i>', 0, 'N'), (25, NULL, 'compras', 'Pagos en parqueaderos', '<i class="fa fa-search fa-fw"></i>', 24, 'S'), (26, NULL, 'recargas', 'Recarga de dinero', '<i class="fa fa-search fa-fw"></i>', 24, 'S'), (27, NULL, 'transferenciasRealizadas', 'Transferencias Realizadas', '<i class="fa fa-search fa-fw"></i>', 24, 'S'), (28, NULL, 'transferenciasRecibidas', 'Transferencias Recibidas', '<i class="fa fa-search fa-fw"></i>', 24, 'N'), (29, NULL, 'transferirDinero', 'Transferir Dinero', '<i class="fa fa-search fa-fw"></i>', 0, 'N'), (30, 99, 'Clientes', 'Clientes', '<i class="fa fa-search fa-fw"></i>', 0, 'N'), (33, 94, 'pagosParqueo', 'Compras de parqueadero', '<i class="fa fa-search fa-fw"></i>', 24, 'N'), (34, 96, 'recargasDinero', 'Recargas de Dinero', '<i class="fa fa-search fa-fw"></i>', 24, 'N'), (35, 93, 'asignarUsuarios', 'Transferir Dinero', '<i class="fa fa-search fa-fw"></i>', 24, 'N'), (36, 97, 'transferenciaRealizada', 'Transferencias Realizadas', '<i class="fa fa-search fa-fw"></i>', 24, 'N'), (37, 98, 'transferenciasRecibidas', 'Transferencias Recibidas', '<i class="fa fa-search fa-fw"></i>', 24, 'N'); /*!40000 ALTER TABLE `menu` ENABLE KEYS */; -- Dumping structure for table violationsg.pais DROP TABLE IF EXISTS `pais`; CREATE TABLE IF NOT EXISTS `pais` ( `pai_id` int(4) NOT NULL AUTO_INCREMENT, `pai_nombre_es` varchar(120) NOT NULL, `pai_nombre_en` varchar(120) NOT NULL, `pai_codigo_telefono` varchar(5) NOT NULL, PRIMARY KEY (`pai_id`) ) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.pais: ~3 rows (approximately) DELETE FROM `pais`; /*!40000 ALTER TABLE `pais` DISABLE KEYS */; INSERT INTO `pais` (`pai_id`, `pai_nombre_es`, `pai_nombre_en`, `pai_codigo_telefono`) VALUES (63, 'Ecuador', 'Ecuador', '593'), (64, 'Chile', 'Chile', '56'), (66, 'Argentina ', 'Argentina ', 'Argen'); /*!40000 ALTER TABLE `pais` ENABLE KEYS */; -- Dumping structure for table violationsg.parqueadero DROP TABLE IF EXISTS `parqueadero`; CREATE TABLE IF NOT EXISTS `parqueadero` ( `par_id` varchar(10) NOT NULL, `par_estado` char(1) NOT NULL, `sec_id` int(11) NOT NULL, PRIMARY KEY (`par_id`), KEY `fk_parqueadero_sector1_idx` (`sec_id`), CONSTRAINT `fk_parqueadero_sector1` FOREIGN KEY (`sec_id`) REFERENCES `sector` (`sec_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.parqueadero: ~33 rows (approximately) DELETE FROM `parqueadero`; /*!40000 ALTER TABLE `parqueadero` DISABLE KEYS */; INSERT INTO `parqueadero` (`par_id`, `par_estado`, `sec_id`) VALUES ('', 'D', 6), ('adf345', 'D', 6), ('EC123', 'D', 1), ('Q004', 'D', 5), ('Q005', 'D', 5), ('Q006', 'O', 5), ('Q007', 'D', 5), ('Q008', 'O', 5), ('Q009', 'D', 5), ('Q010', 'D', 5), ('Q011', 'O', 5), ('Q012', 'D', 5), ('Q013', 'D', 5), ('Q014', 'D', 5), ('Q015', 'O', 5), ('Q016', 'D', 5), ('Q017', 'D', 5), ('Q018', 'D', 5), ('Q019', 'O', 5), ('Q020', 'D', 5), ('Q021', 'D', 5), ('Q022', 'D', 5), ('Q023', 'D', 5), ('Q024', 'D', 5), ('Q025', 'O', 5), ('Q026', 'O', 5), ('Q027', 'O', 5), ('Q028', 'O', 5), ('Q029', 'D', 5), ('Q030', 'O', 5), ('Q031', 'D', 5), ('Q032', 'D', 5), ('Q033', 'D', 5); /*!40000 ALTER TABLE `parqueadero` ENABLE KEYS */; -- Dumping structure for table violationsg.punto_recarga DROP TABLE IF EXISTS `punto_recarga`; CREATE TABLE IF NOT EXISTS `punto_recarga` ( `pun_rec_id` int(11) NOT NULL AUTO_INCREMENT, `pun_rec_nombre` varchar(45) DEFAULT NULL, `pun_rec_ruc` varchar(45) DEFAULT NULL, `pun_rec_codigo` varchar(45) DEFAULT NULL, PRIMARY KEY (`pun_rec_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.punto_recarga: ~0 rows (approximately) DELETE FROM `punto_recarga`; /*!40000 ALTER TABLE `punto_recarga` DISABLE KEYS */; /*!40000 ALTER TABLE `punto_recarga` ENABLE KEYS */; -- Dumping structure for table violationsg.relacion_cliente DROP TABLE IF EXISTS `relacion_cliente`; CREATE TABLE IF NOT EXISTS `relacion_cliente` ( `rel_cli_id` int(11) NOT NULL AUTO_INCREMENT, `cli_id` int(11) NOT NULL, `cli_id_relacionado` int(11) NOT NULL, `rel_cli_hora` timestamp NULL DEFAULT NULL, `rel_cli_tipo` varchar(45) DEFAULT NULL, PRIMARY KEY (`rel_cli_id`), KEY `fk_relacion_cliente_cliente1_idx` (`cli_id`), KEY `fk_relacion_cliente_cliente2_idx` (`cli_id_relacionado`), CONSTRAINT `fk_relacion_cliente_cliente1` FOREIGN KEY (`cli_id`) REFERENCES `cliente` (`cli_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_relacion_cliente_cliente2` FOREIGN KEY (`cli_id_relacionado`) REFERENCES `cliente` (`cli_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.relacion_cliente: ~0 rows (approximately) DELETE FROM `relacion_cliente`; /*!40000 ALTER TABLE `relacion_cliente` DISABLE KEYS */; /*!40000 ALTER TABLE `relacion_cliente` ENABLE KEYS */; -- Dumping structure for table violationsg.rol DROP TABLE IF EXISTS `rol`; CREATE TABLE IF NOT EXISTS `rol` ( `rol_id` int(4) NOT NULL AUTO_INCREMENT, `rol_descripcion` varchar(50) NOT NULL, `rol_estado` varchar(10) NOT NULL, PRIMARY KEY (`rol_id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.rol: ~5 rows (approximately) DELETE FROM `rol`; /*!40000 ALTER TABLE `rol` DISABLE KEYS */; INSERT INTO `rol` (`rol_id`, `rol_descripcion`, `rol_estado`) VALUES (1, 'Super Administrador', 'A'), (2, 'Administrador', 'A'), (3, 'Cliente', 'A'), (4, 'Vigilante', 'A'), (5, 'Invitado', 'A'); /*!40000 ALTER TABLE `rol` ENABLE KEYS */; -- Dumping structure for table violationsg.rol_aplicacion DROP TABLE IF EXISTS `rol_aplicacion`; CREATE TABLE IF NOT EXISTS `rol_aplicacion` ( `rol_id` int(4) NOT NULL, `apl_id` int(4) NOT NULL, PRIMARY KEY (`rol_id`,`apl_id`), KEY `fk_rol_apl_apl_id` (`apl_id`), CONSTRAINT `fk_rol_apl_apl_id` FOREIGN KEY (`apl_id`) REFERENCES `aplicacion` (`apl_id`), CONSTRAINT `fk_rol_apl_rol_id` FOREIGN KEY (`rol_id`) REFERENCES `rol` (`rol_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.rol_aplicacion: ~155 rows (approximately) DELETE FROM `rol_aplicacion`; /*!40000 ALTER TABLE `rol_aplicacion` DISABLE KEYS */; INSERT INTO `rol_aplicacion` (`rol_id`, `apl_id`) VALUES (2, 2), (1, 5), (2, 5), (3, 5), (1, 6), (2, 6), (3, 6), (1, 7), (2, 7), (3, 7), (1, 8), (2, 8), (3, 8), (1, 9), (2, 9), (1, 10), (2, 10), (3, 10), (2, 11), (3, 11), (1, 12), (2, 12), (3, 12), (1, 14), (2, 14), (1, 16), (2, 16), (1, 18), (2, 18), (1, 20), (2, 20), (1, 22), (2, 22), (1, 23), (2, 23), (1, 24), (2, 24), (1, 26), (2, 27), (1, 28), (2, 28), (1, 30), (2, 31), (1, 32), (2, 32), (2, 33), (3, 33), (1, 34), (2, 34), (3, 34), (1, 37), (2, 37), (3, 37), (1, 38), (2, 38), (3, 38), (1, 39), (2, 39), (3, 39), (2, 40), (1, 41), (2, 41), (3, 41), (1, 42), (2, 42), (3, 42), (1, 43), (2, 43), (3, 43), (1, 44), (2, 44), (1, 45), (2, 45), (2, 51), (1, 52), (2, 52), (3, 53), (1, 54), (2, 54), (1, 55), (2, 55), (1, 56), (2, 56), (1, 57), (2, 57), (1, 58), (2, 58), (1, 59), (2, 59), (1, 60), (2, 60), (1, 61), (2, 61), (1, 62), (2, 62), (1, 63), (2, 63), (1, 64), (2, 64), (1, 65), (2, 65), (1, 66), (2, 66), (1, 67), (2, 67), (1, 68), (2, 68), (1, 69), (2, 69), (1, 70), (2, 70), (1, 71), (2, 71), (1, 72), (2, 72), (1, 73), (2, 73), (1, 74), (2, 74), (1, 75), (2, 75), (1, 76), (2, 76), (1, 77), (2, 77), (1, 78), (2, 78), (1, 79), (2, 79), (1, 80), (2, 80), (1, 81), (2, 81), (1, 82), (2, 82), (1, 83), (2, 83), (1, 84), (2, 84), (1, 85), (2, 85), (1, 86), (2, 86), (1, 87), (2, 87), (1, 88), (1, 89), (1, 90), (1, 91), (3, 93), (3, 94), (3, 96), (3, 97), (3, 98), (1, 99); /*!40000 ALTER TABLE `rol_aplicacion` ENABLE KEYS */; -- Dumping structure for table violationsg.rol_usuario DROP TABLE IF EXISTS `rol_usuario`; CREATE TABLE IF NOT EXISTS `rol_usuario` ( `rol_id` int(4) NOT NULL, `usu_id` int(11) NOT NULL, PRIMARY KEY (`rol_id`,`usu_id`), KEY `fk_rol_usu_usu_id` (`usu_id`), CONSTRAINT `fk_rol_usu_rol_id` FOREIGN KEY (`rol_id`) REFERENCES `rol` (`rol_id`), CONSTRAINT `fk_rol_usu_usu_id` FOREIGN KEY (`usu_id`) REFERENCES `usuario` (`usu_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.rol_usuario: ~2 rows (approximately) DELETE FROM `rol_usuario`; /*!40000 ALTER TABLE `rol_usuario` DISABLE KEYS */; INSERT INTO `rol_usuario` (`rol_id`, `usu_id`) VALUES (1, 1), (2, 2); /*!40000 ALTER TABLE `rol_usuario` ENABLE KEYS */; -- Dumping structure for table violationsg.sector DROP TABLE IF EXISTS `sector`; CREATE TABLE IF NOT EXISTS `sector` ( `sec_id` int(11) NOT NULL AUTO_INCREMENT, `sec_nombre` varchar(45) NOT NULL, `sec_latitud` float(10,6) NOT NULL, `sec_longitud` float(10,6) NOT NULL, `ciu_id` int(11) NOT NULL, `sec_ubicacion` varchar(150) NOT NULL, `sec_valor_hora` decimal(10,2) NOT NULL, PRIMARY KEY (`sec_id`), KEY `fk_sector_ciudad_idx` (`ciu_id`), CONSTRAINT `fk_sector_ciudad` FOREIGN KEY (`ciu_id`) REFERENCES `ciudad` (`ciu_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.sector: ~3 rows (approximately) DELETE FROM `sector`; /*!40000 ALTER TABLE `sector` DISABLE KEYS */; INSERT INTO `sector` (`sec_id`, `sec_nombre`, `sec_latitud`, `sec_longitud`, `ciu_id`, `sec_ubicacion`, `sec_valor_hora`) VALUES (1, 'El Condado', -0.125281, -78.467361, 1, 'Juan molineros y calle d', 0.40), (5, 'El Labrador', -0.172981, -78.483574, 1, 'El Tiempo', 0.40), (6, 'Tumbco', -0.222741, -78.385780, 1, 'la morita', 0.40); /*!40000 ALTER TABLE `sector` ENABLE KEYS */; -- Dumping structure for table violationsg.tipo_infraccion DROP TABLE IF EXISTS `tipo_infraccion`; CREATE TABLE IF NOT EXISTS `tipo_infraccion` ( `tip_inf_id` int(4) NOT NULL AUTO_INCREMENT, `tip_inf_descripcion` varchar(150) NOT NULL, PRIMARY KEY (`tip_inf_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.tipo_infraccion: ~2 rows (approximately) DELETE FROM `tipo_infraccion`; /*!40000 ALTER TABLE `tipo_infraccion` DISABLE KEYS */; INSERT INTO `tipo_infraccion` (`tip_inf_id`, `tip_inf_descripcion`) VALUES (1, 'Exceso Vehicular'), (2, 'Mal Parqueo'); /*!40000 ALTER TABLE `tipo_infraccion` ENABLE KEYS */; -- Dumping structure for table violationsg.transaccion DROP TABLE IF EXISTS `transaccion`; CREATE TABLE IF NOT EXISTS `transaccion` ( `tra_id` int(11) NOT NULL AUTO_INCREMENT, `eta_id` int(11) NOT NULL, `cli_id` int(11) NOT NULL, `tra_valor` decimal(10,2) NOT NULL, `tra_saldo` decimal(10,2) NOT NULL, `tra_fecha` datetime NOT NULL, PRIMARY KEY (`tra_id`), KEY `fk_transacciones_establecimientos1_idx` (`eta_id`), KEY `fk_transacciones_clientes1_idx` (`cli_id`), CONSTRAINT `fk_transacciones_clientes1` FOREIGN KEY (`cli_id`) REFERENCES `cliente` (`cli_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_transaccion_establecimiento1` FOREIGN KEY (`eta_id`) REFERENCES `establecimiento` (`eta_id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.transaccion: ~1 rows (approximately) DELETE FROM `transaccion`; /*!40000 ALTER TABLE `transaccion` DISABLE KEYS */; INSERT INTO `transaccion` (`tra_id`, `eta_id`, `cli_id`, `tra_valor`, `tra_saldo`, `tra_fecha`) VALUES (1, 1, 1, 0.80, 0.00, '0000-00-00 00:00:00'); /*!40000 ALTER TABLE `transaccion` ENABLE KEYS */; -- Dumping structure for table violationsg.transferencia_saldo DROP TABLE IF EXISTS `transferencia_saldo`; CREATE TABLE IF NOT EXISTS `transferencia_saldo` ( `tra_sal_id` int(11) NOT NULL AUTO_INCREMENT, `cli_id_de` int(11) NOT NULL, `cli_id_para` int(11) NOT NULL, `tra_sal_valor` float DEFAULT NULL, `tra_sal_hora` timestamp NULL DEFAULT NULL, PRIMARY KEY (`tra_sal_id`), KEY `fk_transferencia_saldo_cliente1_idx` (`cli_id_de`), KEY `fk_transferencia_saldo_cliente2_idx` (`cli_id_para`), CONSTRAINT `fk_transferencia_saldo_cliente1` FOREIGN KEY (`cli_id_de`) REFERENCES `cliente` (`cli_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_transferencia_saldo_cliente2` FOREIGN KEY (`cli_id_para`) REFERENCES `cliente` (`cli_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.transferencia_saldo: ~0 rows (approximately) DELETE FROM `transferencia_saldo`; /*!40000 ALTER TABLE `transferencia_saldo` DISABLE KEYS */; /*!40000 ALTER TABLE `transferencia_saldo` ENABLE KEYS */; -- Dumping structure for table violationsg.usuario DROP TABLE IF EXISTS `usuario`; CREATE TABLE IF NOT EXISTS `usuario` ( `usu_id` int(11) NOT NULL AUTO_INCREMENT, `ciu_id` int(11) DEFAULT NULL, `usu_usuario` varchar(15) NOT NULL, `usu_email` varchar(150) NOT NULL, `usu_nombre` varchar(35) NOT NULL, `usu_apellido` varchar(35) NOT NULL, `usu_clave` char(32) NOT NULL, `usu_estado` char(1) NOT NULL, `usu_fecha_registro` datetime NOT NULL, PRIMARY KEY (`usu_id`), UNIQUE KEY `usu_usuario` (`usu_usuario`), KEY `fk_usu_ciu_id` (`ciu_id`), CONSTRAINT `fk_usu_ciu_id` FOREIGN KEY (`ciu_id`) REFERENCES `ciudad` (`ciu_id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- Dumping data for table violationsg.usuario: ~5 rows (approximately) DELETE FROM `usuario`; /*!40000 ALTER TABLE `usuario` DISABLE KEYS */; INSERT INTO `usuario` (`usu_id`, `ciu_id`, `usu_usuario`, `usu_email`, `usu_nombre`, `usu_apellido`, `usu_clave`, `usu_estado`, `usu_fecha_registro`) VALUES (1, 1, 'manucv', 'emanuelcarrasco@gmail.com', 'Emanuel', 'Carrasco', 'afa4557b6446efdc08d438626d80ecb9', 'A', '0000-00-00 00:00:00'), (2, 1, 'jose', 'jose@email.com', 'Jose', 'Jose', 'afa4557b6446efdc08d438626d80ecb9', 'A', '0000-00-00 00:00:00'), (3, 1, 'luis', 'lmponce@gmail.com', 'Luis', 'Ponce', 'afa4557b6446efdc08d438626d80ecb9', 'A', '2014-10-20 15:46:10'), (4, 1, 'Thomas', 'gerencia@ses.ec', 'Thomas', 'Fal.', '4a32fbff0fd7415ffedc13bb055475ec', 'A', '0000-00-00 00:00:00'), (5, 1, 'Vigilante1', 'vigilante@email.com', 'Vigilante1', 'Vigilante', '25490c7456ad7831b259dd8ec0675cbd', 'A', '0000-00-00 00:00:00'); /*!40000 ALTER TABLE `usuario` ENABLE KEYS */; -- Dumping structure for trigger violationsg.violations_automovil DROP TRIGGER IF EXISTS `violations_automovil`; SET @OLDTMP_SQL_MODE=@@SQL_MODE, SQL_MODE=''; DELIMITER // CREATE TRIGGER `violations_automovil` BEFORE INSERT ON `log_parqueadero` FOR EACH ROW INSERT IGNORE INTO `automovil` ( `aut_placa` ) VALUES ( NEW.aut_placa )// DELIMITER ; SET SQL_MODE=@OLDTMP_SQL_MODE; -- Dumping structure for trigger violationsg.violations_ocupado DROP TRIGGER IF EXISTS `violations_ocupado`; SET @OLDTMP_SQL_MODE=@@SQL_MODE, SQL_MODE=''; DELIMITER // CREATE TRIGGER `violations_ocupado` AFTER INSERT ON `log_parqueadero` FOR EACH ROW UPDATE parqueadero SET par_estado=NEW.log_par_estado WHERE par_id=NEW.par_id// DELIMITER ; SET SQL_MODE=@OLDTMP_SQL_MODE; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
manucv/Violations
db/app_SIP_20141020_v3.sql
SQL
bsd-3-clause
37,845
// Copyright 2013 The go-github AUTHORS. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package github import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" ) const ( libraryVersion = "0.1" defaultBaseURL = "https://api.github.com/" userAgent = "go-github/" + libraryVersion headerRateLimit = "X-RateLimit-Limit" headerRateRemaining = "X-RateLimit-Remaining" headerRateReset = "X-RateLimit-Reset" mimePreview = "application/vnd.github.preview" ) // A Client manages communication with the GitHub API. type Client struct { // HTTP client used to communicate with the API. client *http.Client // Base URL for API requests. Defaults to the public GitHub API, but can be // set to a domain endpoint to use with GitHub Enterprise. BaseURL should // always be specified with a trailing slash. BaseURL *url.URL // User agent used when communicating with the GitHub API. UserAgent string // Rate specifies the current rate limit for the client as determined by the // most recent API call. If the client is used in a multi-user application, // this rate may not always be up-to-date. Call RateLimit() to check the // current rate. Rate Rate // Services used for talking to different parts of the GitHub API. Activity *ActivityService Gists *GistsService Git *GitService Issues *IssuesService Organizations *OrganizationsService PullRequests *PullRequestsService Repositories *RepositoriesService Search *SearchService Users *UsersService } // ListOptions specifies the optional parameters to various List methods that // support pagination. type ListOptions struct { // For paginated result sets, page of results to retrieve. Page int } // NewClient returns a new GitHub API client. If a nil httpClient is // provided, http.DefaultClient will be used. To use API methods which require // authentication, provide an http.Client that will perform the authentication // for you (such as that provided by the goauth2 library). func NewClient(httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } baseURL, _ := url.Parse(defaultBaseURL) c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent} c.Activity = &ActivityService{client: c} c.Gists = &GistsService{client: c} c.Git = &GitService{client: c} c.Issues = &IssuesService{client: c} c.Organizations = &OrganizationsService{client: c} c.PullRequests = &PullRequestsService{client: c} c.Repositories = &RepositoriesService{client: c} c.Search = &SearchService{client: c} c.Users = &UsersService{client: c} return c } // NewRequest creates an API request. A relative URL can be provided in urlStr, // in which case it is resolved relative to the BaseURL of the Client. // Relative URLs should always be specified without a preceding slash. If // specified, the value pointed to by body is JSON encoded and included as the // request body. func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { rel, err := url.Parse(urlStr) if err != nil { return nil, err } u := c.BaseURL.ResolveReference(rel) buf := new(bytes.Buffer) if body != nil { err := json.NewEncoder(buf).Encode(body) if err != nil { return nil, err } } req, err := http.NewRequest(method, u.String(), buf) if err != nil { return nil, err } req.Header.Add("User-Agent", c.UserAgent) return req, nil } // Response is a GitHub API response. This wraps the standard http.Response // returned from GitHub and provides convenient access to things like // pagination links. type Response struct { *http.Response // These fields provide the page values for paginating through a set of // results. Any or all of these may be set to the zero value for // responses that are not part of a paginated set, or for which there // are no additional pages. NextPage int PrevPage int FirstPage int LastPage int Rate } // newResponse creats a new Response for the provided http.Response. func newResponse(r *http.Response) *Response { response := &Response{Response: r} response.populatePageValues() response.populateRate() return response } // populatePageValues parses the HTTP Link response headers and populates the // various pagination link values in the Reponse. func (r *Response) populatePageValues() { if links, ok := r.Response.Header["Link"]; ok && len(links) > 0 { for _, link := range strings.Split(links[0], ",") { segments := strings.Split(strings.TrimSpace(link), ";") // link must at least have href and rel if len(segments) < 2 { continue } // ensure href is properly formatted if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") { continue } // try to pull out page parameter url, err := url.Parse(segments[0][1 : len(segments[0])-1]) if err != nil { continue } page := url.Query().Get("page") if page == "" { continue } for _, segment := range segments[1:] { switch strings.TrimSpace(segment) { case `rel="next"`: r.NextPage, _ = strconv.Atoi(page) case `rel="prev"`: r.PrevPage, _ = strconv.Atoi(page) case `rel="first"`: r.FirstPage, _ = strconv.Atoi(page) case `rel="last"`: r.LastPage, _ = strconv.Atoi(page) } } } } } // populateRate parses the rate related headers and populates the response Rate. func (r *Response) populateRate() { if limit := r.Header.Get(headerRateLimit); limit != "" { r.Rate.Limit, _ = strconv.Atoi(limit) } if remaining := r.Header.Get(headerRateRemaining); remaining != "" { r.Rate.Remaining, _ = strconv.Atoi(remaining) } if reset := r.Header.Get(headerRateReset); reset != "" { if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 { r.Rate.Reset = time.Unix(v, 0) } } } // Do sends an API request and returns the API response. The API response is // decoded and stored in the value pointed to by v, or returned as an error if // an API error has occurred. func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) { resp, err := c.client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() response := newResponse(resp) c.Rate = response.Rate err = CheckResponse(resp) if err != nil { // even though there was an error, we still return the response // in case the caller wants to inspect it further return response, err } if v != nil { err = json.NewDecoder(resp.Body).Decode(v) } return response, err } /* An ErrorResponse reports one or more errors caused by an API request. GitHub API docs: http://developer.github.com/v3/#client-errors */ type ErrorResponse struct { Response *http.Response // HTTP response that caused this error Message string `json:"message"` // error message Errors []Error `json:"errors"` // more detail on individual errors } func (r *ErrorResponse) Error() string { return fmt.Sprintf("%v %v: %d %v %+v", r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, r.Message, r.Errors) } /* An Error reports more details on an individual error in an ErrorResponse. These are the possible validation error codes: missing: resource does not exist missing_field: a required field on a resource has not been set invalid: the formatting of a field is invalid already_exists: another resource has the same valid as this field GitHub API docs: http://developer.github.com/v3/#client-errors */ type Error struct { Resource string `json:"resource"` // resource on which the error occurred Field string `json:"field"` // field on which the error occurred Code string `json:"code"` // validation error code } func (e *Error) Error() string { return fmt.Sprintf("%v error caused by %v field on %v resource", e.Code, e.Field, e.Resource) } // CheckResponse checks the API response for errors, and returns them if // present. A response is considered an error if it has a status code outside // the 200 range. API error responses are expected to have either no response // body, or a JSON response body that maps to ErrorResponse. Any other // response body will be silently ignored. func CheckResponse(r *http.Response) error { if c := r.StatusCode; 200 <= c && c <= 299 { return nil } errorResponse := &ErrorResponse{Response: r} data, err := ioutil.ReadAll(r.Body) if err == nil && data != nil { json.Unmarshal(data, errorResponse) } return errorResponse } // parseBoolResponse determines the boolean result from a GitHub API response. // Several GitHub API methods return boolean responses indicated by the HTTP // status code in the response (true indicated by a 204, false indicated by a // 404). This helper function will determine that result and hide the 404 // error if present. Any other error will be returned through as-is. func parseBoolResponse(err error) (bool, error) { if err == nil { return true, nil } if err, ok := err.(*ErrorResponse); ok && err.Response.StatusCode == http.StatusNotFound { // Simply false. In this one case, we do not pass the error through. return false, nil } // some other real error occurred return false, err } // API response wrapper to a rate limit request. type rateResponse struct { Rate struct { Limit int `json:"limit"` Remaining int `json:"remaining"` Reset int64 `json:"reset"` } `json:"rate"` } // Rate represents the rate limit for the current client. Unauthenticated // requests are limited to 60 per hour. Authenticated requests are limited to // 5,000 per hour. type Rate struct { // The number of requests per hour the client is currently limited to. Limit int // The number of remaining requests the client can make this hour. Remaining int // The time at which the current rate limit will reset. Reset time.Time } // RateLimit returns the rate limit for the current client. func (c *Client) RateLimit() (*Rate, *Response, error) { req, err := c.NewRequest("GET", "rate_limit", nil) if err != nil { return nil, nil, err } response := new(rateResponse) resp, err := c.Do(req, response) if err != nil { return nil, nil, err } rate := &Rate{ Limit: response.Rate.Limit, Remaining: response.Rate.Remaining, Reset: time.Unix(response.Rate.Reset, 0), } return rate, resp, err } /* UnauthenticatedRateLimitedTransport allows you to make unauthenticated calls that need to use a higher rate limit associated with your OAuth application. t := &github.UnauthenticatedRateLimitedTransport{ ClientID: "your app's client ID", ClientSecret: "your app's client secret", } client := github.NewClient(t.Client()) This will append the querystring params client_id=xxx&client_secret=yyy to all requests. See http://developer.github.com/v3/#unauthenticated-rate-limited-requests for more information. */ type UnauthenticatedRateLimitedTransport struct { // ClientID is the GitHub OAuth client ID of the current application, which // can be found by selecting its entry in the list at // https://github.com/settings/applications. ClientID string // ClientSecret is the GitHub OAuth client secret of the current // application. ClientSecret string // Transport is the underlying HTTP transport to use when making requests. // It will default to http.DefaultTransport if nil. Transport http.RoundTripper } // RoundTrip implements the RoundTripper interface. func (t *UnauthenticatedRateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error) { if t.ClientID == "" { return nil, errors.New("ClientID is empty") } if t.ClientSecret == "" { return nil, errors.New("ClientSecret is empty") } // To set extra querystring params, we must make a copy of the Request so // that we don't modify the Request we were given. This is required by the // specification of http.RoundTripper. req = cloneRequest(req) q := req.URL.Query() q.Set("client_id", t.ClientID) q.Set("client_secret", t.ClientSecret) req.URL.RawQuery = q.Encode() // Make the HTTP request. return t.transport().RoundTrip(req) } // Client returns an *http.Client that makes requests which are subject to the // rate limit of your OAuth application. func (t *UnauthenticatedRateLimitedTransport) Client() *http.Client { return &http.Client{Transport: t} } func (t *UnauthenticatedRateLimitedTransport) transport() http.RoundTripper { if t.Transport != nil { return t.Transport } return http.DefaultTransport } // cloneRequest returns a clone of the provided *http.Request. The clone is a // shallow copy of the struct and its Header map. func cloneRequest(r *http.Request) *http.Request { // shallow copy of the struct r2 := new(http.Request) *r2 = *r // deep copy of the Header r2.Header = make(http.Header) for k, s := range r.Header { r2.Header[k] = s } return r2 } // Bool is a helper routine that allocates a new bool value // to store v and returns a pointer to it. func Bool(v bool) *bool { p := new(bool) *p = v return p } // Int is a helper routine that allocates a new int32 value // to store v and returns a pointer to it, but unlike Int32 // its argument value is an int. func Int(v int) *int { p := new(int) *p = v return p } // String is a helper routine that allocates a new string value // to store v and returns a pointer to it. func String(v string) *string { p := new(string) *p = v return p }
Archie22is/go-github
github/github.go
GO
bsd-3-clause
13,602
import pytest import bauble.db as db from bauble.model.family import Family from bauble.model.genus import Genus, GenusSynonym, GenusNote import test.api as api @pytest.fixture def setup(organization, session): setup.organization = session.merge(organization) setup.user = setup.organization.owners[0] setup.session = session db.set_session_schema(session, setup.organization.pg_schema) return setup def test_genus_json(setup): session = setup.session family = Family(family=api.get_random_name()) genus_name = api.get_random_name() genus = Genus(family=family, genus=genus_name) note = GenusNote(genus=genus, note="this is a test") syn = GenusSynonym(genus=genus, synonym=genus) session.add_all([family, genus, note, syn]) session.commit() genus_json = genus.json() assert 'id' in genus_json assert genus_json['id'] == genus.id assert 'genus' in genus_json assert 'str' in genus_json assert 'qualifier' in genus_json note_json = note.json() assert 'id' in note_json assert 'genus_id' in note_json assert note_json['genus_id'] == genus.id syn_json = syn.json() assert 'id' in syn_json assert syn_json['genus_id'] == genus.id assert syn_json['synonym_id'] == genus.id session.delete(genus) session.commit() session.close() def test_server(setup): """ Test the server properly handle /genus resources """ user = setup.user family = api.create_resource('/family', {'family': api.get_random_name()}, user) # create a genus first_genus = api.create_resource('/genus', {'genus': api.get_random_name(), 'family': family}, user) # create another genus and use the first as a synonym data = {'genus': api.get_random_name(), 'family': family, 'notes': [{'user': 'me', 'category': 'test', 'date': '2001-1-1', 'note': 'test note'}, {'user': 'me', 'category': 'test', 'date': '2002-2-2', 'note': 'test note2'}], 'synonyms': [first_genus] #'synonyms': [{'synonym': first_genus}] } second_genus = api.create_resource('/genus', data, user) assert 'id' in second_genus # created # update the genus second_genus['genus'] = api.get_random_name() second_id = second_genus['id'] second_genus = api.update_resource('/genus/' + str(second_id), second_genus, user=user) assert second_genus['id'] == second_id # make sure they have the same id after the update # get the genus first_genus = api.get_resource('/genus/' + str(first_genus['id']), user=user) # query for genera and make sure the second genus is in the results genera = api.query_resource('/genus', q=second_genus['genus'], user=user) # TODO: ** shouldn't len(genera) be 1 since the name should be unique #assert second_genus['ref'] in [genus['ref'] for genus in genera] assert second_genus['id'] in [genus['id'] for genus in genera] # test getting the genus relative to its family # ** TODO: now we just embed the relation in the /genera/:id # ** request....need to create a test to make sure it's happening # genera = api.get_resource('/family/' + str(family['id']) + "/genera", user=user) # assert first_genus['id'] in [genus['id'] for genus in genera] # test getting a family with its genera relations # ** TODO: now we just embed the relation in the /genera/:id # ** request....need to create a test to make sure it's happening #response_json = api.query_resource('/family', q=family['family'], relations="genera,notes", user=user) #families = response_json # TODO: *** i don't know if we still support returning relations like this...do # we need to # print(families[0]['genera']) # assert first_genus['ref'] in [genus['ref'] for genus in families[0]['genera']] # count the number of genera on a family # TODO: ** count is temporarily disabled # count = api.count_resource(family['ref'] + "/genera") # assert count == "2" # delete the created resources api.delete_resource('/genus/' + str(first_genus['id']), user) api.delete_resource('/genus/' + str(second_genus['id']), user) api.delete_resource('/family/' + str(family['id']), user)
Bauble/bauble.api
test/spec/test_genus.py
Python
bsd-3-clause
4,372
<html> <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/console-test.js"></script> <script> // Global Values var globals = []; function log(current) { console.log(globals[current]); console.log([globals[current]]); } function onload() { var foo = { foo: "foo"}; var bar = { bar: "bar" }; bar.__proto__ = foo; var array = ["test", "test2"]; array.length = 10; array.foo = {}; array[4] = "test4"; var svg = document.getElementById("svg-node"); console.log(array); console.log("%o", array); console.log("%O", array); console.log("Test for zero \"%f\" in formatter", 0); console.log("%% self-escape1", "dummy"); console.log("%%s self-escape2", "dummy"); console.log("%%ss self-escape3", "dummy"); console.log("%%s%s%%s self-escape4", "dummy"); console.log("%%%%% self-escape5", "dummy"); console.log("%%%s self-escape6", "dummy"); // Populate Globals var regex1 = /^url\(\s*(?:(?:"(?:[^\\\"]|(?:\\[\da-f]{1,6}\s?|\.))*"|'(?:[^\\\']|(?:\\[\da-f]{1,6}\s?|\.))*')|(?:[!#$%&*-~\w]|(?:\\[\da-f]{1,6}\s?|\.))*)\s*\)/i; var regex2 = new RegExp("foo\\\\bar\\sbaz", "i"); var str = "test"; var str2 = "test named \"test\""; var error = new Error; var errorWithMessage = new Error("my error message"); var node = document.getElementById("p"); var func = function() { return 1; }; var multilinefunc = function() { return 2; }; var num = 1.2e-1; var linkify = "http://webkit.org/"; var valuelessAttribute = document.createAttribute("attr"); var valuedAttribute = document.createAttribute("attr"); valuedAttribute.value = "value"; var existingAttribute = document.getElementById("x").attributes[0]; var throwingLengthGetter = {get length() { throw "Length called"; }}; var objectWithNonEnumerables = Object.create({ foo: 1 }, { getFoo: { value: function() { return this.foo; } }, bar: { get: function() { return this.bar; }, set: function(x) { this.bar = x; } } }); var negZero = 1 / Number.NEGATIVE_INFINITY; var textNode = document.getElementById("x").nextSibling; var arrayLikeFunction = function( /**/ foo/**/, /*/**/bar, /**/baz) {}; arrayLikeFunction.splice = function() {}; var smallTypedArray = new Uint8Array(new ArrayBuffer(400)); smallTypedArray["foo"] = "bar"; var bigTypedArray = new Uint8Array(new ArrayBuffer(400 * 1000 * 1000)); bigTypedArray["FAIL"] = "FAIL: Object.getOwnPropertyNames() should not have been run"; globals = [ regex1, regex2, str, str2, error, errorWithMessage, node, func, multilinefunc, num, linkify, null, undefined, valuelessAttribute, valuedAttribute, existingAttribute, throwingLengthGetter, NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, array, {}, [function() {}], bar, svg, objectWithNonEnumerables, negZero, Object.create(null), Object, Object.prototype, arrayLikeFunction, new Number(42), new String("abc"), new Uint16Array([1, 2, 3]), textNode, domException(), smallTypedArray, bigTypedArray ]; runTest(); } function domException() { var result = "FAIL"; try { var a = document.createElement("div"); var b = document.createElement("div"); a.removeChild(b); } catch(e) { e.stack = ""; result = e; } return result; } function test() { InspectorTest.hideInspectorView(); InspectorTest.evaluateInPage("globals.length", loopOverGlobals.bind(this, 0)); function loopOverGlobals(current, total) { function advance() { var next = current + 1; if (next == total.description) InspectorTest.waitForRemoteObjectsConsoleMessages(onRemoteObjectsLoaded); else loopOverGlobals(next, total); } function onRemoteObjectsLoaded() { InspectorTest.expandConsoleMessages(finish, undefined, function(section) { return section.titleElement.textContent !== "#text"; }); } function finish() { InspectorTest.dumpConsoleMessagesIgnoreErrorStackFrames(); InspectorTest.completeTest(); } InspectorTest.evaluateInPage("log(" + current + ")"); InspectorTest.runAfterPendingDispatches(evalInConsole); function evalInConsole() { InspectorTest.evaluateInConsole("globals[" + current + "]"); InspectorTest.runAfterPendingDispatches(advance); } } } </script> </head> <body onload="onload()"> <div id="x"></div> <p id="p">Tests that console logging dumps proper messages.</p> </body> <svg id="svg-node"></svg> </html>
kurli/blink-crosswalk
LayoutTests/inspector/console/console-format.html
HTML
bsd-3-clause
4,794
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "server.h" /*----------------------------------------------------------------------------- * Set Commands *----------------------------------------------------------------------------*/ void sunionDiffGenericCommand(client *c, robj **setkeys, int setnum, robj *dstkey, int op); /* Factory method to return a set that *can* hold "value". When the object has * an integer-encodable value, an intset will be returned. Otherwise a regular * hash table. */ robj *setTypeCreate(sds value) { if (isSdsRepresentableAsLongLong(value,NULL) == C_OK) return createIntsetObject(); return createSetObject(); } /* Add the specified value into a set. * * If the value was already member of the set, nothing is done and 0 is * returned, otherwise the new element is added and 1 is returned. */ int setTypeAdd(robj *subject, sds value) { long long llval; if (subject->encoding == OBJ_ENCODING_HT) { dict *ht = subject->ptr; dictEntry *de = dictAddRaw(ht,value,NULL); if (de) { dictSetKey(ht,de,sdsdup(value)); dictSetVal(ht,de,NULL); return 1; } } else if (subject->encoding == OBJ_ENCODING_INTSET) { if (isSdsRepresentableAsLongLong(value,&llval) == C_OK) { uint8_t success = 0; subject->ptr = intsetAdd(subject->ptr,llval,&success); if (success) { /* Convert to regular set when the intset contains * too many entries. */ if (intsetLen(subject->ptr) > server.set_max_intset_entries) setTypeConvert(subject,OBJ_ENCODING_HT); return 1; } } else { /* Failed to get integer from object, convert to regular set. */ setTypeConvert(subject,OBJ_ENCODING_HT); /* The set *was* an intset and this value is not integer * encodable, so dictAdd should always work. */ serverAssert(dictAdd(subject->ptr,sdsdup(value),NULL) == DICT_OK); return 1; } } else { serverPanic("Unknown set encoding"); } return 0; } int setTypeRemove(robj *setobj, sds value) { long long llval; if (setobj->encoding == OBJ_ENCODING_HT) { if (dictDelete(setobj->ptr,value) == DICT_OK) { if (htNeedsResize(setobj->ptr)) dictResize(setobj->ptr); return 1; } } else if (setobj->encoding == OBJ_ENCODING_INTSET) { if (isSdsRepresentableAsLongLong(value,&llval) == C_OK) { int success; setobj->ptr = intsetRemove(setobj->ptr,llval,&success); if (success) return 1; } } else { serverPanic("Unknown set encoding"); } return 0; } int setTypeIsMember(robj *subject, sds value) { long long llval; if (subject->encoding == OBJ_ENCODING_HT) { return dictFind((dict*)subject->ptr,value) != NULL; } else if (subject->encoding == OBJ_ENCODING_INTSET) { if (isSdsRepresentableAsLongLong(value,&llval) == C_OK) { return intsetFind((intset*)subject->ptr,llval); } } else { serverPanic("Unknown set encoding"); } return 0; } setTypeIterator *setTypeInitIterator(robj *subject) { setTypeIterator *si = zmalloc(sizeof(setTypeIterator)); si->subject = subject; si->encoding = subject->encoding; if (si->encoding == OBJ_ENCODING_HT) { si->di = dictGetIterator(subject->ptr); } else if (si->encoding == OBJ_ENCODING_INTSET) { si->ii = 0; } else { serverPanic("Unknown set encoding"); } return si; } void setTypeReleaseIterator(setTypeIterator *si) { if (si->encoding == OBJ_ENCODING_HT) dictReleaseIterator(si->di); zfree(si); } /* Move to the next entry in the set. Returns the object at the current * position. * * Since set elements can be internally be stored as SDS strings or * simple arrays of integers, setTypeNext returns the encoding of the * set object you are iterating, and will populate the appropriate pointer * (sdsele) or (llele) accordingly. * * Note that both the sdsele and llele pointers should be passed and cannot * be NULL since the function will try to defensively populate the non * used field with values which are easy to trap if misused. * * When there are no longer elements -1 is returned. */ int setTypeNext(setTypeIterator *si, sds *sdsele, int64_t *llele) { if (si->encoding == OBJ_ENCODING_HT) { dictEntry *de = dictNext(si->di); if (de == NULL) return -1; *sdsele = dictGetKey(de); *llele = -123456789; /* Not needed. Defensive. */ } else if (si->encoding == OBJ_ENCODING_INTSET) { if (!intsetGet(si->subject->ptr,si->ii++,llele)) return -1; *sdsele = NULL; /* Not needed. Defensive. */ } else { serverPanic("Wrong set encoding in setTypeNext"); } return si->encoding; } /* The not copy on write friendly version but easy to use version * of setTypeNext() is setTypeNextObject(), returning new SDS * strings. So if you don't retain a pointer to this object you should call * sdsfree() against it. * * This function is the way to go for write operations where COW is not * an issue. */ sds setTypeNextObject(setTypeIterator *si) { int64_t intele; sds sdsele; int encoding; encoding = setTypeNext(si,&sdsele,&intele); switch(encoding) { case -1: return NULL; case OBJ_ENCODING_INTSET: return sdsfromlonglong(intele); case OBJ_ENCODING_HT: return sdsdup(sdsele); default: serverPanic("Unsupported encoding"); } return NULL; /* just to suppress warnings */ } /* Return random element from a non empty set. * The returned element can be an int64_t value if the set is encoded * as an "intset" blob of integers, or an SDS string if the set * is a regular set. * * The caller provides both pointers to be populated with the right * object. The return value of the function is the object->encoding * field of the object and is used by the caller to check if the * int64_t pointer or the redis object pointer was populated. * * Note that both the sdsele and llele pointers should be passed and cannot * be NULL since the function will try to defensively populate the non * used field with values which are easy to trap if misused. */ int setTypeRandomElement(robj *setobj, sds *sdsele, int64_t *llele) { if (setobj->encoding == OBJ_ENCODING_HT) { dictEntry *de = dictGetFairRandomKey(setobj->ptr); *sdsele = dictGetKey(de); *llele = -123456789; /* Not needed. Defensive. */ } else if (setobj->encoding == OBJ_ENCODING_INTSET) { *llele = intsetRandom(setobj->ptr); *sdsele = NULL; /* Not needed. Defensive. */ } else { serverPanic("Unknown set encoding"); } return setobj->encoding; } unsigned long setTypeSize(const robj *subject) { if (subject->encoding == OBJ_ENCODING_HT) { return dictSize((const dict*)subject->ptr); } else if (subject->encoding == OBJ_ENCODING_INTSET) { return intsetLen((const intset*)subject->ptr); } else { serverPanic("Unknown set encoding"); } } /* Convert the set to specified encoding. The resulting dict (when converting * to a hash table) is presized to hold the number of elements in the original * set. */ void setTypeConvert(robj *setobj, int enc) { setTypeIterator *si; serverAssertWithInfo(NULL,setobj,setobj->type == OBJ_SET && setobj->encoding == OBJ_ENCODING_INTSET); if (enc == OBJ_ENCODING_HT) { int64_t intele; dict *d = dictCreate(&setDictType,NULL); sds element; /* Presize the dict to avoid rehashing */ dictExpand(d,intsetLen(setobj->ptr)); /* To add the elements we extract integers and create redis objects */ si = setTypeInitIterator(setobj); while (setTypeNext(si,&element,&intele) != -1) { element = sdsfromlonglong(intele); serverAssert(dictAdd(d,element,NULL) == DICT_OK); } setTypeReleaseIterator(si); setobj->encoding = OBJ_ENCODING_HT; zfree(setobj->ptr); setobj->ptr = d; } else { serverPanic("Unsupported set conversion"); } } /* This is a helper function for the COPY command. * Duplicate a set object, with the guarantee that the returned object * has the same encoding as the original one. * * The resulting object always has refcount set to 1 */ robj *setTypeDup(robj *o) { robj *set; setTypeIterator *si; sds elesds; int64_t intobj; serverAssert(o->type == OBJ_SET); /* Create a new set object that have the same encoding as the original object's encoding */ if (o->encoding == OBJ_ENCODING_INTSET) { intset *is = o->ptr; size_t size = intsetBlobLen(is); intset *newis = zmalloc(size); memcpy(newis,is,size); set = createObject(OBJ_SET, newis); set->encoding = OBJ_ENCODING_INTSET; } else if (o->encoding == OBJ_ENCODING_HT) { set = createSetObject(); dict *d = o->ptr; dictExpand(set->ptr, dictSize(d)); si = setTypeInitIterator(o); while (setTypeNext(si, &elesds, &intobj) != -1) { setTypeAdd(set, elesds); } setTypeReleaseIterator(si); } else { serverPanic("Unknown set encoding"); } return set; } void saddCommand(client *c) { robj *set; int j, added = 0; set = lookupKeyWrite(c->db,c->argv[1]); if (checkType(c,set,OBJ_SET)) return; if (set == NULL) { set = setTypeCreate(c->argv[2]->ptr); dbAdd(c->db,c->argv[1],set); } for (j = 2; j < c->argc; j++) { if (setTypeAdd(set,c->argv[j]->ptr)) added++; } if (added) { signalModifiedKey(c,c->db,c->argv[1]); notifyKeyspaceEvent(NOTIFY_SET,"sadd",c->argv[1],c->db->id); } server.dirty += added; addReplyLongLong(c,added); } void sremCommand(client *c) { robj *set; int j, deleted = 0, keyremoved = 0; if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL || checkType(c,set,OBJ_SET)) return; for (j = 2; j < c->argc; j++) { if (setTypeRemove(set,c->argv[j]->ptr)) { deleted++; if (setTypeSize(set) == 0) { dbDelete(c->db,c->argv[1]); keyremoved = 1; break; } } } if (deleted) { signalModifiedKey(c,c->db,c->argv[1]); notifyKeyspaceEvent(NOTIFY_SET,"srem",c->argv[1],c->db->id); if (keyremoved) notifyKeyspaceEvent(NOTIFY_GENERIC,"del",c->argv[1], c->db->id); server.dirty += deleted; } addReplyLongLong(c,deleted); } void smoveCommand(client *c) { robj *srcset, *dstset, *ele; srcset = lookupKeyWrite(c->db,c->argv[1]); dstset = lookupKeyWrite(c->db,c->argv[2]); ele = c->argv[3]; /* If the source key does not exist return 0 */ if (srcset == NULL) { addReply(c,shared.czero); return; } /* If the source key has the wrong type, or the destination key * is set and has the wrong type, return with an error. */ if (checkType(c,srcset,OBJ_SET) || checkType(c,dstset,OBJ_SET)) return; /* If srcset and dstset are equal, SMOVE is a no-op */ if (srcset == dstset) { addReply(c,setTypeIsMember(srcset,ele->ptr) ? shared.cone : shared.czero); return; } /* If the element cannot be removed from the src set, return 0. */ if (!setTypeRemove(srcset,ele->ptr)) { addReply(c,shared.czero); return; } notifyKeyspaceEvent(NOTIFY_SET,"srem",c->argv[1],c->db->id); /* Remove the src set from the database when empty */ if (setTypeSize(srcset) == 0) { dbDelete(c->db,c->argv[1]); notifyKeyspaceEvent(NOTIFY_GENERIC,"del",c->argv[1],c->db->id); } /* Create the destination set when it doesn't exist */ if (!dstset) { dstset = setTypeCreate(ele->ptr); dbAdd(c->db,c->argv[2],dstset); } signalModifiedKey(c,c->db,c->argv[1]); signalModifiedKey(c,c->db,c->argv[2]); server.dirty++; /* An extra key has changed when ele was successfully added to dstset */ if (setTypeAdd(dstset,ele->ptr)) { server.dirty++; notifyKeyspaceEvent(NOTIFY_SET,"sadd",c->argv[2],c->db->id); } addReply(c,shared.cone); } void sismemberCommand(client *c) { robj *set; if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL || checkType(c,set,OBJ_SET)) return; if (setTypeIsMember(set,c->argv[2]->ptr)) addReply(c,shared.cone); else addReply(c,shared.czero); } void smismemberCommand(client *c) { robj *set; int j; /* Don't abort when the key cannot be found. Non-existing keys are empty * sets, where SMISMEMBER should respond with a series of zeros. */ set = lookupKeyRead(c->db,c->argv[1]); if (set && checkType(c,set,OBJ_SET)) return; addReplyArrayLen(c,c->argc - 2); for (j = 2; j < c->argc; j++) { if (set && setTypeIsMember(set,c->argv[j]->ptr)) addReply(c,shared.cone); else addReply(c,shared.czero); } } void scardCommand(client *c) { robj *o; if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL || checkType(c,o,OBJ_SET)) return; addReplyLongLong(c,setTypeSize(o)); } /* Handle the "SPOP key <count>" variant. The normal version of the * command is handled by the spopCommand() function itself. */ /* How many times bigger should be the set compared to the remaining size * for us to use the "create new set" strategy? Read later in the * implementation for more info. */ #define SPOP_MOVE_STRATEGY_MUL 5 void spopWithCountCommand(client *c) { long l; unsigned long count, size; robj *set; /* Get the count argument */ if (getPositiveLongFromObjectOrReply(c,c->argv[2],&l,NULL) != C_OK) return; count = (unsigned long) l; /* Make sure a key with the name inputted exists, and that it's type is * indeed a set. Otherwise, return nil */ if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.emptyset[c->resp])) == NULL || checkType(c,set,OBJ_SET)) return; /* If count is zero, serve an empty set ASAP to avoid special * cases later. */ if (count == 0) { addReply(c,shared.emptyset[c->resp]); return; } size = setTypeSize(set); /* Generate an SPOP keyspace notification */ notifyKeyspaceEvent(NOTIFY_SET,"spop",c->argv[1],c->db->id); server.dirty += (count >= size) ? size : count; /* CASE 1: * The number of requested elements is greater than or equal to * the number of elements inside the set: simply return the whole set. */ if (count >= size) { /* We just return the entire set */ sunionDiffGenericCommand(c,c->argv+1,1,NULL,SET_OP_UNION); /* Delete the set as it is now empty */ dbDelete(c->db,c->argv[1]); notifyKeyspaceEvent(NOTIFY_GENERIC,"del",c->argv[1],c->db->id); /* Propagate this command as a DEL operation */ rewriteClientCommandVector(c,2,shared.del,c->argv[1]); signalModifiedKey(c,c->db,c->argv[1]); return; } /* Case 2 and 3 require to replicate SPOP as a set of SREM commands. * Prepare our replication argument vector. Also send the array length * which is common to both the code paths. */ robj *propargv[3]; propargv[0] = shared.srem; propargv[1] = c->argv[1]; addReplySetLen(c,count); /* Common iteration vars. */ sds sdsele; robj *objele; int encoding; int64_t llele; unsigned long remaining = size-count; /* Elements left after SPOP. */ /* If we are here, the number of requested elements is less than the * number of elements inside the set. Also we are sure that count < size. * Use two different strategies. * * CASE 2: The number of elements to return is small compared to the * set size. We can just extract random elements and return them to * the set. */ if (remaining*SPOP_MOVE_STRATEGY_MUL > count) { while(count--) { /* Emit and remove. */ encoding = setTypeRandomElement(set,&sdsele,&llele); if (encoding == OBJ_ENCODING_INTSET) { addReplyBulkLongLong(c,llele); objele = createStringObjectFromLongLong(llele); set->ptr = intsetRemove(set->ptr,llele,NULL); } else { addReplyBulkCBuffer(c,sdsele,sdslen(sdsele)); objele = createStringObject(sdsele,sdslen(sdsele)); setTypeRemove(set,sdsele); } /* Replicate/AOF this command as an SREM operation */ propargv[2] = objele; alsoPropagate(server.sremCommand,c->db->id,propargv,3, PROPAGATE_AOF|PROPAGATE_REPL); decrRefCount(objele); } } else { /* CASE 3: The number of elements to return is very big, approaching * the size of the set itself. After some time extracting random elements * from such a set becomes computationally expensive, so we use * a different strategy, we extract random elements that we don't * want to return (the elements that will remain part of the set), * creating a new set as we do this (that will be stored as the original * set). Then we return the elements left in the original set and * release it. */ robj *newset = NULL; /* Create a new set with just the remaining elements. */ while(remaining--) { encoding = setTypeRandomElement(set,&sdsele,&llele); if (encoding == OBJ_ENCODING_INTSET) { sdsele = sdsfromlonglong(llele); } else { sdsele = sdsdup(sdsele); } if (!newset) newset = setTypeCreate(sdsele); setTypeAdd(newset,sdsele); setTypeRemove(set,sdsele); sdsfree(sdsele); } /* Transfer the old set to the client. */ setTypeIterator *si; si = setTypeInitIterator(set); while((encoding = setTypeNext(si,&sdsele,&llele)) != -1) { if (encoding == OBJ_ENCODING_INTSET) { addReplyBulkLongLong(c,llele); objele = createStringObjectFromLongLong(llele); } else { addReplyBulkCBuffer(c,sdsele,sdslen(sdsele)); objele = createStringObject(sdsele,sdslen(sdsele)); } /* Replicate/AOF this command as an SREM operation */ propargv[2] = objele; alsoPropagate(server.sremCommand,c->db->id,propargv,3, PROPAGATE_AOF|PROPAGATE_REPL); decrRefCount(objele); } setTypeReleaseIterator(si); /* Assign the new set as the key value. */ dbOverwrite(c->db,c->argv[1],newset); } /* Don't propagate the command itself even if we incremented the * dirty counter. We don't want to propagate an SPOP command since * we propagated the command as a set of SREMs operations using * the alsoPropagate() API. */ preventCommandPropagation(c); signalModifiedKey(c,c->db,c->argv[1]); } void spopCommand(client *c) { robj *set, *ele; sds sdsele; int64_t llele; int encoding; if (c->argc == 3) { spopWithCountCommand(c); return; } else if (c->argc > 3) { addReplyErrorObject(c,shared.syntaxerr); return; } /* Make sure a key with the name inputted exists, and that it's type is * indeed a set */ if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.null[c->resp])) == NULL || checkType(c,set,OBJ_SET)) return; /* Get a random element from the set */ encoding = setTypeRandomElement(set,&sdsele,&llele); /* Remove the element from the set */ if (encoding == OBJ_ENCODING_INTSET) { ele = createStringObjectFromLongLong(llele); set->ptr = intsetRemove(set->ptr,llele,NULL); } else { ele = createStringObject(sdsele,sdslen(sdsele)); setTypeRemove(set,ele->ptr); } notifyKeyspaceEvent(NOTIFY_SET,"spop",c->argv[1],c->db->id); /* Replicate/AOF this command as an SREM operation */ rewriteClientCommandVector(c,3,shared.srem,c->argv[1],ele); /* Add the element to the reply */ addReplyBulk(c,ele); decrRefCount(ele); /* Delete the set if it's empty */ if (setTypeSize(set) == 0) { dbDelete(c->db,c->argv[1]); notifyKeyspaceEvent(NOTIFY_GENERIC,"del",c->argv[1],c->db->id); } /* Set has been modified */ signalModifiedKey(c,c->db,c->argv[1]); server.dirty++; } /* handle the "SRANDMEMBER key <count>" variant. The normal version of the * command is handled by the srandmemberCommand() function itself. */ /* How many times bigger should be the set compared to the requested size * for us to don't use the "remove elements" strategy? Read later in the * implementation for more info. */ #define SRANDMEMBER_SUB_STRATEGY_MUL 3 void srandmemberWithCountCommand(client *c) { long l; unsigned long count, size; int uniq = 1; robj *set; sds ele; int64_t llele; int encoding; dict *d; if (getLongFromObjectOrReply(c,c->argv[2],&l,NULL) != C_OK) return; if (l >= 0) { count = (unsigned long) l; } else { /* A negative count means: return the same elements multiple times * (i.e. don't remove the extracted element after every extraction). */ count = -l; uniq = 0; } if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.emptyarray)) == NULL || checkType(c,set,OBJ_SET)) return; size = setTypeSize(set); /* If count is zero, serve it ASAP to avoid special cases later. */ if (count == 0) { addReply(c,shared.emptyarray); return; } /* CASE 1: The count was negative, so the extraction method is just: * "return N random elements" sampling the whole set every time. * This case is trivial and can be served without auxiliary data * structures. This case is the only one that also needs to return the * elements in random order. */ if (!uniq || count == 1) { addReplyArrayLen(c,count); while(count--) { encoding = setTypeRandomElement(set,&ele,&llele); if (encoding == OBJ_ENCODING_INTSET) { addReplyBulkLongLong(c,llele); } else { addReplyBulkCBuffer(c,ele,sdslen(ele)); } } return; } /* CASE 2: * The number of requested elements is greater than the number of * elements inside the set: simply return the whole set. */ if (count >= size) { setTypeIterator *si; addReplyArrayLen(c,size); si = setTypeInitIterator(set); while ((encoding = setTypeNext(si,&ele,&llele)) != -1) { if (encoding == OBJ_ENCODING_INTSET) { addReplyBulkLongLong(c,llele); } else { addReplyBulkCBuffer(c,ele,sdslen(ele)); } size--; } setTypeReleaseIterator(si); serverAssert(size==0); return; } /* For CASE 3 and CASE 4 we need an auxiliary dictionary. */ d = dictCreate(&sdsReplyDictType,NULL); /* CASE 3: * The number of elements inside the set is not greater than * SRANDMEMBER_SUB_STRATEGY_MUL times the number of requested elements. * In this case we create a set from scratch with all the elements, and * subtract random elements to reach the requested number of elements. * * This is done because if the number of requested elements is just * a bit less than the number of elements in the set, the natural approach * used into CASE 4 is highly inefficient. */ if (count*SRANDMEMBER_SUB_STRATEGY_MUL > size) { setTypeIterator *si; /* Add all the elements into the temporary dictionary. */ si = setTypeInitIterator(set); dictExpand(d, size); while ((encoding = setTypeNext(si,&ele,&llele)) != -1) { int retval = DICT_ERR; if (encoding == OBJ_ENCODING_INTSET) { retval = dictAdd(d,sdsfromlonglong(llele),NULL); } else { retval = dictAdd(d,sdsdup(ele),NULL); } serverAssert(retval == DICT_OK); } setTypeReleaseIterator(si); serverAssert(dictSize(d) == size); /* Remove random elements to reach the right count. */ while (size > count) { dictEntry *de; de = dictGetRandomKey(d); dictUnlink(d,dictGetKey(de)); sdsfree(dictGetKey(de)); dictFreeUnlinkedEntry(d,de); size--; } } /* CASE 4: We have a big set compared to the requested number of elements. * In this case we can simply get random elements from the set and add * to the temporary set, trying to eventually get enough unique elements * to reach the specified count. */ else { unsigned long added = 0; sds sdsele; dictExpand(d, count); while (added < count) { encoding = setTypeRandomElement(set,&ele,&llele); if (encoding == OBJ_ENCODING_INTSET) { sdsele = sdsfromlonglong(llele); } else { sdsele = sdsdup(ele); } /* Try to add the object to the dictionary. If it already exists * free it, otherwise increment the number of objects we have * in the result dictionary. */ if (dictAdd(d,sdsele,NULL) == DICT_OK) added++; else sdsfree(sdsele); } } /* CASE 3 & 4: send the result to the user. */ { dictIterator *di; dictEntry *de; addReplyArrayLen(c,count); di = dictGetIterator(d); while((de = dictNext(di)) != NULL) addReplyBulkSds(c,dictGetKey(de)); dictReleaseIterator(di); dictRelease(d); } } /* SRANDMEMBER [<count>] */ void srandmemberCommand(client *c) { robj *set; sds ele; int64_t llele; int encoding; if (c->argc == 3) { srandmemberWithCountCommand(c); return; } else if (c->argc > 3) { addReplyErrorObject(c,shared.syntaxerr); return; } /* Handle variant without <count> argument. Reply with simple bulk string */ if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.null[c->resp])) == NULL || checkType(c,set,OBJ_SET)) return; encoding = setTypeRandomElement(set,&ele,&llele); if (encoding == OBJ_ENCODING_INTSET) { addReplyBulkLongLong(c,llele); } else { addReplyBulkCBuffer(c,ele,sdslen(ele)); } } int qsortCompareSetsByCardinality(const void *s1, const void *s2) { if (setTypeSize(*(robj**)s1) > setTypeSize(*(robj**)s2)) return 1; if (setTypeSize(*(robj**)s1) < setTypeSize(*(robj**)s2)) return -1; return 0; } /* This is used by SDIFF and in this case we can receive NULL that should * be handled as empty sets. */ int qsortCompareSetsByRevCardinality(const void *s1, const void *s2) { robj *o1 = *(robj**)s1, *o2 = *(robj**)s2; unsigned long first = o1 ? setTypeSize(o1) : 0; unsigned long second = o2 ? setTypeSize(o2) : 0; if (first < second) return 1; if (first > second) return -1; return 0; } void sinterGenericCommand(client *c, robj **setkeys, unsigned long setnum, robj *dstkey) { robj **sets = zmalloc(sizeof(robj*)*setnum); setTypeIterator *si; robj *dstset = NULL; sds elesds; int64_t intobj; void *replylen = NULL; unsigned long j, cardinality = 0; int encoding, empty = 0; for (j = 0; j < setnum; j++) { robj *setobj = dstkey ? lookupKeyWrite(c->db,setkeys[j]) : lookupKeyRead(c->db,setkeys[j]); if (!setobj) { /* A NULL is considered an empty set */ empty += 1; sets[j] = NULL; continue; } if (checkType(c,setobj,OBJ_SET)) { zfree(sets); return; } sets[j] = setobj; } /* Set intersection with an empty set always results in an empty set. * Return ASAP if there is an empty set. */ if (empty > 0) { zfree(sets); if (dstkey) { if (dbDelete(c->db,dstkey)) { signalModifiedKey(c,c->db,dstkey); notifyKeyspaceEvent(NOTIFY_GENERIC,"del",dstkey,c->db->id); server.dirty++; } addReply(c,shared.czero); } else { addReply(c,shared.emptyset[c->resp]); } return; } /* Sort sets from the smallest to largest, this will improve our * algorithm's performance */ qsort(sets,setnum,sizeof(robj*),qsortCompareSetsByCardinality); /* The first thing we should output is the total number of elements... * since this is a multi-bulk write, but at this stage we don't know * the intersection set size, so we use a trick, append an empty object * to the output list and save the pointer to later modify it with the * right length */ if (!dstkey) { replylen = addReplyDeferredLen(c); } else { /* If we have a target key where to store the resulting set * create this key with an empty set inside */ dstset = createIntsetObject(); } /* Iterate all the elements of the first (smallest) set, and test * the element against all the other sets, if at least one set does * not include the element it is discarded */ si = setTypeInitIterator(sets[0]); while((encoding = setTypeNext(si,&elesds,&intobj)) != -1) { for (j = 1; j < setnum; j++) { if (sets[j] == sets[0]) continue; if (encoding == OBJ_ENCODING_INTSET) { /* intset with intset is simple... and fast */ if (sets[j]->encoding == OBJ_ENCODING_INTSET && !intsetFind((intset*)sets[j]->ptr,intobj)) { break; /* in order to compare an integer with an object we * have to use the generic function, creating an object * for this */ } else if (sets[j]->encoding == OBJ_ENCODING_HT) { elesds = sdsfromlonglong(intobj); if (!setTypeIsMember(sets[j],elesds)) { sdsfree(elesds); break; } sdsfree(elesds); } } else if (encoding == OBJ_ENCODING_HT) { if (!setTypeIsMember(sets[j],elesds)) { break; } } } /* Only take action when all sets contain the member */ if (j == setnum) { if (!dstkey) { if (encoding == OBJ_ENCODING_HT) addReplyBulkCBuffer(c,elesds,sdslen(elesds)); else addReplyBulkLongLong(c,intobj); cardinality++; } else { if (encoding == OBJ_ENCODING_INTSET) { elesds = sdsfromlonglong(intobj); setTypeAdd(dstset,elesds); sdsfree(elesds); } else { setTypeAdd(dstset,elesds); } } } } setTypeReleaseIterator(si); if (dstkey) { /* Store the resulting set into the target, if the intersection * is not an empty set. */ if (setTypeSize(dstset) > 0) { setKey(c,c->db,dstkey,dstset); addReplyLongLong(c,setTypeSize(dstset)); notifyKeyspaceEvent(NOTIFY_SET,"sinterstore", dstkey,c->db->id); server.dirty++; } else { addReply(c,shared.czero); if (dbDelete(c->db,dstkey)) { server.dirty++; signalModifiedKey(c,c->db,dstkey); notifyKeyspaceEvent(NOTIFY_GENERIC,"del",dstkey,c->db->id); } } decrRefCount(dstset); } else { setDeferredSetLen(c,replylen,cardinality); } zfree(sets); } /* SINTER key [key ...] */ void sinterCommand(client *c) { sinterGenericCommand(c,c->argv+1,c->argc-1,NULL); } /* SINTERSTORE destination key [key ...] */ void sinterstoreCommand(client *c) { sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]); } #define SET_OP_UNION 0 #define SET_OP_DIFF 1 #define SET_OP_INTER 2 void sunionDiffGenericCommand(client *c, robj **setkeys, int setnum, robj *dstkey, int op) { robj **sets = zmalloc(sizeof(robj*)*setnum); setTypeIterator *si; robj *dstset = NULL; sds ele; int j, cardinality = 0; int diff_algo = 1; for (j = 0; j < setnum; j++) { robj *setobj = dstkey ? lookupKeyWrite(c->db,setkeys[j]) : lookupKeyRead(c->db,setkeys[j]); if (!setobj) { sets[j] = NULL; continue; } if (checkType(c,setobj,OBJ_SET)) { zfree(sets); return; } sets[j] = setobj; } /* Select what DIFF algorithm to use. * * Algorithm 1 is O(N*M) where N is the size of the element first set * and M the total number of sets. * * Algorithm 2 is O(N) where N is the total number of elements in all * the sets. * * We compute what is the best bet with the current input here. */ if (op == SET_OP_DIFF && sets[0]) { long long algo_one_work = 0, algo_two_work = 0; for (j = 0; j < setnum; j++) { if (sets[j] == NULL) continue; algo_one_work += setTypeSize(sets[0]); algo_two_work += setTypeSize(sets[j]); } /* Algorithm 1 has better constant times and performs less operations * if there are elements in common. Give it some advantage. */ algo_one_work /= 2; diff_algo = (algo_one_work <= algo_two_work) ? 1 : 2; if (diff_algo == 1 && setnum > 1) { /* With algorithm 1 it is better to order the sets to subtract * by decreasing size, so that we are more likely to find * duplicated elements ASAP. */ qsort(sets+1,setnum-1,sizeof(robj*), qsortCompareSetsByRevCardinality); } } /* We need a temp set object to store our union. If the dstkey * is not NULL (that is, we are inside an SUNIONSTORE operation) then * this set object will be the resulting object to set into the target key*/ dstset = createIntsetObject(); if (op == SET_OP_UNION) { /* Union is trivial, just add every element of every set to the * temporary set. */ for (j = 0; j < setnum; j++) { if (!sets[j]) continue; /* non existing keys are like empty sets */ si = setTypeInitIterator(sets[j]); while((ele = setTypeNextObject(si)) != NULL) { if (setTypeAdd(dstset,ele)) cardinality++; sdsfree(ele); } setTypeReleaseIterator(si); } } else if (op == SET_OP_DIFF && sets[0] && diff_algo == 1) { /* DIFF Algorithm 1: * * We perform the diff by iterating all the elements of the first set, * and only adding it to the target set if the element does not exist * into all the other sets. * * This way we perform at max N*M operations, where N is the size of * the first set, and M the number of sets. */ si = setTypeInitIterator(sets[0]); while((ele = setTypeNextObject(si)) != NULL) { for (j = 1; j < setnum; j++) { if (!sets[j]) continue; /* no key is an empty set. */ if (sets[j] == sets[0]) break; /* same set! */ if (setTypeIsMember(sets[j],ele)) break; } if (j == setnum) { /* There is no other set with this element. Add it. */ setTypeAdd(dstset,ele); cardinality++; } sdsfree(ele); } setTypeReleaseIterator(si); } else if (op == SET_OP_DIFF && sets[0] && diff_algo == 2) { /* DIFF Algorithm 2: * * Add all the elements of the first set to the auxiliary set. * Then remove all the elements of all the next sets from it. * * This is O(N) where N is the sum of all the elements in every * set. */ for (j = 0; j < setnum; j++) { if (!sets[j]) continue; /* non existing keys are like empty sets */ si = setTypeInitIterator(sets[j]); while((ele = setTypeNextObject(si)) != NULL) { if (j == 0) { if (setTypeAdd(dstset,ele)) cardinality++; } else { if (setTypeRemove(dstset,ele)) cardinality--; } sdsfree(ele); } setTypeReleaseIterator(si); /* Exit if result set is empty as any additional removal * of elements will have no effect. */ if (cardinality == 0) break; } } /* Output the content of the resulting set, if not in STORE mode */ if (!dstkey) { addReplySetLen(c,cardinality); si = setTypeInitIterator(dstset); while((ele = setTypeNextObject(si)) != NULL) { addReplyBulkCBuffer(c,ele,sdslen(ele)); sdsfree(ele); } setTypeReleaseIterator(si); server.lazyfree_lazy_server_del ? freeObjAsync(NULL, dstset, -1) : decrRefCount(dstset); } else { /* If we have a target key where to store the resulting set * create this key with the result set inside */ if (setTypeSize(dstset) > 0) { setKey(c,c->db,dstkey,dstset); addReplyLongLong(c,setTypeSize(dstset)); notifyKeyspaceEvent(NOTIFY_SET, op == SET_OP_UNION ? "sunionstore" : "sdiffstore", dstkey,c->db->id); server.dirty++; } else { addReply(c,shared.czero); if (dbDelete(c->db,dstkey)) { server.dirty++; signalModifiedKey(c,c->db,dstkey); notifyKeyspaceEvent(NOTIFY_GENERIC,"del",dstkey,c->db->id); } } decrRefCount(dstset); } zfree(sets); } /* SUNION key [key ...] */ void sunionCommand(client *c) { sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,SET_OP_UNION); } /* SUNIONSTORE destination key [key ...] */ void sunionstoreCommand(client *c) { sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],SET_OP_UNION); } /* SDIFF key [key ...] */ void sdiffCommand(client *c) { sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,SET_OP_DIFF); } /* SDIFFSTORE destination key [key ...] */ void sdiffstoreCommand(client *c) { sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],SET_OP_DIFF); } void sscanCommand(client *c) { robj *set; unsigned long cursor; if (parseScanCursorOrReply(c,c->argv[2],&cursor) == C_ERR) return; if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.emptyscan)) == NULL || checkType(c,set,OBJ_SET)) return; scanGenericCommand(c,set,cursor); }
oranagra/redis
src/t_set.c
C
bsd-3-clause
41,630
package com.impirobotics.frc2014.commands.chassis; import com.impirobotics.frc2014.ImpiLib; import com.impirobotics.frc2014.RobotMap; import com.impirobotics.frc2014.XboxController; import com.impirobotics.frc2014.commands.CommandBase; public class Chassis_Joystick extends CommandBase { private static final double DRIVER_JOYSTICK_DEADZONE = 0.05; public Chassis_Joystick() { requires(chassisSubsystem); } protected void initialize() { } protected void execute() { XboxController driverController = oi.getDriverController(); double straightAxis = -driverController.getLeftY(); straightAxis = ImpiLib.signedSquare(ImpiLib.deadzone(straightAxis,DRIVER_JOYSTICK_DEADZONE)); double turnAxis = driverController.getRightX(); turnAxis = ImpiLib.signedSquare(ImpiLib.deadzone(turnAxis,DRIVER_JOYSTICK_DEADZONE)); chassisSubsystem.haloDrive(straightAxis, turnAxis); } protected boolean isFinished() { return false; } protected void end() { chassisSubsystem.drive(0.0, 0.0); } protected void interrupted() { chassisSubsystem.drive(0.0, 0.0); } }
ImpiRobotics/Impi2014
src/com/impirobotics/frc2014/commands/chassis/Chassis_Joystick.java
Java
bsd-3-clause
1,251
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "blimp/net/test_common.h" #include <string> #include "base/sys_byteorder.h" #include "blimp/common/proto/blimp_message.pb.h" #include "blimp/net/blimp_connection.h" #include "blimp/net/common.h" #include "net/base/io_buffer.h" namespace blimp { MockStreamSocket::MockStreamSocket() {} MockStreamSocket::~MockStreamSocket() {} MockTransport::MockTransport() {} MockTransport::~MockTransport() {} scoped_ptr<BlimpConnection> MockTransport::TakeConnection() { return make_scoped_ptr(TakeConnectionPtr()); } const char* MockTransport::GetName() const { return "mock"; } MockConnectionHandler::MockConnectionHandler() {} MockConnectionHandler::~MockConnectionHandler() {} void MockConnectionHandler::HandleConnection( scoped_ptr<BlimpConnection> connection) { HandleConnectionPtr(connection.get()); } MockPacketReader::MockPacketReader() {} MockPacketReader::~MockPacketReader() {} MockPacketWriter::MockPacketWriter() {} MockPacketWriter::~MockPacketWriter() {} MockBlimpConnection::MockBlimpConnection() {} MockBlimpConnection::~MockBlimpConnection() {} MockConnectionErrorObserver::MockConnectionErrorObserver() {} MockConnectionErrorObserver::~MockConnectionErrorObserver() {} MockBlimpMessageProcessor::MockBlimpMessageProcessor() {} MockBlimpMessageProcessor::~MockBlimpMessageProcessor() {} void MockBlimpMessageProcessor::ProcessMessage( scoped_ptr<BlimpMessage> message, const net::CompletionCallback& callback) { MockableProcessMessage(*message, callback); } std::string EncodeHeader(size_t size) { scoped_ptr<char[]> serialized(new char[kPacketHeaderSizeBytes]); uint32_t net_size = base::HostToNet32(size); memcpy(serialized.get(), &net_size, sizeof(net_size)); return std::string(serialized.get(), kPacketHeaderSizeBytes); } bool BufferStartsWith(net::GrowableIOBuffer* buf, const std::string& str) { return (static_cast<size_t>(buf->capacity()) > str.size() && str == std::string(buf->StartOfBuffer(), str.size())); } } // namespace blimp
highweb-project/highweb-webcl-html5spec
blimp/net/test_common.cc
C++
bsd-3-clause
2,190
ARDUPilotPhotoStitcher ====================== Tool to automate the generation of map tiles captured using an ArduPilot drone. Initial work can be found in "MosaicMaker" folder. It's state is as follows: <br/> - A zoomable, panable image viewer <br/> - Have not yet figured out how to add images in succession <br/> - Cannot read EXIF GPS data from jpegs yet <br/> - Based on http://cyotek.com/blog/creating-a-scrollable-and-zoomable-image-viewer-in-csharp-part-1 and ensuing pages <br/>
uacaps/ARDUPilotPhotoStitcher
README.md
Markdown
bsd-3-clause
543
--test sign function with integer type create table test_number( test_int int, test_smallint smallint, test_numeric numeric(38,10), test_float float, test_real real, test_double double, test_monetary monetary); ------------------------------------------------------ insert into test_number values( 1,2,1940080.2381928563,763378.5813701674,638.688149415,1.0873497133088402E7,2048); insert into test_number values( 2,3,2090402.277705913,9590589.85196592,164.17560682073,7523328.262894288,4096); insert into test_number values( 3,4,3928299.552073598,1812221.489704989,348.3659053035,1.1289692469144318E7,6144); insert into test_number values( 4,5,3882146.4736444056,9331204.100534454,881.993183851,966880.0841043274,8192); insert into test_number values( 5,6,880214.146652177,2780612.406491831,953.472898811,8319367.031997498,10240); insert into test_number values( 1,2,1.2381928563,7.5813701674,6.688149415,1.0873497133088402E7,2); insert into test_number values( 2,3,2.277705913,9.85196592,1.17560682073,7.262894288,4); insert into test_number values( 3,4,3.552073598,1.489704989,3.3659053035,1.1289692469144318E7,6); insert into test_number values( 4,5,3.4736444056,9.100534454,8.993183851,9.0841043274,8); insert into test_number values( 5,6,8.146652177,2.406491831,9.472898811,8.031997498,10); insert into test_number values(0,0,0,0,0,0,0); insert into test_number values(1,1,1,1,1,1,1); insert into test_number values(null,null,null,null,null,null,null); select sign( test_int) from test_number order by 1; drop table test_number;
CUBRID/cubrid-testcases
sql/_04_operator_function/_05_arighmetic_op/_009_sign/cases/1007.sql
SQL
bsd-3-clause
1,553
// Copyright 2010-2016, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef MOZC_RENDERER_MAC_INFOLIST_VIEW_H_ #define MOZC_RENDERER_MAC_INFOLIST_VIEW_H_ #import <Cocoa/Cocoa.h> #include "protocol/renderer_command.pb.h" namespace mozc { namespace renderer { class RendererStyle; } // namespace mozc::renderer } // namespace mozc // InfolistView is an NSView subclass to draw the infolist window // according to the current candidates. @interface InfolistView : NSView { @private mozc::commands::Candidates candidates_; const mozc::renderer::RendererStyle *style_; // The row which has focused background. int focusedRow_; } // setCandidates: sets the candidates to be rendered. - (void)setCandidates:(const mozc::commands::Candidates *)candidates; // Checks the |candidates_| and recalculates the layout. // It also returns the size which is necessary to draw all GUI elements. - (NSSize)updateLayout; @end #endif // MOZC_RENDERER_MAC_INFOLIST_VIEW_H_
kbc-developers/Mozc
src/renderer/mac/InfolistView.h
C
bsd-3-clause
2,464
/*L * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/stats-analysis-commons/LICENSE.txt for details. */ package gov.nih.nci.caintegrator.enumeration; import java.io.Serializable; public enum StatisticalSignificanceType implements Serializable{ pValue, adjustedpValue; }
NCIP/stats-analysis-commons
src/gov/nih/nci/caintegrator/enumeration/StatisticalSignificanceType.java
Java
bsd-3-clause
345
;--------------------------------------- ; CLi² (Command Line Interface) API ; 2016 © breeze/fishbone crew ;--------------------------------------- ; MODULE: #63 getCurrentDate ;--------------------------------------- ; Получить текущую дату ; o:HL - год ; D - месяц ; E - день ; C - день недели ;--------------------------------------- _getCurrentDate ld a,#0b ; включить режим BIN данных ld l,#04 call _nvRamSetData+1 ; устанавливаем данные ld a,#09 ; регистр года (смещение относительно 2000) call _nvRamGetData+1 ; читаем данные ld hl,2000 ld b,0 ld c,a add hl,bc ld a,#08 ; регистр месяца call _nvRamGetData+1 ; читаем данные ld d,a ld a,#07 ; регистр дня месяца call _nvRamGetData+1 ; читаем данные ld e,a ld a,#06 ; регистр дня недели call _nvRamGetData+1 ; читаем данные ld c,a ret ;---------------------------------------
LessNick/cli2
src/system/api/getCurrentDate.asm
Assembly
bsd-3-clause
1,172
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>gem5: Member List</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li id="current"><a href="classes.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul></div> <div class="tabs"> <ul> <li><a href="classes.html"><span>Alphabetical&nbsp;List</span></a></li> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul></div> <h1>FALRUBlk Member List</h1>This is the complete list of members for <a class="el" href="classFALRUBlk.html">FALRUBlk</a>, including all inherited members.<p><table> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#9a62641b35a4fd55708a70b21048e73f">asid</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#af8aebb1d4edb268af3681994de95ba0">CacheBlk</a>()</td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#865d5ebf036ab4f44fc6f9ee9df59e51">checkWrite</a>(PacketPtr pkt)</td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#bdc249b76e37f7b2723a75010d9818a7">clearLoadLocks</a>(Request *req=NULL)</td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#0ca6b49995d8fc8f07c0a014a37adeac">data</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classFALRUBlk.html#8617deba183ce2e379a34276ce563785">inCache</a></td><td><a class="el" href="classFALRUBlk.html">FALRUBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#db30a3ae044a8b1c10984abda05c4e40">invalidate</a>()</td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#a70bf4d3fa785ed0e684fe62581799a4">isDirty</a>() const </td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#7e622b866d70f5c99eaa21ee66471877">isReadable</a>() const </td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#7b724bc96dfae456814cb738a94b6724">isReferenced</a>() const </td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#f8daed3899eef5935a483e842563e8d5">isSecure</a>() const </td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classFALRUBlk.html#f34e98119ba459689179bab02f1c1902">isTouched</a></td><td><a class="el" href="classFALRUBlk.html">FALRUBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#9f3567f6c8659a3af240c82ad2617098">isValid</a>() const </td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#5cb4985ac4956fe781197d4410b274ed">isWritable</a>() const </td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#c10e93bed4b0f39e4c9b8949906ba87d">lockList</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classFALRUBlk.html#0d8a992f0470c01230f645d6fe9697a8">next</a></td><td><a class="el" href="classFALRUBlk.html">FALRUBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#793fbada7c0151de72153ffa4e601abf">operator=</a>(const CacheBlk &amp;rhs)</td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classFALRUBlk.html#f22b2dad2325ac94f3587969b542717e">prev</a></td><td><a class="el" href="classFALRUBlk.html">FALRUBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#db0de60fb759688e4ca5a25ac910bc44">print</a>() const </td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#9a62ef34de20018b9a3911fd6cd3cd40">refCount</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#4a634d8c23931f3e32f318fe87df7c67">set</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#7a705512f096ced21b3acb0f91b24f22">size</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#f6c9359d5f40fca1127f54e5c1bba052">srcMasterId</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#fb5eeab7e07e8072a5a071b42a6a9102">State</a> typedef</td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#526bdbffcb803e008c0fa2927a156af3">status</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#b0dce82ec9e19d5456474e8da2974719">tag</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#4e61ee90fd5b26024493ee91e2bfb964">task_id</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#de94c7cb7d6d89ccc27a18971822fcc2">tickInserted</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#cbcbb169912c4561dc089283b03dc868">trackLoadLocked</a>(PacketPtr pkt)</td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#143eb3546e15b38989939c16c078de35">wasPrefetched</a>() const </td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classCacheBlk.html#4c805b6c8b8864b4e818ef6a24a5c471">whenReady</a></td><td><a class="el" href="classCacheBlk.html">CacheBlk</a></td><td></td></tr> </table><hr size="1"><address style="align: right;"><small> Generated on Fri Apr 17 12:39:38 2015 for gem5 by <a href="http://www.doxygen.org/index.html"> doxygen</a> 1.4.7</small></address> </body> </html>
wnoc-drexel/gem5-stable
src/doxygen/html/classFALRUBlk-members.html
HTML
bsd-3-clause
8,279
import 'normalize.css'; import React from 'react'; import ReactDOM from 'react-dom'; import Coordinate2DWidget from 'paraviewweb/src/React/Widgets/Coordinate2DWidget'; const height = 100; const width = 100; ReactDOM.render( React.createElement(Coordinate2DWidget, { height, width, onChange: console.log, hideXY: true, }), document.querySelector('.content') );
Kitware/paraviewweb
src/React/Widgets/Coordinate2DWidget/example/index.js
JavaScript
bsd-3-clause
386
/* *= require admin/spree_core *= require_self */ .icon-file-alt:before { content: "\f0f6"; } #supplier_backorders tbody td:nth-child(2){ text-align: left; } #supplier_backorders tfoot td:first-child, #purchase_order_lines tfoot td:first-child{ text-align: right; } #supplier_backorders tfoot .backorder_cost{ color: black; opacity: 0.3; font-size: 0.75em; display: block; } #supplier_backorders .actions, #purchase_orders .actions, #purchase_order_lines .actions, #receive_purchase_order_lines .actions { padding-right: 0; } #receive_purchase_order_lines a.receive{ background: none; border-width: 0; font-size: 180%; height: 24px; line-height: 0.9em; padding: 0; width: 27px; } #receive_purchase_order_lines input.quantity{ width: 30px; display: inline-block; padding: 2px; vertical-align: top; text-align: center; } .state.ordered:before { background-color: #FF9300; } .state.receiving:before { background-color: #FF9300; } .state.received:before { background-color: #9FC820; }
complistic-gaff/spree_purchasing
app/assets/stylesheets/admin/spree_purchasing.css
CSS
bsd-3-clause
1,039
from rdkit import Chem from rdkit import rdBase from rdkit.Chem import rdMolDescriptors as rdMD from rdkit.Chem import AllChem from rdkit.Chem.EState import EStateIndices from rdkit.Chem.EState import AtomTypes import time print rdBase.rdkitVersion print rdBase.boostVersion def getEState(mol): return EStateIndices(mol) def localopt(mol, steps = 500): if mol.GetNumConformers() == 0: mol=make3D(mol) AllChem.MMFFOptimizeMolecule(mol, maxIters = steps) return mol def make3D(mol, steps = 50): mol = Chem.AddHs(mol) success = AllChem.EmbedMolecule(mol) if success == -1: # Failed success = AllChem.EmbedMolecule(mol, useRandomCoords = True) if success == -1: raise Error, "Embedding failed!" mol = localopt(mol, steps) return mol def get3D(m,is3d): if not is3d: m = Chem.AddHs(m) AllChem.EmbedMolecule(m) AllChem.MMFFOptimizeMolecule(m) r= rdMD.CalcAUTOCORR3D(m)+rdMD.CalcRDF(m)+rdMD.CalcMORSE(m)+rdMD.CalcWHIM(m)+rdMD.CalcGETAWAY(m) return r def generateALL(): m = Chem.MolFromSmiles('Cc1ccccc1') thefile = open('testAC.txt', 'w') filename="/Users/mbp/Github/rdkit_mine/Code/GraphMol/Descriptors/test_data/PBF_egfr.sdf" suppl = Chem.SDMolSupplier(filename,removeHs=False) mols = [x for x in suppl] start = time.time() for m in mols: r= get3D(m,True) for item in r: thefile.write("%.3f," % item) thefile.write("\n") end = time.time() print end - start thefile = open('testSMWHIM.txt', 'w') writer = Chem.SDWriter('3Dsmallmol.sdf') A=['[H][H]','B','O=O','C','CC','CCC','CCCC','CCCCC','CCCCCC','CO','CCO','CCCO','CCCCO','CCCCCO','CCCCCCO','CCl','CCCl','CCCCl','CCCCCl','CCCCCCl','CCCCCCCl','CBr','CCBr','CCCBr','CCCCBr','CCCCCBr','CCCCCCBr','CI','CCI','CCCI','CCCCI','CCCCCI','CCCCCCI','CF','CCF','CCCF','CCCCF','CCCCCF','CCCCCCF','CS','CCS','CCCS','CCCCS','CCCCCS','CCCCCCS','CN','CCN','CCCN','CCCCN','CCCCCN','CCCCCCN'] for smi in A: m = Chem.MolFromSmiles(smi) m=localopt(m,100) #r=get3D(m,True) print smi print "---------" r=rdMD.CalcWHIM(m) print "Ei:"+str(r[0])+ "," + str(r[1]) + "," + str(r[2])+ "\n" print "Gi:"+str(r[5])+ "," + str(r[6]) + "," + str(r[7])+ "\n" print "SI:"+str(rdMD.CalcSpherocityIndex(m)) print "AS:"+str(rdMD.CalcAsphericity(m)) print "EX:"+str(rdMD.CalcEccentricity(m)) for item in r: thefile.write("%.3f," % item) thefile.write("\n") #m.SetProp("smi", smi) #writer.write(m) thefile = open('testBPA.txt', 'w') writer = Chem.SDWriter('3DBPAmol.sdf') B=['CN(C)CC(Br)c1ccccc1','CN(C)CC(Br)c1ccc(F)cc1','CN(C)CC(Br)c1ccc(Cl)cc1','CN(C)CC(Br)c1ccc(Cl)cc1','CN(C)CC(Br)c1ccc(I)cc1','CN(C)CC(Br)c1ccc(C)cc1','CN(C)CC(Br)c1cccc(F)c1','CN(C)CC(Br)c1cccc(Cl)c1','CN(C)CC(Br)c1cccc(Br)c1','CN(C)CC(Br)c1cccc(I)c1','CN(C)CC(Br)c1cccc(C)c1','CN(C)CC(Br)c1ccc(F)c(Cl)c1','CN(C)CC(Br)c1ccc(F)c(Br)c1','CN(C)CC(Br)c1ccc(F)c(C)c1','CN(C)CC(Br)c1ccc(Cl)c(Cl)c1','CN(C)CC(Br)c1ccc(Cl)c(Br)c1','CN(C)CC(Br)c1ccc(Cl)c(C)c1','CN(C)CC(Br)c1ccc(Br)c(Cl)c1','CN(C)CC(Br)c1ccc(Br)c(Br)c1','CN(C)CC(Br)c1ccc(Br)c(C)c1','CN(C)CC(Br)c1ccc(C)c(C)c1','CN(C)CC(Br)c1ccc(C)c(Br)c1'] for smi in B: m = Chem.MolFromSmiles(smi) m=localopt(m,100) #r=get3D(m,True) r=rdMD.CalcWHIM(m) for item in r: thefile.write("%.3f," % item) thefile.write("\n") #m.SetProp("smi", smi) #writer.write(m) A="G1w,G2w,G3w,Gw" print dir(rdMD)
rdkit/rdkit
Code/GraphMol/Descriptors/test3D_old.py
Python
bsd-3-clause
3,537
""" WSGI config for invoices project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Use Whitenoise to serve static files # See: https://whitenoise.readthedocs.org/ application = DjangoWhiteNoise(application) # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
sztosz/invoices
config/wsgi.py
Python
bsd-3-clause
1,618
""" Sampling along tracks --------------------- The :func:`pygmt.grdtrack` function samples a raster grid's value along specified points. We will need to input a 2D raster to ``grid`` which can be an :class:`xarray.DataArray`. The argument passed to the ``points`` parameter can be a :class:`pandas.DataFrame` table where the first two columns are x and y (or longitude and latitude). Note also that there is a ``newcolname`` parameter that will be used to name the new column of values sampled from the grid. Alternatively, a NetCDF file path can be passed to ``grid``. An ASCII file path can also be accepted for ``points``. To save an output ASCII file, a file name argument needs to be passed to the ``outfile`` parameter. """ import pygmt # Load sample grid and point datasets grid = pygmt.datasets.load_earth_relief() points = pygmt.datasets.load_ocean_ridge_points() # Sample the bathymetry along the world's ocean ridges at specified track points track = pygmt.grdtrack(points=points, grid=grid, newcolname="bathymetry") fig = pygmt.Figure() # Plot the earth relief grid on Cylindrical Stereographic projection, masking land areas fig.basemap(region="g", projection="Cyl_stere/150/-20/15c", frame=True) fig.grdimage(grid=grid, cmap="gray") fig.coast(land="#666666") # Plot the sampled bathymetry points using circles (c) of 0.15 cm size # Points are colored using elevation values (normalized for visual purposes) fig.plot( x=track.longitude, y=track.latitude, style="c0.15c", cmap="terra", color=(track.bathymetry - track.bathymetry.mean()) / track.bathymetry.std(), ) fig.show()
GenericMappingTools/gmt-python
examples/gallery/images/track_sampling.py
Python
bsd-3-clause
1,614
@page linux_nvidia Make sure you are using your NVIDIA chip on Linux @brief 2015-01-26 In the early days of small3d's development, I was using a laptop which I was dual booting into Windows and Debian. The machine had been purchased with Windows pre-installed, and then I also installed the Linux instance. Even though the Windows system reported support for OpenGL 4.2, my Linux image reported OpenGL 3.0 when running glxinfo: glxinfo | grep Open What was strange was that it mentioned an Intel VGA instead of the NVIDIA GeForce which I knew I had. The little detail that I was missing up to that point was that I had two GPUs. NVIDIA supports [Optimus](http://www.nvidia.com/object/optimus_technology.html) technology. If you have a laptop, it could be the case that you have two GPUs too, basically a GeForce chip and an Intel chip. The latter is less capable graphics-wise but it consumes less energy, so Optimus is supposed to switch between the two, choosing GeForce for the more demanding, graphics-intensive tasks, like games or CAD applications, and Intel for the more mundane ones, like document or spreadsheet editing. In Windows the switch between the two is transparent to the user. However, if you are using Ubuntu for example, you may have to take a few extra steps. First of all, to check whether or not you have two video adapters, you can run the following: lspci -v | grep VGA If two entries are returned, one from Intel and one from NVIDIA, your machine is probably using Optimus. In my case, this lead to all programs running on the Intel GPU, regardless of whether or not they were a game or a word processor. I also found out that it is not possible (or not a good idea at least) to configure the entire system only use the GeForce chip. There are two packages that allow us to direct a specific executable to the NVIDIA GPU by prefixing it with a certain command. These are [Bumblebee](http://bumblebee-project.org/) and Primus. I have tried them both and they work well, but Primus runs on top of Bumblebee and it is recommended by the Bumblebee developers as the way to go (it forms part of the same project). On a Debian distribution for example, you can install them by executing: sudo apt-get install bumblebee primus (Note that there are [more detailed instructions](http://bumblebee-project.org/install.html) provided for installation and use, depending on your configuration) After having done so myself, when I would execute: primusrun glxinfo | grep OpenGL or for plain Bumblebee: optirun glxinfo | grep OpenGL The results indicated, in both cases, that the NVIDIA chip had been activated and that it supported OpenGL 4.2. So I created a bash command file to run Eclipse (with which I was editing the game engine's code at the time) which contained: primusrun [path to my Eclipse]/eclipse This allowed my whole development environment, including executables being debugged, to run on the NVIDIA GPU. GLEW also reported that OpenGL 3.3 was supported, so I could work with that version of the API.
dimi309/small3d
doxygen/blog/SwitchingBetweenIntelNvidia.md
Markdown
bsd-3-clause
3,059
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/layers/heads_up_display_layer_impl.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <iomanip> #include <utility> #include <vector> #include "base/logging.h" #include "base/memory/raw_ptr.h" #include "base/memory/shared_memory_mapping.h" #include "base/numerics/safe_conversions.h" #include "base/strings/stringprintf.h" #include "base/task/single_thread_task_runner.h" #include "base/trace_event/process_memory_dump.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/traced_value.h" #include "build/build_config.h" #include "cc/debug/debug_colors.h" #include "cc/metrics/dropped_frame_counter.h" #include "cc/paint/display_item_list.h" #include "cc/paint/image_provider.h" #include "cc/paint/paint_canvas.h" #include "cc/paint/paint_flags.h" #include "cc/paint/paint_image_builder.h" #include "cc/paint/paint_shader.h" #include "cc/paint/record_paint_canvas.h" #include "cc/paint/skia_paint_canvas.h" #include "cc/raster/scoped_gpu_raster.h" #include "cc/resources/memory_history.h" #include "cc/trees/layer_tree_frame_sink.h" #include "cc/trees/layer_tree_host_impl.h" #include "cc/trees/layer_tree_impl.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/gpu/context_provider.h" #include "components/viz/common/quads/solid_color_draw_quad.h" #include "components/viz/common/quads/texture_draw_quad.h" #include "components/viz/common/resources/bitmap_allocation.h" #include "components/viz/common/resources/platform_color.h" #include "gpu/GLES2/gl2extchromium.h" #include "gpu/command_buffer/client/context_support.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "gpu/command_buffer/client/raster_interface.h" #include "gpu/command_buffer/client/shared_image_interface.h" #include "gpu/command_buffer/common/shared_image_trace_utils.h" #include "gpu/command_buffer/common/shared_image_usage.h" #include "gpu/config/gpu_feature_info.h" #include "skia/ext/legacy_display_globals.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/khronos/GLES2/gl2.h" #include "third_party/khronos/GLES2/gl2ext.h" #include "third_party/skia/include/core/SkFont.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkPath.h" #include "third_party/skia/include/core/SkTextBlob.h" #include "third_party/skia/include/core/SkTypeface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gl/trace_util.h" namespace cc { namespace { void DrawArc(PaintCanvas* canvas, const SkRect& oval, SkScalar start_angle, SkScalar sweep_angle, const PaintFlags& flags) { DCHECK_GT(sweep_angle, 0.f); DCHECK_LT(sweep_angle, 360.f); SkPath path; path.moveTo(oval.centerX(), oval.centerY()); path.arcTo(oval, start_angle, sweep_angle, false /* forceMoveTo */); path.close(); canvas->drawPath(path, flags); } class DummyImageProvider : public ImageProvider { public: DummyImageProvider() = default; ~DummyImageProvider() override = default; ImageProvider::ScopedResult GetRasterContent( const DrawImage& draw_image) override { NOTREACHED(); return ScopedResult(); } }; std::string ToStringTwoDecimalPrecision(double input) { std::stringstream stream; stream << std::fixed << std::setprecision(2) << input; return stream.str(); } #if defined(OS_ANDROID) struct MetricsDrawSizes { const int kTopPadding = 35; const int kPadding = 15; const int kFontHeight = 32; const int kWidth = 525; const int kSidePadding = 20; const int kBadgeWidth = 25; } constexpr metrics_sizes; #else struct MetricsDrawSizes { const int kTopPadding = 35; const int kPadding = 15; const int kFontHeight = 22; const int kWidth = 425; const int kSidePadding = 20; const int kBadgeWidth = 25; } constexpr metrics_sizes; #endif constexpr int ComputeTotalHeight(int num_of_lines) { int num_of_spaces = std::max(0, num_of_lines - 1); return num_of_lines * metrics_sizes.kFontHeight + num_of_spaces * metrics_sizes.kPadding + 2 * metrics_sizes.kTopPadding; } } // namespace HeadsUpDisplayLayerImpl::HeadsUpDisplayLayerImpl(LayerTreeImpl* tree_impl, int id) : LayerImpl(tree_impl, id) {} HeadsUpDisplayLayerImpl::~HeadsUpDisplayLayerImpl() { ReleaseResources(); } std::unique_ptr<LayerImpl> HeadsUpDisplayLayerImpl::CreateLayerImpl( LayerTreeImpl* tree_impl) { return HeadsUpDisplayLayerImpl::Create(tree_impl, id()); } class HudGpuBacking : public ResourcePool::GpuBacking { public: ~HudGpuBacking() override { if (mailbox.IsZero()) return; if (returned_sync_token.HasData()) shared_image_interface->DestroySharedImage(returned_sync_token, mailbox); else if (mailbox_sync_token.HasData()) shared_image_interface->DestroySharedImage(mailbox_sync_token, mailbox); } void OnMemoryDump( base::trace_event::ProcessMemoryDump* pmd, const base::trace_event::MemoryAllocatorDumpGuid& buffer_dump_guid, uint64_t tracing_process_id, int importance) const override { if (mailbox.IsZero()) return; auto tracing_guid = gpu::GetSharedImageGUIDForTracing(mailbox); pmd->CreateSharedGlobalAllocatorDump(tracing_guid); pmd->AddOwnershipEdge(buffer_dump_guid, tracing_guid, importance); } raw_ptr<gpu::SharedImageInterface> shared_image_interface = nullptr; }; class HudSoftwareBacking : public ResourcePool::SoftwareBacking { public: ~HudSoftwareBacking() override { layer_tree_frame_sink->DidDeleteSharedBitmap(shared_bitmap_id); } void OnMemoryDump( base::trace_event::ProcessMemoryDump* pmd, const base::trace_event::MemoryAllocatorDumpGuid& buffer_dump_guid, uint64_t tracing_process_id, int importance) const override { pmd->CreateSharedMemoryOwnershipEdge(buffer_dump_guid, shared_mapping.guid(), importance); } raw_ptr<LayerTreeFrameSink> layer_tree_frame_sink; base::WritableSharedMemoryMapping shared_mapping; }; bool HeadsUpDisplayLayerImpl::WillDraw( DrawMode draw_mode, viz::ClientResourceProvider* resource_provider) { if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE && !LayerImpl::WillDraw(draw_mode, resource_provider)) { return false; } int max_texture_size = layer_tree_impl()->max_texture_size(); // TODO(crbug.com/1196414): Support 2D scales in heads up layers. internal_contents_scale_ = GetIdealContentsScaleKey(); internal_content_bounds_ = gfx::ScaleToCeiledSize(bounds(), internal_contents_scale_); internal_content_bounds_.SetToMin( gfx::Size(max_texture_size, max_texture_size)); return true; } void HeadsUpDisplayLayerImpl::AppendQuads( viz::CompositorRenderPass* render_pass, AppendQuadsData* append_quads_data) { viz::SharedQuadState* shared_quad_state = render_pass->CreateAndAppendSharedQuadState(); PopulateScaledSharedQuadState(shared_quad_state, internal_contents_scale_, contents_opaque()); // Appends a dummy quad here, which will be updated later once the resource // is ready in UpdateHudTexture(). We don't add a TextureDrawQuad directly // because we don't have a ResourceId for it yet, and ValidateQuadResources() // would fail. UpdateHudTexture() happens after all quads are appended for all // layers. gfx::Rect quad_rect(internal_content_bounds_); auto* quad = render_pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>(); quad->SetNew(shared_quad_state, quad_rect, quad_rect, SK_ColorTRANSPARENT, false); ValidateQuadResources(quad); current_quad_ = quad; } void HeadsUpDisplayLayerImpl::UpdateHudTexture( DrawMode draw_mode, LayerTreeFrameSink* layer_tree_frame_sink, viz::ClientResourceProvider* resource_provider, bool gpu_raster, const viz::CompositorRenderPassList& list) { if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE) return; // Update state that will be drawn. UpdateHudContents(); // TODO(penghuang): Do not use worker_context_provider() when context_provider // is changed to RasterContextProvider. // https://crbug.com/c/1286950 auto* raster_context_provider = gpu_raster ? layer_tree_frame_sink->worker_context_provider() : nullptr; absl::optional<viz::RasterContextProvider::ScopedRasterContextLock> lock; bool use_oopr = false; if (raster_context_provider) { lock.emplace(raster_context_provider); use_oopr = raster_context_provider->ContextCapabilities().supports_oop_raster; if (!use_oopr) { raster_context_provider = nullptr; lock.reset(); } } auto* context_provider = layer_tree_frame_sink->context_provider(); if (!pool_) { scoped_refptr<base::SingleThreadTaskRunner> task_runner = layer_tree_impl()->task_runner_provider()->HasImplThread() ? layer_tree_impl()->task_runner_provider()->ImplThreadTaskRunner() : layer_tree_impl()->task_runner_provider()->MainThreadTaskRunner(); pool_ = std::make_unique<ResourcePool>( resource_provider, context_provider, std::move(task_runner), ResourcePool::kDefaultExpirationDelay, layer_tree_impl()->settings().disallow_non_exact_resource_reuse); } // Return ownership of the previous frame's resource to the pool, so we // can reuse it once it is not busy in the display compositor. This is safe to // do here because the previous frame has been shipped to the display // compositor by the time we UpdateHudTexture for the current frame. if (in_flight_resource_) pool_->ReleaseResource(std::move(in_flight_resource_)); // Allocate a backing for the resource if needed, either for gpu or software // compositing. ResourcePool::InUsePoolResource pool_resource; bool needs_clear = false; if (draw_mode == DRAW_MODE_HARDWARE) { DCHECK(raster_context_provider || context_provider); const auto& caps = raster_context_provider ? raster_context_provider->ContextCapabilities() : context_provider->ContextCapabilities(); viz::ResourceFormat format = gpu_raster ? viz::PlatformColor::BestSupportedRenderBufferFormat(caps) : viz::PlatformColor::BestSupportedTextureFormat(caps); pool_resource = pool_->AcquireResource(internal_content_bounds_, format, gfx::ColorSpace()); if (!pool_resource.gpu_backing()) { auto backing = std::make_unique<HudGpuBacking>(); auto* sii = raster_context_provider ? raster_context_provider->SharedImageInterface() : context_provider->SharedImageInterface(); backing->shared_image_interface = sii; backing->InitOverlayCandidateAndTextureTarget( pool_resource.format(), caps, layer_tree_impl() ->settings() .resource_settings.use_gpu_memory_buffer_resources); uint32_t flags = gpu::SHARED_IMAGE_USAGE_DISPLAY; if (use_oopr) { flags |= gpu::SHARED_IMAGE_USAGE_RASTER | gpu::SHARED_IMAGE_USAGE_OOP_RASTERIZATION; } else if (gpu_raster) { flags |= gpu::SHARED_IMAGE_USAGE_GLES2 | gpu::SHARED_IMAGE_USAGE_GLES2_FRAMEBUFFER_HINT; } else { flags |= gpu::SHARED_IMAGE_USAGE_GLES2; } if (backing->overlay_candidate) flags |= gpu::SHARED_IMAGE_USAGE_SCANOUT; backing->mailbox = sii->CreateSharedImage( pool_resource.format(), pool_resource.size(), pool_resource.color_space(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, flags, gpu::kNullSurfaceHandle); if (raster_context_provider) { auto* ri = raster_context_provider->RasterInterface(); ri->WaitSyncTokenCHROMIUM(sii->GenUnverifiedSyncToken().GetConstData()); } else { auto* gl = context_provider->ContextGL(); gl->WaitSyncTokenCHROMIUM(sii->GenUnverifiedSyncToken().GetConstData()); } pool_resource.set_gpu_backing(std::move(backing)); needs_clear = true; } else if (pool_resource.gpu_backing()->returned_sync_token.HasData()) { if (raster_context_provider) { auto* ri = raster_context_provider->RasterInterface(); ri->WaitSyncTokenCHROMIUM( pool_resource.gpu_backing()->returned_sync_token.GetConstData()); } else { auto* gl = context_provider->ContextGL(); gl->WaitSyncTokenCHROMIUM( pool_resource.gpu_backing()->returned_sync_token.GetConstData()); } pool_resource.gpu_backing()->returned_sync_token = gpu::SyncToken(); } } else { DCHECK_EQ(draw_mode, DRAW_MODE_SOFTWARE); pool_resource = pool_->AcquireResource(internal_content_bounds_, viz::RGBA_8888, gfx::ColorSpace()); if (!pool_resource.software_backing()) { auto backing = std::make_unique<HudSoftwareBacking>(); backing->layer_tree_frame_sink = layer_tree_frame_sink; backing->shared_bitmap_id = viz::SharedBitmap::GenerateId(); base::MappedReadOnlyRegion shm = viz::bitmap_allocation::AllocateSharedBitmap(pool_resource.size(), pool_resource.format()); backing->shared_mapping = std::move(shm.mapping); layer_tree_frame_sink->DidAllocateSharedBitmap(std::move(shm.region), backing->shared_bitmap_id); pool_resource.set_software_backing(std::move(backing)); } } if (gpu_raster) { // If using |gpu_raster| we DrawHudContents() directly to a gpu texture, // which is wrapped in an SkSurface. DCHECK_EQ(draw_mode, DRAW_MODE_HARDWARE); DCHECK(pool_resource.gpu_backing()); auto* backing = static_cast<HudGpuBacking*>(pool_resource.gpu_backing()); if (use_oopr) { const auto& size = pool_resource.size(); auto display_item_list = base::MakeRefCounted<DisplayItemList>( DisplayItemList::kTopLevelDisplayItemList); RecordPaintCanvas canvas(display_item_list.get(), SkRect::MakeIWH(size.width(), size.height())); display_item_list->StartPaint(); DrawHudContents(&canvas); display_item_list->EndPaintOfUnpaired(gfx::Rect(size)); display_item_list->Finalize(); auto* ri = raster_context_provider->RasterInterface(); constexpr GLuint background_color = SkColorSetARGB(0, 0, 0, 0); constexpr GLuint msaa_sample_count = -1; constexpr bool can_use_lcd_text = true; ri->BeginRasterCHROMIUM(background_color, needs_clear, msaa_sample_count, gpu::raster::kNoMSAA, can_use_lcd_text, gfx::ColorSpace::CreateSRGB(), backing->mailbox.name); gfx::Vector2dF post_translate(0.f, 0.f); gfx::Vector2dF post_scale(1.f, 1.f); DummyImageProvider image_provider; size_t max_op_size_limit = gpu::raster::RasterInterface::kDefaultMaxOpSizeHint; ri->RasterCHROMIUM(display_item_list.get(), &image_provider, size, gfx::Rect(size), gfx::Rect(size), post_translate, post_scale, false /* requires_clear */, &max_op_size_limit); ri->EndRasterCHROMIUM(); backing->mailbox_sync_token = viz::ClientResourceProvider::GenerateSyncTokenHelper(ri); } else { auto* gl = context_provider->ContextGL(); GLuint mailbox_texture_id = gl->CreateAndTexStorage2DSharedImageCHROMIUM(backing->mailbox.name); gl->BeginSharedImageAccessDirectCHROMIUM( mailbox_texture_id, GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM); { ScopedGpuRaster scoped_gpu_raster(context_provider); viz::ClientResourceProvider::ScopedSkSurface scoped_surface( context_provider->GrContext(), pool_resource.color_space().ToSkColorSpace(), mailbox_texture_id, backing->texture_target, pool_resource.size(), pool_resource.format(), skia::LegacyDisplayGlobals::ComputeSurfaceProps( false /* can_use_lcd_text */), 0 /* msaa_sample_count */); SkSurface* surface = scoped_surface.surface(); if (!surface) { pool_->ReleaseResource(std::move(pool_resource)); return; } SkiaPaintCanvas canvas(surface->getCanvas()); DrawHudContents(&canvas); } gl->EndSharedImageAccessDirectCHROMIUM(mailbox_texture_id); gl->DeleteTextures(1, &mailbox_texture_id); backing->mailbox_sync_token = viz::ClientResourceProvider::GenerateSyncTokenHelper(gl); } } else if (draw_mode == DRAW_MODE_HARDWARE) { // If not using |gpu_raster| but using gpu compositing, we DrawHudContents() // into a software bitmap and upload it to a texture for compositing. DCHECK(pool_resource.gpu_backing()); auto* backing = static_cast<HudGpuBacking*>(pool_resource.gpu_backing()); gpu::gles2::GLES2Interface* gl = layer_tree_impl()->context_provider()->ContextGL(); if (!staging_surface_ || gfx::SkISizeToSize(staging_surface_->getCanvas()->getBaseLayerSize()) != pool_resource.size()) { SkSurfaceProps props = skia::LegacyDisplayGlobals::GetSkSurfaceProps(); staging_surface_ = SkSurface::MakeRasterN32Premul( pool_resource.size().width(), pool_resource.size().height(), &props); } SkiaPaintCanvas canvas(staging_surface_->getCanvas()); DrawHudContents(&canvas); TRACE_EVENT0("cc", "UploadHudTexture"); SkPixmap pixmap; staging_surface_->peekPixels(&pixmap); GLuint mailbox_texture_id = gl->CreateAndTexStorage2DSharedImageCHROMIUM(backing->mailbox.name); gl->BeginSharedImageAccessDirectCHROMIUM( mailbox_texture_id, GL_SHARED_IMAGE_ACCESS_MODE_READWRITE_CHROMIUM); gl->BindTexture(backing->texture_target, mailbox_texture_id); DCHECK(GLSupportsFormat(pool_resource.format())); // We should use gl compatible format for skia SW rasterization. constexpr GLenum format = SK_B32_SHIFT ? GL_RGBA : GL_BGRA_EXT; constexpr GLenum type = GL_UNSIGNED_BYTE; gl->TexSubImage2D( backing->texture_target, 0, 0, 0, pool_resource.size().width(), pool_resource.size().height(), format, type, pixmap.addr()); gl->EndSharedImageAccessDirectCHROMIUM(mailbox_texture_id); gl->DeleteTextures(1, &mailbox_texture_id); backing->mailbox_sync_token = viz::ClientResourceProvider::GenerateSyncTokenHelper(gl); } else { // If not using gpu compositing, we DrawHudContents() directly into a shared // memory bitmap, wrapped in an SkSurface, that can be shared to the display // compositor. DCHECK_EQ(draw_mode, DRAW_MODE_SOFTWARE); DCHECK(pool_resource.software_backing()); SkImageInfo info = SkImageInfo::MakeN32Premul( pool_resource.size().width(), pool_resource.size().height()); auto* backing = static_cast<HudSoftwareBacking*>(pool_resource.software_backing()); SkSurfaceProps props = skia::LegacyDisplayGlobals::GetSkSurfaceProps(); sk_sp<SkSurface> surface = SkSurface::MakeRasterDirect( info, backing->shared_mapping.memory(), info.minRowBytes(), &props); SkiaPaintCanvas canvas(surface->getCanvas()); DrawHudContents(&canvas); } // Exports the backing to the ResourceProvider, giving it a ResourceId that // can be used in a DrawQuad. bool exported = pool_->PrepareForExport(pool_resource); DCHECK(exported); viz::ResourceId resource_id = pool_resource.resource_id_for_export(); // Save the resource to prevent reuse until it is exported to the display // compositor. Next time we come here, we can release it back to the pool as // it will be exported by then. in_flight_resource_ = std::move(pool_resource); // This iterates over the RenderPass list of quads to find the HUD quad, which // will always be in the root RenderPass. auto& render_pass = list.back(); for (auto it = render_pass->quad_list.begin(); it != render_pass->quad_list.end(); ++it) { if (*it == current_quad_) { const viz::SharedQuadState* sqs = current_quad_->shared_quad_state; gfx::Rect quad_rect = current_quad_->rect; gfx::Rect visible_rect = current_quad_->visible_rect; current_quad_ = nullptr; auto* quad = render_pass->quad_list.ReplaceExistingElement<viz::TextureDrawQuad>( it); // The acquired resource's size could be bigger than actually needed due // to reuse. In this case, only use the part of the texture that is within // the bounds. gfx::PointF uv_bottom_right(1.f, 1.f); if (in_flight_resource_.size() != internal_content_bounds_) { uv_bottom_right.set_x( static_cast<double>(internal_content_bounds_.width()) / static_cast<double>(in_flight_resource_.size().width())); uv_bottom_right.set_y( static_cast<double>(internal_content_bounds_.height()) / static_cast<double>(in_flight_resource_.size().height())); } const float vertex_opacity[] = {1.f, 1.f, 1.f, 1.f}; quad->SetNew(sqs, quad_rect, visible_rect, /*needs_blending=*/true, resource_id, /*premultiplied_alpha=*/true, /*uv_top_left=*/gfx::PointF(), /*uv_bottom_right=*/uv_bottom_right, /*background_color=*/SK_ColorTRANSPARENT, vertex_opacity, /*flipped=*/false, /*nearest_neighbor=*/false, /*secure_output_only=*/false, gfx::ProtectedVideoType::kClear); ValidateQuadResources(quad); break; } } // If this fails, we didn't find |current_quad_| in the root RenderPass, so we // didn't append it for the frame (why are we here then?), or it landed in // some other RenderPass, both of which are unexpected. DCHECK(!current_quad_); } void HeadsUpDisplayLayerImpl::ReleaseResources() { if (in_flight_resource_) pool_->ReleaseResource(std::move(in_flight_resource_)); pool_.reset(); } gfx::Rect HeadsUpDisplayLayerImpl::GetEnclosingVisibleRectInTargetSpace() const { DCHECK_GT(internal_contents_scale_, 0.f); return GetScaledEnclosingVisibleRectInTargetSpace(internal_contents_scale_); } void HeadsUpDisplayLayerImpl::SetHUDTypeface(sk_sp<SkTypeface> typeface) { if (typeface_ == typeface) return; DCHECK(typeface_.get() == nullptr); typeface_ = std::move(typeface); NoteLayerPropertyChanged(); } const std::vector<gfx::Rect>& HeadsUpDisplayLayerImpl::LayoutShiftRects() const { return layout_shift_rects_; } void HeadsUpDisplayLayerImpl::SetLayoutShiftRects( const std::vector<gfx::Rect>& rects) { layout_shift_rects_ = rects; } void HeadsUpDisplayLayerImpl::ClearLayoutShiftRects() { layout_shift_rects_.clear(); } void HeadsUpDisplayLayerImpl::SetWebVitalMetrics( std::unique_ptr<WebVitalMetrics> web_vital_metrics) { web_vital_metrics_ = std::move(web_vital_metrics); } void HeadsUpDisplayLayerImpl::PushPropertiesTo(LayerImpl* layer) { LayerImpl::PushPropertiesTo(layer); HeadsUpDisplayLayerImpl* layer_impl = static_cast<HeadsUpDisplayLayerImpl*>(layer); layer_impl->SetHUDTypeface(typeface_); layer_impl->SetLayoutShiftRects(layout_shift_rects_); layout_shift_rects_.clear(); if (web_vital_metrics_ && web_vital_metrics_->HasValue()) layer_impl->SetWebVitalMetrics(std::move(web_vital_metrics_)); } void HeadsUpDisplayLayerImpl::UpdateHudContents() { const LayerTreeDebugState& debug_state = layer_tree_impl()->debug_state(); // Don't update numbers every frame so text is readable. base::TimeTicks now = layer_tree_impl()->CurrentBeginFrameArgs().frame_time; if (base::TimeDelta(now - time_of_last_graph_update_).InSecondsF() > 0.25f) { time_of_last_graph_update_ = now; if (debug_state.show_fps_counter) { throughput_value_ = layer_tree_impl()->dropped_frame_counter()->GetAverageThroughput(); const auto& args = layer_tree_impl()->CurrentBeginFrameArgs(); if (args.IsValid()) frame_interval_ = args.interval; } if (debug_state.ShowMemoryStats()) { MemoryHistory* memory_history = layer_tree_impl()->memory_history(); if (memory_history->End()) memory_entry_ = **memory_history->End(); else memory_entry_ = MemoryHistory::Entry(); } } } void HeadsUpDisplayLayerImpl::DrawHudContents(PaintCanvas* canvas) { const LayerTreeDebugState& debug_state = layer_tree_impl()->debug_state(); TRACE_EVENT0("cc", "DrawHudContents"); canvas->clear(SkColorSetARGB(0, 0, 0, 0)); canvas->save(); canvas->scale(internal_contents_scale_); if (debug_state.ShowDebugRects()) { DrawDebugRects(canvas, layer_tree_impl()->debug_rect_history()); if (IsAnimatingHUDContents()) { layer_tree_impl()->SetNeedsRedraw(); } } if (!debug_state.ShouldDrawHudInfo()) { canvas->restore(); return; } // Our output should be in layout space, but all of the draw commands for the // HUD overlays here are in dips. Scale the canvas to account for this // difference. canvas->scale(layer_tree_impl()->painted_device_scale_factor()); SkRect area = SkRect::MakeXYWH(0, 0, 0, 0); if (debug_state.show_fps_counter) { area = DrawFrameThroughputDisplay( canvas, layer_tree_impl()->dropped_frame_counter(), 0, 0); area = DrawGpuRasterizationStatus(canvas, 0, area.bottom(), std::max<SkScalar>(area.width(), 150)); } if (debug_state.ShowMemoryStats() && memory_entry_.total_bytes_used) { area = DrawMemoryDisplay(canvas, 0, area.bottom(), std::max<SkScalar>(area.width(), 150)); } // For the web vital and smoothness HUD on the top right corner, if the width // of the screen is smaller than the default width of the HUD, scale it down. if (bounds_width_in_dips() < metrics_sizes.kWidth) { double scale_to_bounds = static_cast<double>(bounds_width_in_dips()) / static_cast<double>(metrics_sizes.kWidth); canvas->scale(scale_to_bounds, scale_to_bounds); } SkRect metrics_area = SkRect::MakeXYWH( std::max<SkScalar>(0, bounds_width_in_dips() - metrics_sizes.kWidth), 0, metrics_sizes.kWidth, 0); if (debug_state.show_web_vital_metrics) { metrics_area = DrawWebVitalMetrics( canvas, metrics_area.left(), metrics_area.bottom(), std::max<SkScalar>(metrics_area.width(), metrics_sizes.kWidth)); } if (debug_state.show_smoothness_metrics) { metrics_area = DrawSmoothnessMetrics( canvas, metrics_area.left(), metrics_area.bottom(), std::max<SkScalar>(metrics_area.width(), metrics_sizes.kWidth)); } canvas->restore(); } void HeadsUpDisplayLayerImpl::DrawText(PaintCanvas* canvas, const PaintFlags& flags, const std::string& text, TextAlign align, int size, int x, int y) const { DCHECK(typeface_.get()); SkFont font(typeface_, size); font.setEdging(SkFont::Edging::kAntiAlias); if (align == TextAlign::kCenter) { auto width = font.measureText(text.c_str(), text.length(), SkTextEncoding::kUTF8); x -= width * 0.5f; } else if (align == TextAlign::kRight) { auto width = font.measureText(text.c_str(), text.length(), SkTextEncoding::kUTF8); x -= width; } canvas->drawTextBlob( SkTextBlob::MakeFromText(text.c_str(), text.length(), font), x, y, flags); } void HeadsUpDisplayLayerImpl::DrawText(PaintCanvas* canvas, const PaintFlags& flags, const std::string& text, TextAlign align, int size, const SkPoint& pos) const { DrawText(canvas, flags, text, align, size, pos.x(), pos.y()); } void HeadsUpDisplayLayerImpl::DrawGraphBackground(PaintCanvas* canvas, PaintFlags* flags, const SkRect& bounds) const { flags->setColor(DebugColors::HUDBackgroundColor()); canvas->drawRect(bounds, *flags); } void HeadsUpDisplayLayerImpl::DrawGraphLines(PaintCanvas* canvas, PaintFlags* flags, const SkRect& bounds) const { // Draw top and bottom line. flags->setColor(DebugColors::HUDSeparatorLineColor()); canvas->drawLine(bounds.left(), bounds.top() - 1, bounds.right(), bounds.top() - 1, *flags); canvas->drawLine(bounds.left(), bounds.bottom(), bounds.right(), bounds.bottom(), *flags); } void HeadsUpDisplayLayerImpl::DrawSeparatorLine(PaintCanvas* canvas, PaintFlags* flags, const SkRect& bounds) const { // Draw separator line as transparent white. constexpr auto kSeparatorLineColor = SkColorSetARGB(64, 255, 255, 255); flags->setColor(kSeparatorLineColor); canvas->drawLine(bounds.left(), bounds.top(), bounds.right(), bounds.top(), *flags); } SkRect HeadsUpDisplayLayerImpl::DrawFrameThroughputDisplay( PaintCanvas* canvas, const DroppedFrameCounter* dropped_frame_counter, int right, int top) const { const int kPadding = 4; const int kGap = 6; const int kTitleFontHeight = 13; const int kFontHeight = 12; const int kGraphWidth = base::saturated_cast<int>(dropped_frame_counter->frame_history_size()); const int kGraphHeight = 40; int width = kGraphWidth + 4 * kPadding; int height = kTitleFontHeight + kFontHeight + kGraphHeight + 6 * kPadding + 2; int left = 0; SkRect area = SkRect::MakeXYWH(left, top, width, height); PaintFlags flags; DrawGraphBackground(canvas, &flags, area); SkRect title_bounds = SkRect::MakeXYWH(left + kPadding, top + kPadding, kGraphWidth + kGap + 2, kTitleFontHeight); SkRect text_bounds = SkRect::MakeXYWH(left + kPadding, title_bounds.bottom() + 2 * kPadding, kGraphWidth + kGap + 2, kFontHeight); SkRect graph_bounds = SkRect::MakeXYWH(left + kPadding, text_bounds.bottom() + 2 * kPadding, kGraphWidth, kGraphHeight); // Draw the frame rendering stats. const std::string title("Frame Rate"); std::string value_text = "n/a"; if (frame_interval_.has_value()) { // This assumes a constant frame rate. If the frame rate changed throughout // the sequence, then maybe we should average over the sequence. double frame_rate = static_cast<double>(throughput_value_) / (100 * frame_interval_.value().InSecondsF()); value_text = base::StringPrintf("%5.1f fps", frame_rate); } VLOG(1) << value_text; flags.setColor(DebugColors::HUDTitleColor()); DrawText(canvas, flags, title, TextAlign::kLeft, kTitleFontHeight, title_bounds.left(), title_bounds.bottom()); flags.setColor(DebugColors::FPSDisplayTextAndGraphColor()); DrawText(canvas, flags, value_text, TextAlign::kRight, kFontHeight, text_bounds.right(), text_bounds.bottom()); DrawGraphLines(canvas, &flags, graph_bounds); // Collect the frames graph data. SkPath good_path; SkPath dropped_path; SkPath partial_path; for (auto it = --dropped_frame_counter->end(); it; --it) { const auto state = **it; int x = graph_bounds.left() + it.index(); SkPath& path = state == DroppedFrameCounter::kFrameStateDropped ? dropped_path : state == DroppedFrameCounter::kFrameStateComplete ? good_path : partial_path; path.moveTo(x, graph_bounds.top()); path.lineTo(x, graph_bounds.bottom()); } // Draw FPS graph. flags.setAntiAlias(true); flags.setStyle(PaintFlags::kStroke_Style); flags.setStrokeWidth(1); flags.setColor(DebugColors::FPSDisplaySuccessfulFrame()); canvas->drawPath(good_path, flags); flags.setColor(DebugColors::FPSDisplayDroppedFrame()); canvas->drawPath(dropped_path, flags); flags.setColor(DebugColors::FPSDisplayMissedFrame()); canvas->drawPath(partial_path, flags); return area; } SkRect HeadsUpDisplayLayerImpl::DrawMemoryDisplay(PaintCanvas* canvas, int right, int top, int width) const { const int kPadding = 4; const int kTitleFontHeight = 13; const int kFontHeight = 12; const int height = kTitleFontHeight + 2 * kFontHeight + 5 * kPadding; const int left = 0; const SkRect area = SkRect::MakeXYWH(left, top, width, height); const double kMegabyte = 1000.0 * 1000.0; PaintFlags flags; DrawGraphBackground(canvas, &flags, area); SkPoint title_pos = SkPoint::Make(left + kPadding, top + kFontHeight + kPadding); SkPoint stat1_pos = SkPoint::Make(left + width - kPadding - 1, top + kPadding + 2 * kFontHeight); SkPoint stat2_pos = SkPoint::Make(left + width - kPadding - 1, top + 2 * kPadding + 3 * kFontHeight); flags.setColor(DebugColors::HUDTitleColor()); DrawText(canvas, flags, "GPU memory", TextAlign::kLeft, kTitleFontHeight, title_pos); flags.setColor(DebugColors::MemoryDisplayTextColor()); std::string text = base::StringPrintf( "%6.1f MB used", memory_entry_.total_bytes_used / kMegabyte); DrawText(canvas, flags, text, TextAlign::kRight, kFontHeight, stat1_pos); if (!memory_entry_.had_enough_memory) flags.setColor(SK_ColorRED); text = base::StringPrintf("%6.1f MB max ", memory_entry_.total_budget_in_bytes / kMegabyte); DrawText(canvas, flags, text, TextAlign::kRight, kFontHeight, stat2_pos); // Draw memory graph. int length = 2 * kFontHeight + kPadding + 12; SkRect oval = SkRect::MakeXYWH(left + kPadding * 6, top + kTitleFontHeight + kPadding * 3, length, length); flags.setAntiAlias(true); flags.setStyle(PaintFlags::kFill_Style); flags.setColor(SkColorSetARGB(64, 255, 255, 0)); DrawArc(canvas, oval, 180, 180, flags); int radius = length / 2; int cx = oval.left() + radius; int cy = oval.top() + radius; double angle = (static_cast<double>(memory_entry_.total_bytes_used) / memory_entry_.total_budget_in_bytes) * 180; SkColor colors[] = {SK_ColorRED, SK_ColorGREEN, SK_ColorGREEN, SkColorSetARGB(255, 255, 140, 0), SK_ColorRED}; const SkScalar pos[] = {SkFloatToScalar(0.2f), SkFloatToScalar(0.4f), SkFloatToScalar(0.6f), SkFloatToScalar(0.8f), SkFloatToScalar(1.0f)}; flags.setShader(PaintShader::MakeSweepGradient(cx, cy, colors, pos, 5, SkTileMode::kClamp, 0, 360)); flags.setAntiAlias(true); // Draw current status. flags.setStyle(PaintFlags::kStroke_Style); flags.setAlpha(32); flags.setStrokeWidth(4); DrawArc(canvas, oval, 180, angle, flags); flags.setStyle(PaintFlags::kFill_Style); flags.setColor(SkColorSetARGB(255, 0, 255, 0)); DrawArc(canvas, oval, 180, angle, flags); flags.setShader(nullptr); return area; } SkRect HeadsUpDisplayLayerImpl::DrawGpuRasterizationStatus(PaintCanvas* canvas, int right, int top, int width) const { std::string status; SkColor color = SK_ColorRED; switch (layer_tree_impl()->GetGpuRasterizationStatus()) { case GpuRasterizationStatus::ON: status = "on"; color = SK_ColorGREEN; break; case GpuRasterizationStatus::OFF_FORCED: status = "off (forced)"; color = SK_ColorRED; break; case GpuRasterizationStatus::OFF_DEVICE: status = "off (device)"; color = SK_ColorRED; break; } if (status.empty()) return SkRect::MakeEmpty(); const int kPadding = 4; const int kTitleFontHeight = 13; const int kFontHeight = 12; const int height = kTitleFontHeight + kFontHeight + 3 * kPadding; const int left = 0; const SkRect area = SkRect::MakeXYWH(left, top, width, height); PaintFlags flags; DrawGraphBackground(canvas, &flags, area); SkPoint gpu_status_pos = SkPoint::Make(left + width - kPadding, top + 2 * kFontHeight + 2 * kPadding); flags.setColor(DebugColors::HUDTitleColor()); DrawText(canvas, flags, "GPU raster", TextAlign::kLeft, kTitleFontHeight, left + kPadding, top + kFontHeight + kPadding); flags.setColor(color); DrawText(canvas, flags, status, TextAlign::kRight, kFontHeight, gpu_status_pos); return area; } void HeadsUpDisplayLayerImpl::DrawDebugRect( PaintCanvas* canvas, PaintFlags* flags, const DebugRect& rect, SkColor stroke_color, SkColor fill_color, float stroke_width, const std::string& label_text) const { DCHECK(typeface_.get()); gfx::Rect debug_layer_rect = gfx::ScaleToEnclosingRect(rect.rect, 1.0 / internal_contents_scale_, 1.0 / internal_contents_scale_); SkIRect sk_rect = RectToSkIRect(debug_layer_rect); flags->setColor(fill_color); flags->setStyle(PaintFlags::kFill_Style); canvas->drawIRect(sk_rect, *flags); flags->setColor(stroke_color); flags->setStyle(PaintFlags::kStroke_Style); flags->setStrokeWidth(SkFloatToScalar(stroke_width)); canvas->drawIRect(sk_rect, *flags); if (label_text.length()) { const int kFontHeight = 12; const int kPadding = 3; // The debug_layer_rect may be huge, and converting to a floating point may // be lossy, so intersect with the HUD layer bounds first to prevent that. gfx::Rect clip_rect = debug_layer_rect; clip_rect.Intersect(gfx::Rect(internal_content_bounds_)); SkRect sk_clip_rect = RectToSkRect(clip_rect); canvas->save(); canvas->clipRect(sk_clip_rect); canvas->translate(sk_clip_rect.x(), sk_clip_rect.y()); PaintFlags label_flags; label_flags.setColor(stroke_color); SkFont label_font(typeface_, kFontHeight); const SkScalar label_text_width = label_font.measureText( label_text.c_str(), label_text.length(), SkTextEncoding::kUTF8); canvas->drawRect(SkRect::MakeWH(label_text_width + 2 * kPadding, kFontHeight + 2 * kPadding), label_flags); label_flags.setColor(SkColorSetARGB(255, 50, 50, 50)); DrawText(canvas, label_flags, label_text, TextAlign::kLeft, kFontHeight, kPadding, kFontHeight * 0.8f + kPadding); canvas->restore(); } } void HeadsUpDisplayLayerImpl::DrawDebugRects( PaintCanvas* canvas, DebugRectHistory* debug_rect_history) { PaintFlags flags; const std::vector<DebugRect>& debug_rects = debug_rect_history->debug_rects(); std::vector<DebugRect> new_paint_rects; std::vector<DebugRect> new_layout_shift_rects; for (size_t i = 0; i < debug_rects.size(); ++i) { SkColor stroke_color = 0; SkColor fill_color = 0; float stroke_width = 0.f; std::string label_text; switch (debug_rects[i].type) { case LAYOUT_SHIFT_RECT_TYPE: new_layout_shift_rects.push_back(debug_rects[i]); continue; case PAINT_RECT_TYPE: new_paint_rects.push_back(debug_rects[i]); continue; case PROPERTY_CHANGED_RECT_TYPE: stroke_color = DebugColors::PropertyChangedRectBorderColor(); fill_color = DebugColors::PropertyChangedRectFillColor(); stroke_width = DebugColors::PropertyChangedRectBorderWidth(); break; case SURFACE_DAMAGE_RECT_TYPE: stroke_color = DebugColors::SurfaceDamageRectBorderColor(); fill_color = DebugColors::SurfaceDamageRectFillColor(); stroke_width = DebugColors::SurfaceDamageRectBorderWidth(); break; case SCREEN_SPACE_RECT_TYPE: stroke_color = DebugColors::ScreenSpaceLayerRectBorderColor(); fill_color = DebugColors::ScreenSpaceLayerRectFillColor(); stroke_width = DebugColors::ScreenSpaceLayerRectBorderWidth(); break; case TOUCH_EVENT_HANDLER_RECT_TYPE: stroke_color = DebugColors::TouchEventHandlerRectBorderColor(); fill_color = DebugColors::TouchEventHandlerRectFillColor(); stroke_width = DebugColors::TouchEventHandlerRectBorderWidth(); label_text = "touch event listener: "; label_text.append(TouchActionToString(debug_rects[i].touch_action)); break; case WHEEL_EVENT_HANDLER_RECT_TYPE: stroke_color = DebugColors::WheelEventHandlerRectBorderColor(); fill_color = DebugColors::WheelEventHandlerRectFillColor(); stroke_width = DebugColors::WheelEventHandlerRectBorderWidth(); label_text = "mousewheel event listener"; break; case SCROLL_EVENT_HANDLER_RECT_TYPE: stroke_color = DebugColors::ScrollEventHandlerRectBorderColor(); fill_color = DebugColors::ScrollEventHandlerRectFillColor(); stroke_width = DebugColors::ScrollEventHandlerRectBorderWidth(); label_text = "scroll event listener"; break; case NON_FAST_SCROLLABLE_RECT_TYPE: stroke_color = DebugColors::NonFastScrollableRectBorderColor(); fill_color = DebugColors::NonFastScrollableRectFillColor(); stroke_width = DebugColors::NonFastScrollableRectBorderWidth(); label_text = "repaints on scroll"; break; case MAIN_THREAD_SCROLLING_REASON_RECT_TYPE: stroke_color = DebugColors::MainThreadScrollingReasonRectBorderColor(); fill_color = DebugColors::MainThreadScrollingReasonRectFillColor(); stroke_width = DebugColors::MainThreadScrollingReasonRectBorderWidth(); label_text = "main thread scrolling: "; label_text.append(base::ToLowerASCII(MainThreadScrollingReason::AsText( debug_rects[i].main_thread_scrolling_reasons))); break; case ANIMATION_BOUNDS_RECT_TYPE: stroke_color = DebugColors::LayerAnimationBoundsBorderColor(); fill_color = DebugColors::LayerAnimationBoundsFillColor(); stroke_width = DebugColors::LayerAnimationBoundsBorderWidth(); label_text = "animation bounds"; break; } DrawDebugRect(canvas, &flags, debug_rects[i], stroke_color, fill_color, stroke_width, label_text); } if (new_paint_rects.size()) { paint_rects_.swap(new_paint_rects); paint_rects_fade_step_ = DebugColors::kFadeSteps; } if (paint_rects_fade_step_ > 0) { paint_rects_fade_step_--; for (size_t i = 0; i < paint_rects_.size(); ++i) { DrawDebugRect(canvas, &flags, paint_rects_[i], DebugColors::PaintRectBorderColor(paint_rects_fade_step_), DebugColors::PaintRectFillColor(paint_rects_fade_step_), DebugColors::PaintRectBorderWidth(), ""); } } if (new_layout_shift_rects.size()) { layout_shift_debug_rects_.swap(new_layout_shift_rects); layout_shift_rects_fade_step_ = DebugColors::kFadeSteps; } if (layout_shift_rects_fade_step_ > 0) { layout_shift_rects_fade_step_--; for (size_t i = 0; i < layout_shift_debug_rects_.size(); ++i) { DrawDebugRect( canvas, &flags, layout_shift_debug_rects_[i], DebugColors::LayoutShiftRectBorderColor(), DebugColors::LayoutShiftRectFillColor(layout_shift_rects_fade_step_), DebugColors::LayoutShiftRectBorderWidth(), ""); } } } int HeadsUpDisplayLayerImpl::DrawSingleMetric( PaintCanvas* canvas, int left, int right, int top, std::string name, const WebVitalMetrics::MetricsInfo& info, bool has_value, double value) const { std::string value_str = "-"; SkColor metrics_color = DebugColors::HUDTitleColor(); SkColor badge_color = SK_ColorGREEN; if (has_value) { value_str = ToStringTwoDecimalPrecision(value) + info.UnitToString(); if (value < info.green_threshold) { metrics_color = SK_ColorGREEN; } else if (value < info.yellow_threshold) { metrics_color = SK_ColorYELLOW; badge_color = SK_ColorYELLOW; } else { metrics_color = SK_ColorRED; badge_color = SK_ColorRED; } } // Draw the badge for this metric. PaintFlags badge_flags; badge_flags.setColor(badge_color); badge_flags.setStyle(PaintFlags::kFill_Style); badge_flags.setAntiAlias(true); if (badge_color == SK_ColorGREEN) { constexpr int kRadius = 6; int x = left + metrics_sizes.kSidePadding + kRadius; int y = top - kRadius - 2; SkPath circle = SkPath::Circle(x, y, kRadius); canvas->drawPath(circle, badge_flags); } else if (badge_color == SK_ColorYELLOW) { constexpr int kSquareSize = 12; int x = left + metrics_sizes.kSidePadding; int y = top - kSquareSize - 2; SkPath square = SkPath::Rect(SkRect::MakeXYWH(x, y, kSquareSize, kSquareSize)); canvas->drawPath(square, badge_flags); } else { constexpr int kTriangleSize = 16; int top_x = left + metrics_sizes.kSidePadding + kTriangleSize / 2; int top_y = top - kTriangleSize; int bottom_y = top_y + kTriangleSize; SkPath triangle = SkPath::Polygon({SkPoint::Make(top_x, top_y), SkPoint::Make(top_x - kTriangleSize / 2, bottom_y), SkPoint::Make(top_x + kTriangleSize / 2, bottom_y)}, true); canvas->drawPath(triangle, badge_flags); } // Draw the label and values of the metric. PaintFlags flags; flags.setColor(DebugColors::HUDTitleColor()); DrawText(canvas, flags, name, TextAlign::kLeft, metrics_sizes.kFontHeight, left + metrics_sizes.kSidePadding + metrics_sizes.kBadgeWidth, top); flags.setColor(metrics_color); DrawText(canvas, flags, value_str, TextAlign::kRight, metrics_sizes.kFontHeight, right - metrics_sizes.kSidePadding, top); return top + metrics_sizes.kFontHeight + metrics_sizes.kPadding; } SkRect HeadsUpDisplayLayerImpl::DrawWebVitalMetrics(PaintCanvas* canvas, int left, int top, int width) const { const int height = ComputeTotalHeight(3); const SkRect area = SkRect::MakeXYWH(left, top, width, height); PaintFlags flags; DrawGraphBackground(canvas, &flags, area); int current_top = top + metrics_sizes.kTopPadding + metrics_sizes.kFontHeight; double metric_value = 0.f; bool has_lcp = web_vital_metrics_ && web_vital_metrics_->has_lcp; if (has_lcp) metric_value = web_vital_metrics_->largest_contentful_paint.InSecondsF(); current_top = DrawSingleMetric( canvas, left, left + width, current_top, "Largest Contentful Paint", WebVitalMetrics::lcp_info, has_lcp, metric_value); bool has_fid = web_vital_metrics_ && web_vital_metrics_->has_fid; if (has_fid) metric_value = web_vital_metrics_->first_input_delay.InMillisecondsF(); current_top = DrawSingleMetric(canvas, left, left + width, current_top, "First Input Delay", WebVitalMetrics::fid_info, has_fid, metric_value); bool has_layout_shift = web_vital_metrics_ && web_vital_metrics_->has_cls; if (has_layout_shift) metric_value = web_vital_metrics_->layout_shift; current_top = DrawSingleMetric( canvas, left, left + width, current_top, "Cumulative Layout Shift", WebVitalMetrics::cls_info, has_layout_shift, metric_value); return area; } int HeadsUpDisplayLayerImpl::DrawSinglePercentageMetric(PaintCanvas* canvas, int left, int right, int top, std::string name, double value) const { std::string value_str = "-"; SkColor metrics_color = DebugColors::HUDTitleColor(); value_str = ToStringTwoDecimalPrecision(value) + "%"; PaintFlags flags; flags.setColor(DebugColors::HUDTitleColor()); DrawText(canvas, flags, name, TextAlign::kLeft, metrics_sizes.kFontHeight, left + metrics_sizes.kSidePadding + metrics_sizes.kBadgeWidth, top); flags.setColor(metrics_color); DrawText(canvas, flags, value_str, TextAlign::kRight, metrics_sizes.kFontHeight, right - metrics_sizes.kSidePadding, top); return top + metrics_sizes.kFontHeight + metrics_sizes.kPadding; } SkRect HeadsUpDisplayLayerImpl::DrawSmoothnessMetrics(PaintCanvas* canvas, int left, int top, int width) const { const int height = ComputeTotalHeight(3); const SkRect area = SkRect::MakeXYWH(left, top, width, height); PaintFlags flags; DrawGraphBackground(canvas, &flags, area); if (top != 0) { // There are metrics drawn before this. SkRect separator = SkRect::MakeXYWH(area.x(), area.y(), area.width(), area.height()); DrawSeparatorLine(canvas, &flags, separator); } int current_top = top + metrics_sizes.kTopPadding + metrics_sizes.kFontHeight; double avg_smoothness = layer_tree_impl() ->dropped_frame_counter() ->GetMostRecentAverageSmoothness(); current_top = DrawSinglePercentageMetric(canvas, left, left + width, current_top, "Average Dropped Frame", avg_smoothness); double worst_smoothness = layer_tree_impl() ->dropped_frame_counter() ->sliding_window_max_percent_dropped(); current_top = DrawSinglePercentageMetric(canvas, left, left + width, current_top, "Max Dropped Frame", worst_smoothness); double percentile_smoothness = layer_tree_impl() ->dropped_frame_counter() ->GetMostRecent95PercentileSmoothness(); current_top = DrawSinglePercentageMetric(canvas, left, left + width, current_top, "95th Percentile DF", percentile_smoothness); return area; } const char* HeadsUpDisplayLayerImpl::LayerTypeAsString() const { return "cc::HeadsUpDisplayLayerImpl"; } void HeadsUpDisplayLayerImpl::AsValueInto( base::trace_event::TracedValue* dict) const { LayerImpl::AsValueInto(dict); dict->SetString("layer_name", "Heads Up Display Layer"); } } // namespace cc
ric2b/Vivaldi-browser
chromium/cc/layers/heads_up_display_layer_impl.cc
C++
bsd-3-clause
52,022
package com.flash3388.flashlib.vision.processing.analysis; import com.flash3388.flashlib.vision.Image; import com.jmath.vectors.Vector2; import com.jmath.vectors.Vector3; public final class AnalysisAlgorithms { private AnalysisAlgorithms() {} public static double measureDistanceByWidth(Image image, double contourWidth, double realWidth, double fovRadians) { return measureDistance(image.getWidth(), contourWidth, realWidth, fovRadians); } public static double measureDistanceByHeight(Image image, double contourWidth, double realWidth, double fovRadians) { return measureDistance(image.getHeight(), contourWidth, realWidth, fovRadians); } public static double measureDistance(double imageDimension, double contourDimension, double realDimension, double fovRadians) { return (realDimension * imageDimension / (2 * contourDimension * Math.tan(fovRadians))); } public static double calculateHorizontalOffsetRadians(Image image, Vector2 targetPoint, double fovRadians){ double centerX = image.getHeight() * 0.5; double centerY = image.getWidth() * 0.5; double focalLength = centerX / Math.tan(0.5 * fovRadians); Vector3 center = new Vector3(0, 0, focalLength); Vector3 pixel = new Vector3(targetPoint.x() - centerX, targetPoint.y() - centerY, focalLength); return center.angleTo(pixel); } public static double calculateHorizontalOffsetDegrees(Image image, Vector2 targetPoint, double fovDegrees){ return Math.toDegrees(calculateHorizontalOffsetRadians(image, targetPoint, Math.toRadians(fovDegrees))); } public static double calculateHorizontalOffsetDegrees2(double centerX, double imageWidth, double camFovRadians) { // based on Alon and Michaelov's calculations used in 2020 vision code: // https://github.com/Flash3388/flash-vision-perocessing/blob/jetson2020/src/main/java/com/flash3388/ScoreMatchingPipeline.java // ScoreMatchingPipeline.calcAngleOffsetDegrees double imageCenter = imageWidth * 0.5; double xOffset = centerX - imageCenter; double focalLengthPixel = imageCenter / Math.tan(Math.toDegrees(camFovRadians) * 0.5 * Math.PI/180); return Math.toDegrees(Math.atan(xOffset / focalLengthPixel)); } }
Flash3388/FlashLib
flashlib.vision.core/src/main/java/com/flash3388/flashlib/vision/processing/analysis/AnalysisAlgorithms.java
Java
bsd-3-clause
2,310
.datarow :hover { cursor: pointer !important; cursor: hand !important; } .formText { width: 90%; } #status { position: fixed; bottom: 5px; right: 5px; width: 25px; height: 25px; }
encryptedmessaging/emp
client/styles/app.css
CSS
bsd-3-clause
189
module ForumsHelper FORUM_CONTROLLERS = ["forums", "posts", "topics"] def handle_forum_header if FORUM_CONTROLLERS.include?(params[:controller]) out = "" out << stylesheet_link_tag('forums') out << javascript_include_tag("lowpro", "application", :cache => 'beast', :plugin => 'ansuz_savage_beast') out << javascript_include_tag("prototype", "effects") unless @feed_icons.blank? @feed_icons.each do |feed| out << auto_discovery_link_tag(:rss, feed[:url], :title => "Subscribe to '#{feed[:title]}'") end end out end end end
knewter/ansuz
app/helpers/forums_helper.rb
Ruby
bsd-3-clause
605
package org.hisp.dhis.validation; /* * Copyright (c) 2004-2017, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public interface ValidationTask extends Runnable { void init( OrganisationUnitExtended sourceX, ValidationRunContext context ); }
vmluan/dhis2-core
dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/validation/ValidationTask.java
Java
bsd-3-clause
1,731
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} -- | Model for wiki. module HL.Model.Wiki where import HL.Controller import Control.Exception.Lifted (catch) import Control.Spoon import Data.Conduit import Data.Maybe import Data.Monoid import Data.Text (unpack) import Network.HTTP.Conduit import Prelude hiding (readFile) import Text.Pandoc.Definition import Text.Pandoc.Options import Text.Pandoc.Readers.MediaWiki import Text.XML import Text.XML.Cursor -- | Get the MediaWiki markup of a wiki page and then convert it to -- HTML. getWikiPage :: Text -> IO (Either Text (Text,Pandoc)) getWikiPage article = do request <- parseUrl ("http://wiki.haskell.org/api.php?action=query&\ \prop=revisions&rvprop=content&format=xml&titles=" <> unpack article) withManager (\manager -> do response <- http request manager doc <- catch (fmap Just (responseBody response $$+- sinkDoc def)) (\(_::UnresolvedEntityException) -> return Nothing) case doc >>= parse of Nothing -> return (Left "Unable to parse XML from wiki.haskell.org.") Just (title,pan) -> return (fromMaybe (Left ("Unable to parse XML from wiki.haskell.org! \ \And the parser gave us an impure exception! \ \Can you believe it?")) (showSpoon (Right (title,pan))))) where parse doc = do let cursor = fromDocument doc title <- listToMaybe (getTitle cursor) text <- listToMaybe (getText cursor) return (title,readMediaWiki def (unpack text)) name n = Name {nameLocalName = n ,nameNamespace = Nothing ,namePrefix = Nothing} getText cursor = element (name "api") cursor >>= descendant >>= element (name "query") >>= descendant >>= element (name "pages") >>= descendant >>= element (name "page") >>= descendant >>= element (name "revisions") >>= descendant >>= element (name "rev") >>= descendant >>= content getTitle cursor = element (name "api") cursor >>= descendant >>= element (name "query") >>= descendant >>= element (name "pages") >>= descendant >>= element (name "page") >>= attribute (name "title") -- | Make a spoon using the Show instance. showSpoon :: Show a => a -> Maybe a showSpoon a = (fmap (const a) (spoon (length (show a))))
erantapaa/hl
src/HL/Model/Wiki.hs
Haskell
bsd-3-clause
2,701
#!/bin/bash # Copyright 2020 Google LLC. set -euo pipefail USAGE=$' Example usage: inference_deeptrio.sh --model_preset "WGS" --docker_build true --use_gpu true The only trio supported is: child=HG002, parents=HG003,HG004. This is because otherwise there are too many flags needed to set VCFs and BEDs for 3 samples. Flags: --docker_build (true|false) Whether to build docker image. (default: false) --dry_run (true|false) If true, print out the main commands instead of running. (default: false) --use_gpu (true|false) Whether to use GPU when running case study. Make sure to specify vm_zone that is equipped with GPUs. (default: false) --use_hp_information (true|false) Use to set --use_hp_information. Only set this for PACBIO*. --bin_version Version of DeepTrio model to use. --customized_model Path to checkpoint directory containing model checkpoint. --regions Regions passed into both variant calling and hap.py. --make_examples_extra_args Flags for make_examples, specified as "flag1=param1,flag2=param2". --call_variants_extra_args Flags for call_variants, specified as "flag1=param1,flag2=param2". --postprocess_variants_extra_args Flags for postprocess_variants, specified as "flag1=param1,flag2=param2". --model_preset Preset case study to run: WGS, WGS_CHR20, WES, PACBIO, or PACBIO_CHR20. --proposed_variants Path to VCF containing proposed variants. In make_examples_extra_args, you must also specify variant_caller=vcf_candidate_importer but not proposed_variants. --save_intermediate_results (true|false) If True, keep intermediate outputs from make_examples and call_variants. If model_preset is not specified, the below flags are required: --model_type Type of DeepTrio model to run (WGS, WES, PACBIO) --bam_child Path to bam for HG002 on GCP. --bam_parent1 Path to bam for HG003 on GCP. --bam_parent2 Path to bam for HG004 on GCP. --capture_bed Path to GCP bucket containing captured file (only needed for WES model_type) Note: All paths to dataset must be of the form "gs://..." ' # Specify default values. # Booleans; sorted alphabetically. BUILD_DOCKER=false DRY_RUN=false USE_GPU=false USE_HP_INFORMATION="unset" # To distinguish whether this flag is set explicitly or not. SAVE_INTERMEDIATE_RESULTS=false # Strings; sorted alphabetically. BAM="" BAM_PARENT1="" BAM_PARENT2="" BIN_VERSION="1.3.0" CALL_VARIANTS_ARGS="" CAPTURE_BED="" CUSTOMIZED_MODEL="" MAKE_EXAMPLES_ARGS="" MODEL_PRESET="" MODEL_TYPE="" POSTPROCESS_VARIANTS_ARGS="" PROPOSED_VARIANTS="" REGIONS="" while (( "$#" )); do case "$1" in --docker_build) BUILD_DOCKER="$2" if [[ ${BUILD_DOCKER} != "true" ]] && [[ ${BUILD_DOCKER} != "false" ]]; then echo "Error: --docker_build needs to have value (true|false)." >&2 echo "$USAGE" >&2 exit 1 fi shift # Remove argument name from processing shift # Remove argument value from processing ;; --dry_run) DRY_RUN="$2" if [[ ${DRY_RUN} != "true" ]] && [[ ${DRY_RUN} != "false" ]]; then echo "Error: --dry_run needs to have value (true|false)." >&2 echo "$USAGE" >&2 exit 1 fi shift # Remove argument name from processing shift # Remove argument value from processing ;; --use_gpu) USE_GPU="$2" if [[ ${USE_GPU} != "true" ]] && [[ ${USE_GPU} != "false" ]]; then echo "Error: --use_gpu needs to have value (true|false)." >&2 echo "$USAGE" >&2 exit 1 fi shift # Remove argument name from processing shift # Remove argument value from processing ;; --use_hp_information) USE_HP_INFORMATION="$2" if [[ "${USE_HP_INFORMATION}" != "true" ]] && [[ "${USE_HP_INFORMATION}" != "false" ]]; then echo "Error: --use_hp_information needs to have value (true|false)." >&2 echo "$USAGE" >&2 exit 1 fi shift # Remove argument name from processing shift # Remove argument value from processing ;; --save_intermediate_results) SAVE_INTERMEDIATE_RESULTS="$2" if [[ "${SAVE_INTERMEDIATE_RESULTS}" != "true" ]] && [[ "${SAVE_INTERMEDIATE_RESULTS}" != "false" ]]; then echo "Error: --save_intermediate_results needs to have value (true|false)." >&2 echo "$USAGE" >&2 exit 1 fi shift # Remove argument name from processing shift # Remove argument value from processing ;; --regions) REGIONS="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --customized_model) CUSTOMIZED_MODEL="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --make_examples_extra_args) MAKE_EXAMPLES_ARGS="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --call_variants_extra_args) CALL_VARIANTS_ARGS="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --postprocess_variants_extra_args) POSTPROCESS_VARIANTS_ARGS="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --model_preset) MODEL_PRESET="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --model_type) MODEL_TYPE="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --bin_version) BIN_VERSION="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --bam_child) BAM_CHILD="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --bam_parent1) BAM_PARENT1="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --bam_parent2) BAM_PARENT2="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --capture_bed) CAPTURE_BED="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --proposed_variants) PROPOSED_VARIANTS="$2" shift # Remove argument name from processing shift # Remove argument value from processing ;; --help) echo "$USAGE" >&2 exit 1 ;; -*|--*=) # other flags not supported echo "Error: unrecognized flag $1" >&2 echo "Run with --help to see usage." >&2 exit 1 ;; *) echo "Error: unrecognized extra args $1" >&2 echo "Run with --help to see usage." >&2 exit 1 ;; esac done ## Presets # These settings specify the commonly run case studies GCS_DATA_DIR="https://storage.googleapis.com/deepvariant" BASE="${HOME}/custom-case-study" declare -a extra_args declare -a happy_args declare -a docker_args if [[ "${MODEL_PRESET}" = "PACBIO" ]]; then MODEL_TYPE="PACBIO" BASE="${HOME}/pacbio-case-study" BAM_CHILD="${GCS_DATA_DIR}/pacbio-case-study-testdata/HG002.pfda_challenge.grch38.phased.bam" BAM_PARENT1="${GCS_DATA_DIR}/pacbio-case-study-testdata/HG003.pfda_challenge.grch38.phased.bam" BAM_PARENT2="${GCS_DATA_DIR}/pacbio-case-study-testdata/HG004.pfda_challenge.grch38.phased.bam" elif [[ "${MODEL_PRESET}" = "PACBIO_CHR20" ]]; then MODEL_TYPE="PACBIO" BASE="${HOME}/pacbio-case-study" BAM_CHILD="${GCS_DATA_DIR}/pacbio-case-study-testdata/HG002.pfda_challenge.grch38.phased.chr20.bam" BAM_PARENT1="${GCS_DATA_DIR}/pacbio-case-study-testdata/HG003.pfda_challenge.grch38.phased.chr20.bam" BAM_PARENT2="${GCS_DATA_DIR}/pacbio-case-study-testdata/HG004.pfda_challenge.grch38.phased.chr20.bam" if [[ -n "${REGIONS}" ]]; then echo "For --model_preset=${MODEL_PRESET}, regions will be set to chr20." fi REGIONS=chr20 elif [[ "${MODEL_PRESET}" = "WGS" ]]; then MODEL_TYPE="WGS" BASE="${HOME}/wgs-case-study" BAM_CHILD="${GCS_DATA_DIR}/case-study-testdata/HG002.novaseq.pcr-free.35x.dedup.grch38_no_alt.bam" BAM_PARENT1="${GCS_DATA_DIR}/case-study-testdata/HG003.novaseq.pcr-free.35x.dedup.grch38_no_alt.bam" BAM_PARENT2="${GCS_DATA_DIR}/case-study-testdata/HG004.novaseq.pcr-free.35x.dedup.grch38_no_alt.bam" elif [[ "${MODEL_PRESET}" = "WGS_CHR20" ]]; then MODEL_TYPE="WGS" BASE="${HOME}/wgs-case-study" BAM_CHILD="${GCS_DATA_DIR}/case-study-testdata/HG002.novaseq.pcr-free.35x.dedup.grch38_no_alt.chr20.bam" BAM_PARENT1="${GCS_DATA_DIR}/case-study-testdata/HG003.novaseq.pcr-free.35x.dedup.grch38_no_alt.chr20.bam" BAM_PARENT2="${GCS_DATA_DIR}/case-study-testdata/HG004.novaseq.pcr-free.35x.dedup.grch38_no_alt.chr20.bam" if [[ -n "${REGIONS}" ]]; then echo "For --model_preset=${MODEL_PRESET}, regions will be set to chr20." fi REGIONS=chr20 elif [[ "${MODEL_PRESET}" = "WES" ]]; then MODEL_TYPE="WES" BASE="${HOME}/exome-case-study" BAM_CHILD="${GCS_DATA_DIR}/exome-case-study-testdata/HG002.novaseq.wes_idt.100x.dedup.bam" BAM_PARENT1="${GCS_DATA_DIR}/exome-case-study-testdata/HG003.novaseq.wes_idt.100x.dedup.bam" BAM_PARENT2="${GCS_DATA_DIR}/exome-case-study-testdata/HG004.novaseq.wes_idt.100x.dedup.bam" CAPTURE_BED="${GCS_DATA_DIR}/exome-case-study-testdata/idt_capture_novogene.grch38.bed" else if [[ -n "${MODEL_PRESET}" ]]; then echo "Error: --model_preset must be one of WGS, WGS_CHR20, WES, PACBIO, PACBIO_CHR20." >&2 exit 1 fi fi ## Flag consistency sanity checks. ## The user should have not set --use_hp_information if it's not PACBIO. if [[ "${USE_HP_INFORMATION}" != "unset" ]] && [[ "${MODEL_TYPE}" != "PACBIO" ]]; then echo "Error: Only set --use_hp_information for PACBIO." >&2 exit 1 fi if [[ "${USE_HP_INFORMATION}" == "unset" ]] && [[ "${MODEL_TYPE}" == "PACBIO" ]]; then # This is for backward-compatibility. echo "For PACBIO, set use_hp_information=true if it's not explicitly set." USE_HP_INFORMATION="true" fi N_SHARDS="64" INPUT_DIR="${BASE}/input/data" OUTPUT_DIR="${BASE}/output" MODELS_DIR="${INPUT_DIR}/models" CHILD_MODEL_DIR="${MODELS_DIR}/child" PARENT_MODEL_DIR="${MODELS_DIR}/parent" CHILD_MODEL="${CHILD_MODEL_DIR}/model.ckpt" PARENT_MODEL="${PARENT_MODEL_DIR}/model.ckpt" EXAMPLES_PREFIX="${OUTPUT_DIR}/make_examples.tfrecord@${N_SHARDS}.gz" EXAMPLES_CHILD="${OUTPUT_DIR}/make_examples_child.tfrecord@${N_SHARDS}.gz" EXAMPLES_PARENT1="${OUTPUT_DIR}/make_examples_parent1.tfrecord@${N_SHARDS}.gz" EXAMPLES_PARENT2="${OUTPUT_DIR}/make_examples_parent2.tfrecord@${N_SHARDS}.gz" GVCF_TFRECORDS_PREFIX="${OUTPUT_DIR}/gvcf.tfrecord@${N_SHARDS}.gz" GVCF_TFRECORDS_CHILD="${OUTPUT_DIR}/gvcf_child.tfrecord@${N_SHARDS}.gz" GVCF_TFRECORDS_PARENT1="${OUTPUT_DIR}/gvcf_parent1.tfrecord@${N_SHARDS}.gz" GVCF_TFRECORDS_PARENT2="${OUTPUT_DIR}/gvcf_parent2.tfrecord@${N_SHARDS}.gz" CALL_VARIANTS_OUTPUT_CHILD="${OUTPUT_DIR}/call_variants_output_child.tfrecord.gz" CALL_VARIANTS_OUTPUT_PARENT1="${OUTPUT_DIR}/call_variants_output_parent1.tfrecord.gz" CALL_VARIANTS_OUTPUT_PARENT2="${OUTPUT_DIR}/call_variants_output_parent2.tfrecord.gz" OUTPUT_VCF_CHILD="HG002.output.vcf.gz" OUTPUT_VCF_PARENT1="HG003.output.vcf.gz" OUTPUT_VCF_PARENT2="HG004.output.vcf.gz" OUTPUT_VCF_MERGED="HG002-3-4.output.vcf.gz" OUTPUT_GVCF_CHILD="HG002.output.g.vcf.gz" OUTPUT_GVCF_PARENT1="HG003.output.g.vcf.gz" OUTPUT_GVCF_PARENT2="HG004.output.g.vcf.gz" OUTPUT_STATS_CHILD="HG002.output.vcf_stats" OUTPUT_STATS_PARENT1="HG003.output.vcf_stats" OUTPUT_STATS_PARENT2="HG004.output.vcf_stats" REF="${GCS_DATA_DIR}/case-study-testdata/GCA_000001405.15_GRCh38_no_alt_analysis_set.fna" SAMPLE_NAME_CHILD="HG002" SAMPLE_NAME_PARENT1="HG003" SAMPLE_NAME_PARENT2="HG004" TRUTH_VCF_CHILD="${GCS_DATA_DIR}/case-study-testdata/HG002_GRCh38_1_22_v4.2.1_benchmark.vcf.gz" TRUTH_BED_CHILD="${GCS_DATA_DIR}/case-study-testdata/HG002_GRCh38_1_22_v4.2.1_benchmark_noinconsistent.bed" TRUTH_VCF_PARENT1="${GCS_DATA_DIR}/case-study-testdata/HG003_GRCh38_1_22_v4.2.1_benchmark.vcf.gz" TRUTH_BED_PARENT1="${GCS_DATA_DIR}/case-study-testdata/HG003_GRCh38_1_22_v4.2.1_benchmark_noinconsistent.bed" TRUTH_VCF_PARENT2="${GCS_DATA_DIR}/case-study-testdata/HG004_GRCh38_1_22_v4.2.1_benchmark.vcf.gz" TRUTH_BED_PARENT2="${GCS_DATA_DIR}/case-study-testdata/HG004_GRCh38_1_22_v4.2.1_benchmark_noinconsistent.bed" LOG_DIR="${OUTPUT_DIR}/logs" if [[ "${MODEL_TYPE}" = "WES" ]]; then if [[ -n "${REGIONS}" ]]; then echo "Error: --regions is not used with model_type WES. Please use --capture_bed." >&2 exit 1 fi extra_args+=( --regions "/input/$(basename $CAPTURE_BED)") happy_args+=( -T "${INPUT_DIR}/$(basename $CAPTURE_BED)") fi if [[ "${SAVE_INTERMEDIATE_RESULTS}" == "true" ]]; then extra_args+=( --intermediate_results_dir "/output/intermediate_results_dir") fi echo "=========================" echo "# Booleans; sorted alphabetically." echo "BUILD_DOCKER: ${BUILD_DOCKER}" echo "DRY_RUN: ${DRY_RUN}" echo "USE_GPU: ${USE_GPU}" echo "USE_HP_INFORMATION: ${USE_HP_INFORMATION}" echo "SAVE_INTERMEDIATE_RESULTS: ${SAVE_INTERMEDIATE_RESULTS}" echo "# Strings; sorted alphabetically." echo "BAM_CHILD: ${BAM_CHILD}" echo "BAM_PARENT1: ${BAM_PARENT1}" echo "BAM_PARENT2: ${BAM_PARENT2}" echo "BIN_VERSION: ${BIN_VERSION}" echo "CALL_VARIANTS_ARGS: ${CALL_VARIANTS_ARGS}" echo "CAPTURE_BED: ${CAPTURE_BED}" echo "CUSTOMIZED_MODEL: ${CUSTOMIZED_MODEL}" echo "MAKE_EXAMPLES_ARGS: ${MAKE_EXAMPLES_ARGS}" echo "MODEL_PRESET: ${MODEL_PRESET}" echo "MODEL_TYPE: ${MODEL_TYPE}" echo "POSTPROCESS_VARIANTS_ARGS: ${POSTPROCESS_VARIANTS_ARGS}" echo "PROPOSED_VARIANTS: ${PROPOSED_VARIANTS}" echo "REF: ${REF}" echo "REGIONS: ${REGIONS}" echo "=========================" function run() { if [[ "${DRY_RUN}" == "true" ]]; then # Prints out command to stdout and a [DRY RUN] tag to stderr. # This allows the users to use the dry_run mode to get a list of # executable commands by redirecting stdout to a file. 1>&2 printf "[DRY RUN] " && echo "$*" else echo "$*" eval "$@" fi } function copy_gs_or_http_file() { if [[ "$1" == http* ]]; then if curl --output /dev/null --silent --head --fail "$1"; then run echo "Copying from \"$1\" to \"$2\"" run aria2c -c -x10 -s10 "$1" -d "$2" else run echo "File $1 does not exist. Skip copying." fi elif [[ "$1" == gs://* ]]; then status=0 gsutil -q stat "$1" || status=1 if [[ $status == 0 ]]; then run echo "Copying from \"$1\" to \"$2\"" run gsutil -m cp "$1" "$2" else run echo "File $1 does not exist. Skip copying." fi else echo "Unrecognized file format: $1" >&2 exit 1 fi } function copy_correct_index_file() { BAM="$1" INPUT_DIR="$2" # Index files have two acceptable naming patterns. We explicitly check for # both since we cannot use wildcard paths with http files. if [[ "${BAM}" == *".cram" ]]; then copy_gs_or_http_file "${BAM%.cram}.crai" "${INPUT_DIR}" copy_gs_or_http_file "${BAM}.crai" "${INPUT_DIR}" else copy_gs_or_http_file "${BAM%.bam}.bai" "${INPUT_DIR}" copy_gs_or_http_file "${BAM}.bai" "${INPUT_DIR}" fi } function copy_data() { copy_gs_or_http_file "${TRUTH_BED_CHILD}" "${INPUT_DIR}" copy_gs_or_http_file "${TRUTH_VCF_CHILD}" "${INPUT_DIR}" copy_gs_or_http_file "${TRUTH_VCF_CHILD}.tbi" "${INPUT_DIR}" # Copy HG003 truth copy_gs_or_http_file "${TRUTH_BED_PARENT1}" "${INPUT_DIR}" copy_gs_or_http_file "${TRUTH_VCF_PARENT1}" "${INPUT_DIR}" copy_gs_or_http_file "${TRUTH_VCF_PARENT1}.tbi" "${INPUT_DIR}" # Copy HG004 truth copy_gs_or_http_file "${TRUTH_BED_PARENT2}" "${INPUT_DIR}" copy_gs_or_http_file "${TRUTH_VCF_PARENT2}" "${INPUT_DIR}" copy_gs_or_http_file "${TRUTH_VCF_PARENT2}.tbi" "${INPUT_DIR}" copy_gs_or_http_file "${BAM_CHILD}" "${INPUT_DIR}" copy_correct_index_file "${BAM_CHILD}" "${INPUT_DIR}" copy_gs_or_http_file "${BAM_PARENT1}" "${INPUT_DIR}" copy_correct_index_file "${BAM_PARENT1}" "${INPUT_DIR}" copy_gs_or_http_file "${BAM_PARENT2}" "${INPUT_DIR}" copy_correct_index_file "${BAM_PARENT2}" "${INPUT_DIR}" copy_gs_or_http_file "${REF}.gz" "${INPUT_DIR}" copy_gs_or_http_file "${REF}.gz.fai" "${INPUT_DIR}" copy_gs_or_http_file "${REF}.gz.gzi" "${INPUT_DIR}" copy_gs_or_http_file "${REF}.gzi" "${INPUT_DIR}" copy_gs_or_http_file "${REF}.fai" "${INPUT_DIR}" if [[ "${MODEL_TYPE}" = "WES" ]]; then copy_gs_or_http_file "${CAPTURE_BED}" "${INPUT_DIR}" fi if [[ -n "${PROPOSED_VARIANTS}" ]]; then copy_gs_or_http_file "${PROPOSED_VARIANTS}" "${INPUT_DIR}" copy_gs_or_http_file "${PROPOSED_VARIANTS}.tbi" "${INPUT_DIR}" fi } function setup_test() { if [[ "${DRY_RUN}" == "true" ]]; then return fi ## Create local directory structure mkdir -p "${OUTPUT_DIR}" mkdir -p "${INPUT_DIR}" mkdir -p "${MODELS_DIR}" mkdir -p "${CHILD_MODEL_DIR}" mkdir -p "${PARENT_MODEL_DIR}" mkdir -p "${LOG_DIR}" ## Download extra packages # Install aria2 to download data files. sudo apt-get -qq -y update sudo apt-get -qq -y install aria2 sudo apt-get -qq -y install bcftools sudo apt-get -qq -y install tabix if ! hash docker 2>/dev/null; then echo "'docker' was not found in PATH. Installing docker..." # Install docker using instructions on: # https://docs.docker.com/install/linux/docker-ce/ubuntu/ sudo apt-get -qq -y install \ apt-transport-https \ ca-certificates \ curl \ gnupg-agent \ software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ stable" sudo apt-get -qq -y update sudo apt-get -qq -y install docker-ce fi } function get_docker_image() { if [[ "${BUILD_DOCKER}" = true ]]; then if [[ "${USE_GPU}" = true ]]; then IMAGE="deeptrio_gpu:latest" run "sudo docker build \ -f Dockerfile.deeptrio \ --build-arg=FROM_IMAGE=nvidia/cuda:11.3.0-cudnn8-devel-ubuntu20.04 \ --build-arg=DV_GPU_BUILD=1 -t deeptrio_gpu ." run echo "Done building GPU Docker image ${IMAGE}." docker_args+=( --gpus 1 ) else IMAGE="deeptrio:latest" # Building twice in case the first one times out. run "sudo docker build -f Dockerfile.deeptrio -t deeptrio . || \ (sleep 5 ; sudo docker build -f Dockerfile.deeptrio -t deeptrio . )" run echo "Done building Docker image ${IMAGE}." fi else if [[ "${USE_GPU}" = true ]]; then IMAGE="google/deepvariant:deeptrio-${BIN_VERSION}-gpu" # shellcheck disable=SC2027 # shellcheck disable=SC2086 run "sudo docker pull "${IMAGE}" || \ (sleep 5 ; sudo docker pull "${IMAGE}")" docker_args+=( --gpus 1 ) else IMAGE="google/deepvariant:deeptrio-${BIN_VERSION}" # shellcheck disable=SC2027 # shellcheck disable=SC2086 run "sudo docker pull "${IMAGE}" || \ (sleep 5 ; sudo docker pull "${IMAGE}")" fi fi if [[ "${USE_GPU}" = true ]]; then # shellcheck disable=SC2027 # shellcheck disable=SC2086 run "sudo docker run --gpus 1 "${IMAGE}" \ python3 -c 'import tensorflow as tf; \ print(\"is_gpu_available=\" + str(tf.test.is_gpu_available()))'" # shellcheck disable=SC2027 # shellcheck disable=SC2086 run "sudo docker run --gpus 1 "${IMAGE}" \ python3 -c 'import tensorflow as tf; \ tf.test.is_gpu_available() or exit(1)' \ 2> /dev/null || exit 1" fi } function setup_args() { if [[ -n "${CUSTOMIZED_MODEL}" ]]; then # redacted run echo "Copy from gs:// path ${CUSTOMIZED_MODEL} to ${INPUT_DIR}/" run gsutil cp "${CUSTOMIZED_MODEL}".data-00000-of-00001 "${INPUT_DIR}/model.ckpt.data-00000-of-00001" run gsutil cp "${CUSTOMIZED_MODEL}".index "${INPUT_DIR}/model.ckpt.index" run gsutil cp "${CUSTOMIZED_MODEL}".meta "${INPUT_DIR}/model.ckpt.meta" run "gsutil cp ${CUSTOMIZED_MODEL}.input_shape ${INPUT_DIR}/model.ckpt.input_shape || echo 'skip input_shape'" extra_args+=( --customized_model "/input/model.ckpt") # redacted # echo "Copy from gs:// path $CUSTOMIZED_MODEL to ${INPUT_DIR}/" # gsutil cp "${CUSTOMIZED_MODEL}"/child/model.ckpt.data-00000-of-00001 "${INPUT_DIR}/child/" # gsutil cp "${CUSTOMIZED_MODEL}"/child/model.ckpt.index "${INPUT_DIR}child/" # gsutil cp "${CUSTOMIZED_MODEL}"/child/model.ckpt.meta "${INPUT_DIR}child/" # gsutil cp "${CUSTOMIZED_MODEL}"/parent/model.ckpt.data-00000-of-00001 "${INPUT_DIR}/parent/" # gsutil cp "${CUSTOMIZED_MODEL}"/parent/model.ckpt.index "${INPUT_DIR}parent/" # gsutil cp "${CUSTOMIZED_MODEL}"/parent/model.ckpt.meta "${INPUT_DIR}parent/" # extra_args+=( --customized_model "/input/model.ckpt") else run echo "No custom model specified." fi if [[ -n "${MAKE_EXAMPLES_ARGS}" ]]; then # In order to use proposed variants, we have to pass vcf_candidate_importer # to make_examples_extra_args, so we know that we will enter this if # statement. if [[ -n "${PROPOSED_VARIANTS}" ]]; then MAKE_EXAMPLES_ARGS="${MAKE_EXAMPLES_ARGS},proposed_variants=/input/$(basename "$PROPOSED_VARIANTS")" fi extra_args+=( --make_examples_extra_args "${MAKE_EXAMPLES_ARGS}") fi if [[ -n "${CALL_VARIANTS_ARGS}" ]]; then extra_args+=( --call_variants_extra_args "${CALL_VARIANTS_ARGS}") fi if [[ "${USE_HP_INFORMATION}" == "true" ]] || [[ "${USE_HP_INFORMATION}" == "false" ]]; then # Note that because --use_hp_information is a binary flag, I need to use # the --flag=(true|false) format, or use --[no]flag format. extra_args+=( "--use_hp_information=${USE_HP_INFORMATION}" ) fi if [[ -n "${POSTPROCESS_VARIANTS_ARGS}" ]]; then extra_args+=( --postprocess_variants_extra_args "${POSTPROCESS_VARIANTS_ARGS}") fi if [[ -n "${REGIONS}" ]]; then extra_args+=( --regions "${REGIONS}") happy_args+=( -l "${REGIONS}") fi if [[ "${BUILD_DOCKER}" = true ]] || [[ "${BIN_VERSION}" =~ ^1\.[2-9]\.0$ ]]; then extra_args+=( --runtime_report ) fi } function run_deeptrio() { run echo "Run DeepTrio..." run echo "using IMAGE=${IMAGE}" # shellcheck disable=SC2027 # shellcheck disable=SC2046 # shellcheck disable=SC2068 # shellcheck disable=SC2086 # shellcheck disable=SC2145 run "(time (sudo docker run \ -v "${INPUT_DIR}":"/input" \ -v "${OUTPUT_DIR}:/output" \ ${docker_args[@]-} \ "${IMAGE}" \ /opt/deepvariant/bin/deeptrio/run_deeptrio \ --model_type "${MODEL_TYPE}" \ --ref="/input/$(basename $REF).gz" \ --reads_child "/input/$(basename $BAM_CHILD)" \ --reads_parent1 "/input/$(basename $BAM_PARENT1)" \ --reads_parent2 "/input/$(basename $BAM_PARENT2)" \ --output_vcf_child "/output/${OUTPUT_VCF_CHILD}" \ --output_vcf_parent1 "/output/${OUTPUT_VCF_PARENT1}" \ --output_vcf_parent2 "/output/${OUTPUT_VCF_PARENT2}" \ --sample_name_child "${SAMPLE_NAME_CHILD}" \ --sample_name_parent1 "${SAMPLE_NAME_PARENT1}" \ --sample_name_parent2 "${SAMPLE_NAME_PARENT2}" \ --num_shards "$(nproc)" \ --intermediate_results_dir /output/intermediate_results_dir \ --output_gvcf_child "/output/${OUTPUT_GVCF_CHILD}" \ --output_gvcf_parent1 "/output/${OUTPUT_GVCF_PARENT1}" \ --output_gvcf_parent2 "/output/${OUTPUT_GVCF_PARENT2}" \ --logging_dir="/output/logs" \ "${extra_args[@]-}" && \ echo "Done.")) 2>&1 | tee "${LOG_DIR}/deeptrio_runtime.log"" echo } function run_happy() { ## Evaluation: run hap.py local -r truth_vcf=$(basename "${1}") local -r truth_bed=$(basename "${2}") local -r vcf_output=$(basename "${3}") local -r optional_chr="${4-}" run echo "Start evaluation with hap.py..." declare -a optional_chr_args if [[ -n ${optional_chr} ]]; then optional_chr_args+=(-l "${optional_chr}") run echo "... evaluating on ${optional_chr}" fi UNCOMPRESSED_REF=${INPUT_DIR}/$(basename $REF) # hap.py cannot read the compressed fa, so uncompress # into a writable directory. Index file was downloaded earlier. # shellcheck disable=SC2027 # shellcheck disable=SC2046 # shellcheck disable=SC2086 run "zcat <"${INPUT_DIR}/$(basename $REF).gz" >"${UNCOMPRESSED_REF}"" HAPPY_VERSION="v0.3.12" # Pulling twice in case the first one times out. run "sudo docker pull jmcdani20/hap.py:${HAPPY_VERSION} || \ (sleep 5 ; sudo docker pull jmcdani20/hap.py:${HAPPY_VERSION})" # shellcheck disable=SC2086 # shellcheck disable=SC2145 run "( sudo docker run -i \ -v "${INPUT_DIR}:${INPUT_DIR}" \ -v "${OUTPUT_DIR}:${OUTPUT_DIR}" \ jmcdani20/hap.py:${HAPPY_VERSION} /opt/hap.py/bin/hap.py \ "${INPUT_DIR}/${truth_vcf}" \ "${OUTPUT_DIR}/${vcf_output}" \ -f "${INPUT_DIR}/${truth_bed}" \ -r ${UNCOMPRESSED_REF} \ -o "${OUTPUT_DIR}/happy.output${optional_chr}-${vcf_output}" \ --engine=vcfeval \ --pass-only \ ${happy_args[@]-} \ ${optional_chr_args[@]-} \ ) 2>&1 | tee "${LOG_DIR}/happy.output${optional_chr}-${vcf_output}.log"" if [[ "${DRY_RUN}" != "true" ]]; then echo "${HAPPY_VERSION}" > "${LOG_DIR}/happy_version.log" fi run echo "Done." } function run_happy_reports() { local -r optional_chr="${1-}" if [[ ${DRY_RUN} == "true" ]]; then run_happy "${TRUTH_VCF_CHILD}" "${TRUTH_BED_CHILD}" "${OUTPUT_VCF_CHILD}" "${optional_chr}" run_happy "${TRUTH_VCF_PARENT1}" "${TRUTH_BED_PARENT1}" "${OUTPUT_VCF_PARENT1}" "${optional_chr}" run_happy "${TRUTH_VCF_PARENT2}" "${TRUTH_BED_PARENT2}" "${OUTPUT_VCF_PARENT2}" "${optional_chr}" run_happy "${TRUTH_VCF_CHILD}" "${TRUTH_BED_CHILD}" "HG002_split.vcf" "${optional_chr}" run_happy "${TRUTH_VCF_PARENT1}" "${TRUTH_BED_PARENT1}" "HG003_split.vcf" "${optional_chr}" run_happy "${TRUTH_VCF_PARENT2}" "${TRUTH_BED_PARENT2}" "HG004_split.vcf" "${optional_chr}" else run_happy "${TRUTH_VCF_CHILD}" "${TRUTH_BED_CHILD}" "${OUTPUT_VCF_CHILD}" "${optional_chr}" 2>&1 | tee "${LOG_DIR}/happy_child.log" run_happy "${TRUTH_VCF_PARENT1}" "${TRUTH_BED_PARENT1}" "${OUTPUT_VCF_PARENT1}" "${optional_chr}" 2>&1 | tee "${LOG_DIR}/happy_parent1.log" run_happy "${TRUTH_VCF_PARENT2}" "${TRUTH_BED_PARENT2}" "${OUTPUT_VCF_PARENT2}" "${optional_chr}" 2>&1 | tee "${LOG_DIR}/happy_parent2.log" run_happy "${TRUTH_VCF_CHILD}" "${TRUTH_BED_CHILD}" "HG002_split.vcf" "${optional_chr}" 2>&1 | tee "${LOG_DIR}/happy_child_split.log" run_happy "${TRUTH_VCF_PARENT1}" "${TRUTH_BED_PARENT1}" "HG003_split.vcf" "${optional_chr}" 2>&1 | tee "${LOG_DIR}/happy_parent1_split.log" run_happy "${TRUTH_VCF_PARENT2}" "${TRUTH_BED_PARENT2}" "HG004_split.vcf" "${optional_chr}" 2>&1 | tee "${LOG_DIR}/happy_parent2_split.log" fi } function run_glnexus() { if [[ ${DRY_RUN} == "true" ]]; then return fi sudo docker pull quay.io/mlin/glnexus:v1.2.7 || \ (sleep 5 ; sudo docker pull quay.io/mlin/glnexus:v1.2.7) time sudo docker run \ -v "${OUTPUT_DIR}":"/output" \ quay.io/mlin/glnexus:v1.2.7 \ /usr/local/bin/glnexus_cli \ --config DeepVariant_unfiltered \ "/output/${OUTPUT_GVCF_PARENT2}" "/output/${OUTPUT_GVCF_PARENT1}" "/output/${OUTPUT_GVCF_CHILD}" \ | bcftools view - | bgzip -c > "${OUTPUT_DIR}/${OUTPUT_VCF_MERGED}" } function extract_samples() { if [[ ${DRY_RUN} == "true" ]]; then return fi bcftools view -s HG002 "${OUTPUT_DIR}/${OUTPUT_VCF_MERGED}" > "${OUTPUT_DIR}/HG002_split.vcf" bcftools view -s HG003 "${OUTPUT_DIR}/${OUTPUT_VCF_MERGED}" > "${OUTPUT_DIR}/HG003_split.vcf" bcftools view -s HG004 "${OUTPUT_DIR}/${OUTPUT_VCF_MERGED}" > "${OUTPUT_DIR}/HG004_split.vcf" } function main() { run echo 'Starting the test...' setup_test copy_data get_docker_image setup_args run_deeptrio run_glnexus extract_samples run_happy_reports if [[ -z "${REGIONS}" ]]; then run_happy_reports "chr20" fi } main "$@"
google/deepvariant
scripts/inference_deeptrio.sh
Shell
bsd-3-clause
28,096
""" A sub-package for efficiently dealing with polynomials. Within the documentation for this sub-package, a "finite power series," i.e., a polynomial (also referred to simply as a "series") is represented by a 1-D numpy array of the polynomial's coefficients, ordered from lowest order term to highest. For example, array([1,2,3]) represents ``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial applicable to the specific module in question, e.g., `polynomial` (which "wraps" the "standard" basis) or `chebyshev`. For optimal performance, all operations on polynomials, including evaluation at an argument, are implemented as operations on the coefficients. Additional (module-specific) information can be found in the docstring for the module of interest. """ from polynomial import * from chebyshev import * from polyutils import * from numpy.testing import Tester test = Tester(__file__).test bench = Tester(__file__).bench
teoliphant/numpy-refactor
numpy/polynomial/__init__.py
Python
bsd-3-clause
951
/*! cropit - v0.4.5 <https://github.com/scottcheng/cropit> */ (function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("jquery")); else if (typeof define === 'function' && define.amd) define(["jquery"], factory); else if (typeof exports === 'object') exports["cropit"] = factory(require("jquery")); else root["cropit"] = factory(root["jQuery"]); })(this, function (__WEBPACK_EXTERNAL_MODULE_1__) { return /******/ (function (modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if (installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/}; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/([ /* 0 */ /***/ function (module, exports, __webpack_require__) { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {'default': obj}; } var _jquery = __webpack_require__(1); var _jquery2 = _interopRequireDefault(_jquery); var _cropit = __webpack_require__(2); var _cropit2 = _interopRequireDefault(_cropit); var _constants = __webpack_require__(4); var _utils = __webpack_require__(6); var applyOnEach = function applyOnEach($el, callback) { return $el.each(function () { var cropit = _jquery2['default'].data(this, _constants.PLUGIN_KEY); if (!cropit) { return; } callback(cropit); }); }; var callOnFirst = function callOnFirst($el, method, options) { var cropit = $el.first().data(_constants.PLUGIN_KEY); if (!cropit || !_jquery2['default'].isFunction(cropit[method])) { return null; } return cropit[method](options); }; var methods = { init: function init(options) { return this.each(function () { // Only instantiate once per element if (_jquery2['default'].data(this, _constants.PLUGIN_KEY)) { return; } var cropit = new _cropit2['default'](_jquery2['default'], this, options); _jquery2['default'].data(this, _constants.PLUGIN_KEY, cropit); }); }, destroy: function destroy() { return this.each(function () { _jquery2['default'].removeData(this, _constants.PLUGIN_KEY); }); }, isZoomable: function isZoomable() { return callOnFirst(this, 'isZoomable'); }, 'export': function _export(options) { return callOnFirst(this, 'getCroppedImageData', options); }, imageState: function imageState() { return callOnFirst(this, 'getImageState'); }, imageSize: function imageSize() { return callOnFirst(this, 'getImageSize'); }, prop: function prop(name, value) { if ((0, _utils.exists)(value)) { return applyOnEach(this, function (cropit) { cropit['set' + (0, _utils.capitalize)(name)](value); }); } else { return callOnFirst(this, 'get' + (0, _utils.capitalize)(name)); } }, disable: function disable() { return applyOnEach(this, function (cropit) { cropit.disable(); }); }, reenable: function reenable() { return applyOnEach(this, function (cropit) { cropit.reenable(); }); } }; _jquery2['default'].fn.cropit = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (['imageSrc', 'offset', 'previewSize', 'zoom', 'initialZoom', 'exportZoom', 'minZoom', 'maxZoom'].indexOf(method) >= 0) { return methods.prop.apply(this, arguments); } else { return methods.init.apply(this, arguments); } }; /***/ }, /* 1 */ /***/ function (module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function (module, exports, __webpack_require__) { Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {'default': obj}; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _jquery = __webpack_require__(1); var _jquery2 = _interopRequireDefault(_jquery); var _Zoomer = __webpack_require__(3); var _Zoomer2 = _interopRequireDefault(_Zoomer); var _constants = __webpack_require__(4); var _options = __webpack_require__(5); var _utils = __webpack_require__(6); var Cropit = (function () { function Cropit(jQuery, element, options) { _classCallCheck(this, Cropit); this.$el = (0, _jquery2['default'])(element); var defaults = (0, _options.loadDefaults)(this.$el); this.options = _jquery2['default'].extend({}, defaults, options); this.init(); } _createClass(Cropit, [{ key: 'init', value: function init() { var _this = this; this.image = new Image(); this.preImage = new Image(); this.image.onload = this.onImageLoaded.bind(this); this.preImage.onload = this.onPreImageLoaded.bind(this); this.image.onerror = this.preImage.onerror = function () { _this.onImageError.call(_this, _constants.ERRORS.IMAGE_FAILED_TO_LOAD); }; this.$fileInput = this.options.$fileInput.attr({accept: 'image/*'}); this.$preview = this.options.$preview.css({backgroundRepeat: 'no-repeat'}); this.$zoomSlider = this.options.$zoomSlider.attr({min: 0, max: 1, step: 0.01}); this.previewSize = { w: this.options.width || this.$preview.width(), h: this.options.height || this.$preview.height() }; if (this.options.width) { this.$preview.width(this.previewSize.w); } if (this.options.height) { this.$preview.height(this.previewSize.h); } if (this.options.imageBackground) { if (_jquery2['default'].isArray(this.options.imageBackgroundBorderWidth)) { this.imageBgBorderWidthArray = this.options.imageBackgroundBorderWidth; } else { this.imageBgBorderWidthArray = []; [0, 1, 2, 3].forEach(function (i) { _this.imageBgBorderWidthArray[i] = _this.options.imageBackgroundBorderWidth; }); } var $previewContainer = this.options.$previewContainer; this.$imageBg = (0, _jquery2['default'])('<img />').addClass(_constants.CLASS_NAMES.IMAGE_BACKGROUND).attr('alt', '').css('position', 'absolute'); this.$imageBgContainer = (0, _jquery2['default'])('<div />').addClass(_constants.CLASS_NAMES.IMAGE_BACKGROUND_CONTAINER).css({ position: 'absolute', zIndex: 0, left: -this.imageBgBorderWidthArray[3] + window.parseInt(this.$preview.css('border-left-width') || 0), top: -this.imageBgBorderWidthArray[0] + window.parseInt(this.$preview.css('border-top-width') || 0), width: this.previewSize.w + this.imageBgBorderWidthArray[1] + this.imageBgBorderWidthArray[3], height: this.previewSize.h + this.imageBgBorderWidthArray[0] + this.imageBgBorderWidthArray[2] }).append(this.$imageBg); if (this.imageBgBorderWidthArray[0] > 0) { this.$imageBgContainer.css('overflow', 'hidden'); } $previewContainer.css('position', 'relative').prepend(this.$imageBgContainer); this.$preview.css('position', 'relative'); this.$preview.hover(function () { _this.$imageBg.addClass(_constants.CLASS_NAMES.PREVIEW_HOVERED); }, function () { _this.$imageBg.removeClass(_constants.CLASS_NAMES.PREVIEW_HOVERED); }); } this.setInitialZoom(this.options.initialZoom); this.imageLoaded = false; this.moveContinue = false; this.zoomer = new _Zoomer2['default'](); if (this.options.allowDragNDrop) { _jquery2['default'].event.props.push('dataTransfer'); } this.bindListeners(); if (this.options.imageState && this.options.imageState.src) { this.loadImage(this.options.imageState.src); } } }, { key: 'bindListeners', value: function bindListeners() { this.$fileInput.on('change.cropit', this.onFileChange.bind(this)); this.$preview.on(_constants.EVENTS.PREVIEW, this.onPreviewEvent.bind(this)); this.$zoomSlider.on(_constants.EVENTS.ZOOM_INPUT, this.onZoomSliderChange.bind(this)); if (this.options.allowDragNDrop) { this.$preview.on('dragover.cropit dragleave.cropit', this.onDragOver.bind(this)); this.$preview.on('drop.cropit', this.onDrop.bind(this)); } } }, { key: 'unbindListeners', value: function unbindListeners() { this.$fileInput.off('change.cropit'); this.$preview.off(_constants.EVENTS.PREVIEW); this.$preview.off('dragover.cropit dragleave.cropit drop.cropit'); this.$zoomSlider.off(_constants.EVENTS.ZOOM_INPUT); } }, { key: 'onFileChange', value: function onFileChange(e) { this.options.onFileChange(e); if (this.$fileInput.get(0).files) { this.loadFileReader(this.$fileInput.get(0).files[0]); } } }, { key: 'loadFileReader', value: function loadFileReader(file) { var fileReader = new FileReader(); if (file && file.type.match('image')) { fileReader.readAsDataURL(file); fileReader.onload = this.onFileReaderLoaded.bind(this); fileReader.onerror = this.onFileReaderError.bind(this); } else if (file) { this.onFileReaderError(); } } }, { key: 'onFileReaderLoaded', value: function onFileReaderLoaded(e) { this.loadImage(e.target.result); } }, { key: 'onFileReaderError', value: function onFileReaderError() { this.options.onFileReaderError(); } }, { key: 'onDragOver', value: function onDragOver(e) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; this.$preview.toggleClass(_constants.CLASS_NAMES.DRAG_HOVERED, e.type === 'dragover'); } }, { key: 'onDrop', value: function onDrop(e) { var _this2 = this; e.preventDefault(); e.stopPropagation(); var files = Array.prototype.slice.call(e.dataTransfer.files, 0); files.some(function (file) { if (!file.type.match('image')) { return false; } _this2.loadFileReader(file); return true; }); this.$preview.removeClass(_constants.CLASS_NAMES.DRAG_HOVERED); } }, { key: 'loadImage', value: function loadImage(imageSrc) { if (!imageSrc) { return; } this.options.onImageLoading(); this.setImageLoadingClass(); this.preImage.src = imageSrc; } }, { key: 'setImageSrc', value: function setImageSrc(imageSrc) { this.loadImage(imageSrc); } }, { key: 'onPreImageLoaded', value: function onPreImageLoaded() { if (this.options.smallImage === 'reject' && (this.preImage.width * this.options.maxZoom < this.previewSize.w * this.options.exportZoom || this.preImage.height * this.options.maxZoom < this.previewSize.h * this.options.exportZoom)) { this.onImageError(_constants.ERRORS.SMALL_IMAGE); if (this.image.src) { this.setImageLoadedClass(); } return; } if (this.options.allowCrossOrigin) { this.image.crossOrigin = this.preImage.src.indexOf('data:') === 0 ? null : 'Anonymous'; } this.image.src = this.imageSrc = this.preImage.src; } }, { key: 'onImageLoaded', value: function onImageLoaded() { this.imageSize = { w: this.image.width, h: this.image.height }; this.setupZoomer(this.options.imageState && this.options.imageState.zoom || this.initialZoom); if (this.options.imageState && this.options.imageState.offset) { this.setOffset(this.options.imageState.offset); } else { this.centerImage(); } this.options.imageState = {}; this.$preview.css('background-image', 'url(' + this.imageSrc + ')'); if (this.options.imageBackground) { this.$imageBg.attr('src', this.imageSrc); } this.setImageLoadedClass(); this.imageLoaded = true; this.options.onImageLoaded(); } }, { key: 'onImageError', value: function onImageError() { this.options.onImageError.apply(this, arguments); this.removeImageLoadingClass(); } }, { key: 'setImageLoadingClass', value: function setImageLoadingClass() { this.$preview.removeClass(_constants.CLASS_NAMES.IMAGE_LOADED).addClass(_constants.CLASS_NAMES.IMAGE_LOADING); } }, { key: 'setImageLoadedClass', value: function setImageLoadedClass() { this.$preview.removeClass(_constants.CLASS_NAMES.IMAGE_LOADING).addClass(_constants.CLASS_NAMES.IMAGE_LOADED); } }, { key: 'removeImageLoadingClass', value: function removeImageLoadingClass() { this.$preview.removeClass(_constants.CLASS_NAMES.IMAGE_LOADING); } }, { key: 'getEventPosition', value: function getEventPosition(e) { if (e.originalEvent && e.originalEvent.touches && e.originalEvent.touches[0]) { e = e.originalEvent.touches[0]; } if (e.clientX && e.clientY) { return {x: e.clientX, y: e.clientY}; } } }, { key: 'onPreviewEvent', value: function onPreviewEvent(e) { if (!this.imageLoaded) { return; } this.moveContinue = false; this.$preview.off(_constants.EVENTS.PREVIEW_MOVE); if (e.type === 'mousedown' || e.type === 'touchstart') { this.origin = this.getEventPosition(e); this.moveContinue = true; this.$preview.on(_constants.EVENTS.PREVIEW_MOVE, this.onMove.bind(this)); } else { (0, _jquery2['default'])(document.body).focus(); } e.stopPropagation(); return false; } }, { key: 'onMove', value: function onMove(e) { var eventPosition = this.getEventPosition(e); if (this.moveContinue && eventPosition) { this.setOffset({ x: this.offset.x + eventPosition.x - this.origin.x, y: this.offset.y + eventPosition.y - this.origin.y }); } this.origin = eventPosition; e.stopPropagation(); return false; } }, { key: 'setOffset', value: function setOffset(position) { if (!position || !(0, _utils.exists)(position.x) || !(0, _utils.exists)(position.y)) { return; } this.offset = this.fixOffset(position); this.$preview.css('background-position', '' + this.offset.x + 'px ' + this.offset.y + 'px'); if (this.options.imageBackground) { this.$imageBg.css({ left: this.offset.x + this.imageBgBorderWidthArray[3], top: this.offset.y + this.imageBgBorderWidthArray[0] }); } this.options.onOffsetChange(position); } }, { key: 'fixOffset', value: function fixOffset(offset) { if (!this.imageLoaded) { return offset; } var ret = {x: offset.x, y: offset.y}; if (!this.options.freeMove) { if (this.imageSize.w * this.zoom >= this.previewSize.w) { ret.x = Math.min(0, Math.max(ret.x, this.previewSize.w - this.imageSize.w * this.zoom)); } else { ret.x = Math.max(0, Math.min(ret.x, this.previewSize.w - this.imageSize.w * this.zoom)); } if (this.imageSize.h * this.zoom >= this.previewSize.h) { ret.y = Math.min(0, Math.max(ret.y, this.previewSize.h - this.imageSize.h * this.zoom)); } else { ret.y = Math.max(0, Math.min(ret.y, this.previewSize.h - this.imageSize.h * this.zoom)); } } ret.x = (0, _utils.round)(ret.x); ret.y = (0, _utils.round)(ret.y); return ret; } }, { key: 'centerImage', value: function centerImage() { if (!this.imageSize || !this.zoom) { return; } this.setOffset({ x: (this.previewSize.w - this.imageSize.w * this.zoom) / 2, y: (this.previewSize.h - this.imageSize.h * this.zoom) / 2 }); } }, { key: 'onZoomSliderChange', value: function onZoomSliderChange() { if (!this.imageLoaded) { return; } this.zoomSliderPos = Number(this.$zoomSlider.val()); var newZoom = this.zoomer.getZoom(this.zoomSliderPos); if (newZoom === this.zoom) { return; } this.setZoom(newZoom); } }, { key: 'enableZoomSlider', value: function enableZoomSlider() { this.$zoomSlider.removeAttr('disabled'); this.options.onZoomEnabled(); } }, { key: 'disableZoomSlider', value: function disableZoomSlider() { this.$zoomSlider.attr('disabled', true); this.options.onZoomDisabled(); } }, { key: 'setupZoomer', value: function setupZoomer(zoom) { this.zoomer.setup({ imageSize: this.imageSize, previewSize: this.previewSize, exportZoom: this.options.exportZoom, maxZoom: this.options.maxZoom, minZoom: this.options.minZoom, smallImage: this.options.smallImage }); this.setZoom((0, _utils.exists)(zoom) ? zoom : this.zoom); if (this.isZoomable()) { this.enableZoomSlider(); } else { this.disableZoomSlider(); } } }, { key: 'setZoom', value: function setZoom(newZoom) { newZoom = this.fixZoom(newZoom); var updatedWidth = (0, _utils.round)(this.imageSize.w * newZoom); var updatedHeight = (0, _utils.round)(this.imageSize.h * newZoom); if (this.imageLoaded) { var oldZoom = this.zoom; var newX = this.previewSize.w / 2 - (this.previewSize.w / 2 - this.offset.x) * newZoom / oldZoom; var newY = this.previewSize.h / 2 - (this.previewSize.h / 2 - this.offset.y) * newZoom / oldZoom; this.zoom = newZoom; this.setOffset({x: newX, y: newY}); } else { this.zoom = newZoom; } this.zoomSliderPos = this.zoomer.getSliderPos(this.zoom); this.$zoomSlider.val(this.zoomSliderPos); this.$preview.css('background-size', '' + updatedWidth + 'px ' + updatedHeight + 'px'); if (this.options.imageBackground) { this.$imageBg.css({ width: updatedWidth, height: updatedHeight }); } this.options.onZoomChange(newZoom); } }, { key: 'fixZoom', value: function fixZoom(zoom) { return this.zoomer.fixZoom(zoom); } }, { key: 'isZoomable', value: function isZoomable() { return this.zoomer.isZoomable(); } }, { key: 'getCroppedImageData', value: function getCroppedImageData(exportOptions) { if (!this.imageSrc) { return; } var exportDefaults = { type: 'image/png', quality: 0.75, originalSize: false, fillBg: '#fff' }; exportOptions = _jquery2['default'].extend({}, exportDefaults, exportOptions); var exportZoom = exportOptions.originalSize ? 1 / this.zoom : this.options.exportZoom; var zoomedSize = { w: this.zoom * exportZoom * this.imageSize.w, h: this.zoom * exportZoom * this.imageSize.h }; var canvas = (0, _jquery2['default'])('<canvas />').attr({ width: this.previewSize.w * exportZoom, height: this.previewSize.h * exportZoom }).get(0); var canvasContext = canvas.getContext('2d'); if (exportOptions.type === 'image/jpeg') { canvasContext.fillStyle = exportOptions.fillBg; canvasContext.fillRect(0, 0, canvas.width, canvas.height); } canvasContext.drawImage(this.image, this.offset.x * exportZoom, this.offset.y * exportZoom, zoomedSize.w, zoomedSize.h); return canvas.toDataURL(exportOptions.type, exportOptions.quality); } }, { key: 'getImageState', value: function getImageState() { return { src: this.imageSrc, offset: this.offset, zoom: this.zoom }; } }, { key: 'getImageSrc', value: function getImageSrc() { return this.imageSrc; } }, { key: 'getOffset', value: function getOffset() { return this.offset; } }, { key: 'getZoom', value: function getZoom() { return this.zoom; } }, { key: 'getImageSize', value: function getImageSize() { if (!this.imageSize) { return null; } return { width: this.imageSize.w, height: this.imageSize.h }; } }, { key: 'getInitialZoom', value: function getInitialZoom() { return this.options.initialZoom; } }, { key: 'setInitialZoom', value: function setInitialZoom(initialZoomOption) { this.options.initialZoom = initialZoomOption; if (initialZoomOption === 'min') { this.initialZoom = 0; // Will be fixed when image loads } else if (initialZoomOption === 'image') { this.initialZoom = 1; } else { this.initialZoom = 0; } } }, { key: 'getExportZoom', value: function getExportZoom() { return this.options.exportZoom; } }, { key: 'setExportZoom', value: function setExportZoom(exportZoom) { this.options.exportZoom = exportZoom; this.setupZoomer(); } }, { key: 'getMinZoom', value: function getMinZoom() { return this.options.minZoom; } }, { key: 'setMinZoom', value: function setMinZoom(minZoom) { this.options.minZoom = minZoom; this.setupZoomer(); } }, { key: 'getMaxZoom', value: function getMaxZoom() { return this.options.maxZoom; } }, { key: 'setMaxZoom', value: function setMaxZoom(maxZoom) { this.options.maxZoom = maxZoom; this.setupZoomer(); } }, { key: 'getPreviewSize', value: function getPreviewSize() { return { width: this.previewSize.w, height: this.previewSize.h }; } }, { key: 'setPreviewSize', value: function setPreviewSize(size) { if (!size || size.width <= 0 || size.height <= 0) { return; } this.previewSize = { w: size.width, h: size.height }; this.$preview.css({ width: this.previewSize.w, height: this.previewSize.h }); if (this.options.imageBackground) { this.$imageBgContainer.css({ width: this.previewSize.w + this.imageBgBorderWidthArray[1] + this.imageBgBorderWidthArray[3], height: this.previewSize.h + this.imageBgBorderWidthArray[0] + this.imageBgBorderWidthArray[2] }); } if (this.imageLoaded) { this.setupZoomer(); } } }, { key: 'disable', value: function disable() { this.unbindListeners(); this.disableZoomSlider(); this.$el.addClass(_constants.CLASS_NAMES.DISABLED); } }, { key: 'reenable', value: function reenable() { this.bindListeners(); this.enableZoomSlider(); this.$el.removeClass(_constants.CLASS_NAMES.DISABLED); } }, { key: '$', value: function $(selector) { if (!this.$el) { return null; } return this.$el.find(selector); } }]); return Cropit; })(); exports['default'] = Cropit; module.exports = exports['default']; /***/ }, /* 3 */ /***/ function (module, exports) { Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var Zoomer = (function () { function Zoomer() { _classCallCheck(this, Zoomer); this.minZoom = this.maxZoom = 1; } _createClass(Zoomer, [{ key: 'setup', value: function setup(_ref) { var imageSize = _ref.imageSize; var previewSize = _ref.previewSize; var exportZoom = _ref.exportZoom; var maxZoom = _ref.maxZoom; var minZoom = _ref.minZoom; var smallImage = _ref.smallImage; var widthRatio = previewSize.w / imageSize.w; var heightRatio = previewSize.h / imageSize.h; if (minZoom === 'fit') { this.minZoom = Math.min(widthRatio, heightRatio); } else { this.minZoom = Math.max(widthRatio, heightRatio); } if (smallImage === 'allow') { this.minZoom = Math.min(this.minZoom, 1); } this.maxZoom = Math.max(this.minZoom, maxZoom / exportZoom); } }, { key: 'getZoom', value: function getZoom(sliderPos) { if (!this.minZoom || !this.maxZoom) { return null; } return sliderPos * (this.maxZoom - this.minZoom) + this.minZoom; } }, { key: 'getSliderPos', value: function getSliderPos(zoom) { if (!this.minZoom || !this.maxZoom) { return null; } if (this.minZoom === this.maxZoom) { return 0; } else { return (zoom - this.minZoom) / (this.maxZoom - this.minZoom); } } }, { key: 'isZoomable', value: function isZoomable() { if (!this.minZoom || !this.maxZoom) { return null; } return this.minZoom !== this.maxZoom; } }, { key: 'fixZoom', value: function fixZoom(zoom) { return Math.max(this.minZoom, Math.min(this.maxZoom, zoom)); } }]); return Zoomer; })(); exports['default'] = Zoomer; module.exports = exports['default']; /***/ }, /* 4 */ /***/ function (module, exports) { Object.defineProperty(exports, '__esModule', { value: true }); var PLUGIN_KEY = 'cropit'; exports.PLUGIN_KEY = PLUGIN_KEY; var CLASS_NAMES = { PREVIEW: 'cropit-image-preview', PREVIEW_CONTAINER: 'cropit-image-preview-container', FILE_INPUT: 'cropit-image-input', ZOOM_SLIDER: 'cropit-image-zoom-input', IMAGE_BACKGROUND: 'cropit-image-background', IMAGE_BACKGROUND_CONTAINER: 'cropit-image-background-container', PREVIEW_HOVERED: 'cropit-preview-hovered', DRAG_HOVERED: 'cropit-drag-hovered', IMAGE_LOADING: 'cropit-image-loading', IMAGE_LOADED: 'cropit-image-loaded', DISABLED: 'cropit-disabled' }; exports.CLASS_NAMES = CLASS_NAMES; var ERRORS = { IMAGE_FAILED_TO_LOAD: {code: 0, message: 'Image failed to load.'}, SMALL_IMAGE: {code: 1, message: 'Image is too small.'} }; exports.ERRORS = ERRORS; var eventName = function eventName(events) { return events.map(function (e) { return '' + e + '.cropit'; }).join(' '); }; var EVENTS = { PREVIEW: eventName(['mousedown', 'mouseup', 'mouseleave', 'touchstart', 'touchend', 'touchcancel', 'touchleave']), PREVIEW_MOVE: eventName(['mousemove', 'touchmove']), ZOOM_INPUT: eventName(['mousemove', 'touchmove', 'change']) }; exports.EVENTS = EVENTS; /***/ }, /* 5 */ /***/ function (module, exports, __webpack_require__) { Object.defineProperty(exports, '__esModule', { value: true }); var _constants = __webpack_require__(4); var options = { elements: [{ name: '$preview', description: 'The HTML element that displays image preview.', defaultSelector: '.' + _constants.CLASS_NAMES.PREVIEW }, { name: '$fileInput', description: 'File input element.', defaultSelector: 'input.' + _constants.CLASS_NAMES.FILE_INPUT }, { name: '$zoomSlider', description: 'Range input element that controls image zoom.', defaultSelector: 'input.' + _constants.CLASS_NAMES.ZOOM_SLIDER }, { name: '$previewContainer', description: 'Preview container. Only needed when `imageBackground` is true.', defaultSelector: '.' + _constants.CLASS_NAMES.PREVIEW_CONTAINER }].map(function (o) { o.type = 'jQuery element'; o['default'] = '$imageCropper.find(\'' + o.defaultSelector + '\')'; return o; }), values: [{ name: 'width', type: 'number', description: 'Width of image preview in pixels. If set, it will override the CSS property.', 'default': null }, { name: 'height', type: 'number', description: 'Height of image preview in pixels. If set, it will override the CSS property.', 'default': null }, { name: 'imageBackground', type: 'boolean', description: 'Whether or not to display the background image beyond the preview area.', 'default': false }, { name: 'imageBackgroundBorderWidth', type: 'array or number', description: 'Width of background image border in pixels.\n The four array elements specify the width of background image width on the top, right, bottom, left side respectively.\n The background image beyond the width will be hidden.\n If specified as a number, border with uniform width on all sides will be applied.', 'default': [0, 0, 0, 0] }, { name: 'exportZoom', type: 'number', description: 'The ratio between the desired image size to export and the preview size.\n For example, if the preview size is `300px * 200px`, and `exportZoom = 2`, then\n the exported image size will be `600px * 400px`.\n This also affects the maximum zoom level, since the exported image cannot be zoomed to larger than its original size.', 'default': 1 }, { name: 'allowDragNDrop', type: 'boolean', description: 'When set to true, you can load an image by dragging it from local file browser onto the preview area.', 'default': true }, { name: 'minZoom', type: 'string', description: 'This options decides the minimal zoom level of the image.\n If set to `\'fill\'`, the image has to fill the preview area, i.e. both width and height must not go smaller than the preview area.\n If set to `\'fit\'`, the image can shrink further to fit the preview area, i.e. at least one of its edges must not go smaller than the preview area.', 'default': 'fill' }, { name: 'maxZoom', type: 'number', description: 'Determines how big the image can be zoomed. E.g. if set to 1.5, the image can be zoomed to 150% of its original size.', 'default': 1 }, { name: 'initialZoom', type: 'string', description: 'Determines the zoom when an image is loaded.\n When set to `\'min\'`, image is zoomed to the smallest when loaded.\n When set to `\'image\'`, image is zoomed to 100% when loaded.', 'default': 'min' }, { name: 'freeMove', type: 'boolean', description: 'When set to true, you can freely move the image instead of being bound to the container borders', 'default': false }, { name: 'smallImage', type: 'string', description: 'When set to `\'reject\'`, `onImageError` would be called when cropit loads an image that is smaller than the container.\n When set to `\'allow\'`, images smaller than the container can be zoomed down to its original size, overiding `minZoom` option.\n When set to `\'stretch\'`, the minimum zoom of small images would follow `minZoom` option.', 'default': 'reject' }, { name: 'allowCrossOrigin', type: 'boolean', description: 'Set to true if you need to crop image served from other domains.', 'default': false }], callbacks: [{ name: 'onFileChange', description: 'Called when user selects a file in the select file input.', params: [{ name: 'event', type: 'object', description: 'File change event object' }] }, { name: 'onFileReaderError', description: 'Called when `FileReader` encounters an error while loading the image file.' }, { name: 'onImageLoading', description: 'Called when image starts to be loaded.' }, { name: 'onImageLoaded', description: 'Called when image is loaded.' }, { name: 'onImageError', description: 'Called when image cannot be loaded.', params: [{ name: 'error', type: 'object', description: 'Error object.' }, { name: 'error.code', type: 'number', description: 'Error code. `0` means generic image loading failure. `1` means image is too small.' }, { name: 'error.message', type: 'string', description: 'A message explaining the error.' }] }, { name: 'onZoomEnabled', description: 'Called when image the zoom slider is enabled.' }, { name: 'onZoomDisabled', description: 'Called when image the zoom slider is disabled.' }, { name: 'onZoomChange', description: 'Called when zoom changes.', params: [{ name: 'zoom', type: 'number', description: 'New zoom.' }] }, { name: 'onOffsetChange', description: 'Called when image offset changes.', params: [{ name: 'offset', type: 'object', description: 'New offset, with `x` and `y` values.' }] }].map(function (o) { o.type = 'function'; return o; }) }; var loadDefaults = function loadDefaults($el) { var defaults = {}; if ($el) { options.elements.forEach(function (o) { defaults[o.name] = $el.find(o.defaultSelector); }); } options.values.forEach(function (o) { defaults[o.name] = o['default']; }); options.callbacks.forEach(function (o) { defaults[o.name] = function () { }; }); return defaults; }; exports.loadDefaults = loadDefaults; exports['default'] = options; /***/ }, /* 6 */ /***/ function (module, exports) { Object.defineProperty(exports, '__esModule', { value: true }); var exists = function exists(v) { return typeof v !== 'undefined'; }; exports.exists = exists; var round = function round(x) { return +(Math.round(x * 100) + 'e-2'); }; exports.round = round; var capitalize = function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1); }; exports.capitalize = capitalize; /***/ } /******/]) }); ;
Junaid-Farid/staylance-new
frontend/web/js/jquery.cropit.js
JavaScript
bsd-3-clause
72,151
jsonp({"fullName":'Deferrable.prototype.then',"source":'Deferrable.js',"sourceFile":'data/source/Deferrable.js.html#Deferrable-prototype-then',"summary":'<p>\u5b9a\u4e49\u5f53\u524d\u4efb\u52a1\u6267\u884c\u5b8c\u6210\u540e\u7684\u56de\u8c03\u51fd\u6570\u3002</p>\n',"params":[{"type":'Deferrable',"name":'callback',"summary":'<p>\u9700\u8981\u7b49\u5f85\u6267\u884c\u7684\u56de\u8c03\u51fd\u6570\u3002</p>\n'},{"type":'Object',"name":'args',"summary":'<p>\u6267\u884c <em>callback</em> \u65f6\u4f7f\u7528\u7684\u53c2\u6570\u3002</p>\n'}],"name":'then',"memberOf":'Deferrable',"memberType":'method'});
jplusui/jplusui.github.com
resources/cookbooks/jplusui-full-api/data/api/Deferrable.prototype.then.js
JavaScript
bsd-3-clause
604
/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <fstream> #include <iterator> #include <exception> #include "libtorrent/config.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/exception.hpp> #include <boost/bind.hpp> #include <boost/program_options.hpp> #include <boost/regex.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/extensions/metadata_transfer.hpp" #include "libtorrent/extensions/ut_metadata.hpp" #include "libtorrent/extensions/ut_pex.hpp" #include "libtorrent/extensions/smart_ban.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/session.hpp" #include "libtorrent/identify_client.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/ip_filter.hpp" #include "libtorrent/magnet_uri.hpp" #include "libtorrent/bitfield.hpp" #include "libtorrent/file.hpp" using boost::bind; #ifdef _WIN32 #if defined(_MSC_VER) # define for if (false) {} else for #endif #include <windows.h> #include <conio.h> bool sleep_and_input(char* c) { Sleep(500); if (_kbhit()) { *c = _getch(); return true; } return false; }; void clear_home() { CONSOLE_SCREEN_BUFFER_INFO si; HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(h, &si); COORD c = {0, 0}; DWORD n; FillConsoleOutputCharacter(h, ' ', si.dwSize.X * si.dwSize.Y, c, &n); SetConsoleCursorPosition(h, c); } #else #include <stdlib.h> #include <stdio.h> #include <termios.h> #include <string.h> #include <sys/ioctl.h> #define ANSI_TERMINAL_COLORS struct set_keypress { set_keypress() { termios new_settings; tcgetattr(0,&stored_settings); new_settings = stored_settings; // Disable canonical mode, and set buffer size to 1 byte new_settings.c_lflag &= (~ICANON); new_settings.c_cc[VTIME] = 0; new_settings.c_cc[VMIN] = 1; tcsetattr(0,TCSANOW,&new_settings); } ~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); } termios stored_settings; }; bool sleep_and_input(char* c) { // sets the terminal to single-character mode // and resets when destructed set_keypress s; fd_set set; FD_ZERO(&set); FD_SET(0, &set); timeval tv = {0, 500000}; if (select(1, &set, 0, 0, &tv) > 0) { *c = getc(stdin); return true; } return false; } void clear_home() { std::cout << "\033[2J\033[0;0H"; } #endif bool print_peers = false; bool print_log = false; bool print_downloads = false; bool print_piece_bar = false; bool print_file_progress = false; bool sequential_download = false; bool print_ip = true; bool print_as = false; bool print_timers = false; bool print_block = false; bool print_peer_rate = false; bool print_fails = false; bool print_send_bufs = true; std::ofstream g_log_file; int active_torrent = 0; char const* esc(char const* code) { #ifdef ANSI_TERMINAL_COLORS // this is a silly optimization // to avoid copying of strings enum { num_strings = 200 }; static char buf[num_strings][20]; static int round_robin = 0; char* ret = buf[round_robin]; ++round_robin; if (round_robin >= num_strings) round_robin = 0; ret[0] = '\033'; ret[1] = '['; int i = 2; int j = 0; while (code[j]) ret[i++] = code[j++]; ret[i++] = 'm'; ret[i++] = 0; return ret; #else return ""; #endif } std::string to_string(int v, int width) { std::stringstream s; s.flags(std::ios_base::right); s.width(width); s.fill(' '); s << v; return s.str(); } std::string& to_string(float v, int width, int precision = 3) { // this is a silly optimization // to avoid copying of strings enum { num_strings = 20 }; static std::string buf[num_strings]; static int round_robin = 0; std::string& ret = buf[round_robin]; ++round_robin; if (round_robin >= num_strings) round_robin = 0; ret.resize(20); int size = std::sprintf(&ret[0], "%*.*f", width, precision, v); ret.resize((std::min)(size, width)); return ret; } std::string const& add_suffix(float val) { const char* prefix[] = {"kB", "MB", "GB", "TB"}; const int num_prefix = sizeof(prefix) / sizeof(const char*); for (int i = 0; i < num_prefix; ++i) { val /= 1000.f; if (fabs(val) < 1000.f) { std::string& ret = to_string(val, 4); ret += prefix[i]; return ret; } } std::string& ret = to_string(val, 4); ret += "PB"; return ret; } std::string const& piece_bar(libtorrent::bitfield const& p, int width) { #ifdef ANSI_TERMINAL_COLORS static const char* lookup[] = { // black, blue, cyan, white "40", "44", "46", "47" }; const int table_size = sizeof(lookup) / sizeof(lookup[0]); #else static const char char_lookup[] = { ' ', '.', ':', '-', '+', '*', '#'}; const int table_size = sizeof(char_lookup) / sizeof(char_lookup[0]); #endif double piece_per_char = p.size() / double(width); static std::string bar; bar.clear(); bar.reserve(width * 6); bar += "["; // the [piece, piece + pieces_per_char) range is the pieces that are represented by each character double piece = 0; for (int i = 0; i < width; ++i, piece += piece_per_char) { int num_pieces = 0; int num_have = 0; int end = (std::max)(int(piece + piece_per_char), int(piece) + 1); for (int k = int(piece); k < end; ++k, ++num_pieces) if (p[k]) ++num_have; int color = int(std::ceil(num_have / float(num_pieces) * (table_size - 1))); #ifdef ANSI_TERMINAL_COLORS bar += esc(lookup[color]); bar += " "; #else bar += char_lookup[color]; #endif } #ifdef ANSI_TERMINAL_COLORS bar += esc("0"); #endif bar += "]"; return bar; } std::string const& progress_bar(float progress, int width, char const* code = "33") { static std::string bar; bar.clear(); bar.reserve(width + 10); int progress_chars = static_cast<int>(progress * width + .5f); bar = esc(code); std::fill_n(std::back_inserter(bar), progress_chars, '#'); bar += esc("0"); std::fill_n(std::back_inserter(bar), width - progress_chars, '-'); return bar; } int peer_index(libtorrent::tcp::endpoint addr, std::vector<libtorrent::peer_info> const& peers) { using namespace libtorrent; std::vector<peer_info>::const_iterator i = std::find_if(peers.begin() , peers.end(), bind(&peer_info::ip, _1) == addr); if (i == peers.end()) return -1; return i - peers.begin(); } void print_peer_info(std::ostream& out, std::vector<libtorrent::peer_info> const& peers) { using namespace libtorrent; if (print_ip) out << "IP "; #ifndef TORRENT_DISABLE_GEO_IP if (print_as) out << "AS "; #endif out << "down (total | peak ) up (total | peak ) sent-req recv flags source "; if (print_fails) out << "fail hshf "; if (print_send_bufs) out << "rq sndb quota rcvb "; if (print_timers) out << "inactive wait timeout "; out << "disk rtt "; if (print_block) out << "block-progress "; #ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES out << "country "; #endif if (print_peer_rate) out << "peer-rate "; out << "client \n"; for (std::vector<peer_info>::const_iterator i = peers.begin(); i != peers.end(); ++i) { if (i->flags & (peer_info::handshake)) continue; out.fill(' '); if (print_ip) { std::stringstream ip; ip << i->ip.address().to_string() << ":" << i->ip.port(); out.width(22); out << ip.str() << " "; } #ifndef TORRENT_DISABLE_GEO_IP if (print_as) { std::string as_name = i->inet_as_name; if (as_name.size() > 42) as_name.resize(42); out.width(42); out << as_name << " "; } #endif out.width(2); out << esc("32") << (i->down_speed > 0 ? add_suffix(i->down_speed) + "/s " : " ") << "(" << (i->total_download > 0 ? add_suffix(i->total_download) : " ") << "|" << (i->download_rate_peak > 0 ? add_suffix(i->download_rate_peak) + "/s" : " ") << ") " << esc("0") << esc("31") << (i->up_speed > 0 ? add_suffix(i->up_speed) + "/s ": " ") << "(" << (i->total_upload > 0 ? add_suffix(i->total_upload) : " ") << "|" << (i->upload_rate_peak > 0 ? add_suffix(i->upload_rate_peak) + "/s" : " ") << ") " << esc("0") << to_string(i->download_queue_length, 3) << " (" << to_string(i->target_dl_queue_length, 3) << ") " << to_string(i->upload_queue_length, 3) << " " << ((i->flags & peer_info::interesting)?'I':'.') << ((i->flags & peer_info::choked)?'C':'.') << ((i->flags & peer_info::remote_interested)?'i':'.') << ((i->flags & peer_info::remote_choked)?'c':'.') << ((i->flags & peer_info::supports_extensions)?'e':'.') << ((i->flags & peer_info::local_connection)?'l':'r') << ((i->flags & peer_info::seed)?'s':'.') << ((i->flags & peer_info::on_parole)?'p':'.') << ((i->flags & peer_info::optimistic_unchoke)?'O':'.') << ((i->read_state == peer_info::bw_torrent)?'t': (i->read_state == peer_info::bw_global)?'r': (i->read_state == peer_info::bw_network)?'R':'.') << ((i->write_state == peer_info::bw_torrent)?'t': (i->write_state == peer_info::bw_global)?'w': (i->write_state == peer_info::bw_network)?'W':'.') << ((i->flags & peer_info::snubbed)?'S':'.') << ((i->flags & peer_info::upload_only)?'U':'D') #ifndef TORRENT_DISABLE_ENCRYPTION << ((i->flags & peer_info::rc4_encrypted)?'E': (i->flags & peer_info::plaintext_encrypted)?'e':'.') #else << ".." #endif << " " << ((i->source & peer_info::tracker)?"T":"_") << ((i->source & peer_info::pex)?"P":"_") << ((i->source & peer_info::dht)?"D":"_") << ((i->source & peer_info::lsd)?"L":"_") << ((i->source & peer_info::resume_data)?"R":"_") << " "; if (print_fails) { out << to_string(i->failcount, 3) << " " << to_string(i->num_hashfails, 3) << " "; } if (print_send_bufs) { out << to_string(i->requests_in_buffer, 2) << " " << to_string(i->used_send_buffer, 6) << " ("<< add_suffix(i->send_buffer_size) << ") " << to_string(i->send_quota, 5) << " " << to_string(i->used_receive_buffer, 6) << " ("<< add_suffix(i->receive_buffer_size) << ") "; } if (print_timers) { out << to_string(total_seconds(i->last_active), 8) << " " << to_string(total_seconds(i->last_request), 4) << " " << to_string(i->request_timeout, 7) << " "; } out << add_suffix(i->pending_disk_bytes) << " " << to_string(i->rtt, 4) << " "; if (print_block) { if (i->downloading_piece_index >= 0) { out << progress_bar( i->downloading_progress / float(i->downloading_total), 14); } else { out << progress_bar(0.f, 14); } } #ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES if (i->country[0] == 0) { out << " .."; } else { out << " " << i->country[0] << i->country[1]; } #endif if (print_peer_rate) out << " " << (i->remote_dl_rate > 0 ? add_suffix(i->remote_dl_rate) + "/s ": " "); out << " "; if (i->flags & peer_info::handshake) { out << esc("31") << " waiting for handshake" << esc("0") << "\n"; } else if (i->flags & peer_info::connecting) { out << esc("31") << " connecting to peer" << esc("0") << "\n"; } else if (i->flags & peer_info::queued) { out << esc("33") << " queued" << esc("0") << "\n"; } else { out << " " << i->client << "\n"; } } } typedef std::multimap<std::string, libtorrent::torrent_handle> handles_t; using boost::bind; using boost::filesystem::path; using boost::filesystem::exists; using boost::filesystem::directory_iterator; using boost::filesystem::extension; // monitored_dir is true if this torrent is added because // it was found in the directory that is monitored. If it // is, it should be remembered so that it can be removed // if it's no longer in that directory. void add_torrent(libtorrent::session& ses , handles_t& handles , std::string const& torrent , float preferred_ratio , bool compact_mode , path const& save_path , bool monitored_dir , int torrent_upload_limit , int torrent_download_limit) { using namespace libtorrent; boost::intrusive_ptr<torrent_info> t(new torrent_info(torrent.c_str())); std::cout << t->name() << "\n"; add_torrent_params p; lazy_entry resume_data; std::string filename = (save_path / (t->name() + ".fastresume")).string(); std::vector<char> buf; if (load_file(filename.c_str(), buf) == 0) p.resume_data = &buf; p.ti = t; p.save_path = save_path; p.storage_mode = compact_mode ? storage_mode_compact : storage_mode_sparse; p.paused = true; p.duplicate_is_error = false; p.auto_managed = true; torrent_handle h = ses.add_torrent(p); handles.insert(std::make_pair( monitored_dir?std::string(torrent):std::string(), h)); h.set_max_connections(50); h.set_max_uploads(-1); h.set_ratio(preferred_ratio); h.set_upload_limit(torrent_upload_limit); h.set_download_limit(torrent_download_limit); #ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES h.resolve_countries(true); #endif } void scan_dir(path const& dir_path , libtorrent::session& ses , handles_t& handles , float preferred_ratio , bool compact_mode , path const& save_path , int torrent_upload_limit , int torrent_download_limit) { std::set<std::string> valid; using namespace libtorrent; for (directory_iterator i(dir_path), end; i != end; ++i) { if (extension(*i) != ".torrent") continue; std::string file = i->string(); handles_t::iterator k = handles.find(file); if (k != handles.end()) { valid.insert(file); continue; } // the file has been added to the dir, start // downloading it. add_torrent(ses, handles, file, preferred_ratio, compact_mode , save_path, true, torrent_upload_limit, torrent_download_limit); valid.insert(file); } // remove the torrents that are no longer in the directory for (handles_t::iterator i = handles.begin(); !handles.empty() && i != handles.end();) { if (i->first.empty() || valid.find(i->first) != valid.end()) { ++i; continue; } torrent_handle& h = i->second; if (!h.is_valid()) { handles.erase(i++); continue; } h.auto_managed(false); h.pause(); // the alert handler for save_resume_data_alert // will save it to disk and remove the torrent h.save_resume_data(); handles.erase(i++); } } libtorrent::torrent_handle get_active_torrent(handles_t const& handles) { if (active_torrent >= handles.size() || active_torrent < 0) return libtorrent::torrent_handle(); handles_t::const_iterator i = handles.begin(); std::advance(i, active_torrent); return i->second; } void print_alert(libtorrent::alert const* a, std::ostream& os) { using namespace libtorrent; #ifdef ANSI_TERMINAL_COLORS if (a->category() & alert::error_notification) { os << esc("31"); } else if (a->category() & (alert::peer_notification | alert::storage_notification)) { os << esc("33"); } #endif os << "[" << time_now_string() << "] " << a->message(); #ifdef ANSI_TERMINAL_COLORS os << esc("0"); #endif if (g_log_file.good()) g_log_file << "[" << time_now_string() << "] " << a->message() << std::endl; } void handle_alert(libtorrent::session& ses, libtorrent::alert* a) { using namespace libtorrent; if (torrent_finished_alert* p = dynamic_cast<torrent_finished_alert*>(a)) { p->handle.set_max_connections(30); // write resume data for the finished torrent torrent_handle h = p->handle; h.save_resume_data(); } else if (save_resume_data_alert* p = dynamic_cast<save_resume_data_alert*>(a)) { torrent_handle h = p->handle; TORRENT_ASSERT(p->resume_data); if (p->resume_data) { boost::filesystem::ofstream out(h.save_path() / (h.name() + ".fastresume") , std::ios_base::binary); out.unsetf(std::ios_base::skipws); bencode(std::ostream_iterator<char>(out), *p->resume_data); if (h.is_paused() && !h.is_auto_managed()) ses.remove_torrent(h); } } } static char const* state_str[] = {"checking (q)", "checking", "dl metadata" , "downloading", "finished", "seeding", "allocating"}; int main(int ac, char* av[]) { #if BOOST_VERSION < 103400 using boost::filesystem::no_check; path::default_name_check(no_check); #endif int listen_port; float preferred_ratio; int download_limit; int upload_limit; int torrent_upload_limit; int torrent_download_limit; int upload_slots_limit; int half_open_limit; std::string save_path_str; std::string log_level; std::string log_file_name; std::string ip_filter_file; std::string allocation_mode; std::string in_monitor_dir; std::string bind_to_interface; std::string proxy; std::string proxy_login; std::string proxy_type; int poll_interval; int wait_retry; int bind_port_start = 0; int bind_port_end = 0; namespace po = boost::program_options; try { po::options_description desc("supported options"); desc.add_options() ("help,h", "display this help message") ("port,p", po::value<int>(&listen_port)->default_value(6881) , "set listening port") ("ratio,r", po::value<float>(&preferred_ratio)->default_value(0) , "set the preferred upload/download ratio. 0 means infinite. Values " "smaller than 1 are clamped to 1.") ("max-download-rate,d", po::value<int>(&download_limit)->default_value(0) , "the maximum download rate given in kB/s. 0 means infinite.") ("max-upload-rate,u", po::value<int>(&upload_limit)->default_value(0) , "the maximum upload rate given in kB/s. 0 means infinite.") ("max-torrent-upload-rate", po::value<int>(&torrent_upload_limit)->default_value(20) , "the maximum upload rate for an individual torrent, given in kB/s. 0 means infinite.") ("max-torrent-download-rate", po::value<int>(&torrent_download_limit)->default_value(0) , "the maximum download rate for an individual torrent, given in kB/s. 0 means infinite.") ("max-upload-slots", po::value<int>(&upload_slots_limit)->default_value(5) , "the maximum number of upload slots. 0 means infinite.") ("save-path,s", po::value<std::string>(&save_path_str)->default_value("./") , "the path where the downloaded file/folder should be placed.") ("log-level,l", po::value<std::string>(&log_level)->default_value("info") , "sets the level at which events are logged [debug | info | warning | fatal].") ("log-file,f", po::value<std::string>(&log_file_name)->default_value("") , "sets a file to log all events to") ("ip-filter,f", po::value<std::string>(&ip_filter_file)->default_value("") , "sets the path to the ip-filter file used to block access from certain " "ips. ") ("allocation-mode,a", po::value<std::string>(&allocation_mode)->default_value("full") , "sets mode used for allocating the downloaded files on disk. " "Possible options are [full | compact]") ("input-file,i", po::value<std::vector<std::string> >() , "adds an input .torrent file. At least one is required. arguments " "without any flag are implicitly an input file. To start a torrentless " "download, use <info-hash>@<tracker-url> instead of specifying a file.") ("monitor-dir,m", po::value<std::string>(&in_monitor_dir) , "monitors the given directory, looking for .torrent files and " "automatically starts downloading them. It will stop downloading " "torrent files that are removed from the directory") ("poll-interval,t", po::value<int>(&poll_interval)->default_value(2) , "if a directory is being monitored, this is the interval (given " "in seconds) between two refreshes of the directory listing") ("wait-retry,w", po::value<int>(&wait_retry)->default_value(30) , "if the download of a url seed failes, this is the interval (given " "in seconds) to wait until the next retry") ("half-open-limit,o", po::value<int>(&half_open_limit)->default_value(-1) , "Sets the maximum number of simultaneous half-open tcp connections") ("bind,b", po::value<std::string>(&bind_to_interface)->default_value("") , "Sets the local interface to bind outbound and the listen " "socket to") ("proxy-server,x", po::value<std::string>(&proxy)->default_value("") , "Sets the http proxy to be used for tracker and web seeds " "connections. The string is expected to be on the form: " "<hostname>:<port>. If no port is specified, 8080 is assumed") ("proxy-login,n", po::value<std::string>(&proxy_login)->default_value("") , "Sets the username and password used to authenticate with the http " "proxy. The string should be given in the form: <username>:<password>") ("proxy-type", po::value<std::string>(&proxy_type)->default_value("socks5") , "Sets the type of proxy to use [socks5 | http] ") ("bind-port-start", po::value<int>(&bind_port_start)->default_value(0) , "The lower port number that outgoing connections will be bound to") ("bind-port-end", po::value<int>(&bind_port_end)->default_value(0) , "The upper port number that outgoing connections will be bound to") ; po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store(po::command_line_parser(ac, av). options(desc).positional(p).run(), vm); po::notify(vm); // make sure the arguments stays within the usable limits path monitor_dir(in_monitor_dir); if (listen_port < 0 || listen_port > 65525) listen_port = 6881; if (preferred_ratio != 0 && preferred_ratio < 1.f) preferred_ratio = 1.f; upload_limit *= 1000; torrent_upload_limit *= 1000; torrent_download_limit *= 1000; download_limit *= 1000; if (download_limit <= 0) download_limit = -1; if (upload_limit <= 0) upload_limit = -1; if (torrent_upload_limit <= 0) torrent_upload_limit = -1; if (torrent_download_limit <= 0) torrent_download_limit = -1; if (poll_interval < 2) poll_interval = 2; if (wait_retry < 0) wait_retry = 0; if (half_open_limit < 1) half_open_limit = -1; if (upload_slots_limit <= 0) upload_slots_limit = -1; if (!monitor_dir.empty() && !exists(monitor_dir)) { std::cerr << "The monitor directory doesn't exist: " << monitor_dir.string() << std::endl; return 1; } if (vm.count("help") || vm.count("input-file") + vm.count("monitor-dir") == 0) { std::cout << desc << "\n"; return 1; } if (!log_file_name.empty()) g_log_file.open(log_file_name.c_str()); bool compact_allocation_mode = (allocation_mode == "compact"); using namespace libtorrent; std::vector<std::string> input; if (vm.count("input-file") > 0) input = vm["input-file"].as< std::vector<std::string> >(); session_settings settings; proxy_settings ps; if (!proxy.empty()) { std::size_t i = proxy.find(':'); ps.hostname = proxy.substr(0, i); if (i == std::string::npos) ps.port = 8080; else ps.port = atoi(proxy.substr(i + 1).c_str()); if (proxy_type == "socks5") ps.type = proxy_settings::socks5; else ps.type = proxy_settings::http; if (!proxy_login.empty()) { std::size_t i = proxy_login.find(':'); if (i == std::string::npos) { std::cerr << "Proxy login did not match the required format: " << proxy_login << std::endl; return 1; } ps.username = proxy_login.substr(0, i); ps.password = proxy_login.substr(i + 1); if (proxy_type == "socks5") ps.type = proxy_settings::socks5_pw; else ps.type = proxy_settings::http_pw; } } settings.user_agent = "client_test/" LIBTORRENT_VERSION; settings.urlseed_wait_retry = wait_retry; settings.outgoing_ports.first = bind_port_start; settings.outgoing_ports.second = bind_port_end; std::deque<std::string> events; ptime next_dir_scan = time_now(); // the string is the filename of the .torrent file, but only if // it was added through the directory monitor. It is used to // be able to remove torrents that were added via the directory // monitor when they're not in the directory anymore. handles_t handles; session ses; #ifndef TORRENT_DISABLE_GEO_IP ses.load_asnum_db("GeoIPASNum.dat"); ses.load_country_db("GeoIP.dat"); #endif // UPnP port mapping ses.start_upnp(); // NAT-PMP port mapping ses.start_natpmp(); // Local service discovery (finds peers on the local network) ses.start_lsd(); ses.add_extension(&create_metadata_plugin); ses.add_extension(&create_ut_pex_plugin); ses.add_extension(&create_ut_metadata_plugin); ses.add_extension(&create_smart_ban_plugin); ses.set_max_uploads(upload_slots_limit); ses.set_max_half_open_connections(half_open_limit); ses.set_download_rate_limit(download_limit); ses.set_upload_rate_limit(upload_limit); ses.listen_on(std::make_pair(listen_port, listen_port + 10) , bind_to_interface.c_str()); ses.set_settings(settings); ses.set_tracker_proxy(ps); ses.set_peer_proxy(ps); ses.set_web_seed_proxy(ps); #ifndef TORRENT_NO_DEPRECATE if (log_level == "debug") ses.set_severity_level(alert::debug); else if (log_level == "warning") ses.set_severity_level(alert::warning); else if (log_level == "fatal") ses.set_severity_level(alert::fatal); else ses.set_severity_level(alert::info); #endif boost::filesystem::ifstream ses_state_file(".ses_state" , std::ios_base::binary); ses_state_file.unsetf(std::ios_base::skipws); ses.load_state(bdecode( std::istream_iterator<char>(ses_state_file) , std::istream_iterator<char>())); #ifndef TORRENT_DISABLE_DHT settings.use_dht_as_fallback = false; boost::filesystem::ifstream dht_state_file(".dht_state" , std::ios_base::binary); dht_state_file.unsetf(std::ios_base::skipws); entry dht_state; dht_state = bdecode( std::istream_iterator<char>(dht_state_file) , std::istream_iterator<char>()); ses.start_dht(dht_state); ses.add_dht_router(std::make_pair(std::string("router.bittorrent.com") , 6881)); ses.add_dht_router(std::make_pair(std::string("router.utorrent.com") , 6881)); ses.add_dht_router(std::make_pair(std::string("router.bitcomet.com") , 6881)); #endif // look for ipfilter.dat // poor man's parser // reads emule ipfilter files. // with the following format: // // <first-ip> - <last-ip> , <access> , <comment> // // first-ip is an ip address that defines the first // address of the range // last-ip is the last ip address in the range // access is a number specifying the access control // for this ip-range. Right now values > 127 = allowed // and numbers <= 127 = blocked // the rest of the line is ignored // // In the original spec ranges may not overlap, but // here ranges may overlap, and it is the last added // rule that has precedence for addresses that may fall // into more than one range. if (!ip_filter_file.empty()) { std::ifstream in(ip_filter_file.c_str()); ip_filter filter; while (in.good()) { char line[300]; in.getline(line, 300); int len = in.gcount(); if (len <= 0) continue; if (line[0] == '#') continue; int a, b, c, d; char dummy; std::stringstream ln(line); ln >> a >> dummy >> b >> dummy >> c >> dummy >> d >> dummy; address_v4 start((a << 24) + (b << 16) + (c << 8) + d); ln >> a >> dummy >> b >> dummy >> c >> dummy >> d >> dummy; address_v4 last((a << 24) + (b << 16) + (c << 8) + d); int flags; ln >> flags; if (flags <= 127) flags = ip_filter::blocked; else flags = 0; if (ln.fail()) break; filter.add_rule(start, last, flags); } ses.set_ip_filter(filter); } boost::filesystem::path save_path(save_path_str); // load the torrents given on the commandline boost::regex ex("([0-9A-Fa-f]{40})@(.+)"); for (std::vector<std::string>::const_iterator i = input.begin(); i != input.end(); ++i) { #ifndef BOOST_NO_EXCEPTIONS try { #endif // first see if this is a torrentless download if (i->substr(0, 7) == "magnet:") { add_torrent_params p; p.save_path = save_path; p.storage_mode = compact_allocation_mode ? storage_mode_compact : storage_mode_sparse; std::cout << "adding MANGET link: " << *i << std::endl; torrent_handle h = add_magnet_uri(ses, *i, p); handles.insert(std::make_pair(std::string(), h)); h.set_max_connections(50); h.set_max_uploads(-1); h.set_ratio(preferred_ratio); h.set_upload_limit(torrent_upload_limit); h.set_download_limit(torrent_download_limit); continue; } boost::cmatch what; if (boost::regex_match(i->c_str(), what, ex)) { sha1_hash info_hash = boost::lexical_cast<sha1_hash>(what[1]); add_torrent_params p; p.name = std::string(what[2]).c_str(); p.info_hash = info_hash; p.save_path = save_path; p.storage_mode = compact_allocation_mode ? storage_mode_compact : storage_mode_sparse; p.paused = true; p.duplicate_is_error = false; p.auto_managed = true; torrent_handle h = ses.add_torrent(p); handles.insert(std::make_pair(std::string(), h)); h.set_max_connections(50); h.set_max_uploads(-1); h.set_ratio(preferred_ratio); h.set_upload_limit(torrent_upload_limit); h.set_download_limit(torrent_download_limit); continue; } // if it's a torrent file, open it as usual add_torrent(ses, handles, i->c_str(), preferred_ratio , compact_allocation_mode, save_path, false , torrent_upload_limit, torrent_download_limit); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception& e) { std::cout << e.what() << "\n"; } #endif } // main loop std::vector<peer_info> peers; std::vector<partial_piece_info> queue; for (;;) { char c; while (sleep_and_input(&c)) { if (c == 27) { // escape code, read another character #ifdef _WIN32 c = _getch(); #else c = getc(stdin); #endif if (c != '[') break; #ifdef _WIN32 c = _getch(); #else c = getc(stdin); #endif if (c == 65) { // arrow up --active_torrent; if (active_torrent < 0) active_torrent = 0; } else if (c == 66) { // arrow down ++active_torrent; if (active_torrent >= handles.size()) active_torrent = handles.size() - 1; } } if (c == ' ') { if (ses.is_paused()) ses.resume(); else ses.pause(); } if (c == 'm') { std::cout << "saving peers for torrents" << std::endl; std::vector<peer_list_entry> peers; for (handles_t::iterator i = handles.begin(); i != handles.end(); ++i) { i->second.get_full_peer_list(peers); std::ofstream f(("peers_" + i->second.name()).c_str()); for (std::vector<peer_list_entry>::iterator k = peers.begin() , end(peers.end()); k != end; ++k) { f << k->ip.address() #ifndef TORRENT_DISABLE_GEO_IP << "\t" << ses.as_for_ip(k->ip.address()) #endif << std::endl; } } } if (c == 'q') { // keep track of the number of resume data // alerts to wait for int num_resume_data = 0; for (handles_t::iterator i = handles.begin(); i != handles.end(); ++i) { torrent_handle& h = i->second; if (!h.is_valid() || !h.has_metadata()) continue; // pause std::cout << "pausing " << h.name() << std::endl; h.pause(); // save_resume_data will generate an alert when it's done h.save_resume_data(); ++num_resume_data; } std::cout << "waiting for resume data" << std::endl; while (num_resume_data > 0) { alert const* a = ses.wait_for_alert(seconds(30)); if (a == 0) { std::cout << " aborting with " << num_resume_data << " outstanding " "torrents to save resume data for" << std::endl; break; } std::auto_ptr<alert> holder = ses.pop_alert(); ::print_alert(holder.get(), std::cout); std::cout << std::endl; save_resume_data_alert const* rd = dynamic_cast<save_resume_data_alert const*>(a); if (!rd) continue; --num_resume_data; if (!rd->resume_data) continue; torrent_handle h = rd->handle; boost::filesystem::ofstream out(h.save_path() / (h.get_torrent_info().name() + ".fastresume"), std::ios_base::binary); out.unsetf(std::ios_base::skipws); bencode(std::ostream_iterator<char>(out), *rd->resume_data); } break; } if (c == 'j') { torrent_handle h = get_active_torrent(handles); if (h.is_valid()) h.force_recheck(); } if (c == 'r') { torrent_handle h = get_active_torrent(handles); if (h.is_valid()) h.force_reannounce(); } if (c == 's') { torrent_handle h = get_active_torrent(handles); if (h.is_valid()) h.set_sequential_download(!h.is_sequential_download()); } if (c == 'p') { torrent_handle h = get_active_torrent(handles); if (h.is_valid()) { if (!h.is_auto_managed() && h.is_paused()) { h.auto_managed(true); } else { h.auto_managed(false); h.pause(); } } } if (c == 'c') { torrent_handle h = get_active_torrent(handles); if (h.is_valid()) h.clear_error(); } // toggle displays if (c == 'i') print_peers = !print_peers; if (c == 'l') print_log = !print_log; if (c == 'd') print_downloads = !print_downloads; if (c == 'f') print_file_progress = !print_file_progress; if (c == 'a') print_piece_bar = !print_piece_bar; // toggle columns if (c == '1') print_ip = !print_ip; if (c == '2') print_as = !print_as; if (c == '3') print_timers = !print_timers; if (c == '4') print_block = !print_block; if (c == '5') print_peer_rate = !print_peer_rate; if (c == '6') print_fails = !print_fails; if (c == '7') print_send_bufs = !print_send_bufs; } if (c == 'q') break; int terminal_width = 80; #ifndef _WIN32 { winsize size; ioctl(STDOUT_FILENO, TIOCGWINSZ, (char*)&size); terminal_width = size.ws_col; } #endif // loop through the alert queue to see if anything has happened. std::auto_ptr<alert> a; a = ses.pop_alert(); std::string now = time_now_string(); while (a.get()) { std::stringstream event_string; ::print_alert(a.get(), event_string); ::handle_alert(ses, a.get()); events.push_back(event_string.str()); if (events.size() >= 20) events.pop_front(); a = ses.pop_alert(); } session_status sess_stat = ses.status(); std::stringstream out; out << "[q] quit [i] toggle peers [d] toggle downloading pieces [p] toggle paused " "[a] toggle piece bar [s] toggle download sequential [f] toggle files " "[j] force recheck [space] toggle session pause [c] clear error\n" "[1] toggle IP [2] toggle AS [3] toggle timers [4] toggle block progress " "[5] toggle peer rate [6] toggle failures [7] toggle send buffers\n"; int torrent_index = 0; torrent_handle active_handle; for (handles_t::iterator i = handles.begin(); i != handles.end(); ++torrent_index) { torrent_handle& h = i->second; if (!h.is_valid()) { handles.erase(i++); continue; } else { ++i; } #ifdef ANSI_TERMINAL_COLORS char const* term = "\x1b[0m"; #else char const* term = ""; #endif if (active_torrent == torrent_index) { term = "\x1b[0m\x1b[7m"; out << esc("7") << "*"; } else { out << " "; } int queue_pos = h.queue_position(); if (queue_pos == -1) out << "- "; else out << std::setw(3) << queue_pos; if (h.is_paused()) out << esc("34"); else out << esc("37"); out << std::setw(40) << std::setiosflags(std::ios::left); std::string name = h.name(); if (name.size() > 40) name.resize(40); out << name; out << term << " "; torrent_status s = h.status(); bool paused = h.is_paused(); bool auto_managed = h.is_auto_managed(); out << std::setw(13) << std::setiosflags(std::ios::left); if (!s.error.empty()) { out << esc("31") << "error " << s.error; out << esc("0") << std::endl; continue; } if (paused && !auto_managed) out << "paused"; else if (paused && auto_managed) out << "queued"; else out << state_str[s.state]; int seeds = 0; int downloaders = 0; if (s.num_complete >= 0) seeds = s.num_complete; else seeds = s.list_seeds; if (s.num_incomplete >= 0) downloaders = s.num_incomplete; else downloaders = s.list_peers - s.list_seeds; out << "download: " << "(" << esc("32") << add_suffix(s.total_download) << term << ") " "upload: " << esc("31") << (s.upload_rate > 0 ? add_suffix(s.upload_rate) + "/s ": " ") << term << "(" << esc("31") << add_suffix(s.total_upload) << term << ") " << "swarm: " << to_string(downloaders, 4) << ":" << to_string(seeds, 4) << " bw queue: (" << s.up_bandwidth_queue << " | " << s.down_bandwidth_queue << ") " "all-time (Rx: " << esc("32") << add_suffix(s.all_time_download) << term << " Tx: " << esc("31") << add_suffix(s.all_time_upload) << term << ") " << std::hex << s.seed_rank << std::dec << " " << s.last_scrape << "\n" << esc("0"); if (s.state != torrent_status::seeding) { char const* progress_bar_color = "33"; // yellow if (s.state == torrent_status::checking_files || s.state == torrent_status::downloading_metadata) { progress_bar_color = "35"; // magenta } else if (s.current_tracker.empty()) { progress_bar_color = "31"; // red } else if (sess_stat.has_incoming_connections) { progress_bar_color = "32"; // green } out << " progress: " << esc("32") << s.total_done << esc("0") << " Bytes "; out.precision(4); out.width(5); out.fill(' '); out << (s.progress*100) << "% "; out << progress_bar(s.progress, terminal_width - 37, progress_bar_color) << "\n"; if (print_piece_bar && s.progress < 1.f) out << " " << piece_bar(s.pieces, terminal_width - 5) << "\n"; out << " peers: " << esc("37") << s.num_peers << esc("0") << " (" << esc("37") << s.connect_candidates << esc("0") << ") " << "seeds: " << esc("37") << s.num_seeds << esc("0") << " " << "distributed copies: " << esc("37") << s.distributed_copies << esc("0") // << " magnet-link: " << make_magnet_uri(h) << "\n" << " download: " << esc("32") << (s.download_rate > 0 ? add_suffix(s.download_rate) + "/s ": " ") << esc("0"); boost::posix_time::time_duration t = s.next_announce; out << " next announce: " << esc("37") << to_string(t.hours(), 2) << ":" << to_string(t.minutes(), 2) << ":" << to_string(t.seconds(), 2) << esc("0") << " "; out << "tracker: " << esc("36") << s.current_tracker << esc("0") << "\n"; } if (torrent_index != active_torrent) continue; active_handle = h; } cache_status cs = ses.get_cache_status(); if (cs.blocks_read < 1) cs.blocks_read = 1; if (cs.blocks_written < 1) cs.blocks_written = 1; out << "==== conns: " << sess_stat.num_peers << " down: " << esc("32") << add_suffix(sess_stat.download_rate) << "/s" << esc("0") << " (" << esc("32") << add_suffix(sess_stat.total_download) << esc("0") << ") " " up: " << esc("31") << add_suffix(sess_stat.upload_rate) << "/s " << esc("0") << " (" << esc("31") << add_suffix(sess_stat.total_upload) << esc("0") << ")" " waste: " << add_suffix(sess_stat.total_redundant_bytes) << " fail: " << add_suffix(sess_stat.total_failed_bytes) << " unchoked: " << sess_stat.num_unchoked << " / " << sess_stat.allowed_upload_slots << " bw queues: (" << sess_stat.up_bandwidth_queue << " | " << sess_stat.down_bandwidth_queue << ") " " write cache hits: " << ((cs.blocks_written - cs.writes) * 100 / cs.blocks_written) << "% " " read cache hits: " << (cs.blocks_read_hit * 100 / cs.blocks_read) << "% " " cache size: " << add_suffix(cs.cache_size * 16 * 1024) << " (" << add_suffix(cs.read_cache_size * 16 * 1024) << ")" " ====" << std::endl; if (active_handle.is_valid()) { torrent_handle h = active_handle; torrent_status s = h.status(); if ((print_downloads && s.state != torrent_status::seeding) || print_peers) h.get_peer_info(peers); out << "====== " << h.name() << " ======" << std::endl; if (print_peers && !peers.empty()) print_peer_info(out, peers); if (print_downloads) { h.get_download_queue(queue); std::sort(queue.begin(), queue.end(), bind(&partial_piece_info::piece_index, _1) < bind(&partial_piece_info::piece_index, _2)); std::vector<cached_piece_info> pieces; ses.get_cache_info(h.info_hash(), pieces); for (std::vector<partial_piece_info>::iterator i = queue.begin(); i != queue.end(); ++i) { cached_piece_info* cp = 0; std::vector<cached_piece_info>::iterator cpi = std::find_if(pieces.begin(), pieces.end() , bind(&cached_piece_info::piece, _1) == i->piece_index); if (cpi != pieces.end()) cp = &*cpi; out << to_string(i->piece_index, 4) << ": ["; for (int j = 0; j < i->blocks_in_piece; ++j) { int index = peer_index(i->blocks[j].peer, peers); char str[] = "+"; if (index >= 0) str[0] = (index < 10)?'0' + index:'A' + index - 10; #ifdef ANSI_TERMINAL_COLORS if (cp && cp->blocks[j]) out << esc("36;7") << str << esc("0"); else if (i->blocks[j].bytes_progress > 0 && i->blocks[j].state == block_info::requested) { if (i->blocks[j].num_peers > 1) out << esc("1;7"); else out << esc("33;7"); out << to_string(i->blocks[j].bytes_progress / float(i->blocks[j].block_size) * 10, 1) << esc("0"); } else if (i->blocks[j].state == block_info::finished) out << esc("32;7") << str << esc("0"); else if (i->blocks[j].state == block_info::writing) out << esc("35;7") << str << esc("0"); else if (i->blocks[j].state == block_info::requested) out << str; else out << " "; #else if (cp && cp->blocks[j]) out << "c"; else if (i->blocks[j].state == block_info::finished) out << "#"; else if (i->blocks[j].state == block_info::writing) out << "+"; else if (i->blocks[j].state == block_info::requested) out << str; else out << " "; #endif } char const* piece_state[4] = {"", "slow", "medium", "fast"}; out << "] " << piece_state[i->piece_state]; if (cp) out << (i->piece_state > 0?" | ":"") << "cache age: " << (total_milliseconds(time_now() - cp->last_use) / 1000.f); out << "\n"; } for (std::vector<cached_piece_info>::iterator i = pieces.begin() , end(pieces.end()); i != end; ++i) { if (i->kind != cached_piece_info::read_cache) continue; out << to_string(i->piece, 4) << ": ["; for (std::vector<bool>::iterator k = i->blocks.begin() , end(i->blocks.end()); k != end; ++k) { #ifdef ANSI_TERMINAL_COLORS if (*k) out << esc("33;7") << " " << esc("0"); else out << " "; #else if (*k) out << "#"; else out << " "; #endif } out << "] " << "cache age: " << (total_milliseconds(time_now() - i->last_use) / 1000.f) << "\n"; } out << "___________________________________\n"; } if (print_file_progress && s.state != torrent_status::seeding && h.has_metadata()) { std::vector<size_type> file_progress; h.file_progress(file_progress); torrent_info const& info = h.get_torrent_info(); for (int i = 0; i < info.num_files(); ++i) { float progress = info.file_at(i).size > 0 ?float(file_progress[i]) / info.file_at(i).size:1; if (file_progress[i] == info.file_at(i).size) out << progress_bar(1.f, 100, "32"); else out << progress_bar(progress, 100, "33"); out << " " << to_string(progress * 100.f, 5) << "% " << add_suffix(file_progress[i]) << " " << info.file_at(i).path.leaf() << "\n"; } out << "___________________________________\n"; } } if (print_log) { for (std::deque<std::string>::iterator i = events.begin(); i != events.end(); ++i) { out << "\n" << *i; } } clear_home(); puts(out.str().c_str()); if (!monitor_dir.empty() && next_dir_scan < time_now()) { scan_dir(monitor_dir, ses, handles, preferred_ratio , compact_allocation_mode, save_path, torrent_upload_limit , torrent_download_limit); next_dir_scan = time_now() + seconds(poll_interval); } } std::cout << "saving session state" << std::endl; { entry session_state = ses.state(); boost::filesystem::ofstream out(".ses_state" , std::ios_base::binary); out.unsetf(std::ios_base::skipws); bencode(std::ostream_iterator<char>(out), session_state); } #ifndef TORRENT_DISABLE_DHT std::cout << "saving DHT state" << std::endl; dht_state = ses.dht_state(); boost::filesystem::ofstream out(".dht_state" , std::ios_base::binary); out.unsetf(std::ios_base::skipws); bencode(std::ostream_iterator<char>(out), dht_state); #endif std::cout << "closing session" << std::endl; } #ifndef BOOST_NO_EXCEPTIONS catch (std::exception& e) { std::cout << e.what() << "\n"; } #endif return 0; }
chongyc/libtorrent
examples/client_test.cpp
C++
bsd-3-clause
46,630
# NonlinearDynamicsAndChaos A high school project regarding nonlinear dynamics, chaos and fractals. The report can be found when it's done (not yet!). The main program is NOT Main.hs, instead Plot.hs. Until I structure it differently is basically everything in the Plot.hs file. I have some minor helpfunctions in Helpfunctions. You can watch my progress in learning to program and understand this project iteration.hs and Plot.hs.
juliajansson/NonlinearDynamicsAndChaos
README.md
Markdown
bsd-3-clause
433
package com.avast.kafkatests; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Random; public abstract class AbstractComponent implements RunnableComponent { private static final String COMPONENT_NAME_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final int COMPONENT_NAME_LENGTH = 8; protected static final Random random = new Random(); protected final String instanceName; protected final Logger logger; public AbstractComponent() { this.instanceName = randomComponentName(); this.logger = LoggerFactory.getLogger(this.getClass().getName() + "." + instanceName); } private static String randomComponentName() { char[] data = new char[COMPONENT_NAME_LENGTH]; for (int i = 0; i < COMPONENT_NAME_LENGTH; ++i) { data[i] = COMPONENT_NAME_CHARACTERS.charAt(random.nextInt(COMPONENT_NAME_CHARACTERS.length())); } return String.valueOf(data); } }
avast/kafka-tests
src/main/java/com/avast/kafkatests/AbstractComponent.java
Java
bsd-3-clause
1,017
package com.PortfolioManager.domain.entities; import com.PortfolioManager.domain.entities.Portfolio; import com.PortfolioManager.domain.entities.Stock; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.3.2.v20111125-r10461", date="2013-05-21T22:52:28") @StaticMetamodel(OrderStock.class) public class OrderStock_ { public static volatile SingularAttribute<OrderStock, Long> orderID; public static volatile SingularAttribute<OrderStock, Stock> stock; public static volatile SingularAttribute<OrderStock, Double> price; public static volatile SingularAttribute<OrderStock, Double> potentialEarnings; public static volatile SingularAttribute<OrderStock, Date> dateUpdate; public static volatile SingularAttribute<OrderStock, Portfolio> portfolio; public static volatile SingularAttribute<OrderStock, Date> dateFirst; public static volatile SingularAttribute<OrderStock, Integer> stocksNumber; }
Ayadi07/CSI
PortfolioManager2.9/build/generated-sources/ap-source-output/com/PortfolioManager/domain/entities/OrderStock_.java
Java
bsd-3-clause
1,074
<?php function thai_date($time){ global $thai_day_arr,$thai_month_arr; //$thai_date_return="วัน ".$thai_day_arr=array("อาทิตย์","จันทร์","อังคาร","พุธ","พฤหัสบดี","ศุกร์","เสาร์")[date("w",$time)]; $thai_date_return= "".date("j",$time); $thai_date_return.=" ".$thai_month_arr=array( "","ม.ค.","ก.พ.","มี.ค.","เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม","กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม" )[date("n",$time)]; $thai_date_return.= " ".(date("Y",$time)+543); // $thai_date_return.= " ".date("H:i",$time)." น."; return $thai_date_return; } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div class="container" style="padding-left: 50px; font-size:15pt;"> <div style="padding-left:500px;margin-top: 10px"> เลขที่ใบเสร็จ &nbsp;&nbsp; <?= $model->id; ?></div> <div style="padding-left:500px;"> <?= thai_date(time()); ?></div> <div class="row"> <div class="col-md-4"> <div align="center" style="margin-bottom: 5px"> <strong style="font-size:22pt; "><u>ใบเสร็จรับเงิน</u></strong> </div> </div> <div class="col-md-4"> </div> <div class="text-center"> <strong style="font-size:20pt; ">สถาบันกวดวิชาบ้านครูติ๊กติวเตอร์</strong> <div style="font-size:14pt; "> ที่อยู่ 209 / 9 ต.ลุ่มสุ่ม อ.ไทรโยค จ.กาญจนบุรี 71150 </div> </div> </div> <div style="font-size: 20px;"> ได้รับเงินจาก&nbsp; <b style="font-weight:bold;"><?= $model->fullName ?></b> </div> <br> <table border="1" cellspacing="0" width="100%" style="font-size: 18px"> <thead> <tr> <td width="10%" style="font-size: 22px" align="center">#</td> <td width="70%" style="font-size: 22px" class="text-center"><strong>รายการคอร์สเรียน</strong></td> <td width="20%" style="font-size: 22px" class="text-center"><strong>ราคา</strong></td> </tr> </thead> <tbody> <?php $no = 1; ?> <!-- ลูปข้อมูล --> <?php foreach (\common\models\RegisterCourse::find()->where(['id' => $model->id])->all() as $row): ?> <?php foreach (\common\models\Registerdetail::find()->where(['register_course_id' => $row->id])->all() as $course): ?> <?php $sumtotall += $course->price ?> <tr> <td width="10%" style="font-size: 20px" align="center"><?= $no++; ?></td> <td width="70%" style="font-size: 20px"><?= $course->nameCourse; ?></td> <td width="20%" style=" font-size: 20px" align="center"><?= number_format($course->price, 2, '.', '') ; ?></td> </tr> <?php endforeach; ?> <?php endforeach; ?> </tbody> </table> <table width="100%" style=" border: 1px solid black; border-top-style: none;" cellspacing="0" > <tr> <td style=" border: 1px solid black;border-top-style: none; font-size: 22px" width="60%" align="center"><b><?php echo convert($sumtotall . '.00'); ?></b></td> <td style="border: 1px solid black;border-top-style: none;" width="40%"> <table width="100%" style="border: 1px solid black;border-top-style: none; border-bottom-style: none;border-left-style: none;border-right-style: none;" cellspacing="0"> <tr> <td width="47%" style="border: 2px solid black;border-top-style: none;border-left-style: none;border-right-style: none; font-size: 20px">ราคารวม</td> <td width="53%" align="center" style="border: 2px solid black;border-top-style: none;border-right-style: none;font-size: 20px"><?php echo number_format($sumtotall, 2, '.', '') ?></td> </tr> <tr> <td width="47%" style="border: 2px solid black;border-top-style: none;border-left-style: none;border-right-style: none; font-size: 20px">VAT 7%</td> <td width="53%" style="border: 2px solid black;border-top-style: none;border-right-style: none;font-size: 20px" align="center"> <?php $vat =($sumtotall*0.07); echo number_format($vat, 2, '.', ''); ?> </td> </tr> <tr> <td width="47%" style="border: 2px solid black;border-top-style: none;border-bottom-style: none;border-left-style: none;border-right-style: none; font-size: 22px">รวมทั้งสิ้น</td> <td width="53%" style="border: 2px solid black;border-top-style: none;border-bottom-style: none;border-right-style: none;font-size: 20px" align="center"> <b><?php $sumvat =($sumtotall+$vat); echo number_format($sumvat, 2, '.', '')?></b> </td> </tr> </table> </td> </tr> </table> <?php $id= Yii::$app->user->id?> <br><br> <table class="table" style="font-size:15pt;"> <?php foreach(\common\models\Personnel::findAll(['user_id'=>$id]) as $models) :?> <tr> <td style="padding-left:100px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </td> <td style="padding-left:100px;"><b>ลงชื่อ</b> &nbsp;&nbsp;&nbsp; <?=$models->fullName?> &nbsp;&nbsp;&nbsp; <b> ผู้รับเงิน</b> </td> </tr> <tr> <td style="padding-left: 105px;"></td> <td style="padding-left:110px;"> ( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <?=$models->fullName?> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; )</td> </tr> <?php endforeach;?> </table> </div> </body> </html> <?PHP function convert($number) { $txtnum1 = array('ศูนย์', 'หนึ่ง', 'สอง', 'สาม', 'สี่', 'ห้า', 'หก', 'เจ็ด', 'แปด', 'เก้า', 'สิบ'); $txtnum2 = array('', 'สิบ', 'ร้อย', 'พัน', 'หมื่น', 'แสน', 'ล้าน', 'สิบ', 'ร้อย', 'พัน', 'หมื่น', 'แสน', 'ล้าน'); $number = str_replace(",", "", $number); $number = str_replace(" ", "", $number); $number = str_replace("บาท", "", $number); $number = explode(".", $number); if (sizeof($number) > 2) { return 'ทศนิยมหลายตัวนะจ๊ะ'; exit; } $strlen = strlen($number[0]); $convert = ''; for ($i = 0; $i < $strlen; $i++) { $n = substr($number[0], $i, 1); if ($n != 0) { if ($i == ($strlen - 1) AND $n == 1) { $convert .= 'เอ็ด'; } elseif ($i == ($strlen - 2) AND $n == 2) { $convert .= 'ยี่'; } elseif ($i == ($strlen - 2) AND $n == 1) { $convert .= ''; } else { $convert .= $txtnum1[$n]; } $convert .= $txtnum2[$strlen - $i - 1]; } } $convert .= 'บาท'; if ($number[1] == '0' OR $number[1] == '00' OR $number[1] == '' ) { $convert .= 'ถ้วน'; } else { $strlen = strlen($number[1]); for ($i = 0; $i < $strlen; $i++) { $n = substr($number[1], $i, 1); if ($n != 0) { if ($i == ($strlen - 1) AND $n == 1) { $convert .= 'เอ็ด'; } elseif ($i == ($strlen - 2) AND $n == 2 ) { $convert .= 'ยี่'; } elseif ($i == ($strlen - 2) AND $n == 1 ) { $convert .= ''; } else { $convert .= $txtnum1[$n]; } $convert .= $txtnum2[$strlen - $i - 1]; } } $convert .= 'สตางค์'; } return $convert; } ## วิธีใช้งาน //$x = '15.00'; //echo $x . "=>" .convert($x); ?>
Darkdion/bkt
backend/views/payment/_billSuccess.php
PHP
bsd-3-clause
9,061
ZF2DoctrineSkeletonApplication =============================== Introduction ------------ This is a simple, skeleton application using the ZF2 MVC layer and module systems and Doctrine2 ORM Layer. This application is meant to be used as a starting place for those looking to get their feet wet with ZF2 and Doctrine2 ORM Layer. Contains base classes: BaseDoctrineController, BaseDoctrineForm, BaseDoctrineModel and BaseDoctrineEntity and thus facilitate the development of your application. Installation ------------ Simply clone this project and run ```sh $ php composer.phar install ``` Post-Installation ------------------ * Create `doctrine.local.php`: `cp autoload/doctrine.local{.php.dist,.php}` * Edit `doctrine.local.php` and set your params of conexion to database in $dbParams array. * Create your entities and place it in the folder `module\Application\src\Application\Entity`, this entities must belong at namespace `\Application\Entity` * **Optional:** Activate `ZendDeveloperTools`: ```sh $ cp config/autoload/zenddevelopertools.local{.php.dist,.php} ``` Activate the module ZendDeveloperTools in the section 'modules' of file `config\application.config`, uncoment the line //'ZendDeveloperTools'. Web Server Setup ---------------- ### PHP CLI Server The simplest way to get started if you are using PHP 5.4 or above is to start the internal PHP cli-server in the root directory: php -S 0.0.0.0:8080 -t public/ public/index.php This will start the cli-server on port 8080, and bind it to all network interfaces. **Note: ** The built-in CLI server is *for development only*. ### Apache Setup To setup apache, setup a virtual host to point to the public/ directory of the project and you should be ready to go! It should look something like below: <VirtualHost *:80> ServerName zf2-tutorial.localhost DocumentRoot /path/to/zf2-app/public SetEnv APPLICATION_ENV "development" <Directory /path/to/zf2-app/public> DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost>
wyanez/ZF2DoctrineSkeletonApp
README.md
Markdown
bsd-3-clause
2,146
export {a, b as c, d, } from "my-module";
mck89/peast
test/Peast/Syntax/ES2015/files/modules/ExportDeclaration/From2.js
JavaScript
bsd-3-clause
41
using UnityEngine; public class CenterCameraButton : TaskbarButton { public void CenterCameraPosition() { var components = SimulationPanel.instance.GetActiveComponents(); Vector3 centroid = Vector3.zero; foreach (var component in components) centroid += component.transform.position; centroid /= components.Length; Camera.main.transform.position = new Vector3(centroid.x, centroid.y, Camera.main.transform.position.z); } protected override bool ShouldShowButton() { return SimulationPanel.instance.activeComponents.Count > 0; } }
gabrielnaves/TG
shp_sim/Assets/Scripts/GUI/Taskbar/CenterCameraButton.cs
C#
bsd-3-clause
609
{% load activity_stream_tags %} {% following_activity_stream viewed_user count offset %}
philippWassibauer/django-activity-stream
activity_stream/templates/activity_stream/ajax_following_stream.html
HTML
bsd-3-clause
88
#include <ncurses.h> int main() { initscr(); printw("Hello, nCurses World"); refresh(); getch(); endwin(); return 0; }
drakekr/ncurse-exam
0x00-HelloWorld/0x00.c
C
bsd-3-clause
126
/* * Copyright: (c) Mayo Foundation for Medical Education and * Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the * triple-shield Mayo logo are trademarks and service marks of MFMER. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/lexevs-grid/LICENSE.txt for details. */ package org.LexGrid.LexBIG.cagrid.LexEVSGridService.HistoryService.service.globus; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Map; import java.io.File; import javax.security.auth.Subject; import javax.xml.namespace.QName; import javax.xml.rpc.handler.MessageContext; import gov.nih.nci.cagrid.introduce.servicetools.security.AuthorizationExtension; import org.globus.wsrf.impl.security.authorization.exceptions.AuthorizationException; import org.globus.wsrf.impl.security.authorization.exceptions.CloseException; import org.globus.wsrf.impl.security.authorization.exceptions.InitializeException; import org.globus.wsrf.impl.security.authorization.exceptions.InvalidPolicyException; import org.globus.wsrf.security.authorization.PDP; import org.globus.wsrf.security.authorization.PDPConfig; import org.globus.wsrf.config.ContainerConfig; import org.w3c.dom.Node; /** * DO NOT EDIT: This class is autogenerated! * * This is a PDP for use with the globus authorization callout. * This class will have a authorize method for each method on this grid service. * The method is responsibe for making any authorization callouts required to satisfy the * authorization requirements placed on each method call. Each method will either return * apon a successful authorization or will throw an exception apon a failed authorization. * * @created by Introduce Toolkit version 1.3 * */ public class HistoryServiceAuthorization implements PDP { public static final String SERVICE_NAMESPACE = "http://LexBIGCaGridServices.cagrid.LexBIG.LexGrid.org/LexBIGCaGridServices/HistoryService"; Map authorizationClassMap = new HashMap(); public HistoryServiceAuthorization() { } protected String getServiceNamespace(){ return SERVICE_NAMESPACE; } public static String getCallerIdentity() { String caller = org.globus.wsrf.security.SecurityManager.getManager().getCaller(); if ((caller == null) || (caller.equals("<anonymous>"))) { return null; } else { return caller; } } public void authorizeGetServiceSecurityMetadata(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetAncestors(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetBaselines(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetConceptChangeVersions(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetConceptCreationVersion(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetDescendents(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetEarliestBaseline(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetEditActionList(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetEditActionList2(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetEditActionList3(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetLatestBaseline(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetSystemRelease(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeDestroy(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeSetTerminationTime(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetMultipleResourceProperties(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeGetResourceProperty(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public void authorizeQueryResourceProperties(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { } public boolean isPermitted(Subject peerSubject, MessageContext context, QName operation) throws AuthorizationException { if(!operation.getNamespaceURI().equals(getServiceNamespace())){ return false; } if(operation.getLocalPart().equals("getServiceSecurityMetadata")){ authorizeGetServiceSecurityMetadata(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getAncestors")){ authorizeGetAncestors(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getBaselines")){ authorizeGetBaselines(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getConceptChangeVersions")){ authorizeGetConceptChangeVersions(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getConceptCreationVersion")){ authorizeGetConceptCreationVersion(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getDescendents")){ authorizeGetDescendents(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getEarliestBaseline")){ authorizeGetEarliestBaseline(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getEditActionList")){ authorizeGetEditActionList(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getEditActionList2")){ authorizeGetEditActionList2(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getEditActionList3")){ authorizeGetEditActionList3(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getLatestBaseline")){ authorizeGetLatestBaseline(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getSystemRelease")){ authorizeGetSystemRelease(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("destroy")){ authorizeDestroy(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("setTerminationTime")){ authorizeSetTerminationTime(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getMultipleResourceProperties")){ authorizeGetMultipleResourceProperties(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("getResourceProperty")){ authorizeGetResourceProperty(peerSubject, context, operation); return true; } else if(operation.getLocalPart().equals("queryResourceProperties")){ authorizeQueryResourceProperties(peerSubject, context, operation); return true; } return false; } public Node getPolicy(Node query) throws InvalidPolicyException { return null; } public String[] getPolicyNames() { return null; } public Node setPolicy(Node policy) throws InvalidPolicyException { return null; } public void close() throws CloseException { } public void initialize(PDPConfig config, String name, String id) throws InitializeException { try{ String serviceName = (String)config.getProperty(name, "serviceName"); String etcPath = ContainerConfig.getBaseDirectory() + File.separator + (String)config.getProperty(name, "etcDirectoryPath"); } catch (Exception e){ throw new InitializeException(e.getMessage(),e); } } }
NCIP/lexevs-grid
LexEVSAnalyiticalService/src/org/LexGrid/LexBIG/cagrid/LexEVSGridService/HistoryService/service/globus/HistoryServiceAuthorization.java
Java
bsd-3-clause
8,649
{% load i18n %} <div class="inline-group inline-stacked{% if inline_admin_formset.opts.sortable %} sortable{% endif %}{% if inline_admin_formset.opts.classes %} {{ inline_admin_formset.opts.classes|join:" " }}{% endif %}" name="inlinegroup"> <h2>{{ inline_admin_formset.opts.verbose_name_plural|title }}</h2> <ul class="inline-item-tools"> {% block inline-item-tools %} <li><a href="javascript://" class="openhandler" title="{% trans 'Open All Items' %}"></a></li> <li><a href="javascript://" class="closehandler" title="{% trans 'Close All Items' %}"></a></li> {% if inline_admin_formset.opts.allow_add %}<li><a href="javascript://" class="addhandler" title="{% trans 'Add Item' %}"></a></li>{% endif %} {% endblock %} </ul> {{ inline_admin_formset.formset.management_form }} {{ inline_admin_formset.formset.non_form_errors }} <div class="items"> <!-- sortable container --> {% for inline_admin_form in inline_admin_formset %} <div class="inline-related collapse-closed{% if inline_admin_form.original or inline_admin_form.show_url %} has_original{% endif %}"> <!-- sortable items --> <!-- headline, original, delete/link/sort --> <h3> {% for fieldset in inline_admin_form %} {% for line in fieldset %} {% for field in line %} {% if field.field.name == "_order" %} {{ field.field }} &nbsp; {% endif %} {% endfor %} {% endfor %} {% endfor %} <b>{{ inline_admin_formset.opts.verbose_name|title }} #{{ forloop.counter }}</b>&nbsp;&nbsp;{% if inline_admin_form.original %}{{ inline_admin_form.original }}{% endif %} </h3> <ul class="inline-item-tools"> {% if inline_admin_form.show_url %}<li><a href="../../../r/{{ inline_admin_form.original.content_type_id }}/{{ inline_admin_form.original.id }}/" class="viewsitelink" title="{% trans 'View on Site' %}" target="_blank"></a></li>{% else %}<li>&nbsp;</li>{% endif %} {% if inline_admin_formset.opts.sortable %}<li><a href="javascript://" class="draghandler" title="Move Item"></a></li>{% else %}<li>&nbsp;</li>{% endif %} {% if inline_admin_formset.formset.can_delete and inline_admin_form.original %}<li>{{ inline_admin_form.deletion_field.field }}<a href="javascript://" class="deletelink" title="{% trans 'Delete Item' %}"></a></li>{% else %}<li>&nbsp;</li>{% endif %} </ul> <!-- fieldsets --> {% if inline_admin_form.form.non_field_errors %}{{ inline_admin_form.form.non_field_errors }}{% endif %} {% for fieldset in inline_admin_form %} {% include "admin/includes/fieldset_inline.html" %} {% endfor %} {{ inline_admin_form.pk_field.field }} {{ inline_admin_form.fk_field.field }} </div> {% endfor %} {{ inline_admin_formset.extra_forms }} </div> </div> <div class="sortablehelper"> <h3><b>Sortable Helper</b></h3> </div>
gladgod/zhiliao
zhiliao/grappellisafe/templates/admin/edit_inline/stacked.html
HTML
bsd-3-clause
3,159
<?php use yii\helpers\Html; use yii\widgets\DetailView; use kartik\alert\Alert; /* @var $this yii\web\View */ /* @var $model app\models\Curso */ $this->title = $model->nome; ?> <div class="usuario-view"> <h1><?= Html::encode($this->title) ?></h1> <?php echo Alert::widget([ 'type' => Alert::TYPE_SUCCESS, 'title' => $mensagem, 'icon' => 'glyphicon glyphicon-ok-sign', 'delay' => 2000 ]); ?> <p> <?php if ( Yii::$app->user->identity->perfil == 'Administrador') { ?> <?= Html::a('Novo Usuário', ['create'], ['class' => 'btn btn-success']) ?> <a href="?r=usuario/index" class="btn btn-default">Voltar</a> <?php } ?> <?php if ( Yii::$app->user->identity->perfil != 'Administrador') { ?> <a href="?r=site/index" class="btn btn-default">Voltar</a> <?php } ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'nome', 'email', 'curso_id', 'disciplina_id', 'idade', 'estilo', 'perfil', ], ]) ?> </div>
tammy00/rbc_ipc
views/usuario/done.php
PHP
bsd-3-clause
1,193
var margin = {top: 70, right: 20, bottom: 20, left: 10}, svgWidth = 1000, svgHeight = 700, width = svgWidth - margin.left - margin.right, height = svgHeight - margin.top - margin.bottom, data = {}; d3.csv("budget16-top10.csv", function (error, csv_data) { console.log(csv_data); data.income = csv_data.filter(function(d) {return d.type === "income" && d.description != "Дефіцит бюджету"}) //.sort(function(b, a) { return a.total16 - b.total16; }); data.charge = csv_data.filter(function(d) {return d.type === "charges "}) // .sort(function(b, a) { return a.total16 - b.total16; }); var totalIncome = { "y15": data.income.map(function(d) {return parseFloat(d.total15)}), "y16": data.income.map(function(d) {return parseFloat(d.total16)}) }, totalOutcome = { "y15": data.charge.map(function(d) {return parseFloat(d.total15)}), "y16": data.charge.map(function(d) {return parseFloat(d.total16)}) }, outcomeSum = d3.sum(totalOutcome.y16), incomeSum = d3.sum(totalIncome.y16), deficite = parseInt(outcomeSum - incomeSum); console.log(data); //Calculate SCALES var scaleY = d3.scale.linear() .domain([0, d3.max([incomeSum, outcomeSum])]) .range([height, 0]) .clamp(true); var scaleR = d3.scale.linear() .domain(d3.extent(totalIncome.y16.concat(totalOutcome.y16))) .rangeRound([0, 8]) .clamp(true); //Prepare AXES functions var yAxis = d3.svg.axis() .scale(scaleY) .orient("left") .ticks(10); var xTranslate = width/ 2, wCounter = 0; //To calculate transition of every nex element function incrementCouner (d, i){ if (!i) wCounter = 0; var c = wCounter, dif = d.type == "income" ? height - scaleY(deficite) : 0; wCounter = wCounter + parseFloat(d.total16); return "translate( 0," + (height - scaleY(c) + dif) + ")"; } //Hack to limit the width of the text labels function wrap(text, width) { text.each(function() { var text = d3.select(this), words = text.text().split(/\s+/).reverse(), word, line = [], lineNumber = 0, lineHeight = 16, // ems y = text.attr("y"), dy = parseFloat(text.attr("dy")), tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; var dyValue = lineNumber ===1 ? 0 : lineHeight; tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", dyValue + "px").text(word); } } }); } //START DRAWING MAIN CONTAINERS var svg = d3.select('#container') .append('svg') .attr('width', svgWidth) .attr('height', svgHeight) .append("g") .attr("transform", "translate(" + (margin.left) + "," + margin.top + ")"); var pyramide = svg.append("g") .attr("class", "pyramide"); //AXE var axe = pyramide.append("g") .attr("class", "y-ax axis") .attr("transform", "translate(" + xTranslate + ", 0)") .attr("opacity", "0"); axe.call(yAxis); //INCOME BAR pyramide.append("g") .attr("class", "income elementbar") .attr("opacity", "0") .attr("transform", "translate(" + (xTranslate-50) + ", 0)") .append("text") .text("Доходи") .attr("transform", "translate( -100, -40)") .attr("class", "bartitle") .style("text-anchor", "middle"); //CHARGES BAR pyramide.append("g") .attr("class", "charges elementbar") .attr("opacity", "0") .attr("transform", "translate(" + (xTranslate+10) + ", 0)") .append("text") .text("Видатки") .attr("transform", "translate( 100, -40)") .attr("class", "bartitle") .style("text-anchor", "middle"); //INCOME ELEMENTS var income = d3.select(".income") .selectAll("g") .data(data.income) .enter() .append("g") .attr("transform", incrementCouner) .attr("class", "item-group"); income.append("rect") .attr("class", function (d) { return "income-item budget-item data-item "+ (d.description == "Інше" ? "rest":"")}) .attr("x", "-200") .attr("width", "200") .attr("height", function (d) {return height - scaleY(d.total16)+1}); //CHARGE ELEMENTS var charges = d3.select(".charges") .selectAll("g") .data(data.charge) .enter() .append("g") .attr("transform", incrementCouner) .attr("class", "item-group"); charges.append("rect") .attr("class", function (d) { return "charges-item budget-item data-item "+ (d.description == "Інше" ? "rest":"")}) .attr("x", "0") .attr("width", "200") .attr("height", function (d) {return height - scaleY(d.total16)+1;}); //DEFICITE ELEMENT var deficiteGroup = pyramide.select(".income") .append("g") .attr("class", "deficite-group item-group") .attr("transform", "translate(0, 0)"); deficiteGroup.append("rect") .attr("class", "deficite budget-item") .attr("opacity", "0") .attr("x", "-200") .attr("width", "200") .attr("height", function () {return height - scaleY(deficite)-2;}) .attr("rx", "7") .attr("ry", "7"); //SIDE DESCRIPTION TEXTS axe.append("text") .text(function() { return Math.floor(outcomeSum) + " млрд.грн."}) .attr("transform", "translate(0, -10)") .attr("opacity", 1) .style("text-anchor", "middle"); deficiteGroup.append("text") .text(function() { return "Дефіцит бюджету: " + deficite + " млрд."}) .attr("transform", function(d){ return "translate( -220," + (height - scaleY(deficite))/2 + ")"}) .attr("opacity", "0") .attr("class", "side-label") .style("text-anchor", "end"); income.append("text") .text(function(d) { return d.description + ": " + d.total16 + " млрд."}) .attr("transform", function(d){ return "translate( -220," + ((height - scaleY(d.total16))/2+5) + ")"}) .attr("opacity", "0") .attr("class", "side-label") .style("text-anchor", "end"); charges.append("text") .text(function(d) { return d.description + ": " + d.total16 + " млрд."}) .attr("transform", function(d){ return "translate( 220," + ((height - scaleY(d.total16))/2+5) + ")"}) .attr("opacity", 0) .attr("class", "side-label") .style("text-anchor", "start"); pyramide.selectAll(".side-label") .attr("dy", "0") .call(wrap, 200); //ANIMATION OF APPEARANCE //AXE pyramide.selectAll('.axis').transition() .attr("opacity", "1") .duration(500) .delay(0); //BARS pyramide.selectAll('.elementbar').transition() .attr("opacity", "1") .duration(1000) .delay(500); //ELEMENTS pyramide.selectAll(".data-item").transition() .attr("height", function (d) {return height - scaleY(d.total16) - 2;}) .attr("rx", "5") .attr("ry", "5") .duration(300) .delay(3000); pyramide.selectAll(".rest").transition() .attr("opacity", "0.4") .duration(300) .delay(3000); //DEFICITE pyramide.select(".deficite").transition() .attr("opacity", function () {return 1;}) .duration(1000) .delay(3500); });
gooduling/angry-data
Budget2016/script.js
JavaScript
bsd-3-clause
8,212
# Change Log ## [2.0.0](https://github.com/gordonbanderson/weboftalent-pagination/tree/2.0.0) (2016-01-20) \* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
gordonbanderson/weboftalent-pagination
CHANGELOG.md
Markdown
bsd-3-clause
247
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2015, S. Chris Colbert | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ module phosphor.widgets { import algo = collections.algorithm; import Signal = core.Signal; import emit = core.emit; import Pair = utility.Pair; import Size = utility.Size; /** * A layout in which only one widget is visible at a time. * * User code is responsible for managing the current layout index. The * index defaults to -1, which means no widget will be shown. The index * must be set to a valid index in order for a widget to be displayed. * * If the current widget is removed, the current index is reset to -1. * * This layout will typically be used in conjunction with another * widget, such as a tab bar, which manipulates the layout index. */ export class StackedLayout extends Layout { /** * A signal emitted when a widget is removed from the layout. */ static widgetRemoved = new Signal<StackedLayout, Pair<number, Widget>>(); /** * Construct a new stack layout. */ constructor() { super(); } /** * Dispose of the resources held by the layout. */ dispose(): void { this._currentItem = null; this._items = null; super.dispose(); } /** * Get the current index of the layout. */ get currentIndex(): number { return algo.indexOf(this._items, this._currentItem); } /** * Set the current index of the layout. */ set currentIndex(index: number) { var prev = this._currentItem; var next = this.itemAt(index) || null; if (prev === next) { return; } this._currentItem = next; if (prev) prev.widget.hide(); if (next) next.widget.show(); // IE repaints before firing the animation frame which processes // the layout update triggered by the show/hide calls above. This // causes a double paint flicker when changing the visible widget. // The workaround is to refresh the layout immediately. this.refresh(); } /** * Get the current widget in the layout. */ get currentWidget(): Widget { return this._currentItem.widget; } /** * Set the current widget in the layout. */ set currentWidget(widget: Widget) { this.currentIndex = this.indexOf(widget); } /** * Get the number of layout items in the layout. */ get count(): number { return this._items.length; } /** * Get the layout item at the specified index. */ itemAt(index: number): ILayoutItem { return this._items[index]; } /** * Remove and return the layout item at the specified index. */ removeAt(index: number): ILayoutItem { var item = algo.removeAt(this._items, index); if (!item) { return void 0; } if (item === this._currentItem) { this._currentItem = null; item.widget.hide(); } emit(this, StackedLayout.widgetRemoved, new Pair(index, item.widget)); return item; } /** * Add a widget as the last item in the layout. * * If the widget already exists in the layout, it will be moved. * * Returns the index of the added widget. */ addWidget(widget: Widget, alignment?: Alignment): number { return this.insertWidget(this.count, widget, alignment); } /** * Insert a widget into the layout at the given index. * * If the widget already exists in the layout, it will be moved. * * Returns the index of the added widget. */ insertWidget(index: number, widget: Widget, alignment: Alignment = 0): number { widget.hide(); this.remove(widget); this.ensureParent(widget); return algo.insert(this._items, index, new WidgetItem(widget, alignment)); } /** * Move a widget from one index to another. * * This method is more efficient for moving a widget than calling * `insertWidget` for an already added widget. It will not remove * the widget before moving it and will not emit `widgetRemoved`. * * Returns -1 if `fromIndex` is out of range. */ moveWidget(fromIndex: number, toIndex: number): number { return algo.move(this._items, fromIndex, toIndex); } /** * Invalidate the cached layout data and enqueue an update. */ invalidate(): void { this._dirty = true; super.invalidate(); } /** * Compute the preferred size of the layout. */ sizeHint(): Size { if (this._dirty) { this._setupGeometry(); } return this._sizeHint; } /** * Compute the minimum size of the layout. */ minSize(): Size { if (this._dirty) { this._setupGeometry(); } return this._minSize; } /** * Compute the maximum size of the layout. */ maxSize(): Size { if (this._dirty) { this._setupGeometry(); } return this._maxSize; } /** * Update the geometry of the child layout items. */ protected layout(x: number, y: number, width: number, height: number): void { if (this._dirty) { this._setupGeometry(); } if (this._currentItem !== null) { this._currentItem.setGeometry(x, y, width, height); } } /** * Initialize the layout items and internal sizes for the layout. */ private _setupGeometry(): void { // Bail early when no work needs to be done. if (!this._dirty) { return; } this._dirty = false; // No parent means the layout is not yet attached. var parent = this.parent; if (!parent) { this._sizeHint = Size.Zero; this._minSize = Size.Zero; this._maxSize = Size.Zero; return; } // Compute the size bounds based on the visible item. var hintW = 0; var hintH = 0; var minW = 0; var minH = 0; var maxW = Infinity; var maxH = Infinity; var item = this._currentItem; if (item !== null) { item.invalidate(); var itemHint = item.sizeHint(); var itemMin = item.minSize(); var itemMax = item.maxSize(); hintW = Math.max(hintW, itemHint.width); hintH = Math.max(hintH, itemHint.height); minW = Math.max(minW, itemMin.width); minH = Math.max(minH, itemMin.height); maxW = Math.min(maxW, itemMax.width); maxH = Math.min(maxH, itemMax.height); } // Account for padding and border on the parent. var box = parent.boxSizing; var boxW = box.horizontalSum; var boxH = box.verticalSum; hintW += boxW; hintH += boxH; minW += boxW; minH += boxH; maxW += boxW; maxH += boxH; // Update the internal sizes. this._sizeHint = new Size(hintW, hintH); this._minSize = new Size(minW, minH); this._maxSize = new Size(maxW, maxH); } private _dirty = true; private _sizeHint: Size = null; private _minSize: Size = null; private _maxSize: Size = null; private _items: ILayoutItem[] = []; private _currentItem: ILayoutItem = null; } } // module phosphor.widgets
dwillmer/phosphor
src/widgets/stackedlayout.ts
TypeScript
bsd-3-clause
7,067
/*================================================================================ Copyright (c) 2013 Steve Jin. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ @SuppressWarnings("all") public class MultipleCertificatesVerifyFaultThumbprintData extends DynamicData { public int port; public String thumbprint; public int getPort() { return this.port; } public String getThumbprint() { return this.thumbprint; } public void setPort(int port) { this.port=port; } public void setThumbprint(String thumbprint) { this.thumbprint=thumbprint; } }
paksv/vijava
src/com/vmware/vim25/MultipleCertificatesVerifyFaultThumbprintData.java
Java
bsd-3-clause
2,159
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_91) on Tue Dec 29 12:43:36 AEDT 2015 --> <title>DLSet (Bouncy Castle Library 1.54 API Specification)</title> <meta name="date" content="2015-12-29"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DLSet (Bouncy Castle Library 1.54 API Specification)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/bouncycastle/asn1/DLSequence.html" title="class in org.bouncycastle.asn1"><span class="strong">Prev Class</span></a></li> <li><a href="../../../org/bouncycastle/asn1/DLTaggedObject.html" title="class in org.bouncycastle.asn1"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/bouncycastle/asn1/DLSet.html" target="_top">Frames</a></li> <li><a href="DLSet.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_org.bouncycastle.asn1.ASN1Set">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.bouncycastle.asn1</div> <h2 title="Class DLSet" class="title">Class DLSet</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../org/bouncycastle/asn1/ASN1Object.html" title="class in org.bouncycastle.asn1">org.bouncycastle.asn1.ASN1Object</a></li> <li> <ul class="inheritance"> <li><a href="../../../org/bouncycastle/asn1/ASN1Primitive.html" title="class in org.bouncycastle.asn1">org.bouncycastle.asn1.ASN1Primitive</a></li> <li> <ul class="inheritance"> <li><a href="../../../org/bouncycastle/asn1/ASN1Set.html" title="class in org.bouncycastle.asn1">org.bouncycastle.asn1.ASN1Set</a></li> <li> <ul class="inheritance"> <li>org.bouncycastle.asn1.DLSet</li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.lang.Iterable&lt;<a href="../../../org/bouncycastle/asn1/ASN1Encodable.html" title="interface in org.bouncycastle.asn1">ASN1Encodable</a>&gt;, <a href="../../../org/bouncycastle/asn1/ASN1Encodable.html" title="interface in org.bouncycastle.asn1">ASN1Encodable</a>, <a href="../../../org/bouncycastle/util/Encodable.html" title="interface in org.bouncycastle.util">Encodable</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">DLSet</span> extends <a href="../../../org/bouncycastle/asn1/ASN1Set.html" title="class in org.bouncycastle.asn1">ASN1Set</a></pre> <div class="block">The DLSet encodes ASN.1 SET value without element ordering, and always using definite length form. <hr> <h2>X.690</h2> <h3>8: Basic encoding rules</h3> <h4>8.11 Encoding of a set value </h4> <b>8.11.1</b> The encoding of a set value shall be constructed <p> <b>8.11.2</b> The contents octets shall consist of the complete encoding of a data value from each of the types listed in the ASN.1 definition of the set type, in an order chosen by the sender, unless the type was referenced with the keyword <b>OPTIONAL</b> or the keyword <b>DEFAULT</b>. <p> <b>8.11.3</b> The encoding of a data value may, but need not, be present for a type which was referenced with the keyword <b>OPTIONAL</b> or the keyword <b>DEFAULT</b>. <blockquote> NOTE &mdash; The order of data values in a set value is not significant, and places no constraints on the order during transfer </blockquote> <h3>9: Canonical encoding rules</h3> <h4>9.3 Set components</h4> The encodings of the component values of a set value shall appear in an order determined by their tags as specified in 8.6 of ITU-T Rec. X.680 | ISO/IEC 8824-1. Additionally, for the purposes of determining the order in which components are encoded when one or more component is an untagged choice type, each untagged choice type is ordered as though it has a tag equal to that of the smallest tag in that choice type or any untagged choice types nested within. <h3>10: Distinguished encoding rules</h3> <h4>10.3 Set components</h4> The encodings of the component values of a set value shall appear in an order determined by their tags as specified in 8.6 of ITU-T Rec. X.680 | ISO/IEC 8824-1. <blockquote> NOTE &mdash; Where a component of the set is an untagged choice type, the location of that component in the ordering will depend on the tag of the choice component being encoded. </blockquote> <h3>11: Restrictions on BER employed by both CER and DER</h3> <h4>11.5 Set and sequence components with default value </h4> The encoding of a set value or sequence value shall not include an encoding for any component value which is equal to its default value.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../org/bouncycastle/asn1/DLSet.html#DLSet()">DLSet</a></strong>()</code> <div class="block">create an empty set</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../org/bouncycastle/asn1/DLSet.html#DLSet(org.bouncycastle.asn1.ASN1Encodable)">DLSet</a></strong>(<a href="../../../org/bouncycastle/asn1/ASN1Encodable.html" title="interface in org.bouncycastle.asn1">ASN1Encodable</a>&nbsp;obj)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../org/bouncycastle/asn1/DLSet.html#DLSet(org.bouncycastle.asn1.ASN1Encodable[])">DLSet</a></strong>(<a href="../../../org/bouncycastle/asn1/ASN1Encodable.html" title="interface in org.bouncycastle.asn1">ASN1Encodable</a>[]&nbsp;a)</code> <div class="block">create a set from an array of objects.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../org/bouncycastle/asn1/DLSet.html#DLSet(org.bouncycastle.asn1.ASN1EncodableVector)">DLSet</a></strong>(<a href="../../../org/bouncycastle/asn1/ASN1EncodableVector.html" title="class in org.bouncycastle.asn1">ASN1EncodableVector</a>&nbsp;v)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.bouncycastle.asn1.ASN1Set"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.bouncycastle.asn1.<a href="../../../org/bouncycastle/asn1/ASN1Set.html" title="class in org.bouncycastle.asn1">ASN1Set</a></h3> <code><a href="../../../org/bouncycastle/asn1/ASN1Set.html#getInstance(org.bouncycastle.asn1.ASN1TaggedObject,%20boolean)">getInstance</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#getInstance(java.lang.Object)">getInstance</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#getObjectAt(int)">getObjectAt</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#getObjects()">getObjects</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#hashCode()">hashCode</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#iterator()">iterator</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#parser()">parser</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#size()">size</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#sort()">sort</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#toArray()">toArray</a>, <a href="../../../org/bouncycastle/asn1/ASN1Set.html#toString()">toString</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.bouncycastle.asn1.ASN1Primitive"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.bouncycastle.asn1.<a href="../../../org/bouncycastle/asn1/ASN1Primitive.html" title="class in org.bouncycastle.asn1">ASN1Primitive</a></h3> <code><a href="../../../org/bouncycastle/asn1/ASN1Primitive.html#equals(java.lang.Object)">equals</a>, <a href="../../../org/bouncycastle/asn1/ASN1Primitive.html#fromByteArray(byte[])">fromByteArray</a>, <a href="../../../org/bouncycastle/asn1/ASN1Primitive.html#toASN1Primitive()">toASN1Primitive</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_org.bouncycastle.asn1.ASN1Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.bouncycastle.asn1.<a href="../../../org/bouncycastle/asn1/ASN1Object.html" title="class in org.bouncycastle.asn1">ASN1Object</a></h3> <code><a href="../../../org/bouncycastle/asn1/ASN1Object.html#getEncoded()">getEncoded</a>, <a href="../../../org/bouncycastle/asn1/ASN1Object.html#getEncoded(java.lang.String)">getEncoded</a>, <a href="../../../org/bouncycastle/asn1/ASN1Object.html#hasEncodedTagValue(java.lang.Object,%20int)">hasEncodedTagValue</a>, <a href="../../../org/bouncycastle/asn1/ASN1Object.html#toASN1Object()">toASN1Object</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, finalize, getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DLSet()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DLSet</h4> <pre>public&nbsp;DLSet()</pre> <div class="block">create an empty set</div> </li> </ul> <a name="DLSet(org.bouncycastle.asn1.ASN1Encodable)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DLSet</h4> <pre>public&nbsp;DLSet(<a href="../../../org/bouncycastle/asn1/ASN1Encodable.html" title="interface in org.bouncycastle.asn1">ASN1Encodable</a>&nbsp;obj)</pre> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>obj</code> - - a single object that makes up the set.</dd></dl> </li> </ul> <a name="DLSet(org.bouncycastle.asn1.ASN1EncodableVector)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>DLSet</h4> <pre>public&nbsp;DLSet(<a href="../../../org/bouncycastle/asn1/ASN1EncodableVector.html" title="class in org.bouncycastle.asn1">ASN1EncodableVector</a>&nbsp;v)</pre> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>v</code> - - a vector of objects making up the set.</dd></dl> </li> </ul> <a name="DLSet(org.bouncycastle.asn1.ASN1Encodable[])"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DLSet</h4> <pre>public&nbsp;DLSet(<a href="../../../org/bouncycastle/asn1/ASN1Encodable.html" title="interface in org.bouncycastle.asn1">ASN1Encodable</a>[]&nbsp;a)</pre> <div class="block">create a set from an array of objects.</div> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/bouncycastle/asn1/DLSequence.html" title="class in org.bouncycastle.asn1"><span class="strong">Prev Class</span></a></li> <li><a href="../../../org/bouncycastle/asn1/DLTaggedObject.html" title="class in org.bouncycastle.asn1"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/bouncycastle/asn1/DLSet.html" target="_top">Frames</a></li> <li><a href="DLSet.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_org.bouncycastle.asn1.ASN1Set">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
GaloisInc/hacrypto
src/Java/BouncyCastle/BouncyCastle-1.54/bcprov-jdk15on-154/javadoc/org/bouncycastle/asn1/DLSet.html
HTML
bsd-3-clause
15,507
#ifndef _DATE_TIME_WRAPPING_INT_HPP__ #define _DATE_TIME_WRAPPING_INT_HPP__ /* Copyright (c) 2002,2003,2005 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0) * Author: Jeff Garland, Bart Garst * $Date: 2005/10/24 01:32:08 $ */ namespace boost { namespace date_time { //! A wrapping integer used to support time durations (WARNING: only instantiate with a signed type) /*! In composite date and time types this type is used to * wrap at the day boundary. * Ex: * A wrapping_int<short, 10> will roll over after nine, and * roll under below zero. This gives a range of [0,9] * * NOTE: it is strongly recommended that wrapping_int2 be used * instead of wrapping_int as wrapping_int is to be depricated * at some point soon. * * Also Note that warnings will occur if instantiated with an * unsigned type. Only a signed type should be used! */ template<typename int_type_, int_type_ wrap_val> class wrapping_int { public: typedef int_type_ int_type; //typedef overflow_type_ overflow_type; static int_type wrap_value() {return wrap_val;} //!Add, return true if wrapped wrapping_int(int_type v) : value_(v) {}; //! Explicit converion method int_type as_int() const {return value_;} operator int_type() const {return value_;} //!Add, return number of wraps performed /*! The sign of the returned value will indicate which direction the * wraps went. Ex: add a negative number and wrapping under could occur, * this would be indicated by a negative return value. If wrapping over * took place, a positive value would be returned */ int_type add(int_type v) { int_type remainder = static_cast<int_type>(v % (wrap_val)); int_type overflow = static_cast<int_type>(v / (wrap_val)); value_ = static_cast<int_type>(value_ + remainder); return calculate_wrap(overflow); } //! Subtract will return '+d' if wrapping under took place ('d' is the number of wraps) /*! The sign of the returned value will indicate which direction the * wraps went (positive indicates wrap under, negative indicates wrap over). * Ex: subtract a negative number and wrapping over could * occur, this would be indicated by a negative return value. If * wrapping under took place, a positive value would be returned. */ int_type subtract(int_type v) { int_type remainder = static_cast<int_type>(v % (wrap_val)); int_type underflow = static_cast<int_type>(-(v / (wrap_val))); value_ = static_cast<int_type>(value_ - remainder); return calculate_wrap(underflow) * -1; } private: int_type value_; int_type calculate_wrap(int_type wrap) { if ((value_) >= wrap_val) { wrap++; value_ -= (wrap_val); } else if(value_ < 0) { wrap--; value_ += (wrap_val); } return wrap; } }; //! A wrapping integer used to wrap around at the top (WARNING: only instantiate with a signed type) /*! Bad name, quick impl to fix a bug -- fix later!! * This allows the wrap to restart at a value other than 0. */ template<typename int_type_, int_type_ wrap_min, int_type_ wrap_max> class wrapping_int2 { public: typedef int_type_ int_type; static unsigned long wrap_value() {return wrap_max;} static unsigned long min_value() {return wrap_min;} /*! If initializing value is out of range of [wrap_min, wrap_max], * value will be initialized to closest of min or max */ wrapping_int2(int_type v) : value_(v) { if(value_ < wrap_min) { value_ = wrap_min; } if(value_ > wrap_max) { value_ = wrap_max; } } //! Explicit converion method int_type as_int() const {return value_;} operator int_type() const {return value_;} //!Add, return number of wraps performed /*! The sign of the returned value will indicate which direction the * wraps went. Ex: add a negative number and wrapping under could occur, * this would be indicated by a negative return value. If wrapping over * took place, a positive value would be returned */ int_type add(int_type v) { int_type remainder = static_cast<int_type>(v % (wrap_max - wrap_min + 1)); int_type overflow = static_cast<int_type>(v / (wrap_max - wrap_min + 1)); value_ = static_cast<int_type>(value_ + remainder); return calculate_wrap(overflow); } //! Subtract will return '-d' if wrapping under took place ('d' is the number of wraps) /*! The sign of the returned value will indicate which direction the * wraps went. Ex: subtract a negative number and wrapping over could * occur, this would be indicated by a positive return value. If * wrapping under took place, a negative value would be returned */ int_type subtract(int_type v) { int_type remainder = static_cast<int_type>(v % (wrap_max - wrap_min + 1)); int_type underflow = static_cast<int_type>(-(v / (wrap_max - wrap_min + 1))); value_ = static_cast<int_type>(value_ - remainder); return calculate_wrap(underflow); } private: int_type value_; int_type calculate_wrap(int_type wrap) { if ((value_) > wrap_max) { wrap++; value_ -= (wrap_max - wrap_min + 1); } else if((value_) < wrap_min) { wrap--; value_ += (wrap_max - wrap_min + 1); } return wrap; } }; } } //namespace date_time #endif
darwin/upgradr
ieaddon/Upgradr/boost/date_time/wrapping_int.hpp
C++
bsd-3-clause
5,661
#include "DerefStructDeref.h" #include <vector> namespace dale { Node *FormMacroDerefStructDerefParse(Context *ctx, Node *n) { if (!ctx->er->assertArgNums("@:@", n, 2, 2)) { return NULL; } std::vector<Node *> *lst = n->list; (*lst)[0]->token->str_value.clear(); (*lst)[0]->token->str_value.append("@"); std::vector<Node *> *new_lst_inner = new std::vector<Node *>; Node *deref_node = new Node("@"); (*lst)[1]->copyMetaTo(deref_node); new_lst_inner->push_back(deref_node); new_lst_inner->push_back((*lst)[1]); Node *new_lst_inner_node = new Node(new_lst_inner); (*lst)[1]->copyMetaTo(new_lst_inner_node); std::vector<Node *> *new_lst_sm = new std::vector<Node *>; Node *struct_mem_node = new Node(":"); (*lst)[1]->copyMetaTo(struct_mem_node); new_lst_sm->push_back(struct_mem_node); new_lst_sm->push_back(new_lst_inner_node); new_lst_sm->push_back((*lst)[2]); (*lst)[1] = new Node(new_lst_sm); lst->pop_back(); return n; } }
tomhrr/dale
src/dale/Form/Macro/DerefStructDeref/DerefStructDeref.cpp
C++
bsd-3-clause
1,025
/** ** @file tcSky.cpp */ /* ** Copyright (c) 2014, GCBLUE PROJECT ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: ** ** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from ** this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT ** NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ** COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING ** IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tcSky.h" #include "tcTVEngine.h" #include "math_constants.h" #include "tcSkyModel.h" #ifdef _DEBUG #define new DEBUG_NEW #endif void tcSky::BuildSkyDome() { tcTVEngine* engine = tcTVEngine::Get(); CTVScene* scene = engine->GetScene(); tcSkyModel* skyModel = tcSkyModel::Get(); if (skyDomeTop != 0) { scene->DestroyMesh(skyDomeTop); } if (skyDomeBase != 0) { scene->DestroyMesh(skyDomeBase); } skyDomeTop = scene->CreateMeshBuilder("SkyDomeTop"); skyDomeBase = scene->CreateMeshBuilder("SkyDomeBase"); float maxElevation_rad = C_PIOVER180*maxElevation_deg; float minElevation_rad = C_PIOVER180*minElevation_deg; // create top skyDomeTop->SetLightingMode(cTV_LIGHTING_NONE); skyDomeTop->SetPrimitiveType(cTV_TRIANGLEFAN); skyDomeTop->SetCullMode(cTV_DOUBLESIDED); skyDomeTop->SetMeshFormat(cTV_MESHFORMAT_NOLIGHTING | cTV_MESHFORMAT_NOTEX | cTV_MESHFORMAT_DIFFUSE); // skyDomeTop->SetOverlay(true); skyDomeTop->SetAlphaTest(false, 128, false); skyDomeTop->EnableFrustumCulling(false); float y_top = radius * sinf(maxElevation_rad); float r_top = radius * cosf(maxElevation_rad); // radius of dome top Vec3 zenithColor = skyModel->GetZenithColor(); int color_top = RGBA(zenithColor.x, zenithColor.y, zenithColor.z, 1); // add center skyDomeTop->AddVertex(0, y_top, 0, 0, 1, 0, 0, 0, 0, 0, color_top); float daz = C_TWOPI / float(resolutionAz); int color_k_int = -1; for (int k=0; k<resolutionAz; k++) { float az_k = float(k)*daz; float x_top = r_top * sinf(az_k); float z_top = r_top * cosf(az_k); Vec3 color_k = skyModel->GetSkyColor(maxElevation_rad, az_k); color_k_int = RGBA(color_k.x, color_k.y, color_k.z, 1.0f); skyDomeTop->AddVertex(x_top, y_top, z_top, 0, -1, 0, 0, 0, 0, 0, color_k_int); } skyDomeTop->AddVertex(0, y_top, r_top, 0, -1, 0, 0, 0, 0, 0, color_k_int); // complete circle // create base skyDomeBase->SetLightingMode(cTV_LIGHTING_NONE); skyDomeBase->SetPrimitiveType(cTV_TRIANGLESTRIP); skyDomeBase->SetCullMode(cTV_FRONT_CULL); //cTV_DOUBLESIDED); skyDomeBase->SetMeshFormat(cTV_MESHFORMAT_NOLIGHTING | cTV_MESHFORMAT_NOTEX | cTV_MESHFORMAT_DIFFUSE ); // ); skyDomeBase->SetOverlay(true); skyDomeBase->SetAlphaTest(false, 128, false); skyDomeBase->EnableFrustumCulling(false); float del = (maxElevation_rad - minElevation_rad) / float(resolutionEl); // float el_rad = maxElevation_rad; for (int k=0; k<resolutionEl; k++) { float el_rad_top = maxElevation_rad - float(k)*del; float el_rad_bottom = maxElevation_rad - float(k+1)*del; float y_top = radius * sinf(el_rad_top); float y_bottom = radius * sinf(el_rad_bottom); float r_top = radius * cosf(el_rad_top); float r_bottom = radius * cosf(el_rad_bottom); for (int k=0; k<resolutionAz; k++) { float az_k = float(k)*daz; float x_top = r_top * sinf(az_k); float z_top = r_top * cosf(az_k); float x_bottom = r_bottom * sinf(az_k); float z_bottom = r_bottom * cosf(az_k); Vec3 colorTop = skyModel->GetSkyColor(el_rad_top, az_k); Vec3 colorBottom = skyModel->GetSkyColor(el_rad_bottom, az_k); int color_top = RGBA(colorTop.x, colorTop.y, colorTop.z, 1.0f); int color_bottom = RGBA(colorBottom.x, colorBottom.y, colorBottom.z, 1.0f); skyDomeBase->AddVertex(x_top, y_top, z_top, 0, -1, 0, 0, 0, 0, 0, color_top); skyDomeBase->AddVertex(x_bottom, y_bottom, z_bottom, 0, -1, 0, 0, 0, 0, 0, color_bottom); } Vec3 colorTop = skyModel->GetSkyColor(el_rad_top, 0); Vec3 colorBottom = skyModel->GetSkyColor(el_rad_bottom, 0); int color_top = RGBA(colorTop.x, colorTop.y, colorTop.z, 1.0f); int color_bottom = RGBA(colorBottom.x, colorBottom.y, colorBottom.z, 1.0f); skyDomeBase->AddVertex(0, y_top, r_top, 0, -1, 0, 0, 0, 0, 0, color_top); skyDomeBase->AddVertex(0, y_bottom, r_bottom, 0, -1, 0, 0, 0, 0, 0, color_bottom); } skyDomeTop->Enable(false); skyDomeBase->Enable(false); } void tcSky::Render() { wxASSERT(skyDomeTop != 0); skyDomeTop->Enable(true); skyDomeBase->Enable(true); skyDomeTop->Render(); skyDomeBase->Render(); skyDomeTop->Enable(false); skyDomeBase->Enable(false); } void tcSky::SetRadius(float val) { if (radius == val) return; radius = val; if (skyDomeTop == 0) return; BuildSkyDome(); // rebuild with new radius } void tcSky::UpdateCameraPosition(const Vec3& pos) { skyDomeTop->SetPosition(pos.x, 0, pos.z); skyDomeBase->SetPosition(pos.x, 0, pos.z); } tcSky::tcSky() : baseDayAmbient(1, 1, 1), baseNightAmbient(0, 0, 0), baseDayColor(0, 0, 1), baseNightColor(0, 0, 0), resolutionAz(64), resolutionEl(32), maxElevation_deg(55), minElevation_deg(-15), radius(14e8), heightScale(1), origin(0, 0, 0), skyDomeTop(0), skyDomeBase(0) { } tcSky::~tcSky() { }
gcblue/gcblue
src/graphics/tcSky.cpp
C++
bsd-3-clause
6,800
/*L * Copyright HealthCare IT, Inc. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/edct-formbuilder/LICENSE.txt for details. */ package com.healthcit.cacure.model; import javax.persistence.CascadeType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import javax.persistence.Table; @Entity @Table(name="skip_rule") @DiscriminatorValue("formElementSkip") public class FormElementSkipRule extends BaseSkipRule{ @OneToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch=FetchType.LAZY ) @JoinColumn(name="parent_id") private FormElement element; public FormElement getFormElement() { return element; } public void setFormElement(FormElement element) { this.element = element; } @PrePersist @PreUpdate @PreRemove @SuppressWarnings("unused") private void onUpdate() { BaseForm form = getFormElement().getForm(); form.setLastUpdatedBy(form.getLockedBy()); } @Override public FormElementSkipRule clone() { FormElementSkipRule o = new FormElementSkipRule(); o.setLogicalOp(logicalOp); return o; } }
NCIP/edct-formbuilder
src/main/java/com/healthcit/cacure/model/FormElementSkipRule.java
Java
bsd-3-clause
1,419
/* $NetBSD: bus.h,v 1.5 2003/06/15 23:08:59 fvdl Exp $ */ /* $OpenBSD: bus.h,v 1.13 2001/07/30 14:15:59 art Exp $ */ /* * Copyright (c) 1998,1999 Michael Shalayeff * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Michael Shalayeff. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _MACHINE_BUS_H_ #define _MACHINE_BUS_H_ #include <machine/cpufunc.h> /* * Bus address and size types. */ typedef u_long bus_addr_t; typedef u_long bus_size_t; typedef u_long bus_space_handle_t; struct hppa_bus_space_tag { void *hbt_cookie; int (*hbt_map) __P((void *v, bus_addr_t addr, bus_size_t size, int flags, bus_space_handle_t *bshp)); void (*hbt_unmap) __P((void *v, bus_space_handle_t bsh, bus_size_t size)); int (*hbt_subregion) __P((void *v, bus_space_handle_t bsh, bus_size_t offset, bus_size_t size, bus_space_handle_t *nbshp)); int (*hbt_alloc) __P((void *v, bus_addr_t rstart, bus_addr_t rend, bus_size_t size, bus_size_t align, bus_size_t boundary, int flags, bus_addr_t *addrp, bus_space_handle_t *bshp)); void (*hbt_free) __P((void *, bus_space_handle_t, bus_size_t)); void (*hbt_barrier) __P((void *v, bus_space_handle_t h, bus_size_t o, bus_size_t l, int op)); u_int8_t (*hbt_r1) __P((void *, bus_space_handle_t, bus_size_t)); u_int16_t (*hbt_r2) __P((void *, bus_space_handle_t, bus_size_t)); u_int32_t (*hbt_r4) __P((void *, bus_space_handle_t, bus_size_t)); u_int64_t (*hbt_r8) __P((void *, bus_space_handle_t, bus_size_t)); void (*hbt_w1)__P((void *, bus_space_handle_t, bus_size_t, u_int8_t)); void (*hbt_w2)__P((void *, bus_space_handle_t, bus_size_t, u_int16_t)); void (*hbt_w4)__P((void *, bus_space_handle_t, bus_size_t, u_int32_t)); void (*hbt_w8)__P((void *, bus_space_handle_t, bus_size_t, u_int64_t)); void (*hbt_rm_1) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int8_t *a, bus_size_t c)); void (*hbt_rm_2) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int16_t *a, bus_size_t c)); void (*hbt_rm_4) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int32_t *a, bus_size_t c)); void (*hbt_rm_8) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int64_t *a, bus_size_t c)); void (*hbt_wm_1) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int8_t *a, bus_size_t c)); void (*hbt_wm_2) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int16_t *a, bus_size_t c)); void (*hbt_wm_4) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int32_t *a, bus_size_t c)); void (*hbt_wm_8) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int64_t *a, bus_size_t c)); void (*hbt_sm_1) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int8_t vv, bus_size_t c)); void (*hbt_sm_2) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int16_t vv, bus_size_t c)); void (*hbt_sm_4) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int32_t vv, bus_size_t c)); void (*hbt_sm_8) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int64_t vv, bus_size_t c)); void (*hbt_rrm_2) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int16_t *a, bus_size_t c)); void (*hbt_rrm_4) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int32_t *a, bus_size_t c)); void (*hbt_rrm_8) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int64_t *a, bus_size_t c)); void (*hbt_wrm_2) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int16_t *a, bus_size_t c)); void (*hbt_wrm_4) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int32_t *a, bus_size_t c)); void (*hbt_wrm_8) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int64_t *a, bus_size_t c)); void (*hbt_rr_1) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int8_t *a, bus_size_t c)); void (*hbt_rr_2) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int16_t *a, bus_size_t c)); void (*hbt_rr_4) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int32_t *a, bus_size_t c)); void (*hbt_rr_8) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int64_t *a, bus_size_t c)); void (*hbt_wr_1) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int8_t *a, bus_size_t c)); void (*hbt_wr_2) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int16_t *a, bus_size_t c)); void (*hbt_wr_4) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int32_t *a, bus_size_t c)); void (*hbt_wr_8) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int64_t *a, bus_size_t c)); void (*hbt_rrr_2) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int16_t *a, bus_size_t c)); void (*hbt_rrr_4) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int32_t *a, bus_size_t c)); void (*hbt_rrr_8) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int64_t *a, bus_size_t c)); void (*hbt_wrr_2) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int16_t *a, bus_size_t c)); void (*hbt_wrr_4) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int32_t *a, bus_size_t c)); void (*hbt_wrr_8) __P((void *v, bus_space_handle_t h, bus_size_t o, const u_int64_t *a, bus_size_t c)); void (*hbt_sr_1) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int8_t vv, bus_size_t c)); void (*hbt_sr_2) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int16_t vv, bus_size_t c)); void (*hbt_sr_4) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int32_t vv, bus_size_t c)); void (*hbt_sr_8) __P((void *v, bus_space_handle_t h, bus_size_t o, u_int64_t vv, bus_size_t c)); void (*hbt_cp_1) __P((void *v, bus_space_handle_t h1, bus_size_t o1, bus_space_handle_t h2, bus_size_t o2, bus_size_t c)); void (*hbt_cp_2) __P((void *v, bus_space_handle_t h1, bus_size_t o1, bus_space_handle_t h2, bus_size_t o2, bus_size_t c)); void (*hbt_cp_4) __P((void *v, bus_space_handle_t h1, bus_size_t o1, bus_space_handle_t h2, bus_size_t o2, bus_size_t c)); void (*hbt_cp_8) __P((void *v, bus_space_handle_t h1, bus_size_t o1, bus_space_handle_t h2, bus_size_t o2, bus_size_t c)); }; typedef const struct hppa_bus_space_tag *bus_space_tag_t; extern const struct hppa_bus_space_tag hppa_bustag; /* bus access routines */ #define DCIAS(pa) ((void)(pa)) #define BUS_SPACE_ALIGNED_POINTER(p, t) ALIGNED_POINTER(p, t) #define bus_space_map(t,a,c,ca,hp) \ (((t)->hbt_map)((t)->hbt_cookie,(a),(c),(ca),(hp))) #define bus_space_unmap(t,h,c) \ (((t)->hbt_unmap)((t)->hbt_cookie,(h),(c))) #define bus_space_subregion(t,h,o,c,hp) \ (((t)->hbt_subregion)((t)->hbt_cookie,(h),(o),(c),(hp))) #define bus_space_alloc(t,b,e,c,al,bn,ca,ap,hp) \ (((t)->hbt_alloc)((t)->hbt_alloc,(b),(e),(c),(al),(bn),(ca),(ap),(hp))) #define bus_space_free(t,h,c) \ (((t)->hbt_free)((t)->hbt_cookie,(h),(c))) #define bus_space_read_1(t,h,o) (((t)->hbt_r1)((t)->hbt_cookie,(h),(o))) #define bus_space_read_2(t,h,o) (((t)->hbt_r2)((t)->hbt_cookie,(h),(o))) #define bus_space_read_4(t,h,o) (((t)->hbt_r4)((t)->hbt_cookie,(h),(o))) #define bus_space_read_8(t,h,o) (((t)->hbt_r8)((t)->hbt_cookie,(h),(o))) #define bus_space_write_1(t,h,o,v) (((t)->hbt_w1)((t)->hbt_cookie,(h),(o),(v))) #define bus_space_write_2(t,h,o,v) (((t)->hbt_w2)((t)->hbt_cookie,(h),(o),(v))) #define bus_space_write_4(t,h,o,v) (((t)->hbt_w4)((t)->hbt_cookie,(h),(o),(v))) #define bus_space_write_8(t,h,o,v) (((t)->hbt_w8)((t)->hbt_cookie,(h),(o),(v))) /* XXX fredette */ #define __BUS_SPACE_HAS_STREAM_METHODS #define bus_space_read_stream_2 bus_space_read_2 #define bus_space_read_stream_4 bus_space_read_4 #define bus_space_read_stream_8 bus_space_read_8 #define bus_space_write_stream_2 bus_space_write_2 #define bus_space_write_stream_4 bus_space_write_4 #define bus_space_write_stream_8 bus_space_write_8 #define bus_space_read_multi_1(t,h,o,a,c) \ (((t)->hbt_rm_1)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_multi_2(t,h,o,a,c) \ (((t)->hbt_rm_2)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_multi_4(t,h,o,a,c) \ (((t)->hbt_rm_4)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_multi_8(t,h,o,a,c) \ (((t)->hbt_rm_8)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_multi_1(t,h,o,a,c) \ (((t)->hbt_wm_1)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_multi_2(t,h,o,a,c) \ (((t)->hbt_wm_2)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_multi_4(t,h,o,a,c) \ (((t)->hbt_wm_4)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_multi_8(t,h,o,a,c) \ (((t)->hbt_wm_8)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_set_multi_1(t,h,o,v,c) \ (((t)->hbt_sm_1)((t)->hbt_cookie, (h), (o), (v), (c))) #define bus_space_set_multi_2(t,h,o,v,c) \ (((t)->hbt_sm_2)((t)->hbt_cookie, (h), (o), (v), (c))) #define bus_space_set_multi_4(t,h,o,v,c) \ (((t)->hbt_sm_4)((t)->hbt_cookie, (h), (o), (v), (c))) #define bus_space_set_multi_8(t,h,o,v,c) \ (((t)->hbt_sm_8)((t)->hbt_cookie, (h), (o), (v), (c))) #define bus_space_read_multi_stream_2(t, h, o, a, c) \ (((t)->hbt_rrm_2)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_multi_stream_4(t, h, o, a, c) \ (((t)->hbt_rrm_4)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_multi_stream_8(t, h, o, a, c) \ (((t)->hbt_rrm_8)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_multi_stream_2(t, h, o, a, c) \ (((t)->hbt_wrm_2)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_multi_stream_4(t, h, o, a, c) \ (((t)->hbt_wrm_4)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_multi_stream_8(t, h, o, a, c) \ (((t)->hbt_wrm_8)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_region_1(t, h, o, a, c) \ (((t)->hbt_rr_1)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_region_2(t, h, o, a, c) \ (((t)->hbt_rr_2)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_region_4(t, h, o, a, c) \ (((t)->hbt_rr_4)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_region_8(t, h, o, a, c) \ (((t)->hbt_rr_8)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_region_1(t, h, o, a, c) \ (((t)->hbt_wr_1)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_region_2(t, h, o, a, c) \ (((t)->hbt_wr_2)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_region_4(t, h, o, a, c) \ (((t)->hbt_wr_4)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_region_8(t, h, o, a, c) \ (((t)->hbt_wr_8)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_region_stream_2(t, h, o, a, c) \ (((t)->hbt_rrr_2)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_region_stream_4(t, h, o, a, c) \ (((t)->hbt_rrr_4)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_read_region_stream_8(t, h, o, a, c) \ (((t)->hbt_rrr_8)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_region_stream_2(t, h, o, a, c) \ (((t)->hbt_wrr_2)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_region_stream_4(t, h, o, a, c) \ (((t)->hbt_wrr_4)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_write_region_stream_8(t, h, o, a, c) \ (((t)->hbt_wrr_8)((t)->hbt_cookie, (h), (o), (a), (c))) #define bus_space_set_region_1(t, h, o, v, c) \ (((t)->hbt_sr_1)((t)->hbt_cookie, (h), (o), (v), (c))) #define bus_space_set_region_2(t, h, o, v, c) \ (((t)->hbt_sr_2)((t)->hbt_cookie, (h), (o), (v), (c))) #define bus_space_set_region_4(t, h, o, v, c) \ (((t)->hbt_sr_4)((t)->hbt_cookie, (h), (o), (v), (c))) #define bus_space_set_region_8(t, h, o, v, c) \ (((t)->hbt_sr_8)((t)->hbt_cookie, (h), (o), (v), (c))) #define bus_space_copy_1(t, h1, o1, h2, o2, c) \ (((t)->hbt_cp_1)((t)->hbt_cookie, (h1), (o1), (h2), (o2), (c))) #define bus_space_copy_2(t, h1, o1, h2, o2, c) \ (((t)->hbt_cp_2)((t)->hbt_cookie, (h1), (o1), (h2), (o2), (c))) #define bus_space_copy_4(t, h1, o1, h2, o2, c) \ (((t)->hbt_cp_4)((t)->hbt_cookie, (h1), (o1), (h2), (o2), (c))) #define bus_space_copy_8(t, h1, o1, h2, o2, c) \ (((t)->hbt_cp_8)((t)->hbt_cookie, (h1), (o1), (h2), (o2), (c))) #define BUS_SPACE_BARRIER_READ 0 #define BUS_SPACE_BARRIER_WRITE 1 #define bus_space_barrier(t,h,o,l,op) \ ((t)->hbt_barrier((t)->hbt_cookie, (h), (o), (l), (op))) #define BUS_DMA_WAITOK 0x000 /* safe to sleep (pseudo-flag) */ #define BUS_DMA_NOWAIT 0x001 /* not safe to sleep */ #define BUS_DMA_ALLOCNOW 0x002 /* perform resource allocation now */ #define BUS_DMA_COHERENT 0x004 /* hint: map memory DMA coherent */ #define BUS_DMA_STREAMING 0x008 /* hint: sequential, unidirectional */ #define BUS_DMA_BUS1 0x010 /* placeholders for bus functions... */ #define BUS_DMA_BUS2 0x020 #define BUS_DMA_BUS3 0x040 #define BUS_DMA_BUS4 0x080 #define BUS_DMA_READ 0x100 /* mapping is device -> memory only */ #define BUS_DMA_WRITE 0x200 /* mapping is memory -> device only */ #define BUS_DMA_NOCACHE 0x400 /* hint: map non-cached memory */ /* For devices that have a 24-bit address space */ #define BUS_DMA_24BIT BUS_DMA_BUS1 /* Forwards needed by prototypes below. */ struct mbuf; struct proc; struct uio; #define BUS_DMASYNC_POSTREAD 0x01 #define BUS_DMASYNC_POSTWRITE 0x02 #define BUS_DMASYNC_PREREAD 0x04 #define BUS_DMASYNC_PREWRITE 0x08 typedef const struct hppa_bus_dma_tag *bus_dma_tag_t; typedef struct hppa_bus_dmamap *bus_dmamap_t; #define BUS_DMA_TAG_VALID(t) ((t) != (bus_dma_tag_t)0) /* * bus_dma_segment_t * * Describes a single contiguous DMA transaction. Values * are suitable for programming into DMA registers. */ struct hppa_bus_dma_segment { bus_addr_t ds_addr; /* DMA address */ bus_size_t ds_len; /* length of transfer */ void *_ds_mlist; /* page list when dmamem_alloc'ed */ vaddr_t _ds_va; /* VA when dmamem_map'ed */ }; typedef struct hppa_bus_dma_segment bus_dma_segment_t; /* * bus_dma_tag_t * * A machine-dependent opaque type describing the implementation of * DMA for a given bus. */ struct hppa_bus_dma_tag { void *_cookie; /* cookie used in the guts */ /* * DMA mapping methods. */ int (*_dmamap_create) __P((void *, bus_size_t, int, bus_size_t, bus_size_t, int, bus_dmamap_t *)); void (*_dmamap_destroy) __P((void *, bus_dmamap_t)); int (*_dmamap_load) __P((void *, bus_dmamap_t, void *, bus_size_t, struct proc *, int)); int (*_dmamap_load_mbuf) __P((void *, bus_dmamap_t, struct mbuf *, int)); int (*_dmamap_load_uio) __P((void *, bus_dmamap_t, struct uio *, int)); int (*_dmamap_load_raw) __P((void *, bus_dmamap_t, bus_dma_segment_t *, int, bus_size_t, int)); void (*_dmamap_unload) __P((void *, bus_dmamap_t)); void (*_dmamap_sync) __P((void *, bus_dmamap_t, bus_addr_t, bus_size_t, int)); /* * DMA memory utility functions. */ int (*_dmamem_alloc) __P((void *, bus_size_t, bus_size_t, bus_size_t, bus_dma_segment_t *, int, int *, int)); void (*_dmamem_free) __P((void *, bus_dma_segment_t *, int)); int (*_dmamem_map) __P((void *, bus_dma_segment_t *, int, size_t, caddr_t *, int)); void (*_dmamem_unmap) __P((void *, caddr_t, size_t)); paddr_t (*_dmamem_mmap) __P((void *, bus_dma_segment_t *, int, off_t, int, int)); }; #define bus_dmamap_create(t, s, n, m, b, f, p) \ (*(t)->_dmamap_create)((t)->_cookie, (s), (n), (m), (b), (f), (p)) #define bus_dmamap_destroy(t, p) \ (*(t)->_dmamap_destroy)((t)->_cookie, (p)) #define bus_dmamap_load(t, m, b, s, p, f) \ (*(t)->_dmamap_load)((t)->_cookie, (m), (b), (s), (p), (f)) #define bus_dmamap_load_mbuf(t, m, b, f) \ (*(t)->_dmamap_load_mbuf)((t)->_cookie, (m), (b), (f)) #define bus_dmamap_load_uio(t, m, u, f) \ (*(t)->_dmamap_load_uio)((t)->_cookie, (m), (u), (f)) #define bus_dmamap_load_raw(t, m, sg, n, s, f) \ (*(t)->_dmamap_load_raw)((t)->_cookie, (m), (sg), (n), (s), (f)) #define bus_dmamap_unload(t, p) \ (*(t)->_dmamap_unload)((t)->_cookie, (p)) #define bus_dmamap_sync(t, p, o, l, ops) \ (void)((t)->_dmamap_sync ? \ (*(t)->_dmamap_sync)((t)->_cookie, (p), (o), (l), (ops)) : (void)0) #define bus_dmamem_alloc(t, s, a, b, sg, n, r, f) \ (*(t)->_dmamem_alloc)((t)->_cookie, (s), (a), (b), (sg), (n), (r), (f)) #define bus_dmamem_free(t, sg, n) \ (*(t)->_dmamem_free)((t)->_cookie, (sg), (n)) #define bus_dmamem_map(t, sg, n, s, k, f) \ (*(t)->_dmamem_map)((t)->_cookie, (sg), (n), (s), (k), (f)) #define bus_dmamem_unmap(t, k, s) \ (*(t)->_dmamem_unmap)((t)->_cookie, (k), (s)) #define bus_dmamem_mmap(t, sg, n, o, p, f) \ (*(t)->_dmamem_mmap)((t)->_cookie, (sg), (n), (o), (p), (f)) /* * bus_dmamap_t * * Describes a DMA mapping. */ struct hppa_bus_dmamap { /* * PRIVATE MEMBERS: not for use by machine-independent code. */ bus_size_t _dm_size; /* largest DMA transfer mappable */ int _dm_segcnt; /* number of segs this map can map */ bus_size_t _dm_maxsegsz; /* largest possible segment */ bus_size_t _dm_boundary; /* don't cross this */ int _dm_flags; /* misc. flags */ void *_dm_cookie; /* cookie for bus-specific functions */ /* * PUBLIC MEMBERS: these are used by machine-independent code. */ bus_size_t dm_mapsize; /* size of the mapping */ int dm_nsegs; /* # valid segments in mapping */ bus_dma_segment_t dm_segs[1]; /* segments; variable length */ }; #endif /* _MACHINE_BUS_H_ */
MarginC/kame
netbsd/sys/arch/hp700/include/bus.h
C
bsd-3-clause
19,004
from django.core.management.base import BaseCommand from dojo.models import System_Settings class Command(BaseCommand): help = 'Updates product grade calculation' def handle(self, *args, **options): code = """def grade_product(crit, high, med, low): health=100 if crit > 0: health = 40 health = health - ((crit - 1) * 5) if high > 0: if health == 100: health = 60 health = health - ((high - 1) * 3) if med > 0: if health == 100: health = 80 health = health - ((med - 1) * 2) if low > 0: if health == 100: health = 95 health = health - low if health < 5: health = 5 return health """ system_settings = System_Settings.objects.get(id=1) system_settings.product_grade = code system_settings.save()
rackerlabs/django-DefectDojo
dojo/management/commands/system_settings.py
Python
bsd-3-clause
1,040
package scalaxy.streams.benchmark.jmh import java.util.concurrent.TimeUnit import org.openjdk.jmh.annotations._ trait BaseState { @Param(Array("1000", "1000000")) var size: Int = 0 } @State(Scope.Thread) class ArrayState extends BaseState { var intArray: Array[Int] = _ var tup2Array: Array[(Int, Int)] = _ var tup3Array: Array[(Int, Int, Int)] = _ @Setup def init { intArray = Array.tabulate(size)(i => i) tup2Array = Array.tabulate(size)(i => (i, i * 10)) tup3Array = Array.tabulate(size)(i => (i, i * 10, i * 100)) } } @State(Scope.Thread) class ListState extends BaseState { var intList: List[Int] = _ var tup2List: List[(Int, Int)] = _ var tup3List: List[(Int, Int, Int)] = _ @Setup def init { intList = Array.tabulate(size)(i => i).toList tup2List = Array.tabulate(size)(i => (i, i * 10)).toList tup3List = Array.tabulate(size)(i => (i, i * 10, i * 100)).toList } } @State(Scope.Thread) class RangeState extends BaseState
nativelibs4java/scalaxy-streams
Resources/Benchmarks/States.scala
Scala
bsd-3-clause
988
// SDLHmiZoneCapabilities.h // #import "SDLEnum.h" /** * Specifies HMI Zones in the vehicle. Used in RegisterAppInterfaceResponse * * @since SDL 1.0 */ typedef SDLEnum SDLHMIZoneCapabilities NS_TYPED_ENUM; /** * Indicates HMI available for front seat passengers. */ extern SDLHMIZoneCapabilities const SDLHMIZoneCapabilitiesFront; /** * Indicates HMI available for rear seat passengers. */ extern SDLHMIZoneCapabilities const SDLHMIZoneCapabilitiesBack;
smartdevicelink/sdl_ios
SmartDeviceLink/public/SDLHMIZoneCapabilities.h
C
bsd-3-clause
468
""" Author: Dr. John T. Hwang <hwangjt@umich.edu> This package is distributed under New BSD license. Full-factorial sampling. """ import numpy as np from smt.sampling_methods.sampling_method import SamplingMethod class FullFactorial(SamplingMethod): def _initialize(self): self.options.declare( "weights", values=None, types=(list, np.ndarray), desc="relative sampling weights for each nx dimensions", ) self.options.declare( "clip", default=False, types=bool, desc="round number of samples to the sampling number product of each nx dimensions (> asked nt)", ) def _compute(self, nt): """ Compute the requested number of sampling points. Arguments --------- nt : int Number of points requested. Returns ------- ndarray[nt, nx] The sampling locations in the input space. """ xlimits = self.options["xlimits"] nx = xlimits.shape[0] if self.options["weights"] is None: weights = np.ones(nx) / nx else: weights = np.atleast_1d(self.options["weights"]) weights /= np.sum(weights) num_list = np.ones(nx, int) while np.prod(num_list) < nt: ind = np.argmax(weights - num_list / np.sum(num_list)) num_list[ind] += 1 lins_list = [np.linspace(0.0, 1.0, num_list[kx]) for kx in range(nx)] x_list = np.meshgrid(*lins_list, indexing="ij") if self.options["clip"]: nt = np.prod(num_list) x = np.zeros((nt, nx)) for kx in range(nx): x[:, kx] = x_list[kx].reshape(np.prod(num_list))[:nt] return x
bouhlelma/smt
smt/sampling_methods/full_factorial.py
Python
bsd-3-clause
1,806
{% comment %} This is how I setup a large slideshow for something like a home page. Most of the magic happens in the css and js {% endcomment %} {% if slides %} <div id="slideshow"> <div class="slides"> {% for slide in slides %} <div class="slide"> <div class="slideshow_image"><img src="{{ slide.image.display_image.url }}" alt="{{ slide.name }}"></div> <div class="slideshow_article"> <h3>{{ slide.name }}</h3> <p>{{ slide.body }}</p> {% if slide.url %} <p class="slideshow_link"><a href="{{ slide.url }}">{{ slide.url_text }}</a></p> {% endif %} </div> </div> {% endfor %} </div> </div> {% endif %}
davemerwin/django-slideshow
slideshow/templates/slideshow/slideshow.html
HTML
bsd-3-clause
934
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // MediaStreamManager is used to open/enumerate media capture devices (video // supported now). Call flow: // 1. GenerateStream is called when a render process wants to use a capture // device. // 2. MediaStreamManager will ask MediaStreamUIController for permission to // use devices and for which device to use. // 3. MediaStreamManager will request the corresponding media device manager(s) // to enumerate available devices. The result will be given to // MediaStreamUIController. // 4. MediaStreamUIController will, by posting the request to UI, let the // users to select which devices to use and send callback to // MediaStreamManager with the result. // 5. MediaStreamManager will call the proper media device manager to open the // device and let the MediaStreamRequester know it has been done. // If either user or test harness selects --use-fake-device-for-media-stream, // a fake video device or devices are used instead of real ones. // When enumeration and open are done in separate operations, // MediaStreamUIController is not involved as in steps. #ifndef CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_ #define CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_ #include <list> #include <set> #include <string> #include <utility> #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/power_monitor/power_observer.h" #include "base/system_monitor/system_monitor.h" #include "base/threading/thread.h" #include "content/browser/renderer_host/media/audio_output_device_enumerator.h" #include "content/browser/renderer_host/media/media_stream_provider.h" #include "content/common/content_export.h" #include "content/common/media/media_stream_options.h" #include "content/public/browser/media_request_state.h" #include "content/public/browser/resource_context.h" namespace media { class AudioManager; } namespace content { class AudioInputDeviceManager; class AudioOutputDeviceEnumerator; class BrowserContext; class FakeMediaStreamUIProxy; class MediaStreamDeviceSettings; class MediaStreamRequester; class MediaStreamUIProxy; class VideoCaptureManager; // MediaStreamManager is used to generate and close new media devices, not to // start the media flow. The classes requesting new media streams are answered // using MediaStreamRequester. class CONTENT_EXPORT MediaStreamManager : public MediaStreamProviderListener, public base::MessageLoop::DestructionObserver, public base::PowerObserver, public base::SystemMonitor::DevicesChangedObserver { public: // Callback to deliver the result of a media request. typedef base::Callback<void(const MediaStreamDevices& devices, scoped_ptr<MediaStreamUIProxy> ui)> MediaRequestResponseCallback; // Adds |message| to native logs for outstanding device requests, for use by // render processes hosts whose corresponding render processes are requesting // logging from webrtcLoggingPrivate API. Safe to call from any thread. static void SendMessageToNativeLog(const std::string& message); explicit MediaStreamManager(media::AudioManager* audio_manager); ~MediaStreamManager() override; // Used to access VideoCaptureManager. VideoCaptureManager* video_capture_manager(); // Used to access AudioInputDeviceManager. AudioInputDeviceManager* audio_input_device_manager(); // Used to access AudioOutputDeviceEnumerator. AudioOutputDeviceEnumerator* audio_output_device_enumerator(); // Creates a new media access request which is identified by a unique string // that's returned to the caller. This will trigger the infobar and ask users // for access to the device. |render_process_id| and |render_frame_id| are // used to determine where the infobar will appear to the user. |callback| is // used to send the selected device to the clients. An empty list of device // will be returned if the users deny the access. std::string MakeMediaAccessRequest( int render_process_id, int render_frame_id, int page_request_id, const StreamOptions& options, const GURL& security_origin, const MediaRequestResponseCallback& callback); // GenerateStream opens new media devices according to |components|. It // creates a new request which is identified by a unique string that's // returned to the caller. |render_process_id| and |render_frame_id| are used // to determine where the infobar will appear to the user. void GenerateStream(MediaStreamRequester* requester, int render_process_id, int render_frame_id, const ResourceContext::SaltCallback& sc, int page_request_id, const StreamOptions& components, const GURL& security_origin, bool user_gesture); void CancelRequest(int render_process_id, int render_frame_id, int page_request_id); // Cancel an open request identified by |label|. virtual void CancelRequest(const std::string& label); // Cancel all requests for the given |render_process_id|. void CancelAllRequests(int render_process_id); // Closes the stream device for a certain render frame. The stream must have // been opened by a call to GenerateStream. void StopStreamDevice(int render_process_id, int render_frame_id, const std::string& device_id); // Gets a list of devices of |type|, which must be MEDIA_DEVICE_AUDIO_CAPTURE // or MEDIA_DEVICE_VIDEO_CAPTURE. // The request is identified using the string returned to the caller. // When the |requester| is NULL, MediaStreamManager will enumerate both audio // and video devices and also start monitoring device changes, such as // plug/unplug. The new device lists will be delivered via media observer to // MediaCaptureDevicesDispatcher. virtual std::string EnumerateDevices(MediaStreamRequester* requester, int render_process_id, int render_frame_id, const ResourceContext::SaltCallback& sc, int page_request_id, MediaStreamType type, const GURL& security_origin); // Open a device identified by |device_id|. |type| must be either // MEDIA_DEVICE_AUDIO_CAPTURE or MEDIA_DEVICE_VIDEO_CAPTURE. // The request is identified using string returned to the caller. void OpenDevice(MediaStreamRequester* requester, int render_process_id, int render_frame_id, const ResourceContext::SaltCallback& sc, int page_request_id, const std::string& device_id, MediaStreamType type, const GURL& security_origin); // Finds and returns the device id corresponding to the given // |source_id|. Returns true if there was a raw device id that matched the // given |source_id|, false if nothing matched it. bool TranslateSourceIdToDeviceId(MediaStreamType stream_type, const ResourceContext::SaltCallback& rc, const GURL& security_origin, const std::string& source_id, std::string* device_id) const; // Called by UI to make sure the device monitor is started so that UI receive // notifications about device changes. void EnsureDeviceMonitorStarted(); // Implements MediaStreamProviderListener. void Opened(MediaStreamType stream_type, int capture_session_id) override; void Closed(MediaStreamType stream_type, int capture_session_id) override; void DevicesEnumerated(MediaStreamType stream_type, const StreamDeviceInfoArray& devices) override; void Aborted(MediaStreamType stream_type, int capture_session_id) override; // Implements base::SystemMonitor::DevicesChangedObserver. void OnDevicesChanged(base::SystemMonitor::DeviceType device_type) override; // Returns all devices currently opened by a request with label |label|. // If no request with |label| exist, an empty array is returned. StreamDeviceInfoArray GetDevicesOpenedByRequest( const std::string& label) const; // This object gets deleted on the UI thread after the IO thread has been // destroyed. So we need to know when IO thread is being destroyed so that // we can delete VideoCaptureManager and AudioInputDeviceManager. Normally // this is handled by // base::MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop. // But for some tests which use TestBrowserThreadBundle, we need to call // WillDestroyCurrentMessageLoop explicitly because the notification happens // too late. (see http://crbug.com/247525#c14). void WillDestroyCurrentMessageLoop() override; // Sends log messages to the render process hosts whose corresponding render // processes are making device requests, to be used by the // webrtcLoggingPrivate API if requested. void AddLogMessageOnIOThread(const std::string& message); // base::PowerObserver overrides. void OnSuspend() override; void OnResume() override; // Called by the tests to specify a fake UI that should be used for next // generated stream (or when using --use-fake-ui-for-media-stream). void UseFakeUIForTests(scoped_ptr<FakeMediaStreamUIProxy> fake_ui); // Generates a hash of a device's unique ID usable by one // particular security origin. static std::string GetHMACForMediaDeviceID( const ResourceContext::SaltCallback& sc, const GURL& security_origin, const std::string& raw_unique_id); // Convenience method to check if |device_guid| is an HMAC of // |raw_device_id| for |security_origin|. static bool DoesMediaDeviceIDMatchHMAC( const ResourceContext::SaltCallback& sc, const GURL& security_origin, const std::string& device_guid, const std::string& raw_unique_id); private: // Contains all data needed to keep track of requests. class DeviceRequest; // Cache enumerated device list. struct EnumerationCache { EnumerationCache(); ~EnumerationCache(); bool valid; StreamDeviceInfoArray devices; }; // |DeviceRequests| is a list to ensure requests are processed in the order // they arrive. The first member of the pair is the label of the // |DeviceRequest|. using LabeledDeviceRequest = std::pair<std::string, DeviceRequest*>; using DeviceRequests = std::list<LabeledDeviceRequest>; // Initializes the device managers on IO thread. Auto-starts the device // thread and registers this as a listener with the device managers. void InitializeDeviceManagersOnIOThread(); // Helper for sending up-to-date device lists to media observer when a // capture device is plugged in or unplugged. void NotifyDevicesChanged(MediaStreamType stream_type, const StreamDeviceInfoArray& devices); void HandleAccessRequestResponse(const std::string& label, const MediaStreamDevices& devices, content::MediaStreamRequestResult result); void StopMediaStreamFromBrowser(const std::string& label); void DoEnumerateDevices(const std::string& label); void AudioOutputDevicesEnumerated( const AudioOutputDeviceEnumeration& device_enumeration); // Helpers. // Checks if all devices that was requested in the request identififed by // |label| has been opened and set the request state accordingly. void HandleRequestDone(const std::string& label, DeviceRequest* request); // Stop the use of the device associated with |session_id| of type |type| in // all |requests_|. The device is removed from the request. If a request /// doesn't use any devices as a consequence, the request is deleted. void StopDevice(MediaStreamType type, int session_id); // Calls the correct capture manager and close the device with |session_id|. // All requests that uses the device are updated. void CloseDevice(MediaStreamType type, int session_id); // Returns true if a request for devices has been completed and the devices // has either been opened or an error has occurred. bool RequestDone(const DeviceRequest& request) const; MediaStreamProvider* GetDeviceManager(MediaStreamType stream_type); void StartEnumeration(DeviceRequest* request); std::string AddRequest(DeviceRequest* request); DeviceRequest* FindRequest(const std::string& label) const; void DeleteRequest(const std::string& label); void ClearEnumerationCache(EnumerationCache* cache); // Returns true if the |cache| is invalid, false if it's invalid or if // the |stream_type| is MEDIA_NO_SERVICE. // On Android, this function will always return true for // MEDIA_DEVICE_AUDIO_CAPTURE since we don't have a SystemMonitor to tell // us about audio device changes. bool EnumerationRequired(EnumerationCache* cache, MediaStreamType type); // Prepare the request with label |label| by starting device enumeration if // needed. void SetupRequest(const std::string& label); // Prepare |request| of type MEDIA_DEVICE_AUDIO_CAPTURE and/or // MEDIA_DEVICE_VIDEO_CAPTURE for being posted to the UI by parsing // StreamOptions::Constraints for requested device IDs. bool SetupDeviceCaptureRequest(DeviceRequest* request); // Prepare |request| of type MEDIA_TAB_AUDIO_CAPTURE and/or // MEDIA_TAB_VIDEO_CAPTURE for being posted to the UI by parsing // StreamOptions::Constraints for requested tab capture IDs. bool SetupTabCaptureRequest(DeviceRequest* request); // Prepare |request| of type MEDIA_DESKTOP_AUDIO_CAPTURE and/or // MEDIA_DESKTOP_VIDEO_CAPTURE for being posted to the UI by parsing // StreamOptions::Constraints for the requested desktop ID. bool SetupScreenCaptureRequest(DeviceRequest* request); // Called when a request has been setup and devices have been enumerated if // needed. void PostRequestToUI(const std::string& label, DeviceRequest* request); // Returns true if a device with |device_id| has already been requested with // a render procecss_id and render_frame_id and type equal to the the values // in |request|. If it has been requested, |device_info| contain information // about the device. bool FindExistingRequestedDeviceInfo( const DeviceRequest& new_request, const MediaStreamDevice& new_device_info, StreamDeviceInfo* existing_device_info, MediaRequestState* existing_request_state) const; void FinalizeGenerateStream(const std::string& label, DeviceRequest* request); void FinalizeRequestFailed(const std::string& label, DeviceRequest* request, content::MediaStreamRequestResult result); void FinalizeOpenDevice(const std::string& label, DeviceRequest* request); void FinalizeMediaAccessRequest(const std::string& label, DeviceRequest* request, const MediaStreamDevices& devices); void FinalizeEnumerateDevices(const std::string& label, DeviceRequest* request); void HandleCheckMediaAccessResponse(const std::string& label, bool have_access); // This method is called when an audio or video device is plugged in or // removed. It make sure all MediaStreams that use a removed device is // stopped and that the render process is notified. |old_devices| is the list // of previously available devices. |new_devices| is the new // list of currently available devices. void StopRemovedDevices(const StreamDeviceInfoArray& old_devices, const StreamDeviceInfoArray& new_devices); // Helper method used by StopRemovedDevices to stop the use of a certain // device. void StopRemovedDevice(const MediaStreamDevice& device); // Helpers to start and stop monitoring devices. void StartMonitoring(); void StopMonitoring(); #if defined(OS_MACOSX) void StartMonitoringOnUIThread(); #endif // Finds the requested device id from constraints. The requested device type // must be MEDIA_DEVICE_AUDIO_CAPTURE or MEDIA_DEVICE_VIDEO_CAPTURE. bool GetRequestedDeviceCaptureId(const DeviceRequest* request, MediaStreamType type, std::string* device_id) const; void TranslateDeviceIdToSourceId(DeviceRequest* request, MediaStreamDevice* device); // Handles the callback from MediaStreamUIProxy to receive the UI window id, // used for excluding the notification window in desktop capturing. void OnMediaStreamUIWindowId(MediaStreamType video_type, StreamDeviceInfoArray devices, gfx::NativeViewId window_id); #if defined(OS_CHROMEOS) // Ensures that we have checked for presence of a keyboard mic. This is only // done once. This function should be called before posting a request on the // UI thread. void EnsureKeyboardMicChecked(); // Checks if the system has a keyboard mic, and if so, inform the audio // manager via SetKeyboardMicOnDeviceThread(). void CheckKeyboardMicOnUIThread(); // Tells the audio mananger that the system supports a keyboard mic. void SetKeyboardMicOnDeviceThread(); #endif // Task runner shared by VideoCaptureManager and AudioInputDeviceManager and // used for enumerating audio output devices. // Note: Enumeration tasks may take seconds to complete so must never be run // on any of the BrowserThreads (UI, IO, etc). See http://crbug.com/256945. scoped_refptr<base::SingleThreadTaskRunner> device_task_runner_; media::AudioManager* const audio_manager_; // not owned scoped_refptr<AudioInputDeviceManager> audio_input_device_manager_; scoped_refptr<VideoCaptureManager> video_capture_manager_; scoped_ptr<AudioOutputDeviceEnumerator> audio_output_device_enumerator_; #if defined(OS_WIN) base::Thread video_capture_thread_; #endif // Indicator of device monitoring state. bool monitoring_started_; #if defined(OS_CHROMEOS) // Flag that's set when we have checked if the system has a keyboard mic. We // only need to check it once, and not when constructing since that will // affect startup time. // Must be accessed on the IO thread; bool has_checked_keyboard_mic_; #endif // Stores most recently enumerated device lists. The cache is cleared when // monitoring is stopped or there is no request for that type of device. EnumerationCache audio_enumeration_cache_; EnumerationCache video_enumeration_cache_; // Keeps track of live enumeration commands sent to VideoCaptureManager or // AudioInputDeviceManager, in order to only enumerate when necessary. int active_enumeration_ref_count_[NUM_MEDIA_TYPES]; // All non-closed request. Must be accessed on IO thread. DeviceRequests requests_; bool use_fake_ui_; scoped_ptr<FakeMediaStreamUIProxy> fake_ui_; DISALLOW_COPY_AND_ASSIGN(MediaStreamManager); }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_MEDIA_MEDIA_STREAM_MANAGER_H_
Bysmyyr/chromium-crosswalk
content/browser/renderer_host/media/media_stream_manager.h
C
bsd-3-clause
19,666
/* filelist.cpp Файловая панель */ /* Copyright © 1996 Eugene Roshal Copyright © 2000 Far Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // BUGBUG #include "platform.headers.hpp" // Self: #include "filelist.hpp" // Internal: #include "keyboard.hpp" #include "flink.hpp" #include "keys.hpp" #include "macroopcode.hpp" #include "ctrlobj.hpp" #include "filefilter.hpp" #include "dialog.hpp" #include "cmdline.hpp" #include "manager.hpp" #include "filepanels.hpp" #include "help.hpp" #include "fileedit.hpp" #include "namelist.hpp" #include "fileview.hpp" #include "copy.hpp" #include "history.hpp" #include "qview.hpp" #include "preservelongname.hpp" #include "scrbuf.hpp" #include "filemasks.hpp" #include "interf.hpp" #include "message.hpp" #include "clipboard.hpp" #include "delete.hpp" #include "stddlg.hpp" #include "print.hpp" #include "mkdir.hpp" #include "setattr.hpp" #include "filetype.hpp" #include "execute.hpp" #include "fnparce.hpp" #include "datetime.hpp" #include "dirinfo.hpp" #include "pathmix.hpp" #include "network.hpp" #include "dirmix.hpp" #include "strmix.hpp" #include "exitcode.hpp" #include "panelmix.hpp" #include "processname.hpp" #include "mix.hpp" #include "elevation.hpp" #include "uuids.far.hpp" #include "uuids.far.dialogs.hpp" #include "plugins.hpp" #include "lang.hpp" #include "language.hpp" #include "taskbar.hpp" #include "fileowner.hpp" #include "colormix.hpp" #include "keybar.hpp" #include "panelctype.hpp" #include "diskmenu.hpp" #include "string_utils.hpp" #include "cvtname.hpp" #include "vmenu.hpp" #include "vmenu2.hpp" #include "filefilterparams.hpp" #include "desktop.hpp" #include "string_sort.hpp" #include "global.hpp" #include "log.hpp" // Platform: #include "platform.fs.hpp" // Common: #include "common/enum_tokens.hpp" #include "common/rel_ops.hpp" #include "common/scope_exit.hpp" #include "common/string_utils.hpp" #include "common/utility.hpp" #include "common/view/zip.hpp" // External: #include "format.hpp" //---------------------------------------------------------------------------- static_assert(static_cast<size_t>(panel_sort::BY_USER) == static_cast<size_t>(OPENPANELINFO_SORTMODES::SM_USER)); constexpr auto operator+(panel_sort const Value) noexcept { return std::to_underlying(Value); } static const struct { lng Label; int MenuPosition; far_key_code MenuKey; std::initializer_list<std::pair<panel_sort, sort_order>> DefaultLayers; } SortModes[] { { lng::MMenuUnsorted, 5, KEY_CTRLF7, { { panel_sort::UNSORTED, sort_order::ascend, }, }, }, { lng::MMenuSortByName, 0, KEY_CTRLF3, { { panel_sort::BY_NAME, sort_order::ascend, }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByExt, 2, KEY_CTRLF4, { { panel_sort::BY_EXT, sort_order::ascend, }, { panel_sort::BY_NAMEONLY, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByWrite, 3, KEY_CTRLF5, { { panel_sort::BY_MTIME, sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByCreation, 6, KEY_CTRLF8, { { panel_sort::BY_CTIME, sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByAccess, 7, KEY_CTRLF9, { { panel_sort::BY_ATIME, sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortBySize, 4, KEY_CTRLF6, { { panel_sort::BY_SIZE, sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByDiz, 9, KEY_CTRLF10, { { panel_sort::BY_DIZ, sort_order::ascend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByOwner, 10, KEY_CTRLF11, { { panel_sort::BY_OWNER, sort_order::ascend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByAllocatedSize, 11, NO_KEY, { { panel_sort::BY_COMPRESSEDSIZE,sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByNumLinks, 12, NO_KEY, { { panel_sort::BY_NUMLINKS, sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByNumStreams, 13, NO_KEY, { { panel_sort::BY_NUMSTREAMS, sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByStreamsSize, 14, NO_KEY, { { panel_sort::BY_STREAMSSIZE, sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByNameOnly, 1, NO_KEY, { { panel_sort::BY_NAMEONLY, sort_order::ascend, }, { panel_sort::BY_EXT, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, { lng::MMenuSortByChange, 8, NO_KEY, { { panel_sort::BY_CHTIME, sort_order::descend, }, { panel_sort::BY_NAME, sort_order::ascend }, { panel_sort::UNSORTED, sort_order::ascend }, }, }, }; static_assert(std::size(SortModes) == static_cast<size_t>(panel_sort::COUNT)); static constexpr auto order_indicator(sort_order const Order) { switch (Order) { default: case sort_order::keep: return L'='; case sort_order::ascend: return L'▲'; case sort_order::descend: return L'▼'; } } span<std::pair<panel_sort, sort_order> const> default_sort_layers(panel_sort const SortMode) { return SortModes[static_cast<size_t>(SortMode)].DefaultLayers; } template<typename T> auto compare_numbers(T const First, T const Second) { return First < Second? -1 : First != Second; } static auto compare_time(os::chrono::time_point First, os::chrono::time_point Second) { return compare_numbers(First, Second); } // FAT Last Write time is rounded up to the even number of seconds, e.g. 2s 1ms -> 4s static auto to_fat_write_time(os::chrono::time_point Point) { return (Point.time_since_epoch() + 2s - 1ns) / 2s; } // However, people also use this function with FTP, which rounds down to whole seconds static auto to_whole_seconds(os::chrono::time_point Point) { return Point.time_since_epoch() / 1s; } // The ultimate question here is "can these times be considered 'equal'", // so we take an opportunistic approach and try both methods: static auto compare_fat_write_time(os::chrono::time_point First, os::chrono::time_point Second) { if (!compare_numbers(to_fat_write_time(First), to_fat_write_time(Second))) return 0; if (!compare_numbers(to_whole_seconds(First), to_whole_seconds(Second))) return 0; return compare_time(First, Second); } enum SELECT_MODES { SELECT_INVERT, SELECT_INVERTALL, SELECT_INVERTFILES, SELECT_ADD, SELECT_REMOVE, SELECT_ADDEXT, SELECT_REMOVEEXT, SELECT_ADDNAME, SELECT_REMOVENAME, SELECT_ADDMASK, SELECT_REMOVEMASK, SELECT_INVERTMASK, }; namespace custom_sort { static FileList* FileListPtr; static void FileListToSortingPanelItem(const FileListItem *arr, int index, SortingPanelItem* ppi) { const auto& fi = arr[index]; auto& pi = *ppi; pi.FileName = fi.FileName.c_str(); //! CHANGED pi.AlternateFileName = fi.AlternateFileName().c_str(); //! CHANGED pi.FileSize=fi.FileSize; pi.AllocationSize=fi.AllocationSize; pi.FileAttributes=fi.Attributes; pi.LastWriteTime = os::chrono::nt_clock::to_filetime(fi.LastWriteTime); pi.CreationTime = os::chrono::nt_clock::to_filetime(fi.CreationTime); pi.LastAccessTime = os::chrono::nt_clock::to_filetime(fi.LastAccessTime); pi.ChangeTime = os::chrono::nt_clock::to_filetime(fi.ChangeTime); pi.Flags=fi.UserFlags; if (fi.Selected) pi.Flags|=PPIF_SELECTED; pi.CustomColumnData=fi.CustomColumns.data(); pi.CustomColumnNumber=fi.CustomColumns.size(); pi.Description=fi.DizText; //BUGBUG??? pi.UserData = fi.UserData; pi.CRC32=fi.CRC32; pi.Position=fi.Position; //! CHANGED pi.SortGroup=fi.SortGroup - DEFAULT_SORT_GROUP; //! CHANGED pi.NumberOfLinks = fi.IsNumberOfLinksRead() || FileListPtr->IsColumnDisplayed(column_type::links_number)?fi.NumberOfLinks(FileListPtr) : 0; pi.Owner = fi.IsOwnerRead() || FileListPtr->IsColumnDisplayed(column_type::owner)? EmptyToNull(fi.Owner(FileListPtr)) : nullptr; pi.NumberOfStreams = fi.IsNumberOfStreamsRead() || FileListPtr->IsColumnDisplayed(column_type::streams_number)? fi.NumberOfStreams(FileListPtr) : 0; pi.StreamsSize = fi.IsStreamsSizeRead() || FileListPtr->IsColumnDisplayed(column_type::streams_size)? fi.StreamsSize(FileListPtr) : 0; } struct CustomSort { unsigned int *Positions; const FileListItem *Items; size_t ItemsCount; void(*FileListToSortingPanelItem)(const FileListItem*, int, SortingPanelItem*); int ListSortGroups; int ListSelectedFirst; int ListDirectoriesFirst; int ListSortMode; int RevertSorting; int Reserved[2]; HANDLE hSortPlugin; }; static bool SortFileList(CustomSort* cs, wchar_t* indicator) { FarMacroValue values[]={cs}; FarMacroCall fmc={sizeof(FarMacroCall),std::size(values),values,nullptr,nullptr}; OpenMacroPluginInfo info={MCT_PANELSORT,&fmc}; void *ptr; if (!Global->CtrlObject->Plugins->CallPlugin(Global->Opt->KnownIDs.Luamacro.Id, OPEN_LUAMACRO, &info, &ptr) || !ptr) return false; indicator[0] = info.Ret.Values[0].String[0]; indicator[1] = info.Ret.Values[0].String[1]; return true; } static bool CanSort(int SortMode) { FarMacroValue values[] = {static_cast<double>(SortMode)}; FarMacroCall fmc = {sizeof(FarMacroCall),std::size(values),values,nullptr,nullptr}; OpenMacroPluginInfo info = {MCT_CANPANELSORT,&fmc}; void *ptr; return Global->CtrlObject->Plugins->CallPlugin(Global->Opt->KnownIDs.Luamacro.Id, OPEN_LUAMACRO, &info, &ptr) && ptr; } } struct FileList::PluginsListItem { NONCOPYABLE(PluginsListItem); MOVE_CONSTRUCTIBLE(PluginsListItem); PluginsListItem(std::unique_ptr<plugin_panel>&& hPlugin, string_view const HostFile, bool Modified, int PrevViewMode, panel_sort PrevSortMode, bool PrevSortOrder, bool PrevDirectoriesFirst, const PanelViewSettings& PrevViewSettings): m_Plugin(std::move(hPlugin)), m_HostFile(HostFile), m_Modified(Modified), m_PrevViewMode(PrevViewMode), m_PrevSortMode(PrevSortMode), m_PrevSortOrder(PrevSortOrder), m_PrevDirectoriesFirst(PrevDirectoriesFirst), m_PrevViewSettings(PrevViewSettings.clone()) { } std::unique_ptr<plugin_panel> m_Plugin; string m_HostFile; bool m_Modified; int m_PrevViewMode; panel_sort m_PrevSortMode; bool m_PrevSortOrder; bool m_PrevDirectoriesFirst; PanelViewSettings m_PrevViewSettings; }; FileListItem::FileListItem() { m_Owner = values::uninitialised(wchar_t()); } static string GetItemFullName(const FileListItem& Item, const FileList* Owner) { return path::join(Owner->GetCurDir(), IsParentDirectory(Item)? string{} : Item.FileName); } bool FileListItem::IsNumberOfLinksRead() const { return m_NumberOfLinks != values::uninitialised(m_NumberOfLinks); } DWORD FileListItem::NumberOfLinks(const FileList* Owner) const { if (IsNumberOfLinksRead()) return m_NumberOfLinks; if (Attributes & FILE_ATTRIBUTE_DIRECTORY || !Owner->HardlinksSupported()) { m_NumberOfLinks = 1; } else { SCOPED_ACTION(elevation::suppress); const auto Hardlinks = GetNumberOfLinks(GetItemFullName(*this, Owner)); static_assert(std::is_same_v<decltype(m_NumberOfLinks), DWORD>); m_NumberOfLinks = Hardlinks? static_cast<DWORD>(*Hardlinks) : values::unknown(m_NumberOfLinks); } return m_NumberOfLinks; } static void GetStreamsCountAndSize(const FileList* Owner, const FileListItem& Item, unsigned long long& StreamsSize, DWORD& NumberOfStreams, bool Supported) { if (!Supported) { StreamsSize = Item.FileSize; NumberOfStreams = 1; } else { SCOPED_ACTION(elevation::suppress); size_t StreamsCount = 0; if (EnumStreams(GetItemFullName(Item, Owner), StreamsSize, StreamsCount)) { static_assert(std::is_same_v<decltype(NumberOfStreams), DWORD&>); NumberOfStreams = static_cast<DWORD>(StreamsCount); } else { StreamsSize = FileListItem::values::unknown(StreamsSize); NumberOfStreams = FileListItem::values::unknown(NumberOfStreams); } } } bool FileListItem::IsNumberOfStreamsRead() const { return m_NumberOfStreams != values::uninitialised(m_NumberOfStreams); } DWORD FileListItem::NumberOfStreams(const FileList* Owner) const { if (IsNumberOfStreamsRead()) return m_NumberOfStreams; GetStreamsCountAndSize(Owner, *this, m_StreamsSize, m_NumberOfStreams, Owner->StreamsSupported()); return m_NumberOfStreams; } bool FileListItem::IsStreamsSizeRead() const { return m_StreamsSize != values::uninitialised(m_StreamsSize); } unsigned long long FileListItem::StreamsSize(const FileList* Owner) const { if (IsStreamsSizeRead()) return m_StreamsSize; GetStreamsCountAndSize(Owner, *this, m_StreamsSize, m_NumberOfStreams, Owner->StreamsSupported()); return m_StreamsSize; } bool FileListItem::IsOwnerRead() const { return !(m_Owner.size() == 1 && m_Owner.front() == values::uninitialised(wchar_t())); } const string& FileListItem::Owner(const FileList* Owner) const { if (IsOwnerRead()) return m_Owner; if (Owner->GetMode() == panel_mode::NORMAL_PANEL) { SCOPED_ACTION(elevation::suppress); if (!GetFileOwner(Owner->GetComputerName(), GetItemFullName(*this, Owner), m_Owner)) { // One try is enough m_Owner.clear(); } } else { m_Owner.clear(); } return m_Owner; } bool FileListItem::IsContentDataRead() const { return m_ContentData != nullptr; // bad } const std::unique_ptr<content_data>& FileListItem::ContentData(const FileList* Owner) const { if (IsContentDataRead()) return m_ContentData; m_ContentData = Owner->GetContentData(GetItemFullName(*this, Owner)); return m_ContentData; } const string& FileListItem::AlternateOrNormal(bool Alternate) const { return Alternate? AlternateFileName() : FileName; } struct FileList::PrevDataItem { NONCOPYABLE(PrevDataItem); MOVE_CONSTRUCTIBLE(PrevDataItem); PrevDataItem(string rhsPrevName, list_data&& rhsPrevListData, int rhsPrevTopFile): strPrevName(std::move(rhsPrevName)), PrevListData(std::move(rhsPrevListData)), PrevTopFile(rhsPrevTopFile) { } string strPrevName; list_data PrevListData; int PrevTopFile; }; file_panel_ptr FileList::create(window_ptr Owner) { return std::make_shared<FileList>(private_tag(), Owner); } FileList::FileList(private_tag, window_ptr Owner): Panel(std::move(Owner)), m_BackgroundUpdater(std::make_unique<background_updater>(this)) { if (const auto& data = msg(lng::MPanelBracketsForLongName); data.size() > 1) { *openBracket = data[0]; *closeBracket = data[1]; } m_CurDir = os::fs::GetCurrentDirectory(); strOriginalCurDir = m_CurDir; m_SortMode = panel_sort::BY_NAME; m_ViewSettings = Global->Opt->ViewSettings[m_ViewMode].clone(); PreparePanelView(); } FileList::~FileList() { if (m_PanelMode == panel_mode::PLUGIN_PANEL) while (PopPlugin(FALSE)) ; FileList::StopFSWatcher(); FileList::ClearAllItem(); m_ListData.clear(); } FileList::list_data& FileList::list_data::operator=(FileList::list_data&& rhs) noexcept { clear(); Items = std::move(rhs.Items); rhs.Items.clear(); m_Plugin = std::move(rhs.m_Plugin); rhs.m_Plugin = {}; return *this; } void FileList::list_data::clear() { for (auto& i: Items) { if (m_Plugin) { FreePluginPanelItemUserData(m_Plugin, i.UserData); if (i.DeleteDiz) delete[] i.DizText; } for (const auto& Column: i.CustomColumns) { delete[] Column; } i.CustomColumns.clear(); } Items.clear(); m_Plugin = nullptr; } void FileList::ToBegin() { m_CurFile = 0; ShowFileList(); } void FileList::ToEnd() { m_CurFile = m_ListData.empty()? 0 : static_cast<int>(m_ListData.size() - 1); ShowFileList(); } void FileList::MoveCursor(int offset) { m_CurFile = m_ListData.empty()? 0 : std::clamp(m_CurFile + offset, 0, static_cast<int>(m_ListData.size() - 1)); } void FileList::MoveCursorAndShow(int offset) { MoveCursor(offset); ShowFileList(); } void FileList::Scroll(int offset) { m_CurTopFile += offset; MoveCursorAndShow(offset); } void FileList::CorrectPosition() { if (m_ListData.empty()) { m_CurFile=m_CurTopFile=0; return; } if (m_CurTopFile+m_Stripes*m_Height > static_cast<int>(m_ListData.size())) m_CurTopFile = static_cast<int>(m_ListData.size() - m_Stripes * m_Height); if (m_CurFile<0) m_CurFile=0; if (m_CurFile > static_cast<int>(m_ListData.size() - 1)) m_CurFile = static_cast<int>(m_ListData.size() - 1); if (m_CurTopFile<0) m_CurTopFile=0; if (m_CurTopFile > static_cast<int>(m_ListData.size() - 1)) m_CurTopFile = static_cast<int>(m_ListData.size() - 1); if (m_CurFile<m_CurTopFile) m_CurTopFile=m_CurFile; if (m_CurFile>m_CurTopFile+m_Stripes*m_Height-1) m_CurTopFile=m_CurFile-m_Stripes*m_Height+1; } class list_less { public: explicit list_less(const FileList* Owner, const plugin_panel* SortPlugin, bool const IgnorePaths): m_Owner(Owner), m_ListSortMode(Owner->GetSortMode()), m_ListPanelMode(Owner->GetMode()), m_SortPlugin(SortPlugin), m_SortLayers(Global->Opt->PanelSortLayers[static_cast<size_t>(m_ListSortMode)]), m_Reverse(Owner->GetSortOrder()), m_ListSortGroups(Owner->GetSortGroups()), m_ListSelectedFirst(Owner->GetSelectedFirstMode()), m_ListDirectoriesFirst(Owner->GetDirectoriesFirst()), m_SortFolderExt(Global->Opt->SortFolderExt), m_IgnorePaths(IgnorePaths) { } bool operator()(const FileListItem& Item1, const FileListItem& Item2) const { const auto IsParentDirItem1 = IsParentDirectory(Item1); const auto IsParentDirItem2 = IsParentDirectory(Item2); if (IsParentDirItem1 && IsParentDirItem2) return Item1.Position < Item2.Position; if (IsParentDirItem1) return true; if (IsParentDirItem2) return false; if (m_ListDirectoriesFirst) { const auto IsDirItem1 = (Item1.Attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; const auto IsDirItem2 = (Item2.Attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; if (IsDirItem1 != IsDirItem2) return IsDirItem1; } if (m_ListSelectedFirst && Item1.Selected != Item2.Selected) return Item1.Selected; if (m_ListSortGroups && Item1.SortGroup != Item2.SortGroup && ( m_ListSortMode == panel_sort::BY_NAME || m_ListSortMode == panel_sort::BY_EXT || m_ListSortMode == panel_sort::BY_NAMEONLY ) ) return Item1.SortGroup < Item2.SortGroup; if (m_SortPlugin && m_ListSortMode != panel_sort::UNSORTED) { const auto& [a, b] = m_Reverse? std::tie(Item2, Item1) : std::tie(Item1, Item2); // Direct access, no copy. It's its own panel anyways. PluginPanelItemHolderRef pi1, pi2; m_Owner->FileListToPluginItem(a, pi1); m_Owner->FileListToPluginItem(b, pi2); if (const auto Result = Global->CtrlObject->Plugins->Compare(m_SortPlugin, &pi1.Item, &pi2.Item, internal_sort_mode_to_plugin(m_ListSortMode))) { if (Result != -2) return Result < 0; } } for (const auto& [ModeValue, Order]: m_SortLayers) { const auto LayerSort = static_cast<panel_sort>(ModeValue); const auto Reverse = LayerSort == m_ListSortMode || Order == sort_order::keep? m_Reverse : Order == sort_order::descend; if (const auto Result = compare(LayerSort, Reverse, Item1, Item2)) return Result < 0; } return false; } private: int compare(panel_sort const SortMode, bool const Reverse, FileListItem const& Item1, FileListItem const& Item2) const { const auto& [a, b] = Reverse? std::tie(Item2, Item1) : std::tie(Item1, Item2); const auto ignore_path_opt = [&](string_view const FullName) { return m_IgnorePaths? PointToName(FullName) : FullName; }; const auto name_ext_opt = [SortFolderExt = m_SortFolderExt](FileListItem const& i) { return SortFolderExt || !(i.Attributes & FILE_ATTRIBUTE_DIRECTORY)? name_ext(i.FileName) : std::pair(string_view(i.FileName), L""sv); }; switch (SortMode) { case panel_sort::UNSORTED: return compare_numbers(a.Position, b.Position); case panel_sort::BY_NAME: return string_sort::compare(ignore_path_opt(a.FileName), ignore_path_opt(b.FileName)); case panel_sort::BY_NAMEONLY: return string_sort::compare(ignore_path_opt(name_ext_opt(a).first), ignore_path_opt(name_ext_opt(b).first)); case panel_sort::BY_EXT: return string_sort::compare(name_ext_opt(a).second, name_ext_opt(b).second); case panel_sort::BY_MTIME: return compare_time(a.LastWriteTime, b.LastWriteTime); case panel_sort::BY_CTIME: return compare_time(a.CreationTime, b.CreationTime); case panel_sort::BY_ATIME: return compare_time(a.LastAccessTime, b.LastAccessTime); case panel_sort::BY_CHTIME: return compare_time(a.ChangeTime, b.ChangeTime); case panel_sort::BY_SIZE: return compare_numbers(a.FileSize, b.FileSize); case panel_sort::BY_DIZ: return string_sort::compare(NullToEmpty(a.DizText), NullToEmpty(b.DizText)); case panel_sort::BY_OWNER: return string_sort::compare(a.Owner(m_Owner), b.Owner(m_Owner)); case panel_sort::BY_COMPRESSEDSIZE: return compare_numbers(a.AllocationSize, b.AllocationSize); case panel_sort::BY_NUMLINKS: return compare_numbers(a.NumberOfLinks(m_Owner), b.NumberOfLinks(m_Owner)); case panel_sort::BY_NUMSTREAMS: return compare_numbers(a.NumberOfStreams(m_Owner), b.NumberOfStreams(m_Owner)); case panel_sort::BY_STREAMSSIZE: return compare_numbers(a.StreamsSize(m_Owner), b.StreamsSize(m_Owner)); default: assert(false); UNREACHABLE; } } const FileList* const m_Owner; const panel_sort m_ListSortMode; const panel_mode m_ListPanelMode; const plugin_panel* m_SortPlugin; const span<std::pair<panel_sort, sort_order>> m_SortLayers; const bool m_Reverse; bool m_ListSortGroups; bool m_ListSelectedFirst; bool m_ListDirectoriesFirst; bool m_SortFolderExt; bool m_IgnorePaths; }; void FileList::SortFileList(bool KeepPosition) { if (m_ListData.empty() || m_InsideGetFindData) return; string strCurName; if (m_SortMode == panel_sort::BY_DIZ) ReadDiz(); if (KeepPosition) { assert(m_CurFile < static_cast<int>(m_ListData.size())); strCurName = m_ListData[m_CurFile].FileName; } const auto PluginPanel = GetPluginHandle(); const auto hSortPlugin = (m_PanelMode == panel_mode::PLUGIN_PANEL && PluginPanel && PluginPanel->plugin()->has(iCompare))? PluginPanel : nullptr; // ЭТО ЕСТЬ УЗКОЕ МЕСТО ДЛЯ СКОРОСТНЫХ ХАРАКТЕРИСТИК Far Manager // при считывании директории if (m_SortMode < panel_sort::COUNT) { const auto NameColumn = std::find_if(ALL_CONST_RANGE(m_ViewSettings.PanelColumns), [](column const& i){ return i.type == column_type::name; }); const auto IgnorePaths = NameColumn != m_ViewSettings.PanelColumns.cend() && NameColumn->type_flags & COLFLAGS_NAMEONLY; list_less const Predicate(this, hSortPlugin, IgnorePaths); const auto& SortLayers = Global->Opt->PanelSortLayers[static_cast<size_t>(m_SortMode)]; if (std::any_of(ALL_CONST_RANGE(SortLayers), [](std::pair<panel_sort, sort_order> const& Layer){ return Layer.first == panel_sort::UNSORTED; })) { // Unsorted criterion is deterministic and won't report equality, thus ensuring stability std::sort(ALL_RANGE(m_ListData), Predicate); } else { std::stable_sort(ALL_RANGE(m_ListData), Predicate); } } else if (m_SortMode >= panel_sort::BY_USER) { custom_sort::CustomSort cs{}; custom_sort::FileListPtr = this; std::vector<unsigned int> Positions(m_ListData.size()); std::iota(ALL_RANGE(Positions), 0); cs.Positions = Positions.data(); cs.Items = m_ListData.data(); cs.ItemsCount = m_ListData.size(); cs.FileListToSortingPanelItem = custom_sort::FileListToSortingPanelItem; cs.ListSortGroups = m_SortGroups; cs.ListSelectedFirst = SelectedFirst; cs.ListDirectoriesFirst = m_DirectoriesFirst; cs.ListSortMode = static_cast<int>(m_SortMode); cs.RevertSorting = m_ReverseSortOrder; cs.hSortPlugin = hSortPlugin; if (custom_sort::SortFileList(&cs, CustomSortIndicator)) { apply_permutation(ALL_RANGE(m_ListData), Positions.begin()); } else { SetSortMode(panel_sort::BY_NAME); // recursive call return; } } else { LOGWARNING(L"Unknown sort mode {}"sv, m_SortMode); } if (KeepPosition) GoToFile(strCurName); } bool FileList::SendKeyToPlugin(DWORD Key, bool Pred) { if (m_PanelMode != panel_mode::PLUGIN_PANEL) return false; const auto MacroState = Global->CtrlObject->Macro.GetState(); if (MacroState != MACROSTATE_RECORDING_COMMON && MacroState != MACROSTATE_EXECUTING_COMMON && MacroState != MACROSTATE_NOMACRO) return false; INPUT_RECORD rec; KeyToInputRecord(Key, &rec); const auto ProcessCode = Global->CtrlObject->Plugins->ProcessKey(GetPluginHandle(), &rec, Pred); return ProcessCode != 0; } bool FileList::GetPluginInfo(PluginInfo *PInfo) const { const auto PluginPanel = GetPluginHandle(); if (GetMode() != panel_mode::PLUGIN_PANEL || !PluginPanel || !PluginPanel->plugin()) return false; PInfo->StructSize = sizeof(PluginInfo); return Global->CtrlObject->Plugins->GetPluginInfo(PluginPanel->plugin(), PInfo); } long long FileList::VMProcess(int OpCode,void *vParam,long long iParam) { switch (OpCode) { case MCODE_C_ROOTFOLDER: if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); return !m_CachedOpenPanelInfo.CurDir || !*m_CachedOpenPanelInfo.CurDir; } return IsRootPath(m_CurDir)? 1 : equal_icase(m_CurDir, GetPathRoot(m_CurDir)); case MCODE_C_EOF: return m_CurFile == static_cast<int>(m_ListData.size() - 1); case MCODE_C_BOF: return !m_CurFile; case MCODE_C_SELECTED: return GetRealSelCount() != 0; case MCODE_V_ITEMCOUNT: return m_ListData.size(); case MCODE_V_CURPOS: return m_CurFile + 1; case MCODE_C_APANEL_FILTER: return m_Filter && m_Filter->IsEnabledOnPanel(); case MCODE_V_APANEL_PREFIX: // APanel.Prefix case MCODE_V_PPANEL_PREFIX: // PPanel.Prefix { const auto PInfo = static_cast<PluginInfo*>(vParam); const auto PluginPanel = GetPluginHandle(); if (GetMode() == panel_mode::PLUGIN_PANEL && PluginPanel && PluginPanel->plugin()) return Global->CtrlObject->Plugins->GetPluginInfo(PluginPanel->plugin(), PInfo)?1:0; return 0; } case MCODE_V_APANEL_FORMAT: // APanel.Format case MCODE_V_PPANEL_FORMAT: // PPanel.Format { const auto PluginPanel = GetPluginHandle(); if (GetMode() == panel_mode::PLUGIN_PANEL && PluginPanel) { Global->CtrlObject->Plugins->GetOpenPanelInfo(PluginPanel, &m_CachedOpenPanelInfo); *static_cast<OpenPanelInfo*>(vParam) = m_CachedOpenPanelInfo; return 1; } return 0; } case MCODE_F_PANEL_SELECT: { long long Result=-1; const auto mps = static_cast<const MacroPanelSelect*>(vParam); if (m_ListData.empty()) return Result; if (mps->Mode == 1 && static_cast<size_t>(mps->Index) >= m_ListData.size()) return Result; const auto ApplyToList = [&](const auto& Selector) { for (const auto& i: enum_tokens_with_quotes(mps->Item, L"\r\n"sv)) { if (i.empty()) continue; const auto Pos = FindFile(PointToName(i), true); if (Pos == -1) continue; Selector(Pos); Result++; } }; enum class ps_action { remove, add, invert, restore, }; enum class ps_mode { all, position, list_names, list_masks, }; switch (static_cast<ps_action>(mps->Action)) { case ps_action::remove: switch(static_cast<ps_mode>(mps->Mode)) { case ps_mode::all: SaveSelection(); Result=GetRealSelCount(); ClearSelection(); break; case ps_mode::position: SaveSelection(); Result=1; Select(m_ListData[mps->Index], false); break; case ps_mode::list_names: SaveSelection(); Result=0; ApplyToList([&](size_t Pos){ Select(m_ListData[Pos], false); }); break; case ps_mode::list_masks: SaveSelection(); Result = SelectFiles(SELECT_REMOVEMASK, mps->Item); break; } break; case ps_action::add: switch(static_cast<ps_mode>(mps->Mode)) { case ps_mode::all: SaveSelection(); for (auto& i: m_ListData) { Select(i, true); } Result=GetRealSelCount(); break; case ps_mode::position: SaveSelection(); Result=1; Select(m_ListData[mps->Index], true); break; case ps_mode::list_names: SaveSelection(); Result=0; ApplyToList([&](size_t Pos) { Select(m_ListData[Pos], true); }); break; case ps_mode::list_masks: SaveSelection(); Result = SelectFiles(SELECT_ADDMASK, mps->Item); break; } break; case ps_action::invert: switch(static_cast<ps_mode>(mps->Mode)) { case ps_mode::all: SaveSelection(); for (auto& i: m_ListData) { Select(i, !i.Selected); } Result=GetRealSelCount(); break; case ps_mode::position: SaveSelection(); Result=1; Select(m_ListData[mps->Index], !m_ListData[mps->Index].Selected); break; case ps_mode::list_names: SaveSelection(); Result=0; ApplyToList([&](size_t Pos) { Select(m_ListData[Pos], !m_ListData[Pos].Selected); }); break; case ps_mode::list_masks: SaveSelection(); Result = SelectFiles(SELECT_INVERTMASK, mps->Item); break; } break; case ps_action::restore: RestoreSelection(); Result = GetRealSelCount(); break; } if (Result != -1 && mps->Action != 3) { if (SelectedFirst) SortFileList(true); Redraw(); } return Result; } } return 0; } class file_state: public rel_ops<file_state> { public: static auto get(string_view const Filename) { file_state State; State.IsValid = os::fs::GetFileTimeSimple(Filename, nullptr, nullptr, &State.Times.first, &State.Times.second); return State; } bool operator==(const file_state& rhs) const { // Invalid times are considered different return IsValid && rhs.IsValid && Times == rhs.Times; } private: // TODO: Check the file size too? std::pair<os::chrono::time_point, os::chrono::time_point> Times; bool IsValid{}; }; // This function is ~1500 lines long /o bool FileList::ProcessKey(const Manager::Key& Key) { auto LocalKey = Key(); elevation::instance().ResetApprove(); int N; const auto IsEmptyCmdline = Parent()->GetCmdLine()->GetString().empty(); if (IsVisible()) { if ( !InternalProcessKey && (IsEmptyCmdline || none_of(LocalKey, KEY_ENTER, KEY_NUMENTER, KEY_SHIFTENTER, KEY_SHIFTNUMENTER)) && SendKeyToPlugin(LocalKey) ) return true; } else if (LocalKey < KEY_RCTRL0 || LocalKey > KEY_RCTRL9 || !Global->Opt->ShortcutAlwaysChdir) { // Те клавиши, которые работают при погашенных панелях: switch (LocalKey) { case KEY_CTRLF: case KEY_RCTRLF: case KEY_CTRLALTF: case KEY_RCTRLRALTF: case KEY_RCTRLALTF: case KEY_CTRLRALTF: case KEY_CTRLENTER: case KEY_RCTRLENTER: case KEY_CTRLNUMENTER: case KEY_RCTRLNUMENTER: case KEY_CTRLBRACKET: case KEY_RCTRLBRACKET: case KEY_CTRLBACKBRACKET: case KEY_RCTRLBACKBRACKET: case KEY_CTRLSHIFTBRACKET: case KEY_RCTRLSHIFTBRACKET: case KEY_CTRLSHIFTBACKBRACKET: case KEY_RCTRLSHIFTBACKBRACKET: case KEY_CTRL|KEY_SEMICOLON: case KEY_RCTRL|KEY_SEMICOLON: case KEY_CTRL|KEY_ALT|KEY_SEMICOLON: case KEY_RCTRL|KEY_RALT|KEY_SEMICOLON: case KEY_CTRL|KEY_RALT|KEY_SEMICOLON: case KEY_RCTRL|KEY_ALT|KEY_SEMICOLON: case KEY_CTRLALTBRACKET: case KEY_RCTRLRALTBRACKET: case KEY_CTRLRALTBRACKET: case KEY_RCTRLALTBRACKET: case KEY_CTRLALTBACKBRACKET: case KEY_RCTRLRALTBACKBRACKET: case KEY_CTRLRALTBACKBRACKET: case KEY_RCTRLALTBACKBRACKET: case KEY_ALTSHIFTBRACKET: case KEY_RALTSHIFTBRACKET: case KEY_ALTSHIFTBACKBRACKET: case KEY_RALTSHIFTBACKBRACKET: case KEY_CTRLG: case KEY_RCTRLG: case KEY_SHIFTF4: case KEY_F7: case KEY_CTRLH: case KEY_RCTRLH: case KEY_ALTSHIFTF9: case KEY_RALTSHIFTF9: case KEY_CTRLN: case KEY_RCTRLN: case KEY_GOTFOCUS: case KEY_KILLFOCUS: break; // эти спорные, хотя, если Ctrl-F работает, то и эти должны :-) /* case KEY_CTRLINS: case KEY_RCTRLINS: case KEY_CTRLSHIFTINS: case KEY_RCTRLSHIFTINS: case KEY_CTRLALTINS: case KEY_RCTRLRALTINS: case KEY_ALTSHIFTINS: case KEY_RALTSHIFTINS: break; */ default: return false; } } if (!IntKeyState.ShiftPressed() && ShiftSelection!=-1) { if (SelectedFirst) { SortFileList(true); ShowFileList(); } ShiftSelection=-1; } if ( !InternalProcessKey ) { // Create a folder shortcut? if ((LocalKey>=KEY_CTRLSHIFT0 && LocalKey<=KEY_CTRLSHIFT9) || (LocalKey>=KEY_RCTRLSHIFT0 && LocalKey<=KEY_RCTRLSHIFT9)) { SaveShortcutFolder((LocalKey&(~(KEY_CTRL | KEY_RCTRL | KEY_SHIFT | KEY_RSHIFT))) - L'0'); return true; } // Jump to a folder shortcut? else if (LocalKey>=KEY_RCTRL0 && LocalKey<=KEY_RCTRL9) { ExecShortcutFolder(LocalKey-KEY_RCTRL0); return true; } } /* $ 27.08.2002 SVS [*] В панели с одной колонкой Shift-Left/Right аналогично нажатию Shift-PgUp/PgDn. */ if (m_Stripes == 1 && IsEmptyCmdline) { if (any_of(LocalKey, KEY_SHIFTLEFT, KEY_SHIFTNUMPAD4)) LocalKey=KEY_SHIFTPGUP; else if (any_of(LocalKey, KEY_SHIFTRIGHT, KEY_SHIFTNUMPAD6)) LocalKey=KEY_SHIFTPGDN; } switch (LocalKey) { case KEY_GOTFOCUS: if (Global->Opt->SmartFolderMonitor) { StartFSWatcher(true); Parent()->GetAnotherPanel(this)->StartFSWatcher(true); } break; case KEY_KILLFOCUS: if (Global->Opt->SmartFolderMonitor) { StopFSWatcher(); Parent()->GetAnotherPanel(this)->StopFSWatcher(); } break; case KEY_F1: { return m_PanelMode == panel_mode::PLUGIN_PANEL && PluginPanelHelp(GetPluginHandle()); } case KEY_ALTSHIFTF9: case KEY_RALTSHIFTF9: if (m_PanelMode == panel_mode::PLUGIN_PANEL) Global->CtrlObject->Plugins->ConfigureCurrent(GetPluginHandle()->plugin(), FarUuid); else Global->CtrlObject->Plugins->Configure(); return true; case KEY_SHIFTSUBTRACT: SaveSelection(); ClearSelection(); Redraw(); return true; case KEY_SHIFTADD: SaveSelection(); for (auto& i: m_ListData) { if (!(i.Attributes & FILE_ATTRIBUTE_DIRECTORY) || Global->Opt->SelectFolders) Select(i, true); } if (SelectedFirst) SortFileList(true); Redraw(); return true; case KEY_ADD: SelectFiles(SELECT_ADD); return true; case KEY_SUBTRACT: SelectFiles(SELECT_REMOVE); return true; case KEY_CTRLADD: case KEY_RCTRLADD: SelectFiles(SELECT_ADDEXT); return true; case KEY_CTRLSUBTRACT: case KEY_RCTRLSUBTRACT: SelectFiles(SELECT_REMOVEEXT); return true; case KEY_ALTADD: case KEY_RALTADD: SelectFiles(SELECT_ADDNAME); return true; case KEY_ALTSUBTRACT: case KEY_RALTSUBTRACT: SelectFiles(SELECT_REMOVENAME); return true; case KEY_MULTIPLY: SelectFiles(SELECT_INVERT); return true; case KEY_CTRLMULTIPLY: case KEY_RCTRLMULTIPLY: SelectFiles(SELECT_INVERTALL); return true; case KEY_ALTMULTIPLY: case KEY_RALTMULTIPLY: SelectFiles(SELECT_INVERTFILES); return true; case KEY_ALTLEFT: // Прокрутка длинных имен и описаний case KEY_RALTLEFT: if (LeftPos != std::numeric_limits<decltype(LeftPos)>::min()) --LeftPos; Redraw(); return true; case KEY_ALTHOME: // Прокрутка длинных имен и описаний - в начало case KEY_RALTHOME: LeftPos = std::numeric_limits<decltype(LeftPos)>::min(); Redraw(); return true; case KEY_ALTRIGHT: // Прокрутка длинных имен и описаний case KEY_RALTRIGHT: if (LeftPos != std::numeric_limits<decltype(LeftPos)>::max()) ++LeftPos; Redraw(); return true; case KEY_ALTEND: // Прокрутка длинных имен и описаний - в конец case KEY_RALTEND: LeftPos = std::numeric_limits<decltype(LeftPos)>::max(); Redraw(); return true; case KEY_CTRLINS: case KEY_CTRLNUMPAD0: case KEY_RCTRLINS: case KEY_RCTRLNUMPAD0: if (!IsEmptyCmdline) return false; [[fallthrough]]; case KEY_CTRLSHIFTINS: case KEY_CTRLSHIFTNUMPAD0: // копировать имена case KEY_RCTRLSHIFTINS: case KEY_RCTRLSHIFTNUMPAD0: case KEY_CTRLALTINS: case KEY_CTRLALTNUMPAD0: // копировать UNC-имена case KEY_RCTRLRALTINS: case KEY_RCTRLRALTNUMPAD0: case KEY_CTRLRALTINS: case KEY_CTRLRALTNUMPAD0: case KEY_RCTRLALTINS: case KEY_RCTRLALTNUMPAD0: case KEY_ALTSHIFTINS: case KEY_ALTSHIFTNUMPAD0: // копировать полные имена case KEY_RALTSHIFTINS: case KEY_RALTSHIFTNUMPAD0: //if (FileCount>0 && SetCurPath()) // ????? SetCurPath(); CopyNames( any_of(LocalKey, KEY_CTRLALTINS, KEY_CTRLALTNUMPAD0, KEY_RCTRLRALTINS, KEY_RCTRLRALTNUMPAD0, KEY_CTRLRALTINS, KEY_CTRLRALTNUMPAD0, KEY_RCTRLALTINS, KEY_RCTRLALTNUMPAD0, KEY_ALTSHIFTINS, KEY_ALTSHIFTNUMPAD0, KEY_RALTSHIFTINS, KEY_RALTSHIFTNUMPAD0), flags::check_any(LocalKey, KEY_CTRL | KEY_RCTRL) && flags::check_any(LocalKey, KEY_ALT | KEY_RALT) ); return true; case KEY_CTRLSHIFTC: // hdrop copy case KEY_RCTRLSHIFTC: CopyFiles(false); return true; case KEY_CTRLSHIFTX: // hdrop cut case KEY_RCTRLSHIFTX: CopyFiles(true); return true; /* $ 14.02.2001 VVM + Ctrl: вставляет имя файла с пассивной панели. + CtrlAlt: вставляет UNC-имя файла с пассивной панели */ case KEY_CTRL|KEY_SEMICOLON: case KEY_RCTRL|KEY_SEMICOLON: case KEY_CTRL|KEY_ALT|KEY_SEMICOLON: case KEY_RCTRL|KEY_RALT|KEY_SEMICOLON: case KEY_CTRL|KEY_RALT|KEY_SEMICOLON: case KEY_RCTRL|KEY_ALT|KEY_SEMICOLON: { int NewKey = KEY_CTRLF; if (LocalKey & (KEY_ALT|KEY_RALT)) NewKey|=KEY_ALT; const auto SrcPanel = Parent()->PassivePanel(); const auto OldState = SrcPanel->IsVisible() != 0; SrcPanel->SetVisible(true); SrcPanel->ProcessKey(Manager::Key(NewKey)); SrcPanel->SetVisible(OldState); SetCurPath(); return true; } case KEY_CTRLNUMENTER: case KEY_RCTRLNUMENTER: case KEY_CTRLSHIFTNUMENTER: case KEY_RCTRLSHIFTNUMENTER: case KEY_CTRLENTER: case KEY_RCTRLENTER: case KEY_CTRLSHIFTENTER: case KEY_RCTRLSHIFTENTER: case KEY_CTRLJ: case KEY_RCTRLJ: case KEY_CTRLF: case KEY_RCTRLF: case KEY_CTRLALTF: // 29.01.2001 VVM + По CTRL+ALT+F в командную строку сбрасывается UNC-имя текущего файла. case KEY_RCTRLRALTF: case KEY_CTRLRALTF: case KEY_RCTRLALTF: { if (!m_ListData.empty() && SetCurPath()) { string strFileName; if (any_of(LocalKey, KEY_CTRLSHIFTENTER, KEY_RCTRLSHIFTENTER, KEY_CTRLSHIFTNUMENTER, KEY_RCTRLSHIFTNUMENTER)) { if (MakePathForUI(LocalKey, strFileName)) strFileName += ' '; } else { bool add_slash = false; assert(m_CurFile < static_cast<int>(m_ListData.size())); const auto& Current = m_ListData[m_CurFile]; strFileName = Current.AlternateOrNormal(m_ShowShortNames); if (IsParentDirectory(Current)) { if (m_PanelMode == panel_mode::PLUGIN_PANEL) strFileName.clear(); else strFileName.resize(1); // "." add_slash = (LocalKey & 0xFFFF) != (KEY_CTRLF & 0xFFFF); if (none_of(LocalKey, KEY_CTRLALTF, KEY_RCTRLRALTF, KEY_CTRLRALTF, KEY_RCTRLALTF)) LocalKey = KEY_CTRLF; } if (any_of(LocalKey, KEY_CTRLF, KEY_RCTRLF, KEY_CTRLALTF, KEY_RCTRLRALTF, KEY_CTRLRALTF, KEY_RCTRLALTF)) { if (m_PanelMode != panel_mode::PLUGIN_PANEL) strFileName = CreateFullPathName( strFileName, (Current.Attributes & FILE_ATTRIBUTE_DIRECTORY) != 0, any_of(LocalKey, KEY_CTRLALTF, KEY_RCTRLRALTF, KEY_CTRLRALTF, KEY_RCTRLALTF) ); else { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); string strFullName = NullToEmpty(m_CachedOpenPanelInfo.CurDir); if (Global->Opt->PanelCtrlFRule && (m_ViewSettings.Flags&PVS_FOLDERUPPERCASE)) inplace::upper(strFullName); if (!strFullName.empty()) AddEndSlash(strFullName,0); if (Global->Opt->PanelCtrlFRule) { /* $ 13.10.2000 tran по Ctrl-f имя должно отвечать условиям на панели */ if ((m_ViewSettings.Flags&PVS_FILELOWERCASE) && !(Current.Attributes & FILE_ATTRIBUTE_DIRECTORY)) inplace::lower(strFileName); if ((m_ViewSettings.Flags&PVS_FILEUPPERTOLOWERCASE)) if (!(Current.Attributes & FILE_ATTRIBUTE_DIRECTORY) && !IsCaseMixed(strFileName)) inplace::lower(strFileName); } strFileName.insert(0, strFullName); } } if (add_slash) AddEndSlash(strFileName); // добавим первый префикс! if (m_PanelMode == panel_mode::PLUGIN_PANEL && Global->Opt->SubstPluginPrefix && none_of(LocalKey, KEY_CTRLENTER, KEY_RCTRLENTER, KEY_CTRLNUMENTER, KEY_RCTRLNUMENTER, KEY_CTRLJ, KEY_RCTRLJ)) { strFileName.insert(0, GetPluginPrefix()); } if (!strFileName.empty() && (Global->Opt->QuotedName&QUOTEDNAME_INSERT) != 0) inplace::QuoteSpace(strFileName); strFileName += L' '; } Parent()->GetCmdLine()->InsertString(strFileName); } return true; } case KEY_CTRLALTBRACKET: // Вставить сетевое (UNC) путь из левой панели case KEY_RCTRLRALTBRACKET: case KEY_CTRLRALTBRACKET: case KEY_RCTRLALTBRACKET: case KEY_CTRLALTBACKBRACKET: // Вставить сетевое (UNC) путь из правой панели case KEY_RCTRLRALTBACKBRACKET: case KEY_CTRLRALTBACKBRACKET: case KEY_RCTRLALTBACKBRACKET: case KEY_ALTSHIFTBRACKET: // Вставить сетевое (UNC) путь из активной панели case KEY_RALTSHIFTBRACKET: case KEY_ALTSHIFTBACKBRACKET: // Вставить сетевое (UNC) путь из пассивной панели case KEY_RALTSHIFTBACKBRACKET: case KEY_CTRLBRACKET: // Вставить путь из левой панели case KEY_RCTRLBRACKET: case KEY_CTRLBACKBRACKET: // Вставить путь из правой панели case KEY_RCTRLBACKBRACKET: case KEY_CTRLSHIFTBRACKET: // Вставить путь из активной панели case KEY_RCTRLSHIFTBRACKET: case KEY_CTRLSHIFTBACKBRACKET: // Вставить путь из пассивной панели case KEY_RCTRLSHIFTBACKBRACKET: { string strPanelDir; if (MakePathForUI(LocalKey, strPanelDir)) Parent()->GetCmdLine()->InsertString(strPanelDir); return true; } case KEY_CTRLA: case KEY_RCTRLA: { if (!m_ListData.empty() && SetCurPath()) { ShellSetFileAttributes(this); Show(); } return true; } case KEY_CTRLG: case KEY_RCTRLG: { if (m_PanelMode != panel_mode::PLUGIN_PANEL || PluginManager::UseInternalCommand(GetPluginHandle(), PLUGIN_FAROTHER, m_CachedOpenPanelInfo)) if (!m_ListData.empty() && ApplyCommand()) { // позиционируемся в панели if (!Global->WindowManager->IsPanelsActive()) Global->WindowManager->SwitchToPanels(); Update(UPDATE_KEEP_SELECTION); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY); AnotherPanel->Redraw(); } return true; } case KEY_CTRLZ: case KEY_RCTRLZ: if (!m_ListData.empty() && m_PanelMode == panel_mode::NORMAL_PANEL && SetCurPath()) DescribeFiles(); return true; case KEY_CTRLH: case KEY_RCTRLH: { Global->Opt->ShowHidden=!Global->Opt->ShowHidden; Update(UPDATE_KEEP_SELECTION); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); AnotherPanel->Update(UPDATE_KEEP_SELECTION);//|UPDATE_SECONDARY); AnotherPanel->Redraw(); return true; } case KEY_CTRLM: case KEY_RCTRLM: RestoreSelection(); return true; case KEY_CTRLR: case KEY_RCTRLR: { Update(UPDATE_KEEP_SELECTION); Redraw(); { const auto AnotherPanel = Parent()->GetAnotherPanel(this); if (AnotherPanel->GetType() != panel_type::FILE_PANEL) { AnotherPanel->SetCurDir(m_CurDir,false); AnotherPanel->Redraw(); } } break; } case KEY_CTRLN: case KEY_RCTRLN: m_ShowShortNames=!m_ShowShortNames; Redraw(); return true; case KEY_NUMENTER: case KEY_SHIFTNUMENTER: case KEY_ENTER: case KEY_SHIFTENTER: case KEY_CTRLALTENTER: case KEY_RCTRLRALTENTER: case KEY_CTRLRALTENTER: case KEY_RCTRLALTENTER: case KEY_CTRLALTNUMENTER: case KEY_RCTRLRALTNUMENTER: case KEY_CTRLRALTNUMENTER: case KEY_RCTRLALTNUMENTER: { if (m_ListData.empty()) break; if (!IsEmptyCmdline) { Parent()->GetCmdLine()->ProcessKey(Key); return true; } ProcessEnter(true, (LocalKey & KEY_SHIFT) != 0, true, (LocalKey & (KEY_CTRL | KEY_RCTRL)) && (LocalKey & (KEY_ALT | KEY_RALT)), OFP_NORMAL); return true; } case KEY_CTRLBACKSLASH: case KEY_RCTRLBACKSLASH: { auto NeedChangeDir = true; if (m_PanelMode == panel_mode::PLUGIN_PANEL)// && *PluginsList[PluginsListSize-1].HostFile) { const auto CheckFullScreen=IsFullScreen(); Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (!m_CachedOpenPanelInfo.CurDir || !*m_CachedOpenPanelInfo.CurDir) { const auto OldParent = Parent(); ChangeDir(L".."sv, true); NeedChangeDir = false; //"this" мог быть удалён в ChangeDir const auto ActivePanel = OldParent->ActivePanel(); if (CheckFullScreen!=ActivePanel->IsFullScreen()) OldParent->PassivePanel()->Show(); } } if (NeedChangeDir) ChangeDir(L"\\"sv, false); Parent()->ActivePanel()->Show(); return true; } case KEY_SHIFTF1: { if (!m_ListData.empty()) { bool real_files = m_PanelMode != panel_mode::PLUGIN_PANEL; if (!real_files && GetType() == panel_type::FILE_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); real_files = (m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES) != 0; } if (real_files && SetCurPath()) PluginPutFilesToNew(); } return true; } case KEY_SHIFTF2: { if (!m_ListData.empty() && SetCurPath()) { if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (m_CachedOpenPanelInfo.HostFile && *m_CachedOpenPanelInfo.HostFile) ProcessKey(Manager::Key(KEY_F5)); else if ((m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES) == OPIF_REALNAMES) PluginHostGetFiles(); return true; } PluginHostGetFiles(); } return true; } case KEY_SHIFTF3: { ProcessHostFile(); return true; } case KEY_F3: case KEY_NUMPAD5: case KEY_SHIFTNUMPAD5: case KEY_ALTF3: case KEY_RALTF3: case KEY_CTRLSHIFTF3: case KEY_RCTRLSHIFTF3: case KEY_F4: case KEY_ALTF4: case KEY_RALTF4: case KEY_SHIFTF4: case KEY_CTRLSHIFTF4: case KEY_RCTRLSHIFTF4: { if (m_PanelMode == panel_mode::PLUGIN_PANEL) Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(),&m_CachedOpenPanelInfo); if (any_of(LocalKey, KEY_NUMPAD5, KEY_SHIFTNUMPAD5)) LocalKey=KEY_F3; if ((LocalKey==KEY_SHIFTF4 || !m_ListData.empty()) && SetCurPath()) { string strPluginData; bool PluginMode = m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginManager::UseInternalCommand(GetPluginHandle(), PLUGIN_FARGETFILE, m_CachedOpenPanelInfo) && !(m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES); if (PluginMode) { strPluginData = concat(L'<', NullToEmpty(m_CachedOpenPanelInfo.HostFile), L':', NullToEmpty(m_CachedOpenPanelInfo.CurDir), L'>'); } uintptr_t codepage = CP_DEFAULT; const auto Edit = any_of(LocalKey, KEY_F4, KEY_ALTF4, KEY_RALTF4, KEY_SHIFTF4, KEY_CTRLSHIFTF4, KEY_RCTRLSHIFTF4); string strFileName; string strShortFileName; if (LocalKey==KEY_SHIFTF4) { do { if (!dlgOpenEditor(strFileName, codepage)) return false; if (!strFileName.empty()) { inplace::unquote(strFileName); strShortFileName = ConvertNameToShort(strFileName); if (IsAbsolutePath(strFileName)) { PluginMode = false; } // проверим путь к файлу const auto pos = FindLastSlash(strFileName); if (pos != string::npos && pos) { if (!(HasPathPrefix(strFileName) && pos==3)) { if (!os::fs::exists(string_view(strFileName).substr(0, pos))) { if (Message(MSG_WARNING, msg(lng::MWarning), { msg(lng::MEditNewPath1), msg(lng::MEditNewPath2), msg(lng::MEditNewPath3) }, { lng::MHYes, lng::MHNo }, L"WarnEditorPath"sv) != message_result::first_button) return false; } } } } else if (PluginMode) // пустое имя файла в панели плагина не разрешается! { if (Message(MSG_WARNING, msg(lng::MWarning), { msg(lng::MEditNewPlugin1), msg(lng::MEditNewPath3) }, { lng::MCancel }, L"WarnEditorPluginName"sv) != message_result::first_button) return false; } else { strFileName = msg(lng::MNewFileName); } } while (strFileName.empty()); } else { assert(m_CurFile < static_cast<int>(m_ListData.size())); const auto& Current = m_ListData[m_CurFile]; if (Current.Attributes & FILE_ATTRIBUTE_DIRECTORY) { if (Edit) return ProcessKey(Manager::Key(KEY_CTRLA)); CountDirSize(!PluginMode); return true; } strFileName = Current.FileName; strShortFileName = Current.AlternateFileName(); } string strTempName; string TemporaryDirectory; bool UploadFailed = false, NewFile = false; if (PluginMode) { TemporaryDirectory = MakeTemp(); if (!os::fs::create_directory(TemporaryDirectory)) return true; strTempName = path::join(TemporaryDirectory, PointToName(strFileName)); const FileListItem* CurPtr = nullptr; if (LocalKey==KEY_SHIFTF4) { int Pos=FindFile(strFileName); if (Pos!=-1) CurPtr = &m_ListData[Pos]; else { NewFile = true; strFileName = strTempName; } } else { CurPtr = &m_ListData[m_CurFile]; } if (!NewFile) { PluginPanelItemHolderHeap PanelItem; FileListToPluginItem(*CurPtr, PanelItem); if (!Global->CtrlObject->Plugins->GetFile(GetPluginHandle(), &PanelItem.Item, TemporaryDirectory, strFileName, OPM_SILENT | (Edit? OPM_EDIT : OPM_VIEW))) { // BUGBUG check result if (!os::fs::remove_directory(TemporaryDirectory)) { LOGWARNING(L"remove_directory({}): {}"sv, TemporaryDirectory, last_error()); } return true; } } strShortFileName = ConvertNameToShort(strFileName); } auto DeleteViewedFile = PluginMode && !Edit; // внутренний viewer сам все удалит. auto Modaling = false; auto UploadFile = true; auto RefreshedPanel = true; if (!strFileName.empty()) { if (Edit) { const auto EnableExternal = ((any_of(LocalKey, KEY_F4, KEY_SHIFTF4) && Global->Opt->EdOpt.UseExternalEditor) || (any_of(LocalKey, KEY_ALTF4, KEY_RALTF4) && !Global->Opt->EdOpt.UseExternalEditor)) && !Global->Opt->strExternalEditor.empty(); auto Processed = false; const auto SavedState = file_state::get(strFileName); if (any_of(LocalKey, KEY_ALTF4, KEY_RALTF4, KEY_F4) && ProcessLocalFileTypes(strFileName, strShortFileName, LocalKey == KEY_F4? FILETYPE_EDIT:FILETYPE_ALTEDIT, PluginMode)) { UploadFile = file_state::get(strFileName) != SavedState; Processed = true; } if (!Processed || any_of(LocalKey, KEY_CTRLSHIFTF4, KEY_RCTRLSHIFTF4)) { if (EnableExternal) { ProcessExternal(Global->Opt->strExternalEditor, strFileName, strShortFileName, PluginMode, TemporaryDirectory); UploadFile = file_state::get(strFileName) != SavedState; Modaling = PluginMode; // External editor from plugin panel is Modal! } else if (PluginMode) { RefreshedPanel = Global->WindowManager->GetCurrentWindow()->GetType() != windowtype_editor; const auto ShellEditor = FileEditor::create(strFileName, codepage, (LocalKey == KEY_SHIFTF4 ? FFILEEDIT_CANNEWFILE : 0) | FFILEEDIT_DISABLEHISTORY, -1, -1, &strPluginData); if (-1 == ShellEditor->GetExitCode()) Global->WindowManager->ExecuteModal(ShellEditor);//OT UploadFile=ShellEditor->IsFileChanged() || NewFile; Modaling = true; } else { const auto ShellEditor = FileEditor::create(strFileName, codepage, (LocalKey == KEY_SHIFTF4 ? FFILEEDIT_CANNEWFILE : 0) | FFILEEDIT_ENABLEF6); const auto editorExitCode=ShellEditor->GetExitCode(); if (!(editorExitCode == XC_LOADING_INTERRUPTED || editorExitCode == XC_OPEN_ERROR)) { NamesList EditList; for (const auto& i: m_ListData) { if (!(i.Attributes & FILE_ATTRIBUTE_DIRECTORY)) EditList.AddName(i.FileName); } EditList.SetCurName(strFileName); ShellEditor->SetNamesList(EditList); } } } if (PluginMode && UploadFile) { PluginPanelItemHolderHeap PanelItem; const auto strSaveDir = os::fs::GetCurrentDirectory(); if (!os::fs::exists(strTempName)) { string_view Path = strTempName; CutToSlash(Path); const auto Find = os::fs::enum_files(Path + L'*'); const auto ItemIterator = std::find_if(CONST_RANGE(Find, i) { return !(i.Attributes & FILE_ATTRIBUTE_DIRECTORY); }); if (ItemIterator != Find.cend()) strTempName = Path + ItemIterator->FileName; } if (FileNameToPluginItem(strTempName, PanelItem)) { const auto PutCode = Global->CtrlObject->Plugins->PutFiles(GetPluginHandle(), { &PanelItem.Item, 1 }, false, OPM_EDIT); if (PutCode==1 || PutCode==2) SetPluginModified(); if (!PutCode) UploadFailed = true; } FarChDir(strSaveDir); } } else { const auto EnableExternal = ( (LocalKey == KEY_F3 && Global->Opt->ViOpt.UseExternalViewer) || (any_of(LocalKey, KEY_ALTF3, KEY_RALTF3) && !Global->Opt->ViOpt.UseExternalViewer) ) && !Global->Opt->strExternalViewer.empty(); /* $ 02.08.2001 IS обработаем ассоциации для alt-f3 */ auto Processed = false; if (any_of(LocalKey, KEY_ALTF3, KEY_RALTF3) && ProcessLocalFileTypes(strFileName, strShortFileName, FILETYPE_ALTVIEW, PluginMode)) Processed = true; else if (LocalKey == KEY_F3 && ProcessLocalFileTypes(strFileName, strShortFileName, FILETYPE_VIEW, PluginMode)) Processed = true; if (!Processed || any_of(LocalKey, KEY_CTRLSHIFTF3, KEY_RCTRLSHIFTF3)) { if (EnableExternal) ProcessExternal(Global->Opt->strExternalViewer, strFileName, strShortFileName, PluginMode, TemporaryDirectory); else { NamesList ViewList; if (!PluginMode) { for (const auto& i: m_ListData) { if (!(i.Attributes & FILE_ATTRIBUTE_DIRECTORY)) ViewList.AddName(i.FileName); } ViewList.SetCurName(strFileName); } const auto ShellViewer = FileViewer::create( strFileName, true, PluginMode, PluginMode, -1, strPluginData, &ViewList); /* $ 08.04.2002 IS Сбросим DeleteViewedFile, т.к. внутренний viewer сам все удалит */ if (ShellViewer->GetExitCode() && PluginMode) { ShellViewer->SetTempViewName(strFileName); DeleteViewedFile=false; } } } } } /* $ 08.04.2002 IS для файла, который открывался во внутреннем viewer-е, ничего не предпринимаем, т.к. viewer об этом позаботится сам */ if (PluginMode) { if (UploadFailed) { Message(MSG_WARNING, msg(lng::MError), { msg(lng::MCannotSaveFile), msg(lng::MTextSavedToTemp), strFileName }, { lng::MOk }); } else if (Edit || DeleteViewedFile) { // удаляем файл только для случая открытия его в редакторе или во // внешнем viewer-е, т.к. внутренний viewer удаляет файл сам DeleteFileWithFolder(strFileName); } } if (Modaling && RefreshedPanel) { if (!PluginMode || UploadFile) { Update(UPDATE_KEEP_SELECTION); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); if (AnotherPanel->GetMode() == panel_mode::NORMAL_PANEL) { AnotherPanel->Update(UPDATE_KEEP_SELECTION); AnotherPanel->Redraw(); } } // else // SetTitle(); } else if (m_PanelMode == panel_mode::NORMAL_PANEL) AccessTimeUpdateRequired = true; } /* $ 15.07.2000 tran а тут мы вызываем перерисовку панелей потому что этот viewer, editor могут нам неверно восстановить */ //Parent()->Redraw(); return true; } case KEY_F5: case KEY_F6: case KEY_ALTF6: case KEY_RALTF6: case KEY_DRAGCOPY: case KEY_DRAGMOVE: { ProcessCopyKeys(LocalKey); return true; } case KEY_ALTF5: // Печать текущего/выбранных файла/ов case KEY_RALTF5: { if (!m_ListData.empty() && SetCurPath()) PrintFiles(this); return true; } case KEY_SHIFTF5: case KEY_SHIFTF6: { if (!m_ListData.empty() && SetCurPath()) { assert(m_CurFile < static_cast<int>(m_ListData.size())); const auto name = m_ListData[m_CurFile].FileName; // must be a copy const auto selected = m_ListData[m_CurFile].Selected; int RealName = m_PanelMode != panel_mode::PLUGIN_PANEL; ReturnCurrentFile = true; if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); RealName = m_CachedOpenPanelInfo.Flags&OPIF_REALNAMES; } if (RealName) { int ToPlugin = 0; Copy(shared_from_this(), LocalKey == KEY_SHIFTF6, false, true, true, ToPlugin, nullptr); } else { ProcessCopyKeys(LocalKey==KEY_SHIFTF5 ? KEY_F5:KEY_F6); } ReturnCurrentFile = false; if (!m_ListData.empty()) { assert(m_CurFile < static_cast<int>(m_ListData.size())); if (LocalKey != KEY_SHIFTF5 && equal_icase(name, m_ListData[m_CurFile].FileName) && selected > m_ListData[m_CurFile].Selected) { Select(m_ListData[m_CurFile], selected); Redraw(); } } } return true; } case KEY_F7: { if (SetCurPath()) { if (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginManager::UseInternalCommand(GetPluginHandle(), PLUGIN_FARMAKEDIRECTORY, m_CachedOpenPanelInfo)) { string strDirName; auto DirName = strDirName.c_str(); int MakeCode=Global->CtrlObject->Plugins->MakeDirectory(GetPluginHandle(), &DirName,0); strDirName = DirName; if (!MakeCode) { Message(MSG_WARNING, msg(lng::MError), { msg(lng::MCannotCreateFolder), strDirName }, { lng::MOk }); } Update(UPDATE_KEEP_SELECTION); if (MakeCode==1) GoToFile(PointToName(strDirName)); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); /* $ 07.09.2001 VVM ! Обновить соседнюю панель с установкой на новый каталог */ // AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY); // AnotherPanel->Redraw(); if (AnotherPanel->GetType() != panel_type::FILE_PANEL) { AnotherPanel->SetCurDir(m_CurDir,false); AnotherPanel->Redraw(); } } else ShellMakeDir(this); } return true; } case KEY_F8: case KEY_SHIFTDEL: case KEY_SHIFTF8: case KEY_SHIFTNUMDEL: case KEY_SHIFTDECIMAL: case KEY_ALTNUMDEL: case KEY_RALTNUMDEL: case KEY_ALTDECIMAL: case KEY_RALTDECIMAL: case KEY_ALTDEL: case KEY_RALTDEL: { if (IsRepeatedKey() /*&& !Global->Opt->Confirmation.Delete*/) // не удаляем, если зажата клавиша return true; if (!m_ListData.empty() && SetCurPath()) { if (LocalKey==KEY_SHIFTF8) ReturnCurrentFile = true; if (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginManager::UseInternalCommand(GetPluginHandle(), PLUGIN_FARDELETEFILES, m_CachedOpenPanelInfo)) { PluginDelete(); } else { Delete( shared_from_this(), any_of(LocalKey, KEY_SHIFTDEL, KEY_SHIFTNUMDEL, KEY_SHIFTDECIMAL)? delete_type::remove : any_of(LocalKey, KEY_ALTDEL, KEY_RALTDEL, KEY_ALTNUMDEL, KEY_RALTNUMDEL, KEY_ALTDECIMAL, KEY_RALTDECIMAL)? delete_type::erase : Global->Opt->DeleteToRecycleBin? delete_type::recycle : delete_type::remove); } if (LocalKey==KEY_SHIFTF8) ReturnCurrentFile = false; } return true; } // $ 26.07.2001 VVM С альтом скролим всегда по 1 case KEY_MSWHEEL_UP: case KEY_MSWHEEL_UP | KEY_ALT: case KEY_MSWHEEL_UP | KEY_RALT: Scroll(LocalKey & (KEY_ALT | KEY_RALT)? -1 : static_cast<int>(-Global->Opt->MsWheelDelta)); return true; case KEY_MSWHEEL_DOWN: case KEY_MSWHEEL_DOWN | KEY_ALT: case KEY_MSWHEEL_DOWN | KEY_RALT: Scroll(LocalKey & (KEY_ALT | KEY_RALT)? 1 : static_cast<int>(Global->Opt->MsWheelDelta)); return true; case KEY_MSWHEEL_LEFT: case KEY_MSWHEEL_LEFT | KEY_ALT: case KEY_MSWHEEL_LEFT | KEY_RALT: { int Roll = LocalKey & (KEY_ALT | KEY_RALT)? 1 : static_cast<int>(Global->Opt->MsHWheelDelta); repeat(Roll, [&]{ ProcessKey(Manager::Key(KEY_LEFT)); }); return true; } case KEY_MSWHEEL_RIGHT: case KEY_MSWHEEL_RIGHT | KEY_ALT: case KEY_MSWHEEL_RIGHT | KEY_RALT: { int Roll = LocalKey & (KEY_ALT | KEY_RALT)? 1 : static_cast<int>(Global->Opt->MsHWheelDelta); repeat(Roll, [&]{ ProcessKey(Manager::Key(KEY_RIGHT)); }); return true; } case KEY_HOME: case KEY_NUMPAD7: ToBegin(); return true; case KEY_END: case KEY_NUMPAD1: ToEnd(); return true; case KEY_UP: case KEY_NUMPAD8: MoveCursorAndShow(-1); return true; case KEY_DOWN: case KEY_NUMPAD2: MoveCursorAndShow(1); return true; case KEY_PGUP: case KEY_NUMPAD9: N=m_Stripes*m_Height-1; m_CurTopFile-=N; MoveCursorAndShow(-N); return true; case KEY_PGDN: case KEY_NUMPAD3: N=m_Stripes*m_Height-1; m_CurTopFile+=N; MoveCursorAndShow(N); return true; case KEY_LEFT: case KEY_NUMPAD4: if ((m_Stripes == 1 && Global->Opt->ShellRightLeftArrowsRule == 1) || m_Stripes>1 || IsEmptyCmdline) { if (m_CurTopFile>=m_Height && m_CurFile-m_CurTopFile<m_Height) m_CurTopFile-=m_Height; MoveCursorAndShow(-m_Height); return true; } return false; case KEY_RIGHT: case KEY_NUMPAD6: if ((m_Stripes == 1 && Global->Opt->ShellRightLeftArrowsRule == 1) || m_Stripes>1 || IsEmptyCmdline) { if (m_CurFile+m_Height < static_cast<int>(m_ListData.size()) && m_CurFile-m_CurTopFile>=(m_Stripes-1)*(m_Height)) m_CurTopFile+=m_Height; MoveCursorAndShow(m_Height); return true; } return false; /* $ 25.04.2001 DJ оптимизация Shift-стрелок для Selected files first: делаем сортировку один раз */ case KEY_SHIFTHOME: case KEY_SHIFTNUMPAD7: { InternalProcessKey++; while (m_CurFile>0) MoveSelection(up); MoveSelection(up); InternalProcessKey--; if (SelectedFirst) SortFileList(true); ShowFileList(); return true; } case KEY_SHIFTEND: case KEY_SHIFTNUMPAD1: { InternalProcessKey++; while (m_CurFile < static_cast<int>(m_ListData.size() - 1)) MoveSelection(down); MoveSelection(down); InternalProcessKey--; if (SelectedFirst) SortFileList(true); ShowFileList(); return true; } case KEY_SHIFTPGUP: case KEY_SHIFTNUMPAD9: case KEY_SHIFTPGDN: case KEY_SHIFTNUMPAD3: { N=m_Stripes*m_Height-1; InternalProcessKey++; while (N--) MoveSelection(any_of(LocalKey, KEY_SHIFTPGUP, KEY_SHIFTNUMPAD9)? up : down); InternalProcessKey--; if (SelectedFirst) SortFileList(true); ShowFileList(); return true; } case KEY_SHIFTLEFT: case KEY_SHIFTNUMPAD4: case KEY_SHIFTRIGHT: case KEY_SHIFTNUMPAD6: { if (m_ListData.empty()) return true; if (m_Stripes>1) { N=m_Height; InternalProcessKey++; while (N--) MoveSelection(any_of(LocalKey, KEY_SHIFTLEFT, KEY_SHIFTNUMPAD4)? up : down); assert(m_CurFile < static_cast<int>(m_ListData.size())); Select(m_ListData[m_CurFile], ShiftSelection != 0); if (SelectedFirst) SortFileList(true); InternalProcessKey--; if (SelectedFirst) SortFileList(true); ShowFileList(); return true; } return false; } case KEY_SHIFTUP: case KEY_SHIFTNUMPAD8: case KEY_SHIFTDOWN: case KEY_SHIFTNUMPAD2: MoveSelection(any_of(LocalKey, KEY_SHIFTUP, KEY_SHIFTNUMPAD8) ? up : down); ShowFileList(); return true; case KEY_INS: case KEY_NUMPAD0: { if (m_ListData.empty()) return true; assert(m_CurFile < static_cast<int>(m_ListData.size())); auto& Current = m_ListData[m_CurFile]; Select(Current, !Current.Selected); bool avoid_up_jump = SelectedFirst && (m_CurFile > 0) && (m_CurFile+1 == static_cast<int>(m_ListData.size())) && Current.Selected; MoveCursorAndShow(1); if (SelectedFirst) { SortFileList(true); if (avoid_up_jump) ToEnd(); } ShowFileList(); return true; } case KEY_CTRLF3: case KEY_RCTRLF3: SetSortMode(panel_sort::BY_NAME); return true; case KEY_CTRLF4: case KEY_RCTRLF4: SetSortMode(panel_sort::BY_EXT); return true; case KEY_CTRLF5: case KEY_RCTRLF5: SetSortMode(panel_sort::BY_MTIME); return true; case KEY_CTRLF6: case KEY_RCTRLF6: SetSortMode(panel_sort::BY_SIZE); return true; case KEY_CTRLF7: case KEY_RCTRLF7: SetSortMode(panel_sort::UNSORTED); return true; case KEY_CTRLF8: case KEY_RCTRLF8: SetSortMode(panel_sort::BY_CTIME); return true; case KEY_CTRLF9: case KEY_RCTRLF9: SetSortMode(panel_sort::BY_ATIME); return true; case KEY_CTRLF10: case KEY_RCTRLF10: SetSortMode(panel_sort::BY_DIZ); return true; case KEY_CTRLF11: case KEY_RCTRLF11: SetSortMode(panel_sort::BY_OWNER); return true; case KEY_CTRLF12: case KEY_RCTRLF12: SelectSortMode(); return true; case KEY_SHIFTF11: m_SortGroups=!m_SortGroups; if (m_SortGroups) ReadSortGroups(); SortFileList(true); ProcessPluginEvent(FE_CHANGESORTPARAMS, nullptr); Show(); return true; case KEY_SHIFTF12: SelectedFirst=!SelectedFirst; SortFileList(true); ProcessPluginEvent(FE_CHANGESORTPARAMS, nullptr); Show(); return true; case KEY_CTRLPGUP: case KEY_CTRLNUMPAD9: case KEY_RCTRLPGUP: case KEY_RCTRLNUMPAD9: { if (Global->Opt->PgUpChangeDisk || m_PanelMode == panel_mode::PLUGIN_PANEL || !IsRootPath(m_CurDir)) { //"this" может быть удалён в ChangeDir const auto CheckFullScreen = IsFullScreen(); const auto OldParent = Parent(); ChangeDir(L".."sv, true); const auto NewActivePanel = OldParent->ActivePanel(); NewActivePanel->SetViewMode(NewActivePanel->GetViewMode()); if (CheckFullScreen!=NewActivePanel->IsFullScreen()) OldParent->GetAnotherPanel(NewActivePanel)->Show(); NewActivePanel->Show(); } return true; } case KEY_CTRLPGDN: case KEY_RCTRLPGDN: case KEY_CTRLNUMPAD3: case KEY_RCTRLNUMPAD3: case KEY_CTRLSHIFTPGDN: case KEY_RCTRLSHIFTPGDN: case KEY_CTRLSHIFTNUMPAD3: case KEY_RCTRLSHIFTNUMPAD3: ProcessEnter(false, false, !(LocalKey&KEY_SHIFT), false, OFP_ALTERNATIVE); return true; case KEY_APPS: case KEY_SHIFTAPPS: { //вызовем EMenu если он есть if (Global->CtrlObject->Plugins->FindPlugin(Global->Opt->KnownIDs.Emenu.Id)) { Global->CtrlObject->Plugins->CallPlugin(Global->Opt->KnownIDs.Emenu.Id, OPEN_FILEPANEL, {}); // EMenu Plugin :-) } return true; } default: if (((LocalKey>=KEY_ALT_BASE+0x01 && LocalKey<=KEY_ALT_BASE+65535) || (LocalKey>=KEY_RALT_BASE+0x01 && LocalKey<=KEY_RALT_BASE+65535) || (LocalKey>=KEY_ALTSHIFT_BASE+0x01 && LocalKey<=KEY_ALTSHIFT_BASE+65535) || (LocalKey>=KEY_RALTSHIFT_BASE+0x01 && LocalKey<=KEY_RALTSHIFT_BASE+65535)) && (LocalKey&~(KEY_ALT|KEY_RALT|KEY_SHIFT))!=KEY_BS && (LocalKey&~(KEY_ALT|KEY_RALT|KEY_SHIFT))!=KEY_TAB && (LocalKey&~(KEY_ALT|KEY_RALT|KEY_SHIFT))!=KEY_ENTER && (LocalKey&~(KEY_ALT|KEY_RALT|KEY_SHIFT))!=KEY_ESC && !(LocalKey&EXTENDED_KEY_BASE) ) { FastFind(Key); } else break; return true; } return false; } void FileList::Select(FileListItem& SelItem, bool Selection) { if (IsParentDirectory(SelItem) || SelItem.Selected == Selection) return; CacheSelIndex = -1; CacheSelClearIndex = -1; if (Selection) { SelItem.Selected = true; ++m_SelFileCount; m_SelDirCount += SelItem.Attributes & FILE_ATTRIBUTE_DIRECTORY? 1 : 0; SelFileSize += SelItem.FileSize; } else { SelItem.Selected = false; --m_SelFileCount; m_SelDirCount -= SelItem.Attributes & FILE_ATTRIBUTE_DIRECTORY? 1 : 0; SelFileSize -= SelItem.FileSize; } } static bool IsExecutable(string_view const Filename) { const auto Extension = name_ext(Filename).second; static const std::array Executables{ L".exe"sv, L".cmd"sv, L".com"sv, L".bat"sv }; return std::any_of(ALL_CONST_RANGE(Executables), [&](const string_view i) { return equal_icase(Extension, i); }); } void FileList::ProcessEnter(bool EnableExec,bool SeparateWindow,bool EnableAssoc, bool RunAs, OPENFILEPLUGINTYPE Type) { if (m_CurFile >= static_cast<int>(m_ListData.size())) return; const auto& CurItem = m_ListData[m_CurFile]; auto strFileName = CurItem.FileName; auto strShortFileName = CurItem.AlternateFileName(); if (CurItem.Attributes & FILE_ATTRIBUTE_DIRECTORY) { auto IsRealName = true; if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); IsRealName = (m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES) != 0; } // Shift-Enter на каталоге вызывает проводник if (IsRealName && SeparateWindow) { string strFullPath; if (!IsAbsolutePath(CurItem.FileName)) { strFullPath = m_CurDir; AddEndSlash(strFullPath); /* 23.08.2001 VVM ! SHIFT+ENTER на ".." срабатывает для текущего каталога, а не родительского */ if (!IsParentDirectory(CurItem)) strFullPath += CurItem.FileName; } else { strFullPath = CurItem.FileName; } OpenFolderInShell(strFullPath); } else { const auto CheckFullScreen = IsFullScreen(); const auto OldParent = Parent(); // Don't use CurItem directly: ChangeDir calls PopPlugin, which clears m_ListData const auto DirCopy = CurItem.FileName; const auto DataItemCopy = CurItem.UserData; ChangeDir(DirCopy, IsParentDirectory(CurItem), false, true, &DataItemCopy, Type, false); //"this" может быть удалён в ChangeDir const auto ActivePanel = OldParent->ActivePanel(); if (CheckFullScreen!=ActivePanel->IsFullScreen()) { OldParent->PassivePanel()->Show(); } ActivePanel->Show(); } } else { bool OpenedPlugin = false; const auto PluginMode = m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginManager::UseInternalCommand(GetPluginHandle(), PLUGIN_FARGETFILE, m_CachedOpenPanelInfo); string FileNameToDelete; SCOPE_EXIT{ if (PluginMode && !OpenedPlugin && !FileNameToDelete.empty()) GetPluginHandle()->delayed_delete(FileNameToDelete); }; file_state SavedState; if (PluginMode) { const auto strTempDir = MakeTemp(); // BUGBUG check result if (!os::fs::create_directory(strTempDir)) { LOGWARNING(L"create_directory({}): {}"sv, strTempDir, last_error()); } PluginPanelItemHolderHeap PanelItem; FileListToPluginItem(CurItem, PanelItem); if (!Global->CtrlObject->Plugins->GetFile(GetPluginHandle(), &PanelItem.Item, strTempDir, strFileName, OPM_SILENT | OPM_EDIT)) { // BUGBUG check result if (!os::fs::remove_directory(strTempDir)) { LOGWARNING(L"remove_directory({}): {}"sv, strTempDir, last_error()); } return; } FileNameToDelete = strFileName; strShortFileName = ConvertNameToShort(strFileName); SavedState = file_state::get(strFileName); } if (EnableExec) { // Enter if (!SetCurPath()) return; if (SeparateWindow || !ProcessLocalFileTypes(strFileName, strShortFileName, FILETYPE_EXEC, PluginMode, true, RunAs)) { const auto IsItExecutable = IsExecutable(strFileName); auto StopProcessing = false; if (!IsItExecutable && !SeparateWindow) { OpenedPlugin = OpenFilePlugin(strFileName, TRUE, Type, &StopProcessing) != nullptr; if (OpenedPlugin || StopProcessing) return; } if (IsItExecutable || SeparateWindow || Global->Opt->UseRegisteredTypes) { execute_info Info; Info.DisplayCommand = strFileName; Info.WaitMode = PluginMode? execute_info::wait_mode::wait_finish : SeparateWindow? execute_info::wait_mode::no_wait : execute_info::wait_mode::if_needed; Info.SourceMode = IsItExecutable? execute_info::source_mode::known_executable : execute_info::source_mode::known; Info.RunAs = RunAs; Info.Command = ConvertNameToFull(strFileName); Parent()->GetCmdLine()->ExecString(Info); const auto ExclusionFlag = IsItExecutable? EXCLUDECMDHISTORY_NOTPANEL : EXCLUDECMDHISTORY_NOTWINASS; if (!(Global->Opt->ExcludeCmdHistory & ExclusionFlag) && !PluginMode) { Global->CtrlObject->CmdHistory->AddToHistory(QuoteSpace(strFileName), HR_DEFAULT, nullptr, {}, m_CurDir); } } } } else { // CtrlPgDn if (EnableAssoc && ProcessLocalFileTypes(strFileName, strShortFileName, FILETYPE_ALTEXEC, PluginMode)) return; OpenedPlugin = OpenFilePlugin(strFileName, TRUE, Type) != nullptr; } if (PluginMode && !OpenedPlugin) { if (file_state::get(strFileName) != SavedState) { PluginPanelItemHolderHeap PanelItem; if (FileNameToPluginItem(strFileName, PanelItem)) { int PutCode = Global->CtrlObject->Plugins->PutFiles(GetPluginHandle(), { &PanelItem.Item, 1 }, false, OPM_EDIT); if (PutCode == 1 || PutCode == 2) SetPluginModified(); } } } } } bool FileList::SetCurDir(string_view const NewDir, bool ClosePanel, bool IsUpdated, bool const Silent) { UserDataItem UsedData{}; if (m_PanelMode == panel_mode::PLUGIN_PANEL) { if (ClosePanel) { const auto CheckFullScreen = IsFullScreen(); Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); const string strInfoHostFile = NullToEmpty(m_CachedOpenPanelInfo.HostFile); for (;;) { if (ProcessPluginEvent(FE_CLOSE,nullptr)) return false; if (!PopPlugin(TRUE)) break; if (NewDir.empty()) { Update(0); PopPrevData(strInfoHostFile,true,true,true,true); break; } } Parent()->RedrawKeyBar(); if (CheckFullScreen!=IsFullScreen()) { Parent()->GetAnotherPanel(this)->Redraw(); } } else if (m_CurFile < static_cast<int>(m_ListData.size())) { UsedData = m_ListData[m_CurFile].UserData; } } if (!NewDir.empty()) { if (m_PanelMode != panel_mode::PLUGIN_PANEL) Panel::SetCurDir(NewDir, ClosePanel, IsUpdated, Silent); return ChangeDir(NewDir, NewDir == L".."sv, true, IsUpdated, &UsedData, OFP_NORMAL, Silent); } return false; } bool FileList::ChangeDir(string_view const NewDir, bool IsParent, bool ResolvePath,bool IsUpdated, const UserDataItem* DataItem, OPENFILEPLUGINTYPE OfpType, bool const Silent) { bool IsPopPlugin = false; SCOPE_EXIT { if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (m_CachedOpenPanelInfo.Flags & OPIF_SHORTCUT) { const auto InfoCurDir = NullToEmpty(m_CachedOpenPanelInfo.CurDir); const auto InfoHostFile = NullToEmpty(m_CachedOpenPanelInfo.HostFile); const auto InfoData = NullToEmpty(m_CachedOpenPanelInfo.ShortcutData); Global->CtrlObject->FolderHistory->AddToHistory(InfoCurDir, HR_DEFAULT, &PluginManager::GetUUID(GetPluginHandle()), InfoHostFile, InfoData); } } else { Global->CtrlObject->FolderHistory->AddToHistory(GetCurDir()); if (!IsPopPlugin) InitFSWatcher(false); } }; if (m_PanelMode != panel_mode::PLUGIN_PANEL && !IsAbsolutePath(NewDir) && !equal_icase(os::fs::GetCurrentDirectory(), m_CurDir)) FarChDir(m_CurDir); string strFindDir; string strSetDir(NewDir); bool RootPath = false; bool NetPath = false; bool DrivePath = false; if (m_PanelMode != panel_mode::PLUGIN_PANEL) { if (IsParent) { strSetDir = m_CurDir; const auto Type = ParsePath(m_CurDir, nullptr, &RootPath); if(Type == root_type::remote || Type == root_type::unc_remote) { NetPath = true; } else if(Type == root_type::drive_letter) { DrivePath = true; } if(!RootPath) { CutToSlash(strSetDir); } } if (!ResolvePath) strSetDir = ConvertNameToFull(strSetDir); PrepareDiskPath(strSetDir, ResolvePath); if (HasPathPrefix(strSetDir) && strSetDir[5] == L':' && !strSetDir[6]) AddEndSlash(strSetDir); } if (!IsParent && !IsRelativeRoot(strSetDir)) UpperFolderTopFile=m_CurTopFile; if (m_SelFileCount>0) ClearSelection(); if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); /* $ 16.01.2002 VVM + Если у плагина нет OPIF_REALNAMES, то история папок не пишется в реестр */ string strInfoCurDir = NullToEmpty(m_CachedOpenPanelInfo.CurDir); string strInfoHostFile = NullToEmpty(m_CachedOpenPanelInfo.HostFile); /* $ 25.04.01 DJ при неудаче SetDirectory не сбрасываем выделение */ bool SetDirectorySuccess = true; bool GoToPanelFile = false; bool PluginClosed=false; if (IsParent && (strInfoCurDir.empty() // BUGBUG this breaks exiting from a real "\" directory but needed for https://forum.farmanager.com/viewtopic.php?p=86267#p86267 || IsRelativeRoot(strInfoCurDir) )) { if (ProcessPluginEvent(FE_CLOSE,nullptr)) return true; PluginClosed=true; strFindDir = strInfoHostFile; if (strFindDir.empty() && (m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES) && m_CurFile < static_cast<int>(m_ListData.size())) { strFindDir = m_ListData[m_CurFile].FileName; GoToPanelFile=true; } PopPlugin(TRUE); const auto AnotherPanel = Parent()->GetAnotherPanel(this); if (AnotherPanel->GetType() == panel_type::INFO_PANEL) AnotherPanel->Redraw(); } else { strFindDir = strInfoCurDir; auto opmode = static_cast<int>(OfpType == OFP_ALTERNATIVE ? OPM_PGDN : OPM_NONE); SetDirectorySuccess = Global->CtrlObject->Plugins->SetDirectory(GetPluginHandle(), strSetDir, opmode, DataItem) != FALSE; } // после закрытия панели нужно сразу установить внутренний каталог, иначе будет "Cannot find the file" - Mantis#1731 if (m_PanelMode == panel_mode::NORMAL_PANEL) SetCurPath(); if (SetDirectorySuccess) Update(0); else Update(UPDATE_KEEP_SELECTION); PopPrevData(strFindDir, PluginClosed, !GoToPanelFile, IsParent, SetDirectorySuccess); IsPopPlugin = true; return SetDirectorySuccess; } else { if (IsParent) { if (RootPath) { if (NetPath) { auto ShareName = m_CurDir; // strCurDir can be altered during next call DeleteEndSlash(ShareName); if (Global->CtrlObject->Plugins->CallPlugin(Global->Opt->KnownIDs.Network.Id,OPEN_FILEPANEL, UNSAFE_CSTR(ShareName))) // NetWork Plugin :-) { return false; } } if(DrivePath && Global->Opt->PgUpChangeDisk == 2) { string RemoteName; if(DriveLocalToRemoteName(true, m_CurDir, RemoteName)) { if (Global->CtrlObject->Plugins->CallPlugin(Global->Opt->KnownIDs.Network.Id, OPEN_FILEPANEL, UNSAFE_CSTR(RemoteName))) // NetWork Plugin :-) { return false; } } } ChangeDisk(Parent()->ActivePanel()); return true; } } } strFindDir = PointToName(m_CurDir); /* // вот и зачем это? мы уже и так здесь, в Options.Folder // + дальше по тексту strSetDir уже содержит полный путь if ( strSetDir.empty() || strSetDir[1] != L':' || !path::is_separator(strSetDir[2])) FarChDir(Options.Folder); */ /* $ 26.04.2001 DJ проверяем, удалось ли сменить каталог, и обновляем с KEEP_SELECTION, если не удалось */ int UpdateFlags = 0; bool SetDirectorySuccess = true; if (m_PanelMode != panel_mode::PLUGIN_PANEL && IsRelativeRoot(strSetDir)) { strSetDir = extract_root_directory(m_CurDir); } if (!FarChDir(strSetDir)) { if (!Silent && Global->WindowManager->ManagerStarted()) { /* $ 03.11.2001 IS Укажем имя неудачного каталога */ Message(MSG_WARNING, last_error(), msg(lng::MError), { IsParent? L".."s : strSetDir }, { lng::MOk }); UpdateFlags = UPDATE_KEEP_SELECTION; } SetDirectorySuccess=false; } m_CurDir = os::fs::GetCurrentDirectory(); if (!IsUpdated) return SetDirectorySuccess; Update(UpdateFlags); if (IsParent) { GoToFile(strFindDir); m_CurTopFile=UpperFolderTopFile; UpperFolderTopFile=0; CorrectPosition(); } else if (UpdateFlags != UPDATE_KEEP_SELECTION) m_CurFile=m_CurTopFile=0; if (IsFocused()) { Parent()->GetCmdLine()->SetCurDir(m_CurDir); Parent()->GetCmdLine()->Refresh(); } const auto AnotherPanel = Parent()->GetAnotherPanel(this); if (AnotherPanel->GetType() != panel_type::FILE_PANEL) { AnotherPanel->SetCurDir(m_CurDir, false); AnotherPanel->Redraw(); } if (m_PanelMode == panel_mode::PLUGIN_PANEL) Parent()->RedrawKeyBar(); return SetDirectorySuccess; } bool FileList::ChangeDir(string_view const NewDir, bool IsParent) { return ChangeDir(NewDir, IsParent, false, true, nullptr, OFP_NORMAL, false); } bool FileList::ProcessMouse(const MOUSE_EVENT_RECORD *MouseEvent) { if (!IsMouseInClientArea(MouseEvent)) return false; elevation::instance().ResetApprove(); if (IsVisible() && Global->Opt->ShowColumnTitles && !MouseEvent->dwEventFlags && MouseEvent->dwMousePosition.Y == m_Where.top + 1 && MouseEvent->dwMousePosition.X > m_Where.left && MouseEvent->dwMousePosition.X < m_Where.left + 3) { if (MouseEvent->dwButtonState) { if (MouseEvent->dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) ChangeDisk(shared_from_this()); else SelectSortMode(); } return true; } if (IsVisible() && Global->Opt->ShowPanelScrollbar && IntKeyState.MousePos.x == m_Where.right && (MouseEvent->dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) && !(MouseEvent->dwEventFlags & MOUSE_MOVED) && !IsDragging()) { const auto ScrollY = m_Where.top + 1 + Global->Opt->ShowColumnTitles; if (IntKeyState.MousePos.y == ScrollY) { // Press and hold the [▲] button while_mouse_button_pressed([&](DWORD const Button) { if (Button != FROM_LEFT_1ST_BUTTON_PRESSED) return false; ProcessKey(Manager::Key(KEY_UP)); return true; }); Parent()->SetActivePanel(shared_from_this()); return true; } else if (IntKeyState.MousePos.y == ScrollY + m_Height - 1) { // Press and hold the [▼] button while_mouse_button_pressed([&](DWORD const Button) { if (Button != FROM_LEFT_1ST_BUTTON_PRESSED) return false; ProcessKey(Manager::Key(KEY_DOWN)); return true; }); Parent()->SetActivePanel(shared_from_this()); return true; } else if (IntKeyState.MousePos.y > ScrollY && IntKeyState.MousePos.y < ScrollY + m_Height - 1 && m_Height > 2) { // Drag the thumb while (IsMouseButtonPressed() == FROM_LEFT_1ST_BUTTON_PRESSED) { m_CurFile = static_cast<int>((m_ListData.size() - 1)*(IntKeyState.MousePos.y - ScrollY) / (m_Height - 2)); ShowFileList(); Parent()->SetActivePanel(shared_from_this()); } return true; } } static bool delayedShowEMenu = false; if (delayedShowEMenu && MouseEvent->dwButtonState == 0) { delayedShowEMenu = false; Global->CtrlObject->Plugins->CallPlugin(Global->Opt->KnownIDs.Emenu.Id, OPEN_FILEPANEL, const_cast<COORD*>(&MouseEvent->dwMousePosition)); } if (Panel::ProcessMouseDrag(MouseEvent)) return true; if (!(MouseEvent->dwButtonState & MOUSE_ANY_BUTTON_PRESSED)) return false; if ( MouseEvent->dwMousePosition.Y > m_Where.top + Global->Opt->ShowColumnTitles && MouseEvent->dwMousePosition.Y < m_Where.bottom - 2 * Global->Opt->ShowPanelStatus ) { Parent()->SetActivePanel(shared_from_this()); if (m_ListData.empty()) return true; MoveToMouse(MouseEvent); assert(m_CurFile < static_cast<int>(m_ListData.size())); if ((MouseEvent->dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) && MouseEvent->dwEventFlags==DOUBLE_CLICK) { if (m_PanelMode == panel_mode::PLUGIN_PANEL) { FlushInputBuffer(); // !!! INPUT_RECORD rec; FarKeyToInputRecord({VK_RETURN, IntKeyState.ShiftPressed()? SHIFT_PRESSED : 0u}, &rec); if (Global->CtrlObject->Plugins->ProcessKey(GetPluginHandle(), &rec, false)) return true; } /*$ 21.02.2001 SKV Если пришел DOUBLE_CLICK без предшествующего ему простого клика, то курсор не перерисовывается. Перерисуем его. По идее при нормальном DOUBLE_CLICK, будет двойная перерисовка... Но мы же вызываем Fast=TRUE... Вроде всё должно быть ок. */ ShowFileList(); FlushInputBuffer(); ProcessEnter(true, IntKeyState.ShiftPressed(), true, IntKeyState.OnlyCtrlAltPressed(), OFP_NORMAL); return true; } else { /* $ 11.09.2000 SVS Bug #17: Выделяем при условии, что колонка ПОЛНОСТЬЮ пуста. */ if ((MouseEvent->dwButtonState & RIGHTMOST_BUTTON_PRESSED) && !empty) { const DWORD control = MouseEvent->dwControlKeyState&(SHIFT_PRESSED|LEFT_ALT_PRESSED|LEFT_CTRL_PRESSED|RIGHT_ALT_PRESSED|RIGHT_CTRL_PRESSED); //вызовем EMenu если он есть if (!Global->Opt->RightClickSelect && MouseEvent->dwButtonState == RIGHTMOST_BUTTON_PRESSED) { if ((!control || control==SHIFT_PRESSED) && Global->CtrlObject->Plugins->FindPlugin(Global->Opt->KnownIDs.Emenu.Id)) { ShowFileList(); delayedShowEMenu = GetAsyncKeyState(VK_RBUTTON)<0 || GetAsyncKeyState(VK_LBUTTON)<0 || GetAsyncKeyState(VK_MBUTTON)<0; if (!delayedShowEMenu) // show immediately if all mouse buttons released Global->CtrlObject->Plugins->CallPlugin(Global->Opt->KnownIDs.Emenu.Id, OPEN_FILEPANEL, const_cast<COORD*>(&MouseEvent->dwMousePosition)); return true; } } if (!MouseEvent->dwEventFlags || MouseEvent->dwEventFlags==DOUBLE_CLICK) MouseSelection = !m_ListData[m_CurFile].Selected; Select(m_ListData[m_CurFile], MouseSelection); if (SelectedFirst) SortFileList(true); } } ShowFileList(); return true; } if (MouseEvent->dwMousePosition.Y <= m_Where.top + 1) { Parent()->SetActivePanel(shared_from_this()); if (m_ListData.empty()) return true; while_mouse_button_pressed([&](DWORD) { if (IntKeyState.MousePos.y > m_Where.top + 1) return false; MoveCursorAndShow(-1); if (IntKeyState.MouseButtonState==RIGHTMOST_BUTTON_PRESSED) { assert(m_CurFile < static_cast<int>(m_ListData.size())); Select(m_ListData[m_CurFile], MouseSelection); } return true; }); if (SelectedFirst) SortFileList(true); return true; } if (MouseEvent->dwMousePosition.Y >= m_Where.bottom - 2) { Parent()->SetActivePanel(shared_from_this()); if (m_ListData.empty()) return true; while_mouse_button_pressed([&](DWORD) { if (IntKeyState.MousePos.y < m_Where.bottom - 2) return false; MoveCursorAndShow(1); if (IntKeyState.MouseButtonState==RIGHTMOST_BUTTON_PRESSED) { assert(m_CurFile < static_cast<int>(m_ListData.size())); Select(m_ListData[m_CurFile], MouseSelection); } return true; }); if (SelectedFirst) SortFileList(true); return true; } return false; } /* $ 12.09.2000 SVS + Опциональное поведение для правой клавиши мыши на пустой панели */ void FileList::MoveToMouse(const MOUSE_EVENT_RECORD *MouseEvent) { int CurColumn=1,ColumnsWidth = 0; const auto PanelX = MouseEvent->dwMousePosition.X - m_Where.left - 1; int Level = 0; for (const auto& i: m_ViewSettings.PanelColumns) { if (Level == m_ColumnsInStripe) { CurColumn++; Level = 0; } ColumnsWidth += i.width; if (ColumnsWidth>=PanelX) break; ColumnsWidth++; Level++; } // if (!CurColumn) // CurColumn=1; const auto OldCurFile = m_CurFile; m_CurFile = m_CurTopFile + MouseEvent->dwMousePosition.Y - m_Where.top - 1 - Global->Opt->ShowColumnTitles; if (CurColumn>1) m_CurFile+=(CurColumn-1)*m_Height; CorrectPosition(); /* $ 11.09.2000 SVS Bug #17: Проверим на ПОЛНОСТЬЮ пустую колонку. */ if (Global->Opt->PanelRightClickRule == 1) empty=((CurColumn-1)*m_Height > static_cast<int>(m_ListData.size())); else if (Global->Opt->PanelRightClickRule == 2 && (MouseEvent->dwButtonState & RIGHTMOST_BUTTON_PRESSED) && ((CurColumn-1)*m_Height > static_cast<int>(m_ListData.size()))) { m_CurFile=OldCurFile; empty = true; } else empty = false; } void FileList::SetViewMode(int Mode) { if (static_cast<size_t>(Mode) >= Global->Opt->ViewSettings.size()) Mode=VIEW_0; const auto CurFullScreen = IsFullScreen(); const auto OldOwner = IsColumnDisplayed(column_type::owner); const auto OldPacked = IsColumnDisplayed(column_type::size_compressed); const auto OldNumLink = IsColumnDisplayed(column_type::links_number); const auto OldNumStreams = IsColumnDisplayed(column_type::streams_number); const auto OldStreamsSize = IsColumnDisplayed(column_type::streams_size); const auto OldDiz = IsColumnDisplayed(column_type::description); PrepareViewSettings(Mode); const auto NewOwner = IsColumnDisplayed(column_type::owner); auto NewPacked = IsColumnDisplayed(column_type::size_compressed); const auto NewNumLink = IsColumnDisplayed(column_type::links_number); const auto NewNumStreams = IsColumnDisplayed(column_type::streams_number); const auto NewStreamsSize = IsColumnDisplayed(column_type::streams_size); const auto NewDiz = IsColumnDisplayed(column_type::description); const auto NewAccessTime = IsColumnDisplayed(column_type::date_access); DWORD FileSystemFlags = 0; if (NewPacked && os::fs::GetVolumeInformation(GetPathRoot(m_CurDir), nullptr, nullptr, nullptr, &FileSystemFlags, nullptr)) if (!(FileSystemFlags&FILE_FILE_COMPRESSION)) NewPacked = false; if (!m_ListData.empty() && m_PanelMode != panel_mode::PLUGIN_PANEL && ((!OldOwner && NewOwner) || (!OldPacked && NewPacked) || (!OldNumLink && NewNumLink) || (!OldNumStreams && NewNumStreams) || (!OldStreamsSize && NewStreamsSize) || IsColumnDisplayed(column_type::custom_0) || (AccessTimeUpdateRequired && NewAccessTime))) Update(UPDATE_KEEP_SELECTION); if (!OldDiz && NewDiz) ReadDiz(); if ((m_ViewSettings.Flags&PVS_FULLSCREEN) && !CurFullScreen) { if (m_Where.bottom > 0) SetPosition({ 0, m_Where.top, ScrX, m_Where.bottom }); m_ViewMode=Mode; } else { if (!(m_ViewSettings.Flags&PVS_FULLSCREEN) && CurFullScreen) { if (m_Where.bottom > 0) { if (Parent()->IsLeft(shared_from_this())) SetPosition({ 0, m_Where.top, static_cast<int>(ScrX / 2 - Global->Opt->WidthDecrement), m_Where.bottom }); else SetPosition({ static_cast<int>(ScrX / 2 + 1 - Global->Opt->WidthDecrement), m_Where.top, ScrX, m_Where.bottom }); } m_ViewMode=Mode; } else { m_ViewMode=Mode; Global->WindowManager->RefreshWindow(); } } if (m_PanelMode == panel_mode::PLUGIN_PANEL) { //SetScreenPosition(); const auto Result = SerialiseViewSettings(m_ViewSettings.PanelColumns); ProcessPluginEvent(FE_CHANGEVIEWMODE, UNSAFE_CSTR(Result.first)); } } void FileList::ApplySortMode(panel_sort Mode) { m_SortMode = Mode; if (!m_ListData.empty()) SortFileList(true); ProcessPluginEvent(FE_CHANGESORTPARAMS, nullptr); Global->WindowManager->RefreshWindow(); } void FileList::SetSortMode(panel_sort Mode, bool KeepOrder) { if (Mode < panel_sort::COUNT) { if (!KeepOrder) { m_ReverseSortOrder = (m_SortMode == Mode && Global->Opt->AllowReverseSort)? !m_ReverseSortOrder : Global->Opt->PanelSortLayers[static_cast<size_t>(Mode)].front().second == sort_order::descend; } ApplySortMode(Mode); } else if (Mode >= panel_sort::BY_USER) { SetCustomSortMode(Mode, KeepOrder? sort_order::keep : sort_order::flip_or_default, false); } } void FileList::SetCustomSortMode(panel_sort const Mode, sort_order const Order, bool const InvertByDefault) { if (Mode < panel_sort::BY_USER) return; switch (Order) { default: case sort_order::flip_or_default: m_ReverseSortOrder = (Mode == m_SortMode && Global->Opt->AllowReverseSort)? !m_ReverseSortOrder : InvertByDefault; break; case sort_order::keep: break; case sort_order::ascend: m_ReverseSortOrder = false; break; case sort_order::descend: m_ReverseSortOrder = true; break; } ApplySortMode(Mode); } void FileList::ChangeDirectoriesFirst(bool Mode) { Panel::ChangeDirectoriesFirst(Mode); SortFileList(true); ProcessPluginEvent(FE_CHANGESORTPARAMS, nullptr); Show(); } void FileList::OnSortingChange() { Panel::OnSortingChange(); SortFileList(true); ProcessPluginEvent(FE_CHANGESORTPARAMS, nullptr); if (IsVisible()) Show(); } void FileList::InitCurDir(string_view CurDir) { Panel::InitCurDir(CurDir); InitFSWatcher(false); } bool FileList::GoToFile(long idxItem) { if (static_cast<size_t>(idxItem) >= m_ListData.size()) return false; m_CurFile=idxItem; CorrectPosition(); return true; } bool FileList::GoToFile(const string_view Name, const bool OnlyPartName) { return GoToFile(FindFile(Name,OnlyPartName)); } long FileList::FindFile(const string_view Name, const bool OnlyPartName) { long II = -1; for (const auto& I: irange(m_ListData.size())) { const auto CurPtrName = OnlyPartName? PointToName(m_ListData[I].FileName) : m_ListData[I].FileName; if (Name == CurPtrName) return static_cast<long>(I); if (II < 0 && equal_icase(Name, CurPtrName)) II = static_cast<long>(I); } return II; } long FileList::FindFirst(string_view const Name) { return FindNext(0, Name); } long FileList::FindNext(int StartPos, string_view const Name) { if (static_cast<size_t>(StartPos) >= m_ListData.size()) return -1; for (const auto& I: irange(StartPos, m_ListData.size())) { if (CmpName(Name, m_ListData[I].FileName, true) && !IsParentDirectory(m_ListData[I])) return static_cast<long>(I); } return -1; } bool FileList::IsSelected(string_view const Name) { const long Pos = FindFile(Name); return Pos!=-1 && (m_ListData[Pos].Selected || (!m_SelFileCount && Pos==m_CurFile)); } bool FileList::IsSelected(size_t idxItem) { return idxItem < m_ListData.size() && m_ListData[idxItem].Selected; // || (Sel!FileCount && idxItem==CurFile) ??? } bool FileList::FilterIsEnabled() { return m_Filter && m_Filter->IsEnabledOnPanel(); } bool FileList::FileInFilter(size_t idxItem) { return idxItem < m_ListData.size() && (!m_Filter || !m_Filter->IsEnabledOnPanel() || m_Filter->FileInFilter(m_ListData[idxItem])); // BUGBUG, cast } // $ 02.08.2000 IG Wish.Mix #21 - при нажатии '/' или '\' в QuickSerach переходим на директорию bool FileList::FindPartName(string_view const Name,int Next,int Direct) { if constexpr (!features::mantis_698) { int DirFind = 0; string_view NameView = Name; if (!Name.empty() && path::is_separator(Name.back())) { DirFind = 1; NameView.remove_suffix(1); } const auto strMask = exclude_sets(NameView + L'*'); const auto Match = [&](int const I) { if (CmpName(strMask, m_ListData[I].FileName, true, false)) { if (!IsParentDirectory(m_ListData[I])) { if (!DirFind || (m_ListData[I].Attributes & FILE_ATTRIBUTE_DIRECTORY)) { m_CurFile = I; m_CurTopFile = m_CurFile - (m_Where.height() - 1) / 2; ShowFileList(); return true; } } } return false; }; for (int I=m_CurFile+(Next?Direct:0); I >= 0 && I < static_cast<int>(m_ListData.size()); I+=Direct) { if (Match(I)) return true; } for (int I=(Direct > 0)?0:static_cast<int>(m_ListData.size()-1); (Direct > 0) ? I < m_CurFile:I > m_CurFile; I+=Direct) { if (Match(I)) return true; } return false; } else { // АХТУНГ! В разработке string Dest; int DirFind = 0; string strMask = upper(Name); if (!Name.empty() && path::is_separator(Name.back())) { DirFind = 1; strMask.pop_back(); } /* strMask = exclude_sets(strMask + L'*'); */ for (int I = m_CurFile + (Next ? Direct : 0); I >= 0 && static_cast<size_t>(I) < m_ListData.size(); I += Direct) { if (GetPlainString(Dest,I) && contains(upper(Dest), strMask)) //if (CmpName(strMask,ListData[I].FileName,true,I==CurFile)) { if (!IsParentDirectory(m_ListData[I])) { if (!DirFind || (m_ListData[I].Attributes & FILE_ATTRIBUTE_DIRECTORY)) { m_CurFile=I; m_CurTopFile = m_CurFile - (m_Where.height() - 1) / 2; ShowFileList(); return true; } } } } for (int I = (Direct > 0)? 0 : static_cast<int>(m_ListData.size() - 1); (Direct > 0)? I < m_CurFile : I > m_CurFile; I += Direct) { if ( !GetPlainString(Dest, I) || !contains(upper(Dest), strMask) || IsParentDirectory(m_ListData[I]) || (DirFind && !(m_ListData[I].Attributes & FILE_ATTRIBUTE_DIRECTORY)) ) continue; m_CurFile = I; m_CurTopFile = m_CurFile - (m_Where.height() - 1) / 2; ShowFileList(); return true; } return false; } } // собрать в одну строку все данные в отображаемых колонках bool FileList::GetPlainString(string& Dest, int ListPos) const { Dest.clear(); if constexpr (features::mantis_698) { if (static_cast<size_t>(ListPos) >= m_ListData.size()) return false; for (const auto& Column : m_ViewSettings.PanelColumns) { if (Column.type >= column_type::custom_0 && Column.type <= column_type::custom_max) { const size_t ColumnNumber = static_cast<size_t>(Column.type) - static_cast<size_t>(column_type::custom_0); if (ColumnNumber < m_ListData[ListPos].CustomColumns.size()) Dest += m_ListData[ListPos].CustomColumns[ColumnNumber]; continue; } switch (Column.type) { case column_type::name: { string_view Name = m_ListData[ListPos].AlternateOrNormal(m_ShowShortNames); if (!(m_ListData[ListPos].Attributes & FILE_ATTRIBUTE_DIRECTORY) && Column.type_flags & COLFLAGS_NOEXTENSION) { Name = name_ext(Name).first; } if (Column.type_flags & COLFLAGS_NAMEONLY) { //BUGBUG!!! // !!! НЕ УВЕРЕН, но то, что отображается пустое // пространство вместо названия - бага Name = PointToFolderNameIfFolder(Name); } Dest += Name; break; } case column_type::extension: { string_view Ext; if (!(m_ListData[ListPos].Attributes & FILE_ATTRIBUTE_DIRECTORY)) Ext = name_ext(m_ListData[ListPos].AlternateOrNormal(m_ShowShortNames)).second; if (!Ext.empty()) Ext.remove_prefix(1); Dest += Ext; break; } case column_type::size: case column_type::size_compressed: case column_type::streams_size: { const auto SizeToDisplay = (Column.type == column_type::size_compressed) ? m_ListData[ListPos].AllocationSize : Column.type == column_type::streams_size ? m_ListData[ListPos].StreamsSize(this) : m_ListData[ListPos].FileSize; Dest += FormatStr_Size( SizeToDisplay, m_ListData[ListPos].FileName, m_ListData[ListPos].Attributes, m_ListData[ListPos].ShowFolderSize, m_ListData[ListPos].ReparseTag, Column.type, Column.type_flags, Column.width, // BUGBUG width_type m_CurDir); break; } case column_type::date: case column_type::time: case column_type::date_write: case column_type::date_creation: case column_type::date_access: case column_type::date_change: { os::chrono::time_point const FileListItem::* FileTime; switch (Column.type) { case column_type::date_creation: FileTime = &FileListItem::CreationTime; break; case column_type::date_access: FileTime = &FileListItem::LastAccessTime; break; case column_type::date_change: FileTime = &FileListItem::ChangeTime; break; default: FileTime = &FileListItem::LastWriteTime; break; } Dest += FormatStr_DateTime(std::invoke(FileTime, m_ListData[ListPos]), Column.type, Column.type_flags, Column.width); // BUGBUG width_type break; } case column_type::attributes: Dest += FormatStr_Attribute(m_ListData[ListPos].Attributes, Column.width); // BUGBUG width_type break; case column_type::description: Dest += NullToEmpty(m_ListData[ListPos].DizText); break; case column_type::owner: Dest += m_ListData[ListPos].Owner(this); break; case column_type::links_number: Dest += str(m_ListData[ListPos].NumberOfLinks(this)); break; case column_type::streams_number: Dest += str(m_ListData[ListPos].NumberOfStreams(this)); break; default: break; // BUGBUG? } } return true; } return false; } size_t FileList::GetSelCount() const { assert(m_ListData.empty() || !(ReturnCurrentFile||!m_SelFileCount) || (m_CurFile < static_cast<int>(m_ListData.size()))); return !m_ListData.empty()? ((ReturnCurrentFile || !m_SelFileCount)? (IsParentDirectory(m_ListData[m_CurFile])? 0 : 1) : m_SelFileCount) : 0; } size_t FileList::GetRealSelCount() const { return !m_ListData.empty()? m_SelFileCount : 0; } bool FileList::GetSelName(string* strName, string* strShortName, os::fs::find_data* fd) { if (!strName) { GetSelPosition=0; LastSelPosition=-1; return true; } const auto CopyFrom = [&](const FileListItem& Src) { *strName = Src.FileName; if (strShortName) *strShortName = Src.AlternateFileName(); if (fd) *fd = Src; }; if (!m_SelFileCount || ReturnCurrentFile) { if (GetSelPosition || m_CurFile >= static_cast<int>(m_ListData.size())) return false; GetSelPosition=1; CopyFrom(m_ListData[m_CurFile]); LastSelPosition=m_CurFile; return true; } while (GetSelPosition < static_cast<int>(m_ListData.size())) { if (!m_ListData[GetSelPosition++].Selected) continue; CopyFrom(m_ListData[GetSelPosition - 1]); LastSelPosition = GetSelPosition - 1; return true; } return false; } void FileList::ClearLastGetSelection() { if (LastSelPosition < 0 || LastSelPosition >= static_cast<int>(m_ListData.size())) return; Select(m_ListData[LastSelPosition], false); } const FileListItem* FileList::GetLastSelectedItem() const { if (LastSelPosition < 0 || LastSelPosition >= static_cast<int>(m_ListData.size())) return nullptr; return &m_ListData[LastSelPosition]; } bool FileList::GetCurName(string &strName, string &strShortName) const { if (m_ListData.empty()) return false; assert(m_CurFile < static_cast<int>(m_ListData.size())); strName = m_ListData[m_CurFile].FileName; strShortName = m_ListData[m_CurFile].AlternateFileName(); return true; } bool FileList::GetCurBaseName(string &strName, string &strShortName) const { if (m_ListData.empty()) return false; if (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginsList.empty()) // для плагинов { strName = PointToName(PluginsList.front()->m_HostFile); strShortName = strName; } else if (m_PanelMode == panel_mode::NORMAL_PANEL) { assert(m_CurFile < static_cast<int>(m_ListData.size())); strName = m_ListData[m_CurFile].FileName; strShortName = m_ListData[m_CurFile].AlternateFileName(); } return true; } bool FileList::HardlinksSupported() const { return m_HardlinksSupported; } bool FileList::StreamsSupported() const { return m_StreamsSupported; } const string& FileList::GetComputerName() const { return m_ComputerName; } long FileList::SelectFiles(int Mode, string_view const Mask) { enum { sf_doublebox, sf_edit, sf_separator, sf_button_ok, sf_button_filter, sf_button_cancel, sf_count }; auto SelectDlg = MakeDialogItems<sf_count>( { { DI_DOUBLEBOX, {{3, 1}, {51, 5}}, DIF_NONE, }, { DI_EDIT, {{5, 2}, {49, 2}}, DIF_FOCUS | DIF_HISTORY, }, { DI_TEXT, {{-1, 3}, {0, 3}}, DIF_SEPARATOR, }, { DI_BUTTON, {{0, 4}, {0, 4}}, DIF_CENTERGROUP | DIF_DEFAULTBUTTON, msg(lng::MOk), }, { DI_BUTTON, {{0, 4}, {0, 4}}, DIF_CENTERGROUP, msg(lng::MSelectFilter), }, { DI_BUTTON, {{0, 4}, {0, 4}}, DIF_CENTERGROUP, msg(lng::MCancel), }, }); SelectDlg[sf_edit].strHistory = L"Masks"sv; multifilter Filter(this, FFT_SELECT); bool bUseFilter = false; static auto strPrevMask = L"*.*"s; /* $ 20.05.2002 IS При обработке маски, если работаем с именем файла на панели, берем каждую квадратную скобку в имени при образовании маски в скобки, чтобы подобные имена захватывались полученной маской - это специфика, диктуемая CmpName. */ auto strMask = L"*.*"s; string strRawMask; bool WrapBrackets=false; // говорит о том, что нужно взять кв.скобки в скобки if (m_CurFile >= static_cast<int>(m_ListData.size())) return 0; filemasks FileMask; // Класс для работы с масками int RawSelection=FALSE; if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); RawSelection=(m_CachedOpenPanelInfo.Flags & OPIF_RAWSELECTION); } const auto& strCurName = m_ListData[m_CurFile].AlternateOrNormal(m_ShowShortNames); if (Mode==SELECT_ADDEXT || Mode==SELECT_REMOVEEXT) { const auto pos = strCurName.rfind(L'.'); if (pos != string::npos) { // Учтем тот момент, что расширение может содержать символы-разделители strRawMask = concat(L'"', L"*."sv, string_view(strCurName).substr(pos + 1), L'"'); WrapBrackets=true; } else { strMask = L"*."sv; } Mode=(Mode==SELECT_ADDEXT) ? SELECT_ADD:SELECT_REMOVE; } else { if (Mode==SELECT_ADDNAME || Mode==SELECT_REMOVENAME) { // Учтем тот момент, что имя может содержать символы-разделители strRawMask = concat(L"\""sv, strCurName); const auto pos = strRawMask.rfind(L'.'); if (pos != string::npos && pos!=strRawMask.size()-1) strRawMask.resize(pos); append(strRawMask, L".*\""sv); WrapBrackets=true; Mode=(Mode==SELECT_ADDNAME) ? SELECT_ADD:SELECT_REMOVE; } else { if (Mode==SELECT_ADD || Mode==SELECT_REMOVE) { SelectDlg[sf_edit].strData = strPrevMask; SelectDlg[sf_doublebox].strData = msg(Mode == SELECT_ADD? lng::MSelectTitle : lng::MUnselectTitle); { const auto Dlg = Dialog::create(SelectDlg); Dlg->SetHelp(L"SelectFiles"sv); Dlg->SetPosition({ -1, -1, 55, 7 }); Dlg->SetId(Mode==SELECT_ADD?SelectDialogId:UnSelectDialogId); for (;;) { Dlg->ClearDone(); Dlg->Process(); if (Dlg->GetExitCode() == sf_button_filter) { filters::EditFilters(Filter.area(), Filter.panel()); //Рефреш текущему времени для фильтра сразу после выхода из диалога Filter.UpdateCurrentTime(); bUseFilter = true; break; } if (Dlg->GetExitCode() != sf_button_ok) return 0; strMask = SelectDlg[sf_edit].strData; if (FileMask.assign(strMask)) // Проверим вводимые пользователем маски на ошибки { strPrevMask = strMask; break; } } } } else if (Mode==SELECT_ADDMASK || Mode==SELECT_REMOVEMASK || Mode==SELECT_INVERTMASK) { strMask = Mask; if (!FileMask.assign(strMask)) // Проверим маски на ошибки return 0; } } } SaveSelection(); if (!bUseFilter && WrapBrackets) // возьмем кв.скобки в скобки, чтобы получить { // работоспособную маску strMask.clear(); for (const auto& i: strRawMask) { if (i == L']' || i == L'[') { append(strMask, L'[', i, L']'); } else { strMask += i; } } } long workCount=0; if (bUseFilter || FileMask.assign(strMask, FMF_SILENT)) // Скомпилируем маски файлов и работаем { // дальше в зависимости от успеха компиляции for (auto& i: m_ListData) { if ( Mode != SELECT_INVERT && Mode != SELECT_INVERTALL && Mode != SELECT_INVERTFILES && !(bUseFilter? Filter.FileInFilter(i) : FileMask.check(i.AlternateOrNormal(m_ShowShortNames))) ) continue; bool Selection = false; switch (Mode) { case SELECT_ADD: case SELECT_ADDMASK: Selection = true; break; case SELECT_REMOVE: case SELECT_REMOVEMASK: Selection = false; break; case SELECT_INVERT: case SELECT_INVERTALL: case SELECT_INVERTFILES: case SELECT_INVERTMASK: Selection=!i.Selected; break; } if ( bUseFilter || !(i.Attributes & FILE_ATTRIBUTE_DIRECTORY) || (Global->Opt->SelectFolders && Mode != SELECT_INVERTFILES) || !Selection || RawSelection || Mode == SELECT_INVERTALL || Mode == SELECT_INVERTMASK ) { Select(i, Selection); workCount++; } } } if (SelectedFirst) SortFileList(true); ShowFileList(); return workCount; } void FileList::UpdateViewPanel() { const auto ViewPanel = std::dynamic_pointer_cast<QuickView>(Parent()->GetAnotherPanel(this)); if (!ViewPanel || m_ListData.empty() || !ViewPanel->IsVisible() || !SetCurPath()) return; assert(m_CurFile < static_cast<int>(m_ListData.size())); const auto& Current = m_ListData[m_CurFile]; if (m_PanelMode != panel_mode::PLUGIN_PANEL || PluginManager::UseInternalCommand(GetPluginHandle(), PLUGIN_FARGETFILE, m_CachedOpenPanelInfo)) { if (IsParentDirectory(Current)) ViewPanel->ShowFile(m_CurDir, nullptr, false, nullptr); else ViewPanel->ShowFile(Current.FileName, &Current.UserData, false, nullptr); } else if (!(Current.Attributes & FILE_ATTRIBUTE_DIRECTORY)) { const auto strTempDir = MakeTemp(); // BUGBUG check result if (!os::fs::create_directory(strTempDir)) { LOGWARNING(L"create_directory({}): {}"sv, strTempDir, last_error()); } PluginPanelItemHolderHeap PanelItem; FileListToPluginItem(Current, PanelItem); string strFileName; if (!Global->CtrlObject->Plugins->GetFile(GetPluginHandle(), &PanelItem.Item, strTempDir, strFileName, OPM_SILENT | OPM_VIEW | OPM_QUICKVIEW)) { ViewPanel->ShowFile({}, nullptr, false, nullptr); // BUGBUG check result if (!os::fs::remove_directory(strTempDir)) { LOGWARNING(L"remove_directory({}): {}"sv, strTempDir, last_error()); } return; } ViewPanel->ShowFile(strFileName, nullptr, true, nullptr); } else if (!IsParentDirectory(Current)) { ViewPanel->ShowFile(Current.FileName, &Current.UserData, false, GetPluginHandle()); } else { ViewPanel->ShowFile({}, nullptr, false, nullptr); } RefreshTitle(); } void FileList::CompareDir() { const auto Another = std::dynamic_pointer_cast<FileList>(Parent()->GetAnotherPanel(this)); if (!Another || !Another->IsVisible()) { Message(MSG_WARNING, msg(lng::MCompareTitle), { msg(lng::MCompareFilePanelsRequired1), msg(lng::MCompareFilePanelsRequired2) }, { lng::MOk }); return; } Global->ScrBuf->Flush(); const auto select_files = [&](FileList& Panel) { for (auto& i: Panel.m_ListData) { Panel.Select(i, !(i.Attributes & FILE_ATTRIBUTE_DIRECTORY)); } }; select_files(*this); select_files(*Another); const auto use_fat_time = [&](FileList& Panel) { if (Panel.m_PanelMode == panel_mode::PLUGIN_PANEL) { OpenPanelInfo OpInfo{ sizeof(OpInfo) }; Global->CtrlObject->Plugins->GetOpenPanelInfo(Panel.GetPluginHandle(), &OpInfo); return (OpInfo.Flags & OPIF_COMPAREFATTIME) != 0; } else { string FileSystemName; return os::fs::GetVolumeInformation(GetPathRoot(Panel.m_CurDir), {}, {}, {}, {}, &FileSystemName) && contains_icase(FileSystemName, L"FAT"sv); } }; const auto UseFatTime = use_fat_time(*this) || use_fat_time(*Another); // теперь начнем цикл по снятию выделений // каждый элемент активной панели... for (auto& This: m_ListData) { if (!This.Selected) continue; // ...сравниваем с элементом пассивной панели... for (auto& That: Another->m_ListData) { if (!That.Selected) continue; if (!equal_icase(PointToName(This.FileName), PointToName(That.FileName))) continue; const auto Cmp = (UseFatTime? compare_fat_write_time : compare_time)(This.LastWriteTime, That.LastWriteTime); if (!Cmp && (This.FileSize != That.FileSize)) continue; if (Cmp <= 0) Select(This, false); if (Cmp >= 0) Another->Select(That, false); if (Another->m_PanelMode != panel_mode::PLUGIN_PANEL) break; } } const auto refresh = [](FileList& Panel) { if (Panel.GetSelectedFirstMode()) Panel.SortFileList(true); Panel.Redraw(); }; refresh(*this); refresh(*Another); if (!m_SelFileCount && !Another->m_SelFileCount) Message(0, msg(lng::MCompareTitle), { msg(lng::MCompareSameFolders1), msg(lng::MCompareSameFolders2) }, { lng::MOk }); } void FileList::CopyFiles(bool bMoved) { bool RealNames=false; if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); RealNames = (m_CachedOpenPanelInfo.Flags&OPIF_REALNAMES) != 0; } if (m_PanelMode != panel_mode::PLUGIN_PANEL || RealNames) { string CopyData; for (const auto& i: enum_selected()) { string_view Name = i.FileName; if (IsParentDirectory(i)) Name = Name.substr(0, 1); append(CopyData, CreateFullPathName(Name, (i.Attributes & FILE_ATTRIBUTE_DIRECTORY) != 0, false), L'\0'); } if(!CopyData.empty()) { clipboard_accessor Clip; if(Clip->Open()) { Clip->SetHDROP(CopyData, bMoved); } } } } void FileList::CopyNames(bool FillPathName, bool UNC) { string CopyData; if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); } const auto Eol = eol::system.str(); for (const auto& i: enum_selected()) { if (!CopyData.empty()) append(CopyData, Eol); auto strQuotedName = m_ShowShortNames? i.AlternateFileName() : i.FileName; if (FillPathName) { if (m_PanelMode != panel_mode::PLUGIN_PANEL) { /* $ 14.02.2002 IS ".." в текущем каталоге обработаем как имя текущего каталога */ if (IsParentDirectory(i)) strQuotedName.resize(1); strQuotedName = CreateFullPathName(strQuotedName, (i.Attributes & FILE_ATTRIBUTE_DIRECTORY) != 0, UNC); } else { string strFullName = NullToEmpty(m_CachedOpenPanelInfo.CurDir); if (Global->Opt->PanelCtrlFRule && (m_ViewSettings.Flags&PVS_FOLDERUPPERCASE)) inplace::upper(strFullName); if (!strFullName.empty()) AddEndSlash(strFullName); if (Global->Opt->PanelCtrlFRule) { // имя должно отвечать условиям на панели if ((m_ViewSettings.Flags&PVS_FILELOWERCASE) && !(i.Attributes & FILE_ATTRIBUTE_DIRECTORY)) inplace::lower(strQuotedName); if (m_ViewSettings.Flags&PVS_FILEUPPERTOLOWERCASE) if (!(i.Attributes & FILE_ATTRIBUTE_DIRECTORY) && !IsCaseMixed(strQuotedName)) inplace::lower(strQuotedName); } strQuotedName.insert(0, strFullName); // добавим первый префикс! if (m_PanelMode == panel_mode::PLUGIN_PANEL && Global->Opt->SubstPluginPrefix) { strQuotedName.insert(0, GetPluginPrefix()); } } } else { if (IsParentDirectory(i)) { if (m_PanelMode == panel_mode::PLUGIN_PANEL) { strQuotedName=NullToEmpty(m_CachedOpenPanelInfo.CurDir); } else { strQuotedName = GetCurDir(); } strQuotedName = PointToName(strQuotedName); } } if (Global->Opt->QuotedName&QUOTEDNAME_CLIPBOARD) inplace::QuoteSpace(strQuotedName); CopyData += strQuotedName; } SetClipboardText(CopyData); } void FileList::RefreshTitle() { m_Title = L'{'; if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); append(m_Title, trim(string_view(NullToEmpty(m_CachedOpenPanelInfo.PanelTitle)))); } else { m_Title += m_CurDir; } m_Title += L'}'; } size_t FileList::GetFileCount() const { return m_ListData.size(); } void FileList::ClearSelection() { for (auto& i: m_ListData) { Select(i, false); } if (SelectedFirst) SortFileList(true); } void FileList::SaveSelection() { for (auto& i: m_ListData) { i.PrevSelected = i.Selected; } } void FileList::RestoreSelection() { for (auto& i: m_ListData) { Select(i, std::exchange(i.PrevSelected, i.Selected)); } if (SelectedFirst) SortFileList(true); Redraw(); } bool FileList::GetFileName(string& strName, int Pos, os::fs::attributes& FileAttr) const { if (Pos >= static_cast<int>(m_ListData.size())) return false; strName = m_ListData[Pos].FileName; FileAttr=m_ListData[Pos].Attributes; return true; } const std::unordered_set<string>* FileList::GetFilteredExtensions() const { return &m_FilteredExtensions; } int FileList::GetCurrentPos() const { return m_CurFile; } void FileList::EditFilter() { if (!m_Filter) m_Filter = std::make_unique<multifilter>(this, FFT_PANEL); filters::EditFilters(m_Filter->area(), m_Filter->panel()); } static int select_sort_layer(std::vector<std::pair<panel_sort, sort_order>> const& SortLayers) { std::vector<menu_item> AvailableSortModesMenuItems(static_cast<size_t>(panel_sort::COUNT)); auto VisibleCount = AvailableSortModesMenuItems.size(); for (const auto& i: SortModes) { auto& Item = AvailableSortModesMenuItems[i.MenuPosition]; Item.Name = msg(i.Label); if (std::any_of(ALL_CONST_RANGE(SortLayers), [&](std::pair<panel_sort, sort_order> const& Layer) { return Layer.first == static_cast<panel_sort>(&i - SortModes); })) { Item.Flags |= MIF_HIDDEN; --VisibleCount; } } if (!VisibleCount) return -1; const auto AvailableSortModesMenu = VMenu2::create({}, AvailableSortModesMenuItems); AvailableSortModesMenu->SetHelp(L"PanelCmdSort"sv); AvailableSortModesMenu->SetPosition({ -1, -1, 0, 0 }); AvailableSortModesMenu->SetMenuFlags(VMENU_WRAPMODE); return AvailableSortModesMenu->Run(); } static void edit_sort_layers(int MenuPos) { if (MenuPos >= static_cast<int>(panel_sort::COUNT)) return; const auto SortMode = std::find_if(CONST_RANGE(SortModes, i){ return i.MenuPosition == MenuPos; }) - SortModes; if (static_cast<panel_sort>(SortMode) == panel_sort::UNSORTED) return; auto& SortLayers = Global->Opt->PanelSortLayers[SortMode]; std::vector<menu_item> SortLayersMenuItems; SortLayersMenuItems.reserve(SortLayers.size()); std::transform(ALL_CONST_RANGE(SortLayers), std::back_inserter(SortLayersMenuItems), [](std::pair<panel_sort, sort_order> const& Layer) { return menu_item{ msg(SortModes[static_cast<size_t>(Layer.first)].Label), LIF_CHECKED | order_indicator(Layer.second) }; }); SortLayersMenuItems.front().Flags |= LIF_DISABLE; const auto SortLayersMenu = VMenu2::create({}, SortLayersMenuItems); SortLayersMenu->SetHelp(L"PanelCmdSort"sv); SortLayersMenu->SetPosition({ -1, -1, 0, 0 }); SortLayersMenu->SetMenuFlags(VMENU_WRAPMODE); SortLayersMenu->SetBottomTitle(KeysToLocalizedText(KEY_INS, KEY_DEL, KEY_F4, L'+', L'-', L'*', L'=', KEY_CTRLUP, KEY_CTRLDOWN, KEY_CTRLR)); const auto SetCheck = [&](int const Pos, sort_order const Order) { SortLayersMenu->SetCustomCheck(order_indicator(Order), SortLayersMenu->GetSelectPos()); SortLayers[Pos].second = Order; }; SortLayersMenu->Run([&](const Manager::Key& RawKey) { const auto Pos = SortLayersMenu->GetSelectPos(); if (!Pos) return false; switch (const auto Key = RawKey()) { case KEY_INS: case KEY_NUMPAD0: if (Pos > 0) { if (const auto Result = select_sort_layer(SortLayers); Result >= 0) { const auto NewSortModeIndex = std::find_if(CONST_RANGE(SortModes, i) { return i.MenuPosition == Result; }) - SortModes; const auto Order = SortModes[NewSortModeIndex].DefaultLayers.begin()->second; SortLayersMenu->AddItem(MenuItemEx{ msg(SortModes[NewSortModeIndex].Label), MIF_CHECKED | order_indicator(Order) }, Pos); SortLayersMenu->SetSelectPos(Pos); SortLayers.emplace(SortLayers.begin() + Pos, static_cast<panel_sort>(NewSortModeIndex), Order); } } break; case KEY_DEL: case KEY_NUMDEL: if (Pos > 0) { SortLayersMenu->DeleteItem(Pos); SortLayers.erase(SortLayers.begin() + Pos); } break; case KEY_F4: if (const auto Result = select_sort_layer(SortLayers); Result >= 0) { const auto NewSortModeIndex = std::find_if(CONST_RANGE(SortModes, i) { return i.MenuPosition == Result; }) - SortModes; const auto Order = SortModes[NewSortModeIndex].DefaultLayers.begin()->second; SortLayersMenu->at(Pos).Name = msg(SortModes[NewSortModeIndex].Label); SortLayersMenu->at(Pos).SetCustomCheck(order_indicator(Order)); SortLayers[Pos] = { static_cast<panel_sort>(NewSortModeIndex), Order }; } break; case L'+': case KEY_ADD: SetCheck(Pos, sort_order::ascend); break; case L'-': case KEY_SUBTRACT: SetCheck(Pos, sort_order::descend); break; case L'*': case KEY_MULTIPLY: { const auto CurrentOrder = SortLayers[Pos].second; const auto NewOrder = CurrentOrder == sort_order::ascend? sort_order::descend : CurrentOrder == sort_order::descend? sort_order::ascend : CurrentOrder; SetCheck(Pos, NewOrder); } break; case L'=': if (Pos > 0) SetCheck(Pos, sort_order::keep); break; case KEY_CTRLUP: case KEY_RCTRLUP: case KEY_CTRLDOWN: case KEY_RCTRLDOWN: if (Pos > 0) { const auto OtherPos = Pos + ((Key & KEY_UP) == KEY_UP? -1 : 1); if (in_closed_range(1, OtherPos, static_cast<int>(SortLayers.size() - 1))) { using std::swap; swap(SortLayersMenu->at(Pos), SortLayersMenu->at(OtherPos)); swap(SortLayers[Pos], SortLayers[OtherPos]); SortLayersMenu->SetSelectPos(OtherPos); } } break; case KEY_CTRLR: case KEY_RCTRLR: { const auto DefaultLayers = default_sort_layers(static_cast<panel_sort>(SortMode)); SortLayers.assign(ALL_CONST_RANGE(DefaultLayers)); SortLayersMenu->Close(-1); return true; } default: break; } return false; }); } void FileList::SelectSortMode() { std::vector<menu_item> SortMenu(std::size(SortModes)); for (const auto& i: SortModes) { auto& Item = SortMenu[i.MenuPosition]; Item.Name = msg(i.Label); Item.AccelKey = i.MenuKey; } static const menu_item MenuSeparator = { {}, LIF_SEPARATOR }; OpenMacroPluginInfo ompInfo = { MCT_GETCUSTOMSORTMODES,nullptr }; MacroPluginReturn* mpr = nullptr; size_t extra = 0; // number of additional menu items due to custom sort modes { void *ptr; if (Global->CtrlObject->Plugins->CallPlugin(Global->Opt->KnownIDs.Luamacro.Id, OPEN_LUAMACRO, &ompInfo, &ptr) && ptr) { mpr = &ompInfo.Ret; if (mpr->Count >= 3) { extra = 1 + mpr->Count/3; // add 1 item for separator SortMenu.reserve(SortMenu.size() + extra); SortMenu.emplace_back(MenuSeparator); for (size_t i=0; i < mpr->Count; i += 3) { SortMenu.emplace_back(menu_item{ mpr->Values[i + 2].String }); } } else mpr = nullptr; } } const auto& SetCheckAndSelect = [&](size_t const Index) { auto& MenuItem = SortMenu[Index]; MenuItem.SetCustomCheck(order_indicator(m_ReverseSortOrder? sort_order::descend : sort_order::ascend)); MenuItem.SetSelect(true); }; if (m_SortMode < panel_sort::COUNT) { SetCheckAndSelect(SortModes[static_cast<size_t>(m_SortMode)].MenuPosition); } else if (m_SortMode >= panel_sort::BY_USER && mpr) { for (size_t i=0; i < mpr->Count; i += 3) { if (static_cast<int>(mpr->Values[i].Double) == static_cast<int>(m_SortMode)) { SetCheckAndSelect(std::size(SortModes) + 1 + i / 3); break; } } } else { LOGWARNING(L"Unknown sort mode {}"sv, m_SortMode); } enum SortOptions { SortOptUseGroups, SortOptSelectedFirst, SortOptDirectoriesFirst, SortOptCount }; const menu_item InitSortMenuOptions[]= { { msg(lng::MMenuSortUseGroups), GetSortGroups()? MIF_CHECKED : 0, KEY_SHIFTF11 }, { msg(lng::MMenuSortSelectedFirst), SelectedFirst? MIF_CHECKED : 0, KEY_SHIFTF12 }, { msg(lng::MMenuSortDirectoriesFirst), m_DirectoriesFirst? MIF_CHECKED : 0, 0 }, }; static_assert(std::size(InitSortMenuOptions) == SortOptCount); SortMenu.reserve(SortMenu.size() + 1 + std::size(InitSortMenuOptions)); // + 1 for separator SortMenu.emplace_back(MenuSeparator); SortMenu.insert(SortMenu.end(), ALL_CONST_RANGE(InitSortMenuOptions)); int SortCode = -1; bool InvertPressed = true; bool PlusPressed = false; { const auto MenuStrings = VMenu::AddHotkeys(SortMenu); const auto SortModeMenu = VMenu2::create(msg(lng::MMenuSortTitle), SortMenu); SortModeMenu->SetHelp(L"PanelCmdSort"sv); SortModeMenu->SetPosition({ m_Where.left + 4, -1, 0, 0 }); SortModeMenu->SetMenuFlags(VMENU_WRAPMODE); SortModeMenu->SetId(SelectSortModeId); SortModeMenu->SetBottomTitle(KeysToLocalizedText(L'+', L'-', L'*', KEY_F4)); SortCode=SortModeMenu->Run([&](const Manager::Key& RawKey) { const auto Key=RawKey(); bool KeyProcessed = false; switch (Key) { case L'*': case KEY_MULTIPLY: KeyProcessed = true; break; case L'+': case KEY_ADD: case L'-': case KEY_SUBTRACT: InvertPressed = false; PlusPressed = any_of(Key, L'+', KEY_ADD); KeyProcessed = true; break; case KEY_F4: edit_sort_layers(SortModeMenu->GetSelectPos()); break; default: break; } if (KeyProcessed) { SortModeMenu->Close(SortModeMenu->GetSelectPos()); } return KeyProcessed; }); } if (SortCode<0) { return; } // predefined sort modes if (static_cast<size_t>(SortCode) < std::size(SortModes)) { bool KeepOrder = false; if (!InvertPressed) { m_ReverseSortOrder = !PlusPressed; KeepOrder = true; } const auto SortMode = static_cast<panel_sort>(std::find_if(CONST_RANGE(SortModes, i){ return i.MenuPosition == SortCode; }) - SortModes); SetSortMode(SortMode, KeepOrder); } // custom sort modes else if (static_cast<size_t>(SortCode) >= std::size(SortModes) + 1 && static_cast<size_t>(SortCode) < std::size(SortModes) + 1 + extra - 1) { const auto index = 3*(SortCode-std::size(SortModes)-1); const auto mode = static_cast<int>(mpr->Values[index].Double); if (custom_sort::CanSort(mode)) { const auto InvertByDefault = mpr->Values[index+1].Boolean != 0; auto Order = sort_order::flip_or_default; if (!InvertPressed) { m_ReverseSortOrder = !PlusPressed; Order = sort_order::keep; } SetCustomSortMode(panel_sort{ mode }, Order, InvertByDefault); } } // sort options else { const auto Switch = [&](bool CurrentState) { return PlusPressed || (InvertPressed && !CurrentState); }; switch (SortCode - std::size(SortModes) - extra - 1) // -1 for separator { case SortOptUseGroups: if (m_SortGroups != Switch(m_SortGroups)) ProcessKey(Manager::Key(KEY_SHIFTF11)); break; case SortOptSelectedFirst: if (SelectedFirst != Switch(SelectedFirst)) ProcessKey(Manager::Key(KEY_SHIFTF12)); break; case SortOptDirectoriesFirst: ChangeDirectoriesFirst(Switch(m_DirectoriesFirst)); break; } } } void FileList::DeleteDiz(const string& Name, const string& ShortName) { if (m_PanelMode == panel_mode::NORMAL_PANEL) Diz.Erase(Name,ShortName); } void FileList::FlushDiz() { if (m_PanelMode == panel_mode::NORMAL_PANEL) Diz.Flush(m_CurDir); } string FileList::GetDizName() const { return m_PanelMode == panel_mode::NORMAL_PANEL? Diz.GetDizName() : string(); } string_view FileList::GetDescription(const string& Name, const string& ShortName, long long const FileSize) const { return Diz.Get(Name, ShortName, FileSize); } void FileList::CopyDiz(const string& Name, const string& ShortName,const string& DestName, const string& DestShortName,DizList *DestDiz) { Diz.CopyDiz(Name, ShortName, DestName, DestShortName, DestDiz); } void FileList::DescribeFiles() { int DizCount=0; ReadDiz(); SaveSelection(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); const auto AnotherType = AnotherPanel->GetType(); for (const auto& i: enum_selected()) { const auto PrevText = Diz.Get(i.FileName, i.AlternateFileName(), i.FileSize); const auto strMsg = concat(msg(lng::MEnterDescription), L' ', quote_space(i.FileName), L':'); /* $ 09.08.2000 SVS Для Ctrl-Z не нужно брать предыдущее значение! */ string strDizText; if (!GetString( msg(lng::MDescribeFiles), strMsg, L"DizText"sv, PrevText, strDizText, L"FileDiz"sv, FIB_ENABLEEMPTY | (!DizCount? FIB_NOUSELASTHISTORY : 0) | FIB_BUTTONS, {}, {}, {}, &DescribeFileId)) { break; } DizCount++; if (strDizText.empty()) { Diz.Erase(i.FileName, i.AlternateFileName()); } else { Diz.Set(i.FileName, i.AlternateFileName(), strDizText); } ClearLastGetSelection(); // BugZ#442 - Deselection is late when making file descriptions FlushDiz(); // BugZ#863 - При редактировании группы дескрипшенов они не обновляются на ходу //if (AnotherType==QVIEW_PANEL) continue; //TODO ??? if (AnotherType == panel_type::INFO_PANEL) AnotherPanel->Update(0); Update(UPDATE_KEEP_SELECTION); Redraw(); } /*if (DizCount>0) { FlushDiz(); Update(UPDATE_KEEP_SELECTION); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY); AnotherPanel->Redraw(); }*/ } void FileList::SetReturnCurrentFile(bool Mode) { ReturnCurrentFile=Mode; } bool FileList::ApplyCommand() { static string strPrevCommand; string strCommand; if (!GetString( msg(lng::MAskApplyCommandTitle), msg(lng::MAskApplyCommand), L"ApplyCmd"sv, strPrevCommand, strCommand, L"ApplyCmd"sv, FIB_BUTTONS | FIB_EDITPATH | FIB_EDITPATHEXEC, {}, {}, {}, &ApplyCommandId ) || !SetCurPath()) return false; strPrevCommand = strCommand; inplace::trim_left(strCommand); SaveSelection(); ++UpdateDisabled; Parent()->GetCmdLine()->LockUpdatePanel(true); { const auto ExecutionContext = Global->WindowManager->Desktop()->ConsoleSession().GetContext(); for (const auto& i: enum_selected()) { if (CheckForEscAndConfirmAbort()) break; string strConvertedCommand = strCommand; bool PreserveLFN = false; if (SubstFileName(strConvertedCommand, { i.FileName, i.AlternateFileName() }, &PreserveLFN) && !strConvertedCommand.empty()) { SCOPED_ACTION(PreserveLongName)(i.FileName, PreserveLFN); execute_info Info; Info.DisplayCommand = strConvertedCommand; Info.Command = strConvertedCommand; Parent()->GetCmdLine()->ExecString(Info); } ClearLastGetSelection(); } } Parent()->GetCmdLine()->LockUpdatePanel(false); Parent()->GetCmdLine()->Show(); if (Global->Opt->ShowKeyBar) { Parent()->GetKeybar().Show(); } if (GetSelPosition >= static_cast<int>(m_ListData.size())) ClearSelection(); --UpdateDisabled; return true; } void FileList::CountDirSize(bool IsRealNames) { unsigned long SelDirCount=0; DirInfoData Data = {}; //Рефреш текущему времени для фильтра перед началом операции m_Filter->UpdateCurrentTime(); struct { unsigned long long Items; unsigned long long Size; } Total{}; time_check TimeCheck; std::optional<dirinfo_progress> DirinfoProgress; const auto DirInfoCallback = [&](string_view const Name, unsigned long long const ItemsCount, unsigned long long const Size) { if (!TimeCheck) return; if (!DirinfoProgress) DirinfoProgress.emplace(msg(lng::MDirInfoViewTitle)); DirinfoProgress->set_name(Name); DirinfoProgress->set_count(Total.Items + ItemsCount); DirinfoProgress->set_size(Total.Size + Size); }; for (auto& i: m_ListData) { if (i.Selected && (i.Attributes & FILE_ATTRIBUTE_DIRECTORY)) { SelDirCount++; if ((!IsRealNames && !IsParentDirectory(i) && GetPluginDirInfo(GetPluginHandle(), i.FileName, &i.UserData, Data, DirInfoCallback)) || (IsRealNames && GetDirInfo(i.FileName, Data, m_Filter.get(), DirInfoCallback, GETDIRINFO_SCANSYMLINKDEF) == 1)) { SelFileSize -= i.FileSize; SelFileSize += Data.FileSize; i.FileSize = Data.FileSize; i.AllocationSize = Data.AllocationSize; i.ShowFolderSize = 1; Total.Items += Data.DirCount + Data.FileCount; Total.Size += Data.FileSize; } else break; } } const auto GetPluginDirInfoOrParent = [this, &Total](const plugin_panel* const ph, string_view const DirName, const UserDataItem* const UserData, BasicDirInfoData& BasicData, const dirinfo_callback& Callback) { if (!m_CurFile && IsParentDirectory(m_ListData[0])) { const auto PluginCurDir = (m_CachedOpenPanelInfo.CurDir && *m_CachedOpenPanelInfo.CurDir)? PointToName(m_CachedOpenPanelInfo.CurDir) : L"\\"sv; const auto ParentDirInfoCallback = [&](string_view const, unsigned long long const ItemsCount, unsigned long long const Size) { return Callback(PluginCurDir, ItemsCount, Size); }; for (const auto& i: range(m_ListData.begin() + 1, m_ListData.end())) { if (i.Attributes & FILE_ATTRIBUTE_DIRECTORY) { ++BasicData.DirCount; if (!IsParentDirectory(i)) { BasicDirInfoData SubData{}; if (!GetPluginDirInfo(GetPluginHandle(), i.FileName, &i.UserData, SubData, ParentDirInfoCallback)) return false; BasicData.FileCount += SubData.FileCount; BasicData.DirCount += SubData.DirCount; BasicData.FileSize += SubData.FileSize; BasicData.AllocationSize += SubData.AllocationSize; Total.Items += SubData.DirCount + SubData.FileCount; Total.Size += SubData.FileSize; } } else { ++BasicData.FileCount; BasicData.FileSize += i.FileSize; BasicData.AllocationSize += i.AllocationSize; ++Total.Items; Total.Size += i.FileSize; } } return true; } else { return GetPluginDirInfo(ph, DirName, UserData, BasicData, Callback); } }; if (!SelDirCount) { assert(m_CurFile < static_cast<int>(m_ListData.size())); auto& CurFile = m_ListData[m_CurFile]; if ((!IsRealNames && GetPluginDirInfoOrParent(GetPluginHandle(), CurFile.FileName, &CurFile.UserData, Data, DirInfoCallback)) || (IsRealNames && GetDirInfo(IsParentDirectory(CurFile)? L"."s : CurFile.FileName, Data, m_Filter.get(), DirInfoCallback, GETDIRINFO_SCANSYMLINKDEF) == 1)) { CurFile.FileSize = Data.FileSize; CurFile.AllocationSize = Data.AllocationSize; CurFile.ShowFolderSize = 1; } } SortFileList(true); ShowFileList(); Parent()->Redraw(); InitFSWatcher(true); } int FileList::GetPrevViewMode() const { return (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginsList.empty())?PluginsList.front()->m_PrevViewMode:m_ViewMode; } panel_sort FileList::GetPrevSortMode() const { return (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginsList.empty())?PluginsList.front()->m_PrevSortMode:m_SortMode; } bool FileList::GetPrevSortOrder() const { return (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginsList.empty())?PluginsList.front()->m_PrevSortOrder : m_ReverseSortOrder; } bool FileList::GetPrevDirectoriesFirst() const { return (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginsList.empty())?PluginsList.front()->m_PrevDirectoriesFirst:m_DirectoriesFirst; } plugin_panel* FileList::OpenFilePlugin(const string& FileName, int PushPrev, OPENFILEPLUGINTYPE Type, bool* StopProcessing) { if (!PushPrev && m_PanelMode == panel_mode::PLUGIN_PANEL) { for (;;) { if (ProcessPluginEvent(FE_CLOSE,nullptr)) { if (StopProcessing) *StopProcessing = true; return nullptr; } if (!PopPlugin(TRUE)) break; } } auto hNewPlugin = OpenPluginForFile(FileName, 0, Type, StopProcessing); const auto hNewPluginRawCopy = hNewPlugin.get(); if (hNewPlugin) { if (PushPrev) { PrevDataList.emplace_back(FileName, std::move(m_ListData), m_CurTopFile); } const auto WasFullscreen = IsFullScreen(); SetPluginMode(std::move(hNewPlugin), FileName); // SendOnFocus??? true??? m_PanelMode = panel_mode::PLUGIN_PANEL; UpperFolderTopFile=m_CurTopFile; m_CurFile=0; Update(0); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); if ((AnotherPanel->GetType() == panel_type::INFO_PANEL) || WasFullscreen) AnotherPanel->Redraw(); } return hNewPluginRawCopy; } void FileList::ProcessCopyKeys(unsigned const Key) { if (m_ListData.empty() || !SetCurPath()) return; const auto Drag = any_of(Key, KEY_DRAGCOPY, KEY_DRAGMOVE); const auto Ask = !Drag || Global->Opt->Confirm.Drag; const auto Move = any_of(Key, KEY_F6, KEY_DRAGMOVE); const auto AnotherPanel = Parent()->GetAnotherPanel(this); auto AnotherDir = false; if (const auto AnotherFilePanel = std::dynamic_pointer_cast<FileList>(AnotherPanel)) { assert(AnotherFilePanel->m_ListData.empty() || AnotherFilePanel->m_CurFile < static_cast<int>(AnotherFilePanel->m_ListData.size())); if (!AnotherFilePanel->m_ListData.empty() && (AnotherFilePanel->m_ListData[AnotherFilePanel->m_CurFile].Attributes & FILE_ATTRIBUTE_DIRECTORY) && !IsParentDirectory(AnotherFilePanel->m_ListData[AnotherFilePanel->m_CurFile])) { AnotherDir = true; } } if (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginManager::UseInternalCommand(GetPluginHandle(), PLUGIN_FARGETFILES, m_CachedOpenPanelInfo)) { if (none_of(Key, KEY_ALTF6, KEY_RALTF6)) { string strPluginDestPath; int ToPlugin = 0; if ( AnotherPanel->GetMode() == panel_mode::PLUGIN_PANEL && AnotherPanel->IsVisible() && !PluginManager::UseInternalCommand(AnotherPanel->GetPluginHandle(),PLUGIN_FARPUTFILES, m_CachedOpenPanelInfo)) { ToPlugin=2; Copy(shared_from_this(), Move, false, false, Ask, ToPlugin, &strPluginDestPath); } if (ToPlugin!=-1) { if (ToPlugin) PluginToPluginFiles(Move); else { string strDestPath; if (!strPluginDestPath.empty()) strDestPath = strPluginDestPath; else { strDestPath = AnotherPanel->GetCurDir(); if (!AnotherPanel->IsVisible()) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (m_CachedOpenPanelInfo.HostFile && *m_CachedOpenPanelInfo.HostFile) { strDestPath = PointToName(m_CachedOpenPanelInfo.HostFile); const auto pos = strDestPath.rfind(L'.'); if (pos != string::npos) strDestPath.resize(pos); } } } PluginGetFiles(strDestPath, Move); } } } } else { int ToPlugin = AnotherPanel->GetMode() == panel_mode::PLUGIN_PANEL && AnotherPanel->IsVisible() && none_of(Key, KEY_ALTF6, KEY_RALTF6) && !PluginManager::UseInternalCommand(AnotherPanel->GetPluginHandle(),PLUGIN_FARPUTFILES, m_CachedOpenPanelInfo); Copy(shared_from_this(), Move, any_of(Key, KEY_ALTF6, KEY_RALTF6), false, Ask, ToPlugin, nullptr, Drag && AnotherDir); if (ToPlugin==1) PluginPutFilesToAnother(Move,AnotherPanel); } } void FileList::SetSelectedFirstMode(bool Mode) { SelectedFirst=Mode; SortFileList(true); ProcessPluginEvent(FE_CHANGESORTPARAMS, nullptr); } void FileList::ChangeSortOrder(bool Reverse) { Panel::ChangeSortOrder(Reverse); SortFileList(true); ProcessPluginEvent(FE_CHANGESORTPARAMS, nullptr); Show(); } void FileList::UpdateKeyBar() { auto& Keybar = Parent()->GetKeybar(); Keybar.SetLabels(lng::MF1); Keybar.SetCustomLabels(KBA_SHELL); if (GetMode() == panel_mode::PLUGIN_PANEL) { GetOpenPanelInfo(&m_CachedOpenPanelInfo); if (m_CachedOpenPanelInfo.KeyBar) Keybar.Change(m_CachedOpenPanelInfo.KeyBar); } } bool FileList::PluginPanelHelp(const plugin_panel* hPlugin) const { string_view strPath = hPlugin->plugin()->ModuleName(); CutToSlash(strPath); const auto [File, Name, Codepage] = OpenLangFile(strPath, Global->HelpFileMask, Global->Opt->strHelpLanguage); if (!File) return false; help::show(help::make_link(strPath, L"Contents"sv)); return true; } /* $ 19.11.2001 IS для файловых панелей с реальными файлами никакого префикса не добавляем */ string FileList::GetPluginPrefix() const { if (!Global->Opt->SubstPluginPrefix || GetMode() != panel_mode::PLUGIN_PANEL) return {}; Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (!(m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES)) { PluginInfo PInfo = {sizeof(PInfo)}; if (Global->CtrlObject->Plugins->GetPluginInfo(GetPluginHandle()->plugin(), &PInfo) && PInfo.CommandPrefix && *PInfo.CommandPrefix) { const string_view Prefix = PInfo.CommandPrefix; return Prefix.substr(0, Prefix.find(L':')) + L":"sv; } } return {}; } void FileList::GoHome(string_view const Drive) { const auto FarRoot = extract_root_directory(Global->g_strFarModuleName); const auto go_home = [&](Panel& p) { if (p.GetMode() == panel_mode::PLUGIN_PANEL) return; if (starts_with_icase(p.GetCurDir(), Drive)) p.SetCurDir(FarRoot, false); }; // Passive first to prevent redraw issues in wide panel mode go_home(*Parent()->GetAnotherPanel(this)); go_home(*this); } const FileListItem* FileList::GetItem(size_t Index) const { if (static_cast<int>(Index) == -1 || static_cast<int>(Index) == -2) Index=GetCurrentPos(); if (Index >= m_ListData.size()) return nullptr; return &m_ListData[Index]; } void FileList::ClearAllItem() { PrevDataList.clear(); } // flplugin // Файловая панель - работа с плагинами /* В стеке ФАРова панель не хранится - только плагиновые! */ void FileList::PushPlugin(std::unique_ptr<plugin_panel>&& hPlugin, string_view const HostFile) { PluginsList.emplace_back(std::make_shared<PluginsListItem>(std::move(hPlugin), HostFile, false, m_ViewMode, m_SortMode, m_ReverseSortOrder, m_DirectoriesFirst, m_ViewSettings)); ++Global->PluginPanelsCount; } bool FileList::PopPlugin(int EnableRestoreViewMode) { m_ListData.clear(); if (PluginsList.empty()) { m_PanelMode = panel_mode::NORMAL_PANEL; return false; } auto CurPlugin = std::move(PluginsList.back()); PluginsList.pop_back(); --Global->PluginPanelsCount; // We have removed current plugin panel from PluginsList already. // However, ClosePanel provides a notification and plugins might call API functions from it. // So GetPluginHandle() will look into m_ExpiringPluginPanel first. { m_ExpiringPluginPanel = CurPlugin; SCOPE_EXIT{ m_ExpiringPluginPanel = nullptr; }; Global->CtrlObject->Plugins->ClosePanel(std::move(CurPlugin->m_Plugin)); } if (!PluginsList.empty()) { if (EnableRestoreViewMode) { SetViewMode(CurPlugin->m_PrevViewMode); m_SortMode = CurPlugin->m_PrevSortMode; m_ReverseSortOrder = CurPlugin->m_PrevSortOrder; m_DirectoriesFirst = CurPlugin->m_PrevDirectoriesFirst; } if (CurPlugin->m_Modified) { PluginPanelItemHolderHeap PanelItem={}; const auto strSaveDir = os::fs::GetCurrentDirectory(); if (FileNameToPluginItem(CurPlugin->m_HostFile, PanelItem)) { Global->CtrlObject->Plugins->PutFiles(GetPluginHandle(), { &PanelItem.Item, 1 }, false, 0); } else { PluginPanelItem Item{}; Item.FileName = PointToName(CurPlugin->m_HostFile).data(); Global->CtrlObject->Plugins->DeleteFiles(GetPluginHandle(), { &Item, 1 }, 0); } FarChDir(strSaveDir); } Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (!(m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES)) { DeleteFileWithFolder(CurPlugin->m_HostFile); // удаление файла от предыдущего плагина } } else { m_PanelMode = panel_mode::NORMAL_PANEL; if (EnableRestoreViewMode) { SetViewMode(CurPlugin->m_PrevViewMode); m_SortMode = CurPlugin->m_PrevSortMode; m_ReverseSortOrder = CurPlugin->m_PrevSortOrder; m_DirectoriesFirst = CurPlugin->m_PrevDirectoriesFirst; } } if (EnableRestoreViewMode) Parent()->RedrawKeyBar(); return true; } /* DefaultName - имя элемента на которое позиционируемся. Closed - панель закрывается, если в PrevDataList что-то есть - восстанавливаемся оттуда. UsePrev - если востанавливаемся из PrevDataList, элемент для позиционирования брать оттуда же. Position - надо ли вообще устанавливать текущий элемент. */ void FileList::PopPrevData(string_view const DefaultName, bool const Closed, bool const UsePrev, bool const Position, bool const SetDirectorySuccess) { string strName(DefaultName); if (Closed && !PrevDataList.empty()) { PrevDataItem& Item = PrevDataList.back(); if (Item.PrevListData.size() > 1) { MoveSelection(Item.PrevListData, m_ListData); UpperFolderTopFile = Item.PrevTopFile; if (UsePrev) strName = Item.strPrevName; Item.PrevListData.clear(); if (SelectedFirst) SortFileList(false); else if (!m_ListData.empty()) SortFileList(true); } PrevDataList.pop_back(); } if (Position) { const auto Pos = FindFile(PointToName(strName)); if (Pos!=-1) m_CurFile=Pos; else GoToFile(strName); m_CurTopFile=UpperFolderTopFile; UpperFolderTopFile=0; CorrectPosition(); } else if (SetDirectorySuccess) m_CurFile = m_CurTopFile = 0; } bool FileList::FileNameToPluginItem(string_view const Name, PluginPanelItemHolder& pi) { string_view TempDir = Name; if (!CutToSlash(TempDir,true)) return false; FarChDir(TempDir); os::fs::find_data fdata; if (os::fs::get_find_data(Name, fdata)) { FindDataExToPluginPanelItemHolder(fdata, pi); return true; } return false; } static void FileListItemToPluginPanelItemBasic(const FileListItem& From, PluginPanelItem& To) { To.CreationTime = os::chrono::nt_clock::to_filetime(From.CreationTime); To.LastAccessTime = os::chrono::nt_clock::to_filetime(From.LastAccessTime); To.LastWriteTime = os::chrono::nt_clock::to_filetime(From.LastWriteTime); To.ChangeTime = os::chrono::nt_clock::to_filetime(From.ChangeTime); To.FileSize = From.FileSize; To.AllocationSize = From.AllocationSize; To.FileName = {}; To.AlternateFileName = {}; To.Description = {}; To.Owner = {}; To.CustomColumnData = {}; To.CustomColumnNumber = From.CustomColumns.size(); To.Flags = From.UserFlags | (From.Selected ? PPIF_SELECTED : 0); To.UserData = From.UserData; To.FileAttributes = From.Attributes; To.NumberOfLinks = {}; To.CRC32 = From.CRC32; std::fill(ALL_RANGE(To.Reserved), 0); } void FileList::FileListToPluginItem(const FileListItem& fi, PluginPanelItemHolder& Holder) const { auto& pi = Holder.Item; FileListItemToPluginPanelItemBasic(fi, pi); pi.NumberOfLinks = fi.IsNumberOfLinksRead() ? fi.NumberOfLinks(this) : 0; Holder.set_name(fi.FileName); Holder.set_alt_name(fi.AlternateFileName()); Holder.set_columns(fi.CustomColumns); if (fi.DizText) Holder.set_description(fi.DizText); if (fi.IsOwnerRead()) { if (const auto& Owner = fi.Owner(this); !Owner.empty()) Holder.set_owner(Owner); } } size_t FileList::FileListToPluginItem2(const FileListItem& fi,FarGetPluginPanelItem* gpi) const { const auto StringSizeInBytes = [](string_view const Str) { return (Str.size() + 1) * sizeof(wchar_t); }; const auto StaticSize = aligned_sizeof<PluginPanelItem, sizeof(wchar_t)>(), FilenameSize = aligned_size(StringSizeInBytes(fi.FileName), alignof(wchar_t)), AltNameSize = aligned_size(StringSizeInBytes(fi.AlternateFileName()), alignof(wchar_t*)), ColumnsSize = aligned_size(fi.CustomColumns.size() * sizeof(wchar_t*), alignof(wchar_t)), ColumnsDataSize = aligned_size(std::accumulate(ALL_CONST_RANGE(fi.CustomColumns), size_t(0), [&](size_t s, const wchar_t* i) { return s + (i? StringSizeInBytes(i) : 0); }), alignof(wchar_t)), DescriptionSize = aligned_size(fi.DizText? StringSizeInBytes(fi.DizText) : 0, alignof(wchar_t)), OwnerSize = aligned_size(fi.IsOwnerRead() && !fi.Owner(this).empty()? StringSizeInBytes(fi.Owner(this)) : 0, alignof(wchar_t)); const auto size = StaticSize + FilenameSize + AltNameSize + ColumnsSize + ColumnsDataSize + DescriptionSize + OwnerSize; if (!gpi || !gpi->Item || gpi->Size < sizeof(*gpi->Item)) return size; FileListItemToPluginPanelItemBasic(fi, *gpi->Item); gpi->Item->NumberOfLinks = fi.IsNumberOfLinksRead()? fi.NumberOfLinks(this) : 0; auto data = reinterpret_cast<char*>(gpi->Item); const auto end = data + gpi->Size; data += StaticSize; const auto CopyToBuffer = [&](string_view const Str) { const auto Result = reinterpret_cast<const wchar_t*>(data); *copy_string(Str, reinterpret_cast<wchar_t*>(data)) = {}; return Result; }; const auto not_enough_for = [&](size_t const Size) { return data == end || data + Size > end; }; if (not_enough_for(FilenameSize)) return size; gpi->Item->FileName = CopyToBuffer(fi.FileName); data += FilenameSize; if (not_enough_for(AltNameSize)) return size; gpi->Item->AlternateFileName = CopyToBuffer(fi.AlternateFileName()); data += AltNameSize; if (ColumnsSize) { if (not_enough_for(ColumnsSize)) return size; gpi->Item->CustomColumnData = reinterpret_cast<const wchar_t* const*>(data); data += ColumnsSize; } if (ColumnsDataSize) { const auto dataBegin = data; if (not_enough_for(ColumnsDataSize)) { gpi->Item->CustomColumnData = {}; return size; } for (const auto& [Column, Data]: zip(fi.CustomColumns, span(const_cast<const wchar_t**>(gpi->Item->CustomColumnData), fi.CustomColumns.size()))) { if (!Column) { Data = {}; continue; } Data = CopyToBuffer(Column); data += StringSizeInBytes(Column); } data = dataBegin + ColumnsDataSize; } if (DescriptionSize) { if (not_enough_for(DescriptionSize)) return size; gpi->Item->Description = CopyToBuffer(fi.DizText); data += DescriptionSize; } if (OwnerSize) { if (not_enough_for(OwnerSize)) return size; gpi->Item->Owner = CopyToBuffer(fi.Owner(this)); data += OwnerSize; } return size; } FileListItem::FileListItem(const PluginPanelItem& pi) { CreationTime = os::chrono::nt_clock::from_filetime(pi.CreationTime); LastAccessTime = os::chrono::nt_clock::from_filetime(pi.LastAccessTime); LastWriteTime = os::chrono::nt_clock::from_filetime(pi.LastWriteTime); ChangeTime = os::chrono::nt_clock::from_filetime(pi.ChangeTime); FileSize = pi.FileSize; AllocationSize = pi.AllocationSize; UserFlags = pi.Flags; UserData = pi.UserData; Attributes = pi.FileAttributes; // we don't really know, but it's better than show it as 'unknown' ReparseTag = (Attributes & FILE_ATTRIBUTE_REPARSE_POINT)? IO_REPARSE_TAG_SYMLINK : 0; if (pi.CustomColumnData && pi.CustomColumnNumber) { CustomColumns.reserve(pi.CustomColumnNumber); for (const auto& i: span(pi.CustomColumnData, pi.CustomColumnNumber)) { if (!i) { CustomColumns.emplace_back(); continue; } string_view const Data = i; auto Str = std::make_unique<wchar_t[]>(Data.size() + 1); *copy_string(Data, Str.get()) = {}; CustomColumns.emplace_back(Str.release()); } } SortGroup = DEFAULT_SORT_GROUP; CRC32 = pi.CRC32; if (pi.Description) { string_view const Description = pi.Description; auto Str = std::make_unique<wchar_t[]>(Description.size() + 1); *copy_string(Description, Str.get()) = {}; DizText = Str.release(); DeleteDiz = true; } FileName = NullToEmpty(pi.FileName); SetAlternateFileName(NullToEmpty(pi.AlternateFileName)); m_Owner = NullToEmpty(pi.Owner); m_NumberOfLinks = pi.NumberOfLinks; m_NumberOfStreams = 1; m_StreamsSize = FileSize; } std::unique_ptr<plugin_panel> FileList::OpenPluginForFile(const string& FileName, os::fs::attributes const FileAttr, OPENFILEPLUGINTYPE const Type, bool* const StopProcessing) { if (FileName.empty() || FileAttr & FILE_ATTRIBUTE_DIRECTORY) return nullptr; SetCurPath(); Parent()->GetAnotherPanel(this)->CloseFile(); return Global->CtrlObject->Plugins->OpenFilePlugin(&FileName, OPM_NONE, Type, StopProcessing); } plugin_item_list FileList::CreatePluginItemList() { plugin_item_list ItemList; if (m_ListData.empty()) return ItemList; const auto SaveSelPosition = GetSelPosition; const auto OldLastSelPosition = LastSelPosition; ItemList.reserve(m_SelFileCount+1); const auto ConvertAndAddToList = [&](const FileListItem& What) { PluginPanelItemHolderHeapNonOwning NewItem; FileListToPluginItem(What, NewItem); ItemList.emplace_back(NewItem.Item); }; for (const auto& i: enum_selected()) { if (!IsParentDirectory(i) && LastSelPosition >= 0 && static_cast<size_t>(LastSelPosition) < m_ListData.size()) ConvertAndAddToList(m_ListData[LastSelPosition]); } if (ItemList.empty() && !m_ListData.empty() && IsParentDirectory(m_ListData.front())) ConvertAndAddToList(m_ListData.front()); LastSelPosition=OldLastSelPosition; GetSelPosition=SaveSelPosition; return ItemList; } void FileList::PluginDelete() { SaveSelection(); { auto ItemList = CreatePluginItemList(); if (ItemList.empty()) return; const auto Item = GetPluginItem(); if (Global->CtrlObject->Plugins->DeleteFiles(Item.lock()->m_Plugin.get(), ItemList, 0) && !Item.expired()) { SetPluginModified(); PutDizToPlugin(this, ItemList.items(), true, false, nullptr); } } Update(UPDATE_KEEP_SELECTION); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY); AnotherPanel->Redraw(); } void FileList::PutDizToPlugin(FileList *DestPanel, const std::vector<PluginPanelItem>& ItemList, bool Delete, bool Move, DizList *SrcDiz) const { Global->CtrlObject->Plugins->GetOpenPanelInfo(DestPanel->GetPluginHandle(), &m_CachedOpenPanelInfo); if (DestPanel->strPluginDizName.empty() && m_CachedOpenPanelInfo.DescrFilesNumber>0) DestPanel->strPluginDizName = m_CachedOpenPanelInfo.DescrFiles[0]; if (Global->Opt->Diz.UpdateMode != DIZ_UPDATE_ALWAYS && !(Global->Opt->Diz.UpdateMode == DIZ_UPDATE_IF_DISPLAYED && IsDizDisplayed())) return; if (DestPanel->strPluginDizName.empty()) return; if (m_CachedOpenPanelInfo.HostFile && *m_CachedOpenPanelInfo.HostFile && !DestPanel->GetModalMode() && !os::fs::exists(m_CachedOpenPanelInfo.HostFile)) return; Parent()->LeftPanel()->ReadDiz(); Parent()->RightPanel()->ReadDiz(); if (DestPanel->GetModalMode()) DestPanel->ReadDiz(); bool DizPresent = false; for (const auto& i: ItemList) { if (!(i.Flags & PPIF_PROCESSDESCR)) continue; if (Delete) { if (!DestPanel->Diz.Erase(i.FileName, i.AlternateFileName)) continue; } else { if (!SrcDiz->CopyDiz(i.FileName, i.AlternateFileName, i.FileName, i.AlternateFileName, &DestPanel->Diz)) continue; if (Move) SrcDiz->Erase(i.FileName, i.AlternateFileName); } DizPresent = true; } if (!DizPresent) return; const auto strTempDir = MakeTemp(); if (!os::fs::create_directory(strTempDir)) return; const auto strSaveDir = os::fs::GetCurrentDirectory(); const auto strDizName = path::join(strTempDir, DestPanel->strPluginDizName); DestPanel->Diz.Flush({}, &strDizName); if (Move) SrcDiz->Flush({}); PluginPanelItemHolderHeap PanelItem; if (FileNameToPluginItem(strDizName, PanelItem)) { Global->CtrlObject->Plugins->PutFiles(DestPanel->GetPluginHandle(), { &PanelItem.Item, 1 }, false, OPM_SILENT | OPM_DESCR); } else if (Delete) { PluginPanelItem pi={}; pi.FileName = DestPanel->strPluginDizName.c_str(); Global->CtrlObject->Plugins->DeleteFiles(DestPanel->GetPluginHandle(), { &pi,1 }, OPM_SILENT); } FarChDir(strSaveDir); DeleteFileWithFolder(strDizName); } void FileList::PluginGetFiles(const string& DestPath, bool Move) { SaveSelection(); { auto ItemList = CreatePluginItemList(); if (ItemList.empty()) return; auto DestPathPtr = DestPath.c_str(); const auto Item = GetPluginItem(); const auto GetCode = Global->CtrlObject->Plugins->GetFiles(Item.lock()->m_Plugin.get(), ItemList, Move, &DestPathPtr, 0); if (!Item.expired()) { if (GetCode == 1) { if ((Global->Opt->Diz.UpdateMode == DIZ_UPDATE_IF_DISPLAYED && IsDizDisplayed()) || Global->Opt->Diz.UpdateMode == DIZ_UPDATE_ALWAYS) { const auto NewDestPath = DestPathPtr; DizList DestDiz; bool DizFound = false; for (auto& i: ItemList.items()) { if (i.Flags & PPIF_PROCESSDESCR) { if (!DizFound) { Parent()->LeftPanel()->ReadDiz(); Parent()->RightPanel()->ReadDiz(); DestDiz.Read(NewDestPath); DizFound = true; } CopyDiz(i.FileName, i.AlternateFileName, i.FileName, i.FileName, &DestDiz); } } DestDiz.Flush(NewDestPath); } if (!ReturnCurrentFile) ClearSelection(); if (Move) { SetPluginModified(); PutDizToPlugin(this, ItemList.items(), true, false, nullptr); } } else if (!ReturnCurrentFile) PluginClearSelection(ItemList.items()); } } Update(UPDATE_KEEP_SELECTION); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY); AnotherPanel->Redraw(); } void FileList::PluginToPluginFiles(bool Move) { const auto AnotherFilePanel = std::dynamic_pointer_cast<FileList>(Parent()->GetAnotherPanel(this)); if (!AnotherFilePanel || AnotherFilePanel->GetMode() != panel_mode::PLUGIN_PANEL) return; SaveSelection(); auto strTempDir = MakeTemp(); const auto OriginalTempDir = strTempDir; // BUGBUG check result if (!os::fs::create_directory(strTempDir)) { LOGWARNING(L"create_directory({}): {}"sv, strTempDir, last_error()); } { auto ItemList = CreatePluginItemList(); if (ItemList.empty()) return; auto TempDir=strTempDir.c_str(); int PutCode = Global->CtrlObject->Plugins->GetFiles(GetPluginHandle(), ItemList, false, &TempDir, OPM_SILENT); strTempDir=TempDir; if (PutCode==1 || PutCode==2) { const auto strSaveDir = os::fs::GetCurrentDirectory(); FarChDir(strTempDir); PutCode = Global->CtrlObject->Plugins->PutFiles(AnotherFilePanel->GetPluginHandle(), ItemList, false, 0); if (PutCode==1 || PutCode==2) { if (!ReturnCurrentFile) ClearSelection(); AnotherFilePanel->SetPluginModified(); PutDizToPlugin(AnotherFilePanel.get(), ItemList.items(), false, false, &Diz); if (Move && Global->CtrlObject->Plugins->DeleteFiles(GetPluginHandle(), ItemList, OPM_SILENT)) { SetPluginModified(); PutDizToPlugin(this, ItemList.items(), true, false, nullptr); } } else if (!ReturnCurrentFile) PluginClearSelection(ItemList.items()); FarChDir(strSaveDir); } DeleteDirTree(strTempDir); // BUGBUG check result if (!os::fs::remove_directory(OriginalTempDir)) { LOGWARNING(L"remove_directory({}): {}"sv, OriginalTempDir, last_error()); } } Update(UPDATE_KEEP_SELECTION); Redraw(); AnotherFilePanel->Update(UPDATE_KEEP_SELECTION | (m_PanelMode == panel_mode::PLUGIN_PANEL? UPDATE_SECONDARY : 0)); AnotherFilePanel->Redraw(); } void FileList::PluginHostGetFiles() { const auto AnotherPanel = Parent()->GetAnotherPanel(this); SaveSelection(); const auto Enumerator = enum_selected(); const auto it = Enumerator.begin(); if (it == Enumerator.end()) return; const auto& Data = *it; auto strDestPath = AnotherPanel->GetCurDir(); if (((!AnotherPanel->IsVisible() || AnotherPanel->GetType() != panel_type::FILE_PANEL) && !m_SelFileCount) || strDestPath.empty()) { strDestPath = PointToName(Data.FileName); // SVS: А зачем здесь велся поиск точки с начала? const auto pos = strDestPath.rfind(L'.'); if (pos != string::npos) strDestPath.resize(pos); } auto ExitLoop = false; std::unordered_set<Plugin*> UsedPlugins; for (const auto& i: Enumerator) { if (ExitLoop) break; auto hCurPlugin = OpenPluginForFile(i.FileName, i.Attributes, OFP_EXTRACT); if (!hCurPlugin) continue; int OpMode=OPM_TOPLEVEL; if (contains(UsedPlugins, hCurPlugin->plugin())) OpMode|=OPM_SILENT; span<PluginPanelItem> Items; if (Global->CtrlObject->Plugins->GetFindData(hCurPlugin.get(), Items, OpMode)) { auto DestPath = strDestPath.c_str(); ExitLoop = Global->CtrlObject->Plugins->GetFiles(hCurPlugin.get(), Items, false, &DestPath, OpMode) != 1; strDestPath=DestPath; if (!ExitLoop) { ClearLastGetSelection(); } Global->CtrlObject->Plugins->FreeFindData(hCurPlugin.get(), Items, true); UsedPlugins.emplace(hCurPlugin->plugin()); } Global->CtrlObject->Plugins->ClosePanel(std::move(hCurPlugin)); } Update(UPDATE_KEEP_SELECTION); Redraw(); AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY); AnotherPanel->Redraw(); } void FileList::PluginPutFilesToNew() { auto hNewPlugin = Global->CtrlObject->Plugins->OpenFilePlugin(nullptr, OPM_NONE, OFP_CREATE); if (!hNewPlugin) return; auto TmpPanel = create(nullptr); TmpPanel->SetPluginMode(std::move(hNewPlugin), {}); // SendOnFocus??? true??? TmpPanel->m_ModalMode = TRUE; const auto PrevFileCount = m_ListData.size(); /* $ 12.04.2002 IS Если PluginPutFilesToAnother вернула число, отличное от 2, то нужно попробовать установить курсор на созданный файл. */ const auto rc = PluginPutFilesToAnother(false, TmpPanel); if (rc == 2 || m_ListData.size() != PrevFileCount + 1) return; int LastPos = 0; /* Место, где вычисляются координаты вновь созданного файла Позиционирование происходит на файл с максимальной датой создания файла. Посему, если какой-то злобный буратино поимел в текущем каталоге файло с датой создания поболее текущей, то корректного позиционирования не произойдет! */ const FileListItem *PtrLastPos = nullptr; int n = 0; for (const auto& i: m_ListData) { if (!(i.Attributes & FILE_ATTRIBUTE_DIRECTORY) && (!PtrLastPos || PtrLastPos->CreationTime < i.CreationTime)) { LastPos = n; PtrLastPos = &i; } ++n; } if (PtrLastPos) { m_CurFile = LastPos; Redraw(); } } /* $ 12.04.2002 IS PluginPutFilesToAnother теперь int - возвращает то, что возвращает PutFiles: -1 - прервано пользователем 0 - неудача 1 - удача 2 - удача, курсор принудительно установлен на файл и заново его устанавливать не нужно (см. PluginPutFilesToNew) */ int FileList::PluginPutFilesToAnother(bool Move, panel_ptr AnotherPanel) { const auto AnotherFilePanel = std::dynamic_pointer_cast<FileList>(AnotherPanel); if (!AnotherFilePanel || AnotherFilePanel->GetMode() != panel_mode::PLUGIN_PANEL) return 0; SaveSelection(); int PutCode = 0; { auto ItemList = CreatePluginItemList(); if (ItemList.empty()) return 0; SetCurPath(); PutCode = Global->CtrlObject->Plugins->PutFiles(AnotherFilePanel->GetPluginHandle(), ItemList, Move, 0); if (PutCode==1 || PutCode==2) { if (!ReturnCurrentFile) { ClearSelection(); } PutDizToPlugin(AnotherFilePanel.get(), ItemList.items(), false, Move, &Diz); AnotherFilePanel->SetPluginModified(); } else if (!ReturnCurrentFile) PluginClearSelection(ItemList.items()); } Update(UPDATE_KEEP_SELECTION); Redraw(); if (AnotherFilePanel == Parent()->GetAnotherPanel(this)) { AnotherFilePanel->Update(UPDATE_KEEP_SELECTION); AnotherFilePanel->Redraw(); } return PutCode; } void FileList::GetOpenPanelInfo(OpenPanelInfo *Info) const { *Info = {}; if (m_PanelMode == panel_mode::PLUGIN_PANEL) Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), Info); } /* Функция для вызова команды "Архивные команды" (Shift-F3) */ void FileList::ProcessHostFile() { if (m_ListData.empty() || !SetCurPath()) return; int Done=FALSE; SaveSelection(); if (m_PanelMode == panel_mode::PLUGIN_PANEL && !PluginsList.back()->m_HostFile.empty()) { { auto ItemList = CreatePluginItemList(); Done = Global->CtrlObject->Plugins->ProcessHostFile(GetPluginHandle(), ItemList, 0); if (Done) SetPluginModified(); else { if (!ReturnCurrentFile) PluginClearSelection(ItemList.items()); Redraw(); } } if (Done) ClearSelection(); } else { const auto SCount = GetRealSelCount(); if (SCount > 0) { for (auto& i: m_ListData) { if (i.Selected) { Done=ProcessOneHostFile(&i); if (Done == 1) Select(i, false); else if (Done == -1) continue; else // Если ЭТО убрать, то... будем жать ESC до потери пульса break; // } } if (SelectedFirst) SortFileList(true); } else { if ((Done=ProcessOneHostFile(&*(m_ListData.begin() + m_CurFile))) == 1) ClearSelection(); } } if (Done) { Update(UPDATE_KEEP_SELECTION); Redraw(); const auto AnotherPanel = Parent()->GetAnotherPanel(this); AnotherPanel->Update(UPDATE_KEEP_SELECTION|UPDATE_SECONDARY); AnotherPanel->Redraw(); } } /* Обработка одного хост-файла. Return: -1 - Этот файл никаким плагином не поддержан 0 - Плагин вернул FALSE 1 - Плагин вернул TRUE */ int FileList::ProcessOneHostFile(const FileListItem* Item) { int Done=-1; auto hNewPlugin = OpenPluginForFile(Item->FileName, Item->Attributes, OFP_COMMANDS); if (!hNewPlugin) return Done; span<PluginPanelItem> Items; if (Global->CtrlObject->Plugins->GetFindData(hNewPlugin.get(), Items, OPM_TOPLEVEL)) { Done = Global->CtrlObject->Plugins->ProcessHostFile(hNewPlugin.get(), Items, OPM_TOPLEVEL); Global->CtrlObject->Plugins->FreeFindData(hNewPlugin.get(), Items, true); } Global->CtrlObject->Plugins->ClosePanel(std::move(hNewPlugin)); return Done; } void FileList::SetPluginMode(std::unique_ptr<plugin_panel>&& PluginPanel, string_view const PluginFile, bool SendOnFocus) { const auto ParentWindow = Parent(); PushPlugin(std::move(PluginPanel), PluginFile); m_PanelMode = panel_mode::PLUGIN_PANEL; if (SendOnFocus) OnFocusChange(true); Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (m_CachedOpenPanelInfo.StartPanelMode) SetViewMode(VIEW_0 + m_CachedOpenPanelInfo.StartPanelMode-L'0'); if (m_CachedOpenPanelInfo.StartSortMode) { m_SortMode = plugin_sort_mode_to_internal(m_CachedOpenPanelInfo.StartSortMode); m_ReverseSortOrder = m_CachedOpenPanelInfo.StartSortOrder != 0; } if (ParentWindow) { // BUGBUG, redraw logic shouldn't be here ParentWindow->RedrawKeyBar(); const auto AnotherPanel = ParentWindow->GetAnotherPanel(this); if (AnotherPanel->GetType() != panel_type::FILE_PANEL) { AnotherPanel->Update(UPDATE_KEEP_SELECTION); AnotherPanel->Redraw(); } } } void FileList::PluginGetPanelInfo(PanelInfo &Info) { CorrectPosition(); Info.CurrentItem=m_CurFile; Info.TopPanelItem=m_CurTopFile; if(m_ShowShortNames) Info.Flags|=PFLAGS_ALTERNATIVENAMES; Info.ItemsNumber = m_ListData.size(); Info.SelectedItemsNumber=m_ListData.empty()? 0 : GetSelCount(); } size_t FileList::PluginGetPanelItem(int ItemNumber,FarGetPluginPanelItem *Item) { size_t result=0; if (static_cast<size_t>(ItemNumber) < m_ListData.size()) { result=FileListToPluginItem2(m_ListData[ItemNumber], Item); } return result; } size_t FileList::PluginGetSelectedPanelItem(int ItemNumber,FarGetPluginPanelItem *Item) { if (static_cast<size_t>(ItemNumber) >= m_ListData.size()) return 0; if (ItemNumber == CacheSelIndex) return FileListToPluginItem2(m_ListData[CacheSelPos], Item); if (ItemNumber < CacheSelIndex) CacheSelIndex = -1; int CurSel = CacheSelIndex; const size_t StartValue = CacheSelIndex >= 0 ? CacheSelPos + 1 : 0; size_t result = 0; for (const auto& i: irange(StartValue, m_ListData.size())) { if (m_ListData[i].Selected) CurSel++; if (CurSel == ItemNumber) { result = FileListToPluginItem2(m_ListData[i], Item); CacheSelIndex = ItemNumber; CacheSelPos = static_cast<int>(i); break; } } if (CurSel == -1 && !ItemNumber) { result = FileListToPluginItem2(m_ListData[m_CurFile], Item); CacheSelIndex=-1; } return result; } void FileList::PluginGetColumnTypesAndWidths(string& strColumnTypes,string& strColumnWidths) const { std::tie(strColumnTypes, strColumnWidths) = SerialiseViewSettings(m_ViewSettings.PanelColumns); } void FileList::PluginBeginSelection() { SaveSelection(); } void FileList::PluginSetSelection(int ItemNumber,bool Selection) { Select(m_ListData[ItemNumber], Selection); } void FileList::PluginClearSelection(int SelectedItemNumber) { if (static_cast<size_t>(SelectedItemNumber) >= m_ListData.size()) return; if (SelectedItemNumber<=CacheSelClearIndex) CacheSelClearIndex=-1; int CurSel = CacheSelClearIndex; const size_t StartValue = CacheSelClearIndex >= 0? CacheSelClearPos + 1 : 0; for (const auto& i: irange(StartValue, m_ListData.size())) { if (m_ListData[i].Selected) { CurSel++; } if (CurSel==SelectedItemNumber) { Select(m_ListData[i], false); CacheSelClearIndex=SelectedItemNumber; CacheSelClearPos=static_cast<int>(i); break; } } } void FileList::PluginEndSelection() { if (SelectedFirst) { SortFileList(true); } } void FileList::SetPluginModified() { if (PluginsList.empty()) return; PluginsList.back()->m_Modified = true; } plugin_panel* FileList::GetPluginHandle() const { return m_ExpiringPluginPanel? m_ExpiringPluginPanel->m_Plugin.get() : !PluginsList.empty()? PluginsList.back()->m_Plugin.get() : nullptr; } std::weak_ptr<FileList::PluginsListItem> FileList::GetPluginItem() const { assert(!PluginsList.empty()); return m_ExpiringPluginPanel? m_ExpiringPluginPanel : PluginsList.back(); } bool FileList::ProcessPluginEvent(int Event,void *Param) { if (m_PanelMode != panel_mode::PLUGIN_PANEL) return false; return Global->CtrlObject->Plugins->ProcessEvent(GetPluginHandle(), Event, Param) != FALSE; } void FileList::PluginClearSelection(const std::vector<PluginPanelItem>& ItemList) { SaveSelection(); size_t FileNumber=0,PluginNumber=0; while (PluginNumber < ItemList.size()) { const auto& CurPlugin = ItemList[PluginNumber]; if (!(CurPlugin.Flags & PPIF_SELECTED)) { while (!equal_icase(CurPlugin.FileName, m_ListData[FileNumber].FileName)) if (++FileNumber >= m_ListData.size()) return; Select(m_ListData[FileNumber++], false); } PluginNumber++; } } // flupdate // Файловая панель - чтение имен файлов // Флаги для ReadDiz() enum ReadDizFlags { RDF_NO_UPDATE = 0_bit, }; void FileList::Update(int Mode) { if (m_EnableUpdate) { const auto IsKeepSelection = (Mode & UPDATE_KEEP_SELECTION) != 0, IsIgnoreVisible = (Mode & UPDATE_IGNORE_VISIBLE) != 0; switch (m_PanelMode) { case panel_mode::NORMAL_PANEL: ReadFileNames(IsKeepSelection, IsIgnoreVisible); break; case panel_mode::PLUGIN_PANEL: Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (m_PanelMode != panel_mode::PLUGIN_PANEL) ReadFileNames(IsKeepSelection, IsIgnoreVisible); else if ((m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES) || Parent()->GetAnotherPanel(this)->GetMode() == panel_mode::PLUGIN_PANEL || !(Mode & UPDATE_SECONDARY)) UpdatePlugin(IsKeepSelection, IsIgnoreVisible); break; } } } void FileList::UpdateIfRequired() { if (!UpdateRequired || UpdateDisabled) return; UpdateRequired = false; Update((m_KeepSelection? UPDATE_KEEP_SELECTION : 0) | UPDATE_IGNORE_VISIBLE); } void FileList::ReadFileNames(bool const KeepSelection, bool const UpdateEvenIfPanelInvisible) { SCOPED_ACTION(taskbar::indeterminate)(false); strOriginalCurDir = m_CurDir; if (!IsVisible() && !UpdateEvenIfPanelInvisible) { UpdateRequired = true; m_KeepSelection = KeepSelection; return; } UpdateRequired = false; AccessTimeUpdateRequired = false; DizRead = false; decltype(m_ListData) OldData; string strCurName, strNextCurName; // really? if (!Parent()->IsLeft(this) && !Parent()->IsRight(this)) return; const auto strSaveDir = os::fs::GetCurrentDirectory(); { string strOldCurDir(m_CurDir); if (!SetCurPath()) { FlushInputBuffer(); // Очистим буфер ввода, т.к. мы уже можем быть в другом месте... if (m_CurDir == strOldCurDir) //?? i?? { strOldCurDir = GetPathRoot(strOldCurDir); if (!os::fs::IsDiskInDrive(strOldCurDir)) GoHome(strOldCurDir); /* При смене каталога путь не изменился */ } return; } } SortGroupsRead = false; if (IsFocused()) Parent()->GetCmdLine()->SetCurDir(m_CurDir); LastCurFile=-1; const auto AnotherPanel = Parent()->GetAnotherPanel(this); AnotherPanel->QViewDelTempName(); size_t PrevSelFileCount=m_SelFileCount; m_SelFileCount=0; m_SelDirCount = 0; SelFileSize=0; m_TotalFileCount=0; m_TotalDirCount = 0; TotalFileSize=0; CacheSelIndex=-1; CacheSelClearIndex=-1; FreeDiskSize = -1; if (Global->Opt->ShowPanelFree) { // BUGBUG check result if (!os::fs::get_disk_size(m_CurDir, nullptr, nullptr, &FreeDiskSize)) { LOGWARNING(L"get_disk_size({}): {}"sv, m_CurDir, last_error()); } } if (!m_ListData.empty()) { strCurName = m_ListData[m_CurFile].FileName; if (m_ListData[m_CurFile].Selected && !ReturnCurrentFile) { const auto NotSelectedIterator = std::find_if(m_ListData.begin() + m_CurFile + 1, m_ListData.end(), [](const auto& i) { return !i.Selected; }); if (NotSelectedIterator != m_ListData.cend()) { strNextCurName = NotSelectedIterator->FileName; } } } if (KeepSelection || PrevSelFileCount>0) { OldData = std::move(m_ListData); } m_ListData.initialise(nullptr); m_FilteredExtensions.clear(); DWORD FileSystemFlags = 0; string FileSystemName; // BUGBUG check result if (const auto Root = GetPathRoot(m_CurDir); !os::fs::GetVolumeInformation(Root, nullptr, nullptr, nullptr, &FileSystemFlags, &FileSystemName)) { LOGWARNING(L"GetVolumeInformation({}): {}"sv, Root, last_error()); } m_HardlinksSupported = true; m_StreamsSupported = true; if (IsWindows7OrGreater()) { if (!(FileSystemFlags & FILE_SUPPORTS_HARD_LINKS)) { m_HardlinksSupported = false; } } else { if (FileSystemName != L"NTFS"sv) { m_HardlinksSupported = false; } } if(!(FileSystemFlags&FILE_NAMED_STREAMS)) { m_StreamsSupported = false; } m_ComputerName = ExtractComputerName(m_CurDir); SetLastError(ERROR_SUCCESS); // сформируем заголовок вне цикла const auto Title = MakeLine(m_Where.width() - 2, line_type::h2); bool IsShowTitle = false; if (!m_Filter) m_Filter = std::make_unique<multifilter>(this, FFT_PANEL); //Рефреш текущему времени для фильтра перед началом операции m_Filter->UpdateCurrentTime(); Global->CtrlObject->HiFiles->UpdateCurrentTime(); bool bCurDirRoot = false; const auto Type = ParsePath(m_CurDir, nullptr, &bCurDirRoot); bool NetRoot = bCurDirRoot && (Type == root_type::remote || Type == root_type::unc_remote); const auto Find = os::fs::enum_files(path::join(m_CurDir, L'*'), true); bool UseFilter=m_Filter->IsEnabledOnPanel(); { m_ContentPlugins.clear(); m_ContentNames.clear(); m_ContentNamesPtrs.clear(); m_ContentValues.clear(); std::unordered_set<string> ColumnsSet; for (const auto& ColumnsContainer: { &m_ViewSettings.PanelColumns, &m_ViewSettings.StatusColumns }) { for (const auto& Column: *ColumnsContainer) { if (Column.type == column_type::custom_0) { if (ColumnsSet.emplace(Column.title).second) { m_ContentNames.emplace_back(Column.title); } } } } if (!m_ContentNames.empty()) { m_ContentNamesPtrs.reserve(m_ContentNames.size()); std::transform(ALL_CONST_RANGE(m_ContentNames), std::back_inserter(m_ContentNamesPtrs), [](const string& i) { return i.c_str(); }); m_ContentPlugins = Global->CtrlObject->Plugins->GetContentPlugins(m_ContentNamesPtrs); m_ContentValues.resize(m_ContentNames.size()); } } std::optional<error_state> ErrorState; const time_check TimeCheck; for (const auto& fdata: Find) { ErrorState = last_error(); const auto IsDirectory = (fdata.Attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; if (fdata.Attributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM) && !Global->Opt->ShowHidden) continue; if (UseFilter && !m_Filter->FileInFilter(fdata, fdata.FileName)) { if (!IsDirectory) m_FilteredExtensions.emplace(name_ext(fdata.FileName).second); continue; } { FileListItem NewItem{}; static_cast<os::fs::find_data&>(NewItem) = fdata; if (!IsDirectory) { TotalFileSize += NewItem.FileSize; } NewItem.SortGroup = DEFAULT_SORT_GROUP; NewItem.Position = m_ListData.size(); m_ListData.emplace_back(std::move(NewItem)); } ++(IsDirectory? m_TotalDirCount : m_TotalFileCount); if (TimeCheck) { if (IsVisible()) { if (!IsShowTitle) { Text({ m_Where.left + 1, m_Where.top }, colors::PaletteColorToFarColor(COL_PANELBOX), Title); IsShowTitle = true; SetColor(IsFocused()? COL_PANELSELECTEDTITLE:COL_PANELTITLE); } auto strReadMsg = format(msg(lng::MReadingFiles), m_ListData.size()); inplace::truncate_left(strReadMsg, Title.size() - 2); GotoXY(m_Where.left + 1 + static_cast<int>(Title.size() - strReadMsg.size() - 1) / 2, m_Where.top); Text(concat(L' ', strReadMsg, L' ')); } Global->CtrlObject->Macro.SuspendMacros(true); SCOPE_EXIT{ Global->CtrlObject->Macro.SuspendMacros(false); }; if (CheckForEscAndConfirmAbort()) break; } } if (!ErrorState) ErrorState = last_error(); if (!(ErrorState->Win32Error == ERROR_SUCCESS || ErrorState->Win32Error == ERROR_NO_MORE_FILES || ErrorState->Win32Error == ERROR_FILE_NOT_FOUND)) { Message(MSG_WARNING, *ErrorState, msg(lng::MError), { msg(lng::MReadFolderError), }, { lng::MOk }); } if ((Global->Opt->ShowDotsInRoot || !bCurDirRoot) || (NetRoot && Global->CtrlObject->Plugins->FindPlugin(Global->Opt->KnownIDs.Network.Id))) // NetWork Plugin { FileListItem NewItem; FillParentPoint(NewItem); os::chrono::time_point TwoDotsTimes[4]; if (os::fs::GetFileTimeSimple(m_CurDir, &TwoDotsTimes[0], &TwoDotsTimes[1], &TwoDotsTimes[2], &TwoDotsTimes[3])) { NewItem.CreationTime = TwoDotsTimes[0]; NewItem.LastAccessTime = TwoDotsTimes[1]; NewItem.LastWriteTime = TwoDotsTimes[2]; NewItem.ChangeTime = TwoDotsTimes[3]; } else { LOGWARNING(L"GetFileTimeSimple({}): {}"sv, m_CurDir, last_error()); } NewItem.Position = m_ListData.size(); m_ListData.emplace_back(std::move(NewItem)); } if (IsColumnDisplayed(column_type::description)) ReadDiz(); if (AnotherPanel->GetMode() == panel_mode::PLUGIN_PANEL) { const auto hAnotherPlugin = AnotherPanel->GetPluginHandle(); string strPath(m_CurDir); AddEndSlash(strPath); span<PluginPanelItem> PanelData; if (Global->CtrlObject->Plugins->GetVirtualFindData(hAnotherPlugin, PanelData, strPath)) { m_ListData.reserve(m_ListData.size() + PanelData.size()); OpenPanelInfo AnotherPanelInfo{}; Global->CtrlObject->Plugins->GetOpenPanelInfo(hAnotherPlugin, &AnotherPanelInfo); auto ParentPointSeen = AnotherPanelInfo.Flags & OPIF_ADDDOTS? true : false; for (const auto& i: PanelData) { FileListItem Item{ i }; Item.PrevSelected = Item.Selected = false; Item.ShowFolderSize = 0; Item.SortGroup = Global->CtrlObject->HiFiles->GetGroup(Item, this); Item.Position = m_ListData.size(); m_ListData.emplace_back(std::move(Item)); if (!ParentPointSeen && IsParentDirectory(i)) { ParentPointSeen = true; } else { i.FileAttributes & FILE_ATTRIBUTE_DIRECTORY? ++m_TotalDirCount : ++m_TotalFileCount; } TotalFileSize += i.FileSize; } Global->CtrlObject->Plugins->FreeVirtualFindData(hAnotherPlugin, PanelData); } } CorrectPosition(); string strLastSel, strGetSel; if (KeepSelection || PrevSelFileCount>0) { if (LastSelPosition >= 0 && static_cast<size_t>(LastSelPosition) < OldData.size()) strLastSel = OldData[LastSelPosition].FileName; if (GetSelPosition >= 0 && static_cast<size_t>(GetSelPosition) < OldData.size()) strGetSel = OldData[GetSelPosition].FileName; MoveSelection(OldData, m_ListData); } OldData.clear(); if (m_SortGroups) ReadSortGroups(false); if (!KeepSelection && PrevSelFileCount>0) { SaveSelection(); ClearSelection(); } SortFileList(false); if (!strLastSel.empty()) LastSelPosition = FindFile(strLastSel, false); if (!strGetSel.empty()) GetSelPosition = FindFile(strGetSel, false); if (m_CurFile >= static_cast<int>(m_ListData.size()) || !equal_icase(m_ListData[m_CurFile].FileName, strCurName)) if (!GoToFile(strCurName) && !strNextCurName.empty()) GoToFile(strNextCurName); /* $ 13.02.2002 DJ SetTitle() - только если мы текущее окно! */ if (Parent() == Global->WindowManager->GetCurrentWindow().get()) RefreshTitle(); FarChDir(strSaveDir); //??? } void FileList::UpdateIfChanged(bool Changed) { if (Global->Opt->AutoUpdateLimit && m_ListData.size() > static_cast<size_t>(Global->Opt->AutoUpdateLimit)) return; if (m_PanelMode != panel_mode::NORMAL_PANEL) return; if (!Changed && !FSWatcher.TimeChanged()) return; m_UpdatePending = false; if (const auto AnotherPanel = Parent()->GetAnotherPanel(this); AnotherPanel->GetType() == panel_type::INFO_PANEL) { AnotherPanel->Update(UPDATE_KEEP_SELECTION); AnotherPanel->Redraw(); } Update(UPDATE_KEEP_SELECTION); } class FileList::background_updater { public: explicit background_updater(FileList* const Owner): m_Owner(Owner) { } const auto& event_id() const { return m_Listener.GetEventName(); } private: listener m_Listener{[this] { if (Global->WindowManager->IsPanelsActive() && m_Owner->IsVisible()) { m_Owner->UpdateIfChanged(true); m_Owner->Redraw(); } else { m_Owner->m_UpdatePending = true; } }}; FileList* m_Owner; }; void FileList::InitFSWatcher(bool CheckTree) { if (m_PanelMode == panel_mode::PLUGIN_PANEL) return; StopFSWatcher(); DWORD DriveType=DRIVE_REMOTE; const auto Type = ParsePath(m_CurDir); if (Type == root_type::drive_letter || Type == root_type::win32nt_drive_letter) { DriveType = os::fs::drive::get_type(os::fs::drive::get_win32nt_root_directory(m_CurDir[Type == root_type::drive_letter? 0 : 4])); } if (Global->Opt->AutoUpdateRemoteDrive || (!Global->Opt->AutoUpdateRemoteDrive && DriveType != DRIVE_REMOTE) || Type == root_type::volume) { FSWatcher.Set(m_BackgroundUpdater->event_id(), m_CurDir, CheckTree); StartFSWatcher(false, false); //check_time=false, prevent reading file time twice (slow on network) } } void FileList::StartFSWatcher(bool got_focus, bool check_time) { FSWatcher.Watch(got_focus, check_time); } void FileList::StopFSWatcher() { FSWatcher.Release(); } struct hash_less { struct arg { arg(unsigned long long const Value): m_Value(Value) {} arg(FileListItem const& Value): m_Value(Value.FileId) {} unsigned long long m_Value; }; bool operator()(arg const a, arg const b) const { return a.m_Value < b.m_Value; } }; void FileList::MoveSelection(list_data& From, list_data& To) { m_SelFileCount=0; m_SelDirCount = 0; SelFileSize=0; CacheSelIndex=-1; CacheSelClearIndex=-1; // Repurpose some no longer used fields to turn From into a flat map & intrusively store its order for (auto& i: From) { i.FileId = make_hash(i.FileName); i.Position = &i - From.data(); } std::sort(From.begin(), From.end(), hash_less{}); std::vector<size_t> OldPositions; OldPositions.reserve(To.size()); const auto npos = size_t(-1); for (auto& i: To) { const auto& [EqualBegin, EqualEnd] = std::equal_range(ALL_RANGE(From), make_hash(i.FileName), hash_less{}); const auto OldItemIterator = std::find_if(EqualBegin, EqualEnd, [&](FileListItem const& Item){ return Item.FileName == i.FileName;}); if (OldItemIterator == EqualEnd) { OldPositions.emplace_back(npos); continue; } OldPositions.emplace_back(OldItemIterator->Position); if (OldItemIterator->ShowFolderSize) { i.ShowFolderSize = 2; i.FileSize = OldItemIterator->FileSize; i.AllocationSize = OldItemIterator->AllocationSize; } Select(i, OldItemIterator->Selected); i.PrevSelected = OldItemIterator->PrevSelected; // The state has been transferred, so invalidate the old item to prevent propagating // to other items in To with the same name (plugins can do that). OldItemIterator->FileName.clear(); } std::sort(ALL_RANGE(To), [&](FileListItem const& a, FileListItem const& b) { const auto OldPosA = OldPositions[a.Position]; const auto OldPosB = OldPositions[b.Position]; return OldPosA != npos && OldPosB != npos? &From[OldPosA] < &From[OldPosB] : a.Position < b.Position; }); From.clear(); } void FileList::UpdatePlugin(bool const KeepSelection, bool const UpdateEvenIfPanelInvisible) { if (!IsVisible() && !UpdateEvenIfPanelInvisible) { UpdateRequired = true; m_KeepSelection = KeepSelection; return; } DizRead = false; decltype(m_ListData) OldData; std::optional<string> strCurName, strNextCurName; LastCurFile=-1; const auto Item = GetPluginItem(); Global->CtrlObject->Plugins->GetOpenPanelInfo(Item.lock()->m_Plugin.get(), &m_CachedOpenPanelInfo); if (Item.expired()) return; FreeDiskSize=-1; if (Global->Opt->ShowPanelFree) { if (m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES) { // BUGBUG check result if (!os::fs::get_disk_size(m_CurDir, nullptr, nullptr, &FreeDiskSize)) { LOGWARNING(L"get_disk_size({}): {}"sv, m_CurDir, last_error()); } } else if (m_CachedOpenPanelInfo.Flags & OPIF_USEFREESIZE) FreeDiskSize = m_CachedOpenPanelInfo.FreeSize; } span<PluginPanelItem> PanelData; int result = FALSE; { ++m_InsideGetFindData; SCOPE_EXIT { --m_InsideGetFindData; }; result = Global->CtrlObject->Plugins->GetFindData(Item.lock()->m_Plugin.get(), PanelData, 0); } if (Item.expired()) { Update(0); //панель не сортируется внутри GetFindData, и если плагиновая панель закрыта, то панель - несортированная, //Update сохранил позицию, поэтому переместим курсор в начало. GoToFile(0); return; } if (!result) { PopPlugin(TRUE); Update(KeepSelection); // WARP> явный хак, но очень способствует - восстанавливает позицию на панели при ошибке чтения архива. if (!PrevDataList.empty()) GoToFile(PrevDataList.back().strPrevName); return; } size_t PrevSelFileCount=m_SelFileCount; m_SelFileCount=0; m_SelDirCount = 0; SelFileSize=0; m_TotalFileCount=0; m_TotalDirCount = 0; TotalFileSize=0; CacheSelIndex=-1; CacheSelClearIndex=-1; strPluginDizName.clear(); if (!m_ListData.empty()) { strCurName = m_ListData[m_CurFile].FileName; if (m_ListData[m_CurFile].Selected) { const auto ItemIterator = std::find_if(m_ListData.cbegin() + m_CurFile + 1, m_ListData.cend(), [](const auto& i) { return !i.Selected; }); if (ItemIterator != m_ListData.cend()) { strNextCurName = ItemIterator->FileName; } } } else if (m_CachedOpenPanelInfo.Flags & OPIF_ADDDOTS) { strCurName = L".."sv; } if (KeepSelection || PrevSelFileCount>0) { OldData = std::move(m_ListData); } m_ListData.initialise(Item.lock()->m_Plugin.get()); m_FilteredExtensions.clear(); if (!m_Filter) m_Filter = std::make_unique<multifilter>(this, FFT_PANEL); //Рефреш текущему времени для фильтра перед началом операции m_Filter->UpdateCurrentTime(); Global->CtrlObject->HiFiles->UpdateCurrentTime(); bool UseFilter=m_Filter->IsEnabledOnPanel(); m_ListData.reserve(PanelData.size() + ((m_CachedOpenPanelInfo.Flags & OPIF_ADDDOTS)? 1 : 0)); struct { FileListItem* Item{}; bool TryToFind{ true }; } ParentPoint; if (m_CachedOpenPanelInfo.Flags & OPIF_ADDDOTS) { FileListItem NewItem; FillParentPoint(NewItem); if (m_CachedOpenPanelInfo.HostFile && *m_CachedOpenPanelInfo.HostFile) { os::fs::find_data FindData; if (os::fs::get_find_data(m_CachedOpenPanelInfo.HostFile, FindData)) { NewItem.LastWriteTime = FindData.LastWriteTime; NewItem.CreationTime = FindData.CreationTime; NewItem.LastAccessTime = FindData.LastAccessTime; NewItem.ChangeTime = FindData.ChangeTime; } } NewItem.Position = m_ListData.size(); m_ListData.emplace_back(std::move(NewItem)); ParentPoint.TryToFind = false; } for (const auto& PanelItem: PanelData) { if (UseFilter && !(m_CachedOpenPanelInfo.Flags & OPIF_DISABLEFILTER)) { if (!m_Filter->FileInFilter(PanelItem)) { if (!(PanelItem.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)) m_FilteredExtensions.emplace(name_ext(PanelItem.FileName).second); continue; } } if (!Global->Opt->ShowHidden && (PanelItem.FileAttributes & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) continue; FileListItem NewItem(PanelItem); NewItem.SortGroup = (m_CachedOpenPanelInfo.Flags & OPIF_DISABLESORTGROUPS)? DEFAULT_SORT_GROUP : Global->CtrlObject->HiFiles->GetGroup(NewItem, this); NewItem.Position = m_ListData.size(); m_ListData.emplace_back(std::move(NewItem)); if (ParentPoint.TryToFind && !ParentPoint.Item && IsParentDirectory(PanelItem)) { // We reserve capacity so no reallocation will happen and pointer will stay valid. ParentPoint.Item = &m_ListData.back(); FillParentPoint(*ParentPoint.Item); } else { PanelItem.FileAttributes & FILE_ATTRIBUTE_DIRECTORY? ++m_TotalDirCount : ++m_TotalFileCount; TotalFileSize += PanelItem.FileSize; } } if (m_CurFile >= static_cast<int>(m_ListData.size())) m_CurFile = m_ListData.empty()? 0 : static_cast<int>(m_ListData.size() - 1); /* $ 25.02.2001 VVM ! Не считывать повторно список файлов с панели плагина */ if (IsColumnDisplayed(column_type::description)) ReadDiz(PanelData); CorrectPosition(); Global->CtrlObject->Plugins->FreeFindData(Item.lock()->m_Plugin.get(), PanelData, false); std::optional<string> strLastSel, strGetSel; if (KeepSelection || PrevSelFileCount>0) { if (LastSelPosition >= 0 && LastSelPosition < static_cast<long>(OldData.size())) strLastSel = OldData[LastSelPosition].FileName; if (GetSelPosition >= 0 && GetSelPosition < static_cast<long>(OldData.size())) strGetSel = OldData[GetSelPosition].FileName; MoveSelection(OldData, m_ListData); } if (!KeepSelection && PrevSelFileCount>0) { SaveSelection(); ClearSelection(); } SortFileList(false); if (strLastSel) LastSelPosition = FindFile(*strLastSel, false); if (strGetSel) GetSelPosition = FindFile(*strGetSel, false); if (strCurName && (m_CurFile >= static_cast<int>(m_ListData.size()) || !equal_icase(m_ListData[m_CurFile].FileName, *strCurName))) if (!GoToFile(*strCurName) && strNextCurName) GoToFile(*strNextCurName); RefreshTitle(); } void FileList::ReadDiz(span<PluginPanelItem> const Items) { if (DizRead) return; DizRead = true; Diz.Reset(); if (m_PanelMode == panel_mode::NORMAL_PANEL) { Diz.Read(m_CurDir); } else { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); if (!m_CachedOpenPanelInfo.DescrFilesNumber) return; int GetCode=TRUE; span<PluginPanelItem> PanelData; if (Items.empty()) { GetCode = Global->CtrlObject->Plugins->GetFindData(GetPluginHandle(), PanelData, 0); } else { PanelData = Items; } if (GetCode) { for (const auto& i: span(m_CachedOpenPanelInfo.DescrFiles, m_CachedOpenPanelInfo.DescrFilesNumber)) { for (auto& CurPanelData: PanelData) { if (!equal_icase(CurPanelData.FileName, i)) continue; const auto strTempDir = MakeTemp(); if (!os::fs::create_directory(strTempDir)) { LOGWARNING(L"create_directory({}): {}"sv, strTempDir, last_error()); continue; } string strDizName; if (Global->CtrlObject->Plugins->GetFile(GetPluginHandle(), &CurPanelData, strTempDir, strDizName, OPM_SILENT | OPM_VIEW | OPM_QUICKVIEW | OPM_DESCR)) { strPluginDizName = i; Diz.Read({}, &strDizName); DeleteFileWithFolder(strDizName); break; } // BUGBUG check result if (!os::fs::remove_directory(strTempDir)) { LOGWARNING(L"remove_directory({}): {}"sv, strTempDir, last_error()); } //ViewPanel->ShowFile(nullptr,FALSE,nullptr); } } if (Items.empty()) Global->CtrlObject->Plugins->FreeFindData(GetPluginHandle(), PanelData, true); } } for(auto& i: m_ListData) { if (!i.DizText) { i.DeleteDiz = false; // It's ok, the description is null-terminated here i.DizText = Diz.Get(i.FileName, i.AlternateFileName(), i.FileSize).data(); } } } void FileList::ReadSortGroups(bool UpdateFilterCurrentTime) { if (SortGroupsRead) return; if (UpdateFilterCurrentTime) { Global->CtrlObject->HiFiles->UpdateCurrentTime(); } for (auto& i: m_ListData) { i.SortGroup = Global->CtrlObject->HiFiles->GetGroup(i, this); } SortGroupsRead = true; } // занести предопределенные данные для каталога ".." void FileList::FillParentPoint(FileListItem& Item) { Item.Attributes = FILE_ATTRIBUTE_DIRECTORY; Item.FileName = L".."sv; Item.SetAlternateFileName(Item.FileName); Item.UserFlags = PPIF_RESERVED; } // flshow.cpp // Файловая панель - вывод на экран void FileList::UpdateHeight() { m_Height = m_Where.height() - 2 - (Global->Opt->ShowColumnTitles? 1 : 0) - (Global->Opt->ShowPanelStatus? 2 : 0); } void FileList::DisplayObject() { UpdateHeight(); if (UpdateRequired) { UpdateRequired = false; Update(m_KeepSelection? UPDATE_KEEP_SELECTION : 0); } ShowFileList(false); } void FileList::ShowFileList(bool Fast) { string strTitle; string strInfoCurDir; if (m_PanelMode == panel_mode::PLUGIN_PANEL) { if (ProcessPluginEvent(FE_REDRAW,nullptr)) return; Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); strInfoCurDir = NullToEmpty(m_CachedOpenPanelInfo.CurDir); } else { UpdateIfChanged(m_UpdatePending); } bool CurFullScreen=IsFullScreen(); PrepareViewSettings(m_ViewMode); CorrectPosition(); if (CurFullScreen!=IsFullScreen()) { Parent()->SetScreenPosition(); Parent()->GetAnotherPanel(this)->Update(UPDATE_KEEP_SELECTION | UPDATE_SECONDARY); } if (!ProcessingPluginCommand && LastCurFile != m_CurFile) { LastCurFile = m_CurFile; UpdateViewPanel(); } SetScreen({ m_Where.left + 1, m_Where.top + 1, m_Where.right - 1, m_Where.bottom - 1 }, L' ', colors::PaletteColorToFarColor(COL_PANELTEXT)); Box(m_Where, colors::PaletteColorToFarColor(COL_PANELBOX), DOUBLE_BOX); if (Global->Opt->ShowColumnTitles) { // SetScreen(X1+1,Y1+1,X2-1,Y1+1,' ',COL_PANELTEXT); SetColor(COL_PANELTEXT); //??? //GotoXY(X1+1,Y1+1); //Text(string(X2 - X1 - 1, L' ')); } for (size_t I = 0, ColumnPos = m_Where.left + 1; I < m_ViewSettings.PanelColumns.size(); I++) { if (m_ViewSettings.PanelColumns[I].width < 0) continue; if (Global->Opt->ShowColumnTitles) { const auto IDMessage = [&] { switch (m_ViewSettings.PanelColumns[I].type) { case column_type::name: return lng::MColumnName; case column_type::extension: return lng::MColumnExtension; case column_type::size: return lng::MColumnSize; case column_type::size_compressed: return lng::MColumnAlocatedSize; case column_type::date: return lng::MColumnDate; case column_type::time: return lng::MColumnTime; case column_type::date_write: return lng::MColumnWrited; case column_type::date_creation: return lng::MColumnCreated; case column_type::date_access: return lng::MColumnAccessed; case column_type::date_change: return lng::MColumnChanged; case column_type::attributes: return lng::MColumnAttr; case column_type::description: return lng::MColumnDescription; case column_type::owner: return lng::MColumnOwner; case column_type::links_number: return lng::MColumnMumLinks; case column_type::streams_number: return lng::MColumnNumStreams; case column_type::streams_size: return lng::MColumnStreamsSize; default: return lng::MColumnUnknown; } }(); strTitle = IDMessage == lng::MColumnUnknown && !m_ViewSettings.PanelColumns[I].title.empty()? m_ViewSettings.PanelColumns[I].title : msg(IDMessage); if (m_PanelMode == panel_mode::PLUGIN_PANEL && m_CachedOpenPanelInfo.PanelModesArray && m_ViewMode<static_cast<int>(m_CachedOpenPanelInfo.PanelModesNumber) && m_CachedOpenPanelInfo.PanelModesArray[m_ViewMode].ColumnTitles) { const wchar_t *NewTitle = m_CachedOpenPanelInfo.PanelModesArray[m_ViewMode].ColumnTitles[I]; if (NewTitle) strTitle=NewTitle; } SetColor(COL_PANELCOLUMNTITLE); GotoXY(static_cast<int>(ColumnPos), m_Where.top + 1); Text(fit_to_center(strTitle, m_ViewSettings.PanelColumns[I].width)); } if (I == m_ViewSettings.PanelColumns.size() - 1) break; if (m_ViewSettings.PanelColumns[I + 1].width < 0) continue; SetColor(COL_PANELBOX); ColumnPos += m_ViewSettings.PanelColumns[I].width; GotoXY(static_cast<int>(ColumnPos), m_Where.top); const auto DoubleLine = !((I + 1) % m_ColumnsInStripe); Text(BoxSymbols[DoubleLine?BS_T_H2V2:BS_T_H2V1]); if (Global->Opt->ShowColumnTitles) { const auto& ColumnTitleColor = colors::PaletteColorToFarColor(COL_PANELCOLUMNTITLE); auto Color = colors::PaletteColorToFarColor(COL_PANELBOX); Color.BackgroundColor = ColumnTitleColor.BackgroundColor; Color.SetBg4Bit(ColumnTitleColor.IsBg4Bit()); SetColor(Color); GotoXY(static_cast<int>(ColumnPos), m_Where.top + 1); Text(BoxSymbols[DoubleLine?BS_V2:BS_V1]); } if (!Global->Opt->ShowPanelStatus) { GotoXY(static_cast<int>(ColumnPos), m_Where.bottom); Text(BoxSymbols[DoubleLine?BS_B_H2V2:BS_B_H2V1]); } ColumnPos++; } int NextX1 = m_Where.left + 1; if (Global->Opt->ShowSortMode) { wchar_t Indicator = 0; if (m_SortMode < panel_sort::COUNT) { const auto& CurrenModeData = SortModes[static_cast<size_t>(m_SortMode)]; const auto& CurrentModeName = msg(CurrenModeData.Label); // Owerflow from npos to 0 is ok - pick the first character if & isn't there. const auto Char = CurrentModeName[CurrentModeName.find(L'&') + 1]; const auto UseReverseIndicator = Global->Opt->ReverseSortCharCompat && Global->Opt->PanelSortLayers[static_cast<size_t>(m_SortMode)].front().second == sort_order::descend? !m_ReverseSortOrder: m_ReverseSortOrder; Indicator = UseReverseIndicator? upper(Char) : lower(Char); } else if (m_SortMode >= panel_sort::BY_USER) { Indicator = m_ReverseSortOrder? CustomSortIndicator[1] : CustomSortIndicator[0]; } else { LOGWARNING(L"Unknown sort mode {}"sv, m_SortMode); } if (Indicator) { GotoXY(NextX1, m_Where.top + (Global->Opt->ShowColumnTitles? 1 : 0)); SetColor(COL_PANELCOLUMNTITLE); Text(Indicator); NextX1++; if (m_Filter && m_Filter->IsEnabledOnPanel()) { Text(L"*"sv); NextX1++; } } } /* <режимы сортировки> */ if (/* GetSortGroups() || */GetSelectedFirstMode()) { GotoXY(NextX1, m_Where.top + (Global->Opt->ShowColumnTitles? 1 : 0)); SetColor(COL_PANELCOLUMNTITLE); string Indicators; //if (GetSelectedFirstMode()) Indicators.push_back(L'^'); /* if(GetSortGroups()) Indicators.push_back(L'@'); */ Text(Indicators); } /* </режимы сортировки> */ if (!Fast && IsFocused()) { if (m_PanelMode == panel_mode::PLUGIN_PANEL) Parent()->GetCmdLine()->SetCurDir(NullToEmpty(m_CachedOpenPanelInfo.CurDir)); else Parent()->GetCmdLine()->SetCurDir(m_CurDir); Parent()->GetCmdLine()->Show(); } strTitle = GetTitle(); int TitleX2 = m_Where.right; if (Global->Opt->Clock && !Global->Opt->ShowMenuBar && m_Where.left + strTitle.size() + 2 >= ScrX - Global->CurrentTime.size()) TitleX2 = std::min(static_cast<int>(ScrX - Global->CurrentTime.size()), static_cast<int>(m_Where.right)); int MaxSize = TitleX2 - m_Where.left - 1; int XShift = 0; if (!Global->Opt->ShowColumnTitles && Global->Opt->ShowSortMode) { ++XShift; if (m_Filter && m_Filter->IsEnabledOnPanel()) ++XShift; } MaxSize -= XShift; if (MaxSize >= 2) { inplace::truncate_path(strTitle, MaxSize - 2); } strTitle.insert(0, 1, L' '); strTitle.push_back(L' '); const auto TitleSize = static_cast<int>(strTitle.size()); int TitleX = m_Where.left + 1 + XShift + (TitleX2 - m_Where.left - XShift - TitleSize) / 2; if (Global->Opt->Clock && !Global->Opt->ShowMenuBar && TitleX + TitleSize > ScrX - static_cast<int>(Global->CurrentTime.size())) TitleX = ScrX - static_cast<int>(Global->CurrentTime.size()) - TitleSize; SetColor(IsFocused()? COL_PANELSELECTEDTITLE:COL_PANELTITLE); GotoXY(TitleX, m_Where.top); Text(strTitle); if (m_ListData.empty()) { SetScreen({ m_Where.left + 1, m_Where.bottom - 1, m_Where.right - 1, m_Where.bottom - 1 }, L' ', colors::PaletteColorToFarColor(COL_PANELTEXT)); SetColor(COL_PANELTEXT); //??? //GotoXY(X1+1,Y2-1); //Text(string(X2 - X1 - 1, L' ')); } if (m_PanelMode == panel_mode::PLUGIN_PANEL && !m_ListData.empty() && (m_CachedOpenPanelInfo.Flags & OPIF_REALNAMES) // Network plugin sets OPIF_REALNAMES when showing list of shares as they are real FS objects (see M#650). // However, \\server itself is not a real FS directory in any way and it is not possible to set it on a real panel. // We can't simply remove the code below, as other plugins rely on this feature (e. g. Ctrl+PgUp in TmpPanel // "exits" to the CurDir, dynamically set by the plugin), so disabling it for the Network plugin only for now. // Yes, it is ugly, I know. It probably would be better to set CurDir in the Network plugin dynamically in this case // as \\server\current_share_under_cursor, but the plugin doesn't keep that information currently. && GetPluginHandle()->plugin()->Id() != Global->Opt->KnownIDs.Network.Id ) { if (!strInfoCurDir.empty()) { m_CurDir = strInfoCurDir; } else { if (!IsParentDirectory(m_ListData[m_CurFile])) { m_CurDir=m_ListData[m_CurFile].FileName; const auto pos = FindLastSlash(m_CurDir); if (pos != string::npos && pos) { m_CurDir.resize(m_CurDir[pos - 1] != L':'? pos : pos + 1); } } else { m_CurDir = strOriginalCurDir; } } if (IsFocused()) { Parent()->GetCmdLine()->SetCurDir(m_CurDir); Parent()->GetCmdLine()->Show(); } } if ((Global->Opt->ShowPanelTotals || Global->Opt->ShowPanelFree) && (Global->Opt->ShowPanelStatus || !m_SelFileCount)) { ShowTotalSize(m_CachedOpenPanelInfo); } ShowList(FALSE,0); ShowSelectedSize(); if (Global->Opt->ShowPanelScrollbar) { SetColor(COL_PANELSCROLLBAR); const auto per_stripe = [&](size_t const Value) { return Value / m_Stripes + (Value % m_Stripes != 0); }; ScrollBar( m_Where.right, m_Where.top + 1 + Global->Opt->ShowColumnTitles, m_Height, per_stripe(m_CurTopFile), per_stripe(m_ListData.size())); } ShowScreensCount(); if (m_PanelMode == panel_mode::PLUGIN_PANEL) Parent()->RedrawKeyBar(); } FarColor FileList::GetShowColor(int Position, bool FileColor) const { auto ColorAttr = colors::PaletteColorToFarColor(COL_PANELTEXT); if (static_cast<size_t>(Position) >= m_ListData.size()) return ColorAttr; int Pos = highlight::color::normal; if (m_CurFile == Position && IsFocused() && !m_ListData.empty()) { Pos=m_ListData[Position].Selected? highlight::color::selected_current : highlight::color::normal_current; } else if (m_ListData[Position].Selected) { Pos = highlight::color::selected; } const auto HighlightingEnabled = Global->Opt->Highlight && (m_PanelMode != panel_mode::PLUGIN_PANEL || !(m_CachedOpenPanelInfo.Flags & OPIF_DISABLEHIGHLIGHTING)); if (HighlightingEnabled) { if (!m_ListData[Position].Colors) { const auto UseAttrHighlighting = m_PanelMode == panel_mode::PLUGIN_PANEL && m_CachedOpenPanelInfo.Flags & OPIF_USEATTRHIGHLIGHTING; m_ListData[Position].Colors = Global->CtrlObject->HiFiles->GetHiColor(m_ListData[Position], this, UseAttrHighlighting); } auto Colors = m_ListData[Position].Colors->Color[Pos]; highlight::configuration::ApplyFinalColor(Colors, Pos); ColorAttr = FileColor ? Colors.FileColor : Colors.MarkColor; } if (!HighlightingEnabled || (!ColorAttr.ForegroundColor && !ColorAttr.BackgroundColor)) // black on black, default { static const PaletteColors PalColor[] = {COL_PANELTEXT, COL_PANELSELECTEDTEXT, COL_PANELCURSOR, COL_PANELSELECTEDCURSOR}; ColorAttr=colors::PaletteColorToFarColor(PalColor[Pos]); } return ColorAttr; } void FileList::SetShowColor(int Position, bool FileColor) const { SetColor(GetShowColor(Position,FileColor)); } static string size2str(uint64_t const Size, int const Width, bool const FloatStyle, bool const ShowBytes) { if (ShowBytes) { return GroupDigits(Size); } if (FloatStyle) // float style { return trim(FileSizeToStr(Size, Width, COLFLAGS_FLOATSIZE | COLFLAGS_SHOW_MULTIPLIER)); } auto Str = str(Size); if (static_cast<int>(Str.size()) <= Width) return Str; return trim(FileSizeToStr(Size, Width, COLFLAGS_SHOW_MULTIPLIER)); } void FileList::ShowSelectedSize() { if (Global->Opt->ShowPanelStatus) { SetColor(COL_PANELBOX); DrawSeparator(m_Where.bottom - 2); for (size_t I = 0, ColumnPos = m_Where.left + 1; I < m_ViewSettings.PanelColumns.size() - 1; I++) { if (m_ViewSettings.PanelColumns[I].width < 0 || (I == m_ViewSettings.PanelColumns.size() - 2 && m_ViewSettings.PanelColumns[I+1].width < 0)) continue; ColumnPos += m_ViewSettings.PanelColumns[I].width; GotoXY(static_cast<int>(ColumnPos), m_Where.bottom - 2); const auto DoubleLine = !((I + 1) % m_ColumnsInStripe); Text(BoxSymbols[DoubleLine?BS_B_H1V2:BS_B_H1V1]); ColumnPos++; } } if (m_SelFileCount) { auto strFormStr = size2str(SelFileSize, 6, false, true); auto strSelStr = format(msg(lng::MListFileSize), strFormStr, m_SelFileCount - m_SelDirCount, m_SelDirCount, m_SelFileCount); const auto BorderSize = 1; const auto MarginSize = 1; const auto AvailableWidth = static_cast<size_t>(std::max(0, ObjWidth() - BorderSize * 2 - MarginSize * 2)); if (strSelStr.size() > AvailableWidth) { strFormStr = size2str(SelFileSize, 6, false, false); strSelStr = format(msg(lng::MListFileSize), strFormStr, m_SelFileCount - m_SelDirCount, m_SelDirCount, m_SelFileCount); if (strSelStr.size() > AvailableWidth) inplace::truncate_right(strSelStr, AvailableWidth); } SetColor(COL_PANELSELECTEDINFO); GotoXY(static_cast<int>(m_Where.left + BorderSize + (AvailableWidth - strSelStr.size()) / 2), m_Where.bottom - 2 * Global->Opt->ShowPanelStatus); Text(L' '); Text(strSelStr); Text(L' '); } } void FileList::ShowTotalSize(const OpenPanelInfo &Info) { if (!Global->Opt->ShowPanelTotals && m_PanelMode == panel_mode::PLUGIN_PANEL && !(Info.Flags & OPIF_REALNAMES)) return; const auto calc_total_string = [this, Info](bool ShowBytes) { string strFreeSize, strTotalSize; auto strFormSize = size2str(TotalFileSize, 10, true, ShowBytes); if (Global->Opt->ShowPanelFree && (m_PanelMode != panel_mode::PLUGIN_PANEL || (Info.Flags & (OPIF_REALNAMES | OPIF_USEFREESIZE)))) strFreeSize = (FreeDiskSize != static_cast<unsigned long long>(-1)) ? size2str(FreeDiskSize, 10, true, ShowBytes) : L"?"sv; if (Global->Opt->ShowPanelTotals) { if (!Global->Opt->ShowPanelFree || strFreeSize.empty()) { strTotalSize = format(msg(lng::MListFileSize), strFormSize, m_TotalFileCount, m_TotalDirCount, m_TotalFileCount + m_TotalDirCount); } else { const string DHLine(3, BoxSymbols[BS_H2]); strTotalSize = format(msg(lng::MListFileSizeStatus), strFormSize, m_TotalFileCount, m_TotalDirCount, DHLine, strFreeSize); } } else { strTotalSize = format(msg(lng::MListFreeSize), strFreeSize.empty() ? L"?"s : strFreeSize); } return strTotalSize; }; const auto BorderSize = 1; const auto MarginSize = 1; const auto AvailableWidth = static_cast<size_t>(std::max(0, ObjWidth() - BorderSize * 2 - MarginSize * 2)); auto TotalStr = calc_total_string(Global->Opt->ShowBytes); if (TotalStr.size() > AvailableWidth) { if (Global->Opt->ShowBytes) TotalStr = calc_total_string(false); inplace::truncate_right(TotalStr, AvailableWidth); } const string_view TotalStrView = TotalStr; SetColor(COL_PANELTOTALINFO); GotoXY(static_cast<int>(m_Where.left + BorderSize + (AvailableWidth - TotalStrView.size()) / 2), m_Where.bottom); const auto BoxPos = TotalStrView.find(BoxSymbols[BS_H2]); Text(L' '); if (const auto BoxLength = BoxPos == string::npos? 0 : std::count(TotalStrView.begin() + BoxPos, TotalStrView.end(), BoxSymbols[BS_H2])) { Text(TotalStrView.substr(0, BoxPos)); SetColor(COL_PANELBOX); Text(TotalStrView.substr(BoxPos, BoxLength)); SetColor(COL_PANELTOTALINFO); Text(TotalStrView.substr(BoxPos + BoxLength)); } else { Text(TotalStrView); } Text(L' '); } bool FileList::ConvertName(const string_view SrcName, string& strDest, const int MaxLength, const unsigned long long RightAlign, const int ShowStatus, os::fs::attributes const FileAttr) const { strDest.reserve(MaxLength); const auto SrcLength = static_cast<int>(SrcName.size()); if ((RightAlign & COLFLAGS_RIGHTALIGNFORCE) || (RightAlign && (SrcLength>MaxLength))) { if (SrcLength>MaxLength) { strDest = SrcName.substr(SrcLength - MaxLength, MaxLength); } else { strDest.assign(MaxLength - SrcLength, L' '); append(strDest, SrcName); } return SrcLength > MaxLength; } string_view Extension; if (!ShowStatus && ((!(FileAttr & FILE_ATTRIBUTE_DIRECTORY) && (m_ViewSettings.Flags & PVS_ALIGNEXTENSIONS)) || ((FileAttr & FILE_ATTRIBUTE_DIRECTORY) && (m_ViewSettings.Flags & PVS_FOLDERALIGNEXTENSIONS))) && SrcLength <= MaxLength && (Extension = name_ext(SrcName).second).size() > 1 && Extension.size() != SrcName.size() && (SrcName.size() > 2 || SrcName[0] != L'.') && !contains(Extension, L' ')) { Extension.remove_prefix(1); auto Name = SrcName.substr(0, SrcName.size() - Extension.size()); const auto DotPos = std::max(MaxLength - std::max(Extension.size(), size_t(3)), Name.size()); if (Name.size() > 1 && Name[Name.size() - 2] != L' ') Name.remove_suffix(1); strDest += Name; strDest.resize(DotPos, L' '); strDest += Extension; strDest.resize(MaxLength, L' '); } else { strDest.assign(SrcName, 0, std::min(SrcLength, MaxLength)); strDest.resize(MaxLength, L' '); } return SrcLength > MaxLength; } void FileList::PrepareViewSettings(int ViewMode) { if (m_PanelMode == panel_mode::PLUGIN_PANEL) { Global->CtrlObject->Plugins->GetOpenPanelInfo(GetPluginHandle(), &m_CachedOpenPanelInfo); } m_ViewSettings = Global->Opt->ViewSettings[ViewMode].clone(); if (m_PanelMode == panel_mode::PLUGIN_PANEL) { if (m_CachedOpenPanelInfo.PanelModesArray && ViewMode<static_cast<int>(m_CachedOpenPanelInfo.PanelModesNumber) && m_CachedOpenPanelInfo.PanelModesArray[ViewMode].ColumnTypes && m_CachedOpenPanelInfo.PanelModesArray[ViewMode].ColumnWidths) { m_ViewSettings.PanelColumns = DeserialiseViewSettings(m_CachedOpenPanelInfo.PanelModesArray[ViewMode].ColumnTypes, m_CachedOpenPanelInfo.PanelModesArray[ViewMode].ColumnWidths); if (m_CachedOpenPanelInfo.PanelModesArray[ViewMode].StatusColumnTypes && m_CachedOpenPanelInfo.PanelModesArray[ViewMode].StatusColumnWidths) { m_ViewSettings.StatusColumns = DeserialiseViewSettings(m_CachedOpenPanelInfo.PanelModesArray[ViewMode].StatusColumnTypes, m_CachedOpenPanelInfo.PanelModesArray[ViewMode].StatusColumnWidths); } else if (m_CachedOpenPanelInfo.PanelModesArray[ViewMode].Flags&PMFLAGS_DETAILEDSTATUS) { m_ViewSettings.StatusColumns = { { column_type::name, COLFLAGS_RIGHTALIGN, 0, }, { column_type::size, 0, 8, }, { column_type::date, 0, 0, }, { column_type::time, 0, 5, }, }; } else { m_ViewSettings.StatusColumns = { { column_type::name, COLFLAGS_RIGHTALIGN, 0, }, }; } if (m_CachedOpenPanelInfo.PanelModesArray[ViewMode].Flags&PMFLAGS_FULLSCREEN) m_ViewSettings.Flags|=PVS_FULLSCREEN; else m_ViewSettings.Flags&=~PVS_FULLSCREEN; if (m_CachedOpenPanelInfo.PanelModesArray[ViewMode].Flags&PMFLAGS_ALIGNEXTENSIONS) m_ViewSettings.Flags|=PVS_ALIGNEXTENSIONS; else m_ViewSettings.Flags&=~PVS_ALIGNEXTENSIONS; if (!(m_CachedOpenPanelInfo.PanelModesArray[ViewMode].Flags&PMFLAGS_CASECONVERSION)) m_ViewSettings.Flags&=~(PVS_FOLDERUPPERCASE|PVS_FILELOWERCASE|PVS_FILEUPPERTOLOWERCASE); } else { const auto NameOnlyFlag = m_CachedOpenPanelInfo.Flags & OPIF_SHOWNAMESONLY? COLFLAGS_NAMEONLY : COLFLAGS_NONE; const auto RightAlignFlag = m_CachedOpenPanelInfo.Flags & OPIF_SHOWRIGHTALIGNNAMES? COLFLAGS_RIGHTALIGN : COLFLAGS_NONE; for (auto& i: m_ViewSettings.PanelColumns) { if (i.type == column_type::name) { i.type_flags |= NameOnlyFlag; i.type_flags |= RightAlignFlag; } } if (m_CachedOpenPanelInfo.Flags & OPIF_SHOWPRESERVECASE) m_ViewSettings.Flags&=~(PVS_FOLDERUPPERCASE|PVS_FILELOWERCASE|PVS_FILEUPPERTOLOWERCASE); } } PreparePanelView(); UpdateHeight(); } void FileList::PreparePanelView() { PrepareColumnWidths(m_ViewSettings.StatusColumns, (m_ViewSettings.Flags&PVS_FULLSCREEN) != 0); PrepareColumnWidths(m_ViewSettings.PanelColumns, (m_ViewSettings.Flags&PVS_FULLSCREEN) != 0); PrepareStripes(m_ViewSettings.PanelColumns); } void FileList::PrepareColumnWidths(std::vector<column>& Columns, bool FullScreen) const { int ZeroLengthCount = 0; int EmptyColumns = 0; int TotalPercentCount = 0; int TotalPercentWidth = 0; int TotalWidth = static_cast<int>(Columns.size() - 1); for (auto& i: Columns) { if (i.width < 0) { EmptyColumns++; continue; } if (!i.width) { i.width_type = col_width::fixed; //manage all zero-width columns in same way i.width = GetDefaultWidth(i); } if (!i.width) ZeroLengthCount++; switch (i.width_type) { case col_width::fixed: TotalWidth += i.width; break; case col_width::percent: TotalPercentWidth += i.width; TotalPercentCount++; break; } } TotalWidth-=EmptyColumns; int PanelTextWidth = m_Where.width() - 2; if (FullScreen) PanelTextWidth=ScrX-1; int ExtraWidth=PanelTextWidth-TotalWidth; if (TotalPercentCount>0) { const auto ExtraPercentWidth = (TotalPercentWidth > 100 || !ZeroLengthCount) ? ExtraWidth : ExtraWidth * TotalPercentWidth / 100; int TempWidth=0; for (auto& i: Columns) { if (!TotalPercentCount) break; if (i.width_type == col_width::percent) { int PercentWidth = (TotalPercentCount > 1)? (ExtraPercentWidth * i.width / TotalPercentWidth) : (ExtraPercentWidth - TempWidth); if (PercentWidth<1) PercentWidth=1; TempWidth+=PercentWidth; i.width = PercentWidth; i.width_type = col_width::fixed; TotalPercentCount--; } } ExtraWidth-=TempWidth; } for (auto& i: Columns) { if (!ZeroLengthCount) break; if (!i.width) { int AutoWidth=ExtraWidth/ZeroLengthCount; if (AutoWidth<1) AutoWidth=1; i.width = AutoWidth; ExtraWidth-=AutoWidth; ZeroLengthCount--; } } for (;;) { const auto LastColumn = static_cast<int>(Columns.size() - 1); TotalWidth=LastColumn-EmptyColumns; for (const auto& i: Columns) { if (i.width > 0) TotalWidth += i.width; } if (TotalWidth<=PanelTextWidth) break; if (Columns.size() <= 1) { Columns.front().width = PanelTextWidth; break; } else if (PanelTextWidth >= TotalWidth - Columns[LastColumn].width) { Columns[LastColumn].width = PanelTextWidth - (TotalWidth - Columns[LastColumn].width); break; } else Columns.pop_back(); } } namespace { bool CanMakeStripes(const std::vector<column>& Columns, int StripeStride) { if (Columns.size() % StripeStride != 0) return false; const auto FirstStripeBegin = Columns.cbegin(); const auto FirstStripeEnd = FirstStripeBegin + StripeStride; for (auto Stripe = FirstStripeEnd; Stripe != Columns.cend(); Stripe += StripeStride) { if (!std::equal(FirstStripeBegin, FirstStripeEnd, Stripe, [](const column& a, const column& b) { return a.type == b.type; })) { return false; } } return true; } } void FileList::PrepareStripes(const std::vector<column>& Columns) { const auto ColumnsSize = static_cast<int>(Columns.size()); for (const auto& StripeStride: irange(1, ColumnsSize / 2 + 1)) { if (CanMakeStripes(Columns, StripeStride)) { m_Stripes = ColumnsSize / StripeStride; m_ColumnsInStripe = StripeStride; return; } } m_Stripes = 1; m_ColumnsInStripe = ColumnsSize; } void FileList::HighlightBorder(int Level, int ListPos) const { if (Level == m_ColumnsInStripe) { SetColor(COL_PANELBOX); } else { const auto FileColor = GetShowColor(ListPos, true); auto Color = colors::PaletteColorToFarColor(COL_PANELBOX); Color.BackgroundColor = FileColor.BackgroundColor; Color.SetBg4Bit(FileColor.IsBg4Bit()); SetColor(Color); } } void FileList::ShowList(int ShowStatus,int StartColumn) { int StatusShown=FALSE; int MaxLeftPos=0,MinLeftPos=FALSE; size_t ColumnCount=ShowStatus ? m_ViewSettings.StatusColumns.size() : m_ViewSettings.PanelColumns.size(); const auto& Columns = ShowStatus ? m_ViewSettings.StatusColumns : m_ViewSettings.PanelColumns; for (int I = m_Where.top + 1 + Global->Opt->ShowColumnTitles, J = m_CurTopFile; I < m_Where.bottom - 2 * Global->Opt->ShowPanelStatus; I++, J++) { int CurColumn=StartColumn; if (ShowStatus) { SetColor(COL_PANELTEXT); GotoXY(m_Where.left + 1, m_Where.bottom - 1); } else { GotoXY(m_Where.left + 1, I); } int StatusLine=FALSE; int Level = 1; for (const auto& K: irange(ColumnCount)) { int ListPos=J+CurColumn*m_Height; if (ShowStatus) { if (m_CurFile!=ListPos) { CurColumn++; continue; } else StatusLine=TRUE; } else { SetShowColor(ListPos); } int CurX=WhereX(); int CurY=WhereY(); int ShowDivider=TRUE; const auto ColumnType = Columns[K].type; int ColumnWidth=Columns[K].width; if (ColumnWidth<0) { if (!ShowStatus && K==ColumnCount-1) { SetColor(COL_PANELBOX); GotoXY(CurX-1,CurY); Text(CurX - 1 == m_Where.right? BoxSymbols[BS_V2] : L' '); } continue; } if (ListPos < static_cast<int>(m_ListData.size())) { if (!ShowStatus && !StatusShown && m_CurFile==ListPos && Global->Opt->ShowPanelStatus) { ShowList(TRUE,CurColumn); GotoXY(CurX,CurY); StatusShown=TRUE; SetShowColor(ListPos); } if (!ShowStatus) SetShowColor(ListPos); if (ColumnType >= column_type::custom_0 && ColumnType <= column_type::custom_max) { size_t ColumnNumber = static_cast<size_t>(ColumnType) - static_cast<size_t>(column_type::custom_0); const wchar_t *ColumnData = nullptr; if (ColumnNumber < m_ListData[ListPos].CustomColumns.size()) ColumnData = m_ListData[ListPos].CustomColumns[ColumnNumber]; if (!ColumnData) { const auto GetContentData = [&] { const auto& ContentMapPtr = m_ListData[ListPos].ContentData(this); if (!ContentMapPtr) return L""; const auto Iterator = ContentMapPtr->find(Columns[K].title); return Iterator != ContentMapPtr->cend()? Iterator->second.c_str() : L""; }; ColumnData = GetContentData(); } int CurLeftPos=0; if (!ShowStatus && LeftPos>0) { int Length = static_cast<int>(std::wcslen(ColumnData)); if (Length>ColumnWidth) { CurLeftPos = std::min(LeftPos, Length-ColumnWidth); MaxLeftPos = std::max(MaxLeftPos, CurLeftPos); } } Text(fit_to_left(ColumnData + CurLeftPos, ColumnWidth)); } else { switch (ColumnType) { case column_type::name: { int Width=ColumnWidth; const auto ViewFlags = Columns[K].type_flags; if ((ViewFlags & COLFLAGS_MARK) && Width>2) { const auto Mark = m_ListData[ListPos].Selected? L"√ "sv : ViewFlags & COLFLAGS_MARK_DYNAMIC ? L""sv : L" "sv; Text(Mark); Width -= static_cast<int>(Mark.size()); } if (Global->Opt->Highlight && m_ListData[ListPos].Colors && m_ListData[ListPos].Colors->Mark.Char && Width>1) { Width--; const auto OldColor = GetColor(); if (!ShowStatus) SetShowColor(ListPos, false); Text(m_ListData[ListPos].Colors->Mark.Char); SetColor(OldColor); } string_view Name = m_ListData[ListPos].AlternateOrNormal(m_ShowShortNames); if (!(m_ListData[ListPos].Attributes & FILE_ATTRIBUTE_DIRECTORY) && (ViewFlags & COLFLAGS_NOEXTENSION)) { Name = name_ext(Name).first; } const auto NameCopy = Name; if (ViewFlags & COLFLAGS_NAMEONLY) { //BUGBUG!!! // !!! НЕ УВЕРЕН, но то, что отображается пустое // пространство вместо названия - бага Name = PointToFolderNameIfFolder(Name); } int CurLeftPos=0; unsigned long long RightAlign=(ViewFlags & (COLFLAGS_RIGHTALIGN|COLFLAGS_RIGHTALIGNFORCE)); int LeftBracket=FALSE,RightBracket=FALSE; if (!ShowStatus && LeftPos) { const auto Length = static_cast<int>(Name.size()); if (Length>Width) { if (LeftPos>0) { if (!RightAlign) { CurLeftPos = std::min(LeftPos, Length-Width); MaxLeftPos = std::max(MaxLeftPos, CurLeftPos); Name.remove_prefix(CurLeftPos); } } else if (RightAlign) { int CurRightPos=LeftPos; if (Length+CurRightPos<Width) { CurRightPos=Width-Length; } else { RightBracket=TRUE; LeftBracket=(ViewFlags & COLFLAGS_RIGHTALIGNFORCE)==COLFLAGS_RIGHTALIGNFORCE; } Name.remove_prefix(Length + CurRightPos - Width); RightAlign=FALSE; MinLeftPos = std::min(MinLeftPos, CurRightPos); } } } string strName; int TooLong=ConvertName(Name, strName, Width, RightAlign,ShowStatus,m_ListData[ListPos].Attributes); if (CurLeftPos) LeftBracket=TRUE; if (TooLong) { if (RightAlign) LeftBracket=TRUE; if (!RightAlign && static_cast<int>(Name.size()) > Width) RightBracket=TRUE; } if (!ShowStatus) { if (m_ViewSettings.Flags&PVS_FILEUPPERTOLOWERCASE) if (!(m_ListData[ListPos].Attributes & FILE_ATTRIBUTE_DIRECTORY) && !IsCaseMixed(NameCopy)) inplace::lower(strName); if ((m_ViewSettings.Flags&PVS_FOLDERUPPERCASE) && (m_ListData[ListPos].Attributes & FILE_ATTRIBUTE_DIRECTORY)) inplace::upper(strName); if ((m_ViewSettings.Flags&PVS_FILELOWERCASE) && !(m_ListData[ListPos].Attributes & FILE_ATTRIBUTE_DIRECTORY)) inplace::lower(strName); } Text(strName); if (!ShowStatus) { int NameX=WhereX(); if (LeftBracket) { GotoXY(CurX-1,CurY); if (Level == 1) SetColor(COL_PANELBOX); Text(openBracket); SetShowColor(J); } if (RightBracket) { HighlightBorder(Level, ListPos); GotoXY(NameX,CurY); Text(closeBracket); ShowDivider=FALSE; if (Level == m_ColumnsInStripe) SetColor(COL_PANELTEXT); else SetShowColor(J); } } } break; case column_type::extension: { string_view ExtPtr; if (!(m_ListData[ListPos].Attributes & FILE_ATTRIBUTE_DIRECTORY)) { const auto& Name = m_ListData[ListPos].AlternateOrNormal(m_ShowShortNames); ExtPtr = name_ext(Name).second; } if (!ExtPtr.empty()) ExtPtr.remove_prefix(1); const auto ViewFlags = Columns[K].type_flags; Text((ViewFlags & COLFLAGS_RIGHTALIGN? fit_to_right : fit_to_left)(string(ExtPtr), ColumnWidth)); if (!ShowStatus && static_cast<int>(ExtPtr.size()) > ColumnWidth) { int NameX=WhereX(); HighlightBorder(Level, ListPos); GotoXY(NameX,CurY); Text(closeBracket); ShowDivider=FALSE; if (Level == m_ColumnsInStripe) SetColor(COL_PANELTEXT); else SetShowColor(J); } break; } case column_type::size: case column_type::size_compressed: case column_type::streams_size: { const auto SizeToDisplay = (ColumnType == column_type::size_compressed) ? m_ListData[ListPos].AllocationSize : (ColumnType == column_type::streams_size) ? m_ListData[ListPos].StreamsSize(this) : m_ListData[ListPos].FileSize; Text(FormatStr_Size( SizeToDisplay, m_ListData[ListPos].FileName, m_ListData[ListPos].Attributes, m_ListData[ListPos].ShowFolderSize, m_ListData[ListPos].ReparseTag, ColumnType, Columns[K].type_flags, ColumnWidth, m_CurDir)); break; } case column_type::date: case column_type::time: case column_type::date_write: case column_type::date_creation: case column_type::date_access: case column_type::date_change: { os::chrono::time_point const FileListItem::* FileTime; switch (ColumnType) { case column_type::date_creation: FileTime = &FileListItem::CreationTime; break; case column_type::date_access: FileTime = &FileListItem::LastAccessTime; break; case column_type::date_change: FileTime = &FileListItem::ChangeTime; break; default: FileTime = &FileListItem::LastWriteTime; break; } Text(FormatStr_DateTime(std::invoke(FileTime, m_ListData[ListPos]), ColumnType, Columns[K].type_flags, ColumnWidth)); break; } case column_type::attributes: { Text(FormatStr_Attribute(m_ListData[ListPos].Attributes,ColumnWidth)); break; } case column_type::description: { int CurLeftPos=0; if (!ShowStatus && LeftPos>0) { int Length = static_cast<int>(std::wcslen(NullToEmpty(m_ListData[ListPos].DizText))); if (Length>ColumnWidth) { CurLeftPos = std::min(LeftPos, Length-ColumnWidth); MaxLeftPos = std::max(MaxLeftPos, CurLeftPos); } } auto DizText = m_ListData[ListPos].DizText? m_ListData[ListPos].DizText + CurLeftPos : L""sv; const auto pos = DizText.find(L'\4'); if (pos != string::npos) DizText.remove_suffix(DizText.size() - pos); Text(fit_to_left(string(DizText), ColumnWidth)); break; } case column_type::owner: { const auto& Owner = m_ListData[ListPos].Owner(this); size_t Offset = 0; if (!(Columns[K].type_flags & COLFLAGS_FULLOWNER) && m_PanelMode != panel_mode::PLUGIN_PANEL) { const auto SlashPos = FindSlash(Owner); if (SlashPos != string::npos) { Offset = SlashPos + 1; } } else if(!Owner.empty() && path::is_separator(Owner.front())) { Offset = 1; } int CurLeftPos=0; if (!ShowStatus && LeftPos>0) { int Length = static_cast<int>(Owner.size() - Offset); if (Length>ColumnWidth) { CurLeftPos = std::min(LeftPos, Length-ColumnWidth); MaxLeftPos = std::max(MaxLeftPos, CurLeftPos); } } Text(fit_to_left(Owner.substr(Offset + CurLeftPos), ColumnWidth)); break; } case column_type::links_number: { const auto Value = m_ListData[ListPos].NumberOfLinks(this); Text(fit_to_right(Value == FileListItem::values::unknown(Value)? L"?"s : str(Value), ColumnWidth)); break; } case column_type::streams_number: { const auto Value = m_ListData[ListPos].NumberOfStreams(this); Text(fit_to_right(Value == FileListItem::values::unknown(Value)? L"?"s : str(Value), ColumnWidth)); break; } default: break; } } } else { Text(string(ColumnWidth, L' ')); } if (ShowDivider==FALSE) GotoXY(CurX+ColumnWidth+1,CurY); else { if (!ShowStatus) { HighlightBorder(Level, ListPos); } if (K == ColumnCount-1) SetColor(COL_PANELBOX); GotoXY(CurX+ColumnWidth,CurY); if (K==ColumnCount-1) Text(CurX + ColumnWidth == m_Where.right? BoxSymbols[BS_V2] : L' '); else Text(ShowStatus? L' ' : BoxSymbols[Level == m_ColumnsInStripe? BS_V2 : BS_V1]); if (!ShowStatus) SetColor(COL_PANELTEXT); } if (!ShowStatus) { if (Level == m_ColumnsInStripe) { Level = 0; CurColumn++; } Level++; } } if ((!ShowStatus || StatusLine) && WhereX() < m_Where.right) { SetColor(COL_PANELTEXT); Text(string(m_Where.right - WhereX(), L' ')); } } if (!ShowStatus && !StatusShown && Global->Opt->ShowPanelStatus) { SetScreen({ m_Where.left + 1, m_Where.bottom - 1, m_Where.right - 1, m_Where.bottom - 1 }, L' ', colors::PaletteColorToFarColor(COL_PANELTEXT)); SetColor(COL_PANELTEXT); //??? //GotoXY(X1+1,Y2-1); //Text(string(X2 - X1 - 1, L' ')); } if (!ShowStatus) { if (LeftPos<0) LeftPos=MinLeftPos; if (LeftPos>0) LeftPos=MaxLeftPos; } } bool FileList::IsModeFullScreen(int Mode) { return (Global->Opt->ViewSettings[Mode].Flags & PVS_FULLSCREEN) != 0; } bool FileList::IsDizDisplayed() const { return IsColumnDisplayed(column_type::description); } bool FileList::IsColumnDisplayed(function_ref<bool(const column&)> const Compare) const { return std::any_of(ALL_CONST_RANGE(m_ViewSettings.PanelColumns), Compare) || std::any_of(ALL_CONST_RANGE(m_ViewSettings.StatusColumns), Compare); } bool FileList::IsColumnDisplayed(column_type Type) const { return IsColumnDisplayed([&Type](const column& i) { return i.type == Type; }); } int FileList::GetColumnsCount() const { return m_Stripes; } bool FileList::GetSelectedFirstMode() const { return SelectedFirst; } std::unique_ptr<content_data> FileList::GetContentData(const string& Item) const { if (m_ContentPlugins.empty()) return {}; auto Result = std::make_unique<content_data>(); Global->CtrlObject->Plugins->GetContentData(m_ContentPlugins, Item, m_ContentNamesPtrs, m_ContentValues, *Result.get()); return Result; } void FileList::MoveSelection(direction Direction) { if (m_ListData.empty()) return; assert(m_CurFile < static_cast<int>(m_ListData.size())); const auto CurPtr = &m_ListData[m_CurFile]; if (ShiftSelection==-1) { // .. is never selected if (m_CurFile < static_cast<int>(m_ListData.size() - 1) && IsParentDirectory(*CurPtr)) ShiftSelection = !m_ListData[m_CurFile+1].Selected; else ShiftSelection=!CurPtr->Selected; } Select(*CurPtr, ShiftSelection != 0); if (Direction == up) MoveCursor(-1); else MoveCursor(1); if (SelectedFirst && !InternalProcessKey) SortFileList(true); } #ifdef ENABLE_TESTS #include "testing.hpp" TEST_CASE("fat_time") { using namespace std::chrono_literals; static const struct { os::chrono::duration First, Second; int Result; } Tests[] { { 0s, 0s, 0, }, { 0s + 1ms, 0s, 0, }, { 0s + 1ms, 2s, 0, }, { 1s - 1ms, 0s, 0, }, { 1s - 1ms, 2s, 0, }, { 1s, 2s, 0, }, { 1s + 1ms, 1s, 0, }, { 1s + 1ms, 2s, 0, }, { 2s - 1ms, 1s, 0, }, { 2s - 1ms, 2s, 0, }, { 2s, 2s, 0, }, { 2s + 1ms, 2s, 0, }, { 2s + 1ms, 4s, 0, }, { 3s - 1ms, 3s, 0, }, { 3s - 1ms, 4s, 0, }, { 3s, 4s, 0, }, { 3s + 1ms, 3s, 0, }, { 3s + 1ms, 4s, 0, }, { 4s - 1ms, 3s, 0, }, { 4s - 1ms, 4s, 0, }, { 4s, 4s, 0, }, { 4s + 1ms, 4s, 0, }, { 4s + 1ms, 6s, 0, }, { 0s, 2s, -1, }, { 2s, 4s, -1, }, { 2s, 0s, 1, }, { 4s, 2s, 1, }, }; for (const auto& i: Tests) { REQUIRE(compare_fat_write_time(os::chrono::time_point(i.First), os::chrono::time_point(i.Second)) == i.Result); } } #endif
johnd0e/FarManager
far/filelist.cpp
C++
bsd-3-clause
240,529
""" Dealing with SFT tests. """ import logging import sft_meta import sft_schema as schema from sft.utils.helpers import strip_args class SFTPool(): """ This class defines all site functional tests (SFT)s that shall be executed. """ def __init__(self): self.log = logging.getLogger(__name__) self.session=sft_meta.Session() self.log.debug("Initialization finished") def __del__(self): self.session.close() @strip_args def add_sft(self, name, cluster_grp, vo_grp,test_suit): """ Adding a new SFT to the 'global' pool of SFTS. params: name - the name of the SFT, must be unique cluster_grp - the name of the cluster group (see ClusterGroupPool) to which SFTs shall apply vo_grp - the name of the VO group (see VOGroupPool), to which SFT shall apply test_suit - the suit of tests the SFT consists of Notice: the execution time, is must be set via the set_exectime method Notice: XXX checks whether cluster_grp, vo_grp and test_suit exist are currently missing """ sft = self.session.query(schema.SFTTest).filter_by(name=name).first() if sft: self.log.info("SFT test '%s' exists already, overwriting" % name) else: self.log.debug("Adding SFT '%s'." % name) sft = schema.SFTTest() sft.name = name sft.cluster_group = cluster_grp sft.vo_group = vo_grp sft.test_suit = test_suit self.session.add(sft) self.session.commit() @strip_args def set_exectime(self, name, minute='0', hour='*', day='*', month='*', weekday='*'): """ Setting execution time of the SFT. params: name - name of the SFT minute - minute 0-59, default 0 hour - hour 0-23, default * day - day 1-31, default * month - month 1-12, default * weekday - day of week 0-6, Sunday=0, default * Notice: for each param, you can use crontab notation, e.g. '*', '1-3', '*/5', etc. """ sft = self.session.query(schema.SFTTest).filter_by(name=name).first() if sft: sft.minute = minute sft.hour = hour sft.day = day sft.month= month sft.weekday = weekday self.session.commit() @strip_args def remove_sft(self, name): """ removing SFT from SFT pool. params: name - name of SFT to remove """ sft = self.session.query(schema.SFTTest).filter_by(name=name).first() if sft: self.log.info("Removing sft '%s'." % name) self.session.delete(sft) self.session.commit() def list_sfts(self): """ Listing of all existing SFTs in pool. returns list of SFT objects """ return self.session.query(schema.SFTTest).all()
placiflury/gridmonitor-sft
sft/db/sft_handler.py
Python
bsd-3-clause
3,142
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Aurora.DataManager; using Aurora.Simulation.Base; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Services.Connectors; using OpenSim.Services.Interfaces; namespace OpenSim.Services.UserAccountService { public class UserAccountService : ConnectorBase, IUserAccountService, IService { #region Declares protected IAuthenticationService m_AuthenticationService; protected IUserAccountData m_Database; protected IGridService m_GridService; protected IInventoryService m_InventoryService; protected GenericAccountCache<UserAccount> m_cache = new GenericAccountCache<UserAccount>(); #endregion #region IService Members public virtual string Name { get { return GetType().Name; } } public void Initialize(IConfigSource config, IRegistryCore registry) { IConfig handlerConfig = config.Configs["Handlers"]; if (handlerConfig.GetString("UserAccountHandler", "") != Name) return; Configure(config, registry); Init(registry, Name); } public void Configure(IConfigSource config, IRegistryCore registry) { if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand( "create user", "create user [<first> [<last> [<pass> [<email>]]]]", "Create a new user", HandleCreateUser); MainConsole.Instance.Commands.AddCommand("reset user password", "reset user password [<first> [<last> [<password>]]]", "Reset a user password", HandleResetUserPassword); MainConsole.Instance.Commands.AddCommand( "show account", "show account <first> <last>", "Show account details for the given user", HandleShowAccount); MainConsole.Instance.Commands.AddCommand( "set user level", "set user level [<first> [<last> [<level>]]]", "Set user level. If the user's level is > 0, " + "this account will be treated as god-moded. " + "It will also affect the 'login level' command. ", HandleSetUserLevel); MainConsole.Instance.Commands.AddCommand( "set user profile title", "set user profile title [<first> [<last> [<Title>]]]", "Sets the title (Normally resident) in a user's title to some custom value.", HandleSetTitle); MainConsole.Instance.Commands.AddCommand( "set partner", "set partner", "Sets the partner in a user's profile.", HandleSetPartner); } registry.RegisterModuleInterface<IUserAccountService>(this); } public void Start(IConfigSource config, IRegistryCore registry) { m_GridService = registry.RequestModuleInterface<IGridService>(); m_AuthenticationService = registry.RequestModuleInterface<IAuthenticationService>(); m_InventoryService = registry.RequestModuleInterface<IInventoryService>(); m_Database = DataManager.RequestPlugin<IUserAccountData>(); if (m_Database == null) throw new Exception("Could not find a storage interface in the given module"); } public void FinishedStartup() { } #endregion #region IUserAccountService Members public virtual IUserAccountService InnerService { get { return this; } } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public UserAccount GetUserAccount(List<UUID> scopeIDs, string firstName, string lastName) { UserAccount account; if (m_cache.Get(firstName + " " + lastName, out account)) return AllScopeIDImpl.CheckScopeIDs(scopeIDs, account); object remoteValue = DoRemote(scopeIDs, firstName, lastName); if (remoteValue != null || m_doRemoteOnly) { UserAccount acc = (UserAccount)remoteValue; if (remoteValue != null) m_cache.Cache(acc.PrincipalID, acc); return acc; } UserAccount[] d; d = m_Database.Get(scopeIDs, new[] {"FirstName", "LastName"}, new[] {firstName, lastName}); if (d.Length < 1) return null; CacheAccount(d[0]); return d[0]; } public void CacheAccount(UserAccount account) { if ((account != null) && (account.UserLevel <= -1)) return; m_cache.Cache(account.PrincipalID, account); } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public UserAccount GetUserAccount(List<UUID> scopeIDs, string name) { UserAccount account; if (m_cache.Get(name, out account)) return AllScopeIDImpl.CheckScopeIDs(scopeIDs, account); object remoteValue = DoRemote(scopeIDs, name); if (remoteValue != null || m_doRemoteOnly) { UserAccount acc = (UserAccount)remoteValue; if (remoteValue != null) m_cache.Cache(acc.PrincipalID, acc); return acc; } UserAccount[] d; d = m_Database.Get(scopeIDs, new[] {"Name"}, new[] {name}); if (d.Length < 1) { string[] split = name.Split(' '); if (split.Length == 2) return GetUserAccount(scopeIDs, split[0], split[1]); return null; } CacheAccount(d[0]); return d[0]; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low, RenamedMethod="GetUserAccountUUID")] public UserAccount GetUserAccount(List<UUID> scopeIDs, UUID principalID) { UserAccount account; if (m_cache.Get(principalID, out account)) return AllScopeIDImpl.CheckScopeIDs(scopeIDs, account); object remoteValue = DoRemote(scopeIDs, principalID); if (remoteValue != null || m_doRemoteOnly) { UserAccount acc = (UserAccount)remoteValue; if (remoteValue != null) m_cache.Cache(principalID, acc); return acc; } UserAccount[] d; d = m_Database.Get(scopeIDs, new[] {"PrincipalID"}, new[] {principalID.ToString()}); if (d.Length < 1) { m_cache.Cache(principalID, null); return null; } CacheAccount(d[0]); return d[0]; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)] public bool StoreUserAccount(UserAccount data) { object remoteValue = DoRemote(data); if (remoteValue != null || m_doRemoteOnly) return remoteValue == null ? false : (bool)remoteValue; if (data.UserTitle == null) data.UserTitle = ""; m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("UpdateUserInformation", data.PrincipalID); return m_Database.Store(data); } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, string query) { object remoteValue = DoRemote(scopeIDs, query); if (remoteValue != null || m_doRemoteOnly) return (List<UserAccount>)remoteValue; UserAccount[] d = m_Database.GetUsers(scopeIDs, query); if (d == null) return new List<UserAccount>(); List<UserAccount> ret = new List<UserAccount>(d); return ret; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, string query, uint? start, uint? count) { object remoteValue = DoRemote(scopeIDs, query); if (remoteValue != null || m_doRemoteOnly) return (List<UserAccount>)remoteValue; UserAccount[] d = m_Database.GetUsers(scopeIDs, query, start, count); if (d == null) return new List<UserAccount>(); List<UserAccount> ret = new List<UserAccount>(d); return ret; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public List<UserAccount> GetUserAccounts(List<UUID> scopeIDs, int level, int flags) { object remoteValue = DoRemote(level, flags); if (remoteValue != null || m_doRemoteOnly) return (List<UserAccount>)remoteValue; UserAccount[] d = m_Database.GetUsers(scopeIDs, level, flags); if (d == null) return new List<UserAccount>(); List<UserAccount> ret = new List<UserAccount>(d); return ret; } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)] public uint NumberOfUserAccounts(List<UUID> scopeIDs, string query) { object remoteValue = DoRemote(scopeIDs, query); if (remoteValue != null || m_doRemoteOnly) return (uint)remoteValue; return m_Database.NumberOfUsers(scopeIDs, query); } public void CreateUser(string name, string password, string email) { CreateUser(UUID.Random(), UUID.Zero, name, password, email); } /// <summary> /// Create a user /// </summary> /// <param name = "firstName"></param> /// <param name = "lastName"></param> /// <param name = "password"></param> /// <param name = "email"></param> [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)] public string CreateUser(UUID userID, UUID scopeID, string name, string password, string email) { return CreateUser(new UserAccount(scopeID, userID, name, email), password); } /// <summary> /// Create a user /// </summary> /// <param name = "account"></param> [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)] public string CreateUser(UserAccount newAcc, string password) { object remoteValue = DoRemote(newAcc, password); if (remoteValue != null || m_doRemoteOnly) return remoteValue == null ? "" : remoteValue.ToString(); UserAccount account = GetUserAccount(null, newAcc.PrincipalID); UserAccount nameaccount = GetUserAccount(null, newAcc.Name); if (null == account && nameaccount == null) { if (StoreUserAccount(newAcc)) { bool success; if (m_AuthenticationService != null && password != "") { success = m_AuthenticationService.SetPasswordHashed(newAcc.PrincipalID, "UserAccount", password); if (!success) { MainConsole.Instance.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0}.", newAcc.Name); return "Unable to set password"; } } MainConsole.Instance.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} created successfully", newAcc.Name); //Cache it as well CacheAccount(newAcc); m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("CreateUserInformation", newAcc.PrincipalID); return ""; } else { MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: Account creation failed for account {0}", newAcc.Name); return "Unable to save account"; } } else { MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} already exists!", newAcc.Name); return "A user with the same name already exists"; } } [CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)] public void DeleteUser(UUID userID, string password, bool archiveInformation, bool wipeFromDatabase) { object remoteValue = DoRemote(userID, password, archiveInformation, wipeFromDatabase); if (remoteValue != null || m_doRemoteOnly) return; if (password != "" && m_AuthenticationService.Authenticate(userID, "UserAccount", password, 0) == "") return;//Not authed if (!m_Database.DeleteAccount(userID, archiveInformation)) { MainConsole.Instance.WarnFormat("Failed to remove the account for {0}, please check that the database is valid after this operation!", userID); return; } if(wipeFromDatabase) m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("DeleteUserInformation", userID); } #endregion #region Console commands protected void HandleSetPartner(string[] cmdParams) { string first = MainConsole.Instance.Prompt("First User's name"); string second = MainConsole.Instance.Prompt("Second User's name"); IProfileConnector profileConnector = Aurora.DataManager.DataManager.RequestPlugin<IProfileConnector>(); if (profileConnector != null) { IUserProfileInfo firstProfile = profileConnector.GetUserProfile(GetUserAccount(null, first).PrincipalID); IUserProfileInfo secondProfile = profileConnector.GetUserProfile(GetUserAccount(null, second).PrincipalID); firstProfile.Partner = secondProfile.PrincipalID; secondProfile.Partner = firstProfile.PrincipalID; profileConnector.UpdateUserProfile(firstProfile); profileConnector.UpdateUserProfile(secondProfile); MainConsole.Instance.Warn("Partner information updated. "); } } protected void HandleSetTitle(string[] cmdparams) { string firstName; string lastName; string title; firstName = cmdparams.Length < 5 ? MainConsole.Instance.Prompt("First name") : cmdparams[4]; lastName = cmdparams.Length < 6 ? MainConsole.Instance.Prompt("Last name") : cmdparams[5]; UserAccount account = GetUserAccount(null, firstName, lastName); if (account == null) { MainConsole.Instance.Info("No such user"); return; } title = cmdparams.Length < 7 ? MainConsole.Instance.Prompt("User Title") : Util.CombineParams(cmdparams, 6); account.UserTitle = title; Aurora.Framework.IProfileConnector profileConnector = Aurora.DataManager.DataManager.RequestPlugin<Aurora.Framework.IProfileConnector>(); if (profileConnector != null) { Aurora.Framework.IUserProfileInfo profile = profileConnector.GetUserProfile(account.PrincipalID); profile.MembershipGroup = title; profile.CustomType = title; profileConnector.UpdateUserProfile(profile); } bool success = StoreUserAccount(account); if (!success) MainConsole.Instance.InfoFormat("Unable to set user profile title for account {0} {1}.", firstName, lastName); else MainConsole.Instance.InfoFormat("User profile title set for user {0} {1} to {2}", firstName, lastName, title); } protected void HandleSetUserLevel(string[] cmdparams) { string firstName; string lastName; string rawLevel; int level; firstName = cmdparams.Length < 4 ? MainConsole.Instance.Prompt("First name") : cmdparams[3]; lastName = cmdparams.Length < 5 ? MainConsole.Instance.Prompt("Last name") : cmdparams[4]; UserAccount account = GetUserAccount(null, firstName, lastName); if (account == null) { MainConsole.Instance.Info("No such user"); return; } rawLevel = cmdparams.Length < 6 ? MainConsole.Instance.Prompt("User level") : cmdparams[5]; if (int.TryParse(rawLevel, out level) == false) { MainConsole.Instance.Info("Invalid user level"); return; } account.UserLevel = level; bool success = StoreUserAccount(account); if (!success) MainConsole.Instance.InfoFormat("Unable to set user level for account {0} {1}.", firstName, lastName); else MainConsole.Instance.InfoFormat("User level set for user {0} {1} to {2}", firstName, lastName, level); } protected void HandleShowAccount(string[] cmdparams) { if (cmdparams.Length != 4) { MainConsole.Instance.Output("Usage: show account <first-name> <last-name>"); return; } string firstName = cmdparams[2]; string lastName = cmdparams[3]; UserAccount ua = GetUserAccount(null, firstName, lastName); if (ua == null) { MainConsole.Instance.InfoFormat("No user named {0} {1}", firstName, lastName); return; } MainConsole.Instance.InfoFormat("Name: {0}", ua.Name); MainConsole.Instance.InfoFormat("ID: {0}", ua.PrincipalID); MainConsole.Instance.InfoFormat("Title: {0}", ua.UserTitle); MainConsole.Instance.InfoFormat("E-mail: {0}", ua.Email); MainConsole.Instance.InfoFormat("Created: {0}", Utils.UnixTimeToDateTime(ua.Created)); MainConsole.Instance.InfoFormat("Level: {0}", ua.UserLevel); MainConsole.Instance.InfoFormat("Flags: {0}", ua.UserFlags); } /// <summary> /// Handle the create user command from the console. /// </summary> /// <param name = "cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param> protected void HandleCreateUser(string[] cmdparams) { string name, password, email, uuid, scopeID; name = MainConsole.Instance.Prompt("Name", "Default User"); password = MainConsole.Instance.PasswordPrompt("Password"); email = MainConsole.Instance.Prompt("Email", ""); uuid = MainConsole.Instance.Prompt("UUID (Don't change unless you have a reason)", UUID.Random().ToString()); scopeID = MainConsole.Instance.Prompt("Scope (Don't change unless you know what this is)", UUID.Zero.ToString()); CreateUser(UUID.Parse(uuid), UUID.Parse(scopeID), name, Util.Md5Hash(password), email); } protected void HandleResetUserPassword(string[] cmdparams) { string name; string newPassword; name = MainConsole.Instance.Prompt("Name"); newPassword = MainConsole.Instance.PasswordPrompt("New password"); UserAccount account = GetUserAccount(null, name); if (account == null) MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: No such user"); bool success = false; if (m_AuthenticationService != null) success = m_AuthenticationService.SetPassword(account.PrincipalID, "UserAccount", newPassword); if (!success) MainConsole.Instance.ErrorFormat("[USER ACCOUNT SERVICE]: Unable to reset password for account {0}.", name); else MainConsole.Instance.InfoFormat("[USER ACCOUNT SERVICE]: Password reset for user {0}", name); } #endregion } }
NanaYngvarrdottir/Software-Testing
OpenSim/Services/UserAccountService/UserAccountService.cs
C#
bsd-3-clause
23,519
#requires -Version 3.0 #region Info <# Support: https://github.com/jhochwald/NETX/issues #> #endregion Info #region License <# Copyright (c) 2016, Quality Software Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. By using the Software, you agree to the License, Terms and Conditions above! #> <# This is a third-party Software! The developer of this Software is NOT sponsored by or affiliated with Microsoft Corp (MSFT) or any of its subsidiaries in any way The Software is not supported by Microsoft Corp (MSFT)! More about Quality Software Ltd. http://www.q-soft.co.uk #> #endregion License # Make Powershell more Uni* like function global:Reload-PesterModule { <# .SYNOPSIS Load Pester Module .DESCRIPTION Load the Pester PowerShell Module to the Global context. Pester is a Mockup, Unit Test and Function Test Module for PowerShell .NOTES Pester Module must be installed .LINK Pester: https://github.com/pester/Pester .LINK NET-Experts http://www.net-experts.net .LINK Support https://github.com/jhochwald/NETX/issues #> [CmdletBinding()] param () PROCESS { # Lets check if the Pester PowerShell Module is installed if (Get-Module -ListAvailable -Name Pester -ErrorAction SilentlyContinue -WarningAction SilentlyContinue) { try { #Make sure we remove the Pester Module (if loaded) Remove-Module -Name [P]ester -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue # Import the Pester PowerShell Module in the Global context Import-Module -Name [P]ester -DisableNameChecking -Force -Scope Global -ErrorAction Stop -WarningAction SilentlyContinue } catch { # Sorry, Pester PowerShell Module is not here!!! Write-Error -Message 'Error: Pester Module was not imported...' -ErrorAction Stop # Still here? Make sure we are done! break # Aw Snap! We are still here? Fix that the hard way... exit 1 } } else { # Sorry, Pester PowerShell Module is not here!!! Write-Warning -Message 'Pester Module is not installed! Go to https://github.com/pester/Pester to get it!' } } } # Set a compatibility Alias (Set-Alias -Name Load-Pester -Value Reload-PesterModule -Option AllScope -Scope Global -Force -Confirm:$False -ErrorAction SilentlyContinue -WarningAction SilentlyContinue) > $null 2>&1 3>&1 (Set-Alias -Name Load-Test -Value Reload-PesterModule -Option AllScope -Scope Global -Force -Confirm:$False -ErrorAction SilentlyContinue -WarningAction SilentlyContinue) > $null 2>&1 3>&1 # SIG # Begin signature block # MIIfOgYJKoZIhvcNAQcCoIIfKzCCHycCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUqXDHyrr+RThW83LO7t5NyBBT # gGGgghnLMIIEFDCCAvygAwIBAgILBAAAAAABL07hUtcwDQYJKoZIhvcNAQEFBQAw # VzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNV # BAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xMTA0 # MTMxMDAwMDBaFw0yODAxMjgxMjAwMDBaMFIxCzAJBgNVBAYTAkJFMRkwFwYDVQQK # ExBHbG9iYWxTaWduIG52LXNhMSgwJgYDVQQDEx9HbG9iYWxTaWduIFRpbWVzdGFt # cGluZyBDQSAtIEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlO9l # +LVXn6BTDTQG6wkft0cYasvwW+T/J6U00feJGr+esc0SQW5m1IGghYtkWkYvmaCN # d7HivFzdItdqZ9C76Mp03otPDbBS5ZBb60cO8eefnAuQZT4XljBFcm05oRc2yrmg # jBtPCBn2gTGtYRakYua0QJ7D/PuV9vu1LpWBmODvxevYAll4d/eq41JrUJEpxfz3 # zZNl0mBhIvIG+zLdFlH6Dv2KMPAXCae78wSuq5DnbN96qfTvxGInX2+ZbTh0qhGL # 2t/HFEzphbLswn1KJo/nVrqm4M+SU4B09APsaLJgvIQgAIMboe60dAXBKY5i0Eex # +vBTzBj5Ljv5cH60JQIDAQABo4HlMIHiMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB # Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBRG2D7/3OO+/4Pm9IWbsN1q1hSpwTBHBgNV # HSAEQDA+MDwGBFUdIAAwNDAyBggrBgEFBQcCARYmaHR0cHM6Ly93d3cuZ2xvYmFs # c2lnbi5jb20vcmVwb3NpdG9yeS8wMwYDVR0fBCwwKjAooCagJIYiaHR0cDovL2Ny # bC5nbG9iYWxzaWduLm5ldC9yb290LmNybDAfBgNVHSMEGDAWgBRge2YaRQ2XyolQ # L30EzTSo//z9SzANBgkqhkiG9w0BAQUFAAOCAQEATl5WkB5GtNlJMfO7FzkoG8IW # 3f1B3AkFBJtvsqKa1pkuQJkAVbXqP6UgdtOGNNQXzFU6x4Lu76i6vNgGnxVQ380W # e1I6AtcZGv2v8Hhc4EvFGN86JB7arLipWAQCBzDbsBJe/jG+8ARI9PBw+DpeVoPP # PfsNvPTF7ZedudTbpSeE4zibi6c1hkQgpDttpGoLoYP9KOva7yj2zIhd+wo7AKvg # IeviLzVsD440RZfroveZMzV+y5qKu0VN5z+fwtmK+mWybsd+Zf/okuEsMaL3sCc2 # SI8mbzvuTXYfecPlf5Y1vC0OzAGwjn//UYCAp5LUs0RGZIyHTxZjBzFLY7Df8zCC # BJ8wggOHoAMCAQICEhEh1pmnZJc+8fhCfukZzFNBFDANBgkqhkiG9w0BAQUFADBS # MQswCQYDVQQGEwJCRTEZMBcGA1UEChMQR2xvYmFsU2lnbiBudi1zYTEoMCYGA1UE # AxMfR2xvYmFsU2lnbiBUaW1lc3RhbXBpbmcgQ0EgLSBHMjAeFw0xNjA1MjQwMDAw # MDBaFw0yNzA2MjQwMDAwMDBaMGAxCzAJBgNVBAYTAlNHMR8wHQYDVQQKExZHTU8g # R2xvYmFsU2lnbiBQdGUgTHRkMTAwLgYDVQQDEydHbG9iYWxTaWduIFRTQSBmb3Ig # TVMgQXV0aGVudGljb2RlIC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK # AoIBAQCwF66i07YEMFYeWA+x7VWk1lTL2PZzOuxdXqsl/Tal+oTDYUDFRrVZUjtC # oi5fE2IQqVvmc9aSJbF9I+MGs4c6DkPw1wCJU6IRMVIobl1AcjzyCXenSZKX1GyQ # oHan/bjcs53yB2AsT1iYAGvTFVTg+t3/gCxfGKaY/9Sr7KFFWbIub2Jd4NkZrItX # nKgmK9kXpRDSRwgacCwzi39ogCq1oV1r3Y0CAikDqnw3u7spTj1Tk7Om+o/SWJMV # TLktq4CjoyX7r/cIZLB6RA9cENdfYTeqTmvT0lMlnYJz+iz5crCpGTkqUPqp0Dw6 # yuhb7/VfUfT5CtmXNd5qheYjBEKvAgMBAAGjggFfMIIBWzAOBgNVHQ8BAf8EBAMC # B4AwTAYDVR0gBEUwQzBBBgkrBgEEAaAyAR4wNDAyBggrBgEFBQcCARYmaHR0cHM6 # Ly93d3cuZ2xvYmFsc2lnbi5jb20vcmVwb3NpdG9yeS8wCQYDVR0TBAIwADAWBgNV # HSUBAf8EDDAKBggrBgEFBQcDCDBCBgNVHR8EOzA5MDegNaAzhjFodHRwOi8vY3Js # Lmdsb2JhbHNpZ24uY29tL2dzL2dzdGltZXN0YW1waW5nZzIuY3JsMFQGCCsGAQUF # BwEBBEgwRjBEBggrBgEFBQcwAoY4aHR0cDovL3NlY3VyZS5nbG9iYWxzaWduLmNv # bS9jYWNlcnQvZ3N0aW1lc3RhbXBpbmdnMi5jcnQwHQYDVR0OBBYEFNSihEo4Whh/ # uk8wUL2d1XqH1gn3MB8GA1UdIwQYMBaAFEbYPv/c477/g+b0hZuw3WrWFKnBMA0G # CSqGSIb3DQEBBQUAA4IBAQCPqRqRbQSmNyAOg5beI9Nrbh9u3WQ9aCEitfhHNmmO # 4aVFxySiIrcpCcxUWq7GvM1jjrM9UEjltMyuzZKNniiLE0oRqr2j79OyNvy0oXK/ # bZdjeYxEvHAvfvO83YJTqxr26/ocl7y2N5ykHDC8q7wtRzbfkiAD6HHGWPZ1BZo0 # 8AtZWoJENKqA5C+E9kddlsm2ysqdt6a65FDT1De4uiAO0NOSKlvEWbuhbds8zkSd # wTgqreONvc0JdxoQvmcKAjZkiLmzGybu555gxEaovGEzbM9OuZy5avCfN/61PU+a # 003/3iCOTpem/Z8JvE3KGHbJsE2FUPKA0h0G9VgEB7EYMIIFTDCCBDSgAwIBAgIQ # FtT3Ux2bGCdP8iZzNFGAXDANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJHQjEb # MBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRow # GAYDVQQKExFDT01PRE8gQ0EgTGltaXRlZDEjMCEGA1UEAxMaQ09NT0RPIFJTQSBD # b2RlIFNpZ25pbmcgQ0EwHhcNMTUwNzE3MDAwMDAwWhcNMTgwNzE2MjM1OTU5WjCB # kDELMAkGA1UEBhMCREUxDjAMBgNVBBEMBTM1NTc2MQ8wDQYDVQQIDAZIZXNzZW4x # EDAOBgNVBAcMB0xpbWJ1cmcxGDAWBgNVBAkMD0JhaG5ob2ZzcGxhdHogMTEZMBcG # A1UECgwQS3JlYXRpdlNpZ24gR21iSDEZMBcGA1UEAwwQS3JlYXRpdlNpZ24gR21i # SDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK8jDmF0TO09qJndJ9eG # Fqra1lf14NDhM8wIT8cFcZ/AX2XzrE6zb/8kE5sL4/dMhuTOp+SMt0tI/SON6BY3 # 208v/NlDI7fozAqHfmvPhLX6p/TtDkmSH1sD8AIyrTH9b27wDNX4rC914Ka4EBI8 # sGtZwZOQkwQdlV6gCBmadar+7YkVhAbIIkSazE9yyRTuffidmtHV49DHPr+ql4ji # NJ/K27ZFZbwM6kGBlDBBSgLUKvufMY+XPUukpzdCaA0UzygGUdDfgy0htSSp8MR9 # Rnq4WML0t/fT0IZvmrxCrh7NXkQXACk2xtnkq0bXUIC6H0Zolnfl4fanvVYyvD88 # qIECAwEAAaOCAbIwggGuMB8GA1UdIwQYMBaAFCmRYP+KTfrr+aZquM/55ku9Sc4S # MB0GA1UdDgQWBBSeVG4/9UvVjmv8STy4f7kGHucShjAOBgNVHQ8BAf8EBAMCB4Aw # DAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhCAQEE # BAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcCARYd # aHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQwYDVR0fBDwwOjA4oDagNIYy # aHR0cDovL2NybC5jb21vZG9jYS5jb20vQ09NT0RPUlNBQ29kZVNpZ25pbmdDQS5j # cmwwdAYIKwYBBQUHAQEEaDBmMD4GCCsGAQUFBzAChjJodHRwOi8vY3J0LmNvbW9k # b2NhLmNvbS9DT01PRE9SU0FDb2RlU2lnbmluZ0NBLmNydDAkBggrBgEFBQcwAYYY # aHR0cDovL29jc3AuY29tb2RvY2EuY29tMCMGA1UdEQQcMBqBGGhvY2h3YWxkQGty # ZWF0aXZzaWduLm5ldDANBgkqhkiG9w0BAQsFAAOCAQEASSZkxKo3EyEk/qW0ZCs7 # CDDHKTx3UcqExigsaY0DRo9fbWgqWynItsqdwFkuQYJxzknqm2JMvwIK6BtfWc64 # WZhy0BtI3S3hxzYHxDjVDBLBy91kj/mddPjen60W+L66oNEXiBuIsOcJ9e7tH6Vn # 9eFEUjuq5esoJM6FV+MIKv/jPFWMp5B6EtX4LDHEpYpLRVQnuxoc38mmd+NfjcD2 # /o/81bu6LmBFegHAaGDpThGf8Hk3NVy0GcpQ3trqmH6e3Cpm8Ut5UkoSONZdkYWw # rzkmzFgJyoM2rnTMTh4ficxBQpB7Ikv4VEnrHRReihZ0zwN+HkXO1XEnd3hm+08j # LzCCBdgwggPAoAMCAQICEEyq+crbY2/gH/dO2FsDhp0wDQYJKoZIhvcNAQEMBQAw # gYUxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO # BgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMSswKQYD # VQQDEyJDT01PRE8gUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEwMDEx # OTAwMDAwMFoXDTM4MDExODIzNTk1OVowgYUxCzAJBgNVBAYTAkdCMRswGQYDVQQI # ExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAOBgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoT # EUNPTU9ETyBDQSBMaW1pdGVkMSswKQYDVQQDEyJDT01PRE8gUlNBIENlcnRpZmlj # YXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA # kehUktIKVrGsDSTdxc9EZ3SZKzejfSNwAHG8U9/E+ioSj0t/EFa9n3Byt2F/yUsP # F6c947AEYe7/EZfH9IY+Cvo+XPmT5jR62RRr55yzhaCCenavcZDX7P0N+pxs+t+w # gvQUfvm+xKYvT3+Zf7X8Z0NyvQwA1onrayzT7Y+YHBSrfuXjbvzYqOSSJNpDa2K4 # Vf3qwbxstovzDo2a5JtsaZn4eEgwRdWt4Q08RWD8MpZRJ7xnw8outmvqRsfHIKCx # H2XeSAi6pE6p8oNGN4Tr6MyBSENnTnIqm1y9TBsoilwie7SrmNnu4FGDwwlGTm0+ # mfqVF9p8M1dBPI1R7Qu2XK8sYxrfV8g/vOldxJuvRZnio1oktLqpVj3Pb6r/SVi+ # 8Kj/9Lit6Tf7urj0Czr56ENCHonYhMsT8dm74YlguIwoVqwUHZwK53Hrzw7dPamW # oUi9PPevtQ0iTMARgexWO/bTouJbt7IEIlKVgJNp6I5MZfGRAy1wdALqi2cVKWlS # ArvX31BqVUa/oKMoYX9w0MOiqiwhqkfOKJwGRXa/ghgntNWutMtQ5mv0TIZxMOmm # 3xaG4Nj/QN370EKIf6MzOi5cHkERgWPOGHFrK+ymircxXDpqR+DDeVnWIBqv8mqY # qnK8V0rSS527EPywTEHl7R09XiidnMy/s1Hap0flhFMCAwEAAaNCMEAwHQYDVR0O # BBYEFLuvfgI9+qbxPISOre44mOzZMjLUMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB # Af8EBTADAQH/MA0GCSqGSIb3DQEBDAUAA4ICAQAK8dVGhLeuUbtssk1BFACTTJzL # 5cBUz6AljgL5/bCiDfUgmDwTLaxWorDWfhGS6S66ni6acrG9GURsYTWimrQWEmla # jOHXPqQa6C8D9K5hHRAbKqSLesX+BabhwNbI/p6ujyu6PZn42HMJWEZuppz01yfT # ldo3g3Ic03PgokeZAzhd1Ul5ACkcx+ybIBwHJGlXeLI5/DqEoLWcfI2/LpNiJ7c5 # 2hcYrr08CWj/hJs81dYLA+NXnhT30etPyL2HI7e2SUN5hVy665ILocboaKhMFrEa # mQroUyySu6EJGHUMZah7yyO3GsIohcMb/9ArYu+kewmRmGeMFAHNaAZqYyF1A4CI # im6BxoXyqaQt5/SlJBBHg8rN9I15WLEGm+caKtmdAdeUfe0DSsrw2+ipAT71VpnJ # Ho5JPbvlCbngT0mSPRaCQMzMWcbmOu0SLmk8bJWx/aode3+Gvh4OMkb7+xOPdX9M # i0tGY/4ANEBwwcO5od2mcOIEs0G86YCR6mSceuEiA6mcbm8OZU9sh4de826g+XWl # m0DoU7InnUq5wHchjf+H8t68jO8X37dJC9HybjALGg5Odu0R/PXpVrJ9v8dtCpOM # pdDAth2+Ok6UotdubAvCinz6IPPE5OXNDajLkZKxfIXstRRpZg6C583OyC2mUX8h # wTVThQZKXZ+tuxtfdDCCBeAwggPIoAMCAQICEC58h8wOk0pS/pT9HLfNNK8wDQYJ # KoZIhvcNAQEMBQAwgYUxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1h # bmNoZXN0ZXIxEDAOBgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBM # aW1pdGVkMSswKQYDVQQDEyJDT01PRE8gUlNBIENlcnRpZmljYXRpb24gQXV0aG9y # aXR5MB4XDTEzMDUwOTAwMDAwMFoXDTI4MDUwODIzNTk1OVowfTELMAkGA1UEBhMC # R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9y # ZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxIzAhBgNVBAMTGkNPTU9ETyBS # U0EgQ29kZSBTaWduaW5nIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC # AQEAppiQY3eRNH+K0d3pZzER68we/TEds7liVz+TvFvjnx4kMhEna7xRkafPnp4l # s1+BqBgPHR4gMA77YXuGCbPj/aJonRwsnb9y4+R1oOU1I47Jiu4aDGTH2EKhe7VS # A0s6sI4jS0tj4CKUN3vVeZAKFBhRLOb+wRLwHD9hYQqMotz2wzCqzSgYdUjBeVoI # zbuMVYz31HaQOjNGUHOYXPSFSmsPgN1e1r39qS/AJfX5eNeNXxDCRFU8kDwxRstw # rgepCuOvwQFvkBoj4l8428YIXUezg0HwLgA3FLkSqnmSUs2HD3vYYimkfjC9G7WM # crRI8uPoIfleTGJ5iwIGn3/VCwIDAQABo4IBUTCCAU0wHwYDVR0jBBgwFoAUu69+ # Aj36pvE8hI6t7jiY7NkyMtQwHQYDVR0OBBYEFCmRYP+KTfrr+aZquM/55ku9Sc4S # MA4GA1UdDwEB/wQEAwIBhjASBgNVHRMBAf8ECDAGAQH/AgEAMBMGA1UdJQQMMAoG # CCsGAQUFBwMDMBEGA1UdIAQKMAgwBgYEVR0gADBMBgNVHR8ERTBDMEGgP6A9hjto # dHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9SU0FDZXJ0aWZpY2F0aW9uQXV0 # aG9yaXR5LmNybDBxBggrBgEFBQcBAQRlMGMwOwYIKwYBBQUHMAKGL2h0dHA6Ly9j # cnQuY29tb2RvY2EuY29tL0NPTU9ET1JTQUFkZFRydXN0Q0EuY3J0MCQGCCsGAQUF # BzABhhhodHRwOi8vb2NzcC5jb21vZG9jYS5jb20wDQYJKoZIhvcNAQEMBQADggIB # AAI/AjnD7vjKO4neDG1NsfFOkk+vwjgsBMzFYxGrCWOvq6LXAj/MbxnDPdYaCJT/ # JdipiKcrEBrgm7EHIhpRHDrU4ekJv+YkdK8eexYxbiPvVFEtUgLidQgFTPG3UeFR # AMaH9mzuEER2V2rx31hrIapJ1Hw3Tr3/tnVUQBg2V2cRzU8C5P7z2vx1F9vst/dl # CSNJH0NXg+p+IHdhyE3yu2VNqPeFRQevemknZZApQIvfezpROYyoH3B5rW1CIKLP # DGwDjEzNcweU51qOOgS6oqF8H8tjOhWn1BUbp1JHMqn0v2RH0aofU04yMHPCb7d4 # gp1c/0a7ayIdiAv4G6o0pvyM9d1/ZYyMMVcx0DbsR6HPy4uo7xwYWMUGd8pLm1Gv # TAhKeo/io1Lijo7MJuSy2OU4wqjtxoGcNWupWGFKCpe0S0K2VZ2+medwbVn4bSoM # fxlgXwyaiGwwrFIJkBYb/yud29AgyonqKH4yjhnfe0gzHtdl+K7J+IMUk3Z9ZNCO # zr41ff9yMU2fnr0ebC+ojwwGUPuMJ7N2yfTm18M04oyHIYZh/r9VdOEhdwMKaGy7 # 5Mmp5s9ZJet87EUOeWZo6CLNuO+YhU2WETwJitB/vCgoE/tqylSNklzNwmWYBp7O # SFvUtTeTRkF8B93P+kPvumdh/31J4LswfVyA4+YWOUunMYIE2TCCBNUCAQEwgZEw # fTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G # A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxIzAhBgNV # BAMTGkNPTU9ETyBSU0EgQ29kZSBTaWduaW5nIENBAhAW1PdTHZsYJ0/yJnM0UYBc # MAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3AgEMMQowCKACgAChAoAAMBkGCSqGSIb3 # DQEJAzEMBgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEV # MCMGCSqGSIb3DQEJBDEWBBQgqfiFhI79dYvrqEsZFlV/MucCDTANBgkqhkiG9w0B # AQEFAASCAQANqXbwkxo5IIi6DObISgW8t/FO69wP/DjJmXhg5eB3m0wGfxkiLKpJ # ykQuQn1lNYlgpMmr8VDwI2wRcVVj2PUlh5Oyx5fJGetvYUmF+vPlBS693My6W4SR # 6eAyWLuXiy3ecN9hzF+JsEjqulJ4kHY+kLDafaSSFmGGrlk0yXRwtQgTG5cHm9S0 # zpi4h1zJcFH9Ibsa7nCo4DAbEcv4hgZ2ncBMRUhqt2Qf6kIanEJM+cTq+kNloUPc # w95RLk9bi5ZEovK5BuqmqlChOV9tAb0G3tXdJZDKy7luAJtz8GwVcPGw+2OEzgzt # +e/JnXyqHrDRIRtePjqoZQGZOoTbSqWVoYICojCCAp4GCSqGSIb3DQEJBjGCAo8w # ggKLAgEBMGgwUjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt # c2ExKDAmBgNVBAMTH0dsb2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gRzICEhEh # 1pmnZJc+8fhCfukZzFNBFDAJBgUrDgMCGgUAoIH9MBgGCSqGSIb3DQEJAzELBgkq # hkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE2MTAxMjEzMTM0NlowIwYJKoZIhvcN # AQkEMRYEFBZ2rY3HXDSfKjX8uo9W6NA895ePMIGdBgsqhkiG9w0BCRACDDGBjTCB # ijCBhzCBhAQUY7gvq2H1g5CWlQULACScUCkz7HkwbDBWpFQwUjELMAkGA1UEBhMC # QkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExKDAmBgNVBAMTH0dsb2JhbFNp # Z24gVGltZXN0YW1waW5nIENBIC0gRzICEhEh1pmnZJc+8fhCfukZzFNBFDANBgkq # hkiG9w0BAQEFAASCAQBOHCPe26mvqCRa0oC9iSuvePdNtsAAzPZE3hgHtCix7gNq # r3vfrXsH9vEaqc6xRLd88XOuOJbfPizb7Gtc18UFJD0v1R0JekGMrlcTTIwkMm7u # DKLTyu5+uctpvk6oqgEzwIzs0Dzx6XRF1GOhDUO6EmIaHDO9avODrVFn0BuredSn # DE7PFKDycV0HzUNccCfehpfkwGlYiXwzfgoiHIMIdzqC6DkQZkZka2x5fJJ/3FDZ # K7ByZgHqsfqtUjrRdTT8OwR2ILQk0gdYGKXf4N3y8O/sX4IGpzJtlqCNtWGwKsTn # LQ9UOVwgelsYeU6XJ0Elc844F+1OOtaTQuuBWxNV # SIG # End signature block
jhochwald/NETX
Profile/functions/LoadTest.ps1
PowerShell
bsd-3-clause
15,211
from django.shortcuts import redirect from django.template.response import TemplateResponse from ..forms import AnonymousUserShippingForm, ShippingAddressesForm from ...userprofile.forms import get_address_form from ...userprofile.models import Address from ...teamstore.utils import get_team def anonymous_user_shipping_address_view(request, checkout): team = get_team(request.session['team']) if team.group_shipping: address_form, preview = get_address_form( request.POST or None, country_code=request.country.code, autocomplete_type='shipping', initial={'country': request.country.code}, instance=team.shipping_address) else: address_form, preview = get_address_form( request.POST or None, country_code=request.country.code, autocomplete_type='shipping', initial={'country': request.country.code}, instance=checkout.shipping_address) user_form = AnonymousUserShippingForm( not preview and request.POST or None, initial={'email': checkout.email} if not preview else request.POST.dict()) if team.group_shipping and user_form.is_valid(): checkout.shipping_address = team.shipping_address checkout.email = user_form.cleaned_data['email'] return redirect('checkout:shipping-method') elif all([user_form.is_valid(), address_form.is_valid()]): checkout.shipping_address = address_form.instance checkout.email = user_form.cleaned_data['email'] return redirect('checkout:shipping-method') return TemplateResponse( request, 'checkout/shipping_address.html', context={ 'address_form': address_form, 'user_form': user_form, 'group_shipping': team.group_shipping, 'checkout': checkout}) def user_shipping_address_view(request, checkout): data = request.POST or None additional_addresses = request.user.addresses.all() checkout.email = request.user.email shipping_address = checkout.shipping_address if shipping_address is not None and shipping_address.id: address_form, preview = get_address_form( data, country_code=request.country.code, initial={'country': request.country}) addresses_form = ShippingAddressesForm( data, additional_addresses=additional_addresses, initial={'address': shipping_address.id}) elif shipping_address: address_form, preview = get_address_form( data, country_code=shipping_address.country.code, instance=shipping_address) addresses_form = ShippingAddressesForm( data, additional_addresses=additional_addresses) else: address_form, preview = get_address_form( data, initial={'country': request.country}, country_code=request.country.code) addresses_form = ShippingAddressesForm( data, additional_addresses=additional_addresses) if addresses_form.is_valid() and not preview: if addresses_form.cleaned_data['address'] != ShippingAddressesForm.NEW_ADDRESS: address_id = addresses_form.cleaned_data['address'] checkout.shipping_address = Address.objects.get(id=address_id) return redirect('checkout:shipping-method') elif address_form.is_valid(): checkout.shipping_address = address_form.instance return redirect('checkout:shipping-method') return TemplateResponse( request, 'checkout/shipping_address.html', context={ 'address_form': address_form, 'user_form': addresses_form, 'checkout': checkout, 'additional_addresses': additional_addresses})
jonathanmeier5/teamstore
saleor/checkout/views/shipping.py
Python
bsd-3-clause
3,737
// // https://github.com/NServiceKit/NServiceKit.Text // NServiceKit.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Linq; #if WINDOWS_PHONE && !WP8 using NServiceKit.Text.WP; #endif namespace NServiceKit.Text.Common { /// <summary>Collection of deserializes.</summary> /// <typeparam name="TSerializer">Type of the serializer.</typeparam> internal static class DeserializeCollection<TSerializer> where TSerializer : ITypeSerializer { /// <summary>The serializer.</summary> private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); /// <summary>Gets parse method.</summary> /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or /// illegal values.</exception> /// <param name="type">The type.</param> /// <returns>The parse method.</returns> public static ParseStringDelegate GetParseMethod(Type type) { var collectionInterface = type.GetTypeWithGenericInterfaceOf(typeof(ICollection<>)); if (collectionInterface == null) throw new ArgumentException(string.Format("Type {0} is not of type ICollection<>", type.FullName)); //optimized access for regularly used types if (type.HasInterface(typeof(ICollection<string>))) return value => ParseStringCollection(value, type); if (type.HasInterface(typeof(ICollection<int>))) return value => ParseIntCollection(value, type); var elementType = collectionInterface.GenericTypeArguments()[0]; var supportedTypeParseMethod = Serializer.GetParseFn(elementType); if (supportedTypeParseMethod != null) { var createCollectionType = type.HasAnyTypeDefinitionsOf(typeof(ICollection<>)) ? null : type; return value => ParseCollectionType(value, createCollectionType, elementType, supportedTypeParseMethod); } return null; } /// <summary>Parse string collection.</summary> /// <param name="value"> The value.</param> /// <param name="createType">Type of the create.</param> /// <returns>A list of.</returns> public static ICollection<string> ParseStringCollection(string value, Type createType) { var items = DeserializeArrayWithElements<string, TSerializer>.ParseGenericArray(value, Serializer.ParseString); return CollectionExtensions.CreateAndPopulate(createType, items); } /// <summary>Parse int collection.</summary> /// <param name="value"> The value.</param> /// <param name="createType">Type of the create.</param> /// <returns>A list of.</returns> public static ICollection<int> ParseIntCollection(string value, Type createType) { var items = DeserializeArrayWithElements<int, TSerializer>.ParseGenericArray(value, x => int.Parse(x)); return CollectionExtensions.CreateAndPopulate(createType, items); } /// <summary>Parse collection.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="value"> The value.</param> /// <param name="createType">Type of the create.</param> /// <param name="parseFn"> The parse function.</param> /// <returns>A list of.</returns> public static ICollection<T> ParseCollection<T>(string value, Type createType, ParseStringDelegate parseFn) { if (value == null) return null; var items = DeserializeArrayWithElements<T, TSerializer>.ParseGenericArray(value, parseFn); return CollectionExtensions.CreateAndPopulate(createType, items); } /// <summary>The parse delegate cache.</summary> private static Dictionary<Type, ParseCollectionDelegate> ParseDelegateCache = new Dictionary<Type, ParseCollectionDelegate>(); /// <summary>Parse collection delegate.</summary> /// <param name="value"> The value.</param> /// <param name="createType">Type of the create.</param> /// <param name="parseFn"> The parse function.</param> /// <returns>An object.</returns> private delegate object ParseCollectionDelegate(string value, Type createType, ParseStringDelegate parseFn); /// <summary>Parse collection type.</summary> /// <param name="value"> The value.</param> /// <param name="createType"> Type of the create.</param> /// <param name="elementType">Type of the element.</param> /// <param name="parseFn"> The parse function.</param> /// <returns>An object.</returns> public static object ParseCollectionType(string value, Type createType, Type elementType, ParseStringDelegate parseFn) { ParseCollectionDelegate parseDelegate; if (ParseDelegateCache.TryGetValue(elementType, out parseDelegate)) return parseDelegate(value, createType, parseFn); var mi = typeof(DeserializeCollection<TSerializer>).GetPublicStaticMethod("ParseCollection"); var genericMi = mi.MakeGenericMethod(new[] { elementType }); parseDelegate = (ParseCollectionDelegate)genericMi.MakeDelegate(typeof(ParseCollectionDelegate)); Dictionary<Type, ParseCollectionDelegate> snapshot, newCache; do { snapshot = ParseDelegateCache; newCache = new Dictionary<Type, ParseCollectionDelegate>(ParseDelegateCache); newCache[elementType] = parseDelegate; } while (!ReferenceEquals( Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot)); return parseDelegate(value, createType, parseFn); } } }
NServiceKit/NServiceKit.Text
src/NServiceKit.Text/Common/DeserializeCollection.cs
C#
bsd-3-clause
6,238
d3 = {version: "2.7.5"}; // semver
alex/d3
src/core/core.js
JavaScript
bsd-3-clause
35
// Autogenerated from isource/library/elements.i package ideal.library.elements; public interface deeply_immutable_dictionary<key_type, value_type> extends deeply_immutable_collection<dictionary.entry<key_type, value_type>>, immutable_dictionary<key_type, value_type> { }
gnanam336/ideal
bootstrapped/ideal/library/elements/deeply_immutable_dictionary.java
Java
bsd-3-clause
274
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <gtest/gtest.h> #include <moveit/planning_scene/planning_scene.h> #include <urdf_parser/urdf_parser.h> #include <fstream> #include <boost/filesystem/path.hpp> #include <moveit_resources/config.h> // This function needs to return void so the gtest FAIL() macro inside // it works right. void loadRobotModel(urdf::ModelInterfaceSharedPtr& robot_model_out) { boost::filesystem::path res_path(MOVEIT_TEST_RESOURCES_DIR); std::string xml_string; std::fstream xml_file((res_path / "pr2_description/urdf/robot.xml").string().c_str(), std::fstream::in); EXPECT_TRUE(xml_file.is_open()); while (xml_file.good()) { std::string line; std::getline(xml_file, line); xml_string += (line + "\n"); } xml_file.close(); robot_model_out = urdf::parseURDF(xml_string); } TEST(PlanningScene, LoadRestore) { urdf::ModelInterfaceSharedPtr urdf_model; loadRobotModel(urdf_model); srdf::ModelSharedPtr srdf_model(new srdf::Model()); planning_scene::PlanningScene ps(urdf_model, srdf_model); moveit_msgs::PlanningScene ps_msg; ps.getPlanningSceneMsg(ps_msg); ps.setPlanningSceneMsg(ps_msg); } TEST(PlanningScene, LoadRestoreDiff) { urdf::ModelInterfaceSharedPtr urdf_model; loadRobotModel(urdf_model); srdf::ModelSharedPtr srdf_model(new srdf::Model()); planning_scene::PlanningScenePtr ps(new planning_scene::PlanningScene(urdf_model, srdf_model)); collision_detection::World& world = *ps->getWorldNonConst(); Eigen::Affine3d id = Eigen::Affine3d::Identity(); world.addToObject("sphere", shapes::ShapeConstPtr(new shapes::Sphere(0.4)), id); moveit_msgs::PlanningScene ps_msg; ps_msg.robot_state.is_diff = true; EXPECT_TRUE(planning_scene::PlanningScene::isEmpty(ps_msg)); ps->getPlanningSceneMsg(ps_msg); ps->setPlanningSceneMsg(ps_msg); EXPECT_FALSE(planning_scene::PlanningScene::isEmpty(ps_msg)); EXPECT_TRUE(world.hasObject("sphere")); planning_scene::PlanningScenePtr next = ps->diff(); EXPECT_TRUE(next->getWorld()->hasObject("sphere")); next->getWorldNonConst()->addToObject("sphere2", shapes::ShapeConstPtr(new shapes::Sphere(0.5)), id); EXPECT_EQ(next->getWorld()->size(), 2); EXPECT_EQ(ps->getWorld()->size(), 1); next->getPlanningSceneDiffMsg(ps_msg); EXPECT_EQ(ps_msg.world.collision_objects.size(), 1); next->decoupleParent(); moveit_msgs::PlanningScene ps_msg2; next->getPlanningSceneDiffMsg(ps_msg2); EXPECT_EQ(ps_msg2.world.collision_objects.size(), 0); next->getPlanningSceneMsg(ps_msg); EXPECT_EQ(ps_msg.world.collision_objects.size(), 2); ps->setPlanningSceneMsg(ps_msg); EXPECT_EQ(ps->getWorld()->size(), 2); } TEST(PlanningScene, MakeAttachedDiff) { srdf::ModelSharedPtr srdf_model(new srdf::Model()); urdf::ModelInterfaceSharedPtr urdf_model; loadRobotModel(urdf_model); planning_scene::PlanningScenePtr ps(new planning_scene::PlanningScene(urdf_model, srdf_model)); collision_detection::World& world = *ps->getWorldNonConst(); Eigen::Affine3d id = Eigen::Affine3d::Identity(); world.addToObject("sphere", shapes::ShapeConstPtr(new shapes::Sphere(0.4)), id); planning_scene::PlanningScenePtr attached_object_diff_scene = ps->diff(); moveit_msgs::AttachedCollisionObject att_obj; att_obj.link_name = "r_wrist_roll_link"; att_obj.object.operation = moveit_msgs::CollisionObject::ADD; att_obj.object.id = "sphere"; collision_detection::CollisionRequest req; collision_detection::CollisionResult res; attached_object_diff_scene->processAttachedCollisionObjectMsg(att_obj); attached_object_diff_scene->checkCollision(req, res); ps->checkCollision(req, res); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
v4hn/moveit
moveit_core/planning_scene/test/test_planning_scene.cpp
C++
bsd-3-clause
5,540
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_environment_execlp_74a.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-74a.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: environment Read input from an environment variable * GoodSource: Fixed string * Sinks: execlp * BadSink : execute command with wexeclp * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files * * */ #include "std_testcase.h" #include <map> #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT L"cmd.exe" #define COMMAND_ARG1 L"/c" #define COMMAND_ARG2 L"dir " #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH L"/bin/sh" #define COMMAND_INT L"sh" #define COMMAND_ARG1 L"-c" #define COMMAND_ARG2 L"ls " #define COMMAND_ARG3 data #endif #define ENV_VARIABLE L"ADD" #ifdef _WIN32 #define GETENV _wgetenv #else #define GETENV getenv #endif using namespace std; namespace CWE78_OS_Command_Injection__wchar_t_environment_execlp_74 { #ifndef OMITBAD /* bad function declaration */ void badSink(map<int, wchar_t *> dataMap); void bad() { wchar_t * data; map<int, wchar_t *> dataMap; wchar_t dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; { /* Append input from an environment variable to data */ size_t dataLen = wcslen(data); wchar_t * environment = GETENV(ENV_VARIABLE); /* If there is data in the environment variable */ if (environment != NULL) { /* POTENTIAL FLAW: Read data from an environment variable */ wcsncat(data+dataLen, environment, 100-dataLen-1); } } /* Put data in a map */ dataMap[0] = data; dataMap[1] = data; dataMap[2] = data; badSink(dataMap); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(map<int, wchar_t *> dataMap); static void goodG2B() { wchar_t * data; map<int, wchar_t *> dataMap; wchar_t dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); /* Put data in a map */ dataMap[0] = data; dataMap[1] = data; dataMap[2] = data; goodG2BSink(dataMap); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE78_OS_Command_Injection__wchar_t_environment_execlp_74; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s06/CWE78_OS_Command_Injection__wchar_t_environment_execlp_74a.cpp
C++
bsd-3-clause
3,495
<?php namespace LazyRecord\Schema; use ArrayAccess; use IteratorAggregate; use SQLBuilder\Universal\Syntax\Conditions; use LazyRecord\BaseCollection; use LazyRecord\BaseModel; use LogicException; class Relationship implements IteratorAggregate, ArrayAccess { const HAS_MANY = 1; const HAS_ONE = 2; const BELONGS_TO = 3; const MANY_TO_MANY = 4; /** * @var array The stashed data */ public $data = array(); /** * @var string The accessor name */ public $accessor; /** * @var Conditions The SQLBuilder Condition Syntax Object */ public $where; public $orderBy = array(); public function __construct($accessor, array $data = array()) { $this->accessor = $accessor; $this->data = $data; } public function newForeignSchema() { $class = $this->data['foreign_schema']; return new $class; } public function newForeignModel() { $schema = $this->newForeignSchema(); $modelClass = $schema->getModelClass(); return new $modelClass(); } public function newForeignCollection() { $schema = $this->newForeignSchema(); $collectionClass = $schema->getCollectionClass(); return new $collectionClass; } /** * Resolve the junction relationship to retrieve foreign collection of the foreign collection. * * This method is only for many-to-many relationship object. * * @return LazyRecord\BaseCollection The foreign foreign collection. */ public function newForeignForeignCollection($junctionRelation) { $junctionSchema = new $junctionRelation['foreign_schema']; $foreignRelation = $junctionSchema->getRelation( $this['relation_foreign'] ); $collection = $foreignRelation->newForeignCollection(); $this->applyFilter($collection); // apply this filter to the foreign collection. return $collection; } public function isType($type) { return $this->data['type'] === $type; } public function isManyToMany() { return $this->data['type'] === Relationship::MANY_TO_MANY; } public function isOneToMany() { return $this->data['type'] === Relationship::HAS_MANY; } public function isHasMany() { return $this->data['type'] === Relationship::HAS_MANY; } public function applyFilter(BaseCollection & $collection) { if ( isset($this->data['filter']) ) { $collection = call_user_func_array( $this->data['filter'] , array($collection) ); } } public function applyWhere(BaseCollection & $collection) { if ($this->where) { $collection->setWhere($this->where); } } public function applyOrder(BaseCollection & $collection) { if (isset($this->data['orderBy']) && $this->data['orderBy']) { var_dump( $this->data['orderBy'] ); foreach($this->data['orderBy'] as $o ) { $collection->orderBy($o[0] , $o[1]); } } } public function getForeignCollection() { $collection = $this->newForeignCollection(); $this->applyFilter($collection); $this->applyWhere($collection); $this->applyOrder($collection); return $collection; } /** * Provide dynamic cascading accessors * * $relationship->foreign_schema('something') * $relationship->view('something') */ public function __call($m, $as) { $this->data[ $m ] = $as[0]; return $this; } /** * Define filter for collection * * @param callback $filter filter callback. */ public function filter($filter) { $this->data['filter'] = $filter; return $this; } public function order() { throw new LogicException("order(column, ordering) is now deprecated, please use orderBy(column, ordering)"); } /** * Save order on the relationship. * * @param string $column * @param string $ordering */ public function orderBy($column, $ordering) { $this->orderBy[] = array($column ,$ordering); return $this; } public function where($expr = NULL , array $args = array()) { if (!$this->where) { $this->where = new Conditions; } if ($expr) { if (is_string($expr)) { $this->where->appendExpr($expr, $args); } else if (is_array($expr)) { foreach($expr as $key => $val) { $this->where->equal($key, $val); } } else { throw new InvalidArgumentException("Unsupported argument type of 'where' method."); } } return $this->where; } /** * To support foreach operation. */ public function getIterator() { return new ArrayIterator($this->data); } public function offsetSet($name,$value) { $this->data[$name] = $value; } public function offsetExists($name) { return isset($this->data[$name]); } public function offsetGet($name) { return $this->data[$name]; } public function offsetUnset($name) { unset($this->data[$name]); } /** * To support var_export */ public static function __set_state(array $data) { $r = new self($data['accessor'], $data['data']); if (isset($data['where'])) { $r->where = $data['where']; } if (isset($data['orderBy'])) { $r->orderBy = $data['orderBy']; } return $r; } public function __get($key) { if (isset($this->data[$key])) { return $this->data[$key]; } } public function __set($key, $val) { $this->data[$key] = $val; } }
talib570/LazyRecord
src/LazyRecord/Schema/Relationship.php
PHP
bsd-3-clause
5,989
from httpx import AsyncClient # Runtime import to avoid syntax errors in samples on Python < 3.5 and reach top-dir import os _TOP_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__file__), '../', )), ) _SAMPLES_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__file__), '../samples/', )), ) import sys sys.path.append(_TOP_DIR) sys.path.append(_SAMPLES_DIR) from asyncutils import AsyncTestCase from wiringfastapi import web class WiringFastAPITest(AsyncTestCase): client: AsyncClient def setUp(self) -> None: super().setUp() self.client = AsyncClient(app=web.app, base_url='http://test') def tearDown(self) -> None: self._run(self.client.aclose()) super().tearDown() def test_depends_marker_injection(self): class ServiceMock: async def process(self): return 'Foo' with web.container.service.override(ServiceMock()): response = self._run(self.client.get('/')) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {'result': 'Foo'}) def test_depends_injection(self): response = self._run(self.client.get('/auth', auth=('john_smith', 'secret'))) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {'username': 'john_smith', 'password': 'secret'})
rmk135/objects
tests/unit/wiring/test_wiringfastapi_py36.py
Python
bsd-3-clause
1,426
<?php namespace Application\Entity; use Application\Entity\Interfaces\IEntity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\MappedSuperclass */ abstract class BaseEntity implements IEntity{ static protected $monthsShort = array(1 => "jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sept", "okt", "nov", "dec"); static protected $monthsLong = array(1 => "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"); /** * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ protected $id; /* public function getId() { return $this->id; }* /** * Magic getter to expose protected properties. * * @param string $property * @return mixed */ public function __get($property) { return $this->$property; } /* public function setId($id) { $this->id = $id; return $this; }*/ public function equals($entity) { if ($entity === null || !is_a($entity, get_class($this))) { return false; } if ($this->id !== null) { return $this->id === $entity->id; } else { return $this === $entity; } } /* public function fromArray(array $array) { foreach ($array as $prop=>$value) { if (property_exists($this, $prop)) { $this->$prop = $value; } } }*/ /** * Convert the object to an array. * * @return array */ public function toArray(BaseEntity $owner = null) { $array = get_object_vars($this); foreach ($array as $i => &$property) { if (is_object($property)) { // is a oneToMany relationship if (is_a($property, 'Doctrine\ORM\PersistentCollection')) { $property = $property->toArray(); foreach ($property as &$item) {// deze weg zou ons terug naar de entity lijden waar we de toArray op hebben uitgevoerd, if ($item->equals($owner)) { unset($array[$i]); continue 2; } } foreach ($property as &$item) { if (is_object($item) && is_subclass_of($item, __CLASS__)) { $item = $item->toArray($this); } } } else { if (is_subclass_of($property, __CLASS__)) { if ($property->equals($owner)) { unset($array[$i]); } else { $property = $property->toArray($this); } } } } } return $array; } /* public function getDateAsString(\DateTime $date, $timeIncluded = false) { $sDate = $date->format("j"); $sDate .= " " . self::$monthsLong[$date->format("n")]; $sDate .= " " . $date->format("Y"); if($timeIncluded) { $sDate .= " " . $date->format("H:i"); } return $sDate; }*/ }
langemol/myrecipes-backend
module/Application/src/Application/Entity/BaseEntity.php
PHP
bsd-3-clause
3,393
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2017, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import collections # Sentinel to avoid the situation where `None` *is* the default value. NoDefault = collections.namedtuple('NoDefault', [])() class ValueNotFoundException(Exception): """Raised when a value cannot be found. Used for control-flow only.""" class Handler: def __init__(self, name, prefix='', default=NoDefault, description=None): # e.g. my_option_name self.name = name # e.g. p_my_option_name self.click_name = prefix + name self.default = default self.description = description self.missing = [] @property def cli_name(self): import q2cli.util # e.g. p-my-option-name return q2cli.util.to_cli_name(self.click_name) def get_click_options(self): """Should yield 1 or more click.Options""" raise NotImplementedError() def get_value(self, arguments, fallback=None): """Should find 1 or more arguments and convert to a single API value""" raise NotImplementedError() def _locate_value(self, arguments, fallback, multiple=False): """Default lookup procedure to find a click.Option provided by user""" # TODO revisit this interaction between _locate_value, single vs. # multiple options, and fallbacks. Perhaps handlers should always # use tuples to store values, even for single options, in order to # normalize single-vs-multiple option handling. Probably not worth # revisiting until there are more unit + integration tests of q2cli # since there's the potential to break things. # Is it in args? v = arguments[self.click_name] missing_value = () if multiple else None if v != missing_value: return v # Does our fallback know about it? if fallback is not None: try: fallback_value = fallback(self.name, self.cli_name) except ValueNotFoundException: pass else: # TODO fallbacks don't know whether they're handling a single # vs. multiple option, so the current expectation is that # fallbacks will always return a single value. Revisit this # expectation in the future; perhaps fallbacks should be aware # of single-vs-multiple options, or perhaps they could always # return a tuple. if multiple: fallback_value = (fallback_value,) return fallback_value # Do we have a default? if self.default is not NoDefault: return self.default # Give up self.missing.append(self.cli_name) raise ValueNotFoundException() def _parse_boolean(self, string): """Parse string representing a boolean into Python bool type. Supported values match `configparser.ConfigParser.getboolean`. """ trues = ['1', 'yes', 'true', 'on'] falses = ['0', 'no', 'false', 'off'] string_lower = string.lower() if string_lower in trues: return True elif string_lower in falses: return False else: import itertools import click msg = ( "Error: unrecognized value for --%s flag: %s\n" "Supported values (case-insensitive): %s" % (self.cli_name, string, ', '.join(itertools.chain(trues, falses))) ) click.secho(msg, err=True, fg='red', bold=True) ctx = click.get_current_context() ctx.exit(1) def _add_description(self, option, requirement): def pretty_cat(a, b, space=1): if a: return a + (' ' * space) + b return b if self.description: option.help = pretty_cat(option.help, self.description) option.help = pretty_cat(option.help, requirement, space=2) return option class VerboseHandler(Handler): """Handler for verbose output (--verbose flag).""" def __init__(self): super().__init__('verbose', default=False) def get_click_options(self): import q2cli # `is_flag` will set the default to `False`, but `self._locate_value` # needs to distinguish between the presence or absence of the flag # provided by the user. yield q2cli.Option( ['--' + self.cli_name], is_flag=True, default=None, help='Display verbose output to stdout and/or stderr during ' 'execution of this action. [default: %s]' % self.default) def get_value(self, arguments, fallback=None): value = self._locate_value(arguments, fallback) # Value may have been specified in --cmd-config (or another source in # the future). If we don't have a bool type yet, attempt to interpret a # string representing a boolean. if type(value) is not bool: value = self._parse_boolean(value) return value class QuietHandler(Handler): """Handler for quiet output (--quiet flag).""" def __init__(self): super().__init__('quiet', default=False) def get_click_options(self): import q2cli # `is_flag` will set the default to `False`, but `self._locate_value` # needs to distinguish between the presence or absence of the flag # provided by the user. yield q2cli.Option( ['--' + self.cli_name], is_flag=True, default=None, help='Silence output if execution is successful ' '(silence is golden). [default: %s]' % self.default) def get_value(self, arguments, fallback=None): value = self._locate_value(arguments, fallback) # Value may have been specified in --cmd-config (or another source in # the future). If we don't have a bool type yet, attempt to interpret a # string representing a boolean. if type(value) is not bool: value = self._parse_boolean(value) return value class OutputDirHandler(Handler): """Meta handler which returns a fallback function as its value.""" def __init__(self): super().__init__('output_dir') def get_click_options(self): import click import q2cli yield q2cli.Option( ['--' + self.cli_name], type=click.Path(exists=False, dir_okay=True, file_okay=False, writable=True), help='Output unspecified results to a directory') def get_value(self, arguments, fallback=None): import os import os.path import click try: path = self._locate_value(arguments, fallback=fallback) # TODO: do we want a --force like flag? if os.path.exists(path): click.secho("Error: --%s directory already exists, won't " "overwrite." % self.cli_name, err=True, fg='red', bold=True) ctx = click.get_current_context() ctx.exit(1) os.makedirs(path) def fallback_(name, cli_name): return os.path.join(path, name) return fallback_ except ValueNotFoundException: # Always fail to find a value as this handler doesn't exist. def fail(*_): raise ValueNotFoundException() return fail class CommandConfigHandler(Handler): """Meta handler which returns a fallback function as its value.""" def __init__(self, cli_plugin, cli_action): self.cli_plugin = cli_plugin self.cli_action = cli_action super().__init__('cmd_config') def get_click_options(self): import click import q2cli yield q2cli.Option( ['--' + self.cli_name], type=click.Path(exists=True, dir_okay=False, file_okay=True, readable=True), help='Use config file for command options') def get_value(self, arguments, fallback=None): import configparser import warnings try: path = self._locate_value(arguments, fallback=fallback) config = configparser.ConfigParser() config.read(path) try: config_section = config['.'.join([ self.cli_plugin, self.cli_action ])] except KeyError: warnings.warn("Config file does not contain a section" " for %s" % '.'.join([self.cli_plugin, self.cli_action]), UserWarning) raise ValueNotFoundException() def fallback_(name, cli_name): try: return config_section[cli_name] except KeyError: raise ValueNotFoundException() return fallback_ except ValueNotFoundException: # Always fail to find a value as this handler doesn't exist. def fail(*_): raise ValueNotFoundException() return fail class GeneratedHandler(Handler): def __init__(self, name, repr, ast, default=NoDefault, description=None): super().__init__(name, prefix=self.prefix, default=default, description=description) self.repr = repr self.ast = ast class CollectionHandler(GeneratedHandler): view_map = { 'List': list, 'Set': set } def __init__(self, inner_handler, **kwargs): self.inner_handler = inner_handler # inner_handler needs to be set first so the prefix lookup works super().__init__(**kwargs) self.view_type = self.view_map[self.ast['name']] @property def prefix(self): return self.inner_handler.prefix def get_click_options(self): import q2cli.core for option in self.inner_handler.get_click_options(): option.multiple = True # validation happens on a callback for q2cli.core.Option, so unset # it because we need standard click behavior for multi-options # without this, the result of not-passing a value is `None` instead # of `()` which confuses ._locate_value option.callback = None option.type = q2cli.core.MultipleType(option.type) yield option def get_value(self, arguments, fallback=None): args = self._locate_value(arguments, fallback, multiple=True) if args is None: return None decoded_values = [] for arg in args: # Use an empty dict because we don't need the inner handler to # look for anything; that's our job. We just need it to decode # whatever it was we found. empty = collections.defaultdict(lambda: None) decoded = self.inner_handler.get_value(empty, fallback=lambda *_: arg) decoded_values.append(decoded) value = self.view_type(decoded_values) if len(value) != len(decoded_values): self._error_with_duplicate_in_set(decoded_values) return value def _error_with_duplicate_in_set(self, elements): import click import collections counter = collections.Counter(elements) dups = {name for name, count in counter.items() if count > 1} ctx = click.get_current_context() click.echo(ctx.get_usage() + '\n', err=True) click.secho("Error: Option --%s was given these values: %r more than " "one time, values passed should be unique." % (self.cli_name, dups), err=True, fg='red', bold=True) ctx.exit(1) class ArtifactHandler(GeneratedHandler): prefix = 'i_' def get_click_options(self): import q2cli import q2cli.core type = q2cli.core.ResultPath(repr=self.repr, exists=True, file_okay=True, dir_okay=False, readable=True) if self.default is None: requirement = '[optional]' else: requirement = '[required]' option = q2cli.Option(['--' + self.cli_name], type=type, help="") yield self._add_description(option, requirement) def get_value(self, arguments, fallback=None): import qiime2 path = self._locate_value(arguments, fallback) if path is None: return None else: return qiime2.Artifact.load(path) class ResultHandler(GeneratedHandler): prefix = 'o_' def get_click_options(self): import q2cli type = q2cli.core.ResultPath(self.repr, exists=False, file_okay=True, dir_okay=False, writable=True) option = q2cli.Option(['--' + self.cli_name], type=type, help="") yield self._add_description( option, '[required if not passing --output-dir]') def get_value(self, arguments, fallback=None): return self._locate_value(arguments, fallback) def parameter_handler_factory(name, repr, ast, default=NoDefault, description=None): if ast['name'] == 'Metadata': return MetadataHandler(name, default=default, description=description) elif ast['name'] == 'MetadataCategory': return MetadataCategoryHandler(name, default=default, description=description) else: return RegularParameterHandler(name, repr, ast, default=default, description=description) class MetadataHandler(Handler): def __init__(self, name, default=NoDefault, description=None): if default is not NoDefault and default is not None: raise TypeError( "The only supported default value for Metadata is `None`. " "Found this default value: %r" % (default,)) super().__init__(name, prefix='m_', default=default, description=description) self.click_name += '_file' def get_click_options(self): import click import q2cli import q2cli.core name = '--' + self.cli_name type = click.Path(exists=True, file_okay=True, dir_okay=False, readable=True) type = q2cli.core.MultipleType(type) help = ('Metadata file or artifact viewable as metadata. This ' 'option may be supplied multiple times to merge metadata.') if self.default is None: requirement = '[optional]' else: requirement = '[required]' option = q2cli.Option([name], type=type, help=help, multiple=True) yield self._add_description(option, requirement) def get_value(self, arguments, fallback=None): import os import qiime2 import q2cli.util paths = self._locate_value(arguments, fallback, multiple=True) if paths is None: return paths metadata = [] for path in paths: try: # check to see if path is an artifact artifact = qiime2.Artifact.load(path) except Exception: try: metadata.append(qiime2.Metadata.load(path)) except Exception as e: header = ("There was an issue with loading the file %s as " "metadata:" % path) with open(os.devnull, 'w') as dev_null: q2cli.util.exit_with_error( e, header=header, file=dev_null, suppress_footer=True) else: try: metadata.append(qiime2.Metadata.from_artifact(artifact)) except Exception as e: header = ("There was an issue with viewing the artifact " "%s as metadata:" % path) with open(os.devnull, 'w') as dev_null: q2cli.util.exit_with_error( e, header=header, file=dev_null, suppress_footer=True) return metadata[0].merge(*metadata[1:]) class MetadataCategoryHandler(Handler): def __init__(self, name, default=NoDefault, description=None): if default is not NoDefault and default is not None: raise TypeError( "The only supported default value for MetadataCategory is " "`None`. Found this default value: %r" % (default,)) super().__init__(name, prefix='m_', default=default, description=description) self.click_name += '_category' # Not passing `description` to metadata handler because `description` # applies to the metadata category (`self`). self.metadata_handler = MetadataHandler(name, default=default) def get_click_options(self): import q2cli name = '--' + self.cli_name type = str help = ('Category from metadata file or artifact viewable as ' 'metadata.') if self.default is None: requirement = '[optional]' else: requirement = '[required]' option = q2cli.Option([name], type=type, help=help) yield from self.metadata_handler.get_click_options() yield self._add_description(option, requirement) def get_value(self, arguments, fallback=None): # Attempt to find all options before erroring so that all handlers' # missing options can be displayed to the user. try: metadata_value = self.metadata_handler.get_value(arguments, fallback=fallback) except ValueNotFoundException: pass try: category_value = self._locate_value(arguments, fallback) except ValueNotFoundException: pass missing = self.metadata_handler.missing + self.missing if missing: self.missing = missing raise ValueNotFoundException() # If metadata category is optional, there is a chance for metadata to # be provided without a metadata category, or vice versa. if metadata_value is None and category_value is not None: self.missing.append(self.metadata_handler.cli_name) raise ValueNotFoundException() elif metadata_value is not None and category_value is None: self.missing.append(self.cli_name) raise ValueNotFoundException() if metadata_value is None and category_value is None: return None else: return metadata_value.get_category(category_value) class RegularParameterHandler(GeneratedHandler): prefix = 'p_' def __init__(self, name, repr, ast, default=NoDefault, description=None): import q2cli.util super().__init__(name, repr, ast, default=default, description=description) # TODO: just create custom click.ParamType to avoid this silliness if ast['type'] == 'collection': ast, = ast['fields'] self.type = q2cli.util.convert_primitive(ast) def get_click_options(self): import q2cli import q2cli.util if self.type is bool: no_name = self.prefix + 'no_' + self.name cli_no_name = q2cli.util.to_cli_name(no_name) name = '--' + self.cli_name + '/--' + cli_no_name # click.Option type is determined implicitly for flags with # secondary options, and explicitly passing type=bool results in a # TypeError, so we pass type=None (the default). option_type = None else: name = '--' + self.cli_name option_type = self.type if self.default is NoDefault: requirement = '[required]' elif self.default is None: requirement = '[optional]' else: requirement = '[default: %s]' % self.default # Pass `default=None` and `show_default=False` to `click.Option` # because the handlers are responsible for resolving missing values and # supplying defaults. Telling Click about the default value here makes # it impossible to determine whether the user supplied or omitted a # value once the handlers are invoked. option = q2cli.Option([name], type=option_type, default=None, show_default=False, help='') yield self._add_description(option, requirement) def get_value(self, arguments, fallback=None): value = self._locate_value(arguments, fallback) if value is None: return None elif self.type is bool: # TODO: should we defer to the Bool primitive? It only allows # 'true' and 'false'. if type(value) is not bool: value = self._parse_boolean(value) return value else: import qiime2.sdk primitive = qiime2.sdk.parse_type(self.repr, expect='primitive') # TODO/HACK: the repr is the primitive used, but since there's a # collection handler managing the set/list this get_value should # handle only the pieces. This is super gross, but would be # unecessary if click.ParamTypes were implemented for each # kind of QIIME 2 input. if self.ast['type'] == 'collection': primitive, = primitive.fields return primitive.decode(value)
gregcaporaso/q2cli
q2cli/handlers.py
Python
bsd-3-clause
22,305
""" ======================================= Receiver Operating Characteristic (ROC) ======================================= Example of Receiver Operating Characteristic (ROC) metric to evaluate classifier output quality. ROC curves typically feature true positive rate on the Y axis, and false positive rate on the X axis. This means that the top left corner of the plot is the "ideal" point - a false positive rate of zero, and a true positive rate of one. This is not very realistic, but it does mean that a larger area under the curve (AUC) is usually better. The "steepness" of ROC curves is also important, since it is ideal to maximize the true positive rate while minimizing the false positive rate. ROC curves are typically used in binary classification to study the output of a classifier. In order to extend ROC curve and ROC area to multi-class or multi-label classification, it is necessary to binarize the output. One ROC curve can be drawn per label, but one can also draw a ROC curve by considering each element of the label indicator matrix as a binary prediction (micro-averaging). .. note:: See also :func:`sklearn.metrics.roc_auc_score`, :ref:`example_plot_roc_crossval.py`. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.cross_validation import train_test_split from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier # Import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target # Binarize the output y = label_binarize(y, classes=[0, 1, 2]) n_classes = y.shape[1] # Add noisy features to make the problem harder random_state = np.random.RandomState(0) n_samples, n_features = X.shape X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] # shuffle and split training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, random_state=0) # Learn to predict each class against the other classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=random_state)) y_score = classifier.fit(X_train, y_train).decision_function(X_test) # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) # Plot of a ROC curve for a specific class plt.figure() plt.plot(fpr[2], tpr[2], label='ROC curve (area = %0.2f)' % roc_auc[2]) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show() # Plot ROC curve plt.figure() plt.plot(fpr["micro"], tpr["micro"], label='micro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["micro"])) for i in range(n_classes): plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i, roc_auc[i])) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Some extension of Receiver operating characteristic to multi-class') plt.legend(loc="lower right") plt.show()
flightgong/scikit-learn
examples/plot_roc.py
Python
bsd-3-clause
3,681
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import unittest from telemetry import story from telemetry import page as page_module from telemetry import value from telemetry.value import improvement_direction from telemetry.value import none_values from telemetry.value import scalar class TestBase(unittest.TestCase): def setUp(self): story_set = story.StorySet(base_dir=os.path.dirname(__file__)) story_set.AddStory( page_module.Page('http://www.bar.com/', story_set, story_set.base_dir, name='http://www.bar.com/')) story_set.AddStory( page_module.Page('http://www.baz.com/', story_set, story_set.base_dir, name='http://www.baz.com/')) story_set.AddStory( page_module.Page('http://www.foo.com/', story_set, story_set.base_dir, name='http://www.foo.com/')) self.story_set = story_set @property def pages(self): return self.story_set.stories class ValueTest(TestBase): def testRepr(self): page0 = self.pages[0] v = scalar.ScalarValue(page0, 'x', 'unit', 3, important=True, description='desc', tir_label='my_ir', improvement_direction=improvement_direction.DOWN) expected = ('ScalarValue(http://www.bar.com/, x, unit, 3, important=True, ' 'description=desc, tir_label=my_ir, ' 'improvement_direction=down, grouping_keys={}') self.assertEquals(expected, str(v)) def testBuildbotValueType(self): page0 = self.pages[0] v = scalar.ScalarValue(page0, 'x', 'unit', 3, important=True, improvement_direction=improvement_direction.DOWN) self.assertEquals('default', v.GetBuildbotDataType( value.COMPUTED_PER_PAGE_SUMMARY_OUTPUT_CONTEXT)) self.assertEquals([3], v.GetBuildbotValue()) self.assertEquals(('x', page0.name), v.GetChartAndTraceNameForPerPageResult()) v = scalar.ScalarValue(page0, 'x', 'unit', 3, important=False, improvement_direction=improvement_direction.DOWN) self.assertEquals( 'unimportant', v.GetBuildbotDataType(value.COMPUTED_PER_PAGE_SUMMARY_OUTPUT_CONTEXT)) def testScalarSamePageMerging(self): page0 = self.pages[0] v0 = scalar.ScalarValue(page0, 'x', 'unit', 1, description='important metric', improvement_direction=improvement_direction.UP) v1 = scalar.ScalarValue(page0, 'x', 'unit', 2, description='important metric', improvement_direction=improvement_direction.UP) self.assertTrue(v1.IsMergableWith(v0)) vM = scalar.ScalarValue.MergeLikeValuesFromSamePage([v0, v1]) self.assertEquals(page0, vM.page) self.assertEquals('x', vM.name) self.assertEquals('unit', vM.units) self.assertEquals('important metric', vM.description) self.assertEquals(True, vM.important) self.assertEquals([1, 2], vM.values) self.assertEquals(improvement_direction.UP, vM.improvement_direction) def testScalarDifferentPageMerging(self): page0 = self.pages[0] page1 = self.pages[1] v0 = scalar.ScalarValue(page0, 'x', 'unit', 1, description='important metric', improvement_direction=improvement_direction.UP) v1 = scalar.ScalarValue(page1, 'x', 'unit', 2, description='important metric', improvement_direction=improvement_direction.UP) vM = scalar.ScalarValue.MergeLikeValuesFromDifferentPages([v0, v1]) self.assertEquals(None, vM.page) self.assertEquals('x', vM.name) self.assertEquals('unit', vM.units) self.assertEquals('important metric', vM.description) self.assertEquals(True, vM.important) self.assertEquals([1, 2], vM.values) self.assertEquals(improvement_direction.UP, vM.improvement_direction) def testScalarWithNoneValueMerging(self): page0 = self.pages[0] v0 = scalar.ScalarValue( page0, 'x', 'unit', 1, improvement_direction=improvement_direction.DOWN) v1 = scalar.ScalarValue(page0, 'x', 'unit', None, none_value_reason='n', improvement_direction=improvement_direction.DOWN) self.assertTrue(v1.IsMergableWith(v0)) vM = scalar.ScalarValue.MergeLikeValuesFromSamePage([v0, v1]) self.assertEquals(None, vM.values) expected_none_value_reason = ( 'Merging values containing a None value results in a None value. ' 'None values: [ScalarValue(http://www.bar.com/, x, unit, None, ' 'important=True, description=None, tir_label=None, ' 'improvement_direction=down, grouping_keys={}]') self.assertEquals(expected_none_value_reason, vM.none_value_reason) def testScalarWithNoneValueMustHaveNoneReason(self): page0 = self.pages[0] self.assertRaises(none_values.NoneValueMissingReason, lambda: scalar.ScalarValue( page0, 'x', 'unit', None, improvement_direction=improvement_direction.UP)) def testScalarWithNoneReasonMustHaveNoneValue(self): page0 = self.pages[0] self.assertRaises(none_values.ValueMustHaveNoneValue, lambda: scalar.ScalarValue( page0, 'x', 'unit', 1, none_value_reason='n', improvement_direction=improvement_direction.UP)) def testAsDict(self): v = scalar.ScalarValue(None, 'x', 'unit', 42, important=False, improvement_direction=improvement_direction.DOWN) d = v.AsDictWithoutBaseClassEntries() self.assertEquals(d, {'value': 42}) def testNoneValueAsDict(self): v = scalar.ScalarValue(None, 'x', 'unit', None, important=False, none_value_reason='n', improvement_direction=improvement_direction.DOWN) d = v.AsDictWithoutBaseClassEntries() self.assertEquals(d, {'value': None, 'none_value_reason': 'n'}) def testFromDictInt(self): d = { 'type': 'scalar', 'name': 'x', 'units': 'unit', 'value': 42, 'improvement_direction': improvement_direction.DOWN, } v = value.Value.FromDict(d, {}) self.assertTrue(isinstance(v, scalar.ScalarValue)) self.assertEquals(v.value, 42) self.assertEquals(v.improvement_direction, improvement_direction.DOWN) def testFromDictFloat(self): d = { 'type': 'scalar', 'name': 'x', 'units': 'unit', 'value': 42.4, 'improvement_direction': improvement_direction.UP, } v = value.Value.FromDict(d, {}) self.assertTrue(isinstance(v, scalar.ScalarValue)) self.assertEquals(v.value, 42.4) def testFromDictWithoutImprovementDirection(self): d = { 'type': 'scalar', 'name': 'x', 'units': 'unit', 'value': 42, } v = value.Value.FromDict(d, {}) self.assertTrue(isinstance(v, scalar.ScalarValue)) self.assertIsNone(v.improvement_direction) def testFromDictNoneValue(self): d = { 'type': 'scalar', 'name': 'x', 'units': 'unit', 'value': None, 'none_value_reason': 'n', 'improvement_direction': improvement_direction.UP, } v = value.Value.FromDict(d, {}) self.assertTrue(isinstance(v, scalar.ScalarValue)) self.assertEquals(v.value, None) self.assertEquals(v.none_value_reason, 'n')
catapult-project/catapult-csm
telemetry/telemetry/value/scalar_unittest.py
Python
bsd-3-clause
7,682
#ifndef TASK_ADD #define TASK_ADD extern struct Mmutex MutexA; #endif // TASK_ADD
Kefir0192/MThreadStatic
sources/example/test_stm32f051r8/file/inc/task_add.h
C
bsd-3-clause
85
<?php /** * Jazz Library/Framework * * LICENSE * This library is being released under the terms of the New BSD License. A * copy of the license is packaged with the software (LICENSE.txt). If no * copy is found, a copy of the license template can be found at: * http://www.opensource.org/licenses/bsd-license.php * * @package Jazz * @subpackage Helper * @author Michael Luster <phpjazz@nyclagniappe.com> * @copyright Copyright (c) NYCLagniappe.com - All Rights Reserved * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @link https://github.com/nyclagniappe/phpjazz */ namespace Jazz\Helper; require_once ('Jazz/Helper.php'); /** * Navigation Helper * * @package Jazz * @subpackage Helper * @author Michael Luster <phpjazz@nyclagniappe.com> * @copyright Copyright (c) NYCLagniappe.com - All Rights Reserved * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @link https://github.com/nyclagniappe/phpjazz */ class Nav extends \Jazz\Helper { /** * List of links. * @var array $_links */ private $_links = array(); /** * List of Link Titles. * @var array $_titles */ private $_titles = array(); /** * Link highlight. * @var int|string $_highlight */ private $_highlight; /** * Constructor: calls the setup method. */ public function __construct() { $this->setup(); } /** * Setup the Navigation. */ protected function setup() {} /** * Renders Helper * @return string */ public function render() { $view = $this->getView(); if ($this->getScript() === null) { $this->setScript('helpers/nav'); } $view->links = $this->getLinks(); $view->titles = $this->getTitles(); $view->highlight = $this->getHighlight(); return parent::render(); } /** ACTION METHODS **/ /** * Adds a link * @param int|string $key * @param string $url * @param string $title * @throws \InvalidArgumentException */ public function addLink($key, $url, $title) { // verify precondition if (!is_int($key) && !is_string($key)) { throw new \InvalidArgumentException('key'); } if (!is_string($url)) { throw new \InvalidArgumentException('url'); } if (!is_string($title)) { throw new \InvalidArgumentException('title'); } $this->_links[$key] = $url; $this->_titles[$key] = $title; } /** * Removes a link * @param int|string $key */ public function removeLink($key) { if ($this->exists($key)) { unset ($this->_links[$key]); unset ($this->_titles[$key]); } } /** MUTATOR METHODS **/ /** * Sets a link to be highlighted * @param int|string $key * @throws \InvalidArgumentException */ public function setHighlight($key) { // verify precondition if (!$this->exists($key)) { throw new \InvalidArgumentException('key'); } $this->_highlight = $key; } /** ACCESSOR METHODS **/ /** * Returns ALL links * @return array */ public function getLinks() { return $this->_links; } /** * Returns ALL titles * @return array */ public function getTitles() { return $this->_titles; } /** * Returns highlight * @return int|string */ public function getHighlight() { return $this->_highlight; } /** * Returns if a key exists * @param int|string $key * @return bool */ public function exists($key) { return array_key_exists($key, $this->_links); } }
ibayou/phpjazz
archive/Jazz/Helper/Nav.php
PHP
bsd-3-clause
3,858
/*============================================================== * Copyright (c) 2009 Blake Fisher. All Rights Reserved. * * This software is released under the BSD License * <http://www.opensource.org/licenses/bsd-license.php> *============================================================== */ #pragma once #include <vector> using namespace std; /** Defines a class that can pass various events to registered listeners based on some state S is the state class SM is the state machine class L is the listener class */ template <class S, class SM, class L> class StateRouter { public: /** The default constructor */ StateRouter() { mStateMachine = NULL; } /** The destructor */ ~StateRouter(){} /** Set the state machine @param sm The state machine that will be used to redirect events */ void set_state_machine(SM *sm) { mStateMachine = sm; } /** Register to receive events when the state machine is in the provided state @param l The listener to receive events @param s The listener will only receive events when the state machine is in this state @return Whether or not the listener was successfully registered */ bool register_listener(L *l, S s) { // Find out if we already have a listener for the passed state if (this->get_state_idx(s) != -1) { // We already have a listener, so fail return false; } // Add to our list of listeners mListeners.push_back(l); mListenerStates.push_back(s); return true; } /** Stop sending frame information to the listener registered on the passed state @param s The state to remove a listener from */ void unregister_listener(S s) { // Find the relevant state int idx = this->get_state_idx(s); // Remove the relevant listener and state if (idx != -1) { mListeners.erase(mListeners.begin() + idx); mListenerStates.erase(mListenerStates.begin() + idx); } } protected: // Variables -------------------- /** The state machine */ SM *mStateMachine; /** Registered listeners */ vector<L*> mListeners; /** The corresponding state of each listener */ vector<S> mListenerStates; // Methods -------------------- /** Get the listener for the passed state @param s The relevant state @return The listener. NULL if there is none */ L *get_listener(S s) { int idx = this->get_state_idx(s); if (idx == -1) { return NULL; } else { return mListeners[idx]; } } L *get_listener() { if (!mStateMachine) { return NULL; } return this->get_listener(mStateMachine->get_current_state()); } /** Get the index into the state that's been registered @param s The relevant state @return An index into our mListeners and mListenerStates vectors. -1 if there is no listener for the passed state */ int get_state_idx(S s) { // Find the relevant state typename vector<S>::iterator foundState; foundState = find(mListenerStates.begin(), mListenerStates.end(), s); if (foundState == mListenerStates.end()) { return -1; } else { return foundState - mListenerStates.begin(); } } };
vashero/tachyon-game
src/stateRouter.hpp
C++
bsd-3-clause
3,266
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, 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. */ #include <folly/portability/GTest.h> #include <xattr/key_validator.h> #include <cctype> #include <locale> #include "daemon/subdocument_validators.h" /** * Ensure that we don't accept empty keys */ TEST(XattrKeyValidator, Empty) { EXPECT_FALSE(is_valid_xattr_key({nullptr, 0})); EXPECT_FALSE(is_valid_xattr_key({".", 1})); } /** * Ensure that we accept keys without a dot (the path is empty) */ TEST(XattrKeyValidator, FullXattr) { std::string key = "mydata"; EXPECT_TRUE(is_valid_xattr_key({key.data(), key.size()})); } /** * Ensure that we enforce the max limit */ TEST(XattrKeyValidator, KeyLengthWithoutPath) { std::string key = "The Three Strikes and You're Out"; for (auto ii = key.length(); ii > 0; --ii) { if (ii >= SUBDOC_MAX_XATTR_LENGTH) { EXPECT_FALSE(is_valid_xattr_key({key.data(), ii})); } else { EXPECT_TRUE(is_valid_xattr_key({key.data(), ii})); } } } /** * Ensure that we enforce the max limit with a path element.. */ TEST(XattrKeyValidator, KeyLengthWithPath) { std::string key = "The Three Strikes and You're Out"; for (auto ii = key.length(); ii > 1; --ii) { // Just make a copy and inject a dot ;) std::string copy = key; const_cast<char*>(copy.data())[ii - 1] = '.'; if (ii > SUBDOC_MAX_XATTR_LENGTH) { EXPECT_FALSE(is_valid_xattr_key({copy.data(), copy.size()})) << "[" << copy << "]"; } else { EXPECT_TRUE(is_valid_xattr_key({copy.data(), copy.size()})) << "[" << copy << "]"; } } } /** * Ensure that we accept keys with a path */ TEST(XattrKeyValidator, PartialXattr) { std::string key = "mydata.foobar"; EXPECT_TRUE(is_valid_xattr_key({key.data(), key.size()})); } TEST(XattrKeyValidator, FullWithArrayIndex) { std::string key = "mydata[0]"; EXPECT_TRUE(is_valid_xattr_key({key.data(), key.size()})); } /** * X-Keys starting with a leading underscore ('_', 0x5F) are considered system * Such keys must be at least two characters */ TEST(XattrKeyValidator, SystemXattr) { std::string key = "_sync"; EXPECT_TRUE(is_valid_xattr_key({key.data(), key.size()})); key = "_"; EXPECT_FALSE(is_valid_xattr_key({key.data(), key.size()})); } /** * X-Keys starting with a leading dollar sign ('$', 0x24) are considered * virtual xattrs */ TEST(XattrKeyValidator, VirtualXattr) { std::string key = "$document"; EXPECT_TRUE(is_valid_xattr_key({key.data(), key.size()})); key = "$XTOC"; EXPECT_TRUE(is_valid_xattr_key({key.data(), key.size()})); key = "$"; EXPECT_FALSE(is_valid_xattr_key({key.data(), key.size()})); } /** * There is no restrictions on the characters that may be inside the xattr * key. It'll take way too long time to test all of the possible values, so * lets just validate with all 7 bit ASCII characters. */ TEST(XattrKeyValidator, AllCharachtersInXattr) { std::vector<char> key(2); key[0] = 'a'; // 0 is not allowed according to (should be using the two byte encoding) key[1] = 0; EXPECT_FALSE(is_valid_xattr_key({key.data(), key.size()})); for (int ii = 1; ii < 0x80; ++ii) { key[1] = char(ii); EXPECT_TRUE(is_valid_xattr_key({key.data(), key.size()})) << ii; } } /** * X-Keys starting with the following characters are reserved and * cannot be used: * * ispunct(), excluding underscore (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~) * * iscntrl() */ TEST(XattrKeyValidator, RestrictedXattrPrefix) { std::locale loc("C"); std::vector<char> key(2); key[1] = 'b'; for (int ii = 0; ii < 0x80; ++ii) { // values over 0x80 == multibyte UTF8 key[0] = char(ii); if ((std::ispunct(key[0], loc) && (key[0] != '_' && key[0] != '$')) || std::iscntrl(key[0], loc)) { EXPECT_FALSE(is_valid_xattr_key({key.data(), key.size()})); } else { EXPECT_TRUE(is_valid_xattr_key({key.data(), key.size()})); } } } /** * XATTRS should be UTF8 */ static void testInvalidUtf(char magic, int nbytes) { std::vector<char> data; data.push_back(magic); for (int ii = 0; ii < nbytes; ++ii) { EXPECT_FALSE(is_valid_xattr_key({data.data(), data.size()})); data.push_back(char(0xbf)); } EXPECT_TRUE(is_valid_xattr_key({data.data(), data.size()})); for (int ii = 1; ii < nbytes + 1; ++ii) { data[ii] = char(0xff); EXPECT_FALSE(is_valid_xattr_key({data.data(), data.size()})) << ii; data[ii] = char(0xbf); EXPECT_TRUE(is_valid_xattr_key({data.data(), data.size()})) << ii; } } TEST(XattrKeyValidator, InvalidUTF8_2Bytes) { testInvalidUtf(char(0xDF), 1); } TEST(XattrKeyValidator, InvalidUTF8_3Bytes) { testInvalidUtf(char(0xEF), 2); } TEST(XattrKeyValidator, InvalidUTF8_4Bytes) { testInvalidUtf(char(0xF7), 3); }
daverigby/kv_engine
tests/mcbp/xattr_key_validator_test.cc
C++
bsd-3-clause
5,631
package com.nordicsemi.nrfUARTv2; /** * Created by Michele on 10/19/16. */ import android.util.Log; import java.util.Arrays; import java.util.Date; import java.util.List; public class SensorData { private List<String> pressureReadings; private List<String> temperatureReadings; private List<String> axesReadings; private Float voltageReading; // private Integer packetSize; private String timestamp; public static final String TAG = "SensorData"; public SensorData(List<String> pressureData, List<String> additionalData, String date) { pressureReadings = pressureData; temperatureReadings = additionalData.subList(additionalData.indexOf("T") + 1, additionalData.indexOf("O")); axesReadings = additionalData.subList(additionalData.indexOf("O") + 1, additionalData.indexOf("V")); voltageReading = Float.parseFloat(additionalData.get(additionalData.indexOf("V") + 1)); // packetSize = Integer.parseInt(additionalData.get(additionalData.size() - 2)); timestamp = date; } public void printDataToDebug () { Log.d(TAG, "Pressure readings: " + pressureReadings); Log.d(TAG, "Temp: " + temperatureReadings); Log.d(TAG, "Axes: " + axesReadings); Log.d(TAG, "Voltage: " + voltageReading); // Log.d(TAG, "Packet size: " + packetSize); } public List<String> getPressureReadings () { return pressureReadings; } public List<String> getTemperatureReadings() { return temperatureReadings; } public List<String> getAxesReadings () { return axesReadings; } public Float getVoltageReading() { return voltageReading; } // public Integer getPacketSize () { // return packetSize; // } }
Medsentec/PUPS-Android-Application
app/src/main/java/com/nordicsemi/nrfUARTv2/SensorData.java
Java
bsd-3-clause
1,788
/*************************************************************************** # Copyright (c) 2015-21, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of NVIDIA CORPORATION nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************/ #pragma once #pragma warning(push) #pragma warning(disable : 4244 4267) #include <nanovdb/NanoVDB.h> #include <nanovdb/util/GridHandle.h> #include <nanovdb/util/HostBuffer.h> #pragma warning(pop) #include "BrickedGrid.h" namespace Falcor { /** Voxel grid based on NanoVDB. */ class FALCOR_API Grid { public: using SharedPtr = std::shared_ptr<Grid>; /** Create a sphere voxel grid. \param[in] radius Radius of the sphere in world units. \param[in] voxelSize Size of a voxel in world units. \param[in] blendRange Range in voxels to blend from 0 to 1 (starting at surface inwards). \return A new grid. */ static SharedPtr createSphere(float radius, float voxelSize, float blendRange = 2.f); /** Create a box voxel grid. \param[in] width Width of the box in world units. \param[in] height Height of the box in world units. \param[in] depth Depth of the box in world units. \param[in] voxelSize Size of a voxel in world units. \param[in] blendRange Range in voxels to blend from 0 to 1 (starting at surface inwards). \return A new grid. */ static SharedPtr createBox(float width, float height, float depth, float voxelSize, float blendRange = 2.f); /** Create a grid from a file. Currently only OpenVDB and NanoVDB grids of type float are supported. \param[in] filename Filename of the grid. Can also include a full path or relative path from a data directory. \param[in] gridname Name of the grid to load. \return A new grid, or nullptr if the grid failed to load. */ static SharedPtr createFromFile(const std::string& filename, const std::string& gridname); /** Render the UI. */ void renderUI(Gui::Widgets& widget); /** Bind the grid to a given shader var. \param[in] var The shader variable to set the data into. */ void setShaderData(const ShaderVar& var); /** Get the minimum index stored in the grid. */ int3 getMinIndex() const; /** Get the maximum index stored in the grid. */ int3 getMaxIndex() const; /** Get the minimum value stored in the grid. */ float getMinValue() const; /** Get the maximum value stored in the grid. */ float getMaxValue() const; /** Get the total number of active voxels in the grid. */ uint64_t getVoxelCount() const; /** Get the size of the grid in bytes as allocated in GPU memory. */ uint64_t getGridSizeInBytes() const; /** Get the grid's bounds in world space. */ AABB getWorldBounds() const; /** Get a value stored in the grid. Note: This function is not safe for access from multiple threads. \param[in] ijk The index-space position to access the data from. */ float getValue(const int3& ijk) const; /** Get the raw NanoVDB grid handle. */ const nanovdb::GridHandle<nanovdb::HostBuffer>& getGridHandle() const; /** Get the (affine) NanoVDB transformation matrix. */ glm::mat4 getTransform() const; /** Get the inverse (affine) NanoVDB transformation matrix. */ glm::mat4 getInvTransform() const; private: Grid(nanovdb::GridHandle<nanovdb::HostBuffer> gridHandle); static SharedPtr createFromNanoVDBFile(const std::string& path, const std::string& gridname); static SharedPtr createFromOpenVDBFile(const std::string& path, const std::string& gridname); // Host data. nanovdb::GridHandle<nanovdb::HostBuffer> mGridHandle; nanovdb::FloatGrid* mpFloatGrid; nanovdb::FloatGrid::AccessorType mAccessor; // Device data. Buffer::SharedPtr mpBuffer; BrickedGrid mBrickedGrid; friend class SceneCache; }; }
NVIDIAGameWorks/Falcor
Source/Falcor/Scene/Volume/Grid.h
C
bsd-3-clause
5,780
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_101) on Sat Aug 20 05:41:48 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Class org.apache.solr.rest.ManagedResourceStorage.InMemoryStorageIO (Solr 6.2.0 API)</title> <meta name="date" content="2016-08-20"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.rest.ManagedResourceStorage.InMemoryStorageIO (Solr 6.2.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/solr/rest/ManagedResourceStorage.InMemoryStorageIO.html" title="class in org.apache.solr.rest">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/solr/rest/class-use/ManagedResourceStorage.InMemoryStorageIO.html" target="_top">Frames</a></li> <li><a href="ManagedResourceStorage.InMemoryStorageIO.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.solr.rest.ManagedResourceStorage.InMemoryStorageIO" class="title">Uses of Class<br>org.apache.solr.rest.ManagedResourceStorage.InMemoryStorageIO</h2> </div> <div class="classUseContainer">No usage of org.apache.solr.rest.ManagedResourceStorage.InMemoryStorageIO</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/solr/rest/ManagedResourceStorage.InMemoryStorageIO.html" title="class in org.apache.solr.rest">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/solr/rest/class-use/ManagedResourceStorage.InMemoryStorageIO.html" target="_top">Frames</a></li> <li><a href="ManagedResourceStorage.InMemoryStorageIO.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2016 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
berkeleybop/bbop-manager-golr
solr/docs/solr-core/org/apache/solr/rest/class-use/ManagedResourceStorage.InMemoryStorageIO.html
HTML
bsd-3-clause
5,257
.PHONY: all test dumpautoload all: test composer.phar: wget https://getcomposer.org/composer.phar chmod a+x ./composer.phar dumpautoload: composer.phar ./composer.phar dumpautoload test: composer.phar dumpautoload ./composer.phar test
john-whitley/seperate-eloquent-concerns
Makefile
Makefile
bsd-3-clause
243
Sedra CMS ========= This repository contains multiple modules to provide a basic CMS based on the [Sedra framework](https://github.com/matthieusieben/Sedra.framework). ## Installation First, you will need to checkout the [Sedra framework](https://github.com/matthieusieben/Sedra.framework) in your web directory. Next, open a terminal and `cd` to the `application` folder located at the root of the framework you just downloaded. Now move the `settings.example.php` to a temporary location mv settings.example.php ~/Desktop And then checkout the [Sedra CMS](https://github.com/matthieusieben/Sedra.cms) in the current directory: git clone git://github.com/matthieusieben/Sedra.cms.git . Move the settings file back: mv ~/Desktop/settings.example.php settings.php And add the following lines (dont forget to also setup your database settings). $config['modules']['page'] = TRUE; $config['modules']['home'] = TRUE; $config['modules']['blog'] = TRUE; $config['modules']['theme'] = FALSE; Navigate to `setup.php` to create the database and its content. Navigate to `index.php?q=account` and login using `admin@example.com`, `admin` as login and password, respectively. ## Licence See **LICENCE** file. ## Owner - Matthieu Sieben <http://goo.gl/OJ2ce>
matthieusieben/Sedra.cms
README.md
Markdown
bsd-3-clause
1,293
<?php error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT); /** * Bootstrap * * @category * @package BeardSite * @author Tim Marshall <Tim@CodingBeard.com> * @copyright (c) 2015, Tim Marshall * @license New BSD License */ use CodingBeard\ErrorHandler; use Phalcon\Loader; use Phalcon\Mvc\Application; try { $config = include __DIR__ . "/../app/config/config.php"; $router = include __DIR__ . "/../app/config/routes.php"; $loader = new Loader(); $loader->registerDirs($config->loader->dirs->toArray()); $loader->registerNamespaces($config->loader->namespaces->toArray()); $loader->register(); include __DIR__ . "/../vendor/autoload.php"; ErrorHandler::registerShutdown($config->application->showErrors); include __DIR__ . "/../app/config/services.php"; $application = new Application($di); $modules = []; foreach ($config->modules->files as $name => $path) { $modules[$name] = [ 'className' => "{$name}\Module", 'path' => $path ]; } $application->registerModules($modules); echo $application->handle()->getContent(); } catch (Exception $e) { ErrorHandler::handleException($e, $config->application->showErrors); }
CodingBeard/BeardSite
public/index.php
PHP
bsd-3-clause
1,230
<?php namespace Apps\Common\Enum; /** * 搜索数据的类型 * @package Apps\Common\Enum */ class SearchDataType { /** * 美容院 */ const BeautyParlors = 1; /** * 美容院服务项目 */ const BeautyParlorService = 2; /** * 活动 */ const Activity = 3; /** * 问答 */ const Question = 4; }
fu-tao/meelier_c2.0
common/enum/SearchDataType.php
PHP
bsd-3-clause
372
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ZNS.EliteTracker.Models.Documents { public class Comment : BaseDocument { public string DocumentId { get; set; } public CommanderRef Commander { get; set; } public string Body { get; set; } public DateTime Date { get; set; } [Raven.Imports.Newtonsoft.Json.JsonIgnore] public ICommentable Entity { get; set; } } }
ZNS/EliteTracker
ZNS.EliteTracker/Models/Documents/Comment.cs
C#
bsd-3-clause
471
/***************************************************************************** power_measurement_probe.hpp Functions to obtain energy and power consumption metrics This file belongs to the KisTA library All rights reserved by the authors (until further License definition) Author: F. Herrera Institution: UC Deparment: TEISA / GIM Date: 2016 March *****************************************************************************/ #ifndef KISTA_POWER_MEASUREMENT_PROBE_HPP #define KISTA_POWER_MEASUREMENT_PROBE_HPP #include "systemc.h" namespace kista { // -------------------------------------------------------------- // class for power measurement // -------------------------------------------------------------- // prototype for the function which allows to retrieve the consumed energy typedef double (*CONS_ENERGY_FUN_PTR)(); class power_measurement_probe:public sc_module { public: SC_HAS_PROCESS(power_measurement_probe); // constructor // name of the probe (shall be unique per probe) // pointer to the function which allows to retrieve the consumed energy until a specific time // averaging time (1 sec by default) // power_measurement_probe(sc_module_name name, CONS_ENERGY_FUN_PTR consumed_energy_J_f, sc_time av_period_par = sc_time(1,SC_SEC) ); // constructor with out name parameter (a unique name is assigned by default) // pointer to the function which allows to retrieve the consumed energy until a specific time // averaging time (1 sec by default) // power_measurement_probe(CONS_ENERGY_FUN_PTR consumed_energy_J_f, sc_time av_period_par = sc_time(1,SC_SEC) ); void set_averaging_time(sc_time av_time); // Average power as a result of total energy/simulated time // (can be called during simulation and at the end of the simulation) const double &get_total_average_power_W(); // Get the last calculated average power (energy/averaging time, 1s or the value settled by set_power_averaging_time) const double &get_average_power_W(); // Maximum value of the average power (similar to find the maximum load at average intervals and multiply by the peak power const double &get_peak_av_power_W(); void power_accounter_proc(); private: CONS_ENERGY_FUN_PTR get_consumed_energy_J_f; sc_time averaging_time; // accounting variables double curr_av_power_W; double peak_av_power_W; double total_average_power_watts; }; } // end namespace kista #endif
nandohca/kista
src/energy_power/power_measurement_probe.hpp
C++
bsd-3-clause
2,629
<?php /** * Copyright (c) 2011-present Mediasift Ltd * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the names of the copyright holders nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @category Libraries * @package Storyplayer/Injectables * @author Stuart Herbert <stuart.herbert@datasift.com> * @copyright 2011-present Mediasift Ltd www.datasift.com * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://datasift.github.io/storyplayer */ namespace DataSift\Storyplayer\Injectables; /** * determine our default system-under-test to test against * * @category Libraries * @package Storyplayer/Injectables * @author Stuart Herbert <stuart.herbert@datasift.com> * @copyright 2011-present Mediasift Ltd www.datasift.com * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://datasift.github.io/storyplayer */ trait DefaultSystemUnderTestName { public $defaultSystemUnderTestName; public function initDefaultSystemUnderTestName($injectables) { $entries = $injectables->knownSystemsUnderTestList->getEntries(); // special case - if there's only one defined, use that if (count($entries) == 1) { reset($entries); $this->defaultSystemUnderTestName = current($entries)->getName(); return; } // special case - is there one in the storyplayer.json[.dist] // config that we've already loaded? // do we have any defaults in the storyplayer.json file? $config = $injectables->storyplayerConfig; if (isset($config->defaults, $config->defaults->{'system-under-test'})) { $this->defaultSystemUnderTestName = $config->defaults->{'system-under-test'}; return; } // if we get here, then we do not know what the default should be $this->defaultSystemUnderTestName = null; } }
datasift/storyplayer
src/php/DataSift/Storyplayer/Injectables/DefaultSystemUnderTestName.php
PHP
bsd-3-clause
3,384
# Copyright 2015-2016, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. FROM ubuntu:14.04 # Install Git and basic packages. RUN apt-get update && apt-get install -y \ autoconf \ autotools-dev \ build-essential \ bzip2 \ ccache \ curl \ gcc \ gcc-multilib \ git \ golang \ gyp \ lcov \ libc6 \ libc6-dbg \ libc6-dev \ libgtest-dev \ libtool \ make \ perl \ strace \ python-dev \ python-setuptools \ python-yaml \ telnet \ unzip \ wget \ zip && apt-get clean #================ # Build profiling RUN apt-get update && apt-get install -y time && apt-get clean #================= # C++ dependencies RUN apt-get update && apt-get -y install libgflags-dev libgtest-dev libc++-dev clang && apt-get clean # Prepare ccache RUN ln -s /usr/bin/ccache /usr/local/bin/gcc RUN ln -s /usr/bin/ccache /usr/local/bin/g++ RUN ln -s /usr/bin/ccache /usr/local/bin/cc RUN ln -s /usr/bin/ccache /usr/local/bin/c++ RUN ln -s /usr/bin/ccache /usr/local/bin/clang RUN ln -s /usr/bin/ccache /usr/local/bin/clang++ #====================== # Zookeeper dependencies # TODO(jtattermusch): is zookeeper still needed? RUN apt-get install -y libzookeeper-mt-dev RUN mkdir /var/local/jenkins # Define the default command. CMD ["bash"]
VcamX/grpc
tools/dockerfile/test/cxx_ubuntu1404_x64/Dockerfile
Dockerfile
bsd-3-clause
2,724
<?php /** * Mend Library * * PHP version 5.3 * * @category Zend_Mend * @package View * @subpackage Helpers * @author Doug Hurst <dalan.hurst@gmail.com> * @copyright 2011 Doug Hurst * @license http://www.opensource.org/licenses/bsd-license New BSD License * @link http://github.com/dalanhurst/Zend_Mend */ /** * HTML5 Form Search Element View Helper * * @category Zend_Mend * @package View * @subpackage Helpers * @author Doug Hurst <dalan.hurst@gmail.com> * @copyright 2011 Doug Hurst * @license http://www.opensource.org/licenses/bsd-license New BSD License * @link http://github.com/dalanhurst/Zend_Mend */ class Mend_View_Helper_FormSearch extends Mend_View_Helper_FormHtml5Abstract { /** @staticvar HTML5_TYPE input[type] introduced by HTML5 **/ const HTML5_TYPE = 'search'; /** * Generates an input type='search' element * * @param string|array $name If a string, the element name. If an * array, all other parameters are ignored, and the array elements * are used in place of added parameters * @param mixed $value The element value * @param array $attribs Attributes for the element tag * * @return string The element HTML. */ public function formSearch($name, $value = null, $attribs = null) { return parent::formHtml5($name, $value, $attribs); } }
ranjithinnergys/Zend_Mend
library/Mend/View/Helper/FormSearch.php
PHP
bsd-3-clause
1,423
{-# LANGUAGE CPP #-} #include "overlapping-compat.h" module Servant.ForeignSpec where import Data.Monoid ((<>)) import Data.Proxy import Servant.Foreign import Test.Hspec spec :: Spec spec = describe "Servant.Foreign" $ do camelCaseSpec listFromAPISpec camelCaseSpec :: Spec camelCaseSpec = describe "camelCase" $ do it "converts FunctionNames to camelCase" $ do camelCase (FunctionName ["post", "counter", "inc"]) `shouldBe` "postCounterInc" camelCase (FunctionName ["get", "hyphen-ated", "counter"]) `shouldBe` "getHyphenatedCounter" ---------------------------------------------------------------------- data LangX instance HasForeignType LangX String NoContent where typeFor _ _ _ = "voidX" instance HasForeignType LangX String Int where typeFor _ _ _ = "intX" instance HasForeignType LangX String Bool where typeFor _ _ _ = "boolX" instance OVERLAPPING_ HasForeignType LangX String String where typeFor _ _ _ = "stringX" instance OVERLAPPABLE_ HasForeignType LangX String a => HasForeignType LangX String [a] where typeFor lang ftype _ = "listX of " <> typeFor lang ftype (Proxy :: Proxy a) type TestApi = "test" :> Header "header" [String] :> QueryFlag "flag" :> Get '[JSON] Int :<|> "test" :> QueryParam "param" Int :> ReqBody '[JSON] [String] :> Post '[JSON] NoContent :<|> "test" :> QueryParams "params" Int :> ReqBody '[JSON] String :> Put '[JSON] NoContent :<|> "test" :> Capture "id" Int :> Delete '[JSON] NoContent :<|> "test" :> CaptureAll "ids" Int :> Get '[JSON] [Int] testApi :: [Req String] testApi = listFromAPI (Proxy :: Proxy LangX) (Proxy :: Proxy String) (Proxy :: Proxy TestApi) listFromAPISpec :: Spec listFromAPISpec = describe "listFromAPI" $ do it "generates 4 endpoints for TestApi" $ do length testApi `shouldBe` 5 let [getReq, postReq, putReq, deleteReq, captureAllReq] = testApi it "collects all info for get request" $ do shouldBe getReq $ defReq { _reqUrl = Url [ Segment $ Static "test" ] [ QueryArg (Arg "flag" "boolX") Flag ] , _reqMethod = "GET" , _reqHeaders = [HeaderArg $ Arg "header" "listX of stringX"] , _reqBody = Nothing , _reqReturnType = Just "intX" , _reqFuncName = FunctionName ["get", "test"] } it "collects all info for post request" $ do shouldBe postReq $ defReq { _reqUrl = Url [ Segment $ Static "test" ] [ QueryArg (Arg "param" "intX") Normal ] , _reqMethod = "POST" , _reqHeaders = [] , _reqBody = Just "listX of stringX" , _reqReturnType = Just "voidX" , _reqFuncName = FunctionName ["post", "test"] } it "collects all info for put request" $ do shouldBe putReq $ defReq { _reqUrl = Url [ Segment $ Static "test" ] -- Shoud this be |intX| or |listX of intX| ? [ QueryArg (Arg "params" "listX of intX") List ] , _reqMethod = "PUT" , _reqHeaders = [] , _reqBody = Just "stringX" , _reqReturnType = Just "voidX" , _reqFuncName = FunctionName ["put", "test"] } it "collects all info for delete request" $ do shouldBe deleteReq $ defReq { _reqUrl = Url [ Segment $ Static "test" , Segment $ Cap (Arg "id" "intX") ] [] , _reqMethod = "DELETE" , _reqHeaders = [] , _reqBody = Nothing , _reqReturnType = Just "voidX" , _reqFuncName = FunctionName ["delete", "test", "by", "id"] } it "collects all info for capture all request" $ do shouldBe captureAllReq $ defReq { _reqUrl = Url [ Segment $ Static "test" , Segment $ Cap (Arg "ids" "listX of intX") ] [] , _reqMethod = "GET" , _reqHeaders = [] , _reqBody = Nothing , _reqReturnType = Just "listX of intX" , _reqFuncName = FunctionName ["get", "test", "by", "ids"] }
zerobuzz/servant
servant-foreign/test/Servant/ForeignSpec.hs
Haskell
bsd-3-clause
4,035
package edu.ucdenver.ccp.common.file; /* * #%L * Colorado Computational Pharmacology's common module * %% * Copyright (C) 2012 - 2014 Regents of the University of Colorado * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ import java.io.File; import java.io.FileFilter; import java.util.Collection; import java.util.Set; import java.util.TreeSet; import org.apache.commons.io.filefilter.IOFileFilter; public class FileListFilter implements IOFileFilter { private final Set<String> filenameSet; public FileListFilter(Collection<String> list) { filenameSet = new TreeSet<String>(); filenameSet.addAll(list); } @Override public boolean accept(File arg0) { return filenameSet.contains(arg0.getName()); } /** * ...ignores the directory. Could be a bug... */ @Override public boolean accept(File arg0, String arg1) { return filenameSet.contains(arg1); } }
UCDenver-ccp/common
src/main/java/edu/ucdenver/ccp/common/file/FileListFilter.java
Java
bsd-3-clause
2,389
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>mne.write_bem_solution &#8212; MNE 0.20.7 documentation</title> <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/bootstrap_divs.css" /> <link rel="stylesheet" type="text/css" href="../_static/gallery.css" /> <link rel="stylesheet" type="text/css" href="../_static/gallery-binder.css" /> <link rel="stylesheet" type="text/css" href="../_static/gallery-dataframe.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script src="../_static/bootstrap_divs.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="canonical" href="https://mne.tools/stable/index.html" /> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-37225609-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <link rel="stylesheet" href="../_static/style.css " type="text/css" /> <link rel="stylesheet" href="../_static/font-awesome.css" type="text/css" /> <link rel="stylesheet" href="../_static/font-source-code-pro.css" type="text/css" /> <link rel="stylesheet" href="../_static/font-source-sans-pro.css" type="text/css" /> <link rel="stylesheet" href="../_static/flag-icon.css" type="text/css" /> <script type="text/javascript"> !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s); js.id=id;js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); </script> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'> <meta name="apple-mobile-web-app-capable" content="yes"> <script type="text/javascript" src="../_static/js/jquery-1.11.0.min.js "></script> <script type="text/javascript" src="../_static/js/jquery-fix.js "></script> <script type="text/javascript" src="../_static/bootstrap-3.3.7/js/bootstrap.min.js "></script> <script type="text/javascript" src="../_static/bootstrap-sphinx.js "></script> </head><body> <div id="navbar" class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <!-- .btn-navbar is used as the toggle for collapsed navbar content --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"><span><img src="../_static/mne_logo_small.png"></span> </a> <span class="navbar-text navbar-version pull-left"><b>0.20.7</b></span> </div> <div class="collapse navbar-collapse nav-collapse"> <ul class="nav navbar-nav"> <li><a href="../install/index.html">Install</a></li> <li><a href="../overview/index.html">Overview</a></li> <li><a href="../auto_tutorials/index.html">Tutorials</a></li> <li><a href="../auto_examples/index.html">Examples</a></li> <li><a href="../glossary.html">Glossary</a></li> <li><a href="../python_reference.html">API</a></li> <li><a href="../install/contributing.html">Contribute</a></li> <li class="dropdown globaltoc-container"> <a role="button" id="dLabelGlobalToc" data-toggle="dropdown" data-target="#" href="../index.html">Site <b class="caret"></b></a> <ul class="dropdown-menu globaltoc" role="menu" aria-labelledby="dLabelGlobalToc"></ul> </li> <li class="hidden-sm"></li> </ul> <div class="navbar-form navbar-right navbar-btn dropdown btn-group-sm" style="margin-left: 20px; margin-top: 5px; margin-bottom: 5px"> <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown"> v0.20.7 <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="https://mne-tools.github.io/dev/index.html">Development</a></li> <li><a href="https://mne-tools.github.io/stable/index.html">v0.20 (stable)</a></li> <li><a href="https://mne-tools.github.io/0.19/index.html">v0.19</a></li> <li><a href="https://mne-tools.github.io/0.18/index.html">v0.18</a></li> <li><a href="https://mne-tools.github.io/0.17/index.html">v0.17</a></li> <li><a href="https://mne-tools.github.io/0.16/index.html">v0.16</a></li> <li><a href="https://mne-tools.github.io/0.15/index.html">v0.15</a></li> <li><a href="https://mne-tools.github.io/0.14/index.html">v0.14</a></li> <li><a href="https://mne-tools.github.io/0.13/index.html">v0.13</a></li> <li><a href="https://mne-tools.github.io/0.12/index.html">v0.12</a></li> <li><a href="https://mne-tools.github.io/0.11/index.html">v0.11</a></li> </ul> </div> <form class="navbar-form navbar-right" action="../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> </div> <div class="container"> <div class="row"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <p class="logo"><a href="../index.html"> <img class="logo" src="../_static/mne_logo_small.png" alt="Logo"/> </a></p><ul> <li><a class="reference internal" href="#">mne.write_bem_solution</a></li> </ul> <form action="../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="body col-md-12 content" role="main"> <div class="section" id="mne-write-bem-solution"> <h1>mne.write_bem_solution<a class="headerlink" href="#mne-write-bem-solution" title="Permalink to this headline">¶</a></h1> <dl class="py function"> <dt id="mne.write_bem_solution"> <code class="sig-prename descclassname">mne.</code><code class="sig-name descname">write_bem_solution</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">fname</span></em>, <em class="sig-param"><span class="n">bem</span></em><span class="sig-paren">)</span><a class="reference external" href="http://github.com/mne-tools/mne-python/blob/maint/0.20/mne/bem.py#L1538-L1568"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#mne.write_bem_solution" title="Permalink to this definition">¶</a></dt> <dd><p>Write a BEM model with solution.</p> <dl class="field-list"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl> <dt><strong>fname</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a></span></dt><dd><p>The filename to use.</p> </dd> <dt><strong>bem</strong><span class="classifier">instance of <a class="reference internal" href="mne.bem.ConductorModel.html#mne.bem.ConductorModel" title="mne.bem.ConductorModel"><code class="xref py py-obj docutils literal notranslate"><span class="pre">ConductorModel</span></code></a></span></dt><dd><p>The BEM model with solution to save.</p> </dd> </dl> </dd> </dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference internal" href="mne.read_bem_solution.html#mne.read_bem_solution" title="mne.read_bem_solution"><code class="xref py py-obj docutils literal notranslate"><span class="pre">read_bem_solution</span></code></a></dt><dd></dd> </dl> </div> </dd></dl> <div style='clear:both'></div></div> </div> </div> </div> <footer class="footer"> <div class="container institutions"> <a href="https://www.massgeneral.org/"><img class="institution_lg" src="../_static/institution_logos/MGH.svg" title="Massachusetts General Hospital" alt="Massachusetts General Hospital"/></a> <a href="https://martinos.org/"><img class="institution_lg" src="../_static/institution_logos/Martinos.png" title="Athinoula A. Martinos Center for Biomedical Imaging" alt="Athinoula A. Martinos Center for Biomedical Imaging"/></a> <a href="https://hms.harvard.edu/"><img class="institution_lg" src="../_static/institution_logos/Harvard.png" title="Harvard Medical School" alt="Harvard Medical School"/></a> <a href="https://web.mit.edu/"><img class="institution_sm" src="../_static/institution_logos/MIT.svg" title="Massachusetts Institute of Technology" alt="Massachusetts Institute of Technology"/></a> <a href="https://www.nyu.edu/"><img class="institution_md" src="../_static/institution_logos/NYU.png" title="New York University" alt="New York University"/></a> <a href="http://www.cea.fr/"><img class="institution_md" src="../_static/institution_logos/CEA.png" title="Commissariat à l´énergie atomique et aux énergies alternatives" alt="Commissariat à l´énergie atomique et aux énergies alternatives"/></a> <a href="https://sci.aalto.fi/"><img class="institution_md" src="../_static/institution_logos/Aalto.svg" title="Aalto-yliopiston perustieteiden korkeakoulu" alt="Aalto-yliopiston perustieteiden korkeakoulu"/></a> <a href="https://www.telecom-paris.fr/"><img class="institution_md" src="../_static/institution_logos/Telecom_Paris_Tech.png" title="Télécom ParisTech" alt="Télécom ParisTech"/></a> <a href="https://www.washington.edu/"><img class="institution_sm" src="../_static/institution_logos/Washington.png" title="University of Washington" alt="University of Washington"/></a> <a href="https://icm-institute.org/"><img class="institution_lg" src="../_static/institution_logos/ICM.jpg" title="Institut du Cerveau et de la Moelle épinière" alt="Institut du Cerveau et de la Moelle épinière"/></a> <a href="https://www.bu.edu/"><img class="institution_sm" src="../_static/institution_logos/BU.svg" title="Boston University" alt="Boston University"/></a> <a href="https://www.inserm.fr/"><img class="institution_xs" src="../_static/institution_logos/Inserm.svg" title="Institut national de la santé et de la recherche médicale" alt="Institut national de la santé et de la recherche médicale"/></a> <a href="https://www.fz-juelich.de/"><img class="institution_sm" src="../_static/institution_logos/Julich.svg" title="Forschungszentrum Jülich" alt="Forschungszentrum Jülich"/></a> <a href="https://www.tu-ilmenau.de/"><img class="institution_sm" src="../_static/institution_logos/Ilmenau.gif" title="Technische Universität Ilmenau" alt="Technische Universität Ilmenau"/></a> <a href="https://bids.berkeley.edu/"><img class="institution_md" src="../_static/institution_logos/BIDS.png" title="Berkeley Institute for Data Science" alt="Berkeley Institute for Data Science"/></a> <a href="https://www.inria.fr/"><img class="institution_sm" src="../_static/institution_logos/inria.png" title="Institut national de recherche en informatique et en automatique" alt="Institut national de recherche en informatique et en automatique"/></a> <a href="https://www.au.dk/"><img class="institution_sm" src="../_static/institution_logos/Aarhus.png" title="Aarhus Universitet" alt="Aarhus Universitet"/></a> <a href="https://www.uni-graz.at/"><img class="institution_md" src="../_static/institution_logos/Graz.jpg" title="Karl-Franzens-Universität Graz" alt="Karl-Franzens-Universität Graz"/></a> </div> <div class="container"> <ul class="list-inline"> <li><a href="https://github.com/mne-tools/mne-python">GitHub</a></li> <li>·</li> <li><a href="https://mail.nmr.mgh.harvard.edu/mailman/listinfo/mne_analysis">Mailing list</a></li> <li>·</li> <li><a href="https://gitter.im/mne-tools/mne-python">Gitter</a></li> <li>·</li> <li><a href="../whats_new.html">What's new</a></li> <li>·</li> <li><a href="../overview/cite.html">Cite MNE</a></li> <li class="pull-right"><a href="#">Back to top</a></li> </ul> <p>&copy; Copyright 2012-2020, MNE Developers. Last updated on 2020-07-10.</p> </div> </footer> <script src="https://mne.tools/versionwarning.js"></script> </body> </html>
mne-tools/mne-tools.github.io
0.20/generated/mne.write_bem_solution.html
HTML
bsd-3-clause
14,472
/* * JavaCL - Java API and utilities for OpenCL * http://javacl.googlecode.com/ * * Copyright (c) 2009-2015, Olivier Chafik (http://ochafik.com/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Olivier Chafik nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.nativelibs4java.opencl; import com.nativelibs4java.opencl.CLImageFormat.ChannelOrder; import com.nativelibs4java.opencl.CLImageFormat.ChannelDataType; import com.nativelibs4java.util.NIOUtils; import java.awt.Image; import java.awt.Rectangle; import java.awt.image.*; import java.nio.*; import static com.nativelibs4java.opencl.ImageIOUtils.ImageInfo.*; /** * No apparent correspondance with any OpenCL image type for the following BufferedImage types : * TYPE_3BYTE_BGR * TYPE_4BYTE_ABGR (support only argb or bgra : need to see if endian-magic can help...) * TYPE_4BYTE_ABGR_PRE (no support for pre-multiplied channels) * TYPE_BYTE_BINARY * TYPE_BYTE_INDEXED * TYPE_CUSTOM * TYPE_INT_ARGB_PRE (no support for pre-multiplied channels) * TYPE_INT_BGR * TYPE_INT_RGB (no support for UnsignedInt8 channel data type) * TYPE_USHORT_555_RGB * TYPE_USHORT_565_RGB */ class ImageIOUtils { public static class ImageInfo<I extends Image> { public final int bufferedImageType; public final CLImageFormat clImageFormat; //public final int width, height; public final ImageDataGetter<I> dataGetter; public final ImageDataSetter<I> dataSetter; public final Class<? extends Buffer> bufferClass; public final Class<?> bufferElementsClass; public final int channelCount; public final int pixelByteSize; public ImageInfo( int bufferedImageType, CLImageFormat clImageFormat, ImageDataGetter dataGetter, ImageDataSetter dataSetter, Class<? extends Buffer> bufferClass, Class<?> bufferElementsClass, int channelCount, int pixelByteSize) { this.bufferedImageType = bufferedImageType; this.clImageFormat = clImageFormat; this.dataGetter = dataGetter; this.dataSetter = dataSetter; this.bufferClass = bufferClass; this.bufferElementsClass = bufferElementsClass; this.channelCount = channelCount; this.pixelByteSize = pixelByteSize; } public interface ImageDataGetter<I extends Image> { Buffer getData(I image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder); } public interface ImageDataSetter<I extends Image> { void setData(I image, Buffer data, boolean allowDeoptimizingDirectWrite); } } public static ImageInfo<Image> getGenericImageInfo() { return new ImageInfo<Image>( 0, CLImageFormat.INT_ARGB_FORMAT, new ImageDataGetter<Image>() { public Buffer getData(Image image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { int[] intData = null; int width = image.getWidth(null), height = image.getHeight(null); PixelGrabber grabber = new PixelGrabber(image, 0, 0, width, height, true); try { grabber.grabPixels(); intData = (int[])grabber.getPixels(); } catch (InterruptedException ex) { throw new RuntimeException("Pixel read operation was interrupted", ex); } IntBuffer output = IntBuffer.wrap(intData); if (directBuffer) return NIOUtils.directCopy(output, byteOrder); else return output; } }, new ImageDataSetter() { public void setData(Image image, Buffer data, boolean allowDeoptimizingDirectWrite) { if (!(image instanceof BufferedImage)) throw new UnsupportedOperationException("Image must be a BufferedImage"); BufferedImage bufferedImage = (BufferedImage)image; int width = bufferedImage.getWidth(), height = bufferedImage.getHeight(); WritableRaster raster = checkWritableRaster(bufferedImage); IntBuffer input = checkBuffer(data, IntBuffer.class); int[] intData = input.array(); if (intData == null) { intData = new int[width * height]; input.get(intData); } raster.setPixels(0, 0, width, height, intData); } }, IntBuffer.class, Integer.class, 1, 4 ); } static void checkSinglePixelPackedSampleModel(Raster raster) { if (raster.getNumDataElements() != 1) throw new IllegalArgumentException("Raster has " + raster.getNumBands() + " data elements, should have only 1 !"); //SampleModel sampleModel = raster.getSampleModel(); //if (!(sampleModel instanceof SinglePixelPackedSampleModel)) // throw new IllegalArgumentException("Expected SinglePixelPackedSampleModel, got " + sampleModel.getClass().getName()); //return (SinglePixelPackedSampleModel)sampleModel; } static <DB extends DataBuffer> DB checkDataBuffer(Raster raster, Class<DB> dbType) { DataBuffer dataBuffer = raster.getDataBuffer(); if (!dbType.isInstance(dataBuffer)) throw new IllegalArgumentException("Expected " + dbType.getName() + ", got " + (dataBuffer == null ? null : dataBuffer.getClass().getName())); return (DB)dataBuffer; } static <B extends Buffer> B checkBuffer(Buffer buffer, Class<B> bType) { if (!bType.isInstance(buffer)) throw new IllegalArgumentException("Expected " + bType.getName() + ", got " + (buffer == null ? null : buffer.getClass().getName())); return (B)buffer; } static WritableRaster checkWritableRaster(BufferedImage image) { Raster raster = image.getRaster(); if (!(raster instanceof WritableRaster)) throw new UnsupportedOperationException("Image data is not writable"); return (WritableRaster)raster; } public static ImageInfo<BufferedImage> getShortGrayImageInfo() { return new ImageInfo<BufferedImage>( BufferedImage.TYPE_USHORT_GRAY, new CLImageFormat(CLImageFormat.ChannelOrder.LUMINANCE, CLImageFormat.ChannelDataType.UNormInt16), new ImageDataGetter<BufferedImage>() { public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { int width = image.getWidth(), height = image.getHeight(); WritableRaster raster = checkWritableRaster(image); checkSinglePixelPackedSampleModel(raster); short[] existingArray = getIndirectArray(optionalExistingOutput, width * height, short[].class); short[] array; ShortBuffer output = null; if (!allowDeoptimizingDirectRead || isSubRaster(raster)) array = (short[])raster.getDataElements(0, 0, width, height, existingArray); else { array = checkDataBuffer(raster, DataBufferShort.class).getData(); if (optionalExistingOutput instanceof ShortBuffer) { output = (ShortBuffer)optionalExistingOutput; if (output != null && output.capacity() == width * height) { if (!output.isDirect()) System.arraycopy(array, 0, output.array(), 0, width * height); else { output.duplicate().put(array); } } } } if (output == null) output = ShortBuffer.wrap(array); return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; } }, new ImageDataSetter<BufferedImage>() { public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { int width = image.getWidth(), height = image.getHeight(); WritableRaster raster = checkWritableRaster(image); checkSinglePixelPackedSampleModel(raster); ShortBuffer input = checkBuffer(inputBuffer, ShortBuffer.class); short[] inputArray = input.isDirect() ? null : input.array(); if (allowDeoptimizingDirectWrite) { if (input.isDirect()) { short[] outputArray = checkDataBuffer(raster, DataBufferShort.class).getData(); ShortBuffer.wrap(outputArray).put(input.duplicate()); return; } } if (inputArray == null) { inputArray = new short[width * height]; input.duplicate().get(inputArray); } raster.setDataElements(0, 0, width, height, inputArray); } }, ShortBuffer.class, Short.class, 1, 2 ); } /** * Image stored in TYPE_USHORT_GRAY BufferedImages but in ChannelOrder.RGBA/BGRA + ChannelDataType.short */ public static ImageInfo<BufferedImage> getARGBShortGrayImageInfo(CLImageFormat format) { return new ImageInfo<BufferedImage>( BufferedImage.TYPE_USHORT_GRAY, format, new ImageDataGetter<BufferedImage>() { public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { int width = image.getWidth(), height = image.getHeight(); WritableRaster raster = checkWritableRaster(image); checkSinglePixelPackedSampleModel(raster); int length = width * height; short[] existingArray = getIndirectArray(optionalExistingOutput, length, short[].class); short[] array = (short[])raster.getDataElements(0, 0, width, height, existingArray); ShortBuffer output = null; if (optionalExistingOutput instanceof ShortBuffer) { output = (ShortBuffer)optionalExistingOutput; if (output.capacity() != length * 4) output = null; } if (output == null) output = NIOUtils.directShorts(length * 4, byteOrder); for (int i = 0; i < length; i++) { int offset = i * 4; short value = array[i]; output.put(offset, value); output.put(offset + 1, value); output.put(offset + 2, value); output.put(offset + 3, (short)0xffff); } return output; } }, new ImageDataSetter<BufferedImage>() { public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { int width = image.getWidth(), height = image.getHeight(); WritableRaster raster = checkWritableRaster(image); checkSinglePixelPackedSampleModel(raster); ShortBuffer input = checkBuffer(inputBuffer, ShortBuffer.class); int length = width * height; short[] data = new short[length]; short[] four = new short[4]; for (int i = 0; i < length; i++) { int offset = i * 4; int a = input.get(offset); int b = input.get(offset + 1); int c = input.get(offset + 2); int alpha = input.get(offset + 3); // TODO multiply by ALPHA ??? data[i] = (short)((a + b + c) / 3); } raster.setDataElements(0, 0, width, height, data); } }, ShortBuffer.class, Short.class, 4, 4 * 2 ); } public static ImageInfo<BufferedImage> getByteGrayImageInfo() { return new ImageInfo<BufferedImage>( BufferedImage.TYPE_BYTE_GRAY, new CLImageFormat(CLImageFormat.ChannelOrder.LUMINANCE, CLImageFormat.ChannelDataType.SignedInt8), new ImageDataGetter<BufferedImage>() { public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { int width = image.getWidth(), height = image.getHeight(); WritableRaster raster = checkWritableRaster(image); checkSinglePixelPackedSampleModel(raster); byte[] existingArray = getIndirectArray(optionalExistingOutput, width * height, byte[].class); byte[] array; ByteBuffer output = null; if (!allowDeoptimizingDirectRead || isSubRaster(raster)) array = (byte[])raster.getDataElements(0, 0, width, height, existingArray); else { array = checkDataBuffer(raster, DataBufferByte.class).getData(); if (optionalExistingOutput instanceof ByteBuffer) { output = (ByteBuffer)optionalExistingOutput; if (output != null && output.capacity() == width * height) { if (!output.isDirect()) System.arraycopy(array, 0, output.array(), 0, width * height); else { output.duplicate().put(array); } } } } if (output == null) output = ByteBuffer.wrap(array); return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; } }, new ImageDataSetter<BufferedImage>() { public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { int width = image.getWidth(), height = image.getHeight(); WritableRaster raster = checkWritableRaster(image); checkSinglePixelPackedSampleModel(raster); ByteBuffer input = checkBuffer(inputBuffer, ByteBuffer.class); byte[] inputArray = input.isDirect() ? null : input.array(); if (allowDeoptimizingDirectWrite) { if (input.isDirect()) { byte[] outputArray = checkDataBuffer(raster, DataBufferByte.class).getData(); ByteBuffer.wrap(outputArray).put(input.duplicate()); return; } } if (inputArray == null) { inputArray = new byte[width * height]; input.duplicate().get(inputArray); } raster.setDataElements(0, 0, width, height, inputArray); } }, ByteBuffer.class, Byte.class, 1, 1 ); } static <A> A getIndirectArray(Buffer buffer, int length, Class<A> arrayClass) { if (buffer instanceof IntBuffer && arrayClass == int[].class) return (A)((IntBuffer)buffer).array(); if (buffer instanceof ShortBuffer && arrayClass == short[].class) return (A)((ShortBuffer)buffer).array(); if (buffer instanceof ByteBuffer && arrayClass == byte[].class) return (A)((ByteBuffer)buffer).array(); if (buffer instanceof FloatBuffer && arrayClass == float[].class) return (A)((FloatBuffer)buffer).array(); if (buffer instanceof LongBuffer && arrayClass == long[].class) return (A)((LongBuffer)buffer).array(); if (buffer instanceof DoubleBuffer && arrayClass == double[].class) return (A)((DoubleBuffer)buffer).array(); if (buffer instanceof CharBuffer && arrayClass == char[].class) return (A)((CharBuffer)buffer).array(); return null; } public static boolean isSubRaster(Raster raster) { Rectangle bounds = raster.getBounds(); return raster.getParent() != null || bounds.x != 0 || bounds.y != 0; } public static ImageInfo<BufferedImage> getIntARGBImageInfo() { return new ImageInfo<BufferedImage>( BufferedImage.TYPE_INT_ARGB, CLImageFormat.INT_ARGB_FORMAT, new ImageDataGetter<BufferedImage>() { public Buffer getData(BufferedImage image, Buffer optionalExistingOutput, boolean directBuffer, boolean allowDeoptimizingDirectRead, ByteOrder byteOrder) { int width = image.getWidth(), height = image.getHeight(); WritableRaster raster = checkWritableRaster(image); checkSinglePixelPackedSampleModel(raster); int[] existingArray = getIndirectArray(optionalExistingOutput, width * height, int[].class); int[] array; IntBuffer output = null; if (!allowDeoptimizingDirectRead || isSubRaster(raster)) array = (int[])raster.getDataElements(0, 0, width, height, existingArray); else { array = checkDataBuffer(raster, DataBufferInt.class).getData(); if (optionalExistingOutput instanceof IntBuffer) { output = (IntBuffer)optionalExistingOutput; if (output != null && output.capacity() == width * height) { if (output.array() != null) System.arraycopy(array, 0, output.array(), 0, width * height); else { output.duplicate().put(array); } } } } if (output == null) output = IntBuffer.wrap(array); return directBuffer && !output.isDirect() ? NIOUtils.directCopy(output, byteOrder) : output; } }, new ImageDataSetter<BufferedImage>() { public void setData(BufferedImage image, Buffer inputBuffer, boolean allowDeoptimizingDirectWrite) { int width = image.getWidth(), height = image.getHeight(); WritableRaster raster = checkWritableRaster(image); checkSinglePixelPackedSampleModel(raster); IntBuffer input = checkBuffer(inputBuffer, IntBuffer.class); int[] inputArray = input.isDirect() ? null : input.array(); if (allowDeoptimizingDirectWrite) { if (input.isDirect()) { int[] outputArray = checkDataBuffer(raster, DataBufferInt.class).getData(); IntBuffer.wrap(outputArray).put(input.duplicate()); return; } } if (inputArray == null) { inputArray = new int[width * height]; input.duplicate().get(inputArray); } raster.setDataElements(0, 0, width, height, inputArray); } }, IntBuffer.class, Integer.class, 1, 4 ); } public static ImageInfo<?> getImageInfo(Image image) { if (image instanceof BufferedImage) return getBufferedImageInfo(((BufferedImage)image).getType()); return getGenericImageInfo(); } public static ImageInfo<BufferedImage> getBufferedImageInfo(int bufferedImageType) { switch (bufferedImageType) { case BufferedImage.TYPE_INT_ARGB: return getIntARGBImageInfo(); case BufferedImage.TYPE_BYTE_GRAY: return getByteGrayImageInfo(); case BufferedImage.TYPE_USHORT_GRAY: return getShortGrayImageInfo(); default: return (ImageInfo)getGenericImageInfo(); } } public static ImageInfo<BufferedImage> getBufferedImageInfo(CLImageFormat imageFormat) { if (imageFormat == null || imageFormat.getChannelOrder() == null || imageFormat.getChannelDataType() == null) return null; switch (imageFormat.getChannelOrder()) { case BGRA: case RGBA: switch (imageFormat.getChannelDataType()) { case UNormInt16: case UnsignedInt16: case SignedInt16: return getARGBShortGrayImageInfo(imageFormat); } } return getBufferedImageInfo(getBufferedImageType(imageFormat)); } static int getBufferedImageType(CLImageFormat imageFormat) { if (imageFormat == null || imageFormat.getChannelOrder() == null || imageFormat.getChannelDataType() == null) return 0; switch (imageFormat.getChannelOrder()) { case INTENSITY: case LUMINANCE: switch (imageFormat.getChannelDataType()) { case UNormInt8: case UnsignedInt8: case SignedInt8: return BufferedImage.TYPE_BYTE_GRAY; case UnsignedInt16: case UNormInt16: case SignedInt16: return BufferedImage.TYPE_USHORT_GRAY; default: return 0; } case ARGB: case BGRA: case RGBA: switch (imageFormat.getChannelDataType()) { case UNormInt8: case UnsignedInt8: case SignedInt8: return BufferedImage.TYPE_INT_ARGB; default: return 0; } case RGB: switch (imageFormat.getChannelDataType()) { case UNormInt8: case UnsignedInt8: case SignedInt8: return BufferedImage.TYPE_INT_BGR; default: return 0; } case RGBx: default: return 0; } } }
a260749110/javacl_deepLearn
Core/target/generated-sources/main/com/nativelibs4java/opencl/ImageIOUtils.java
Java
bsd-3-clause
23,534
<?php class Functor { public function __construct($fmap) { $this->fmap = $fmap; } } class Applicative { public function __construct($pure, $ap, $Functor) { $this->pure = $pure; $this->ap = $ap; $this->Functor = $Functor; } } class Monad { public function __construct($bind, $Applicative) { $this->bind = $bind; $this->Applicative = $Applicative; } } $liftM2 = function($dict111) { return function($f) use ($dict111) { return function($ma) use ($dict111, $f) { return function($mb) use ($dict111, $f, $ma) { return ($dict111->bind)($ma)(function($a) use ($dict111, $f, $ma, $mb) { return ($dict111->bind)($mb)(function($b) use ($a, $dict111, $f, $ma, $mb) { return ($dict111->Applicative->pure)($f($a)($b)); }); }); }; }; }; }; class NothingCon { public function __construct() { $this->values = array(); } } $Nothing = new NothingCon(); class JustCon { public function __construct($a1) { $this->values = array($a1); } } $Just = function($a1) { return new JustCon($a1); }; $functorMaybe = new Functor(function($f) use ($Just, $Nothing) { return function($ma) use ($Just, $Nothing, $f) { return (function() use ($Just, $Nothing, $f, $ma) { if ($ma instanceof NothingCon) { return $Nothing; } if ($ma instanceof JustCon) { $a = $ma->values[0]; return $Just($f($a)); } })(); }; }); $applicativeMaybe = new Applicative($Just, function($mf) use ($Just, $Nothing) { return function($ma) use ($Just, $Nothing, $mf) { return (function() use ($Just, $Nothing, $ma, $mf) { if ($mf instanceof NothingCon) { return $Nothing; } if ($mf instanceof JustCon) { $f = $mf->values[0]; return (function() use ($Just, $Nothing, $f, $ma, $mf) { if ($ma instanceof NothingCon) { return $Nothing; } if ($ma instanceof JustCon) { $a = $ma->values[0]; return $Just($f($a)); } })(); } })(); }; }, $functorMaybe); $monadMaybe = new Monad(function($ma) use ($Just, $Nothing, $functorMaybe) { return function($f) use ($Just, $Nothing, $functorMaybe, $ma) { return (function() use ($Just, $Nothing, $f, $functorMaybe, $ma) { if ($ma instanceof NothingCon) { return $Nothing; } if ($ma instanceof JustCon) { $a = $ma->values[0]; return $f($a); } })(); }; }, $applicativeMaybe); $and = function($a) { return function($b) use ($a) { return (function() use ($a, $b) { if ($a === true) { return $b; } return false; })(); }; }; class Show { public function __construct($show) { $this->show = $show; } } $showBool = new Show(function($a) { return (function() use ($a) { if ($a === true) { return "true"; } if ($a === false) { return "false"; } })(); }); $showMaybe = function($dictShow) { return new Show(function($a) use ($dictShow) { return (function() use ($a, $dictShow) { if ($a instanceof NothingCon) { return "Nothing"; } if ($a instanceof JustCon) { $a = $a->values[0]; return ($dictShow->show)($a); } })(); }); }; $not = function($a) { return (function() use ($a) { if ($a === true) { return false; } return true; })(); }; $asdf = function($dict396) use ($and, $liftM2, $not) { return function($a) use ($and, $dict396, $liftM2, $not) { return function($b) use ($a, $and, $dict396, $liftM2, $not) { return ($dict396->Applicative->Functor->fmap)($not)($liftM2($dict396)($and)($a)($b)); }; }; }; $test = ($showMaybe($showBool)->show)($asdf($monadMaybe)($Just(true))($Just(true))); ?>
LightAndLight/hindley-milner
test/files/monad.lam.php
PHP
bsd-3-clause
4,405
/* * Copyright (c) 1997 - 2006 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "kadm5_locl.h" #include <sys/types.h> #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif RCSID("$Id$"); static void set_funcs(kadm5_client_context *c) { #define SET(C, F) (C)->funcs.F = kadm5 ## _c_ ## F SET(c, chpass_principal); SET(c, chpass_principal_with_key); SET(c, create_principal); SET(c, delete_principal); SET(c, destroy); SET(c, flush); SET(c, get_principal); SET(c, get_principals); SET(c, get_privs); SET(c, modify_principal); SET(c, randkey_principal); SET(c, rename_principal); } kadm5_ret_t _kadm5_c_init_context(kadm5_client_context **ctx, kadm5_config_params *params, krb5_context context) { krb5_error_code ret; char *colon; *ctx = malloc(sizeof(**ctx)); if(*ctx == NULL) return ENOMEM; memset(*ctx, 0, sizeof(**ctx)); krb5_add_et_list (context, initialize_kadm5_error_table_r); set_funcs(*ctx); (*ctx)->context = context; if(params->mask & KADM5_CONFIG_REALM) { ret = 0; (*ctx)->realm = strdup(params->realm); if ((*ctx)->realm == NULL) ret = ENOMEM; } else ret = krb5_get_default_realm((*ctx)->context, &(*ctx)->realm); if (ret) { free(*ctx); return ret; } if(params->mask & KADM5_CONFIG_ADMIN_SERVER) (*ctx)->admin_server = strdup(params->admin_server); else { char **hostlist; ret = krb5_get_krb_admin_hst (context, &(*ctx)->realm, &hostlist); if (ret) { free((*ctx)->realm); free(*ctx); return ret; } (*ctx)->admin_server = strdup(*hostlist); krb5_free_krbhst (context, hostlist); } if ((*ctx)->admin_server == NULL) { free((*ctx)->realm); free(*ctx); return ENOMEM; } colon = strchr ((*ctx)->admin_server, ':'); if (colon != NULL) *colon++ = '\0'; (*ctx)->kadmind_port = 0; if(params->mask & KADM5_CONFIG_KADMIND_PORT) (*ctx)->kadmind_port = params->kadmind_port; else if (colon != NULL) { char *end; (*ctx)->kadmind_port = htons(strtol (colon, &end, 0)); } if ((*ctx)->kadmind_port == 0) (*ctx)->kadmind_port = krb5_getportbyname (context, "kerberos-adm", "tcp", 749); return 0; } static krb5_error_code get_kadm_ticket(krb5_context context, krb5_ccache id, krb5_principal client, const char *server_name) { krb5_error_code ret; krb5_creds in, *out; memset(&in, 0, sizeof(in)); in.client = client; ret = krb5_parse_name(context, server_name, &in.server); if(ret) return ret; ret = krb5_get_credentials(context, 0, id, &in, &out); if(ret == 0) krb5_free_creds(context, out); krb5_free_principal(context, in.server); return ret; } static krb5_error_code get_new_cache(krb5_context context, krb5_principal client, const char *password, krb5_prompter_fct prompter, const char *keytab, const char *server_name, krb5_ccache *ret_cache) { krb5_error_code ret; krb5_creds cred; krb5_get_init_creds_opt *opt; krb5_ccache id; ret = krb5_get_init_creds_opt_alloc (context, &opt); if (ret) return ret; krb5_get_init_creds_opt_set_default_flags(context, "kadmin", krb5_principal_get_realm(context, client), opt); krb5_get_init_creds_opt_set_forwardable (opt, FALSE); krb5_get_init_creds_opt_set_proxiable (opt, FALSE); if(password == NULL && prompter == NULL) { krb5_keytab kt; if(keytab == NULL) ret = krb5_kt_default(context, &kt); else ret = krb5_kt_resolve(context, keytab, &kt); if(ret) { krb5_get_init_creds_opt_free(context, opt); return ret; } ret = krb5_get_init_creds_keytab (context, &cred, client, kt, 0, server_name, opt); krb5_kt_close(context, kt); } else { ret = krb5_get_init_creds_password (context, &cred, client, password, prompter, NULL, 0, server_name, opt); } krb5_get_init_creds_opt_free(context, opt); switch(ret){ case 0: break; case KRB5_LIBOS_PWDINTR: /* don't print anything if it was just C-c:ed */ case KRB5KRB_AP_ERR_BAD_INTEGRITY: case KRB5KRB_AP_ERR_MODIFIED: return KADM5_BAD_PASSWORD; default: return ret; } ret = krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id); if(ret) return ret; ret = krb5_cc_initialize (context, id, cred.client); if (ret) return ret; ret = krb5_cc_store_cred (context, id, &cred); if (ret) return ret; krb5_free_cred_contents (context, &cred); *ret_cache = id; return 0; } /* * Check the credential cache `id´ to figure out what principal to use * when talking to the kadmind. If there is a initial kadmin/admin@ * credential in the cache, use that client principal. Otherwise, use * the client principals first component and add /admin to the * principal. */ static krb5_error_code get_cache_principal(krb5_context context, krb5_ccache *id, krb5_principal *client) { krb5_error_code ret; const char *name, *inst; krb5_principal p1, p2; ret = krb5_cc_default(context, id); if(ret) { *id = NULL; return ret; } ret = krb5_cc_get_principal(context, *id, &p1); if(ret) { krb5_cc_close(context, *id); *id = NULL; return ret; } ret = krb5_make_principal(context, &p2, NULL, "kadmin", "admin", NULL); if (ret) { krb5_cc_close(context, *id); *id = NULL; krb5_free_principal(context, p1); return ret; } { krb5_creds in, *out; krb5_kdc_flags flags; flags.i = 0; memset(&in, 0, sizeof(in)); in.client = p1; in.server = p2; /* check for initial ticket kadmin/admin */ ret = krb5_get_credentials_with_flags(context, KRB5_GC_CACHED, flags, *id, &in, &out); krb5_free_principal(context, p2); if (ret == 0) { if (out->flags.b.initial) { *client = p1; krb5_free_creds(context, out); return 0; } krb5_free_creds(context, out); } } krb5_cc_close(context, *id); *id = NULL; name = krb5_principal_get_comp_string(context, p1, 0); inst = krb5_principal_get_comp_string(context, p1, 1); if(inst == NULL || strcmp(inst, "admin") != 0) { ret = krb5_make_principal(context, &p2, NULL, name, "admin", NULL); krb5_free_principal(context, p1); if(ret != 0) return ret; *client = p2; return 0; } *client = p1; return 0; } krb5_error_code _kadm5_c_get_cred_cache(krb5_context context, const char *client_name, const char *server_name, const char *password, krb5_prompter_fct prompter, const char *keytab, krb5_ccache ccache, krb5_ccache *ret_cache) { krb5_error_code ret; krb5_ccache id = NULL; krb5_principal default_client = NULL, client = NULL; /* treat empty password as NULL */ if(password && *password == '\0') password = NULL; if(server_name == NULL) server_name = KADM5_ADMIN_SERVICE; if(client_name != NULL) { ret = krb5_parse_name(context, client_name, &client); if(ret) return ret; } if(ccache != NULL) { id = ccache; ret = krb5_cc_get_principal(context, id, &client); if(ret) return ret; } else { /* get principal from default cache, ok if this doesn't work */ ret = get_cache_principal(context, &id, &default_client); if (ret) { /* * No client was specified by the caller and we cannot * determine the client from a credentials cache. */ const char *user; user = get_default_username (); if(user == NULL) { krb5_set_error_message(context, KADM5_FAILURE, "Unable to find local user name"); return KADM5_FAILURE; } ret = krb5_make_principal(context, &default_client, NULL, user, "admin", NULL); if(ret) return ret; } } /* * No client was specified by the caller, but we have a client * from the default credentials cache. */ if (client == NULL && default_client != NULL) client = default_client; if(id && client && (default_client == NULL || krb5_principal_compare(context, client, default_client) != 0)) { ret = get_kadm_ticket(context, id, client, server_name); if(ret == 0) { *ret_cache = id; krb5_free_principal(context, default_client); if (default_client != client) krb5_free_principal(context, client); return 0; } if(ccache != NULL) /* couldn't get ticket from cache */ return -1; } /* get creds via AS request */ if(id && (id != ccache)) krb5_cc_close(context, id); if (client != default_client) krb5_free_principal(context, default_client); ret = get_new_cache(context, client, password, prompter, keytab, server_name, ret_cache); krb5_free_principal(context, client); return ret; } static kadm5_ret_t kadm_connect(kadm5_client_context *ctx) { kadm5_ret_t ret; krb5_principal server; krb5_ccache cc; int s; struct addrinfo *ai, *a; struct addrinfo hints; int error; char portstr[NI_MAXSERV]; char *hostname, *slash; char *service_name; krb5_context context = ctx->context; memset (&hints, 0, sizeof(hints)); hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; snprintf (portstr, sizeof(portstr), "%u", ntohs(ctx->kadmind_port)); hostname = ctx->admin_server; slash = strchr (hostname, '/'); if (slash != NULL) hostname = slash + 1; error = getaddrinfo (hostname, portstr, &hints, &ai); if (error) { krb5_clear_error_message(context); return KADM5_BAD_SERVER_NAME; } for (a = ai; a != NULL; a = a->ai_next) { s = socket (a->ai_family, a->ai_socktype, a->ai_protocol); if (s < 0) continue; if (connect (s, a->ai_addr, a->ai_addrlen) < 0) { krb5_clear_error_message(context); krb5_warn (context, errno, "connect(%s)", hostname); close (s); continue; } break; } if (a == NULL) { freeaddrinfo (ai); krb5_clear_error_message(context); krb5_warnx (context, "failed to contact %s", hostname); return KADM5_FAILURE; } ret = _kadm5_c_get_cred_cache(context, ctx->client_name, ctx->service_name, NULL, ctx->prompter, ctx->keytab, ctx->ccache, &cc); if(ret) { freeaddrinfo (ai); close(s); return ret; } if (ctx->realm) asprintf(&service_name, "%s@%s", KADM5_ADMIN_SERVICE, ctx->realm); else asprintf(&service_name, "%s", KADM5_ADMIN_SERVICE); if (service_name == NULL) { freeaddrinfo (ai); close(s); krb5_clear_error_message(context); return ENOMEM; } ret = krb5_parse_name(context, service_name, &server); free(service_name); if(ret) { freeaddrinfo (ai); if(ctx->ccache == NULL) krb5_cc_close(context, cc); close(s); return ret; } ctx->ac = NULL; ret = krb5_sendauth(context, &ctx->ac, &s, KADMIN_APPL_VERSION, NULL, server, AP_OPTS_MUTUAL_REQUIRED, NULL, NULL, cc, NULL, NULL, NULL); if(ret == 0) { krb5_data params; kadm5_config_params p; memset(&p, 0, sizeof(p)); if(ctx->realm) { p.mask |= KADM5_CONFIG_REALM; p.realm = ctx->realm; } ret = _kadm5_marshal_params(context, &p, &params); ret = krb5_write_priv_message(context, ctx->ac, &s, &params); krb5_data_free(&params); if(ret) { freeaddrinfo (ai); close(s); if(ctx->ccache == NULL) krb5_cc_close(context, cc); return ret; } } else if(ret == KRB5_SENDAUTH_BADAPPLVERS) { close(s); s = socket (a->ai_family, a->ai_socktype, a->ai_protocol); if (s < 0) { freeaddrinfo (ai); krb5_clear_error_message(context); return errno; } if (connect (s, a->ai_addr, a->ai_addrlen) < 0) { close (s); freeaddrinfo (ai); krb5_clear_error_message(context); return errno; } ret = krb5_sendauth(context, &ctx->ac, &s, KADMIN_OLD_APPL_VERSION, NULL, server, AP_OPTS_MUTUAL_REQUIRED, NULL, NULL, cc, NULL, NULL, NULL); } freeaddrinfo (ai); if(ret) { close(s); return ret; } krb5_free_principal(context, server); if(ctx->ccache == NULL) krb5_cc_close(context, cc); ctx->sock = s; return 0; } kadm5_ret_t _kadm5_connect(void *handle) { kadm5_client_context *ctx = handle; if(ctx->sock == -1) return kadm_connect(ctx); return 0; } static kadm5_ret_t kadm5_c_init_with_context(krb5_context context, const char *client_name, const char *password, krb5_prompter_fct prompter, const char *keytab, krb5_ccache ccache, const char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { kadm5_ret_t ret; kadm5_client_context *ctx; krb5_ccache cc; ret = _kadm5_c_init_context(&ctx, realm_params, context); if(ret) return ret; if(password != NULL && *password != '\0') { ret = _kadm5_c_get_cred_cache(context, client_name, service_name, password, prompter, keytab, ccache, &cc); if(ret) return ret; /* XXX */ ccache = cc; } if (client_name != NULL) ctx->client_name = strdup(client_name); else ctx->client_name = NULL; if (service_name != NULL) ctx->service_name = strdup(service_name); else ctx->service_name = NULL; ctx->prompter = prompter; ctx->keytab = keytab; ctx->ccache = ccache; /* maybe we should copy the params here */ ctx->sock = -1; *server_handle = ctx; return 0; } static kadm5_ret_t init_context(const char *client_name, const char *password, krb5_prompter_fct prompter, const char *keytab, krb5_ccache ccache, const char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { krb5_context context; kadm5_ret_t ret; kadm5_server_context *ctx; ret = krb5_init_context(&context); if (ret) return ret; ret = kadm5_c_init_with_context(context, client_name, password, prompter, keytab, ccache, service_name, realm_params, struct_version, api_version, server_handle); if(ret){ krb5_free_context(context); return ret; } ctx = *server_handle; ctx->my_context = 1; return 0; } kadm5_ret_t kadm5_c_init_with_password_ctx(krb5_context context, const char *client_name, const char *password, const char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { return kadm5_c_init_with_context(context, client_name, password, krb5_prompter_posix, NULL, NULL, service_name, realm_params, struct_version, api_version, server_handle); } kadm5_ret_t kadm5_c_init_with_password(const char *client_name, const char *password, const char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { return init_context(client_name, password, krb5_prompter_posix, NULL, NULL, service_name, realm_params, struct_version, api_version, server_handle); } kadm5_ret_t kadm5_c_init_with_skey_ctx(krb5_context context, const char *client_name, const char *keytab, const char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { return kadm5_c_init_with_context(context, client_name, NULL, NULL, keytab, NULL, service_name, realm_params, struct_version, api_version, server_handle); } kadm5_ret_t kadm5_c_init_with_skey(const char *client_name, const char *keytab, const char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { return init_context(client_name, NULL, NULL, keytab, NULL, service_name, realm_params, struct_version, api_version, server_handle); } kadm5_ret_t kadm5_c_init_with_creds_ctx(krb5_context context, const char *client_name, krb5_ccache ccache, const char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { return kadm5_c_init_with_context(context, client_name, NULL, NULL, NULL, ccache, service_name, realm_params, struct_version, api_version, server_handle); } kadm5_ret_t kadm5_c_init_with_creds(const char *client_name, krb5_ccache ccache, const char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { return init_context(client_name, NULL, NULL, NULL, ccache, service_name, realm_params, struct_version, api_version, server_handle); } #if 0 kadm5_ret_t kadm5_init(char *client_name, char *pass, char *service_name, kadm5_config_params *realm_params, unsigned long struct_version, unsigned long api_version, void **server_handle) { } #endif
ystk/debian-heimdal
lib/kadm5/init_c.c
C
bsd-3-clause
19,249
#pragma once #include <folly/MPMCQueue.h> #include <memory> #include <string> #include <thread> namespace comm { using taskType = std::function<void()>; class WorkerThread { std::unique_ptr<std::thread> thread; folly::MPMCQueue<std::unique_ptr<taskType>> tasks; const std::string name; public: WorkerThread(const std::string name); void scheduleTask(const taskType task); ~WorkerThread(); }; } // namespace comm
Ashoat/squadcal
native/cpp/CommonCpp/Tools/WorkerThread.h
C
bsd-3-clause
430
{% extends "sentry/teams/manage.html" %} {% load i18n %} {% block title %}{% trans "Remove Member" %} | {{ block.super }}{% endblock %} {% block heading %}{% trans "Remove Member" %}{% endblock %} {% block breadcrumb %} {{ block.super }} <li class="divider">/</li> <li><a href="{% url sentry-remove-team-member team.slug member.pk %}">{% trans "Remove Member" %}</a></li> {% endblock %} {% block main %} <form class="form-stacked" action="" method="post"> {% csrf_token %} <div class="alert alert-block alert-error">{% trans "Are you sure you wish to revoke this user's access? <strong>This change is permanent and will revoke their API keys immediately.</strong>" %}</div> <div class="actions"> <button type="submit" class="btn danger">{% trans "Confirm" %}</button> <a href="{% url sentry-manage-team team.slug %}" class="btn">{% trans "Cancel" %}</a> </div> </form> {% endblock %}
alex/sentry
sentry/templates/sentry/teams/members/remove.html
HTML
bsd-3-clause
953
<?php namespace app\modules\controlcenter; use Yii; use yii\base\Theme; /** * Created by PhpStorm. * User: leijiao * Date: 16/3/10 * Time: 上午11:50 */ class Module extends \yii\base\Module { public $controllerNamespace = 'app\modules\controlcenter\controllers'; public $layout="@app/modules/controlcenter/themes/basic/layouts/main.php"; public function init() { parent::init(); \Yii::$app->view->theme = new Theme([ 'basePath' => '@app/modules/controlcenter/themes/basic', 'pathMap' => ['@app/modules/controlcenter/views'=>'@app/modules/controlcenter/themes/basic'], 'baseUrl' => '@app/modules/controlcenter/themes/basic', ]); } }
vin120/vcos
backend/modules/controlcenter/Module.php
PHP
bsd-3-clause
722
<?php /** * @link http://www.writesdown.com/ * @copyright Copyright (c) 2015 WritesDown * @license http://www.writesdown.com/license/ */ namespace tests\codeception\common\fixtures; use yii\test\ActiveFixture; /** * Class ModuleFixture * * @author Agiel K. Saputra <13nightevil@gmail.com> * @since 0.1.2 */ class ModuleFixture extends ActiveFixture { /** * @var string */ public $modelClass = 'common\models\Module'; /** * @var string */ public $dataFile = '@tests/codeception/common/fixtures/data/init_module.php'; }
writesdown/app-cms
tests/codeception/common/fixtures/ModuleFixture.php
PHP
bsd-3-clause
567