code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /* * @copyright 2014 Mautic Contributors. All rights reserved * @author Mautic * * @link http://mautic.org * * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ namespace Mautic\LeadBundle\Controller; use Mautic\CoreBundle\Controller\FormController; use Mautic\LeadBundle\Entity\LeadField; use Mautic\LeadBundle\Model\FieldModel; use Symfony\Component\Form\Form; use Symfony\Component\Form\FormError; class FieldController extends FormController { /** * Generate's default list view. * * @param int $page * * @return array|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response */ public function indexAction($page = 1) { //set some permissions $permissions = $this->get('mautic.security')->isGranted(['lead:fields:full'], 'RETURN_ARRAY'); $session = $this->get('session'); if (!$permissions['lead:fields:full']) { return $this->accessDenied(); } if ($this->request->getMethod() == 'POST') { $this->setListFilters(); } $limit = $session->get('mautic.leadfield.limit', $this->coreParametersHelper->getParameter('default_pagelimit')); $search = $this->request->get('search', $session->get('mautic.leadfield.filter', '')); $session->set('mautic.leadfilter.filter', $search); //do some default filtering $orderBy = $this->get('session')->get('mautic.leadfilter.orderby', 'f.order'); $orderByDir = $this->get('session')->get('mautic.leadfilter.orderbydir', 'ASC'); $start = ($page === 1) ? 0 : (($page - 1) * $limit); if ($start < 0) { $start = 0; } $request = $this->factory->getRequest(); $search = $request->get('search', $session->get('mautic.lead.emailtoken.filter', '')); $session->set('mautic.lead.emailtoken.filter', $search); $fields = $this->getModel('lead.field')->getEntities([ 'start' => $start, 'limit' => $limit, 'filter' => ['string' => $search], 'orderBy' => $orderBy, 'orderByDir' => $orderByDir, ]); $count = count($fields); if ($count && $count < ($start + 1)) { //the number of entities are now less then the current page so redirect to the last page if ($count === 1) { $lastPage = 1; } else { $lastPage = (ceil($count / $limit)) ?: 1; } $session->set('mautic.leadfield.page', $lastPage); $returnUrl = $this->generateUrl('mautic_contactfield_index', ['page' => $lastPage]); return $this->postActionRedirect([ 'returnUrl' => $returnUrl, 'viewParameters' => ['page' => $lastPage], 'contentTemplate' => 'MauticLeadBundle:Field:index', 'passthroughVars' => [ 'activeLink' => '#mautic_contactfield_index', 'mauticContent' => 'leadfield', ], ]); } //set what page currently on so that we can return here after form submission/cancellation $session->set('mautic.leadfield.page', $page); $tmpl = $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index'; return $this->delegateView([ 'viewParameters' => [ 'items' => $fields, 'searchValue' => $search, 'permissions' => $permissions, 'tmpl' => $tmpl, 'totalItems' => $count, 'limit' => $limit, 'page' => $page, ], 'contentTemplate' => 'MauticLeadBundle:Field:list.html.php', 'passthroughVars' => [ 'activeLink' => '#mautic_contactfield_index', 'route' => $this->generateUrl('mautic_contactfield_index', ['page' => $page]), 'mauticContent' => 'leadfield', ], ]); } /** * Generate's new form and processes post data. * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response */ public function newAction() { if (!$this->get('mautic.security')->isGranted('lead:fields:full')) { return $this->accessDenied(); } //retrieve the entity $field = new LeadField(); /** @var FieldModel $model */ $model = $this->getModel('lead.field'); //set the return URL for post actions $returnUrl = $this->generateUrl('mautic_contactfield_index'); $action = $this->generateUrl('mautic_contactfield_action', ['objectAction' => 'new']); //get the user form factory $form = $model->createForm($field, $this->get('form.factory'), $action); ///Check for a submitted form and process it if ($this->request->getMethod() == 'POST') { $valid = false; if (!$cancelled = $this->isFormCancelled($form)) { if ($valid = $this->isFormValid($form)) { $request = $this->request->request->all(); if (isset($request['leadfield']['properties'])) { $result = $model->setFieldProperties($field, $request['leadfield']['properties']); if ($result !== true) { //set the error $form->get('properties')->addError( new FormError( $this->get('translator')->trans($result, [], 'validators') ) ); $valid = false; } } if ($valid) { try { //form is valid so process the data $model->saveEntity($field); $this->addFlash( 'mautic.core.notice.created', [ '%name%' => $field->getLabel(), '%menu_link%' => 'mautic_contactfield_index', '%url%' => $this->generateUrl( 'mautic_contactfield_action', [ 'objectAction' => 'edit', 'objectId' => $field->getId(), ] ), ] ); } catch (\Exception $e) { $form['alias']->addError( new FormError( $this->get('translator')->trans('mautic.lead.field.failed', ['%error%' => $e->getMessage()], 'validators') ) ); $valid = false; } } } } if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) { return $this->postActionRedirect( [ 'returnUrl' => $returnUrl, 'contentTemplate' => 'MauticLeadBundle:Field:index', 'passthroughVars' => [ 'activeLink' => '#mautic_contactfield_index', 'mauticContent' => 'leadfield', ], ] ); } elseif ($valid && !$cancelled) { return $this->editAction($field->getId(), true); } elseif (!$valid) { // some bug in Symfony prevents repopulating list options on errors $field = $form->getData(); $newForm = $model->createForm($field, $this->get('form.factory'), $action); $this->copyErrorsRecursively($form, $newForm); $form = $newForm; } } return $this->delegateView( [ 'viewParameters' => [ 'form' => $form->createView(), ], 'contentTemplate' => 'MauticLeadBundle:Field:form.html.php', 'passthroughVars' => [ 'activeLink' => '#mautic_contactfield_index', 'route' => $this->generateUrl('mautic_contactfield_action', ['objectAction' => 'new']), 'mauticContent' => 'leadfield', ], ] ); } /** * Generate's edit form and processes post data. * * @param $objectId * @param bool|false $ignorePost * * @return array|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response */ public function editAction($objectId, $ignorePost = false) { if (!$this->get('mautic.security')->isGranted('lead:fields:full')) { return $this->accessDenied(); } /** @var FieldModel $model */ $model = $this->getModel('lead.field'); $field = $model->getEntity($objectId); //set the return URL $returnUrl = $this->generateUrl('mautic_contactfield_index'); $postActionVars = [ 'returnUrl' => $returnUrl, 'contentTemplate' => 'MauticLeadBundle:Field:index', 'passthroughVars' => [ 'activeLink' => '#mautic_contactfield_index', 'mauticContent' => 'leadfield', ], ]; //list not found if ($field === null) { return $this->postActionRedirect( array_merge($postActionVars, [ 'flashes' => [ [ 'type' => 'error', 'msg' => 'mautic.lead.field.error.notfound', 'msgVars' => ['%id%' => $objectId], ], ], ]) ); } elseif ($model->isLocked($field)) { //deny access if the entity is locked return $this->isLocked($postActionVars, $field, 'lead.field'); } $action = $this->generateUrl('mautic_contactfield_action', ['objectAction' => 'edit', 'objectId' => $objectId]); $form = $model->createForm($field, $this->get('form.factory'), $action); ///Check for a submitted form and process it if (!$ignorePost && $this->request->getMethod() == 'POST') { $valid = false; if (!$cancelled = $this->isFormCancelled($form)) { if ($valid = $this->isFormValid($form)) { $request = $this->request->request->all(); if (isset($request['leadfield']['properties'])) { $result = $model->setFieldProperties($field, $request['leadfield']['properties']); if ($result !== true) { //set the error $form->get('properties')->addError(new FormError( $this->get('translator')->trans($result, [], 'validators') )); $valid = false; } } if ($valid) { //form is valid so process the data $model->saveEntity($field, $form->get('buttons')->get('save')->isClicked()); $this->addFlash('mautic.core.notice.updated', [ '%name%' => $field->getLabel(), '%menu_link%' => 'mautic_contactfield_index', '%url%' => $this->generateUrl('mautic_contactfield_action', [ 'objectAction' => 'edit', 'objectId' => $field->getId(), ]), ]); } } } else { //unlock the entity $model->unlockEntity($field); } if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) { return $this->postActionRedirect( array_merge($postActionVars, [ 'viewParameters' => ['objectId' => $field->getId()], 'contentTemplate' => 'MauticLeadBundle:Field:index', ] ) ); } elseif ($valid) { // Rebuild the form with new action so that apply doesn't keep creating a clone $action = $this->generateUrl('mautic_contactfield_action', ['objectAction' => 'edit', 'objectId' => $field->getId()]); $form = $model->createForm($field, $this->get('form.factory'), $action); } else { // some bug in Symfony prevents repopulating list options on errors $field = $form->getData(); $newForm = $model->createForm($field, $this->get('form.factory'), $action); $this->copyErrorsRecursively($form, $newForm); $form = $newForm; } } else { //lock the entity $model->lockEntity($field); } return $this->delegateView([ 'viewParameters' => [ 'form' => $form->createView(), ], 'contentTemplate' => 'MauticLeadBundle:Field:form.html.php', 'passthroughVars' => [ 'activeLink' => '#mautic_contactfield_index', 'route' => $action, 'mauticContent' => 'leadfield', ], ]); } /** * Clone an entity. * * @param $objectId * * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response */ public function cloneAction($objectId) { $model = $this->getModel('lead.field'); $entity = $model->getEntity($objectId); if ($entity != null) { if (!$this->get('mautic.security')->isGranted('lead:fields:full')) { return $this->accessDenied(); } $clone = clone $entity; $clone->setIsPublished(false); $clone->setIsFixed(false); $model->saveEntity($clone); $objectId = $clone->getId(); } return $this->editAction($objectId); } /** * Delete a field. * * @param $objectId * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse */ public function deleteAction($objectId) { if (!$this->get('mautic.security')->isGranted('lead:fields:full')) { return $this->accessDenied(); } $returnUrl = $this->generateUrl('mautic_contactfield_index'); $flashes = []; $postActionVars = [ 'returnUrl' => $returnUrl, 'contentTemplate' => 'MauticLeadBundle:Field:index', 'passthroughVars' => [ 'activeLink' => '#mautic_contactfield_index', 'mauticContent' => 'lead', ], ]; if ($this->request->getMethod() == 'POST') { $model = $this->getModel('lead.field'); $field = $model->getEntity($objectId); if ($field === null) { $flashes[] = [ 'type' => 'error', 'msg' => 'mautic.lead.field.error.notfound', 'msgVars' => ['%id%' => $objectId], ]; } elseif ($model->isLocked($field)) { return $this->isLocked($postActionVars, $field, 'lead.field'); } elseif ($field->isFixed()) { //cannot delete fixed fields return $this->accessDenied(); } $model->deleteEntity($field); $flashes[] = [ 'type' => 'notice', 'msg' => 'mautic.core.notice.deleted', 'msgVars' => [ '%name%' => $field->getLabel(), '%id%' => $objectId, ], ]; } //else don't do anything return $this->postActionRedirect( array_merge($postActionVars, [ 'flashes' => $flashes, ]) ); } /** * Deletes a group of entities. * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse */ public function batchDeleteAction() { if (!$this->get('mautic.security')->isGranted('lead:fields:full')) { return $this->accessDenied(); } $returnUrl = $this->generateUrl('mautic_contactfield_index'); $flashes = []; $postActionVars = [ 'returnUrl' => $returnUrl, 'contentTemplate' => 'MauticLeadBundle:Field:index', 'passthroughVars' => [ 'activeLink' => '#mautic_contactfield_index', 'mauticContent' => 'lead', ], ]; if ($this->request->getMethod() == 'POST') { $model = $this->getModel('lead.field'); $ids = json_decode($this->request->query->get('ids', '{}')); $deleteIds = []; // Loop over the IDs to perform access checks pre-delete foreach ($ids as $objectId) { $entity = $model->getEntity($objectId); if ($entity === null) { $flashes[] = [ 'type' => 'error', 'msg' => 'mautic.lead.field.error.notfound', 'msgVars' => ['%id%' => $objectId], ]; } elseif ($entity->isFixed()) { $flashes[] = $this->accessDenied(true); } elseif ($model->isLocked($entity)) { $flashes[] = $this->isLocked($postActionVars, $entity, 'lead.field', true); } else { $deleteIds[] = $objectId; } } // Delete everything we are able to if (!empty($deleteIds)) { $entities = $model->deleteEntities($deleteIds); $flashes[] = [ 'type' => 'notice', 'msg' => 'mautic.lead.field.notice.batch_deleted', 'msgVars' => [ '%count%' => count($entities), ], ]; } } //else don't do anything return $this->postActionRedirect( array_merge($postActionVars, [ 'flashes' => $flashes, ]) ); } }
PatchRanger/mautic
app/bundles/LeadBundle/Controller/FieldController.php
PHP
gpl-3.0
19,576
import unittest from model.session import * from model.dbhandler import * class SessionTest(unittest.TestCase): def test_instance(self): session = Session('123') session.addData('key', 'vall') self.assertNotEqual(session.data, None) def test_add_data(self): session1 = Session('1234') session1.addData('testKey', 'testVal') session1.addData('list', ['val1, val2']) session2 = Session('1234') self.assertEqual(session1.data, session2.data) def test_destroy(self): session = Session('123') session.addData('key', 'vall') Session.destroy('1234') Session.destroy('123') dbh = DbHandler.getInstance() cur = dbh.cur cur.execute("""SELECT data FROM `user_session` WHERE sid IN ('123', '1234')""") self.assertEqual(cur.rowcount, 0)
gantonov/restaurant-e-menu
cgi-bin/tests/test_session.py
Python
gpl-3.0
891
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class plantillamatrixcontroler extends CI_Controller { private $DBGASTO = null; private $usuariologin, $sessionflag, $usuariocodger, $acc_lectura, $acc_escribe, $acc_modifi; function __construct() { parent::__construct(); $this->load->library('encrypt'); // TODO buscar como setiear desde aqui key encrypt $this->load->library('session'); $this->load->helper(array('form', 'url','html')); $this->load->library('table'); $this->load->model('menu'); $this->output->enable_profiler(TRUE); } public function _verificarsesion() { if( $this->session->userdata('logueado') != TRUE) redirect('manejousuarios/desverificarintranet'); } /** * Index Page cuando se invoca la url de este controlador, * aqui se invoca la vista o otro metodo que la invoque * map to /index.php/plantillamatrixcontroler/index */ public function index() { $this->seccionformulario(); } public function seccionformulario() { /* ***** ini manejo de sesion ******************* */ $this->_verificarsesion(); $userdata = $this->session->all_userdata(); $usercorreo = $userdata['correo']; $userintranet = $userdata['intranet']; $sessionflag = $this->session->userdata('username').date("YmdHis"); $data['usercorreo'] = $usercorreo; $data['userintranet'] = $userintranet; $data['menu'] = $this->menu->menudesktop(); /* ***** fin manejo de sesion ******************* */ /* **** hay que cargar las bae de datos */ $DBGASTO = $this->load->database('gastossystema',TRUE); /* ***** fin ********** */ /* ****** ini cargar y listaar CATEGORIAS para comboboxes u otros ********** */ $sqlcategoria = " select ifnull(cod_categoria,'99999999999999') as cod_categoria, ifnull(des_categoria,'sin_descripcion') as des_categoria, ifnull(fecha_categoria, '20160101') as fecha_categoria from categoria where ifnull(cod_categoria, '') <> '' and cod_categoria <> ''"; // documentado en wiki tabla y select $resultadoscategoria = $DBGASTO->query($sqlcategoria); $arreglocategoriaes = array(''=>''); // declaro un arreglo y lo lleno con la lista (sera el combobox) foreach ($resultadoscategoria->result() as $row) $arreglocategoriaes[''.$row->cod_categoria] = '' . $row->des_categoria . '-' . $row->fecha_categoria; $data['list_categoria'] = $arreglocategoriaes; // meto en data para enviar a la vista unset($arreglocategoriaes['']); /* ****** fin cargar y listaar CATEGORIAS para comboboxes u otros ********** */ /* ****** ini cargar y listaar SUBCATEGORIAS para comboboxes vista ********** */ $sqlsubcategoria = " SELECT ifnull(ca.cod_categoria,'0') as cod_categoria, ifnull(ca.des_categoria,'ninguna') as des_categoria, ifnull(sb.cod_subcategoria,'0') as cod_subcategoria, ifnull(sb.des_subcategoria,'ninguna') as des_subcategoria, ca.fecha_categoria, sb.fecha_subcategoria, sb.sessionflag FROM categoria AS ca JOIN subcategoria AS sb ON sb.cod_categoria = ca.cod_categoria WHERE ifnull(cod_subcategoria, '') <> '' AND cod_subcategoria <> ''"; // documentado en wiki tabla y select $resultadossubcategoria = $DBGASTO->query($sqlsubcategoria); $arreglosubcategoriaes = array(''=>''); foreach ($resultadossubcategoria->result() as $row) $arreglosubcategoriaes[''.$row->cod_subcategoria] = $row->des_categoria . ' - ' . $row->des_subcategoria; $data['list_subcategoria'] = $arreglosubcategoriaes; // agrega este arreglo una lista para el combo box unset($arreglosubcategoriaes['']); /* cargar y listaar las UBIUCACIONES que se usaran para registros */ $sqlentidad = " select abr_entidad, abr_zona, des_entidad, ifnull(cod_entidad,'99999999999999') as cod_entidad, -- YYYYMMDDhhmmss ifnull(des_entidad,'sin_descripcion') as des_entidad from entidad where ifnull(cod_entidad, '') <> '' and cod_entidad <> '' "; $resultadosentidad = $DBGASTO->query($sqlentidad); $arregloentidades = array(''=>''); foreach ($resultadosentidad->result() as $row) { $arregloentidades[''.$row->cod_entidad] = $row->cod_entidad . ' - ' . $row->abr_entidad .' - ' . $row->des_entidad . ' ('. $row->abr_zona .')'; } $data['list_entidad'] = $arregloentidades; // agrega este arreglo una lista para el combo box unset($arregloentidades['']); /* ****** fin cargar y listaar SUBCATEGORIAS para comboboxes vista ********** */ /* ****** ini cargar y preparar para llamar y pintar vista ********** */ $this->load->view('header.php',$data); $this->load->view('plantillamatrixvista.php',$data); $this->load->view('footer.php',$data); /* ****** fin cargar y preparar para llamar y pintar vista ********** */ } public function secciontablamatrix() { /* ***** ini manejo de sesion ******************* */ $this->_verificarsesion(); $userdata = $this->session->all_userdata(); $usercorreo = $userdata['correo']; $userintranet = $userdata['intranet']; $sessionflag = $this->session->userdata('username').date("YmdHis"); $data['usercorreo'] = $usercorreo; $data['userintranet'] = $userintranet; $data['menu'] = $this->menu->menudesktop(); /* ***** fin manejo de sesion ******************* */ /* **** hay que cargar las bae de datos */ $DBGASTO = $this->load->database('gastossystema',TRUE); /* ***** fin ********** */ /* ******** inicio preparacino query cualquiera ejemplo ************* */ $this->load->helper(array('form', 'url','inflector')); $cantidadLineas = 0; // creanos nuestro query sql que trae datos $sqlregistro = " SELECT registro_gastos.cod_registro, registro_adjunto.cod_adjunto, registro_gastos.cod_entidad, registro_gastos.cod_categoria, registro_gastos.cod_subcategoria, registro_gastos.des_registro, registro_gastos.mon_registro, categoria.des_categoria, subcategoria.des_subcategoria, entidad.des_entidad, entidad.abr_entidad, entidad.abr_zona, registro_gastos.estado, registro_gastos.num_factura, registro_adjunto.hex_adjunto, registro_adjunto.nam_adjunto, registro_adjunto.ruta_adjunto, registro_gastos.fecha_registro, registro_gastos.fecha_factura, registro_adjunto.fecha_adjunto, registro_gastos.sessionflag FROM gastossystema.registro_gastos LEFT JOIN gastossystema.registro_adjunto ON registro_adjunto.cod_registro = registro_gastos.cod_registro LEFT JOIN gastossystema.subcategoria ON subcategoria.cod_subcategoria = registro_gastos.cod_subcategoria LEFT JOIN gastossystema.categoria ON categoria.cod_categoria = registro_gastos.cod_categoria LEFT JOIN gastossystema.entidad ON entidad.cod_entidad = registro_gastos.cod_entidad WHERE ifnull(registro_gastos.cod_registro,'') <> '' and registro_gastos.cod_registro <> '' ORDER BY cod_registro DESC LIMIT 5"; /* ***** ini OBTENER DATOS DE FORMULARIO ***************************** */ $fechafiltramatrix = $this->input->get_post('fechafiltramatrix'); $cod_entidad = $this->input->get_post('cod_entidad'); $cod_subcategoria = $this->input->get_post('cod_subcategoria'); /* ***** fin OBTENER DATOS DE FORMULARIO ***************************** */ /* ***** ini filtrar los resultados del query segun formulario **************** */ //if ( $fechafiltramatrix != '') // $sqlregistro .= "and CONVERT(fecha_registro,UNSIGNED INTEGER) = CONVERT('".$fechafiltramatrix."',UNSIGNED INTEGER)"; if ( $cod_entidad != '') $sqlregistro .= "and cod_entidad = '".$cod_entidad."'"; if ( $cod_subcategoria != '') $sqlregistro .= "and registro_gastos.cod_subcategoria = '".$cod_subcategoria."'"; $resultadocarga = $DBGASTO->query($sqlregistro); // ejecuto el query /* ***** fin filtrar los resultados del query segun formulario **************** */ /* ***** ini pintar una tabla recorriendo el query **************** */ $this->load->helper(array('form', 'url','html')); $this->load->library('table'); $this->table->clear(); $tmplnewtable = array ( 'table_open' => '<table border="1" cellpadding="1" cellspacing="1" class="table">' ); $this->table->set_caption("Tabla de gastos"); $this->table->set_template($tmplnewtable); $this->table->set_heading( 'Registro', 'Categoria', 'Subcategoria',// 'cod_categoria', 'des_categoria', 'des_subcategoria', 'Destino', //'des_entidad','abr_entidad', 'abr_zona', 'Concepto descripcion', 'Monto', 'Estado', 'Realizado el' ); $resultadocargatabla = $resultadocarga->result_array(); // llamo a los resultados del query foreach ($resultadocargatabla as $rowtable) { $this->table->add_row( $rowtable['cod_registro'], $rowtable['des_categoria'], $rowtable['des_subcategoria'], $rowtable['des_entidad'] . ' ('.$rowtable['abr_entidad'].') -'. $rowtable['abr_zona'], $rowtable['des_registro'], $rowtable['mon_registro'], $rowtable['estado'], $rowtable['fecha_registro'] ); } $data['htmlquepintamatrix'] = $this->table->generate(); // html generado lo envia a la matrix /* ***** fin pintar una tabla recorriendo el query **************** */ $data['menu'] = $this->menu->menudesktop(); $data['seccionpagina'] = 'secciontablamatrix'; $data['userintran'] = $userintran; $data['fechafiltramatrix'] = $fechafiltramatrix; $data['cod_entidad'] = $cod_entidad; $data['cod_subcategoria'] = $cod_subcategoria; $this->load->view('header.php',$data); $this->load->view('cargargastoex.php',$data); $this->load->view('footer.php',$data); } public function enviarcorreo() { // PROCESO POSTERIOR generacion de txt y envio por correo $sql = "SELECT right('000000000'+DBA.td_orden_despacho.cod_interno,10) as cp, null as v2, DBA.td_orden_despacho.cantidad as ca, null as v3, '' as v4, ";//DBA.td_orden_despacho.precio_venta "; $sql .= " isnull(convert(integer, (DBA.td_orden_despacho.cantidad/(SELECT top 1 unid_empaque FROM DBA.ta_proveedor_producto where cod_proveedor<>'000000000000' and cod_interno=right('000000000'+DBA.td_orden_despacho.cod_interno,10)))),0) as bu "; $sql .= " FROM DBA.tm_orden_despacho join DBA.td_orden_despacho on DBA.tm_orden_despacho.cod_order=DBA.td_orden_despacho.cod_order WHERE dba.tm_orden_despacho.cod_order='".$filenamen."'"; $this->load->dbutil(); $querypaltxt = $DBGASTO->query($sql); // ejemplo desde el sql generamos un adjunto $correocontenido = $DBGASTOutil->csv_from_result($querypaltxt, "\t", "\n", '', FALSE); $this->load->helper('file'); $filenameneweordendespachoadjuntar = $cargaconfig['upload_path'] . '/ordendespachogenerada' . $this->numeroordendespacho . '.txt'; if ( ! write_file($filenameneweordendespachoadjuntar, $correocontenido)) { echo 'Unable to write the file'; } // en la db buscamos el correo del usuario y vemos a cuantos se enviaran $sql = "select top 1 correo from dba.tm_codmsc_correo where codmsc='".$intranet."'"; $sqlcorreoorigen = $DBGASTO->query($sql); $obtuvecorreo = 0; foreach ($sqlcorreoorigen->result() as $correorow) { $correoorigenaenviarle = $correorow->correo; $obtuvecorreo++; } if ($obtuvecorreo < 1) $correoorigenaenviarle = 'ordenesdespachos@intranet1.net.ve, lenz_gerardo@intranet1.net.ve'; // ahora procedemos apreparar el envio de correo $this->load->library('email'); $configm1['protocol'] = 'smtp'; // esta configuracion requiere mejoras $configm1['smtp_host'] = 'ssl://intranet1.net.ve'; // porque en la libreia, no conecta bien ssl $configm1['smtp_port'] = '465'; $configm1['smtp_timeout'] = '8'; $configm1['smtp_user'] = 'usuarioqueenviacorreo'; $configm1['smtp_pass'] = 'superclave'; $configm1['charset'] = 'utf-8'; $configm1['starttls'] = TRUE; $configm1['smtp_crypto'] = 'tls'; $configm1['newline'] = "\n"; $configm1['mailtype'] = 'text'; // or html $configm1['validation'] = FALSE; // bool whether to validate email or not $this->email->initialize($configm1); $this->email->from('ordenesdespachos@intranet1.net.ve', 'ordenesdespachos'); $this->email->cc($correousuariosesion); $this->email->to($correoorigenaenviarle); // enviar a los destinos de galpones $this->email->subject('Orden Despacho '. $this->numeroordendespacho .' Origen:'.$intranet.' Destino:'.$fechafiltramatrix); //$messageenviar = str_replace("\n", "\r\n", $correocontenido); $this->email->message('Orden de despacho adjunta.'.PHP_EOL.PHP_EOL.$correocontenido ); $this->email->attach($filenameneweordendespachoadjuntar); $this->email->send(); /* $configm2['protocol'] = 'mail';// en sysdevel y sysnet envia pero syscenter no $configm2['wordwrap'] = FALSE; $configm2['starttls'] = TRUE; // requiere sendmail o localmail use courierd START_TLS_REQUIRED=1 sendmail no envia $configm2['smtp_crypto'] = 'tls'; // $configm2['mailtype'] = 'html'; $this->load->library('email'); $this->email->initialize($configm2); $this->email->from('ordenesdespachos@intranet1.net.ve', 'ordenesdespachos'); // if ($obtuvecorreo < 1) $this->email->cc($correousuariosesion); $this->email->reply_to('ordenesdespachos@intranet1.net.ve', 'ordenesdespachos'); $this->email->to($correoorigenaenviarle ); // enviar a los destinos de galpones //if ($obtuvecorreo < 1) $this->email->subject('Registro de gasto '. $this->numeroordendespacho .' Responsable:'.$intranet.' Fecha registro:'.$fechafiltramatrix); //else // $this->email->subject('Orden prueba '. $this->numeroordendespacho .' Origen:'.$intranet.' Destino:'.$fechafiltramatrix); $this->email->message('Orden de despacho adjunta.'.PHP_EOL.PHP_EOL.'**************************************'.PHP_EOL.PHP_EOL.$resultadocargatablatxtmsg.$data['htmltablageneradodetalle'].'***************************************'.PHP_EOL.PHP_EOL.'Orden para el galpon cargar oasis:'.PHP_EOL.PHP_EOL.$correocontenido ); $this->email->attach($filenameneweordendespachoadjuntar); $this->email->send(); //echo $this->email->print_debugger(); */ } }
venenux/simplegastos
sysgastosweb/simplegastoswebphp/appweb/controllers/plantillamatrixcontroler.php
PHP
gpl-3.0
13,925
/** * AvaTax Brazil * The Avatax-Brazil API exposes the most commonly services available for interacting with the AvaTax-Brazil services, allowing calculation of taxes, issuing electronic invoice documents and modifying existing transactions when allowed by tax authorities. This API is exclusively for use by business with a physical presence in Brazil. * * OpenAPI spec version: 1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. define(['expect.js', '../../src/index'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. factory(require('expect.js'), require('../../src/index')); } else { // Browser globals (root is window) factory(root.expect, root.AvaTaxBrazil); } }(this, function(expect, AvaTaxBrazil) { 'use strict'; var instance; beforeEach(function() { instance = new AvaTaxBrazil.Body4(); }); var getProperty = function(object, getter, property) { // Use getter method if present; otherwise, get the property directly. if (typeof object[getter] === 'function') return object[getter](); else return object[property]; } var setProperty = function(object, setter, property, value) { // Use setter method if present; otherwise, set the property directly. if (typeof object[setter] === 'function') object[setter](value); else object[property] = value; } describe('Body4', function() { it('should create an instance of Body4', function() { // uncomment below and update the code to test Body4 //var instane = new AvaTaxBrazil.Body4(); //expect(instance).to.be.a(AvaTaxBrazil.Body4); }); it('should have the property startDate (base name: "startDate")', function() { // uncomment below and update the code to test the property startDate //var instane = new AvaTaxBrazil.Body4(); //expect(instance).to.be(); }); it('should have the property finishDate (base name: "finishDate")', function() { // uncomment below and update the code to test the property finishDate //var instane = new AvaTaxBrazil.Body4(); //expect(instance).to.be(); }); }); }));
Avalara/avataxbr-clients
javascript-client/test/model/Body4.spec.js
JavaScript
gpl-3.0
2,454
''' Created on Mar 25, 2016 Created on Jan 27, 2016 3.3V pin : 1,17 5V pin : 2,4 Ground : 6,9,14,20,25,30,34,39 EPROM : 27,28 GPIO : 3,5,7,8,10,11,12,13,15,16,18,10,21,22,23,24,26,29,31,32,33,35,36,37,38,40 Motor Control : 29,31,33,35 front 7,8 left 11,12 right 15,16 back 21,22 top 23,24 signal 26 sigt 10 wireless IMU import socket, traceback host = '' port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) while 1: try: message, address = s.recvfrom(8192) print message except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() @author: kumaran @author: kumaran ''' import RPi.GPIO as GPIO import time from string import atoi,atof import sys,tty,termios import random class EchoSensor(object): def __init__(self,trigger,echo): self.trigger = trigger self.echo = echo #print "Sensor configured with t,e",self.trigger,self.echo GPIO.setup(self.trigger,GPIO.OUT) GPIO.setup(self.echo,GPIO.IN,pull_up_down = GPIO.PUD_DOWN) time.sleep(0.5) def measure(self): GPIO.output(self.trigger,0) #GPIO.input(self.echo,pull_up_down = GPIO.PUD_DOWN) GPIO.output(self.trigger,True) time.sleep(0.00001) GPIO.output(self.trigger,False) self.startTime=time.time() while GPIO.input(self.echo) == False: self.startTime = time.time() while GPIO.input(self.echo) == True: self.stopTime = time.time() self.elapsedTime=self.stopTime-self.startTime self.distance=(self.elapsedTime*34000.0)/2.0 return self.distance def avgDistance(self,trails): self.avgdist=0.0 for i in range(trails): time.sleep(0.1) self.avgdist+=self.measure() return self.avgdist/trails class Engine(object): def __init__(self,lm1,lm2,rm1,rm2,t,dc,ft=0,fc=0,bt=0,bc=0): self.status="x" self.turnDelay=[t-0.2,t-0.1,t,t+0.1,t+0.2] self.leftMotor=[lm1,lm2] self.rightMotor=[rm1,rm2] self.motors=self.leftMotor+self.rightMotor self.DistanceCutoff=dc self.Maxturns = 5 GPIO.setup(self.motors,GPIO.OUT) if ft and fc: self.FronSensor=True self.FS=EchoSensor(ft,fc) else: self.FronSensor=False if bt and bc: self.BackSensor=True self.BS=EchoSensor(bt,bc) else: self.BackSensor=False def Scan(self): if self.FronSensor and self.BackSensor: if self.status in ["x","s","t"]: self.FS.measure() self.BS.measure() elif self.status == 'f': self.FS.measure() elif self.status == 'r': self.BS.measure() else: print "Problem with Echo sensors" def Stop(self): self.status='s' GPIO.output(self.motors,0) def Run(self): self.turns=0 while self.status != 'h': time.sleep(0.01) self.Scan() self.Move() #print self.status,self.FS.distance,self.BS.distance self.Stop() GPIO.cleanup() print 'No way to go.. stopping....' def Move(self): if self.status in ["s","x","t","f"] and self.FS.distance > self.DistanceCutoff: self.MoveForward() self.turns=0 elif self.status in ["s","x","t","r"] and self.BS.distance > self.DistanceCutoff: self.MoveBackward() self.turns = 0 elif self.status == "f" and self.FS.distance < self.DistanceCutoff: self.Turn() elif self.status == "r" and self.BS.distance < self.DistanceCutoff: self.Turn() else: self.turns+=1 self.Turn() if self.turns > self.Maxturns: self.status = 'h' def MoveForward(self): self.status = 'f' GPIO.output(self.motors,(0,1,1,0)) def MoveBackward(self): self.status = 'r' GPIO.output(self.motors,(1,0,0,1)) def Turn(self): if random.choice(['L','R'])=='R': GPIO.output(self.motors,(0,0,0,1)) time.sleep(random.choice(self.turnDelay)) self.Stop() else: GPIO.output(self.motors,(1,0,0,0)) time.sleep(random.choice(self.turnDelay)) self.Stop() if __name__=="__main__": GPIO.setmode(GPIO.BOARD) Neo=Engine(29,31,33,35,0.5,30.0,22,21,24,23) Neo.Run()
kumar-physics/pi
ObstacleAvoidance/ObstacleAvoidance/Jeno.py
Python
gpl-3.0
4,812
using System.Web.Http; namespace Netas.Nipps.SystemManager.Presentation { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type. // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries. // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712. //config.EnableQuerySupport(); } } }
aozkesek/dotNET
appsystemmanager/fe/Netas.Nipps.SystemManager.Presentation/App_Start/WebApiConfig.cs
C#
gpl-3.0
859
import { EntityRepository } from 'typeorm'; import LicenceEntity from '../entities/Licence'; import BaseRepository from './BaseRepository'; @EntityRepository(LicenceEntity) export default class LicenceRepository extends BaseRepository<LicenceEntity> {}
antoinejaussoin/retro-board
backend/src/db/repositories/LicenceRepository.ts
TypeScript
gpl-3.0
254
def check_voter(name): if voted.get(name): print("kick them out!") else: voted[name] = True print("let them vote!") book = dict() book["apple"] = 0.67 book["milk"] = 1.49 book["avocado"] = 1.49 print(book) print(book["avocado"]) phone_book = {} phone_book["jenny"] = 711256 phone_book["emergency"] = 1 print(phone_book["jenny"]) voted ={} check_voter("tom") check_voter("kate") check_voter("tom")
serggrom/python-algorithms
Hash-tables.py
Python
gpl-3.0
446
using Abrotelia.Core.Data.Persistence; using Abrotelia.JsonToDb.Extensions; using LiteDB; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abrotelia.JsonToDb { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: json2db <path_of_litedb_file> <import_path>"); Environment.Exit(0); } var dirImport = args[1]; if (!Directory.Exists(dirImport)) { Console.WriteLine($"Directory '{dirImport}' does not exist"); Environment.Exit(0); } using (var db = new LiteDatabase(args[0])) { try { foreach (var file in Directory.GetFiles(dirImport, "*.json")) { var collection = Path.GetFileNameWithoutExtension(file); var json = File.ReadAllText(file); foreach (var value in JsonSerializer.Deserialize(json).AsArray.ToArray()) { var document = value.AsDocument; if ("authors" == collection) { db.GetCollection<PMAuthor>(collection).Insert(document.ToPMAuthor()); } else if ("galleryItems" == collection) { db.GetCollection<PMGalleryItem>(collection).Insert(document.ToPMGalleryItem()); } else if ("pages" == collection) { db.GetCollection<PMPage>(collection).Insert(document.ToPMPage()); } else { db.GetCollection(collection).Insert(document); } } } } catch (Exception ex) { Console.WriteLine($"Napaka:\n{ex.Message}\n{ex.StackTrace}\n\n"); } } } } }
vkocjancic/abrotelia
Abrotelia.JsonToDb/Program.cs
C#
gpl-3.0
2,388
var db = require('../db'); var User = db.model('User', { username: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true, select: false }, active: { type: Boolean, default: true, select: false }, resetToken: { type: String }, resetTokenValid: { type: Date } }); module.exports = User;
MICSTI/ping
models/user.js
JavaScript
gpl-3.0
492
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EspoCRM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ Espo.define('views/fields/date', 'views/fields/base', function (Dep) { return Dep.extend({ type: 'date', editTemplate: 'fields/date/edit', searchTemplate: 'fields/date/search', validations: ['required', 'date', 'after', 'before'], searchTypeOptions: ['lastSevenDays', 'ever', 'currentMonth', 'lastMonth', 'currentQuarter', 'lastQuarter', 'currentYear', 'lastYear', 'today', 'past', 'future', 'lastXDays', 'nextXDays', 'on', 'after', 'before', 'between'], setup: function () { Dep.prototype.setup.call(this); }, data: function () { if (this.mode === 'search') { this.searchData.dateValue = this.getDateTime().toDisplayDate(this.searchParams.dateValue); this.searchData.dateValueTo = this.getDateTime().toDisplayDate(this.searchParams.dateValueTo); } return Dep.prototype.data.call(this); }, setupSearch: function () { this.searchData.typeOptions = this.searchTypeOptions; this.events = _.extend({ 'change select.search-type': function (e) { var type = $(e.currentTarget).val(); this.handleSearchType(type); }, }, this.events || {}); }, stringifyDateValue: function (value) { if (!value) { if (this.mode == 'edit' || this.mode == 'search') { return ''; } return this.translate('None'); } if (this.mode == 'list' || this.mode == 'detail') { if (this.getConfig().get('readableDateFormatDisabled')) { return this.getDateTime().toDisplayDate(value); } var d = moment.utc(value, this.getDateTime().internalDateFormat); var today = moment().tz('UTC').startOf('day'); var dt = today.clone(); var ranges = { 'today': [dt.unix(), dt.add(1, 'days').unix()], 'tomorrow': [dt.unix(), dt.add(1, 'days').unix()], 'yesterday': [dt.add(-3, 'days').unix(), dt.add(1, 'days').unix()] }; if (d.unix() >= ranges['today'][0] && d.unix() < ranges['today'][1]) { return this.translate('Today'); } else if (d.unix() >= ranges['tomorrow'][0] && d.unix() < ranges['tomorrow'][1]) { return this.translate('Tomorrow'); } else if (d.unix() >= ranges['yesterday'][0] && d.unix() < ranges['yesterday'][1]) { return this.translate('Yesterday'); } var readableFormat = this.getDateTime().getReadableDateFormat(); if (d.format('YYYY') == today.format('YYYY')) { return d.format(readableFormat); } else { return d.format(readableFormat + ', YYYY'); } } return this.getDateTime().toDisplayDate(value); }, getValueForDisplay: function () { var value = this.model.get(this.name); return this.stringifyDateValue(value); }, afterRender: function () { if (this.mode == 'edit' || this.mode == 'search') { this.$element = this.$el.find('[name="' + this.name + '"]'); var wait = false; this.$element.on('change', function () { if (!wait) { this.trigger('change'); wait = true; setTimeout(function () { wait = false }, 100); } }.bind(this)); var options = { format: this.getDateTime().dateFormat.toLowerCase(), weekStart: this.getDateTime().weekStart, autoclose: true, todayHighlight: true, }; var language = this.getConfig().get('language'); if (!(language in $.fn.datepicker.dates)) { $.fn.datepicker.dates[language] = { days: this.translate('dayNames', 'lists'), daysShort: this.translate('dayNamesShort', 'lists'), daysMin: this.translate('dayNamesMin', 'lists'), months: this.translate('monthNames', 'lists'), monthsShort: this.translate('monthNamesShort', 'lists'), today: this.translate('Today'), clear: this.translate('Clear'), }; } var options = { format: this.getDateTime().dateFormat.toLowerCase(), weekStart: this.getDateTime().weekStart, autoclose: true, todayHighlight: true, language: language }; var $datePicker = this.$element.datepicker(options).on('show', function (e) { $('body > .datepicker.datepicker-dropdown').css('z-index', 1200); }.bind(this)); if (this.mode == 'search') { var $elAdd = this.$el.find('input[name="' + this.name + '-additional"]'); $elAdd.datepicker(options).on('show', function (e) { $('body > .datepicker.datepicker-dropdown').css('z-index', 1200); }.bind(this)); $elAdd.parent().find('button.date-picker-btn').on('click', function (e) { $elAdd.datepicker('show'); }); } this.$element.parent().find('button.date-picker-btn').on('click', function (e) { this.$element.datepicker('show'); }.bind(this)); if (this.mode == 'search') { var $searchType = this.$el.find('select.search-type'); this.handleSearchType($searchType.val()); } } }, handleSearchType: function (type) { this.$el.find('div.primary').addClass('hidden'); this.$el.find('div.additional').addClass('hidden'); this.$el.find('div.additional-number').addClass('hidden'); if (~['on', 'notOn', 'after', 'before'].indexOf(type)) { this.$el.find('div.primary').removeClass('hidden'); } else if (~['lastXDays', 'nextXDays'].indexOf(type)) { this.$el.find('div.additional-number').removeClass('hidden'); } else if (type == 'between') { this.$el.find('div.primary').removeClass('hidden'); this.$el.find('div.additional').removeClass('hidden'); } }, parseDate: function (string) { return this.getDateTime().fromDisplayDate(string); }, parse: function (string) { return this.parseDate(string); }, fetch: function () { var data = {}; data[this.name] = this.parse(this.$element.val()); return data; }, fetchSearch: function () { var value = this.parseDate(this.$element.val()); var type = this.$el.find('[name="'+this.name+'-type"]').val(); var data; if (type == 'between') { if (!value) { return false; } var valueTo = this.parseDate(this.$el.find('[name="' + this.name + '-additional"]').val()); if (!valueTo) { return false; } data = { type: type, value: [value, valueTo], dateValue: value, dateValueTo: valueTo }; } else if (~['lastXDays', 'nextXDays'].indexOf(type)) { var number = this.$el.find('[name="' + this.name + '-number"]').val(); data = { type: type, value: number, number: number }; } else if (~['on', 'notOn', 'after', 'before'].indexOf(type)) { if (!value) { return false; } data = { type: type, value: value, dateValue: value }; } else { data = { type: type }; } return data; }, validateRequired: function () { if (this.isRequired()) { if (this.model.get(this.name) === null) { var msg = this.translate('fieldIsRequired', 'messages').replace('{field}', this.translate(this.name, 'fields', this.model.name)); this.showValidationMessage(msg); return true; } } }, validateDate: function () { if (this.model.get(this.name) === -1) { var msg = this.translate('fieldShouldBeDate', 'messages').replace('{field}', this.translate(this.name, 'fields', this.model.name)); this.showValidationMessage(msg); return true; } }, validateAfter: function () { var field = this.model.getFieldParam(this.name, 'after'); if (field) { var value = this.model.get(this.name); var otherValue = this.model.get(field); if (value && otherValue) { if (moment(value).unix() <= moment(otherValue).unix()) { var msg = this.translate('fieldShouldAfter', 'messages').replace('{field}', this.translate(this.name, 'fields', this.model.name)) .replace('{otherField}', this.translate(field, 'fields', this.model.name)); this.showValidationMessage(msg); return true; } } } }, validateBefore: function () { var field = this.model.getFieldParam(this.name, 'before'); if (field) { var value = this.model.get(this.name); var otherValue = this.model.get(field); if (value && otherValue) { if (moment(value).unix() >= moment(otherValue).unix()) { var msg = this.translate('fieldShouldBefore', 'messages').replace('{field}', this.translate(this.name, 'fields', this.model.name)) .replace('{otherField}', this.translate(field, 'fields', this.model.name)); this.showValidationMessage(msg); return true; } } } }, }); });
IgorGulyaev/iteamzen
client/src/views/fields/date.js
JavaScript
gpl-3.0
12,615
#include "pyloscoordinat.h" #include <boost/test/unit_test.hpp> using namespace ribi::pylos; BOOST_AUTO_TEST_CASE(pylos_coordinat) { //if (verbose) { TRACE("Test PylosCoordinat operators"); } { const Coordinat c1(0,2,2); const Coordinat c2(0,2,3); const Coordinat c3(0,3,2); const Coordinat c1_too(0,2,2); BOOST_CHECK_NE(c1, c2); BOOST_CHECK_NE(c1, c3); BOOST_CHECK_EQUAL(c1, c1_too); BOOST_CHECK_NE(c2, c3); } //if (verbose) { TRACE("Test Coordinat GetBelow function on (1,0,1)"); } { const std::vector<Coordinat> v = GetBelow(Coordinat(1,0,1)); BOOST_CHECK_EQUAL(v.size(), 4); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(0,0,1)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(0,0,2)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(0,1,1)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(0,1,2)) != v.end()); } //if (verbose) { TRACE("Test Coordinat GetBelow function on (1,0,2)"); } { const std::vector<Coordinat> v = GetBelow(Coordinat(1,0,2)); BOOST_CHECK(v.size() == 4); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(0,0,2)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(0,0,3)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(0,1,2)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(0,1,3)) != v.end()); } //if (verbose) { TRACE("Test Coordinat GetAbove function on (0,0,0)"); } { const std::vector<Coordinat> v = GetAbove(Coordinat(0,0,0)); BOOST_CHECK(v.size() == 1); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(1,0,0)) != v.end()); } //if (verbose) { TRACE("Test Coordinat GetAbove function on (0,1,2)"); } { const std::vector<Coordinat> v = GetAbove(Coordinat(0,1,2)); BOOST_CHECK(v.size() == 4); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(1,0,1)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(1,0,2)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(1,1,1)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(1,1,2)) != v.end()); } //if (verbose) { TRACE("Test Coordinat GetAbove function on (1,2,1)"); } { const std::vector<Coordinat> v = GetAbove(Coordinat(1,2,1)); BOOST_CHECK(v.size() == 2); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(2,1,0)) != v.end()); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(2,1,1)) != v.end()); } //if (verbose) { TRACE("Test Coordinat GetAbove function on (2,0,0)"); } { const std::vector<Coordinat> v = GetAbove(Coordinat(2,0,0)); BOOST_CHECK(v.size() == 1); BOOST_CHECK(std::find(v.begin(),v.end(),Coordinat(3,0,0)) != v.end()); } }
richelbilderbeek/Pylos
pyloscoordinat_test.cpp
C++
gpl-3.0
2,871
/* * This file is part of Transdroid <http://www.transdroid.org> * * Transdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Transdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Transdroid. If not, see <http://www.gnu.org/licenses/>. * */ package org.transdroid.daemon.task; import org.transdroid.daemon.DaemonException; /** * The result daemon task that failed. Use getException() to see what went wrong. * * @author erickok */ public class DaemonTaskFailureResult extends DaemonTaskResult { private DaemonException e; public DaemonTaskFailureResult(DaemonTask executedTask, DaemonException e) { super(executedTask, false); this.e = e; } /** * Return the exception that occurred during the task execution. * * @return A daemon exception object with string res ID or fixed string message */ public DaemonException getException() { return e; } @Override public String toString() { return "Failure on " + executedTask.toString() + ": " + getException().toString(); } }
erickok/transdroid
app/src/main/java/org/transdroid/daemon/task/DaemonTaskFailureResult.java
Java
gpl-3.0
1,543
import { MyseriesService } from '../../services/myseries.service'; import { Component, OnInit, EventEmitter } from '@angular/core'; import { TVMAZE_API_URL } from '../../app.tokens'; import { TvmazeService } from '../../services/tvmaze.service'; import { Serie } from '../../model/serie.model'; @Component({ selector: 'app-seriestable', templateUrl: './seriestable.component.html', styleUrls: ['./seriestable.component.css'], providers: [ { provide: TVMAZE_API_URL, useValue: 'http://api.tvmaze.com/schedule?country=US' }, TvmazeService, MyseriesService], inputs: ['d', 'filter'], outputs: ['noseries'] }) export class SeriestableComponent implements OnInit { private series: Array<Serie>; private d: Date; private filter: string; private field: string; private reverse: boolean; private errorseries: EventEmitter<string>; private myseries: Array<Serie>; constructor(private ts: TvmazeService, private ms: MyseriesService) { this.errorseries = new EventEmitter<string>(); } ngOnInit() { this.field = 'name'; this.reverse = false; this.ts.getSeries(this.d).subscribe( series => this.series = series, error => this.EmitError(error) ); this.getMySeries(); } addToMySeries(serie) { this.ms.addSerie(serie).subscribe( s => {this.getMySeries(); alert(s.name + ' añadida a mis series'); }, error => this.handleError(error) ); } inMySeries(id) { for (let i in this.myseries) { if (this.findById(this.myseries[i], id)) { return true; } }; return false; } private EmitError(error) { this.errorseries.emit('Lista de series no disponible'); } private getMySeries() { this.ms.getSeries().subscribe( series => this.myseries = series, error => this.handleError(error) ); } private findById(element, id) { return (element.id === id); } private handleError(error) { // TODO: do something } }
jorgeas80/webhub
ng2/appseries/src/app/components/seriestable/seriestable.component.ts
TypeScript
gpl-3.0
1,996
using System.Linq; using System.Collections.Generic; using NzbDrone.Core.Qualities; using NzbDrone.Core.Tv; using NzbDrone.Core.MediaFiles.MediaInfo; namespace NzbDrone.Core.Parser.Model { public class LocalMovie { public LocalMovie() { } public string Path { get; set; } public long Size { get; set; } public ParsedMovieInfo ParsedMovieInfo { get; set; } public Movie Movie { get; set; } public QualityModel Quality { get; set; } public MediaInfoModel MediaInfo { get; set; } public bool ExistingFile { get; set; } public override string ToString() { return Path; } } }
jamesmacwhite/Radarr
src/NzbDrone.Core/Parser/Model/LocalMovie.cs
C#
gpl-3.0
713
/** * multipool-stats-backend is a web application which collects statistics * on several Switching-profit crypto-currencies mining pools and display * then in a Browser. * Copyright (C) 2014 Stratehm (stratehm@hotmail.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with multipool-stats-backend. If not, see <http://www.gnu.org/licenses/>. */ package strat.mining.multipool.stats.client.place; import java.util.List; import org.jsonmaker.gwt.client.Jsonizer; public class WafflePoolPlaceDescriptor { public interface WafflePlaceDescriptorJsonizer extends Jsonizer { } private List<String> addresses; private boolean isGlobalCollapsed = false; private boolean isDisplaySummary = true; private boolean isDisplayBTC = true; private boolean isDisplayPower = true; public List<String> getAddresses() { return addresses; } public void setAddresses(List<String> addresses) { this.addresses = addresses; } public boolean isGlobalCollapsed() { return isGlobalCollapsed; } public void setGlobalCollapsed(boolean isGlobalCollapsed) { this.isGlobalCollapsed = isGlobalCollapsed; } public boolean isDisplaySummary() { return isDisplaySummary; } public void setDisplaySummary(boolean isDisplaySummary) { this.isDisplaySummary = isDisplaySummary; } public boolean isDisplayBTC() { return isDisplayBTC; } public void setDisplayBTC(boolean isDisplayBTC) { this.isDisplayBTC = isDisplayBTC; } public boolean isDisplayPower() { return isDisplayPower; } public void setDisplayPower(boolean isDisplayPower) { this.isDisplayPower = isDisplayPower; } }
Stratehm/multipool-stats-backend
src/main/java/strat/mining/multipool/stats/client/place/WafflePoolPlaceDescriptor.java
Java
gpl-3.0
2,141
/* Copyright © Iain McDonald 2012 This file is part of FinancialPricer. FinancialPricer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FinancialPricer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FinancialPricer. If not, see <http://www.gnu.org/licenses/>. */ using System; namespace LbF { [FinancialInstrument(Name = "Bond")] public class BondPricer : Instrument { [FinancialInput] public DayCount DayCountBasis { get; set; } [FinancialInput] public int Period { get; set; } [FinancialOutput] public double Clean { get; set; } [FinancialOutput] public double Accrued { get; private set; } [FinancialOutput] public double YieldToMaturity { get; set; } [FinancialInput] public DateTime HorizonDate { get; set; } [FinancialInput] public double HorizonPrice { get; set; } [FinancialInput] public double HorizonReinvestment { get; set; } [FinancialOutput] public double HorizonPV { get; private set; } [FinancialOutput] public double HorizonYield { get; private set; } [FinancialOutput] public double HorizonGross { get; private set; } public BondPricer() { this.Settlement = DateTime.Parse("1 January 2000"); this.Maturity = DateTime.Parse("1 January 2007"); this.DayCountBasis = DayCount.Thirty360; this.Period = 2; this.Rate = 0.08d; this.Clean = 0.97d; this.YieldToMaturity = 0d; this.Principal = 1000; this.PV = 0d; this.HorizonDate = DateTime.Parse("1 January 2007"); this.HorizonPrice = 1; this.HorizonReinvestment = 0.05d; } protected BondPricer(DateTime settlement, DateTime maturity, DayCount basis, int period, double coupon, double clean, uint principal, double yieldToMaturity, DateTime horizonDate, double horizonPrice, double horizonReinvestment) { this.Settlement = settlement; this.Maturity = maturity; this.DayCountBasis = basis; this.Period = period; this.Rate = coupon; this.Clean = clean; this.YieldToMaturity = yieldToMaturity; this.Principal = principal; this.HorizonDate = horizonDate; this.HorizonPrice = horizonPrice; this.HorizonReinvestment = horizonReinvestment; } public BondPricer(DateTime settlement, DateTime maturity, DayCount basis, int period, double coupon, double clean, uint principal, DateTime horizonDate, double horizonPrice, double horizonReinvestment) : this(settlement, maturity, basis, period, coupon, clean, principal, 0d, horizonDate, horizonPrice, horizonReinvestment) { } public BondPricer(DateTime settlement, DateTime maturity, DayCount basis, int period, double coupon, uint principal, double yieldToMaturity, DateTime horizonDate, double horizonPrice, double horizonReinvestment) : this(settlement, maturity, basis, period, coupon, 0d, principal, yieldToMaturity, horizonDate, horizonPrice, horizonReinvestment) { } public override void Calculate() { CalculatePV(); CalculateYieldToHorizon(); } public double GetCurrentYield() { if (Math.Abs(this.Clean) < Mathematics.Error) CalculateClean(); return this.Rate / this.Clean * 100d; } public double GetAdjustedCurrentYield() { if (Math.Abs(this.Clean) < Mathematics.Error) CalculateClean(); DateTime previousCoupon; DateTime nextCoupon; Basis.GetPreviousNextCoupons(this.Settlement, this.Maturity, this.Period, out previousCoupon, out nextCoupon); var accruedPeriod = Basis.AccruedPeriod(nextCoupon, this.Settlement, this.Period, this.DayCountBasis) / this.Period; var payments = Basis.PaymentCount(this.Maturity, nextCoupon, this.Period) / this.Period; return (this.Rate + ((1 - this.Clean) / (payments + accruedPeriod))) / this.Clean; } public void CalculateYieldToHorizon() { DateTime previousCoupon; DateTime nextCoupon; Basis.GetPreviousNextCoupons(this.HorizonDate, this.Maturity, this.Period, out previousCoupon, out nextCoupon); var accruedPeriod = Basis.AccruedPeriod(this.HorizonDate, previousCoupon, this.Period, this.DayCountBasis); var lastCoupon = previousCoupon; Basis.GetPreviousNextCoupons(this.Settlement, lastCoupon, this.Period, out previousCoupon, out nextCoupon); var payments = Basis.PaymentCount(lastCoupon, nextCoupon, this.Period); Basis.GetPreviousNextCoupons(this.Settlement, this.Maturity, this.Period, out previousCoupon, out nextCoupon); var accruedToPay = Basis.AccruedPeriod(this.Settlement, previousCoupon, this.Period, this.DayCountBasis); var couponsToHorizon = 0d; var payment = (this.Rate / this.Period) * this.Principal; for (var i = 0; i < payments; ++i) couponsToHorizon += payment * Math.Pow(1 + this.HorizonReinvestment / this.Period, i + accruedPeriod); this.HorizonPV = this.HorizonPrice * this.Principal + (accruedPeriod * this.Principal * this.Rate / this.Period) + couponsToHorizon; this.HorizonYield = Math.Pow(Math.Pow(this.HorizonPV / this.PV, 1 / (payments + accruedPeriod - accruedToPay)), this.Period) - 1; this.HorizonGross = this.HorizonPV - this.PV; } public override void CalculatePV() { if (Math.Abs(this.YieldToMaturity) < Mathematics.Error) SolveBondYield(); else CalculateClean(); } private void CalculateClean() { DateTime previousCoupon; DateTime nextCoupon; Basis.GetPreviousNextCoupons(this.Settlement, this.Maturity, this.Period, out previousCoupon, out nextCoupon); var accruedPeriod = Basis.AccruedPeriod(this.Settlement, previousCoupon, this.Period, this.DayCountBasis); var payments = Basis.PaymentCount(this.Maturity, nextCoupon, this.Period); this.Accrued = accruedPeriod * (this.Rate / this.Period) * this.Principal; this.PV = 0d; for (var i = 0; i < payments; ++i) { var payment = (this.Rate / this.Period) * this.Principal; var discountFactor = Math.Pow(1 + this.YieldToMaturity / this.Period, -(1 - accruedPeriod + i)); this.PV += (i == payments - 1) ? (payment + this.Principal) * discountFactor : payment * discountFactor; } this.Clean = this.PV - this.Accrued; } private void SolveBondYield() { DateTime previousCoupon; DateTime nextCoupon; Basis.GetPreviousNextCoupons(this.Settlement, this.Maturity, this.Period, out previousCoupon, out nextCoupon); var accruedPeriod = Basis.AccruedPeriod(this.Settlement, previousCoupon, this.Period, this.DayCountBasis); var payments = Basis.PaymentCount(this.Maturity, nextCoupon, this.Period); this.Accrued = accruedPeriod * (this.Rate / this.Period) * this.Principal; Func<double, double> bondPrice = (calcYield => { var pv = 0d; for (var i = 0; i < payments; ++i) { var payment = (this.Rate / this.Period); var discountFactor = Math.Pow(1 + calcYield / this.Period, -(1 - accruedPeriod + i)); pv += (i == payments - 1) ? (payment + 1) * discountFactor : payment * discountFactor; } return pv - accruedPeriod * (this.Rate / this.Period) - this.Clean; }); this.YieldToMaturity = Mathematics.FindRoot(bondPrice, 0d, 0.5d); this.PV = this.Clean * this.Principal + this.Accrued; } } }
lifebeyondfife/FinancialPricer
BondPricer/BondPricer.cs
C#
gpl-3.0
7,510
package org.outermedia.solrfusion.response.parser; /* * #%L * SolrFusion * %% * Copyright (C) 2014 outermedia GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.xml.bind.annotation.*; import java.util.List; /** * Data holder class keeping the a solr result object. * * @author stephan */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "resultType") @Getter @Setter @ToString public class Result { @XmlAttribute(name = "name", required = true) private String resultName; @XmlAttribute(name = "numFound", required = true) private int numFound; @XmlAttribute(name = "start", required = true) private int start; @XmlAttribute(name = "maxScore", required = true) private float maxScore; @XmlElement(name = "doc", required = true) @Getter @Setter private List<Document> documents; }
outermedia/solr-fusion
src/main/java/org/outermedia/solrfusion/response/parser/Result.java
Java
gpl-3.0
1,565
<?php require_once 'config.php'; $estado = $_POST['estado']; $municipio = $_POST['municipio']; $SQL = "INSERT INTO MUNICIPIO (ID_MUNICIPIO, NOME, ESTADO) VALUES (DEFAULT, ?, ?)"; $stmt = $conn->prepare($SQL); $stmt->bindParam(1, $municipio); $stmt->bindParam(2, $estado); $stmt->execute(); echo "<script>alert('Municipio cadastrado com sucesso!');</script>"; echo "<script language=\"javascript\">window.location=\"municipio.php\";</script>"; ?>
arthurfalcao/WikiLitica
templates/cadastro_municipio.php
PHP
gpl-3.0
452
#!/usr/bin/python # (c) Nelen & Schuurmans. GPL licensed, see LICENSE.txt. from optparse import make_option from django.core.management.base import BaseCommand from lizard_wbconfiguration.models import AreaField from django.db import transaction from django.db.models import get_model import logging logger = logging.getLogger(__name__) class Command(BaseCommand): """ (Remove and re-)insert model field names to wb configuration. """ help = ("Example: bin/django wb_configuration --app=app "\ "--model_name=model") option_list = BaseCommand.option_list + ( make_option('--app', help='app', type='str', default=None), make_option('--model_name', help='Model name.', type='str', default=None)) @transaction.commit_on_success def handle(self, *args, **options): if not options['app'] or not options['model_name']: logger.error("Expected --app and --model args. "\ "Use -help for example.") return model = get_model(options['app'], options['model_name']) for field in model._meta.fields: code = ".".join([options['app'], options['model_name'], field.name]) AreaField.objects.get_or_create( code=code, app_name=options['app'].lower(), model_name=options['model_name'].lower(), field_name=field.name) logger.debug('Inserting "%s" field', field.name)
lizardsystem/lizard-wbconfiguration
lizard_wbconfiguration/management/commands/wb_configuration.py
Python
gpl-3.0
1,672
define([ 'core/js/adapt' ], function (Adapt) { var PopupView = Backbone.View.extend({ className: 'iconpopup__popup', events: { 'click .js-iconpopup-close-btn-click': 'closePopup' }, initialize: function () { this.listenToOnce(Adapt, 'notify:opened', this.onOpened); // Audio this.audioIsEnabled = this.model.get('audioIsEnabled'); if (this.audioIsEnabled) { this.audioChannel = this.model.get('audioChannel'); this.audioSrc = this.model.get('_audio').src; this.audioId = this.model.get('audioId'); } this.render(); }, onOpened: function () { if (!this.audioIsEnabled) return; if (Adapt.audio.audioClip[this.audioChannel].status==1) { Adapt.audio.audioClip[this.audioChannel].onscreenID = ""; Adapt.trigger('audio:playAudio', this.audioSrc, this.audioId, this.audioChannel); } }, render: function () { var data = this.model.toJSON(); var template = Handlebars.templates['popup']; this.$el.html(template(data)); }, closePopup: function (event) { Adapt.trigger('notify:close'); } }); return PopupView; });
deltanet/adapt-icon-popup
js/popupView.js
JavaScript
gpl-3.0
1,192
#!/usr/bin/env python3 # -*- coding: utf8 -*- """Module to upload standin plans. This module is there in order to parse, figure out and uploads standin plans for the FLS Wiesbaden framework. """ __all__ = [] __version__ = '4.36.1' __author__ = 'Lukas Schreiner' import urllib.parse import urllib.error import traceback import sys import os import os.path import json import base64 import configparser import shutil import pickle import requests import glob from requests.auth import HTTPBasicAuth from threading import Thread from datetime import datetime from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject from PyQt5.QtGui import QIcon from searchplaner import SearchPlaner from errorlog import ErrorDialog from planparser import getParser from planparser.untis import Parser as UntisParser import sentry_sdk # absolute hack, but required for cx_Freeze to work properly. if sys.platform == 'win32': import PyQt5.sip APP = None APPQT = None class WatchFile(object): """A file which is or was watched in order to retrieve information""" def __init__(self, path, fname): self.path = path self.name = fname stInfo = os.stat(self.getFullName) self.mtime = stInfo.st_mtime self.atime = stInfo.st_atime @property def getFullName(self): return '%s/%s' % (self.path, self.name) class Vertretungsplaner(QObject): showDlg = pyqtSignal() hideDlg = pyqtSignal() message = pyqtSignal(str, str, int, int) cleanupDlg = pyqtSignal() def getWatchPath(self): return self.config.get("default", "path") def getSendURL(self): return self.config.get("default", "url") def getAPIKey(self): return self.config.get("default", "api") def getStatus(self): return self.locked def getOption(self, name): return self.config.has_option('options', name) and self.config.get('options', name) in ['True', True] def getIntervall(self): return float(self.config.get("default", "intervall")) def isProxyEnabled(self): return self.config.getboolean('proxy', 'enable', fallback=False) def getRun(self): return self.run def setRun(self, run): self.run = run def showInfo(self, title, msg): self.showToolTip(title, msg, 'info') def showError(self, title, msg): self.showToolTip(title, msg, 'error') def showToolTip(self, title, msg, msgtype): trayIcon = QSystemTrayIcon.Critical if msgtype == 'error' else QSystemTrayIcon.Information timeout = 10000 self.message.emit(title, msg, trayIcon, timeout) def getHandler(self, fileName): extension = os.path.splitext(fileName)[-1].lower() ptype = self.config.get('vplan', 'type') return getParser(extension, self.config) @pyqtSlot() def getNewFiles(self): print('Starte suche...') self.locked = True pathToWatch = self.getWatchPath() try: after = dict([(f, WatchFile(pathToWatch, f)) for f in os.listdir(pathToWatch)]) except FileNotFoundError: print('\nCould not poll directory %s (does not exist!)' % (pathToWatch,)) # try recreate the directory (maybe it does not exist in base path: try: os.makedirs(pathToWatch) except: pass self.locked = False return added = [f for f in after if not f in self.before] removed = [f for f in self.before if not f in after] same = [f for f in after if f in self.before] changed = [f for f in same if self.before[f].mtime != after[f].mtime] todo = added + changed if todo: print("\nChanged/Added new Files: ", ", ".join(todo)) for f in todo: f = f.strip() handler = self.getHandler(f) if handler: transName = '{}_{}_{}'.format( datetime.now().strftime('%Y-%m-%dT%H%M%S'), self.config.get('sentry', 'transPrefix', fallback='n'), f.replace(' ', '_') ) with sentry_sdk.start_transaction(op='parseUploadPlan', name=transName) as transaction: try: self.parsePlanByHandler(transaction, handler, f) except Exception as e: sentry_sdk.capture_exception(e) self.showError( 'Neuer Vertretungsplan', 'Vertretungsplan konnte nicht verarbeitet ' + \ 'werden, weil die Datei fehlerhaft ist.' ) print('Error: %s' % (str(e),)) traceback.print_exc() self.dlg.addError(str(e)) #FIXME: self.showDlg.emit() raise print('Ending transaction {}'.format(transName)) transaction.finish() # for untis, we parse only the first one! if handler.onlyFirstFile(): break else: print('"%s" will be ignored.' % (f,)) if removed: print("\nRemoved files: ", ", ".join(removed)) self.before = after self.locked = False def initPlan(self): pathToWatch = self.getWatchPath() try: if not os.path.exists(pathToWatch): os.makedirs(pathToWatch) self.before = dict([(f, WatchFile(pathToWatch, f)) for f in os.listdir(pathToWatch)]) except FileNotFoundError: print('\nCould not poll directory %s (does not exist!)' % (pathToWatch,)) self.before = {} # Now start Looping self.search = Thread(target=SearchPlaner, args=(self,)).start() def sendPlan(self, transaction, table, absFile, planType='all'): data = json.dumps(table).encode('utf-8') # check what we need to do. # 1st we need to save the data? if self.config.getboolean('options', 'saveResult'): destFileName = os.path.join( self.config.get('default', 'resultPath'), 'vplan-result-{:s}.json'.format(datetime.now().strftime('%Y-%m-%d_%H%M%S_%f')) ) if not os.path.exists(os.path.dirname(destFileName)): os.makedirs(os.path.dirname(destFileName)) with open(destFileName, 'wb') as f: f.write('Type: {:s}\n'.format(planType).encode('utf-8')) f.write(data) if self.config.getboolean('options', 'upload'): data = base64.b64encode(data).decode('utf-8').replace('\n', '') values = { 'apikey': base64.b64encode(self.getAPIKey().encode('utf-8')).decode('utf-8').replace('\n', ''), 'data': data, 'type': planType } values = urllib.parse.urlencode(values) if self.getOption('debugOnline'): values['XDEBUG_SESSION_START'] = '1' proxies = None if self.isProxyEnabled(): print('Proxy is activated') httpproxy = "http://"+self.config.get("proxy", "phost")+":"+self.config.get("proxy", "pport") proxies = { "http" : httpproxy, "https": httpproxy } transaction.set_data('http.proxy_uri', httpproxy) transaction.set_tag('http.proxy', True) else: print('Proxy is deactivated') transaction.set_tag('http.proxy', False) headers = {} httpauth = None if self.config.has_option("siteauth", "enable") and self.config.get("siteauth", "enable") == 'True': httpauth = HTTPBasicAuth( self.config.get('siteauth', 'username'), self.config.get('siteauth', 'password') ) transaction.set_tag('http.basic_auth', True) else: transaction.set_tag('http.basic_auth', False) # add post info headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8' errorMessage = None errObj = None try: req = requests.post(self.getSendURL(), data=values, proxies=proxies, headers=headers, auth=httpauth) except requests.exceptions.ConnectionError as err: self.createCoreDump(err) errorMessage = ( 'Warnung', 'Der Vertretungsplan konnte eventuell nicht korrekt hochgeladen werden. ' 'Bitte kontaktieren Sie das Website-Team der FLS! ' 'Beim Hochladen konnte keine Verbindung zum Server aufgebaut werden.' ) errObj = err print('HTTP-Fehler aufgetreten: {:s}'.format(str(err))) sentry_sdk.capture_exception(err) except urllib.error.URLError as err: self.createCoreDump(err) errorMessasge = ( 'Warnung', 'Der Vertretungsplan konnte eventuell nicht korrekt hochgeladen werden. \ Bitte kontaktieren Sie das Website-Team der FLS!' ) errObj = err print('URL-Fehler aufgetreten: {:s}'.format(err.reason)) sentry_sdk.capture_exception(err) except Exception as err: self.createCoreDump(err) errorMessage = ( 'Warnung', 'Der Vertretungsplan konnte eventuell nicht korrekt hochgeladen werden. \ Bitte kontaktieren Sie das Website-Team der FLS!' ) errObj = err print("Unbekannter Fehler aufgetreten: ", err) sentry_sdk.capture_exception(err) else: transaction.set_tag('http.status_code', req.status_code) transaction.set_data('http.text', req.text) if req.status_code != 204: errorMessage = ( 'Warnung', 'Der Vertretungsplan konnte eventuell nicht korrekt hochgeladen werden. ' 'Es wurde ein abweichender Statuscode erhalten: {:d}'.format(req.status_code) ) errObj = req.text else: print(req.text) print('Erfolgreich hochgeladen.') # any error to show in detail to user? if errorMessage: transaction.set_data('vplan.send_error', errorMessage) if errObj: self.dlg.addData(str(errObj)) self.showError(*errorMessage) self.dlg.addError(errorMessage[1]) else: self.showInfo('Vertretungsplan hochgeladen', 'Die Datei wurde erfolgreich hochgeladen.') # now move the file and save an backup. Also delete the older one. self.moveAndDeleteVPlanFile(absFile) def createCoreDump(self, err): if not self.getOption('createCoreDump'): return try: __file__ except NameError: __file__ = 'flsvplan.py' path = os.path.dirname(__file__) if os.path.dirname(__file__) else sys.path[0] if path and not os.path.isdir(path): path = os.path.dirname(path) path = '%s%scoredump' % (path, os.sep) filename = '%s%s%s-%s.dump' % (path, os.sep, __file__, datetime.now().strftime('%Y%m%d%H%M%S%f')) # truncate folder if os.path.exists(path): shutil.rmtree(path, ignore_errors=False, onerror=None) os.makedirs(path) dump = {} dump['tb'] = traceback.format_exc() dump['tbTrace'] = {} dump['err'] = self.dumpObject(err) excInfo = sys.exc_info() i = 0 while i < len(excInfo): dump['tbTrace'][i] = 'No args available: %s' % (excInfo[i],) i += 1 with open(filename, 'wb') as f: pickle.dump(dump, f, protocol=pickle.HIGHEST_PROTOCOL) print('Coredump created in %s' % (filename,)) def dumpObject(self, obj): struc = {} for k, v in vars(obj).items(): if not k.startswith('_') and k != 'fp': try: struc[k] = self.dumpObject(v) except: struc[k] = v return struc def moveAndDeleteVPlanFile(self, absFile): # file => Actual file (move to lastFile) # self.lastFile => last File (delete) path = absFile if os.path.exists(self.lastFile) and self.lastFile != '': # delete os.remove(self.lastFile) print('File %s removed' % (self.lastFile)) # move newFile = '' if self.config.get('options', 'backupFiles') == 'True': newFile = "%s.backup" % (path) if self.config.get('options', 'backupFolder') != 'False': backdir = self.config.get('options', 'backupFolder') if backdir[-1:] is not os.sep: backdir = '%s%s' % (backdir, os.sep) newFile = '%s%s%s%s.backup' % (self.getWatchPath(), os.sep, backdir, path) # before: check if folder eixsts. backdir = '%s%s%s' % (self.getWatchPath(), os.sep, backdir) if not os.path.exists(backdir): os.makedirs(backdir) print('Copy %s to %s for backup.' % (path, newFile)) shutil.copyfile(path, newFile) if self.config.get('options', 'delUpFile') == 'True' and os.path.exists(path): print('Delete uploaded file %s' % (path)) os.remove(path) folderPath = os.path.dirname(path) if self.config.get('options', 'delFolder') == 'True' and os.path.exists(folderPath): for filename in glob.iglob(folderPath + '/*'): try: os.remove(filename) except: pass self.lastFile = newFile def parsePlanByHandler(self, transaction, hdl, fileName): # send a notification self.showInfo('Neuer Vertretungsplan', 'Es wurde eine neue Datei gefunden und wird jetzt verarbeitet.') absPath = os.path.join(self.config.get('default', 'path'), fileName) djp = hdl(self.config, self.dlg, absPath) djp.planFileLoaded.connect(self.planFileLoaded) djp.planParserPrepared.connect(self.planParserPrepared) with transaction.start_child(op='parse::loadFile', description=fileName) as transChild: djp.loadFile(transChild) with transaction.start_child(op='parse::preParse', description=fileName): djp.preParse(transChild) with transaction.start_child(op='parse::parse', description=fileName): djp.parse(transChild) with transaction.start_child(op='parse::postParse', description=fileName): djp.postParse(transChild) data = djp.getResult() data['system'] = { 'version': __version__, 'handler': hdl.__name__, 'fname': absPath } self.showInfo('Neuer Vertretungsplan', 'Vertretungsplan wurde verarbeitet und wird nun hochgeladen.') with transaction.start_child(op='parse::sendPlan', description=fileName): self.sendPlan(transChild, data, absPath) # something to show? if self.dlg.hasData: self.showDlg.emit() @pyqtSlot() def planFileLoaded(self): pass @pyqtSlot() def planParserPrepared(self): if self.dlg.isVisible(): self.hideDlg.emit() self.cleanupDlg.emit() def loadConfig(self): self.config = configparser.ConfigParser() self.config.read(["config.ini"], encoding='utf-8') @pyqtSlot() def bye(self): global APPQT self.run = False sys.exit(0) def initTray(self): self.tray = QSystemTrayIcon(QIcon('logo.ico'), self) menu = QMenu('FLS Vertretungsplaner') menu.addAction('Planer hochladen', self.getNewFiles) menu.addAction('Beenden', self.bye) self.tray.setContextMenu(menu) self.message.connect(self.tray.showMessage) self.tray.show() self.showInfo( 'Vertretungsplaner startet...', 'Bei Problemen wenden Sie sich bitte an das Website-Team der Friedrich-List-Schule Wiesbaden.' ) def initSentry(self): # check if sentry is enabled. if not self.config.getboolean('sentry', 'enable', fallback=False) \ or not self.config.get('sentry', 'sendsn', fallback=None): return try: import sentry_sdk except: pass else: # proxy settings? if self.isProxyEnabled(): httpproxy = "http://"+self.config.get("proxy", "phost")+":"+self.config.get("proxy", "pport") else: httpproxy = None def logSentrySend(event, hint): print('Now sending sentry data!!!') sentry_sdk.init( self.config.get('sentry', 'sendsn'), max_breadcrumbs=self.config.getint('sentry', 'maxBreadcrumbs', fallback=50), debug=self.config.getboolean('sentry', 'debug', fallback=False), send_default_pii=self.config.getboolean('sentry', 'pii', fallback=False), environment=self.config.get('sentry', 'environment', fallback=None), sample_rate=self.config.getfloat('sentry', 'sampleRate', fallback=1.0), traces_sample_rate=self.config.getfloat('sentry', 'tracesSampleRate', fallback=1.0), http_proxy=httpproxy, https_proxy=httpproxy, before_send=logSentrySend, release=__version__ ) self._sentryEnabled = True def __init__(self): super().__init__() self.lastFile = '' self.run = True self.config = None self.tray = None self.search = None self.before = None self.locked = False self._sentryEnabled = False self.loadConfig() self.initSentry() self.initTray() debugLog = self.config.getboolean('options', 'debugLogs', fallback=False) self.dlg = ErrorDialog(debugLog) self.showDlg.connect(self.dlg.open) self.hideDlg.connect(self.dlg.close) self.cleanupDlg.connect(self.dlg.cleanup) self.initPlan() if __name__ == '__main__': APPQT = QApplication(sys.argv) APPQT.setQuitOnLastWindowClosed(False) APP = Vertretungsplaner() sys.exit(APPQT.exec_())
FLS-Wiesbaden/vplanUploader
flsvplan.py
Python
gpl-3.0
15,692
using System.Threading; using Selkie.Services.Monitor.SpecFlow.Steps.Common; using TechTalk.SpecFlow; namespace Selkie.Services.Monitor.SpecFlow.Steps { public class GivenIWaitUntilServicesAreRunningStep : BaseStep { [Given(@"I wait until services are running")] public override void Do() { Thread.Sleep(30000); } } }
tschroedter/Selkie.Services.Monitor
Selkie.Services.Monitor.SpecFlow/Steps/GivenIWaitUntilServicesAreRunningStep.cs
C#
gpl-3.0
377
package alexiil.mc.mod.items; import java.lang.reflect.Field; import java.util.*; import java.util.Map.Entry; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import org.apache.commons.lang3.mutable.MutableLong; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.item.ItemExpireEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; import net.minecraftforge.fml.common.gameevent.TickEvent.WorldTickEvent; public class ItemCacheHandler { private static final Map<World, Map<ChunkPos, Deque<EntityItem>>> cachedItems = new MapMaker().weakKeys().makeMap(); private static final Map<World, Map<ChunkPos, Integer>> chunkStats = new MapMaker().weakKeys().makeMap(); private static final Map<World, MutableLong> startProfiling = new MapMaker().weakKeys().makeMap(); private static final Field entityItemAge, entityItemPickupDelay; static { Class<EntityItem> cls = EntityItem.class; Field[] fields = cls.getDeclaredFields(); entityItemAge = fields[2]; entityItemAge.setAccessible(true); EternalItems.log.info("[set-age] Got field: " + entityItemAge); entityItemPickupDelay = fields[3]; entityItemPickupDelay.setAccessible(true); EternalItems.log.info("[get-pickup-delay] Got field: " + entityItemPickupDelay); } public static void preInit() {} private static Map<ChunkPos, Deque<EntityItem>> getCachedItems(World world) { if (cachedItems.containsKey(world)) return cachedItems.get(world); throw new Error("Tried to get a list of cached items before the world was loaded, this will not persist!"); // Deque<EntityItem> items = Queues.newArrayDeque(); // cachedItems.put(world, items); // return items; } private static Deque<EntityItem> getCachedItems(World world, ChunkPos ccip) { Map<ChunkPos, Deque<EntityItem>> map = getCachedItems(world); if (!map.containsKey(ccip)) { map.put(ccip, new ArrayDeque<EntityItem>()); } return map.get(ccip); } private static Map<ChunkPos, Integer> getChunkMap(World world) { if (chunkStats.containsKey(world)) return chunkStats.get(world); throw new Error("Tried to get a list of chunks before the world was loaded, this will not persist!"); // Map<Chunk, Integer> items = new MapMaker().weakKeys().makeMap(); // chunkStats.put(world, items); // return items; } private static void incrementChunkStat(World world, Chunk chunk) { Map<ChunkPos, Integer> stats = getChunkMap(world); ChunkPos ccip = chunk.getPos(); if (!stats.containsKey(ccip)) { stats.put(ccip, 1); } else { stats.put(ccip, stats.get(ccip) + 1); } } // FIXME: Cache this value dammit! This probably really expensive and called multiple times per tick when it really // doesn't need to be. private static int getNumberOfItems(World world) { return world.getEntities(EntityItem.class, Predicates.alwaysTrue()).size(); } // FIXME: Cache this value dammit! This probably really expensive and called multiple times per tick when it really // doesn't need to be. private static int getNumberOfItems(World world, ChunkPos ccip) { return world.getEntities(EntityItem.class, new ChunkPredicate(ccip)).size(); } public static void worldLoaded(WorldEvent.Load event) { WorldServer world = (WorldServer) event.getWorld(); ItemWorldSaveHandler items; try { ItemWorldSaveHandler.WORLD_HOLDER.set(world); WorldSavedData data = world.getPerWorldStorage().getOrLoadData(ItemWorldSaveHandler.class, ItemWorldSaveHandler.NAME); if (data == null) { items = new ItemWorldSaveHandler(ItemWorldSaveHandler.NAME); world.getPerWorldStorage().setData(ItemWorldSaveHandler.NAME, items); } else { items = (ItemWorldSaveHandler) data; } } finally { ItemWorldSaveHandler.WORLD_HOLDER.set(null); } cachedItems.put(world, items.getItems()); chunkStats.put(world, items.getChunkStats()); startProfiling.put(world, items.getStartProfiling()); } public static void itemAdded(EntityJoinWorldEvent event) { World world = event.getWorld(); world.theProfiler.startSection("eternalitems"); world.theProfiler.startSection("item_added"); EntityItem item = (EntityItem) event.getEntity(); int itemsInWorld = getNumberOfItems(world); ChunkPos ccip = new ChunkPos(((int) item.posX) >> 4, ((int) item.posZ) >> 4); Deque<EntityItem> items = getCachedItems(world, ccip); if (itemsInWorld >= EternalItems.getMaxItems() || getNumberOfItems(world, ccip) > EternalItems.getMaxItemsChunk()) { // Don't add the item to the world, instead add it to the cached queue event.setCanceled(true); items.add(item); } Chunk chunk = world.getChunkFromBlockCoords(item.getPosition()); incrementChunkStat(world, chunk); world.theProfiler.endSection(); world.theProfiler.endSection(); } private static boolean setAgeTo0(EntityItem entity) { try { // TODO: Use an access transformer instead of this slow reflection entityItemAge.set(entity, new Integer(0)); return true; } catch (IllegalArgumentException e) { EternalItems.log.warn("[set-age] Did you select the wrong field AlexIIL?", e); } catch (IllegalAccessException e) { EternalItems.log.warn("[set-age] Did you not give yourself access to it properly AlexIIL?", e); } return false; } private static int getPickupDelay(EntityItem entity) { try { // TODO: Use an access transformer instead of this slow reflection return entityItemPickupDelay.getInt(entity); } catch (IllegalArgumentException e) { EternalItems.log.warn("[get-pickup-delay] Did you select the wrong field AlexIIL?", e); } catch (IllegalAccessException e) { EternalItems.log.warn("[get-pickup-delay] Did you not give yourself access to it properly AlexIIL?", e); } return 0; } public static void itemExpired(ItemExpireEvent event) { EntityItem item = event.getEntityItem(); if (item.isDead) return; if (getPickupDelay(item) == 32767) return;// Infinite pickup delay World world = item.world; world.theProfiler.startSection("eternalitems"); world.theProfiler.startSection("item_expire"); int itemsInWorld = getNumberOfItems(world); ChunkPos ccip = new ChunkPos(((int) item.posX) >> 4, ((int) item.posZ) >> 4); Deque<EntityItem> items = getCachedItems(world, ccip); if (setAgeTo0(item)) { item.lifespan = 1000; } else { item.lifespan += 1000; } boolean spaceInWorld = itemsInWorld < EternalItems.getMaxItems(); if (!spaceInWorld) { items.add(item); } else { int itemsInChunk = getNumberOfItems(world, ccip); boolean spaceInChunk = itemsInChunk < EternalItems.getMaxItemsChunk(); if (!spaceInChunk) { items.add(item); } else { event.setExtraLife(1000); event.setCanceled(true); } } world.theProfiler.endSection(); world.theProfiler.endSection(); } public static void worldTick(WorldTickEvent worldTickEvent) { if (!worldTickEvent.phase.equals(Phase.END)) return; World world = worldTickEvent.world; world.theProfiler.startSection("eternalitems"); world.theProfiler.startSection("world_tick"); tryAddItems(world, getCachedItems(world)); world.theProfiler.endSection(); world.theProfiler.endSection(); } private static void tryAddItems(World world, Map<ChunkPos, Deque<EntityItem>> map) { while (addItem(world, map)); } /** @return <code>True</code> if an item from the queue was added to the world without going over the item cap */ private static boolean addItem(World world, Map<ChunkPos, Deque<EntityItem>> map) { if (map.isEmpty()) return false; int itemsInWorld = getNumberOfItems(world); if (itemsInWorld >= EternalItems.getMaxItems()) return false; boolean added = false; for (ChunkPos ccip : map.keySet()) { Deque<EntityItem> queue = map.get(ccip); if (queue.isEmpty()) continue; boolean spaceInChunk = getNumberOfItems(world, ccip) < EternalItems.getMaxItemsChunk(); if (!spaceInChunk) { continue; } EntityItem entity = queue.remove(); entity.world = world;// If this has been loaded, then it could be null, so just set it anyway world.spawnEntity(entity); itemsInWorld++; added = true; if (itemsInWorld >= EternalItems.getMaxItems()) { return true; } } return added; } public static ITextComponent[] getDebugLines(World world) { Map<ChunkPos, Deque<EntityItem>> items = getCachedItems(world); ITextComponent[] lines = new ITextComponent[2]; int numInWorld = getNumberOfItems(world); int max = EternalItems.getMaxItems(); lines[0] = new TextComponentTranslation(Lib.LocaleStrings.CHAT_STATS_ITEM_COUNT, numInWorld, max); int size = 0; int numChunks = 0; for (Entry<ChunkPos, Deque<EntityItem>> entry : items.entrySet()) { int added = entry.getValue().size(); size += added; if (added > 0) { numChunks++; } } lines[1] = new TextComponentTranslation(Lib.LocaleStrings.CHAT_STATS_CACHE_SIZE, size, numChunks); return lines; } public static String[] getItemPositionInfo(World world) { List<EntityItem> items = world.getEntities(EntityItem.class, Predicates.alwaysTrue()); String[] lines = new String[items.size()]; for (int i = 0; i < items.size(); i++) { EntityItem item = items.get(i); lines[i] = item.toString(); } return lines; } public static void resetChunkStats(World world) { getChunkMap(world).clear(); MutableLong mutLong = startProfiling.get(world); mutLong.setValue(world.getTotalWorldTime()); } public static ITextComponent[] getChunkStats(World world) { ITextComponent[] lines = new ITextComponent[6]; long length = world.getTotalWorldTime() - startProfiling.get(world).getValue(); lines[0] = new TextComponentTranslation(Lib.LocaleStrings.CHAT_STATS_CHUNK_MOST_ITEMS_HEADER, length); // "Showing the 5 highest item producing chunks since " + length + " ticks ago"; final Map<ChunkPos, Integer> chunkMap = getChunkMap(world); Set<ChunkPos> chunks = chunkMap.keySet(); List<ChunkPos> sortedChunks = Lists.newArrayList(); sortedChunks.addAll(chunks); Collections.sort(sortedChunks, new Comparator<ChunkPos>() { @Override public int compare(ChunkPos o1, ChunkPos o2) { int one = chunkMap.get(o1); int two = chunkMap.get(o2); return two - one; } }); for (int i = 0; i < 5; i++) { if (i >= sortedChunks.size()) { lines[i + 1] = new TextComponentTranslation(Lib.LocaleStrings.CHAT_STATS_CHUNK_MOST_ITEMS_NO_MORE); break; } ChunkPos ccip = sortedChunks.get(i); int num = chunkMap.get(ccip); boolean plural = num != 1; String chunkCoords = "[" + ccip.chunkXPos + ", " + ccip.chunkZPos + "]"; String key = plural ? Lib.LocaleStrings.CHAT_STATS_CHUNK_MOST_ITEMS_PLURAL : Lib.LocaleStrings.CHAT_STATS_CHUNK_MOST_ITEMS_SINGULAR; lines[i + 1] = new TextComponentTranslation(key, num, chunkCoords); } return lines; } private static class ChunkPredicate implements Predicate<Entity> { private final ChunkPos ccip; private ChunkPredicate(ChunkPos ccip) { this.ccip = ccip; } @Override public boolean apply(Entity input) { return input.posX - ccip.getXStart() <= 16 && input.posZ - ccip.getZStart() <= 16; } } }
AlexIIL/EternalItems
src/main/java/alexiil/mc/mod/items/ItemCacheHandler.java
Java
gpl-3.0
13,403
/* ... */ private ContatoHelper helper; private Button btSalvar; @Override public void onCreate(Bundle icicle) { /* ... */ helper = new ContatoHelper(this); carregar(); ir(); /* ... */ } private void carregar() { /* ... */ btSalvar = (Button) findViewById(R.id.bt_salvar); } private void ir() { btSalvar.setOnClickListener(new OnClickListener() { public void onClick(View view) { ContentValues values = new ContentValues(); values.put("nome", etNome.getText().toString()); values.put("telefone", etTefone.getText().toString()); values.put("email", etEmail.getText().toString()); helper.criar(values); finish(); } }); } @Override protected void onDestroy() { super.onDestroy(); helper.close(); }
atilacamurca/guia-aberto-android
source/SalvarActivity-2.java
Java
gpl-3.0
777
#include <cts-gui/scripting/luatablewidget.h> #include <cassert> namespace cts { namespace gui { LuaTableTreeWidget::LuaTableTreeWidget(sol::state* luaState, LuaTreeItem::ModelStyle modelStyle, QWidget* parent /*= 0*/) : QTreeView(parent) , m_luaState(luaState) , m_modelStyle(modelStyle) , m_treeModel(nullptr) , m_sortModel(nullptr) { setupWidget(); setLuaState(m_luaState, m_modelStyle); } void LuaTableTreeWidget::setLuaState(sol::state* luaState, LuaTreeItem::ModelStyle modelStyle) { m_luaState = luaState; m_modelStyle = modelStyle; update(); } void LuaTableTreeWidget::update() { // clear selection before setting the new data or we will encounter random crashes... selectionModel()->clear(); // set new data m_treeModel->setData(m_luaState, m_modelStyle); m_sortModel->sort(0); expandToDepth(0); // adjust view resizeColumnToContents(0); resizeColumnToContents(1); resizeColumnToContents(2); } void LuaTableTreeWidget::setupWidget() { m_treeModel = new LuaItemModel(this); m_sortModel = new QSortFilterProxyModel(this); m_sortModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_sortModel->setSortLocaleAware(true); m_sortModel->setSourceModel(m_treeModel); setModel(m_sortModel); setSortingEnabled(true); } LuaItemModel* LuaTableTreeWidget::getTreeModel() { return m_treeModel; } } }
Schulteatq/CityTrafficSimulatorPlusPlus
cts-gui/src/scripting/luatablewidget.cpp
C++
gpl-3.0
1,382
#!/usr/bin/env ruby require 'solidruby' include SolidRuby r = import(f: 'example013.dxf') .linear_extrude(h: 100, center: true, co: 3) r *= import(f: 'example013.dxf') .linear_extrude(h: 100, ce: true, co: 3) .rotate(y: 90) r *= import(f: 'example013.dxf') .linear_extrude(h: 100, ce: true, co: 3) .rotate(x: 90) r.save('example013.scad') # echo(version=version()); # # intersection() { # linear_extrude(height = 100, center = true, convexity= 3) # import(file = "example013.dxf"); # rotate([0, 90, 0]) # linear_extrude(height = 100, center = true, convexity= 3) # import(file = "example013.dxf"); # rotate([90, 0, 0]) # linear_extrude(height = 100, center = true, convexity= 3) # import(file = "example013.dxf"); # }
MC-Squared/SolidRuby
examples/openscad_examples/old/example013.rb
Ruby
gpl-3.0
764
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /*jshint globalstrict: false */ // Initializing PDFJS global object (if still undefined) if (typeof PDFJS === 'undefined') { (typeof window !== 'undefined' ? window : this).PDFJS = {}; } PDFJS.version = '1.0.21'; PDFJS.build = 'f954cde'; (function pdfjsWrapper() { // Use strict in our context only - users might not want it 'use strict'; /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ /* Copyright 2012 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL, Promise */ 'use strict'; var globalScope = (typeof window === 'undefined') ? this : window; var isWorker = (typeof window == 'undefined'); var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; // The global PDFJS object exposes the API // In production, it will be declared outside a global wrapper // In development, it will be declared here if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } globalScope.PDFJS.pdfBug = false; PDFJS.VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = PDFJS.OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90 }; // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { // If multiple arguments were passed, pass them all to the log function. if (arguments.length > 1) { var logArguments = ['Error:']; logArguments.push.apply(logArguments, arguments); console.log.apply(console, logArguments); // Join the arguments into a single string for the lines below. msg = [].join.call(arguments, ' '); } else { console.log('Error: ' + msg); } console.log(backtrace()); UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown); throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; var UnsupportedManager = PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { listeners.push(cb); }, notify: function (featureId) { warn('Unsupported feature "' + featureId + '"'); for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); // Combines two URLs. The baseUrl shall be absolute URL. If the url is an // absolute URL, it will be returned as is. function combineUrl(baseUrl, url) { if (!url) { return baseUrl; } if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) { return url; } var i; if (url.charAt(0) == '/') { // absolute path i = baseUrl.indexOf('://'); if (url.charAt(1) === '/') { ++i; } else { i = baseUrl.indexOf('/', i + 3); } return baseUrl.substring(0, i) + url; } else { // relative path var pathLength = baseUrl.length; i = baseUrl.lastIndexOf('#'); pathLength = i >= 0 ? i : pathLength; i = baseUrl.lastIndexOf('?', pathLength); pathLength = i >= 0 ? i : pathLength; var prefixLength = baseUrl.lastIndexOf('/', pathLength); return baseUrl.substring(0, prefixLength + 1) + url; } } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url) { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': return true; default: return false; } } PDFJS.isValidUrl = isValidUrl; function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } var PasswordResponses = PDFJS.PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); function bytesToString(bytes) { var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToArray(str) { var length = str.length; var array = []; for (var i = 0; i < length; ++i) { array[i] = str.charCodeAt(i); } return array; } function stringToBytes(str) { var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { return shadow(PDFJS, 'isLittleEndian', isLittleEndian()); } }); // Lazy test if the userAgant support CanvasTypedArrays function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays()); } }); var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = PDFJS.Util = (function UtilClosure() { function Util() {} Util.makeCssRgb = function Util_makeCssRgb(rgb) { return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')'; }; Util.makeCssCmyk = function Util_makeCssCmyk(cmyk) { var rgb = ColorSpace.singletons.cmyk.getRgb(cmyk, 0); return Util.makeCssRgb(rgb); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; // TODO(mack): Rename appendToArray Util.concatenateToArray = function concatenateToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function concatenateToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() { function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = { clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v == 'boolean'; } function isInt(v) { return typeof v == 'number' && ((v | 0) == v); } function isNum(v) { return typeof v == 'number'; } function isString(v) { return typeof v == 'string'; } function isNull(v) { return v === null; } function isName(v) { return v instanceof Name; } function isCmd(v, cmd) { return v instanceof Cmd && (!cmd || v.cmd == cmd); } function isDict(v, type) { if (!(v instanceof Dict)) { return false; } if (!type) { return true; } var dictType = v.get('Type'); return isName(dictType) && dictType.name == type; } function isArray(v) { return v instanceof Array; } function isStream(v) { return typeof v == 'object' && v !== null && v !== undefined && ('getBytes' in v); } function isArrayBuffer(v) { return typeof v == 'object' && v !== null && v !== undefined && ('byteLength' in v); } function isRef(v) { return v instanceof Ref; } function isPDFFunction(v) { var fnDict; if (typeof v != 'object') { return false; } else if (isDict(v)) { fnDict = v; } else if (isStream(v)) { fnDict = v.dict; } else { return false; } return fnDict.has('FunctionType'); } /** * Legacy support for PDFJS Promise implementation. * TODO remove eventually * @ignore */ var LegacyPromise = PDFJS.LegacyPromise = (function LegacyPromiseClosure() { return function LegacyPromise() { var resolve, reject; var promise = new Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); promise.resolve = resolve; promise.reject = reject; return promise; }; })(); /** * Polyfill for Promises: * The following promise implementation tries to generally implment the * Promise/A+ spec. Some notable differences from other promise libaries are: * - There currently isn't a seperate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (x) { return new globalScope.Promise(function (resolve) { resolve(x); }); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status == STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof(handler.onResolve) == 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof(handler.onReject) === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} array of data and/or promises to wait for. * @return {Promise} New dependant promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if x is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param x resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(x) { return new Promise(function (resolve) { resolve(x); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status == STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = reject; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; } }; globalScope.Promise = Promise; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = {}; this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); PDFJS.createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } // Blob builder is deprecated in FF14 and removed in FF18. var bb = new MozBlobBuilder(); bb.append(data); return bb.getBlob(contentType); }; PDFJS.createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType) { if (!PDFJS.disableCreateObjectURL && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = PDFJS.createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(name, comObj) { this.name = name; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacks = this.callbacks = {}; var ah = this.actionHandler = {}; ah['console_log'] = [function ahConsoleLog(data) { console.log.apply(console, data); }]; ah['console_error'] = [function ahConsoleError(data) { console.error.apply(console, data); }]; ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) { UnsupportedManager.notify(data); }]; comObj.onmessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacks) { var callback = callbacks[callbackId]; delete callbacks[callbackId]; callback(data.data); } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var deferred = {}; var promise = new Promise(function (resolve, reject) { deferred.resolve = resolve; deferred.reject = reject; }); deferred.promise = promise; promise.then(function(resolvedData) { comObj.postMessage({ isReply: true, callbackId: data.callbackId, data: resolvedData }); }); action[0].call(action[1], data.data, deferred); } else { action[0].call(action[1], data.data); } } else { error('Unkown action from worker: ' + data.action); } }; } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {function} [callback] Optional callback that will handle a reply. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, callback, transfers) { var message = { action: actionName, data: data }; if (callback) { var callbackId = this.callbackIndex++; this.callbacks[callbackId] = callback; message.callbackId = callbackId; } if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.src = imageUrl; } var ColorSpace = (function ColorSpaceClosure() { // Constructor should define this.numComps, this.defaultColor, this.name function ColorSpace() { error('should not call ColorSpace constructor'); } ColorSpace.prototype = { /** * Converts the color value to the RGB color. The color components are * located in the src array starting from the srcOffset. Returns the array * of the rgb components, each value ranging from [0,255]. */ getRgb: function ColorSpace_getRgb(src, srcOffset) { var rgb = new Uint8Array(3); this.getRgbItem(src, srcOffset, rgb, 0); return rgb; }, /** * Converts the color value to the RGB color, similar to the getRgb method. * The result placed into the dest array starting from the destOffset. */ getRgbItem: function ColorSpace_getRgbItem(src, srcOffset, dest, destOffset) { error('Should not call ColorSpace.getRgbItem'); }, /** * Converts the specified number of the color values to the RGB colors. * The colors are located in the src array starting from the srcOffset. * The result is placed into the dest array starting from the destOffset. * The src array items shall be in [0,2^bits) range, the dest array items * will be in [0,255] range. alpha01 indicates how many alpha components * there are in the dest array; it will be either 0 (RGB array) or 1 (RGBA * array). */ getRgbBuffer: function ColorSpace_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { error('Should not call ColorSpace.getRgbBuffer'); }, /** * Determines the number of bytes required to store the result of the * conversion done by the getRgbBuffer method. As in getRgbBuffer, * |alpha01| is either 0 (RGB output) or 1 (RGBA output). */ getOutputLength: function ColorSpace_getOutputLength(inputLength, alpha01) { error('Should not call ColorSpace.getOutputLength'); }, /** * Returns true if source data will be equal the result/output data. */ isPassthrough: function ColorSpace_isPassthrough(bits) { return false; }, /** * Fills in the RGB colors in the destination buffer. alpha01 indicates * how many alpha components there are in the dest array; it will be either * 0 (RGB array) or 1 (RGBA array). */ fillRgb: function ColorSpace_fillRgb(dest, originalWidth, originalHeight, width, height, actualHeight, bpc, comps, alpha01) { var count = originalWidth * originalHeight; var rgbBuf = null; var numComponentColors = 1 << bpc; var needsResizing = originalHeight != height || originalWidth != width; var i, ii; if (this.isPassthrough(bpc)) { rgbBuf = comps; } else if (this.numComps === 1 && count > numComponentColors && this.name !== 'DeviceGray' && this.name !== 'DeviceRGB') { // Optimization: create a color map when there is just one component and // we are converting more colors than the size of the color map. We // don't build the map if the colorspace is gray or rgb since those // methods are faster than building a map. This mainly offers big speed // ups for indexed and alternate colorspaces. // // TODO it may be worth while to cache the color map. While running // testing I never hit a cache so I will leave that out for now (perhaps // we are reparsing colorspaces too much?). var allColors = bpc <= 8 ? new Uint8Array(numComponentColors) : new Uint16Array(numComponentColors); var key; for (i = 0; i < numComponentColors; i++) { allColors[i] = i; } var colorMap = new Uint8Array(numComponentColors * 3); this.getRgbBuffer(allColors, 0, numComponentColors, colorMap, 0, bpc, /* alpha01 = */ 0); var destPos, rgbPos; if (!needsResizing) { // Fill in the RGB values directly into |dest|. destPos = 0; for (i = 0; i < count; ++i) { key = comps[i] * 3; dest[destPos++] = colorMap[key]; dest[destPos++] = colorMap[key + 1]; dest[destPos++] = colorMap[key + 2]; destPos += alpha01; } } else { rgbBuf = new Uint8Array(count * 3); rgbPos = 0; for (i = 0; i < count; ++i) { key = comps[i] * 3; rgbBuf[rgbPos++] = colorMap[key]; rgbBuf[rgbPos++] = colorMap[key + 1]; rgbBuf[rgbPos++] = colorMap[key + 2]; } } } else { if (!needsResizing) { // Fill in the RGB values directly into |dest|. this.getRgbBuffer(comps, 0, width * actualHeight, dest, 0, bpc, alpha01); } else { rgbBuf = new Uint8Array(count * 3); this.getRgbBuffer(comps, 0, count, rgbBuf, 0, bpc, /* alpha01 = */ 0); } } if (rgbBuf) { if (needsResizing) { rgbBuf = PDFImage.resize(rgbBuf, bpc, 3, originalWidth, originalHeight, width, height); } rgbPos = 0; destPos = 0; for (i = 0, ii = width * actualHeight; i < ii; i++) { dest[destPos++] = rgbBuf[rgbPos++]; dest[destPos++] = rgbBuf[rgbPos++]; dest[destPos++] = rgbBuf[rgbPos++]; destPos += alpha01; } } }, /** * True if the colorspace has components in the default range of [0, 1]. * This should be true for all colorspaces except for lab color spaces * which are [0,100], [-128, 127], [-128, 127]. */ usesZeroToOneRange: true }; ColorSpace.parse = function ColorSpace_parse(cs, xref, res) { var IR = ColorSpace.parseToIR(cs, xref, res); if (IR instanceof AlternateCS) { return IR; } return ColorSpace.fromIR(IR); }; ColorSpace.fromIR = function ColorSpace_fromIR(IR) { var name = isArray(IR) ? IR[0] : IR; var whitePoint, blackPoint; switch (name) { case 'DeviceGrayCS': return this.singletons.gray; case 'DeviceRgbCS': return this.singletons.rgb; case 'DeviceCmykCS': return this.singletons.cmyk; case 'CalGrayCS': whitePoint = IR[1].WhitePoint; blackPoint = IR[1].BlackPoint; var gamma = IR[1].Gamma; return new CalGrayCS(whitePoint, blackPoint, gamma); case 'PatternCS': var basePatternCS = IR[1]; if (basePatternCS) { basePatternCS = ColorSpace.fromIR(basePatternCS); } return new PatternCS(basePatternCS); case 'IndexedCS': var baseIndexedCS = IR[1]; var hiVal = IR[2]; var lookup = IR[3]; return new IndexedCS(ColorSpace.fromIR(baseIndexedCS), hiVal, lookup); case 'AlternateCS': var numComps = IR[1]; var alt = IR[2]; var tintFnIR = IR[3]; return new AlternateCS(numComps, ColorSpace.fromIR(alt), PDFFunction.fromIR(tintFnIR)); case 'LabCS': whitePoint = IR[1].WhitePoint; blackPoint = IR[1].BlackPoint; var range = IR[1].Range; return new LabCS(whitePoint, blackPoint, range); default: error('Unkown name ' + name); } return null; }; ColorSpace.parseToIR = function ColorSpace_parseToIR(cs, xref, res) { if (isName(cs)) { var colorSpaces = res.get('ColorSpace'); if (isDict(colorSpaces)) { var refcs = colorSpaces.get(cs.name); if (refcs) { cs = refcs; } } } cs = xref.fetchIfRef(cs); var mode; if (isName(cs)) { mode = cs.name; this.mode = mode; switch (mode) { case 'DeviceGray': case 'G': return 'DeviceGrayCS'; case 'DeviceRGB': case 'RGB': return 'DeviceRgbCS'; case 'DeviceCMYK': case 'CMYK': return 'DeviceCmykCS'; case 'Pattern': return ['PatternCS', null]; default: error('unrecognized colorspace ' + mode); } } else if (isArray(cs)) { mode = cs[0].name; this.mode = mode; var numComps, params; switch (mode) { case 'DeviceGray': case 'G': return 'DeviceGrayCS'; case 'DeviceRGB': case 'RGB': return 'DeviceRgbCS'; case 'DeviceCMYK': case 'CMYK': return 'DeviceCmykCS'; case 'CalGray': params = cs[1].getAll(); return ['CalGrayCS', params]; case 'CalRGB': return 'DeviceRgbCS'; case 'ICCBased': var stream = xref.fetchIfRef(cs[1]); var dict = stream.dict; numComps = dict.get('N'); if (numComps == 1) { return 'DeviceGrayCS'; } else if (numComps == 3) { return 'DeviceRgbCS'; } else if (numComps == 4) { return 'DeviceCmykCS'; } break; case 'Pattern': var basePatternCS = cs[1]; if (basePatternCS) { basePatternCS = ColorSpace.parseToIR(basePatternCS, xref, res); } return ['PatternCS', basePatternCS]; case 'Indexed': case 'I': var baseIndexedCS = ColorSpace.parseToIR(cs[1], xref, res); var hiVal = cs[2] + 1; var lookup = xref.fetchIfRef(cs[3]); if (isStream(lookup)) { lookup = lookup.getBytes(); } return ['IndexedCS', baseIndexedCS, hiVal, lookup]; case 'Separation': case 'DeviceN': var name = cs[1]; numComps = 1; if (isName(name)) { numComps = 1; } else if (isArray(name)) { numComps = name.length; } var alt = ColorSpace.parseToIR(cs[2], xref, res); var tintFnIR = PDFFunction.getIR(xref, xref.fetchIfRef(cs[3])); return ['AlternateCS', numComps, alt, tintFnIR]; case 'Lab': params = cs[1].getAll(); return ['LabCS', params]; default: error('unimplemented color space object "' + mode + '"'); } } else { error('unrecognized color space object: "' + cs + '"'); } return null; }; /** * Checks if a decode map matches the default decode map for a color space. * This handles the general decode maps where there are two values per * component. e.g. [0, 1, 0, 1, 0, 1] for a RGB color. * This does not handle Lab, Indexed, or Pattern decode maps since they are * slightly different. * @param {Array} decode Decode map (usually from an image). * @param {Number} n Number of components the color space has. */ ColorSpace.isDefaultDecode = function ColorSpace_isDefaultDecode(decode, n) { if (!decode) { return true; } if (n * 2 !== decode.length) { warn('The decode map is not the correct length'); return true; } for (var i = 0, ii = decode.length; i < ii; i += 2) { if (decode[i] !== 0 || decode[i + 1] != 1) { return false; } } return true; }; ColorSpace.singletons = { get gray() { return shadow(this, 'gray', new DeviceGrayCS()); }, get rgb() { return shadow(this, 'rgb', new DeviceRgbCS()); }, get cmyk() { return shadow(this, 'cmyk', new DeviceCmykCS()); } }; return ColorSpace; })(); /** * Alternate color space handles both Separation and DeviceN color spaces. A * Separation color space is actually just a DeviceN with one color component. * Both color spaces use a tinting function to convert colors to a base color * space. */ var AlternateCS = (function AlternateCSClosure() { function AlternateCS(numComps, base, tintFn) { this.name = 'Alternate'; this.numComps = numComps; this.defaultColor = new Float32Array(numComps); for (var i = 0; i < numComps; ++i) { this.defaultColor[i] = 1; } this.base = base; this.tintFn = tintFn; } AlternateCS.prototype = { getRgb: ColorSpace.prototype.getRgb, getRgbItem: function AlternateCS_getRgbItem(src, srcOffset, dest, destOffset) { var baseNumComps = this.base.numComps; var input = 'subarray' in src ? src.subarray(srcOffset, srcOffset + this.numComps) : Array.prototype.slice.call(src, srcOffset, srcOffset + this.numComps); var tinted = this.tintFn(input); this.base.getRgbItem(tinted, 0, dest, destOffset); }, getRgbBuffer: function AlternateCS_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { var tintFn = this.tintFn; var base = this.base; var scale = 1 / ((1 << bits) - 1); var baseNumComps = base.numComps; var usesZeroToOneRange = base.usesZeroToOneRange; var isPassthrough = (base.isPassthrough(8) || !usesZeroToOneRange) && alpha01 === 0; var pos = isPassthrough ? destOffset : 0; var baseBuf = isPassthrough ? dest : new Uint8Array(baseNumComps * count); var numComps = this.numComps; var scaled = new Float32Array(numComps); var i, j; for (i = 0; i < count; i++) { for (j = 0; j < numComps; j++) { scaled[j] = src[srcOffset++] * scale; } var tinted = tintFn(scaled); if (usesZeroToOneRange) { for (j = 0; j < baseNumComps; j++) { baseBuf[pos++] = tinted[j] * 255; } } else { base.getRgbItem(tinted, 0, baseBuf, pos); pos += baseNumComps; } } if (!isPassthrough) { base.getRgbBuffer(baseBuf, 0, count, dest, destOffset, 8, alpha01); } }, getOutputLength: function AlternateCS_getOutputLength(inputLength, alpha01) { return this.base.getOutputLength(inputLength * this.base.numComps / this.numComps, alpha01); }, isPassthrough: ColorSpace.prototype.isPassthrough, fillRgb: ColorSpace.prototype.fillRgb, isDefaultDecode: function AlternateCS_isDefaultDecode(decodeMap) { return ColorSpace.isDefaultDecode(decodeMap, this.numComps); }, usesZeroToOneRange: true }; return AlternateCS; })(); var PatternCS = (function PatternCSClosure() { function PatternCS(baseCS) { this.name = 'Pattern'; this.base = baseCS; } PatternCS.prototype = {}; return PatternCS; })(); var IndexedCS = (function IndexedCSClosure() { function IndexedCS(base, highVal, lookup) { this.name = 'Indexed'; this.numComps = 1; this.defaultColor = new Uint8Array([0]); this.base = base; this.highVal = highVal; var baseNumComps = base.numComps; var length = baseNumComps * highVal; var lookupArray; if (isStream(lookup)) { lookupArray = new Uint8Array(length); var bytes = lookup.getBytes(length); lookupArray.set(bytes); } else if (isString(lookup)) { lookupArray = new Uint8Array(length); for (var i = 0; i < length; ++i) { lookupArray[i] = lookup.charCodeAt(i); } } else if (lookup instanceof Uint8Array || lookup instanceof Array) { lookupArray = lookup; } else { error('Unrecognized lookup table: ' + lookup); } this.lookup = lookupArray; } IndexedCS.prototype = { getRgb: ColorSpace.prototype.getRgb, getRgbItem: function IndexedCS_getRgbItem(src, srcOffset, dest, destOffset) { var numComps = this.base.numComps; var start = src[srcOffset] * numComps; this.base.getRgbItem(this.lookup, start, dest, destOffset); }, getRgbBuffer: function IndexedCS_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { var base = this.base; var numComps = base.numComps; var outputDelta = base.getOutputLength(numComps, alpha01); var lookup = this.lookup; for (var i = 0; i < count; ++i) { var lookupPos = src[srcOffset++] * numComps; base.getRgbBuffer(lookup, lookupPos, 1, dest, destOffset, 8, alpha01); destOffset += outputDelta; } }, getOutputLength: function IndexedCS_getOutputLength(inputLength, alpha01) { return this.base.getOutputLength(inputLength * this.base.numComps, alpha01); }, isPassthrough: ColorSpace.prototype.isPassthrough, fillRgb: ColorSpace.prototype.fillRgb, isDefaultDecode: function IndexedCS_isDefaultDecode(decodeMap) { // indexed color maps shouldn't be changed return true; }, usesZeroToOneRange: true }; return IndexedCS; })(); var DeviceGrayCS = (function DeviceGrayCSClosure() { function DeviceGrayCS() { this.name = 'DeviceGray'; this.numComps = 1; this.defaultColor = new Float32Array([0]); } DeviceGrayCS.prototype = { getRgb: ColorSpace.prototype.getRgb, getRgbItem: function DeviceGrayCS_getRgbItem(src, srcOffset, dest, destOffset) { var c = (src[srcOffset] * 255) | 0; c = c < 0 ? 0 : c > 255 ? 255 : c; dest[destOffset] = dest[destOffset + 1] = dest[destOffset + 2] = c; }, getRgbBuffer: function DeviceGrayCS_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { var scale = 255 / ((1 << bits) - 1); var j = srcOffset, q = destOffset; for (var i = 0; i < count; ++i) { var c = (scale * src[j++]) | 0; dest[q++] = c; dest[q++] = c; dest[q++] = c; q += alpha01; } }, getOutputLength: function DeviceGrayCS_getOutputLength(inputLength, alpha01) { return inputLength * (3 + alpha01); }, isPassthrough: ColorSpace.prototype.isPassthrough, fillRgb: ColorSpace.prototype.fillRgb, isDefaultDecode: function DeviceGrayCS_isDefaultDecode(decodeMap) { return ColorSpace.isDefaultDecode(decodeMap, this.numComps); }, usesZeroToOneRange: true }; return DeviceGrayCS; })(); var DeviceRgbCS = (function DeviceRgbCSClosure() { function DeviceRgbCS() { this.name = 'DeviceRGB'; this.numComps = 3; this.defaultColor = new Float32Array([0, 0, 0]); } DeviceRgbCS.prototype = { getRgb: ColorSpace.prototype.getRgb, getRgbItem: function DeviceRgbCS_getRgbItem(src, srcOffset, dest, destOffset) { var r = (src[srcOffset] * 255) | 0; var g = (src[srcOffset + 1] * 255) | 0; var b = (src[srcOffset + 2] * 255) | 0; dest[destOffset] = r < 0 ? 0 : r > 255 ? 255 : r; dest[destOffset + 1] = g < 0 ? 0 : g > 255 ? 255 : g; dest[destOffset + 2] = b < 0 ? 0 : b > 255 ? 255 : b; }, getRgbBuffer: function DeviceRgbCS_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { if (bits === 8 && alpha01 === 0) { dest.set(src.subarray(srcOffset, srcOffset + count * 3), destOffset); return; } var scale = 255 / ((1 << bits) - 1); var j = srcOffset, q = destOffset; for (var i = 0; i < count; ++i) { dest[q++] = (scale * src[j++]) | 0; dest[q++] = (scale * src[j++]) | 0; dest[q++] = (scale * src[j++]) | 0; q += alpha01; } }, getOutputLength: function DeviceRgbCS_getOutputLength(inputLength, alpha01) { return (inputLength * (3 + alpha01) / 3) | 0; }, isPassthrough: function DeviceRgbCS_isPassthrough(bits) { return bits == 8; }, fillRgb: ColorSpace.prototype.fillRgb, isDefaultDecode: function DeviceRgbCS_isDefaultDecode(decodeMap) { return ColorSpace.isDefaultDecode(decodeMap, this.numComps); }, usesZeroToOneRange: true }; return DeviceRgbCS; })(); var DeviceCmykCS = (function DeviceCmykCSClosure() { // The coefficients below was found using numerical analysis: the method of // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors, // where color_value is the tabular value from the table of sampled RGB colors // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding // CMYK color conversion using the estimation below: // f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255 function convertToRgb(src, srcOffset, srcScale, dest, destOffset) { var c = src[srcOffset + 0] * srcScale; var m = src[srcOffset + 1] * srcScale; var y = src[srcOffset + 2] * srcScale; var k = src[srcOffset + 3] * srcScale; var r = c * (-4.387332384609988 * c + 54.48615194189176 * m + 18.82290502165302 * y + 212.25662451639585 * k + -285.2331026137004) + m * (1.7149763477362134 * m - 5.6096736904047315 * y + -17.873870861415444 * k - 5.497006427196366) + y * (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) + k * (-21.86122147463605 * k - 189.48180835922747) + 255; var g = c * (8.841041422036149 * c + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k + -79.2970844816548) + m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) + y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) + k * (-20.737325471181034 * k - 187.80453709719578) + 255; var b = c * (0.8842522430003296 * c + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k + -14.183576799673286) + m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) + y * (0.03296041114873217 * y + 115.60384449646641 * k + -193.58209356861505) + k * (-22.33816807309886 * k - 180.12613974708367) + 255; dest[destOffset] = r > 255 ? 255 : r < 0 ? 0 : r; dest[destOffset + 1] = g > 255 ? 255 : g < 0 ? 0 : g; dest[destOffset + 2] = b > 255 ? 255 : b < 0 ? 0 : b; } function DeviceCmykCS() { this.name = 'DeviceCMYK'; this.numComps = 4; this.defaultColor = new Float32Array([0, 0, 0, 1]); } DeviceCmykCS.prototype = { getRgb: ColorSpace.prototype.getRgb, getRgbItem: function DeviceCmykCS_getRgbItem(src, srcOffset, dest, destOffset) { convertToRgb(src, srcOffset, 1, dest, destOffset); }, getRgbBuffer: function DeviceCmykCS_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { var scale = 1 / ((1 << bits) - 1); for (var i = 0; i < count; i++) { convertToRgb(src, srcOffset, scale, dest, destOffset); srcOffset += 4; destOffset += 3 + alpha01; } }, getOutputLength: function DeviceCmykCS_getOutputLength(inputLength, alpha01) { return (inputLength / 4 * (3 + alpha01)) | 0; }, isPassthrough: ColorSpace.prototype.isPassthrough, fillRgb: ColorSpace.prototype.fillRgb, isDefaultDecode: function DeviceCmykCS_isDefaultDecode(decodeMap) { return ColorSpace.isDefaultDecode(decodeMap, this.numComps); }, usesZeroToOneRange: true }; return DeviceCmykCS; })(); // // CalGrayCS: Based on "PDF Reference, Sixth Ed", p.245 // var CalGrayCS = (function CalGrayCSClosure() { function CalGrayCS(whitePoint, blackPoint, gamma) { this.name = 'CalGray'; this.numComps = 1; this.defaultColor = new Float32Array([0]); if (!whitePoint) { error('WhitePoint missing - required for color space CalGray'); } blackPoint = blackPoint || [0, 0, 0]; gamma = gamma || 1; // Translate arguments to spec variables. this.XW = whitePoint[0]; this.YW = whitePoint[1]; this.ZW = whitePoint[2]; this.XB = blackPoint[0]; this.YB = blackPoint[1]; this.ZB = blackPoint[2]; this.G = gamma; // Validate variables as per spec. if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) { error('Invalid WhitePoint components for ' + this.name + ', no fallback available'); } if (this.XB < 0 || this.YB < 0 || this.ZB < 0) { info('Invalid BlackPoint for ' + this.name + ', falling back to default'); this.XB = this.YB = this.ZB = 0; } if (this.XB !== 0 || this.YB !== 0 || this.ZB !== 0) { warn(this.name + ', BlackPoint: XB: ' + this.XB + ', YB: ' + this.YB + ', ZB: ' + this.ZB + ', only default values are supported.'); } if (this.G < 1) { info('Invalid Gamma: ' + this.G + ' for ' + this.name + ', falling back to default'); this.G = 1; } } function convertToRgb(cs, src, srcOffset, dest, destOffset, scale) { // A represents a gray component of a calibrated gray space. // A <---> AG in the spec var A = src[srcOffset] * scale; var AG = Math.pow(A, cs.G); // Computes intermediate variables M, L, N as per spec. // Except if other than default BlackPoint values are used. var M = cs.XW * AG; var L = cs.YW * AG; var N = cs.ZW * AG; // Decode XYZ, as per spec. var X = M; var Y = L; var Z = N; // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4. // This yields values in range [0, 100]. var Lstar = Math.max(116 * Math.pow(Y, 1 / 3) - 16, 0); // Convert values to rgb range [0, 255]. dest[destOffset] = Lstar * 255 / 100; dest[destOffset + 1] = Lstar * 255 / 100; dest[destOffset + 2] = Lstar * 255 / 100; } CalGrayCS.prototype = { getRgb: ColorSpace.prototype.getRgb, getRgbItem: function CalGrayCS_getRgbItem(src, srcOffset, dest, destOffset) { convertToRgb(this, src, srcOffset, dest, destOffset, 1); }, getRgbBuffer: function CalGrayCS_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { var scale = 1 / ((1 << bits) - 1); for (var i = 0; i < count; ++i) { convertToRgb(this, src, srcOffset, dest, destOffset, scale); srcOffset += 1; destOffset += 3 + alpha01; } }, getOutputLength: function CalGrayCS_getOutputLength(inputLength, alpha01) { return inputLength * (3 + alpha01); }, isPassthrough: ColorSpace.prototype.isPassthrough, fillRgb: ColorSpace.prototype.fillRgb, isDefaultDecode: function CalGrayCS_isDefaultDecode(decodeMap) { return ColorSpace.isDefaultDecode(decodeMap, this.numComps); }, usesZeroToOneRange: true }; return CalGrayCS; })(); // // LabCS: Based on "PDF Reference, Sixth Ed", p.250 // var LabCS = (function LabCSClosure() { function LabCS(whitePoint, blackPoint, range) { this.name = 'Lab'; this.numComps = 3; this.defaultColor = new Float32Array([0, 0, 0]); if (!whitePoint) { error('WhitePoint missing - required for color space Lab'); } blackPoint = blackPoint || [0, 0, 0]; range = range || [-100, 100, -100, 100]; // Translate args to spec variables this.XW = whitePoint[0]; this.YW = whitePoint[1]; this.ZW = whitePoint[2]; this.amin = range[0]; this.amax = range[1]; this.bmin = range[2]; this.bmax = range[3]; // These are here just for completeness - the spec doesn't offer any // formulas that use BlackPoint in Lab this.XB = blackPoint[0]; this.YB = blackPoint[1]; this.ZB = blackPoint[2]; // Validate vars as per spec if (this.XW < 0 || this.ZW < 0 || this.YW !== 1) { error('Invalid WhitePoint components, no fallback available'); } if (this.XB < 0 || this.YB < 0 || this.ZB < 0) { info('Invalid BlackPoint, falling back to default'); this.XB = this.YB = this.ZB = 0; } if (this.amin > this.amax || this.bmin > this.bmax) { info('Invalid Range, falling back to defaults'); this.amin = -100; this.amax = 100; this.bmin = -100; this.bmax = 100; } } // Function g(x) from spec function fn_g(x) { if (x >= 6 / 29) { return x * x * x; } else { return (108 / 841) * (x - 4 / 29); } } function decode(value, high1, low2, high2) { return low2 + (value) * (high2 - low2) / (high1); } // If decoding is needed maxVal should be 2^bits per component - 1. function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) { // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax] // not the usual [0, 1]. If a command like setFillColor is used the src // values will already be within the correct range. However, if we are // converting an image we have to map the values to the correct range given // above. // Ls,as,bs <---> L*,a*,b* in the spec var Ls = src[srcOffset]; var as = src[srcOffset + 1]; var bs = src[srcOffset + 2]; if (maxVal !== false) { Ls = decode(Ls, maxVal, 0, 100); as = decode(as, maxVal, cs.amin, cs.amax); bs = decode(bs, maxVal, cs.bmin, cs.bmax); } // Adjust limits of 'as' and 'bs' as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as; bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs; // Computes intermediate variables X,Y,Z as per spec var M = (Ls + 16) / 116; var L = M + (as / 500); var N = M - (bs / 200); var X = cs.XW * fn_g(L); var Y = cs.YW * fn_g(M); var Z = cs.ZW * fn_g(N); var r, g, b; // Using different conversions for D50 and D65 white points, // per http://www.color.org/srgb.pdf if (cs.ZW < 1) { // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249) r = X * 3.1339 + Y * -1.6170 + Z * -0.4906; g = X * -0.9785 + Y * 1.9160 + Z * 0.0333; b = X * 0.0720 + Y * -0.2290 + Z * 1.4057; } else { // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888) r = X * 3.2406 + Y * -1.5372 + Z * -0.4986; g = X * -0.9689 + Y * 1.8758 + Z * 0.0415; b = X * 0.0557 + Y * -0.2040 + Z * 1.0570; } // clamp color values to [0,1] range then convert to [0,255] range. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0; dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0; dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0; } LabCS.prototype = { getRgb: ColorSpace.prototype.getRgb, getRgbItem: function LabCS_getRgbItem(src, srcOffset, dest, destOffset) { convertToRgb(this, src, srcOffset, false, dest, destOffset); }, getRgbBuffer: function LabCS_getRgbBuffer(src, srcOffset, count, dest, destOffset, bits, alpha01) { var maxVal = (1 << bits) - 1; for (var i = 0; i < count; i++) { convertToRgb(this, src, srcOffset, maxVal, dest, destOffset); srcOffset += 3; destOffset += 3 + alpha01; } }, getOutputLength: function LabCS_getOutputLength(inputLength, alpha01) { return (inputLength * (3 + alpha01) / 3) | 0; }, isPassthrough: ColorSpace.prototype.isPassthrough, isDefaultDecode: function LabCS_isDefaultDecode(decodeMap) { // XXX: Decoding is handled with the lab conversion because of the strange // ranges that are used. return true; }, usesZeroToOneRange: false }; return LabCS; })(); var PDFFunction = (function PDFFunctionClosure() { var CONSTRUCT_SAMPLED = 0; var CONSTRUCT_INTERPOLATED = 2; var CONSTRUCT_STICHED = 3; var CONSTRUCT_POSTSCRIPT = 4; return { getSampleArray: function PDFFunction_getSampleArray(size, outputSize, bps, str) { var i, ii; var length = 1; for (i = 0, ii = size.length; i < ii; i++) { length *= size[i]; } length *= outputSize; var array = []; var codeSize = 0; var codeBuf = 0; // 32 is a valid bps so shifting won't work var sampleMul = 1.0 / (Math.pow(2.0, bps) - 1); var strBytes = str.getBytes((length * bps + 7) / 8); var strIdx = 0; for (i = 0; i < length; i++) { while (codeSize < bps) { codeBuf <<= 8; codeBuf |= strBytes[strIdx++]; codeSize += 8; } codeSize -= bps; array.push((codeBuf >> codeSize) * sampleMul); codeBuf &= (1 << codeSize) - 1; } return array; }, getIR: function PDFFunction_getIR(xref, fn) { var dict = fn.dict; if (!dict) { dict = fn; } var types = [this.constructSampled, null, this.constructInterpolated, this.constructStiched, this.constructPostScript]; var typeNum = dict.get('FunctionType'); var typeFn = types[typeNum]; if (!typeFn) { error('Unknown type of function'); } return typeFn.call(this, fn, dict, xref); }, fromIR: function PDFFunction_fromIR(IR) { var type = IR[0]; switch (type) { case CONSTRUCT_SAMPLED: return this.constructSampledFromIR(IR); case CONSTRUCT_INTERPOLATED: return this.constructInterpolatedFromIR(IR); case CONSTRUCT_STICHED: return this.constructStichedFromIR(IR); //case CONSTRUCT_POSTSCRIPT: default: return this.constructPostScriptFromIR(IR); } }, parse: function PDFFunction_parse(xref, fn) { var IR = this.getIR(xref, fn); return this.fromIR(IR); }, constructSampled: function PDFFunction_constructSampled(str, dict) { function toMultiArray(arr) { var inputLength = arr.length; var outputLength = arr.length / 2; var out = []; var index = 0; for (var i = 0; i < inputLength; i += 2) { out[index] = [arr[i], arr[i + 1]]; ++index; } return out; } var domain = dict.get('Domain'); var range = dict.get('Range'); if (!domain || !range) { error('No domain or range'); } var inputSize = domain.length / 2; var outputSize = range.length / 2; domain = toMultiArray(domain); range = toMultiArray(range); var size = dict.get('Size'); var bps = dict.get('BitsPerSample'); var order = dict.get('Order') || 1; if (order !== 1) { // No description how cubic spline interpolation works in PDF32000:2008 // As in poppler, ignoring order, linear interpolation may work as good info('No support for cubic spline interpolation: ' + order); } var encode = dict.get('Encode'); if (!encode) { encode = []; for (var i = 0; i < inputSize; ++i) { encode.push(0); encode.push(size[i] - 1); } } encode = toMultiArray(encode); var decode = dict.get('Decode'); if (!decode) { decode = range; } else { decode = toMultiArray(decode); } var samples = this.getSampleArray(size, outputSize, bps, str); return [ CONSTRUCT_SAMPLED, inputSize, domain, encode, decode, samples, size, outputSize, Math.pow(2, bps) - 1, range ]; }, constructSampledFromIR: function PDFFunction_constructSampledFromIR(IR) { // See chapter 3, page 109 of the PDF reference function interpolate(x, xmin, xmax, ymin, ymax) { return ymin + ((x - xmin) * ((ymax - ymin) / (xmax - xmin))); } return function constructSampledFromIRResult(args) { // See chapter 3, page 110 of the PDF reference. var m = IR[1]; var domain = IR[2]; var encode = IR[3]; var decode = IR[4]; var samples = IR[5]; var size = IR[6]; var n = IR[7]; var mask = IR[8]; var range = IR[9]; if (m != args.length) { error('Incorrect number of arguments: ' + m + ' != ' + args.length); } var x = args; // Building the cube vertices: its part and sample index // http://rjwagner49.com/Mathematics/Interpolation.pdf var cubeVertices = 1 << m; var cubeN = new Float64Array(cubeVertices); var cubeVertex = new Uint32Array(cubeVertices); var i, j; for (j = 0; j < cubeVertices; j++) { cubeN[j] = 1; } var k = n, pos = 1; // Map x_i to y_j for 0 <= i < m using the sampled function. for (i = 0; i < m; ++i) { // x_i' = min(max(x_i, Domain_2i), Domain_2i+1) var domain_2i = domain[i][0]; var domain_2i_1 = domain[i][1]; var xi = Math.min(Math.max(x[i], domain_2i), domain_2i_1); // e_i = Interpolate(x_i', Domain_2i, Domain_2i+1, // Encode_2i, Encode_2i+1) var e = interpolate(xi, domain_2i, domain_2i_1, encode[i][0], encode[i][1]); // e_i' = min(max(e_i, 0), Size_i - 1) var size_i = size[i]; e = Math.min(Math.max(e, 0), size_i - 1); // Adjusting the cube: N and vertex sample index var e0 = e < size_i - 1 ? Math.floor(e) : e - 1; // e1 = e0 + 1; var n0 = e0 + 1 - e; // (e1 - e) / (e1 - e0); var n1 = e - e0; // (e - e0) / (e1 - e0); var offset0 = e0 * k; var offset1 = offset0 + k; // e1 * k for (j = 0; j < cubeVertices; j++) { if (j & pos) { cubeN[j] *= n1; cubeVertex[j] += offset1; } else { cubeN[j] *= n0; cubeVertex[j] += offset0; } } k *= size_i; pos <<= 1; } var y = new Float64Array(n); for (j = 0; j < n; ++j) { // Sum all cube vertices' samples portions var rj = 0; for (i = 0; i < cubeVertices; i++) { rj += samples[cubeVertex[i] + j] * cubeN[i]; } // r_j' = Interpolate(r_j, 0, 2^BitsPerSample - 1, // Decode_2j, Decode_2j+1) rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]); // y_j = min(max(r_j, range_2j), range_2j+1) y[j] = Math.min(Math.max(rj, range[j][0]), range[j][1]); } return y; }; }, constructInterpolated: function PDFFunction_constructInterpolated(str, dict) { var c0 = dict.get('C0') || [0]; var c1 = dict.get('C1') || [1]; var n = dict.get('N'); if (!isArray(c0) || !isArray(c1)) { error('Illegal dictionary for interpolated function'); } var length = c0.length; var diff = []; for (var i = 0; i < length; ++i) { diff.push(c1[i] - c0[i]); } return [CONSTRUCT_INTERPOLATED, c0, diff, n]; }, constructInterpolatedFromIR: function PDFFunction_constructInterpolatedFromIR(IR) { var c0 = IR[1]; var diff = IR[2]; var n = IR[3]; var length = diff.length; return function constructInterpolatedFromIRResult(args) { var x = n == 1 ? args[0] : Math.pow(args[0], n); var out = []; for (var j = 0; j < length; ++j) { out.push(c0[j] + (x * diff[j])); } return out; }; }, constructStiched: function PDFFunction_constructStiched(fn, dict, xref) { var domain = dict.get('Domain'); if (!domain) { error('No domain'); } var inputSize = domain.length / 2; if (inputSize != 1) { error('Bad domain for stiched function'); } var fnRefs = dict.get('Functions'); var fns = []; for (var i = 0, ii = fnRefs.length; i < ii; ++i) { fns.push(PDFFunction.getIR(xref, xref.fetchIfRef(fnRefs[i]))); } var bounds = dict.get('Bounds'); var encode = dict.get('Encode'); return [CONSTRUCT_STICHED, domain, bounds, encode, fns]; }, constructStichedFromIR: function PDFFunction_constructStichedFromIR(IR) { var domain = IR[1]; var bounds = IR[2]; var encode = IR[3]; var fnsIR = IR[4]; var fns = []; for (var i = 0, ii = fnsIR.length; i < ii; i++) { fns.push(PDFFunction.fromIR(fnsIR[i])); } return function constructStichedFromIRResult(args) { var clip = function constructStichedFromIRClip(v, min, max) { if (v > max) { v = max; } else if (v < min) { v = min; } return v; }; // clip to domain var v = clip(args[0], domain[0], domain[1]); // calulate which bound the value is in for (var i = 0, ii = bounds.length; i < ii; ++i) { if (v < bounds[i]) { break; } } // encode value into domain of function var dmin = domain[0]; if (i > 0) { dmin = bounds[i - 1]; } var dmax = domain[1]; if (i < bounds.length) { dmax = bounds[i]; } var rmin = encode[2 * i]; var rmax = encode[2 * i + 1]; var v2 = rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin); // call the appropriate function return fns[i]([v2]); }; }, constructPostScript: function PDFFunction_constructPostScript(fn, dict, xref) { var domain = dict.get('Domain'); var range = dict.get('Range'); if (!domain) { error('No domain.'); } if (!range) { error('No range.'); } var lexer = new PostScriptLexer(fn); var parser = new PostScriptParser(lexer); var code = parser.parse(); return [CONSTRUCT_POSTSCRIPT, domain, range, code]; }, constructPostScriptFromIR: function PDFFunction_constructPostScriptFromIR( IR) { var domain = IR[1]; var range = IR[2]; var code = IR[3]; var numOutputs = range.length / 2; var evaluator = new PostScriptEvaluator(code); // Cache the values for a big speed up, the cache size is limited though // since the number of possible values can be huge from a PS function. var cache = new FunctionCache(); return function constructPostScriptFromIRResult(args) { var initialStack = []; for (var i = 0, ii = (domain.length / 2); i < ii; ++i) { initialStack.push(args[i]); } var key = initialStack.join('_'); if (cache.has(key)) { return cache.get(key); } var stack = evaluator.execute(initialStack); var transformed = []; for (i = numOutputs - 1; i >= 0; --i) { var out = stack.pop(); var rangeIndex = 2 * i; if (out < range[rangeIndex]) { out = range[rangeIndex]; } else if (out > range[rangeIndex + 1]) { out = range[rangeIndex + 1]; } transformed[i] = out; } cache.set(key, transformed); return transformed; }; } }; })(); var FunctionCache = (function FunctionCacheClosure() { // Of 10 PDF's with type4 functions the maxium number of distinct values seen // was 256. This still may need some tweaking in the future though. var MAX_CACHE_SIZE = 1024; function FunctionCache() { this.cache = {}; this.total = 0; } FunctionCache.prototype = { has: function FunctionCache_has(key) { return key in this.cache; }, get: function FunctionCache_get(key) { return this.cache[key]; }, set: function FunctionCache_set(key, value) { if (this.total < MAX_CACHE_SIZE) { this.cache[key] = value; this.total++; } } }; return FunctionCache; })(); var PostScriptStack = (function PostScriptStackClosure() { var MAX_STACK_SIZE = 100; function PostScriptStack(initialStack) { this.stack = initialStack || []; } PostScriptStack.prototype = { push: function PostScriptStack_push(value) { if (this.stack.length >= MAX_STACK_SIZE) { error('PostScript function stack overflow.'); } this.stack.push(value); }, pop: function PostScriptStack_pop() { if (this.stack.length <= 0) { error('PostScript function stack underflow.'); } return this.stack.pop(); }, copy: function PostScriptStack_copy(n) { if (this.stack.length + n >= MAX_STACK_SIZE) { error('PostScript function stack overflow.'); } var stack = this.stack; for (var i = stack.length - n, j = n - 1; j >= 0; j--, i++) { stack.push(stack[i]); } }, index: function PostScriptStack_index(n) { this.push(this.stack[this.stack.length - n - 1]); }, // rotate the last n stack elements p times roll: function PostScriptStack_roll(n, p) { var stack = this.stack; var l = stack.length - n; var r = stack.length - 1, c = l + (p - Math.floor(p / n) * n), i, j, t; for (i = l, j = r; i < j; i++, j--) { t = stack[i]; stack[i] = stack[j]; stack[j] = t; } for (i = l, j = c - 1; i < j; i++, j--) { t = stack[i]; stack[i] = stack[j]; stack[j] = t; } for (i = c, j = r; i < j; i++, j--) { t = stack[i]; stack[i] = stack[j]; stack[j] = t; } } }; return PostScriptStack; })(); var PostScriptEvaluator = (function PostScriptEvaluatorClosure() { function PostScriptEvaluator(operators) { this.operators = operators; } PostScriptEvaluator.prototype = { execute: function PostScriptEvaluator_execute(initialStack) { var stack = new PostScriptStack(initialStack); var counter = 0; var operators = this.operators; var length = operators.length; var operator, a, b; while (counter < length) { operator = operators[counter++]; if (typeof operator == 'number') { // Operator is really an operand and should be pushed to the stack. stack.push(operator); continue; } switch (operator) { // non standard ps operators case 'jz': // jump if false b = stack.pop(); a = stack.pop(); if (!a) { counter = b; } break; case 'j': // jump a = stack.pop(); counter = a; break; // all ps operators in alphabetical order (excluding if/ifelse) case 'abs': a = stack.pop(); stack.push(Math.abs(a)); break; case 'add': b = stack.pop(); a = stack.pop(); stack.push(a + b); break; case 'and': b = stack.pop(); a = stack.pop(); if (isBool(a) && isBool(b)) { stack.push(a && b); } else { stack.push(a & b); } break; case 'atan': a = stack.pop(); stack.push(Math.atan(a)); break; case 'bitshift': b = stack.pop(); a = stack.pop(); if (a > 0) { stack.push(a << b); } else { stack.push(a >> b); } break; case 'ceiling': a = stack.pop(); stack.push(Math.ceil(a)); break; case 'copy': a = stack.pop(); stack.copy(a); break; case 'cos': a = stack.pop(); stack.push(Math.cos(a)); break; case 'cvi': a = stack.pop() | 0; stack.push(a); break; case 'cvr': // noop break; case 'div': b = stack.pop(); a = stack.pop(); stack.push(a / b); break; case 'dup': stack.copy(1); break; case 'eq': b = stack.pop(); a = stack.pop(); stack.push(a == b); break; case 'exch': stack.roll(2, 1); break; case 'exp': b = stack.pop(); a = stack.pop(); stack.push(Math.pow(a, b)); break; case 'false': stack.push(false); break; case 'floor': a = stack.pop(); stack.push(Math.floor(a)); break; case 'ge': b = stack.pop(); a = stack.pop(); stack.push(a >= b); break; case 'gt': b = stack.pop(); a = stack.pop(); stack.push(a > b); break; case 'idiv': b = stack.pop(); a = stack.pop(); stack.push((a / b) | 0); break; case 'index': a = stack.pop(); stack.index(a); break; case 'le': b = stack.pop(); a = stack.pop(); stack.push(a <= b); break; case 'ln': a = stack.pop(); stack.push(Math.log(a)); break; case 'log': a = stack.pop(); stack.push(Math.log(a) / Math.LN10); break; case 'lt': b = stack.pop(); a = stack.pop(); stack.push(a < b); break; case 'mod': b = stack.pop(); a = stack.pop(); stack.push(a % b); break; case 'mul': b = stack.pop(); a = stack.pop(); stack.push(a * b); break; case 'ne': b = stack.pop(); a = stack.pop(); stack.push(a != b); break; case 'neg': a = stack.pop(); stack.push(-b); break; case 'not': a = stack.pop(); if (isBool(a) && isBool(b)) { stack.push(a && b); } else { stack.push(a & b); } break; case 'or': b = stack.pop(); a = stack.pop(); if (isBool(a) && isBool(b)) { stack.push(a || b); } else { stack.push(a | b); } break; case 'pop': stack.pop(); break; case 'roll': b = stack.pop(); a = stack.pop(); stack.roll(a, b); break; case 'round': a = stack.pop(); stack.push(Math.round(a)); break; case 'sin': a = stack.pop(); stack.push(Math.sin(a)); break; case 'sqrt': a = stack.pop(); stack.push(Math.sqrt(a)); break; case 'sub': b = stack.pop(); a = stack.pop(); stack.push(a - b); break; case 'true': stack.push(true); break; case 'truncate': a = stack.pop(); a = a < 0 ? Math.ceil(a) : Math.floor(a); stack.push(a); break; case 'xor': b = stack.pop(); a = stack.pop(); if (isBool(a) && isBool(b)) { stack.push(a != b); } else { stack.push(a ^ b); } break; default: error('Unknown operator ' + operator); break; } } return stack.stack; } }; return PostScriptEvaluator; })(); var HIGHLIGHT_OFFSET = 4; // px var SUPPORTED_TYPES = ['Link', 'Text', 'Widget']; var Annotation = (function AnnotationClosure() { // 12.5.5: Algorithm: Appearance streams function getTransformMatrix(rect, bbox, matrix) { var bounds = Util.getAxialAlignedBoundingBox(bbox, matrix); var minX = bounds[0]; var minY = bounds[1]; var maxX = bounds[2]; var maxY = bounds[3]; if (minX === maxX || minY === maxY) { // From real-life file, bbox was [0, 0, 0, 0]. In this case, // just apply the transform for rect return [1, 0, 0, 1, rect[0], rect[1]]; } var xRatio = (rect[2] - rect[0]) / (maxX - minX); var yRatio = (rect[3] - rect[1]) / (maxY - minY); return [ xRatio, 0, 0, yRatio, rect[0] - minX * xRatio, rect[1] - minY * yRatio ]; } function getDefaultAppearance(dict) { var appearanceState = dict.get('AP'); if (!isDict(appearanceState)) { return; } var appearance; var appearances = appearanceState.get('N'); if (isDict(appearances)) { var as = dict.get('AS'); if (as && appearances.has(as.name)) { appearance = appearances.get(as.name); } } else { appearance = appearances; } return appearance; } function Annotation(params) { if (params.data) { this.data = params.data; return; } var dict = params.dict; var data = this.data = {}; data.subtype = dict.get('Subtype').name; var rect = dict.get('Rect') || [0, 0, 0, 0]; data.rect = Util.normalizeRect(rect); data.annotationFlags = dict.get('F'); var color = dict.get('C'); if (isArray(color) && color.length === 3) { // TODO(mack): currently only supporting rgb; need support different // colorspaces data.color = color; } else { data.color = [0, 0, 0]; } // Some types of annotations have border style dict which has more // info than the border array if (dict.has('BS')) { var borderStyle = dict.get('BS'); data.borderWidth = borderStyle.has('W') ? borderStyle.get('W') : 1; } else { var borderArray = dict.get('Border') || [0, 0, 1]; data.borderWidth = borderArray[2] || 0; // TODO: implement proper support for annotations with line dash patterns. var dashArray = borderArray[3]; if (data.borderWidth > 0 && dashArray && isArray(dashArray)) { var dashArrayLength = dashArray.length; if (dashArrayLength > 0) { // According to the PDF specification: the elements in a dashArray // shall be numbers that are nonnegative and not all equal to zero. var isInvalid = false; var numPositive = 0; for (var i = 0; i < dashArrayLength; i++) { var validNumber = (+dashArray[i] >= 0); if (!validNumber) { isInvalid = true; break; } else if (dashArray[i] > 0) { numPositive++; } } if (isInvalid || numPositive === 0) { data.borderWidth = 0; } } } } this.appearance = getDefaultAppearance(dict); data.hasAppearance = !!this.appearance; } Annotation.prototype = { getData: function Annotation_getData() { return this.data; }, hasHtml: function Annotation_hasHtml() { return false; }, getHtmlElement: function Annotation_getHtmlElement(commonObjs) { throw new NotImplementedException( 'getHtmlElement() should be implemented in subclass'); }, // TODO(mack): Remove this, it's not really that helpful. getEmptyContainer: function Annotation_getEmptyContainer(tagName, rect, borderWidth) { assert(!isWorker, 'getEmptyContainer() should be called from main thread'); var bWidth = borderWidth || 0; rect = rect || this.data.rect; var element = document.createElement(tagName); element.style.borderWidth = bWidth + 'px'; var width = rect[2] - rect[0] - 2 * bWidth; var height = rect[3] - rect[1] - 2 * bWidth; element.style.width = width + 'px'; element.style.height = height + 'px'; return element; }, isInvisible: function Annotation_isInvisible() { var data = this.data; if (data && SUPPORTED_TYPES.indexOf(data.subtype) !== -1) { return false; } else { return !!(data && data.annotationFlags && // Default: not invisible data.annotationFlags & 0x1); // Invisible } }, isViewable: function Annotation_isViewable() { var data = this.data; return !!(!this.isInvisible() && data && (!data.annotationFlags || !(data.annotationFlags & 0x22)) && // Hidden or NoView data.rect); // rectangle is nessessary }, isPrintable: function Annotation_isPrintable() { var data = this.data; return !!(!this.isInvisible() && data && data.annotationFlags && // Default: not printable data.annotationFlags & 0x4 && // Print data.rect); // rectangle is nessessary }, loadResources: function(keys) { var promise = new LegacyPromise(); this.appearance.dict.getAsync('Resources').then(function(resources) { if (!resources) { promise.resolve(); return; } var objectLoader = new ObjectLoader(resources.map, keys, resources.xref); objectLoader.load().then(function() { promise.resolve(resources); }); }.bind(this)); return promise; }, getOperatorList: function Annotation_getOperatorList(evaluator) { var promise = new LegacyPromise(); if (!this.appearance) { promise.resolve(new OperatorList()); return promise; } var data = this.data; var appearanceDict = this.appearance.dict; var resourcesPromise = this.loadResources([ 'ExtGState', 'ColorSpace', 'Pattern', 'Shading', 'XObject', 'Font' // ProcSet // Properties ]); var bbox = appearanceDict.get('BBox') || [0, 0, 1, 1]; var matrix = appearanceDict.get('Matrix') || [1, 0, 0, 1, 0 ,0]; var transform = getTransformMatrix(data.rect, bbox, matrix); var border = data.border; resourcesPromise.then(function(resources) { var opList = new OperatorList(); opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]); evaluator.getOperatorList(this.appearance, resources, opList); opList.addOp(OPS.endAnnotation, []); promise.resolve(opList); this.appearance.reset(); }.bind(this)); return promise; } }; Annotation.getConstructor = function Annotation_getConstructor(subtype, fieldType) { if (!subtype) { return; } // TODO(mack): Implement FreeText annotations if (subtype === 'Link') { return LinkAnnotation; } else if (subtype === 'Text') { return TextAnnotation; } else if (subtype === 'Widget') { if (!fieldType) { return; } if (fieldType === 'Tx') { return TextWidgetAnnotation; } else { return WidgetAnnotation; } } else { return Annotation; } }; // TODO(mack): Support loading annotation from data Annotation.fromData = function Annotation_fromData(data) { var subtype = data.subtype; var fieldType = data.fieldType; var Constructor = Annotation.getConstructor(subtype, fieldType); if (Constructor) { return new Constructor({ data: data }); } }; Annotation.fromRef = function Annotation_fromRef(xref, ref) { var dict = xref.fetchIfRef(ref); if (!isDict(dict)) { return; } var subtype = dict.get('Subtype'); subtype = isName(subtype) ? subtype.name : ''; if (!subtype) { return; } var fieldType = Util.getInheritableProperty(dict, 'FT'); fieldType = isName(fieldType) ? fieldType.name : ''; var Constructor = Annotation.getConstructor(subtype, fieldType); if (!Constructor) { return; } var params = { dict: dict, ref: ref, }; var annotation = new Constructor(params); if (annotation.isViewable() || annotation.isPrintable()) { return annotation; } else { warn('unimplemented annotation type: ' + subtype); } }; Annotation.appendToOperatorList = function Annotation_appendToOperatorList( annotations, opList, pdfManager, partialEvaluator, intent) { function reject(e) { annotationsReadyPromise.reject(e); } var annotationsReadyPromise = new LegacyPromise(); var annotationPromises = []; for (var i = 0, n = annotations.length; i < n; ++i) { if (intent === 'display' && annotations[i].isViewable() || intent === 'print' && annotations[i].isPrintable()) { annotationPromises.push( annotations[i].getOperatorList(partialEvaluator)); } } Promise.all(annotationPromises).then(function(datas) { opList.addOp(OPS.beginAnnotations, []); for (var i = 0, n = datas.length; i < n; ++i) { var annotOpList = datas[i]; opList.addOpList(annotOpList); } opList.addOp(OPS.endAnnotations, []); annotationsReadyPromise.resolve(); }, reject); return annotationsReadyPromise; }; return Annotation; })(); PDFJS.Annotation = Annotation; var WidgetAnnotation = (function WidgetAnnotationClosure() { function WidgetAnnotation(params) { Annotation.call(this, params); if (params.data) { return; } var dict = params.dict; var data = this.data; data.fieldValue = stringToPDFString( Util.getInheritableProperty(dict, 'V') || ''); data.alternativeText = stringToPDFString(dict.get('TU') || ''); data.defaultAppearance = Util.getInheritableProperty(dict, 'DA') || ''; var fieldType = Util.getInheritableProperty(dict, 'FT'); data.fieldType = isName(fieldType) ? fieldType.name : ''; data.fieldFlags = Util.getInheritableProperty(dict, 'Ff') || 0; this.fieldResources = Util.getInheritableProperty(dict, 'DR') || Dict.empty; // Building the full field name by collecting the field and // its ancestors 'T' data and joining them using '.'. var fieldName = []; var namedItem = dict; var ref = params.ref; while (namedItem) { var parent = namedItem.get('Parent'); var parentRef = namedItem.getRaw('Parent'); var name = namedItem.get('T'); if (name) { fieldName.unshift(stringToPDFString(name)); } else { // The field name is absent, that means more than one field // with the same name may exist. Replacing the empty name // with the '`' plus index in the parent's 'Kids' array. // This is not in the PDF spec but necessary to id the // the input controls. var kids = parent.get('Kids'); var j, jj; for (j = 0, jj = kids.length; j < jj; j++) { var kidRef = kids[j]; if (kidRef.num == ref.num && kidRef.gen == ref.gen) { break; } } fieldName.unshift('`' + j); } namedItem = parent; ref = parentRef; } data.fullName = fieldName.join('.'); } var parent = Annotation.prototype; Util.inherit(WidgetAnnotation, Annotation, { isViewable: function WidgetAnnotation_isViewable() { if (this.data.fieldType === 'Sig') { warn('unimplemented annotation type: Widget signature'); return false; } return parent.isViewable.call(this); } }); return WidgetAnnotation; })(); var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() { function TextWidgetAnnotation(params) { WidgetAnnotation.call(this, params); if (params.data) { return; } this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q'); } // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont() function setTextStyles(element, item, fontObj) { var style = element.style; style.fontSize = item.fontSize + 'px'; style.direction = item.fontDirection < 0 ? 'rtl': 'ltr'; if (!fontObj) { return; } style.fontWeight = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); style.fontStyle = fontObj.italic ? 'italic' : 'normal'; var fontName = fontObj.loadedName; var fontFamily = fontName ? '"' + fontName + '", ' : ''; // Use a reasonable default font if the font doesn't specify a fallback var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } var parent = WidgetAnnotation.prototype; Util.inherit(TextWidgetAnnotation, WidgetAnnotation, { hasHtml: function TextWidgetAnnotation_hasHtml() { return !this.data.hasAppearance && !!this.data.fieldValue; }, getHtmlElement: function TextWidgetAnnotation_getHtmlElement(commonObjs) { assert(!isWorker, 'getHtmlElement() shall be called from main thread'); var item = this.data; var element = this.getEmptyContainer('div'); element.style.display = 'table'; var content = document.createElement('div'); content.textContent = item.fieldValue; var textAlignment = item.textAlignment; content.style.textAlign = ['left', 'center', 'right'][textAlignment]; content.style.verticalAlign = 'middle'; content.style.display = 'table-cell'; var fontObj = item.fontRefName ? commonObjs.getData(item.fontRefName) : null; var cssRules = setTextStyles(content, item, fontObj); element.appendChild(content); return element; }, getOperatorList: function TextWidgetAnnotation_getOperatorList(evaluator) { if (this.appearance) { return Annotation.prototype.getOperatorList.call(this, evaluator); } var promise = new LegacyPromise(); var opList = new OperatorList(); var data = this.data; // Even if there is an appearance stream, ignore it. This is the // behaviour used by Adobe Reader. var defaultAppearance = data.defaultAppearance; if (!defaultAppearance) { promise.resolve(opList); return promise; } // Include any font resources found in the default appearance var stream = new Stream(stringToBytes(defaultAppearance)); evaluator.getOperatorList(stream, this.fieldResources, opList); var appearanceFnArray = opList.fnArray; var appearanceArgsArray = opList.argsArray; var fnArray = []; var argsArray = []; // TODO(mack): Add support for stroke color data.rgb = [0, 0, 0]; // TODO THIS DOESN'T MAKE ANY SENSE SINCE THE fnArray IS EMPTY! for (var i = 0, n = fnArray.length; i < n; ++i) { var fnId = appearanceFnArray[i]; var args = appearanceArgsArray[i]; if (fnId === OPS.setFont) { data.fontRefName = args[0]; var size = args[1]; if (size < 0) { data.fontDirection = -1; data.fontSize = -size; } else { data.fontDirection = 1; data.fontSize = size; } } else if (fnId === OPS.setFillRGBColor) { data.rgb = args; } else if (fnId === OPS.setFillGray) { var rgbValue = args[0] * 255; data.rgb = [rgbValue, rgbValue, rgbValue]; } } promise.resolve(opList); return promise; } }); return TextWidgetAnnotation; })(); var InteractiveAnnotation = (function InteractiveAnnotationClosure() { function InteractiveAnnotation(params) { Annotation.call(this, params); } Util.inherit(InteractiveAnnotation, Annotation, { hasHtml: function InteractiveAnnotation_hasHtml() { return true; }, highlight: function InteractiveAnnotation_highlight() { if (this.highlightElement && this.highlightElement.hasAttribute('hidden')) { this.highlightElement.removeAttribute('hidden'); } }, unhighlight: function InteractiveAnnotation_unhighlight() { if (this.highlightElement && !this.highlightElement.hasAttribute('hidden')) { this.highlightElement.setAttribute('hidden', true); } }, initContainer: function InteractiveAnnotation_initContainer() { var item = this.data; var rect = item.rect; var container = this.getEmptyContainer('section', rect, item.borderWidth); container.style.backgroundColor = item.color; var color = item.color; var rgb = []; for (var i = 0; i < 3; ++i) { rgb[i] = Math.round(color[i] * 255); } item.colorCssRgb = Util.makeCssRgb(rgb); var highlight = document.createElement('div'); highlight.className = 'annotationHighlight'; highlight.style.left = highlight.style.top = -HIGHLIGHT_OFFSET + 'px'; highlight.style.right = highlight.style.bottom = -HIGHLIGHT_OFFSET + 'px'; highlight.setAttribute('hidden', true); this.highlightElement = highlight; container.appendChild(this.highlightElement); return container; } }); return InteractiveAnnotation; })(); var TextAnnotation = (function TextAnnotationClosure() { function TextAnnotation(params) { InteractiveAnnotation.call(this, params); if (params.data) { return; } var dict = params.dict; var data = this.data; var content = dict.get('Contents'); var title = dict.get('T'); data.content = stringToPDFString(content || ''); data.title = stringToPDFString(title || ''); if (data.hasAppearance) { data.name = 'NoIcon'; } else { data.name = dict.has('Name') ? dict.get('Name').name : 'Note'; } if (dict.has('C')) { data.hasBgColor = true; } } var ANNOT_MIN_SIZE = 10; Util.inherit(TextAnnotation, InteractiveAnnotation, { getHtmlElement: function TextAnnotation_getHtmlElement(commonObjs) { assert(!isWorker, 'getHtmlElement() shall be called from main thread'); var item = this.data; var rect = item.rect; // sanity check because of OOo-generated PDFs if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) { rect[3] = rect[1] + ANNOT_MIN_SIZE; } if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) { rect[2] = rect[0] + (rect[3] - rect[1]); // make it square } var container = this.initContainer(); container.className = 'annotText'; var image = document.createElement('img'); image.style.height = container.style.height; image.style.width = container.style.width; var iconName = item.name; image.src = PDFJS.imageResourcesPath + 'annotation-' + iconName.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: iconName}); var contentWrapper = document.createElement('div'); contentWrapper.className = 'annotTextContentWrapper'; contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px'; contentWrapper.style.top = '-10px'; var content = document.createElement('div'); content.className = 'annotTextContent'; content.setAttribute('hidden', true); var i, ii; if (item.hasBgColor) { var color = item.color; var rgb = []; for (i = 0; i < 3; ++i) { // Enlighten the color (70%) var c = Math.round(color[i] * 255); rgb[i] = Math.round((255 - c) * 0.7) + c; } content.style.backgroundColor = Util.makeCssRgb(rgb); } var title = document.createElement('h1'); var text = document.createElement('p'); title.textContent = item.title; if (!item.content && !item.title) { content.setAttribute('hidden', true); } else { var e = document.createElement('span'); var lines = item.content.split(/(?:\r\n?|\n)/); for (i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; e.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { e.appendChild(document.createElement('br')); } } text.appendChild(e); var pinned = false; var showAnnotation = function showAnnotation(pin) { if (pin) { pinned = true; } if (content.hasAttribute('hidden')) { container.style.zIndex += 1; content.removeAttribute('hidden'); } }; var hideAnnotation = function hideAnnotation(unpin) { if (unpin) { pinned = false; } if (!content.hasAttribute('hidden') && !pinned) { container.style.zIndex -= 1; content.setAttribute('hidden', true); } }; var toggleAnnotation = function toggleAnnotation() { if (pinned) { hideAnnotation(true); } else { showAnnotation(true); } }; var self = this; image.addEventListener('click', function image_clickHandler() { toggleAnnotation(); }, false); image.addEventListener('mouseover', function image_mouseOverHandler() { showAnnotation(); }, false); image.addEventListener('mouseout', function image_mouseOutHandler() { hideAnnotation(); }, false); content.addEventListener('click', function content_clickHandler() { hideAnnotation(true); }, false); } content.appendChild(title); content.appendChild(text); contentWrapper.appendChild(content); container.appendChild(image); container.appendChild(contentWrapper); return container; } }); return TextAnnotation; })(); var LinkAnnotation = (function LinkAnnotationClosure() { function LinkAnnotation(params) { InteractiveAnnotation.call(this, params); if (params.data) { return; } var dict = params.dict; var data = this.data; var action = dict.get('A'); if (action) { var linkType = action.get('S').name; if (linkType === 'URI') { var url = action.get('URI'); if (isName(url)) { // Some bad PDFs do not put parentheses around relative URLs. url = '/' + url.name; } else if (url) { url = addDefaultProtocolToUrl(url); } // TODO: pdf spec mentions urls can be relative to a Base // entry in the dictionary. if (!isValidUrl(url, false)) { url = ''; } data.url = url; } else if (linkType === 'GoTo') { data.dest = action.get('D'); } else if (linkType === 'GoToR') { var urlDict = action.get('F'); if (isDict(urlDict)) { // We assume that the 'url' is a Filspec dictionary // and fetch the url without checking any further url = urlDict.get('F') || ''; } // TODO: pdf reference says that GoToR // can also have 'NewWindow' attribute if (!isValidUrl(url, false)) { url = ''; } data.url = url; data.dest = action.get('D'); } else if (linkType === 'Named') { data.action = action.get('N').name; } else { warn('unrecognized link type: ' + linkType); } } else if (dict.has('Dest')) { // simple destination link var dest = dict.get('Dest'); data.dest = isName(dest) ? dest.name : dest; } } // Lets URLs beginning with 'www.' default to using the 'http://' protocol. function addDefaultProtocolToUrl(url) { if (url && url.indexOf('www.') === 0) { return ('http://' + url); } return url; } Util.inherit(LinkAnnotation, InteractiveAnnotation, { hasOperatorList: function LinkAnnotation_hasOperatorList() { return false; }, getHtmlElement: function LinkAnnotation_getHtmlElement(commonObjs) { var container = this.initContainer(); container.className = 'annotLink'; var item = this.data; var rect = item.rect; container.style.borderColor = item.colorCssRgb; container.style.borderStyle = 'solid'; var link = document.createElement('a'); link.href = link.title = this.data.url || ''; container.appendChild(link); return container; } }); return LinkAnnotation; })(); /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /* * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font renderer * that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will happen * automatically if the browser doesn't support workers or sending typed arrays * to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled in * development mode. If unspecified in the production build, the worker will be * loaded based on the location of the pdf.js file. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js * will automatically keep fetching more data even if it isn't needed to display * the current page. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Controls the logging level. * The constants from PDFJS.VERBOSITY_LEVELS should be used: * - errors * - warnings [default] * - infos * @var {number} */ PDFJS.verbosity = (PDFJS.verbosity === undefined ? PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity); /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray} data - A typed array with PDF data. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters} source Can be a url to * where a PDF is located, a typed array (Uint8Array) already populated with * data or parameter object. * * @param {Object} pdfDataRangeTransport is optional. It is used if you want * to manually serve range requests for data in the PDF. See viewer.js for * an example of pdfDataRangeTransport's interface. * * @param {function} passwordCallback is optional. It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @return {Promise} A promise that is resolved with {@link PDFDocumentProxy} * object. */ PDFJS.getDocument = function getDocument(source, pdfDataRangeTransport, passwordCallback, progressCallback) { var workerInitializedPromise, workerReadyPromise, transport; if (typeof source === 'string') { source = { url: source }; } else if (isArrayBuffer(source)) { source = { data: source }; } else if (typeof source !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!source.url && !source.data) { error('Invalid parameter array, need either .data or .url'); } // copy/use all keys as is except 'url' -- full path is required var params = {}; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { params[key] = combineUrl(window.location.href, source[key]); continue; } params[key] = source[key]; } workerInitializedPromise = new PDFJS.LegacyPromise(); workerReadyPromise = new PDFJS.LegacyPromise(); transport = new WorkerTransport(workerInitializedPromise, workerReadyPromise, pdfDataRangeTransport, progressCallback); workerInitializedPromise.then(function transportInitialized() { transport.passwordCallback = passwordCallback; transport.fetchDocument(params); }); return workerReadyPromise; }; /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport) { this.pdfInfo = pdfInfo; this.transport = transport; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { var promise = new PDFJS.LegacyPromise(); var js = this.pdfInfo.javaScript; promise.resolve(js); return promise; }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb array, * dest: dest obj, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { var promise = new PDFJS.LegacyPromise(); var outline = this.pdfInfo.outline; promise.resolve(outline); return promise; }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { var promise = new PDFJS.LegacyPromise(); var info = this.pdfInfo.info; var metadata = this.pdfInfo.metadata; promise.resolve({ info: info, metadata: (metadata ? new PDFJS.Metadata(metadata) : null) }); return promise; }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { var promise = new PDFJS.LegacyPromise(); this.transport.getData(promise); return promise; }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoPromise; }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { this.transport.destroy(); } }; return PDFDocumentProxy; })(); /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (optional) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * Proxy to a PDFPage in the worker thread. * @class */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageInfo, transport) { this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = !!globalScope.PDFJS.enableStats; this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingDestroy = false; this.intentStates = {}; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageInfo.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PageViewport} Contains 'width' and 'height' properties along * with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0); }, /** * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations() { if (this.annotationsPromise) { return this.annotationsPromise; } var promise = new PDFJS.LegacyPromise(); this.annotationsPromise = promise; this.transport.getAnnotations(this.pageInfo.pageIndex); return promise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingDestroy = false; var renderingIntent = ('intent' in params ? (params.intent == 'print' ? 'print' : 'display') : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there is no displayReadyPromise yet, then the operatorList was never // requested before. Make the request and create the promise. if (!intentState.displayReadyPromise) { intentState.receivingOperatorList = true; intentState.displayReadyPromise = new LegacyPromise(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = new RenderTask(internalRenderTask); var self = this; intentState.displayReadyPromise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingDestroy) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingDestroy = true; } self._tryDestroy(); if (error) { renderTask.promise.reject(error); } else { renderTask.promise.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent() { var promise = new PDFJS.LegacyPromise(); this.transport.messageHandler.send('GetTextContent', { pageIndex: this.pageNumber - 1 }, function textContentCallback(textContent) { promise.resolve(textContent); } ); return promise; }, /** * Destroys resources allocated by the page. */ destroy: function PDFPageProxy_destroy() { this.pendingDestroy = true; this._tryDestroy(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryDestroy: function PDFPageProxy__destroy() { if (!this.pendingDestroy || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.pendingDestroy = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; intentState.displayReadyPromise.resolve(transparency); }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryDestroy(); } } }; return PDFPageProxy; })(); /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(workerInitializedPromise, workerReadyPromise, pdfDataRangeTransport, progressCallback) { this.pdfDataRangeTransport = pdfDataRangeTransport; this.workerReadyPromise = workerReadyPromise; this.progressCallback = progressCallback; this.commonObjs = new PDFObjects(); this.pageCache = []; this.pagePromises = []; this.downloadInfoPromise = new PDFJS.LegacyPromise(); this.passwordCallback = null; // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fullfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an Uint8Array // as it arrives on the worker. Chrome added this with version 15. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { var workerSrc = PDFJS.workerSrc; if (!workerSrc) { error('No PDFJS.workerSrc specified'); } try { // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 workerSrc += '.jsf?ln=pdf.js'; var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', worker); this.messageHandler = messageHandler; messageHandler.on('test', function transportTest(data) { var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this.worker = worker; if (!data.supportTransfers) { PDFJS.postMessageTransfers = false; } this.setupMessageHandler(messageHandler); workerInitializedPromise.resolve(); } else { globalScope.PDFJS.disableWorker = true; this.loadFakeWorkerFiles().then(function() { this.setupFakeWorker(); workerInitializedPromise.resolve(); }.bind(this)); } }.bind(this)); var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, null, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. globalScope.PDFJS.disableWorker = true; this.loadFakeWorkerFiles().then(function() { this.setupFakeWorker(); workerInitializedPromise.resolve(); }.bind(this)); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { this.pageCache = []; this.pagePromises = []; var self = this; this.messageHandler.send('Terminate', null, function () { FontLoader.clear(); if (self.worker) { self.worker.terminate(); } }); }, loadFakeWorkerFiles: function WorkerTransport_loadFakeWorkerFiles() { if (!PDFJS.fakeWorkerFilesLoadedPromise) { PDFJS.fakeWorkerFilesLoadedPromise = new LegacyPromise(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. Util.loadScript(PDFJS.workerSrc, function() { PDFJS.fakeWorkerFilesLoadedPromise.resolve(); }); } return PDFJS.fakeWorkerFilesLoadedPromise; }, setupFakeWorker: function WorkerTransport_setupFakeWorker() { warn('Setting up fake worker.'); // If we don't use a worker, just post/sendMessage to the main thread. var fakeWorker = { postMessage: function WorkerTransport_postMessage(obj) { fakeWorker.onmessage({data: obj}); }, terminate: function WorkerTransport_terminate() {} }; var messageHandler = new MessageHandler('main', fakeWorker); this.setupMessageHandler(messageHandler); // If the main thread is our worker, setup the handling for the messages // the main thread sends to it self. PDFJS.WorkerMessageHandler.setup(messageHandler); }, setupMessageHandler: function WorkerTransport_setupMessageHandler(messageHandler) { this.messageHandler = messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var pdfDocument = new PDFDocumentProxy(pdfInfo, this); this.pdfDocument = pdfDocument; this.workerReadyPromise.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportPassword(data) { if (this.passwordCallback) { return this.passwordCallback(updatePassword, PasswordResponses.NEED_PASSWORD); } this.workerReadyPromise.reject(data.exception.message, data.exception); }, this); messageHandler.on('IncorrectPassword', function transportBadPass(data) { if (this.passwordCallback) { return this.passwordCallback(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } this.workerReadyPromise.reject(data.exception.message, data.exception); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(data) { this.workerReadyPromise.reject(data.exception.name, data.exception); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(data) { this.workerReadyPromise.reject(data.exception.message, data.exception); }, this); messageHandler.on('UnknownError', function transportUnknownError(data) { this.workerReadyPromise.reject(data.exception.message, data.exception); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoPromise.resolve(data); }, this); messageHandler.on('GetPage', function transportPage(data) { var pageInfo = data.pageInfo; var page = new PDFPageProxy(pageInfo, this); this.pageCache[pageInfo.pageIndex] = page; var promise = this.pagePromises[pageInfo.pageIndex]; promise.resolve(page); }, this); messageHandler.on('GetAnnotations', function transportAnnotations(data) { var annotations = data.annotations; var promise = this.pageCache[data.pageIndex].annotationsPromise; promise.resolve(annotations); }, this); messageHandler.on('StartRenderPage', function transportRender(data) { var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; var font; if ('error' in exportedData) { var error = exportedData.error; warn('Error during font loading: ' + error); this.commonObjs.resolve(id, error); break; } else { font = new FontFace(exportedData); } FontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.progressCallback) { this.progressCallback({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('DocError', function transportDocError(data) { this.workerReadyPromise.reject(data); }, this); messageHandler.on('PageError', function transportError(data, intent) { var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[intent]; if (intentState.displayReadyPromise) { intentState.displayReadyPromise.reject(data.error); } else { error(data.error); } }, this); messageHandler.on('JpegDecode', function(data, deferred) { var imageUrl = data[0]; var components = data[1]; if (components != 3 && components != 1) { error('Only 3 component or 1 component can be returned'); } var img = new Image(); img.onload = (function messageHandler_onloadClosure() { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components == 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components == 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } deferred.resolve({ data: buf, width: width, height: height}); }).bind(this); img.src = imageUrl; }); }, fetchDocument: function WorkerTransport_fetchDocument(source) { source.disableAutoFetch = PDFJS.disableAutoFetch; source.chunkedViewerLoading = !!this.pdfDataRangeTransport; this.messageHandler.send('GetDocRequest', { source: source, disableRange: PDFJS.disableRange, maxImageSize: PDFJS.maxImageSize, cMapUrl: PDFJS.cMapUrl, cMapPacked: PDFJS.cMapPacked, disableFontFace: PDFJS.disableFontFace, disableCreateObjectURL: PDFJS.disableCreateObjectURL, verbosity: PDFJS.verbosity }); }, getData: function WorkerTransport_getData(promise) { this.messageHandler.send('GetData', null, function(data) { promise.resolve(data); }); }, getPage: function WorkerTransport_getPage(pageNumber, promise) { if (pageNumber <= 0 || pageNumber > this.numPages || (pageNumber|0) !== pageNumber) { var pagePromise = new PDFJS.LegacyPromise(); pagePromise.reject(new Error('Invalid page request')); return pagePromise; } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } promise = new PDFJS.LegacyPromise(); this.pagePromises[pageIndex] = promise; this.messageHandler.send('GetPageRequest', { pageIndex: pageIndex }); return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { var promise = new PDFJS.LegacyPromise(); this.messageHandler.send('GetPageIndex', { ref: ref }, function (pageIndex) { promise.resolve(pageIndex); } ); return promise; }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex) { this.messageHandler.send('GetAnnotationsRequest', { pageIndex: pageIndex }); }, getDestinations: function WorkerTransport_getDestinations() { var promise = new PDFJS.LegacyPromise(); this.messageHandler.send('GetDestinations', null, function transportDestinations(destinations) { promise.resolve(destinations); } ); return promise; }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.send('Cleanup', null, function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.destroy(); } } this.commonObjs.clear(); FontLoader.clear(); }.bind(this) ); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = {}; } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { promise: new LegacyPromise(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.promise.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = {}; } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this.internalRenderTask = internalRenderTask; /** * Promise for rendering task completion. * @type {Promise} */ this.promise = new PDFJS.LegacyPromise(); } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this.internalRenderTask.cancel(); this.promise.reject(new Error('Rendering is cancelled')); }, /** * Registers callback to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then(onFulfilled, onRejected); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.cancelled = false; } InternalRenderTask.prototype = { initalizeGraphics: function InternalRenderTask_initalizeGraphics(transparency) { if (this.cancelled) { return; } if (PDFJS.pdfBug && 'StepperManager' in globalScope && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continue.bind(this); } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.params.continueCallback) { this.params.continueCallback(this._next.bind(this)); } else { this._next(); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continue.bind(this), this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); var Metadata = PDFJS.Metadata = (function MetadataClosure() { function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code != 60 && code != 62 && code != 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = {}; this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; return Metadata; })(); // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; var MAX_GROUP_SIZE = 4096; var COMPILE_TYPE3_GLYPHS = true; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based on. if (!ctx.mozCurrentTransform) { // Store the original context ctx._scaleX = ctx._scaleX || 1.0; ctx._scaleY = ctx._scaleY || 1.0; ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = [ctx._scaleX, 0, 0, ctx._scaleY, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { var cache = {}; return { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (id in cache) { canvasEntry = cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { cache = {}; } }; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Color spaces this.fillColorSpace = ColorSpace.singletons.gray; this.fillColorSpaceObj = null; this.strokeColorSpace = ColorSpace.singletons.gray; this.strokeColorSpaceObj = null; this.fillColorObj = null; this.strokeColorObj = null; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; if (canvasCtx) { addContextCurrentTransform(canvasCtx); } } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var fullChunkHeight = 16; var fracChunks = height / fullChunkHeight; var fullChunks = Math.floor(fracChunks); var totalChunks = Math.ceil(fracChunks); var partialChunkHeight = height - fullChunks * fullChunkHeight; var chunkImgData = ctx.createImageData(width, fullChunkHeight); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var destDataLength = dest.length; var srcLength = src.byteLength; var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? fullChunkHeight : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * fullChunkHeight); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? fullChunkHeight : partialChunkHeight; elemsInThisChunk = imgData.width * thisChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, i * fullChunkHeight); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? fullChunkHeight : partialChunkHeight; elemsInThisChunk = imgData.width * thisChunkHeight * 3; destPos = 0; for (j = 0; j < elemsInThisChunk; j += 3) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * fullChunkHeight); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var fullChunkHeight = 16; var fracChunks = height / fullChunkHeight; var fullChunks = Math.floor(fracChunks); var totalChunks = Math.ceil(fracChunks); var partialChunkHeight = height - fullChunks * fullChunkHeight; var chunkImgData = ctx.createImageData(width, fullChunkHeight); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? fullChunkHeight : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * fullChunkHeight); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (property in sourceCtx) { destCtx[property] = sourceCtx[property]; } } if ('setLineDash' in sourceCtx) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } else if ('mozDash' in sourceCtx) { destCtx.mozDash = sourceCtx.mozDash; destCtx.mozDashOffset = sourceCtx.mozDashOffset; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop) { var addBackdropFn; if (backdrop) { addBackdropFn = function (r0, g0, b0, bytes) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i] / 255; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 1) { var alpha_ = 1 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) | 0; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) | 0; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) | 0; } } }.bind(null, backdrop[0], backdrop[1], backdrop[2]); } else { addBackdropFn = function () {}; } var composeFn; if (subtype === 'Luminosity') { composeFn = function (maskDataBytes, layerDataBytes) { var length = maskDataBytes.length; for (var i = 3; i < length; i += 4) { var y = ((maskDataBytes[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskDataBytes[i - 2] * 152) + // * 0.59 .... (maskDataBytes[i - 1] * 28)) | 0; // * 0.11 .... layerDataBytes[i] = (layerDataBytes[i] * y) >> 16; } }; } else { composeFn = function (maskDataBytes, layerDataBytes) { var length = maskDataBytes.length; for (var i = 3; i < length; i += 4) { var alpha = maskDataBytes[i]; layerDataBytes[i] = (layerDataBytes[i] * alpha / 255) | 0; } }; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 65536; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); addBackdropFn(maskData.data); composeFn(maskData.data, layerData.data); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop; if (smask.backdrop) { var cs = smask.colorSpace || ColorSpace.singletons.rgb; backdrop = cs.getRgb(smask.backdrop, 0); } if (WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, so we fill with white if // we can. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; if (transparency) { this.ctx.clearRect(0, 0, width, height); } else { this.ctx.mozOpaque = true; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); } var transform = viewport.transform; this.ctx.save(); this.ctx.transform.apply(this.ctx, transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen == i) { return i; } var executionEndIdx; var endTime = Date.now() + EXECUTION_TIME; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; var deferred = Promise.resolve(); while (true) { if (stepper && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId.substring(0, 2) == 'g_'; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!common && !objs.isResolved(depObjId)) { objs.get(depObjId, continueCallback); return i; } if (common && !commonObjs.isResolved(depObjId)) { commonObjs.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i == argsArrayLen) { return i; } // If the execution took longer then a certain amount of time, schedule // to continue exeution after a short delay. // However, this is only possible if a 'continueCallback' is passed in. if (continueCallback && Date.now() > endTime) { deferred.then(continueCallback); return i; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { this.ctx.restore(); CachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if ('setLineDash' in ctx) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { this.endSMaskGroup(); } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = CachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); if (this.current.activeSMask) { this.current.activeSMask = null; } }, restore: function CanvasGraphics_restore() { var prev = this.stateStack.pop(); if (prev) { if (this.current.activeSMask) { this.endSMaskGroup(); } this.current = prev; this.ctx.restore(); } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); }, // Path moveTo: function CanvasGraphics_moveTo(x, y) { this.ctx.moveTo(x, y); this.current.setCurrentPoint(x, y); }, lineTo: function CanvasGraphics_lineTo(x, y) { this.ctx.lineTo(x, y); this.current.setCurrentPoint(x, y); }, curveTo: function CanvasGraphics_curveTo(x1, y1, x2, y2, x3, y3) { this.ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3); this.current.setCurrentPoint(x3, y3); }, curveTo2: function CanvasGraphics_curveTo2(x2, y2, x3, y3) { var current = this.current; this.ctx.bezierCurveTo(current.x, current.y, x2, y2, x3, y3); current.setCurrentPoint(x3, y3); }, curveTo3: function CanvasGraphics_curveTo3(x1, y1, x3, y3) { this.curveTo(x1, y1, x3, y3, x3, y3); this.current.setCurrentPoint(x3, y3); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, rectangle: function CanvasGraphics_rectangle(x, y, width, height) { if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } this.ctx.rect(x, y, width, height); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; if (this.current.lineWidth === 0) { ctx.lineWidth = this.getSinglePixelWidth(); } // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var needRestore = false; if (fillColor && fillColor.hasOwnProperty('type') && fillColor.type === 'Pattern') { ctx.save(); ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if ('mozFillRule' in this.ctx) { this.ctx.mozFillRule = 'evenodd'; this.ctx.fill(); this.ctx.mozFillRule = 'nonzero'; } else { try { this.ctx.fill('evenodd'); } catch (ex) { // shouldn't really happen, but browsers might think differently this.ctx.fill(); } } this.pendingEOFill = false; } else { this.ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { if (!('pendingTextPaths' in this)) { this.ctx.beginPath(); return; } var paths = this.pendingTextPaths; var ctx = this.ctx; ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.coded) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE; this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 : size / MIN_FONT_SIZE; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, applyTextTransforms: function CanvasGraphics_applyTextTransforms() { var ctx = this.ctx; var current = this.current; ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (current.fontDirection > 0) { ctx.scale(current.textHScale, -1); } else { ctx.scale(-current.textHScale, 1); } }, paintChar: function (character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize / current.fontSizeScale; var textRenderingMode = current.textRenderingMode; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * current.fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var vertical = font.vertical; var defaultVMetrics = font.defaultVMetrics; var i, glyph, width; var VERTICAL_TEXT_ROTATION = Math.PI / 2; if (fontSize === 0) { return; } // Type3 fonts - each glyph is a "mini-PDF" if (font.coded) { ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, 1); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (glyph === null) { // word break this.ctx.translate(wordSpacing, 0); current.x += wordSpacing * textHScale; continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(glyph.operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = ((transformed[0] * fontSize + charSpacing) * current.fontDirection); ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; } else { ctx.save(); this.applyTextTransforms(); var lineWidth = current.lineWidth; var a1 = current.textMatrix[0], b1 = current.textMatrix[1]; var scale = Math.sqrt(a1 * a1 + b1 * b1); if (scale === 0 || lineWidth === 0) { lineWidth = this.getSinglePixelWidth(); } else { lineWidth /= scale; } if (fontSizeScale != 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0; for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (glyph === null) { // word break x += current.fontDirection * wordSpacing; continue; } var restoreNeeded = false; var character = glyph.fontChar; var vmetric = glyph.vmetric || defaultVMetrics; if (vertical) { var vx = glyph.vmetric ? vmetric[1] : glyph.width * 0.5; vx = -vx * fontSize * current.fontMatrix[0]; var vy = vmetric[2] * fontSize * current.fontMatrix[0]; } width = vmetric ? -vmetric[0] : glyph.width; var charWidth = width * fontSize * current.fontMatrix[0] + charSpacing * current.fontDirection; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; if (vertical) { scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) { // some standard fonts may not have the exact width, trying to // rescale per character var measuredWidth = ctx.measureText(character).width * 1000 / current.fontSize * current.fontSizeScale; var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; if (accent) { scaledAccentX /= characterScaleX; } } this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); } }, showSpacedText: function CanvasGraphics_showSpacedText(arr) { var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; // TJ array's number is independent from fontMatrix var textHScale = current.textHScale * 0.001 * current.fontDirection; var arrLength = arr.length; var vertical = font.vertical; for (var i = 0; i < arrLength; ++i) { var e = arr[i]; if (isNum(e)) { var spacingLength = -e * fontSize * textHScale; if (vertical) { current.y += spacingLength; } else { current.x += spacingLength; } } else { this.showText(e); } } }, nextLineShowText: function CanvasGraphics_nextLineShowText(text) { this.nextLine(); this.showText(text); }, nextLineSetSpacingShowText: function CanvasGraphics_nextLineSetSpacingShowText(wordSpacing, charSpacing, text) { this.setWordSpacing(wordSpacing); this.setCharSpacing(charSpacing); this.nextLineShowText(text); }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.rectangle(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color setStrokeColorSpace: function CanvasGraphics_setStrokeColorSpace(raw) { this.current.strokeColorSpace = ColorSpace.fromIR(raw); }, setFillColorSpace: function CanvasGraphics_setFillColorSpace(raw) { this.current.fillColorSpace = ColorSpace.fromIR(raw); }, setStrokeColor: function CanvasGraphics_setStrokeColor(/*...*/) { var cs = this.current.strokeColorSpace; var rgbColor = cs.getRgb(arguments, 0); var color = Util.makeCssRgb(rgbColor); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR, cs) { var pattern; if (IR[0] == 'TilingPattern') { var args = IR[1]; var base = cs.base; var color; if (base) { var baseComps = base.numComps; color = base.getRgb(args, 0); } pattern = new TilingPattern(IR, color, this.ctx, this.objs, this.commonObjs, this.baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { var cs = this.current.strokeColorSpace; if (cs.name == 'Pattern') { this.current.strokeColor = this.getColorN_Pattern(arguments, cs); } else { this.setStrokeColor.apply(this, arguments); } }, setFillColor: function CanvasGraphics_setFillColor(/*...*/) { var cs = this.current.fillColorSpace; var rgbColor = cs.getRgb(arguments, 0); var color = Util.makeCssRgb(rgbColor); this.ctx.fillStyle = color; this.current.fillColor = color; }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { var cs = this.current.fillColorSpace; if (cs.name == 'Pattern') { this.current.fillColor = this.getColorN_Pattern(arguments, cs); } else { this.setFillColor.apply(this, arguments); } }, setStrokeGray: function CanvasGraphics_setStrokeGray(gray) { this.current.strokeColorSpace = ColorSpace.singletons.gray; var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0); var color = Util.makeCssRgb(rgbColor); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillGray: function CanvasGraphics_setFillGray(gray) { this.current.fillColorSpace = ColorSpace.singletons.gray; var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0); var color = Util.makeCssRgb(rgbColor); this.ctx.fillStyle = color; this.current.fillColor = color; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { this.current.strokeColorSpace = ColorSpace.singletons.rgb; var rgbColor = this.current.strokeColorSpace.getRgb(arguments, 0); var color = Util.makeCssRgb(rgbColor); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { this.current.fillColorSpace = ColorSpace.singletons.rgb; var rgbColor = this.current.fillColorSpace.getRgb(arguments, 0); var color = Util.makeCssRgb(rgbColor); this.ctx.fillStyle = color; this.current.fillColor = color; }, setStrokeCMYKColor: function CanvasGraphics_setStrokeCMYKColor(c, m, y, k) { this.current.strokeColorSpace = ColorSpace.singletons.cmyk; var color = Util.makeCssCmyk(arguments); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillCMYKColor: function CanvasGraphics_setFillCMYKColor(c, m, y, k) { this.current.fillColorSpace = ColorSpace.singletons.cmyk; var color = Util.makeCssCmyk(arguments); this.ctx.fillStyle = color; this.current.fillColor = color; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (matrix && isArray(matrix) && 6 == matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (bbox && isArray(bbox) && 4 == bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.rectangle(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implmenting: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = CachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, colorSpace: group.colorSpace && ColorSpace.fromIR(group.colorSpace) }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if ('imageSmoothingEnabled' in this.ctx) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (rect && isArray(rect) && 4 == rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.rectangle(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && !('compiled' in glyph)) { var MAX_SIZE_TO_COMPILE = 1000; if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; var fillColor = this.current.fillColor; maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') && fillColor.type === 'Pattern') ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; var fillColor = this.current.fillColor; maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') && fillColor.type === 'Pattern') ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; var fillColor = this.current.fillColor; maskCtx.fillStyle = (fillColor && fillColor.hasOwnProperty('type') && fillColor.type === 'Pattern') ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { if (this.pendingClip) { if (this.pendingClip == EO_CLIP) { if ('mozFillRule' in this.ctx) { this.ctx.mozFillRule = 'evenodd'; this.ctx.clip(); this.ctx.mozFillRule = 'nonzero'; } else { try { this.ctx.clip('evenodd'); } catch (ex) { // shouldn't really happen, but browsers might think differently this.ctx.clip(); } } } else { this.ctx.clip(); } this.pendingClip = null; } this.ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { var inverse = this.ctx.mozCurrentTransformInverse; // max of the current horizontal and vertical scale return Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generageGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generageGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generageGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[i]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { smaskCache = null; figuresCache = null; } return { get isEnabled() { if (PDFJS.disableWebGL) { return false; } var enabled = false; try { generageGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false); tmpCanvas.context.drawImage(canvas, 0, 0); canvas = tmpCanvas.canvas; } else { tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, 0, 0); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var combinedScale; // Obtain scale from matrix and current transformation matrix. if (shadingFill) { combinedScale = Util.singularValueDecompose2dScale( ctx.mozCurrentTransform); } else { var matrixScale = Util.singularValueDecompose2dScale(matrix); var curMatrixScale = Util.singularValueDecompose2dScale( owner.baseTransform); combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, combinedScale, coords, colors, figures, shadingFill ? null : background); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) { this.name = IR[1][0].name; this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.objs = objs; this.commonObjs = commonObjs; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var objs = this.objs; var commonObjs = this.commonObjs; var ctx = this.ctx; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && 4 == bbox.length) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.rectangle(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var rgbColor = ColorSpace.singletons.rgb.getRgb(color, 0); var cssColor = Util.makeCssRgb(rgbColor); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); PDFJS.disableFontFace = false; var FontLoader = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG'); if (!styleElement) { styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG'; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG'); if (styleElement) { styleElement.parentNode.removeChild(styleElement); } }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, loadTestFontId: 0, loadingContext: { requests: [], nextRequestId: 0 }, isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() { if (isWorker) { return false; } // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var userAgent = window.navigator.userAgent; var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent); if (m && m[1] >= 14) { return true; } // TODO other browsers return false; })(), bind: function fontLoaderBind(fonts, callback) { assert(!isWorker, 'bind() shall be called from main thread'); var rules = [], fontsToLoad = []; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; var rule = font.bindDOM(); if (rule) { rules.push(rule); fontsToLoad.push(font); } } var request = FontLoader.queueLoadingCallback(callback); if (rules.length > 0 && !this.isSyncFontLoadingSupported) { FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = FontLoader.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; FontLoader.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; var FontFace = (function FontFaceClosure() { function FontFace(name, file, properties) { this.compiledGlyphs = {}; if (arguments.length === 1) { // importing translated data var data = arguments[0]; for (var i in data) { this[i] = data[i]; } return; } } FontFace.prototype = { bindDOM: function FontFace_bindDOM() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + window.btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; FontLoader.insertRule(rule); if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this, url); } return rule; }, getPathGenerator: function (objs, character) { if (!(character in this.compiledGlyphs)) { var js = objs.get(this.loadedName + '_path_' + character); /*jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } return this.compiledGlyphs[character]; } }; return FontFace; })(); }).call((typeof window === 'undefined') ? this : window); if (!PDFJS.workerSrc && typeof document !== 'undefined') { // workerSrc is not set -- using last script url to define default location PDFJS.workerSrc = (function () { 'use strict'; var scriptTagContainer = document.body || document.getElementsByTagName('head')[0]; var pdfjsSrc = scriptTagContainer.lastChild.src; return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js'); })(); }
javaopensource2017/devweb
devweb/framework/resources/META-INF/resources/pdf.js/pdf.js
JavaScript
gpl-3.0
277,125
package fi.pyramus.rest.model; public class CourseType { public CourseType() { } public CourseType(Long id, String name, Boolean archived) { this(); this.id = id; this.name = name; this.archived = archived; } public CourseType(String name, Boolean archived) { this(null, name, archived); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } private Long id; private String name; private Boolean archived; }
leafsoftinfo/pyramus
rest-model/src/main/java/fi/pyramus/rest/model/CourseType.java
Java
gpl-3.0
751
from Social import * class Comment(db.Model): __tablename__ = "Comments" Id = db.Column(db.Integer, unique=True, primary_key=True) post = db.Column(db.Integer) author = db.Column(db.String(20)) text = db.Column(db.String(500)) date = db.Column(db.DateTime(25)) def __init__(self, post, author, text): self.post = post self.text = text self.author = author.UserId self.date = datetime.datetime.now() class Post(db.Model): __tablename__ = "Posts" Id = db.Column(db.Integer, unique=True, primary_key=True) author = db.Column(db.String(20)) text = db.Column(db.String(500)) date = db.Column(db.DateTime(25)) def __init__(self, author, text): self.author = author.UserId self.text = text self.date = datetime.datetime.now() class Hashtag(db.Model): __tablename__ = "Hashtag" Id = db.Column(db.Integer, unique=True, primary_key=True) name = db.Column(db.String(25)) posts = db.Column(db.String(25)) def __init__(self, name, FirstPost): self.name = name self.posts = FirstPost def __repr__(self): return "<Hashtag #"+self.name+">" class User(db.Model): __tablename__ = "Users" UserId = db.Column(db.String(20), unique=True, primary_key=True) name = db.Column(db.String(10)) cognome = db.Column(db.String(10)) img = db.Column(db.String(255)) desc = db.Column(db.String(255)) Hash = db.Column(db.String(60)) Salt = db.Column(db.String(100)) follows = db.Column(db.String(1000)) FeedKey = db.Column(db.String(70), unique=True) def __init__(self, name, cognome, UserName, password, desc): self.UserId = UserName self.name = name self.cognome = cognome self.img = "/static/NewUser.png" self.desc = desc self.Salt = bcrypt.gensalt()[7:] self.Hash = bcrypt.hashpw(str(password), "$2a$12$"+self.Salt) self.follows = "" self.FeedKey = bcrypt.hashpw(str(password+UserName), bcrypt.gensalt()) db.session.add(self) db.session.commit() def __repr__(self): return "<User {id}>".format(id=self.UserId) @property def is_authenticated(self): return True @property def is_active(self): return True @property def is_anonymous(self): return False def get_id(self): return unicode(self.UserId)
JackSpera/NapNap
Models.py
Python
gpl-3.0
2,444
<?php echo head(array('bodyid'=>'home')); ?> <div id="primary"> <?php if ($homepageText = get_theme_option('Homepage Text')): ?> <p><?php echo $homepageText; ?></p> <?php endif; ?> <?php if ((get_theme_option('Display Featured Exhibit')) && function_exists('exhibit_builder_display_random_featured_exhibit')): ?> <!-- Featured Exhibit --> <?php echo dh_display_random_featured_exhibits(20); ?> <?php endif; ?> <?php if (get_theme_option('Display Featured Item') == 1): ?> <!-- Featured Item --> <h2><?php echo __('Featured Items'); ?></h2> <div id="featured-item" class="grid js-masonry" data-masonry-options='{ "itemSelector": ".record", "columWidth": 296.666666667, "transitionDuration": "0.2s" }'> <?php echo random_featured_items(20); ?> </div><!--end featured-item--> <?php endif; ?> <?php if (get_theme_option('Display Featured Collection')): ?> <!-- Featured Collection --> <h2><?php echo __('Featured Collections'); ?></h2> <div id="featured-collection" class="grid js-masonry" data-masonry-options='{ "itemSelector": ".record", "columWidth": 296.666666667, "transitionDuration": "0.2s" }'> <?php echo dh_random_featured_collections(5); ?> </div><!-- end featured collection --> <?php endif; ?> </div><!-- end primary --> <?php echo foot(); ?>
jaguillette/hvd-dh-omeka-theme
index.php
PHP
gpl-3.0
1,345
/* * Created on 19-may-2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ /* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibáñez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * gvsig@gva.es * www.gvsig.gva.es * * or * * IVER T.I. S.A * Salamanca 50 * 46005 Valencia * Spain * * +34 963163400 * dac@iver.es */ package com.iver.cit.gvsig; /** */ import java.awt.geom.Rectangle2D; import com.iver.andami.PluginServices; import com.iver.andami.plugins.Extension; import com.iver.andami.ui.mdiManager.IWindow; import com.iver.cit.gvsig.project.documents.layout.gui.Layout; /** * DOCUMENT ME! * * @author vcn */ public class PrintProperties extends Extension /*implements IPreferenceExtension*/ { private Layout l; // private static final IPreference printPropertiesPage = new PrintPropertiesPage(); // private Paper paper; Rectangle2D.Double aux = null; /** * DOCUMENT ME! * * @param s DOCUMENT ME! */ public void execute(String s) { l = (Layout) PluginServices.getMDIManager().getActiveWindow(); l.showFConfig(); //l.showPagePropertiesWindow(Print.printerJob); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisible() { IWindow f = PluginServices.getMDIManager().getActiveWindow(); if (f == null) { return false; } return (f instanceof Layout); } /** * @see com.iver.mdiApp.plugins.IExtension#isEnabled() */ public boolean isEnabled() { Layout f = (Layout) PluginServices.getMDIManager().getActiveWindow(); if (f == null || !f.getLayoutContext().isEditable()) { return false; } return true; } /** * @see com.iver.andami.plugins.IExtension#initialize() */ public void initialize() { registerIcons(); } private void registerIcons(){ PluginServices.getIconTheme().registerDefault( "layout-page-setup", this.getClass().getClassLoader().getResource("images/Frame.gif") ); PluginServices.getIconTheme().registerDefault( "prepare-page-icon", this.getClass().getClassLoader().getResource("images/prepare-page.png") ); PluginServices.getIconTheme().registerDefault( "portrait-page-setup", this.getClass().getClassLoader().getResource("images/portrait-page.png") ); PluginServices.getIconTheme().registerDefault( "landscape-page-setup", this.getClass().getClassLoader().getResource("images/landscape-page.png") ); } // public IPreference getPreferencesPage() { // return printPropertiesPage; // } }
iCarto/siga
appgvSIG/src/com/iver/cit/gvsig/PrintProperties.java
Java
gpl-3.0
3,670
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * lsciss question renderer class. * * @package qtype * @subpackage lsciss * @copyright 2016 Learning Science Ltd https://learnsci.co.uk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); use Learnsci\Spreadsheet; use Learnsci\CellGrader; use Learnsci\LsspreadsheetUtils; use Learnsci\Chart; use Learnsci\ChartStats; class qtype_lsciss_renderer extends qtype_renderer { public function formulation_and_controls(question_attempt $qa, question_display_options $options) { global $CFG; $question = $qa->get_question(); //moodle going throughtext and filtering $questiontext = $question->format_questiontext($qa); $spreadSheet = new Spreadsheet(); $spreadSheet->setJsonStringFromDb($question->lsspreaddata); $graded = $spreadSheet->grade_spreadsheet_question($qa->get_last_qt_data()); $chart = new Chart(); $chartJS = $chart->get_chart_javascript($question->id, $CFG->wwwroot, '', ''); $feedbackStyles = [ 'correctFeedbackClass' => $this->feedback_class(1), 'correctFeedbackImage' => $this->feedback_image(1), 'wrongFeedbackClass' => $this->feedback_class(0), 'wrongFeedbackImage' => $this->feedback_image(0) ]; $html = $spreadSheet->getTakeTableFromLsspreaddata($qa->get_field_prefix(), $options, $qa, $graded, $feedbackStyles); //$html .= $showChart; $html .= '<div style="clear:both;"></div>'; $result = html_writer::tag('div', $questiontext . $html, array('class' => 'qtext')); return $result; } public function specific_feedback(question_attempt $qa) { // TODO. return ''; } public function correct_response(question_attempt $qa) { // TODO. return ''; } }
LearningScience/moodle-qtype_lsciss
renderer.php
PHP
gpl-3.0
2,583
# -*- coding: utf-8 -*- """ Started on thu, jun 21st, 2018 @author: carlos.arana """ # Librerias utilizadas import pandas as pd import sys module_path = r'D:\PCCS\01_Dmine\Scripts' if module_path not in sys.path: sys.path.append(module_path) from VarInt.VarInt import VarInt from classes.Meta import Meta from Compilador.Compilador import compilar """ Las librerias locales utilizadas renglones arriba se encuentran disponibles en las siguientes direcciones: SCRIPT: | DISPONIBLE EN: ------ | ------------------------------------------------------------------------------------ VarInt | https://github.com/INECC-PCCS/01_Dmine/tree/master/Scripts/VarInt Meta | https://github.com/INECC-PCCS/01_Dmine/tree/master/Scripts/Classes Compilador | https://github.com/INECC-PCCS/01_Dmine/tree/master/Scripts/Compilador """ # Documentacion del Parametro --------------------------------------------------------------------------------------- # Descripciones del Parametro M = Meta M.ClaveParametro = 'P9902' M.NombreParametro = 'Personal Docente' M.DescParam = 'Personal docente en educación básica y media superior de la modalidad escolarizada' M.UnidadesParam = 'Personas' M.TituloParametro = 'PD' # Para nombrar la columna del parametro M.PeriodoParam = '2015' M.TipoInt = 1 # 1: Binaria; 2: Multivariable, 3: Integral # Handlings M.ParDtype = 'float' M.TipoVar = 'C' # (Tipos de Variable: [C]ontinua, [D]iscreta [O]rdinal, [B]inaria o [N]ominal) M.array = [] M.TipoAgr = 'sum' # Descripciones del proceso de Minería M.nomarchivodataset = 'P9902' M.extarchivodataset = 'xlsx' M.ContenidoHojaDatos = 'Número de docentes por nivel educativo' M.ClaveDataset = 'INEGI' M.ActDatos = '2015' M.Agregacion = 'Suma de unidades para los municipios que componen cada ciudad del SUN' \ # Descripciones generadas desde la clave del parámetro M.getmetafromds = 1 Meta.fillmeta(M) # Construccion del Parámetro ----------------------------------------------------------------------------------------- # Cargar dataset inicial dataset = pd.read_excel(M.DirFuente + '\\' + M.ArchivoDataset, sheetname='DATOS', dtype={'CVE_MUN': 'str'}) dataset.set_index('CVE_MUN', inplace=True) del(dataset['Nombre']) dataset = dataset.rename_axis('CVE_MUN') dataset.head(2) list(dataset) # Generar dataset para parámetro y Variable de Integridad var1 = 'Docentes Total' par_dataset = dataset[var1] par_dataset = dataset[var1].astype('float') par_dataset = par_dataset.to_frame(name = M.ClaveParametro) par_dataset, variables_dataset = VarInt(par_dataset, dataset, tipo=M.TipoInt) # Compilacion compilar(M, dataset, par_dataset, variables_dataset)
Caranarq/01_Dmine
99_Descentralizacion/P9902/P9902.py
Python
gpl-3.0
2,753
/* * Copyright (C) 2000-2012 InfoChamp System Corporation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.gk.engine.client.build.form; import java.util.Iterator; import java.util.List; import org.gk.engine.client.build.XComponent; import org.gk.engine.client.gen.UIGen; import com.extjs.gxt.ui.client.widget.Component; import com.extjs.gxt.ui.client.widget.Header; import com.google.gwt.xml.client.Node; public class XHeader extends XComponent { protected Header header; protected String heading; protected String icon; public XHeader(Node node, List<UIGen> widgets) { super(node, widgets); heading = super.getAttribute("heading", ""); icon = super.getAttribute("icon", ""); } public Header getHeader() { return header; } public void setHeader(Header header) { this.header = header; } public String getHeading() { return heading; } public String getIcon() { return icon; } @Override public Component build() { // 這個判斷只是為了避免程式出錯而已,header不應該為null if (header == null) { header = new Header(); } if (!heading.equals("")) { header.setText(heading); } if (!icon.equals("")) { header.setIconStyle(icon); } for (Iterator<UIGen> it = widgets.iterator(); it.hasNext();) { UIGen ui = it.next(); header.addTool(ui.build()); } return header; } }
ezoengine/GKEngine
main/gk/src/org/gk/engine/client/build/form/XHeader.java
Java
gpl-3.0
2,059
package net.foreworld.nw.listener; /** * * @author huangxin (3203317@qq.com) * */ public interface OnShowListener { public void onShow(); }
3203317/vnc
viewer/src/net/foreworld/nw/listener/OnShowListener.java
Java
gpl-3.0
147
#include <algorithm> #include "yaml-cpp/node/convert.h" namespace { // we're not gonna mess with the mess that is all the isupper/etc. functions bool IsLower(char ch) { return 'a' <= ch && ch <= 'z'; } bool IsUpper(char ch) { return 'A' <= ch && ch <= 'Z'; } char ToLower(char ch) { return IsUpper(ch) ? ch + 'a' - 'A' : ch; } std::string tolower(const std::string& str) { std::string s(str); std::transform(s.begin(), s.end(), s.begin(), ToLower); return s; } template <typename T> bool IsEntirely(const std::string& str, T func) { for (std::size_t i = 0; i < str.size(); i++) if (!func(str[i])) return false; return true; } // IsFlexibleCase // . Returns true if 'str' is: // . UPPERCASE // . lowercase // . Capitalized bool IsFlexibleCase(const std::string& str) { if (str.empty()) return true; if (IsEntirely(str, IsLower)) return true; bool firstcaps = IsUpper(str[0]); std::string rest = str.substr(1); return firstcaps && (IsEntirely(rest, IsLower) || IsEntirely(rest, IsUpper)); } } namespace RIVET_YAML { bool convert<bool>::decode(const Node& node, bool& rhs) { if (!node.IsScalar()) return false; // we can't use iostream bool extraction operators as they don't // recognize all possible values in the table below (taken from // http://yaml.org/type/bool.html) static const struct { std::string truename, falsename; } names[] = { {"y", "n"}, {"yes", "no"}, {"true", "false"}, {"on", "off"}, }; if (!IsFlexibleCase(node.Scalar())) return false; for (unsigned i = 0; i < sizeof(names) / sizeof(names[0]); i++) { if (names[i].truename == tolower(node.Scalar())) { rhs = true; return true; } if (names[i].falsename == tolower(node.Scalar())) { rhs = false; return true; } } return false; } }
hep-mirrors/rivet
src/Core/yamlcpp/convert.cpp
C++
gpl-3.0
1,837
import configparser import logging import os from shutil import copyfile class wordclock_config: def __init__(self, basePath): self.loadConfig(basePath) def loadConfig(self, basePath): pathToConfigFile = basePath + '/wordclock_config/wordclock_config.cfg' pathToReferenceConfigFile = basePath + '/wordclock_config/wordclock_config.reference.cfg' if not os.path.exists(pathToConfigFile): if not os.path.exists(pathToReferenceConfigFile): logging.error('No config-file available!') logging.error(' Expected ' + pathToConfigFile + ' or ' + pathToReferenceConfigFile) raise Exception('Missing config-file') copyfile(pathToReferenceConfigFile, pathToConfigFile) logging.warning('No config-file specified! Was created from reference-config!') logging.info('Parsing ' + pathToConfigFile) self.config = configparser.ConfigParser() self.config.read(pathToConfigFile) self.reference_config = configparser.ConfigParser() self.reference_config.read(pathToReferenceConfigFile) # Add to the loaded configuration the current base path to provide it # to other classes/plugins for further usage self.config.set('wordclock', 'base_path', basePath) def request(self, method, *args): try: return getattr(self.config, method)(*args) except: logging.warning("Defaulting to reference value for [" + str(args[0]) + "] " + str(args[1]) ) return getattr(self.reference_config, method)(*args) def getboolean(self, *args): return self.request("getboolean", *args) def getint(self, *args): return self.request("getint", *args) def get(self, *args): return self.request("get", *args)
bk1285/rpi_wordclock
wordclock_tools/wordclock_config.py
Python
gpl-3.0
1,847
// Decompiled with JetBrains decompiler // Type: System.IO.Ports.SerialData // Assembly: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 5ABD58FD-DF31-44FD-A492-63F2B47CC9AF // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll namespace System.IO.Ports { /// <summary> /// Specifies the type of character that was received on the serial port of the <see cref="T:System.IO.Ports.SerialPort"/> object. /// </summary> public enum SerialData { Chars = 1, Eof = 2, } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System/System/IO/Ports/SerialData.cs
C#
gpl-3.0
549
class DiscoveredHostSerializer < ActiveModel::Serializer include ActionView::Helpers::NumberHelper embed :ids, include: true attributes :id, :name, :type, :ip, :last_report, :mac, :subnet_id, :subnet_name, :memory, :disk_count, :disks_size, :cpus, :organization_id, :organization_name, :location_id, :location_name, :created_at, :updated_at, :memory_human_size, :disks_human_size, :subnet_to_s, :is_virtual def cpus object.cpu_count end def memory_human_size return "0 MB" if object.memory.blank? || object.memory.to_i == 0 number_to_human_size(object.memory.to_i * 1024 * 1024) end def disks_human_size return "0 MB" if object.disks_size.blank? || object.disks_size.to_i == 0 number_to_human_size(object.disks_size.to_i * 1024 * 1024) end def subnet_to_s object.subnet.to_s end def is_virtual object.facts['is_virtual'] end end
daviddavis/foretello_api_v21
app/serializers/discovered_host_serializer.rb
Ruby
gpl-3.0
980
<div id="main_bg"></div> <div class="container"><div class="row">
NorthWebSolutions/Aram
application/views/templates/start_content.php
PHP
gpl-3.0
65
import enum from zope.schema.interfaces import IBaseVocabulary from zope.interface import directlyProvides from isu.enterprise.enums import vocabulary @vocabulary('mural') @enum.unique class Mural(enum.IntEnum): Extramural = 0 Intramural = 1 @vocabulary('degree') @enum.unique class Degree(enum.IntEnum): NoDegree = 0 Bacheloir = 5 # Бакалавр Specialist = 6 # Специалист Master = 7 # Магистр PhD = 8 MD = 9 Professor = 10 @vocabulary('academicity') @enum.unique class AcademicRelevance(enum.IntEnum): """ Программы прикладного бакалавриата рассчитаны на то, что выпускник получит больше практических навыков, пройдет длительную стажировку и по окончании вуза сможет "встать к станку". Академический бакалавриат дает больше теоретических знаний, и его выпускники более ориентированы на продолжение обучения в магистратуре. """ Academс = 1 Applied = 2
isu-enterprise/isu.college
src/isu/college/enums.py
Python
gpl-3.0
1,242
<?php /** * The install module English file of ZenTaoPMS. * * @copyright Copyright 2009-2012 青岛易软天创网络科技有限公司 (QingDao Nature Easy Soft Network Technology Co,LTD www.cnezsoft.com) * @license LGPL (http://www.gnu.org/licenses/lgpl.html) * @author Chunsheng Wang <chunsheng@cnezsoft.com> * @package install * @version $Id: en.php 3374 2012-07-27 01:23:08Z wwccss $ * @link http://www.zentao.net */ $lang->install->common = 'Install'; $lang->install->next = 'Next'; $lang->install->pre = 'Back'; $lang->install->reload = 'Reload'; $lang->install->error = 'Error '; $lang->install->start = 'Start install'; $lang->install->keepInstalling = 'Keep install this version'; $lang->install->seeLatestRelease = 'See the latest release.'; $lang->install->welcome = 'Welcome to use ZenTaoPMS.'; $lang->install->desc = <<<EOT ZenTaoPMS is an opensource project management software licensed under LGPL. It has product manage, project mange, testing mange features, also with organization manage and affair manage. ZenTaoPMS is developped by PHH and mysql under the zentaophp framework developped by the same team. Through the framework, ZenTaoPMS can be customed and extended very easily. ZenTaoPMS is developped by <strong class='red'><a href='http://www.cnezsoft.com' target='_blank'>Nature EasySoft Network Tecnology Co.ltd, QingDao, China</a></strong>。 The official website of ZenTaoPMS is <a href='http://en.zentao.net' target='_blank'>http://en.zentao.net</a> twitter:zentaopms The version of current release is <strong class='red'>%s</strong>。 EOT; $lang->install->newReleased= "<strong class='red'>Notice</strong>:There is a new version <strong class='red'>%s</strong>, released on %s。"; $lang->install->choice = 'You can '; $lang->install->checking = 'System checking'; $lang->install->ok = 'OK(√)'; $lang->install->fail = 'Failed(×)'; $lang->install->loaded = 'Loaded'; $lang->install->unloaded = 'Not loaded'; $lang->install->exists = 'Exists '; $lang->install->notExists = 'Not exists '; $lang->install->writable = 'Writable '; $lang->install->notWritable= 'Not writable '; $lang->install->phpINI = 'PHP ini file'; $lang->install->checkItem = 'Items'; $lang->install->current = 'Current'; $lang->install->result = 'Result'; $lang->install->action = 'How to fix'; $lang->install->phpVersion = 'PHP version'; $lang->install->phpFail = 'Must > 5.2.0'; $lang->install->pdo = 'PDO extension'; $lang->install->pdoFail = 'Edit the php.ini file to load PDO extsion.'; $lang->install->pdoMySQL = 'PDO_MySQL extension'; $lang->install->pdoMySQLFail = 'Edit the php.ini file to load PDO_MySQL extsion.'; $lang->install->json = 'JSON extension'; $lang->install->jsonFail = 'Edit the php.ini file to load JSON extension'; $lang->install->tmpRoot = 'Temp directory'; $lang->install->dataRoot = 'Upload directory.'; $lang->install->mkdir = '<p>Should creat the directory %s。<br /> Under linux, can try<br /> mkdir -p %s</p>'; $lang->install->chmod = 'Should change the permission of "%s".<br />Under linux, can try<br />chmod o=rwx -R %s'; $lang->install->settingDB = 'Set database'; $lang->install->webRoot = 'ZenTaoPMS path'; $lang->install->requestType = 'URL type'; $lang->install->defaultLang = 'Default Language'; $lang->install->dbHost = 'Database host'; $lang->install->dbHostNote = 'If localhost can not connect, try 127.0.0.1'; $lang->install->dbPort = 'Host port'; $lang->install->dbUser = 'Database user'; $lang->install->dbPassword = 'Database password'; $lang->install->dbName = 'Database name'; $lang->install->dbPrefix = 'Table prefix'; $lang->install->createDB = 'Auto create database'; $lang->install->clearDB = 'Clear data if database exists.'; $lang->install->importDemoData = 'Import demo data if database exists.'; $lang->install->requestTypes['GET'] = 'GET'; $lang->install->requestTypes['PATH_INFO'] = 'PATH_INFO'; $lang->install->errorConnectDB = 'Database connect failed.'; $lang->install->errorCreateDB = 'Database create failed.'; $lang->install->errorTableExists = 'The same tables alread exists, to continue install, go back and check the clear db box.'; $lang->install->errorCreateTable = 'Table create failed.'; $lang->install->errorImportDemoData = 'Import demo data.'; $lang->install->setConfig = 'Create config file'; $lang->install->key = 'Item'; $lang->install->value = 'Value'; $lang->install->saveConfig = 'Save config'; $lang->install->save2File = '<div class="a-center"><span class="fail">Try to save the config auto, but failed.</span></div>Copy the text of the textareaand save to "<strong> %s </strong>".'; $lang->install->saved2File = 'The config file has saved to "<strong>%s</strong> ".'; $lang->install->errorNotSaveConfig = "Hasn't save the config file. "; $lang->install->getPriv = 'Set admin'; $lang->install->company = 'Company name'; $lang->install->pms = 'ZenTaoPMS domain'; $lang->install->pmsNote = 'The domain name or ip address of ZenTaoPMS, no http://'; $lang->install->account = 'Administrator'; $lang->install->password = 'Admin password'; $lang->install->errorEmptyPassword = "Can't be empty"; $lang->install->success = "Success installed"; $lang->install->joinZentao = <<<EOT You have installed ZentaoPMS %s successfully. <strong class='red'>Please remove install.php in time</strong>。Now you can <a href='index.php'>login ZenTaoPMS</a>, create groups and grant priviledges. <i>Tips: For you get zentao news in time, please register Zetao community(<a href='http://www.zentao.net' target='_blank'>www.zentao.net</a>).</i> EOT;
isleon/zentao
module/install/lang/en.php
PHP
gpl-3.0
5,838
// Pingus - A free Lemmings clone // Copyright (C) 1999 Ingo Ruhnke <grumbel@gmx.de> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef HEADER_PINGUS_PINGUS_WORLDOBJS_WOODTHING_HPP #define HEADER_PINGUS_PINGUS_WORLDOBJS_WOODTHING_HPP #include "pingus/worldobjs/entrance.hpp" namespace WorldObjs { // FIXME: Re-enable this namespace. //namespace Entrances { class WoodThing : public Entrance { private: Sprite surface2; public: WoodThing(const FileReader& reader); void update(); void draw (SceneContext& gc); private: WoodThing (const WoodThing&); WoodThing& operator= (const WoodThing&); }; //} // namespace Entrances } // namespace WorldObjs #endif /* EOF */
plouj/pingus
src/pingus/worldobjs/woodthing.hpp
C++
gpl-3.0
1,307
using CP77.CR2W.Reflection; namespace CP77.CR2W.Types { [REDMeta] public class gamedataArchetypeType_Record : gamedataTweakDBRecord { public gamedataArchetypeType_Record(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/gamedataArchetypeType_Record.cs
C#
gpl-3.0
258
/* * Copyright 2012-2015 the original author or authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.tengu.chat.ui.widget; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.google.zxing.ResultPoint; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Matrix.ScaleToFit; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; import de.tengu.chat.R; /** * @author Andreas Schildbach */ public class ScannerView extends View { private static final long LASER_ANIMATION_DELAY_MS = 100l; private static final int DOT_OPACITY = 0xa0; private static final int DOT_TTL_MS = 500; private final Paint maskPaint; private final Paint laserPaint; private final Paint dotPaint; private boolean isResult; private final int maskColor, maskResultColor; private final int laserColor; private final int dotColor, dotResultColor; private final Map<float[], Long> dots = new HashMap<float[], Long>(16); private Rect frame; private final Matrix matrix = new Matrix(); public ScannerView(final Context context, final AttributeSet attrs) { super(context, attrs); final Resources res = getResources(); maskColor = res.getColor(R.color.black54); maskResultColor = res.getColor(R.color.black87); laserColor = res.getColor(R.color.red500); dotColor = res.getColor(R.color.orange500); dotResultColor = res.getColor(R.color.scan_result_dots); maskPaint = new Paint(); maskPaint.setStyle(Style.FILL); laserPaint = new Paint(); laserPaint.setStrokeWidth(res.getDimensionPixelSize(R.dimen.scan_laser_width)); laserPaint.setStyle(Style.STROKE); dotPaint = new Paint(); dotPaint.setAlpha(DOT_OPACITY); dotPaint.setStyle(Style.STROKE); dotPaint.setStrokeWidth(res.getDimension(R.dimen.scan_dot_size)); dotPaint.setAntiAlias(true); } public void setFraming(final Rect frame, final RectF framePreview, final int displayRotation, final int cameraRotation, final boolean cameraFlip) { this.frame = frame; matrix.setRectToRect(framePreview, new RectF(frame), ScaleToFit.FILL); matrix.postRotate(-displayRotation, frame.exactCenterX(), frame.exactCenterY()); matrix.postScale(cameraFlip ? -1 : 1, 1, frame.exactCenterX(), frame.exactCenterY()); matrix.postRotate(cameraRotation, frame.exactCenterX(), frame.exactCenterY()); invalidate(); } public void setIsResult(final boolean isResult) { this.isResult = isResult; invalidate(); } public void addDot(final ResultPoint dot) { dots.put(new float[] { dot.getX(), dot.getY() }, System.currentTimeMillis()); invalidate(); } @Override public void onDraw(final Canvas canvas) { if (frame == null) return; final long now = System.currentTimeMillis(); final int width = canvas.getWidth(); final int height = canvas.getHeight(); final float[] point = new float[2]; // draw mask darkened maskPaint.setColor(isResult ? maskResultColor : maskColor); canvas.drawRect(0, 0, width, frame.top, maskPaint); canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, maskPaint); canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, maskPaint); canvas.drawRect(0, frame.bottom + 1, width, height, maskPaint); if (isResult) { laserPaint.setColor(dotResultColor); laserPaint.setAlpha(160); dotPaint.setColor(dotResultColor); } else { laserPaint.setColor(laserColor); final boolean laserPhase = (now / 600) % 2 == 0; laserPaint.setAlpha(laserPhase ? 160 : 255); dotPaint.setColor(dotColor); // schedule redraw postInvalidateDelayed(LASER_ANIMATION_DELAY_MS); } canvas.drawRect(frame, laserPaint); // draw points for (final Iterator<Map.Entry<float[], Long>> i = dots.entrySet().iterator(); i.hasNext();) { final Map.Entry<float[], Long> entry = i.next(); final long age = now - entry.getValue(); if (age < DOT_TTL_MS) { dotPaint.setAlpha((int) ((DOT_TTL_MS - age) * 256 / DOT_TTL_MS)); matrix.mapPoints(point, entry.getKey()); canvas.drawPoint(point[0], point[1], dotPaint); } else { i.remove(); } } } }
syntafin/TenguChat
src/main/java/de/tengu/chat/ui/widget/ScannerView.java
Java
gpl-3.0
5,449
import base64 from django.contrib.auth import authenticate import logging def basic_http_authentication(request): if not 'HTTP_AUTHORIZATION' in request.META: return None auth = request.META['HTTP_AUTHORIZATION'].split() user = None if len(auth) == 2: if auth[0].lower() == "basic": uname, passwd = base64.b64decode(auth[1]).split(':') user = authenticate(username=uname, password=passwd) return user
efornal/shoal
app/http_auth.py
Python
gpl-3.0
468
package com.baeldung.webjar; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = WebjarsdemoApplication.class) @WebAppConfiguration public class WebjarsdemoApplicationIntegrationTest { @Test public void contextLoads() { } }
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-boot-ops/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java
Java
gpl-3.0
508
/* * Copyright (c) 2021, Aleksei Belkin <mailbelkin@gmail.com>. * All rights reserved. */ #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QQuickStyle> #include "appcore.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); AppCore appCore(&app); app.setOrganizationName("My Organization"); app.setOrganizationDomain("My Domain"); QQuickStyle::setStyle("Material"); QQmlApplicationEngine engine; QQmlContext *context = engine.rootContext(); context->setContextProperty("appCore", &appCore); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
be1ay/MyHash_Stribog
main.cpp
C++
gpl-3.0
763
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * GoTo.java * Copyright (C) 2018 University of Waikato, Hamilton, NZ */ package adams.gui.flow.tree.menu; import adams.core.option.AbstractArgumentOption; import adams.core.option.AbstractOption; import adams.core.option.BooleanOption; import adams.core.option.ClassOption; import adams.core.option.OptionTraversalPath; import adams.core.option.OptionTraverser; import adams.flow.core.AbstractActorReference; import adams.flow.core.Actor; import adams.flow.core.CallableActorUser; import adams.gui.action.AbstractPropertiesAction; import adams.gui.core.GUIHelper; import adams.gui.flow.tree.Node; import adams.gui.goe.FlowHelper; import nz.ac.waikato.cms.locator.ClassLocator; import javax.swing.JMenu; import javax.swing.JMenuItem; import java.awt.event.ActionEvent; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; /** * Jumps to the callable actor reference by this actor. * * @author fracpete */ public class GoTo extends AbstractTreePopupSubMenuAction { /** for serialization. */ private static final long serialVersionUID = 3991575839421394939L; /** * Returns the caption of this action. * * @return the caption, null if not applicable */ @Override protected String getTitle() { return "Go to"; } /** * Returns all the actor references for this actor. * * @param actor the actor to inspect * @return the references */ protected AbstractActorReference[] getReferences(Actor actor) { List<AbstractActorReference> result; result = new ArrayList<>(); actor.getOptionManager().traverse(new OptionTraverser() { @Override public void handleBooleanOption(BooleanOption option, OptionTraversalPath path) { } @Override public void handleClassOption(ClassOption option, OptionTraversalPath path) { } @Override public void handleArgumentOption(AbstractArgumentOption option, OptionTraversalPath path) { if (ClassLocator.matches(AbstractActorReference.class, option.getBaseClass())) { Object current = option.getCurrentValue(); if (option.isMultiple()) { for (int i = 0; i < Array.getLength(current); i++) result.add((AbstractActorReference) Array.get(current, i)); } else { result.add((AbstractActorReference) current); } } } @Override public boolean canHandle(AbstractOption option) { return (option instanceof AbstractArgumentOption); } @Override public boolean canRecurse(Class cls) { return true; } @Override public boolean canRecurse(Object obj) { return true; } }); return result.toArray(new AbstractActorReference[result.size()]); } /** * Creates a new menu. */ @Override public JMenu createMenu() { JMenu result; JMenuItem item; Actor actor; AbstractActorReference[] refs; List<Node> nodes; String[] paths; int i; int n; if (m_State.selNode == null) return null; result = new JMenu(getName()); if (getIcon() != null) result.setIcon(getIcon()); else result.setIcon(GUIHelper.getEmptyIcon()); actor = m_State.selNode.getActor(); refs = getReferences(actor); paths = new String[refs.length]; if (refs.length > 0) { nodes = FlowHelper.findCallableActorsHandler(m_State.selNode); for (i = 0; i < refs.length; i++) { for (n = 0; n < nodes.size(); n++) { int index = nodes.get(i).indexOf(refs[i].getValue()); if (index > -1) { paths[i] = ((Node) nodes.get(i).getChildAt(index)).getFullName(); break; } } } } for (i = 0; i < refs.length; i++) { if (paths[i] == null) continue; final String path = paths[i]; item = new JMenuItem(refs[i].getValue()); item.addActionListener((ActionEvent e) -> m_State.tree.locateAndDisplay(path, true)); result.add(item); } result.setEnabled(result.getItemCount() > 0); return result; } /** * Ignored. * * @return always null */ @Override protected AbstractPropertiesAction[] getSubMenuActions() { return null; } /** * Updates the action using the current state information. */ @Override protected void doUpdate() { boolean enabled; Actor actor; enabled = false; if (m_State.isSingleSel) { actor = m_State.selNode.getActor(); enabled = actor instanceof CallableActorUser; } setEnabled(enabled); } }
waikato-datamining/adams-base
adams-core/src/main/java/adams/gui/flow/tree/menu/GoTo.java
Java
gpl-3.0
5,207
using UnityEngine; using System.Collections; /// <summary> /// This class is use to disable the attached star animation. /// In fact, it don't disable the animator but makes impossible /// all other transitions by setting a bool parameter. /// </summary> public class DisableAnimator : MonoBehaviour { /// <summary> /// This methods is called by a animation event and tells to the animator /// that the object is destroying (no other animation can start). /// </summary> public void Destroying(){ this.GetComponent<Animator> ().SetBool ("destroying", true); } }
nicolaswenk/cf_heritage
Assets/Scripts/View/Utils/DisableAnimator.cs
C#
gpl-3.0
575
import sys if sys.version_info > (3,): from builtins import chr import unittest import os import re from adsft import extraction, rules, utils from adsft.tests import test_base from adsputils import load_config import unittest import httpretty from requests.exceptions import HTTPError class TestXMLExtractorBase(test_base.TestUnit): """ Base class for XML Extractor unit tests """ def setUp(self): super(TestXMLExtractorBase, self).setUp() self.preferred_parser_names = load_config().get('PREFERRED_XML_PARSER_NAMES') # Iterate through all the parsers defined in config.py #self.preferred_parser_names = (None,) # Iterate through the parsers (as defined in config.py) until one succeeds class TestXMLExtractor(TestXMLExtractorBase): """ Checks the basic functionality of the XML extractor. The content that is to be extracted is defined within a dictionary inside settings.py. If this is modified, these tests should first be changed to reflect the needed updates. """ def setUp(self): """ Generic setup of the test class. Makes a dictionary item that the worker would expect to receive from the RabbitMQ instance. Loads the relevant worker as well into a class attribute so it is easier to access. :return: """ super(TestXMLExtractor, self).setUp() self.dict_item = {'ft_source': self.test_stub_xml, 'file_format': 'xml', 'provider': 'MNRAS'} self.extractor = extraction.EXTRACTOR_FACTORY['xml'](self.dict_item) def test_that_we_can_open_an_xml_file(self): """ Tests the open_xml method. Checks that it opens and reads the XML file correctly by comparing with the expected content of the file. :return: no return """ full_text_content = self.extractor.open_xml() self.assertIn( '<journal-title>JOURNAL TITLE</journal-title>', full_text_content ) def test_that_we_can_parse_the_xml_content(self): """ Tests the parse_xml method. Checks that the parsed content allows access to the XML marked-up content, and that the content extracted matches what is expected. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) journal_title = self.extractor.extract_string('//journal-title') self.assertEqual(journal_title, 'JOURNAL TITLE') def test_that_we_correctly_remove_inline_fomulas_from_the_xml_content(self): """ Tests the parse_xml method. Checks that the parsed content allows access to the XML marked-up content, and that the content extracted matches what is expected. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//sec[@id="s1"]//p') self.assertEqual(section, 'INTRODUCTION GOES HERE') def test_iso_8859_1_xml(self): """ Test that we properly read iso 8859 formatted file. Since we are not reading the default file we must recreate the extractor object. :return: no return """ self.dict_item['ft_source'] = self.test_stub_iso8859 self.extractor = extraction.EXTRACTOR_FACTORY['xml'](self.dict_item) full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) article_number = self.extractor.extract_string('//article-number') self.assertEqual(article_number, '483879') def test_multi_file(self): """ some entries in fulltext/all.links specify multiple files typically the first has text from the article while the rest have the text from tables :return: no return """ self.dict_item = {'ft_source': self.test_multi_file, 'file_format': 'xml', 'provider': 'MNRAS', 'bibcode': 'test'} content = extraction.extract_content([self.dict_item]) # does the fulltext contain two copies of the file's contents self.assertEqual(2, content[0]['fulltext'].count('Entry 1')) def test_that_we_can_extract_using_settings_template(self): """ Tests the extract_multi_content method. This checks that all the meta data extracted is what we expect. The expected meta data to be extracted is defined in settings.py by the user. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: content = self.extractor.extract_multi_content(preferred_parser_names=(parser_name,)) self.assertEqual(list(rules.META_CONTENT['xml'].keys()).sort(), list(content.keys()).sort()) def test_that_we_can_extract_all_content_from_payload_input(self): """ Tests the extract_content method. This checks that all of the XML meta data defined in settings.py is extracted from the stub XML data. :return: no return """ file_path = u'{0}/{1}'.format(self.app.conf['FULLTEXT_EXTRACT_PATH'], self.test_stub_xml) pay_load = [self.dict_item] content = extraction.extract_content(pay_load) self.assertTrue( set(rules.META_CONTENT['xml'].keys()).issubset(content[0].keys()) ) def test_that_the_correct_extraction_is_used_for_the_datatype(self): """ Ensure that the defined data type in the settings.py dictionary loads the correct method for extraction :return: no return """ extract_string = self.extractor.data_factory['string'] extract_list = self.extractor.data_factory['list'] if sys.version_info > (3,): es_name = extract_string.__name__ el_name = extract_list.__name__ else: es_name = extract_string.func_name el_name = extract_list.func_name self.assertTrue( es_name == 'extract_string', ) self.assertTrue( el_name == 'extract_list', ) def test_that_we_can_extract_a_list_of_datasets(self): """ Within an XML document there may exist more than one dataset. To ensure that they are all extracted, we should check that this works otherwise there will be missing content :return: no return """ self.dict_item['bibcode'] = 'test' full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: content = self.extractor.extract_multi_content(preferred_parser_names=(parser_name,)) full_text = content['fulltext'] acknowledgements = content['acknowledgements'] data_set = content['dataset'] data_set_length = len(data_set) if sys.version_info > (3,): test_type = str else: test_type = unicode self.assertIs(test_type, type(acknowledgements)) self.assertIs(test_type, type(full_text)) expected_full_text = 'INTRODUCTION' self.assertTrue( expected_full_text in full_text, u'Full text is wrong: {0} [expected: {1}, data: {2}]' .format(full_text, expected_full_text, full_text) ) self.assertIs(list, type(data_set)) expected_dataset = 2 self.assertTrue( data_set_length == expected_dataset, u'Number of datasets is wrong: {0} [expected: {1}, data: {2}]' .format(data_set_length, expected_dataset, data_set) ) def test_that_we_can_parse_html_entity_correctly(self): """ Tests the parse_xml method. Checks that the HTML entities are parsed without errors caused by escaped ambersands. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//sec[@id="s2"]//p') self.assertEqual(section, u'THIS SECTION TESTS HTML ENTITIES LIKE \xc5 >.') def test_that_the_tail_is_preserved(self): """ Tests that when a tag is removed any trailing text is preserved by appending it to the previous or parent element. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//sec[@id="s3"]//p') self.assertEqual(section, u'THIS SECTION TESTS THAT THE TAIL IS PRESERVED .') def test_that_comments_are_ignored(self): """ Tests that parsing the xml file ignores any comments like <!-- example comment -->. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//sec[@id="s4"]//p') self.assertEqual(section, u'THIS SECTION TESTS THAT COMMENTS ARE REMOVED.') def test_that_cdata_is_removed(self): """ Tests that parsing the xml file either removes CDATA tags like in the case of <?CDATA some data?> where it is in the form of a "processing instruction" or ignores the cdata content when in this <![CDATA] some data]]> form, which BeautifulSoup calls a "declaration". :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//sec[@id="s5"]//p') self.assertEqual(section, u'THIS SECTION TESTS THAT CDATA IS REMOVED.') def test_that_table_is_extracted_correctly(self): """ Tests that the labels/comments for tables are kept while the content of the table is removed. Table footers are being removed in some cases where a graphic tag with no closing tag like <graphic xlink:href="example.gif"> is reconciled with a closing tag that encompasses additonal content like the table footer. Since graphics are one of the tags we remove to avoid garbage text in our output, it correctly gets removed but takes content that should remain in the fulltext output with it (like the table footer). :return: no return """ full_text_content = self.extractor.open_xml() s = u"TABLE I. TEXT a NOTES a TEXT" for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//table-wrap') self.assertEqual(section, s) def test_body_tag(self): """ This tests that the parsers correctly extract the body tag. This is important for parsers lxml-xml and direct-lxml-xml which remove the body tag if they are not in the format: <html> <head></head> <body></body> </html> Also important for parsers lxml-xml and direct-lxml-xml, which are affected by namespaces in tags of the form namespace:name (e.g. ja:body). """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body') self.assertEqual(section, u"I. INTRODUCTION INTRODUCTION GOES HERE " u"II. SECTION II THIS SECTION TESTS HTML ENTITIES LIKE \xc5 >. " u"III. SECTION III THIS SECTION TESTS THAT THE TAIL IS PRESERVED . " u"IV. SECTION IV THIS SECTION TESTS THAT COMMENTS ARE REMOVED. " u"V. SECTION V THIS SECTION TESTS THAT CDATA IS REMOVED. " u"Manual Entry 1 Manual Entry 2 TABLE I. TEXT a NOTES a TEXT" ) def test_extraction_of_acknowledgments(self): """ This tests that acknowledgments are extracted, acknowledgments should include the facilities as of issue #100 in github. There are cases in which the acknowledgments are found inside the body tag, but the body tag should not include the acknowledgments as of issue #18. An acknowledgement field is included in the body tag in test.xml to test that these are being moved outside of the body tag, which is why we see 'ACK INSIDE BODY TAG.' appended to this acknowledgment. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: content = self.extractor.extract_multi_content(preferred_parser_names=(parser_name,)) self.assertEqual(content['acknowledgements'], u"Acknowledgments WE ACKNOWLEDGE. Facilities: FacilityName1 , " "FacilityName2 , FacilityName3 , FacilityName4 , FacilityName5 , " "FacilityName6 , FacilityName7\nACK INSIDE BODY TAG.") def test_extraction_of_facilities(self): """ This tests that we can extract the faciltites field.The first facility is a test to make sure we are not extracting facilities where the xlink:href is missing, and the second facilities where xlink:href is empty. This is discussed here: https://github.com/adsabs/ADSfulltext/issues/107 :return: no return """ facilities = [u'FacilityID3', u'FacilityID4', u'FacilityID5', u'FacilityID6', u'FacilityID7'] full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: content = self.extractor.extract_multi_content(preferred_parser_names=(parser_name,)) self.assertEqual(sorted(content['facility']), facilities) def test_removal_of_comment_syntax_around_body(self): """ This tests the removal of comment syntax indicating the body of the article used by some publishers (AGU, sometimes Wiley). See https://github.com/adsabs/ADSfulltext/issues/104 :return: no return """ raw_xml = "<!-- body <body><p>body content</p></body> endbody -->" for parser_name in self.preferred_parser_names: self.assertEqual(self.extractor._remove_special_elements(raw_xml, parser_name), "<body><p>body content</p></body> ") class TestNonStandardXMLExtractor(TestXMLExtractorBase): """ Checks the basic functionality of the XML extractor. The content that is to be extracted is defined within a dictionary inside settings.py. If this is modified, these tests should first be changed to reflect the needed updates. """ def setUp(self): """ Generic setup of the test class. Makes a dictionary item that the worker would expect to receive from the RabbitMQ instance. Loads the relevant worker as well into a class attribute so it is easier to access. :return: """ super(TestNonStandardXMLExtractor, self).setUp() self.dict_item = {'ft_source': self.test_stub_nonstandard_xml, 'file_format': 'xml', 'provider': 'MNRAS'} self.extractor = extraction.EXTRACTOR_FACTORY['xml'](self.dict_item) def test_failure_of_all_parsers_in_loop(self): """ This ensures that articles that fail to get extracted by all of the parsers we loop through (defined in config) will return an empty body. See https://github.com/adsabs/ADSfulltext/issues/101 """ self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) content = self.extractor.extract_string('//body') self.assertEqual(content, u'') class TestTEIXMLExtractor(TestXMLExtractorBase): """ Checks the basic functionality of the TEI XML extractor (content generated by Grobid). """ def setUp(self): """ Generic setup of the test class. Makes a dictionary item that the worker would expect to receive from the RabbitMQ instance. Loads the relevant worker as well into a class attribute so it is easier to access. :return: """ super(TestTEIXMLExtractor, self).setUp() self.dict_item = {'ft_source': self.test_stub_teixml, 'file_format': 'teixml', 'provider': 'A&A', 'bibcode': 'TEST'} self.extractor = extraction.EXTRACTOR_FACTORY['teixml'](self.dict_item) def test_that_we_can_open_an_xml_file(self): """ Tests the open_xml method. Checks that it opens and reads the XML file correctly by comparing with the expected content of the file. :return: no return """ full_text_content = self.extractor.open_xml() self.assertIn( '<title level="a" type="main">ASTRONOMY AND ASTROPHYSICS The NASA Astrophysics Data System: Architecture</title>', full_text_content ) def test_that_we_can_parse_the_xml_content(self): """ Tests the parse_xml method. Checks that the parsed content allows access to the XML marked-up content, and that the content extracted matches what is expected. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) journal_title = self.extractor.extract_string('//title') self.assertEqual(journal_title, 'ASTRONOMY AND ASTROPHYSICS The NASA Astrophysics Data System: Architecture') def test_that_we_can_extract_using_settings_template(self): """ Tests the extract_multi_content method. This checks that all the meta data extracted is what we expect. The expected meta data to be extracted is defined in settings.py by the user. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: content = self.extractor.extract_multi_content(preferred_parser_names=(parser_name,)) self.assertEqual(rules.META_CONTENT['teixml'].keys(), content.keys()) def test_that_we_can_extract_all_content_from_payload_input(self): """ Tests the extract_content method. This checks that all of the XML meta data defined in settings.py is extracted from the stub XML data. :return: no return """ pay_load = [self.dict_item] content = extraction.extract_content(pay_load) self.assertTrue( set(rules.META_CONTENT['teixml'].keys()).issubset(content[0].keys()) ) def test_that_we_can_extract_acknowledgments(self): """ """ ack = u"Acknowledgements. The usefulness of a bibliographic service is only as good as the quality and quantity of the data it contains . The ADS project has been lucky in benefitting from the skills and dedication of several people who have significantly contributed to the creation and management of the underlying datasets. In particular, we would like to acknowledge the work of Elizabeth Bohlen, Donna Thompson, Markus Demleitner, and Joyce Watson. Funding for this project has been provided by NASA under grant NCC5-189." full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: content = self.extractor.extract_multi_content(preferred_parser_names=(parser_name,)) self.assertEqual(content['acknowledgements'], ack) class TestXMLElsevierExtractor(TestXMLExtractorBase): """ Checks the basic functionality of the Elsevier XML extractor. The content that is to be extracted is defined within a dictionary inside settings.py. This does inherit from the normal XML extractor, but has different requirements for extraction XPATHs due to the name spaces used within the XML. """ def setUp(self): """ Generic setup of the test class. Makes a dictionary item that the worker would expect to receive from the RabbitMQ instance. Loads the relevant worker as well into a class attribute so it is easier to access. :return: """ super(TestXMLElsevierExtractor, self).setUp() self.dict_item = {'ft_source': self.test_stub_exml, 'bibcode': 'TEST' } self.extractor = extraction.EXTRACTOR_FACTORY['elsevier'](self.dict_item) def test_that_we_can_open_an_xml_file(self): """ Tests the open_xml method. Checks that it opens and reads the XML file correctly by comparing with the expected content of the file. This is different to opening a normal XML file. :return: no return """ full_text_content = self.extractor.open_xml() self.assertIn('JOURNAL CONTENT', full_text_content) def test_that_we_can_parse_the_xml_content(self): """ Tests the parse_xml method. Checks that the parsed content allows access to the XML marked-up content, and that the content extracted matches what is expected. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) journal_title = self.extractor.extract_string('//*[local-name()=\'title\']') self.assertIn('JOURNAL TITLE', journal_title) def test_that_we_can_extract_using_settings_template(self): """ Tests the extract_multi_content method. This checks that all the meta data keywords extracted are the same as those expected. The expected meta data to be extracted is defined in settings.py by the user. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: content = self.extractor.extract_multi_content(preferred_parser_names=(parser_name,)) if sys.version_info > (3,): func = self.assertCountEqual else: func = self.assertItemsEqual func(['fulltext', 'acknowledgements', 'dataset'], content.keys(), content.keys()) self.assertIn('JOURNAL CONTENT', content['fulltext']) def test_that_the_correct_extraction_is_used_for_the_datatype(self): """ Ensure that the defined data type in the settings.py dictionary loads the correct method for extraction :return: no return """ extract_string = self.extractor.data_factory['string'] extract_list = self.extractor.data_factory['list'] if sys.version_info > (3,): es_name = extract_string.__name__ el_name = extract_list.__name__ else: es_name = extract_string.func_name el_name = extract_list.func_name self.assertTrue( es_name == 'extract_string', ) self.assertTrue( el_name == 'extract_list', ) def test_that_we_can_extract_a_list_of_datasets(self): """ Within an XML document there may exist more than one dataset. To ensure that they are all extracted, we should check that this works otherwise there will be missing content :return: no return """ self.dict_item['bibcode'] = 'test' full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: content = self.extractor.extract_multi_content(preferred_parser_names=(parser_name,)) full_text = content['fulltext'] acknowledgements = content['acknowledgements'] data_set = content['dataset'] data_set_length = len(data_set) if sys.version_info > (3,): test_type = str else: test_type = unicode self.assertIs(test_type, type(acknowledgements)) self.assertIs(test_type, type(full_text)) expected_full_text = 'CONTENT' self.assertTrue( expected_full_text in full_text, u'Full text is wrong: {0} [expected: {1}, data: {2}]' .format(full_text, expected_full_text, full_text) ) self.assertIs(list, type(data_set)) expected_dataset = 2 self.assertTrue( data_set_length == expected_dataset, u'Number of datasets is wrong: {0} [expected: {1}, data: {2}]' .format(data_set_length, expected_dataset, data_set) ) def test_that_we_can_parse_html_entity_correctly(self): """ Tests the parse_xml method. Checks that the HTML entities are parsed without errors caused by escaped ambersands. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//section[@id="s2"]//para') self.assertEqual(section, u'THIS SECTION TESTS HTML ENTITIES LIKE \xc5 >.') def test_that_the_tail_is_preserved(self): """ Tests that when a tag is removed any trailing text is preserved by appending it to the previous or parent element. This test currently only works with the lxml-xml parser when extracting Elsevier XML data. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//section[@id="s3"]//para') self.assertEqual(section, u'THIS SECTION TESTS THAT THE TAIL IS PRESERVED .') def test_that_comments_are_ignored(self): """ Tests that parsing the xml file ignores any comments like <!-- example comment -->. :return: no return """ full_text_content = self.extractor.open_xml() for parser_name in self.preferred_parser_names: self.extractor.parse_xml(preferred_parser_names=(parser_name,)) section = self.extractor.extract_string('//body//section[@id="s4"]//para') self.assertEqual(section, u'THIS SECTION TESTS THAT COMMENTS ARE REMOVED.') class TestHTMLExtractor(test_base.TestUnit): """ Tests class to ensure the methods for opening and extracting content from HTML files works correctly. """ def setUp(self): """ Generic setup of the test class. Makes a dictionary item that the worker would expect to receive from the RabbitMQ instance. Loads the relevant worker as well into a class attribute so it is easier to access. :return: no return """ super(TestHTMLExtractor, self).setUp() self.dict_item = { 'ft_source': u'{0},{1}'.format(self.test_stub_html, self.test_stub_html_table), 'bibcode': 'TEST' } self.extractor = extraction.EXTRACTOR_FACTORY['html'](self.dict_item) def test_that_we_can_open_an_html_file(self): """ Tests the open_html method. Checks the content loaded matches what is inside the file. :return: no return """ full_text_content = self.extractor.open_html() self.assertIn('TITLE', full_text_content) def test_can_parse_an_html_file(self): """ Tests the parse_html method. Checks that the HTML is parsed correctly, and that it allows relevant content to be extracted in the way we expect it to be. :return: no return """ raw_html = self.extractor.open_html() parsed_html = self.extractor.parse_html() header = parsed_html.xpath('//h2')[0].text self.assertIn('TITLE', header, self.app.conf['PROJ_HOME']) def test_that_we_can_extract_table_contents_correctly(self): """ Tests the collate_tables method. This checks that the tables linked inside the HTML file are found and aggregated into a dictionary, where each entry in the dictionary has the table name as the keyword and the table content as the value. This just ensures they exist and that they can be searched as expect. :return: no return """ raw_html = self.extractor.open_html() parsed_html = self.extractor.parse_html() table_content = self.extractor.collate_tables() for key in table_content.keys(): self.assertTrue(table_content[key].xpath('//table')) self.assertTrue(self.extractor.parsed_html.xpath('//h2')) def test_that_we_can_extract_using_settings_template(self): """ Tests the extract_mutli_content. This checks that the full text that was extracted from the HTML document includes the content of the HTML tables that are linked from within the parent HTML document. :return: no return """ content = self.extractor.extract_multi_content() self.assertEqual(list(content.keys()), ['fulltext']) self.assertIn( 'ONLY IN TABLE', content['fulltext'], u'Table is not in the fulltext: {0}'.format(content['fulltext']) ) class TestOCRandTXTExtractor(test_base.TestUnit): """ Class that test the methods of loading and extracting full text content from text and optical character recognition files. """ def setUp(self): """ Generic setup of the test class. Makes a dictionary item that the worker would expect to receive from the RabbitMQ instance. Loads the relevant worker as well into a class attribute so it is easier to access. :return: no return """ super(TestOCRandTXTExtractor, self).setUp() self.dict_item = {'ft_source': self.test_stub_text, 'bibcode': 'TEST'} self.dict_item_ocr = {'ft_source': self.test_stub_ocr, 'bibcode': 'TEST'} self.extractor = extraction.EXTRACTOR_FACTORY['txt'](self.dict_item) self.TC = utils.TextCleaner(text='') def test_open_txt_file(self): """ Tests the open_text method. Checks that the content loaded matches what is in the file. :return: no return """ raw_text = self.extractor.open_text() self.assertIn('Introduction', raw_text) def test_parse_txt_file(self): """ Tests the parse_text method. Checks that the text is parsed correctly, specifically, it should be decoded, translated, and normalised, so it should not contain certain escape characters. This checks it does not have strange escape characters. This is for a 'txt' file. :return: no return """ raw_text = self.extractor.open_text() parsed_text = self.extractor.parse_text(translate=True, decode=True) self.assertIn('Introduction', parsed_text) self.assertNotIn("\x00", parsed_text) def test_parse_ocr_file(self): """ Tests the parse_text method. Checks that the text is parsed correctly, specifically, it should be decoded, translated, and normalised, so it should not contain certain escape characters. This checks it does not have strange escape characters. This is for a 'ocr' file. :return: no return """ self.extractor.dict_item = self.dict_item_ocr raw_text = self.extractor.open_text() parsed_text = self.extractor.parse_text(translate=True, decode=True) self.assertIn('introduction', parsed_text.lower()) self.assertIn('THIS IS AN INTERESTING TITLE', parsed_text) self.assertNotIn("\x00", parsed_text) def test_ASCII_parsing(self): """ Tests the parse_text method. Checks that escape characters are removed as expected for ASCII characters. :return: no return """ self.extractor.raw_text \ = 'Tab\t CarriageReturn\r New line\n Random Escape characters:' \ + chr(1) + chr(4) + chr(8) expected_out_string = 'Tab CarriageReturn New line Random Escape characters:' new_instring = self.extractor.parse_text(translate=True, decode=True) self.assertEqual(new_instring, expected_out_string) def test_Unicode_parsing(self): """ Tests the parse_text method. Checks that escape characters are removed as expected for unicode characters. :return: no return """ self.extractor.raw_text = \ u'Tab\t CarriageReturn New line\n Random Escape characters:' \ + u'\u0000' expected_out_string = u'Tab CarriageReturn New line Random Escape characters:' new_instring = self.extractor.parse_text(translate=True, decode=True) self.assertEqual(new_instring, expected_out_string) def test_translation_map_works(self): """ Tests the translation map from the utils.py module. Ensures that escape characters are removed from the string. :return: no return """ # test replace with spaces instring = \ 'Tab\t CarriageReturn\r New line\n Random Escape characters:'\ + chr(0x0B) + chr(0xA0) + chr(0x1680) expected_out_string = \ 'Tab\t CarriageReturn New line\n Random Escape characters: ' new_instring = instring.translate(self.TC.master_translate_map) self.assertEqual(new_instring, expected_out_string) # test replace with None instring = \ 'Tab\t CarriageReturn\r New line\n Random Escape characters:' \ + chr(0x00) + chr(0xAD) + chr(0xE000) expected_out_string = \ 'Tab\t CarriageReturn New line\n Random Escape characters:' new_instring = instring.translate(self.TC.master_translate_map) self.assertEqual(new_instring, expected_out_string) # test both instring = \ 'Tab\t CarriageReturn\r New line\n Random Escape characters:' \ + chr(0x202F) + chr(0xFDD0) expected_out_string = \ 'Tab\t CarriageReturn New line\n Random Escape characters: ' new_instring = instring.translate(self.TC.master_translate_map) self.assertEqual(new_instring, expected_out_string) def test_extract_multi_content_on_text_data(self): """ Tests the extract_multi_content method. Checks that the full text extracted matches what we expect it should extract. :return: no return """ content = self.extractor.extract_multi_content() self.assertIn('introduction', content['fulltext'].lower()) class TestHTTPExtractor(test_base.TestUnit): """ Class that tests the methods used to extract full text content from HTTP sources behaves as expected. """ def setUp(self): """ Generic setup of the test class. Makes a dictionary item that the worker would expect to receive from the RabbitMQ instance. Loads the relevant worker as well into a class attribute so it is easier to access. :return: no return """ super(TestHTTPExtractor, self).setUp() self.dict_item = {'ft_source': 'http://fake/http/address', 'bibcode': 'TEST'} self.extractor = extraction.EXTRACTOR_FACTORY['http'](self.dict_item) self.body_content = 'Full text extract' def tearDown(self): """ Generic teardown of the test class. It closes down all the instances of HTTPretty that is used to mock HTTP responses. :return: no return """ # disable afterwards, so that you will have no problems in code that # uses that socket module httpretty.disable() # reset HTTPretty state (clean up registered urls and request history) httpretty.reset() @httpretty.activate def test_http_can_be_open(self): """ Tests the open_http method. Checks that the HTTP content is loaded correctly. :return: no return """ httpretty.register_uri(httpretty.GET, self.dict_item['ft_source'], body=self.body_content) response = self.extractor.open_http() self.assertEqual( response, self.body_content, u'Expected response: {0}\n but got: {1}' .format(self.body_content, response) ) @httpretty.activate def test_http_response_not_200(self): """ Tests the open_http method. Checks that an HTTPError is thrown if it receives a response from the server that is not equal to 200. :return: no return """ httpretty.register_uri(httpretty.GET, self.dict_item['ft_source'], body=self.body_content, status=304) self.assertRaises(HTTPError, self.extractor.open_http) @httpretty.activate def test_http_parses(self): """ Tests the parse_http method. Checks that the content received from the server is parsed as we expect it to be. The result is compared to the expected output. :return: no return """ httpretty.register_uri(httpretty.GET, self.dict_item['ft_source'], body=self.body_content, status=200) self.extractor.open_http() parsed_content = self.extractor.parse_http() self.assertEqual(parsed_content, self.body_content) @httpretty.activate def test_http_multi_content(self): """ Tests the extract_multi_content method. Checks that the full text content is extracted from the HTTP resource correctly, by comparin to what we expect the content to be. :return: no return """ httpretty.register_uri(httpretty.GET, self.dict_item['ft_source'], body=self.body_content, status=200) content = self.extractor.extract_multi_content() self.assertEqual(content['fulltext'], self.body_content) if __name__ == '__main__': unittest.main()
adsabs/ADSfulltext
adsft/tests/test_extraction.py
Python
gpl-3.0
40,776
''' Created on Sep 02, 2014 :author: svakulenko ''' # Bing API Version 2.0 # sample URL for web search # https://api.datamarket.azure.com/Bing/Search/Web?$format=json&Query=%27Xbox% # 27&$top=2 from eWRT.ws.rest import RESTClient from eWRT.ws import AbstractIterableWebSource class BingSearch(AbstractIterableWebSource): """wrapper for the Bing Search API""" NAME = "Bing Search" ROOT_URL = 'https://api.datamarket.azure.com/Bing/Search' DEFAULT_MAX_RESULTS = 50 # requires only 1 api access SUPPORTED_PARAMS = ['command', 'output_format'] DEFAULT_COMMAND = 'Web' # Image, News DEFAULT_FORMAT = 'json' DEFAULT_START_INDEX = 0 RESULT_PATH = lambda x: x['d']['results'] # path to the results in json MAPPING = {'date': ('valid_from', 'convert_date'), 'text': ('content', None), 'title': 'Title', } def __init__(self, api_key, username, api_url=ROOT_URL): """fixes the credentials and initiates the RESTClient""" assert(api_key) self.api_key = api_key self.api_url = api_url self.username = username self.client = RESTClient( self.api_url, password=self.api_key, user=self.username, authentification_method='basic') def search_documents(self, search_terms, max_results=DEFAULT_MAX_RESULTS, from_date=None, to_date=None, command=DEFAULT_COMMAND, output_format=DEFAULT_FORMAT): """calls iterator and results' post-processor""" # Web search is by default fetched = self.invoke_iterator(search_terms, max_results, from_date, to_date, command, output_format) result_path = lambda x: x['d']['results'] return self.process_output(fetched, result_path) def request(self, search_term, current_index, max_results=DEFAULT_MAX_RESULTS, from_date=None, to_date=None, command=DEFAULT_COMMAND, output_format=DEFAULT_FORMAT): """calls Bing Search API""" parameters = {'Query': search_term, '$format': output_format, '$top': max_results, '$skip': current_index} # for testing purposes # print(current_index, max_results, search_term) response = self.client.execute(command, query_parameters=parameters) return response @classmethod def convert_item(cls, item): """output convertor: applies a mapping to convert the result to the required format """ result = {'url': item['Url'], 'title': item['Title'], } return result
weblyzard/ewrt
src/eWRT/ws/bing/search.py
Python
gpl-3.0
2,765
<?php /** * Entrada [ http://www.entrada-project.org ] * * Entrada is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Entrada is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Entrada. If not, see <http://www.gnu.org/licenses/>. * * This file is loaded when someone opens the Feedback Agent. * * @author Organisation: Queen's University * @author Unit: School of Medicine * @author Developer: Matt Simpson <matt.simpson@queensu.ca> * @copyright Copyright 2010 Queen's University. All Rights Reserved. * */ @set_include_path(implode(PATH_SEPARATOR, array( dirname(__FILE__) . "/core", dirname(__FILE__) . "/core/includes", dirname(__FILE__) . "/core/library", dirname(__FILE__) . "/core/library/vendor", get_include_path(), ))); /** * Include the Entrada init code. */ require_once("init.inc.php"); ob_start("on_checkout"); if((!isset($_SESSION["isAuthorized"])) || (!$_SESSION["isAuthorized"])) { echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"DTD/xhtml1-transitional.dtd\">\n"; echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"; echo "<body>\n"; echo "<script type=\"text/javascript\">\n"; echo "alert('It appears as though your session has expired; you will now be taken back to the login page.');\n"; echo "if(window.opener) {\n"; echo " window.opener.location = '".ENTRADA_URL.((isset($_SERVER["REQUEST_URI"])) ? "?url=".rawurlencode(clean_input($_SERVER["REQUEST_URI"], array("nows", "url"))) : "")."';\n"; echo " top.window.close();\n"; echo "} else {\n"; echo " window.location = '".ENTRADA_URL.((isset($_SERVER["REQUEST_URI"])) ? "?url=".rawurlencode(clean_input($_SERVER["REQUEST_URI"], array("nows", "url"))) : "")."';\n"; echo "}\n"; echo "</script>\n"; echo "</body>\n"; echo "</html>\n"; exit; } else { $PAGE_META["title"] = "Clerkship Schedule Corrections"; if((isset($_GET["step"])) && ((int) trim($_GET["step"]))) { $STEP = (int) trim($_GET["step"]); } $ENCODED_INFORMATION = ""; if((isset($_GET["step"])) && ((int) trim($_GET["step"]))) { $STEP = (int) trim($_GET["step"]); } if(isset($_POST["enc"])) { $ENCODED_INFORMATION = trim($_POST["enc"]); } elseif(isset($_POST["action"])) { $ENCODED_INFORMATION = trim($_POST["enc"]); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=<?php echo DEFAULT_CHARSET; ?>" /> <title>%TITLE%</title> <meta name="description" content="%DESCRIPTION%" /> <meta name="keywords" content="%KEYWORDS%" /> <meta name="robots" content="noindex, nofollow" /> <meta name="MSSmartTagsPreventParsing" content="true" /> <meta http-equiv="imagetoolbar" content="no" /> <link href="<?php echo ENTRADA_URL; ?>/css/common.css?release=<?php echo html_encode(APPLICATION_VERSION); ?>" rel="stylesheet" type="text/css" media="all" /> <link href="<?php echo ENTRADA_URL; ?>/css/print.css?release=<?php echo html_encode(APPLICATION_VERSION); ?>" rel="stylesheet" type="text/css" media="print" /> <link href="<?php echo ENTRADA_URL; ?>/images/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <link href="<?php echo ENTRADA_URL; ?>/w3c/p3p.xml" rel="P3Pv1" type="text/xml" /> <link href="<?php echo ENTRADA_RELATIVE; ?>/css/common.css?release=<?php echo html_encode(APPLICATION_VERSION); ?>" rel="stylesheet" type="text/css" media="all" /> <link href="<?php echo ENTRADA_RELATIVE; ?>/css/print.css?release=<?php echo html_encode(APPLICATION_VERSION); ?>" rel="stylesheet" type="text/css" media="print" /> <link href="<?php echo $ENTRADA_TEMPLATE->relative(); ?>/css/common.css?release=<?php echo html_encode(APPLICATION_VERSION); ?>" rel="stylesheet" type="text/css" media="all" /> <link href="<?php echo ENTRADA_RELATIVE; ?>/css/jquery/jquery-ui.css" media="screen" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="<?php echo ENTRADA_RELATIVE; ?>/javascript/jquery/jquery.min.js"></script> <script type="text/javascript" src="<?php echo ENTRADA_RELATIVE; ?>/javascript/jquery/jquery-ui.min.js"></script> <script type="text/javascript">jQuery.noConflict();</script> %HEAD% <style type="text/css"> body { overflow: hidden; margin: 0px; padding: 0px; } </style> <script type="text/javascript" src="<?php echo ENTRADA_RELATIVE; ?>/javascript/jquery/jquery.min.js?release=<?php echo html_encode(APPLICATION_VERSION); ?>"></script> <script type="text/javascript"> function submitCorrection() { var formData = jQuery("#correction-form").serialize(); jQuery("#correction-form").remove(); jQuery("#form-submitting").show(); jQuery.ajax({ url: '<?php echo ENTRADA_URL; ?>/agent-clerkship.php?step=2&amp;enc=<?php echo $ENCODED_INFORMATION; ?>', type: 'POST', dataType: 'html', data: formData, async: true, success: function(data) { jQuery("#form-submitting").parent().append(data); jQuery("#form-submitting").hide(); } }); return false; } function newCorrection() { jQuery("#wizard-body, #wizard-footer").remove(); jQuery.ajax({ url: '<?php echo ENTRADA_URL; ?>/agent-clerkship.php?step=1&amp;enc=<?php echo $ENCODED_INFORMATION; ?>', type: 'POST', dataType: 'html', async: true, success: function(data) { jQuery("#form-submitting").parent().append(data); } }); return false; } function closeWindow() { window.close(); } </script> </head> <body> <?php switch($STEP) { case "2" : $message = "Attention Clerkship Schedule Maintainer,\n"; $message .= "The following schedule modification request has been submitted:\n"; $message .= "=======================================================\n\n"; $message .= "Submitted At:\t\t".date("r", time())."\n"; $message .= "Submitted By:\t\t".$_SESSION["details"]["firstname"]." ".$_SESSION["details"]["lastname"]." [".$_SESSION["details"]["username"]."]\n"; $message .= "E-Mail Address:\t\t".$_SESSION["details"]["email"]."\n\n"; $message .= "Schedule Update Request:\n"; $message .= "-------------------------------------------------------\n"; $message .= clean_input($_POST["correction"], array("trim", "emailcontent"))."\n\n"; $message .= "Web-Browser / OS:\n"; $message .= "-------------------------------------------------------\n"; $message .= clean_input($_SERVER["HTTP_USER_AGENT"], array("trim", "emailcontent"))."\n\n"; $message .= "======================================================="; $mail = new Zend_Mail("iso-8859-1"); $mail->addHeader("X-Priority", "3"); $mail->addHeader('Content-Transfer-Encoding', '8bit'); $mail->addHeader("X-Originating-IP", $_SERVER["REMOTE_ADDR"]); $mail->addHeader("X-Section", "Electives Approval"); $mail->addTo($AGENT_CONTACTS["agent-clerkship"]["email"], $AGENT_CONTACTS["agent-clerkship"]["name"]); $mail->setFrom(($_SESSION["details"]["email"]) ? $_SESSION["details"]["email"] : "noreply@post.queensu.ca", $_SESSION["details"]["firstname"]." ".$_SESSION["details"]["lastname"]); $mail->setSubject("Clerkship Schedule Correction - ".APPLICATION_NAME); $mail->setReplyTo(($_SESSION["details"]["email"]) ? $_SESSION["details"]["email"] : "", $_SESSION["details"]["firstname"]." ".$_SESSION["details"]["lastname"]); $mail->setBodyText($message); try{ $mail->send(); $SUCCESS++; $SUCCESSSTR[] = "Thank-you for contacting us. If we have questions regarding your schedule correction we will contact you and let you know."; } catch (Zend_Mail_Transport_Exception $e) { $ERROR++; $ERRORSTR[] = "We apologize however, we are unable to submit your clerkship schedule update request at this time.<br /><br />The MEdTech Unit has been informed of this, please try again later."; application_log("error", "Unable to send clerkship schedule update with the correction agent. Zend_mail said: ".$e->getMessage()); } ?> <div id="wizard-body" style="position: absolute; top: 35px; left: 0px; width: 452px; height: 440px; padding-left: 15px; overflow: auto"> <?php if($ERROR) { echo "<h2>Submission Failure</h2>\n"; echo display_error(); } elseif($SUCCESS) { echo "<h2>Submitted Successfully</h2>\n"; echo display_success(); } ?> To send a <strong>new correction</strong> or <strong>close this window</strong> please use the buttons below. </div> <div id="wizard-footer" style="position: absolute; top: 465px; left: 0px; width: 452px; height: 40px; border-top: 2px #CCCCCC solid; padding: 4px 4px 4px 10px"> <table style="width: 452px" cellspacing="0" cellpadding="0" border="0"> <tr> <td style="width: 180px; text-align: left"> <input type="button" class="btn" value="Close" onclick="closeWindow()" /> </td> <td style="width: 272px; text-align: right"> <input type="button" class="btn btn-primary" value="New Correction" onclick="newCorrection();" /> </td> </tr> </table> </div> <?php break; case "1" : default : ?> <form id="correction-form" action="<?php echo ENTRADA_URL; ?>/agent-clerkship.php?step=2" method="post" style="display: inline"> <div id="form-processing" style="display: block; position: absolute; top: 0px; left: 0px; width: 485px; height: 555px"> <div id="wizard-body" style="position: absolute; top: 35px; left: 0px; width: 452px; height: 440px; padding-left: 15px; overflow: auto"> <h2>Your Clerkship Schedule is Important</h2> <table style="width: 452px;" cellspacing="1" cellpadding="1" border="0"> <colgroup> <col style="width: 25%" /> <col style="width: 75%" /> </colgroup> <tbody> <tr> <td colspan="2"> <div class="display-notice"> <?php if($_SESSION["permissions"][$ENTRADA_USER->getAccessId()]["group"] == "student") : ?> <strong>Notice:</strong> Keeping the Undergrad office informed of clerkship schedule changes or inconsistencies is very important as this information is used to ensure you can graduate. If you see a problem with your schedule, please let us know immediately using this form. <?php else : ?> <strong>Notice:</strong> If you see an issue with the Clerkship schedule that needs our attention, please use this form to contact the Undergraduate office. Please be as specific as possible when sending in this request. <?php endif; ?> </div> </td> </tr> <tr> <td><span class="form-nrequired">Your Name:</span></td> <td><a href="mailto:<?php echo html_encode($_SESSION["details"]["email"]); ?>"><?php echo html_encode($_SESSION["details"]["firstname"]." ".$_SESSION["details"]["lastname"]); ?></a></td> </tr> <tr> <td><span class="form-nrequired">Your E-Mail:</span></td> <td><a href="mailto:<?php echo html_encode($_SESSION["details"]["email"]); ?>"><?php echo html_encode($_SESSION["details"]["email"]); ?></a></td> </tr> <tr> <td colspan="2" style="padding-top: 15px"> <label for="correction" class="form-required">Please describe in detail the problem with your clerkship schedule.</label> </td> </tr> <tr> <td colspan="2"> <textarea id="correction" name="correction" style="width: 98%; height: 115px"></textarea> </td> </tr> </tbody> </table> </div> <div id="wizard-footer" style="position: absolute; top: 465px; left: 0px; width: 452px; height: 40px; border-top: 2px #CCCCCC solid; padding: 4px 4px 4px 10px"> <table style="width: 100" cellspacing="0" cellpadding="0" border="0"> <tr> <td style="width: 180px; text-align: left"> <input type="button" class="btn" value="Close" onclick="closeWindow()" /> </td> <td style="width: 272px; text-align: right"> <input type="button" class="btn btn-primary" value="Submit" onclick="submitCorrection()" /> </td> </tr> </table> </div> </div> </form> <div id="form-submitting" style="display: none; position: absolute; top: 0px; left: 0px; background-color: #FFFFFF; opacity:.90; filter: alpha(opacity=90); -moz-opacity: 0.90"> <div style="display: table; width: 485px; height: 555px; _position: relative; overflow: hidden"> <div style="_position: absolute; _top: 50%; display: table-cell; vertical-align: middle;"> <div style="_position: relative; _top: -50%; width: 100%; text-align: center"> <span style="color: #003366; font-size: 18px; font-weight: bold"> <img src="<?php echo ENTRADA_URL; ?>/images/loading.gif" width="32" height="32" alt="Correction Sending" title="Please wait while your schedule correction is submitted" style="vertical-align: middle" /> Please Wait: correction is being sent </span> </div> </div> </div> </div> <?php break; } ?> </body> </html> <?php }
EntradaProject/entrada-1x
www-root/agent-clerkship.php
PHP
gpl-3.0
13,532
/* * File: FilteredHyperedgeCollection.hpp * * Author: ABSEHER Michael (abseher@dbai.tuwien.ac.at) * * Copyright 2015-2017, Michael Abseher * E-Mail: <abseher@dbai.tuwien.ac.at> * * This file is part of htd. * * htd is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your * option) any later version. * * htd is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * You should have received a copy of the GNU General Public License * along with htd. If not, see <http://www.gnu.org/licenses/>. */ #ifndef HTD_HTD_FILTEREDHYPEREDGECOLLECTION_HPP #define HTD_HTD_FILTEREDHYPEREDGECOLLECTION_HPP #include <htd/Globals.hpp> #include <htd/Hyperedge.hpp> #include <htd/ConstCollection.hpp> #include <htd/IHyperedgeCollection.hpp> #include <array> #include <memory> #include <vector> namespace htd { /** * Class for the efficient storage of hyperedge collections based on existing vectors of hyperedges. */ class FilteredHyperedgeCollection { public: /** * The value type of the collection. */ typedef htd::Hyperedge value_type; /** * Custom read-only iterator for hyperedge collections. */ class FilteredHyperedgeCollectionConstIterator { public: /** * The difference type between two iterators. */ typedef std::ptrdiff_t difference_type; /** * The value type of the iterator. */ typedef htd::Hyperedge value_type; /** * The reference type of the iterator. */ typedef const htd::Hyperedge & reference; /** * The pointer type of the iterator. */ typedef const htd::Hyperedge * pointer; /** * The const_reference type of the iterator. */ typedef const htd::Hyperedge & const_reference; /** * The const_pointer type of the iterator. */ typedef const htd::Hyperedge * const_pointer; /** * The category of the iterator. */ typedef std::random_access_iterator_tag iterator_category; /** * Constructor for an iterator. * * @param[in] collection The underlying collection. * @param[in] position The position of the new iterator within the collection. */ HTD_API FilteredHyperedgeCollectionConstIterator(const FilteredHyperedgeCollection & collection, htd::index_t position); /** * Copy constructor for a FilteredHyperedgeCollectionConstIterator object. * * @param[in] original The original FilteredHyperedgeCollectionConstIterator object. */ HTD_API FilteredHyperedgeCollectionConstIterator(const FilteredHyperedgeCollectionConstIterator & original); /** * Move constructor for a FilteredHyperedgeCollectionConstIterator object. * * @param[in] original The original FilteredHyperedgeCollectionConstIterator object. */ HTD_API FilteredHyperedgeCollectionConstIterator(FilteredHyperedgeCollectionConstIterator && original); /** * Destructor for a FilteredHyperedgeCollectionConstIterator object. */ HTD_API virtual ~FilteredHyperedgeCollectionConstIterator(); /** * Increment the iterator. * * @return A reference to the incremented iterator. */ HTD_API FilteredHyperedgeCollectionConstIterator & operator++(void); /** * Increment the iterator. * * @return A copy of the iterator reflecting the state before the increment operation took place. */ HTD_API FilteredHyperedgeCollectionConstIterator operator++(int); /** * Increment the iterator. * * @param[in] positions The number of positions the iterator shall be incremented. * * @return A reference to the incremented iterator. */ HTD_API FilteredHyperedgeCollectionConstIterator & operator+=(std::size_t positions); /** * Decrement the iterator. * * @return A reference to the decremented iterator. */ HTD_API FilteredHyperedgeCollectionConstIterator & operator--(void); /** * Decrement the iterator. * * @return A copy of the iterator reflecting the state before the decrement operation took place. */ HTD_API FilteredHyperedgeCollectionConstIterator operator--(int); /** * Decrement the iterator. * * @param[in] positions The number of positions the iterator shall be decremented. * * @return A reference to the decremented iterator. */ HTD_API FilteredHyperedgeCollectionConstIterator & operator-=(std::size_t positions); /** * Compute the distance between two iterators. * * The distance is given by the difference between the position of the iterator at the * right-hand side of the operator and the position of the iterator at the left-hand * side of the operator. * * @param[in] rhs The iterator at the right-hand side of the operator. * * @return The distance between two iterators. */ HTD_API long operator-(const FilteredHyperedgeCollectionConstIterator & rhs); /** * Copy assignment operator for an iterator. * * @param[in] original The original iterator. */ HTD_API FilteredHyperedgeCollectionConstIterator & operator=(const FilteredHyperedgeCollectionConstIterator & original); /** * Move assignment operator for an iterator. * * @param[in] original The original iterator. */ HTD_API FilteredHyperedgeCollectionConstIterator & operator=(FilteredHyperedgeCollectionConstIterator && original); /** * Equality operator for an iterator. * * @param[in] rhs The iterator at the right-hand side of the operator. * * @return True if the iterator points to the same element as the iterator at the right-hand side of the operator, false otherwise. */ HTD_API bool operator==(const FilteredHyperedgeCollectionConstIterator & rhs) const; /** * Inequality operator for an iterator. * * @param[in] rhs The iterator at the right-hand side of the operator. * * @return True if the iterator does not point to the same element as the iterator at the right-hand side of the operator, false otherwise. */ HTD_API bool operator!=(const FilteredHyperedgeCollectionConstIterator & rhs) const; /** * Dereference the iterator. * * @return A pointer to the element at the current iterator position. */ HTD_API const htd::Hyperedge * operator->(void) const; /** * Dereference the iterator. * * @return A reference to the element at the current iterator position. */ HTD_API const htd::Hyperedge & operator*(void) const; private: std::shared_ptr<htd::IHyperedgeCollection> baseCollection_; std::shared_ptr<std::vector<htd::index_t>> relevantIndices_; htd::index_t position_; }; /** * Constructor for a FilteredHyperedgeCollection object representing an empty collection. */ HTD_API FilteredHyperedgeCollection(void) HTD_NOEXCEPT; /** * Constructor for a FilteredHyperedgeCollection. * * @param[in] baseCollection A pointer to a wrapper of the underlying hyperedge collection. * @param[in] relevantIndices The relevant indices within the hyperedge collection. * * @note When calling this constructor the control over the pointer to the wrapper of the base collection * is taken over by the hyperedge collection. The pointer of the provided wrapper of the base collection * must not be freed outside the context of the hyperedge collection. */ HTD_API FilteredHyperedgeCollection(htd::IHyperedgeCollection * baseCollection, const std::vector<htd::index_t> & relevantIndices); /** * Constructor for a FilteredHyperedgeCollection. * * @param[in] baseCollection A pointer to a wrapper of the underlying hyperedge collection. * @param[in] relevantIndices The relevant indices within the hyperedge collection. * * @note When calling this constructor the control over the pointer to the wrapper of the base collection * is taken over by the hyperedge collection. The pointer of the provided wrapper of the base collection * must not be freed outside the context of the hyperedge collection. */ HTD_API FilteredHyperedgeCollection(htd::IHyperedgeCollection * baseCollection, std::vector<htd::index_t> && relevantIndices); /** * Constructor for a FilteredHyperedgeCollection. * * @param[in] baseCollection A pointer to a wrapper of the underlying hyperedge collection. * @param[in] relevantIndices The relevant indices within the hyperedge collection. * * @note When calling this constructor the control over the pointer to the wrapper of the base collection * is taken over by the hyperedge collection. The pointer of the provided wrapper of the base collection * must not be freed outside the context of the hyperedge collection. */ HTD_API FilteredHyperedgeCollection(std::shared_ptr<htd::IHyperedgeCollection> baseCollection, const std::vector<htd::index_t> & relevantIndices); /** * Constructor for a FilteredHyperedgeCollection. * * @param[in] baseCollection A pointer to a wrapper of the underlying hyperedge collection. * @param[in] relevantIndices The relevant indices within the hyperedge collection. * * @note When calling this constructor the control over the pointer to the wrapper of the base collection * is taken over by the hyperedge collection. The pointer of the provided wrapper of the base collection * must not be freed outside the context of the hyperedge collection. */ HTD_API FilteredHyperedgeCollection(std::shared_ptr<htd::IHyperedgeCollection> baseCollection, std::vector<htd::index_t> && relevantIndices); /** * Copy constructor for a FilteredHyperedgeCollection object. * * @param[in] original The original FilteredHyperedgeCollection object. */ HTD_API FilteredHyperedgeCollection(const FilteredHyperedgeCollection & original) HTD_NOEXCEPT; /** * Move constructor for a FilteredHyperedgeCollection object. * * @param[in] original The original FilteredHyperedgeCollection object. */ HTD_API FilteredHyperedgeCollection(FilteredHyperedgeCollection && original) HTD_NOEXCEPT; /** * Destructor for a FilteredHyperedgeCollection object. */ HTD_API virtual ~FilteredHyperedgeCollection(); /** * Getter for the size of the collection. * * @return The size of the collection. */ HTD_API std::size_t size(void) const HTD_NOEXCEPT; /** * Getter for the iterator to the first element in the collection. * * @return An iterator to the first element in the collection. */ HTD_API FilteredHyperedgeCollectionConstIterator begin(void) const HTD_NOEXCEPT; /** * Getter for the iterator to the end of the collection. * * @return An iterator to the end of the collection. */ HTD_API FilteredHyperedgeCollectionConstIterator end(void) const HTD_NOEXCEPT; /** * Copy assignment operator for a FilteredHyperedgeCollection object. * * @param[in] original The original FilteredHyperedgeCollection object. */ HTD_API FilteredHyperedgeCollection & operator=(const FilteredHyperedgeCollection & original) HTD_NOEXCEPT; /** * Move assignment operator for a FilteredHyperedgeCollection object. * * @param[in] original The original FilteredHyperedgeCollection object. */ HTD_API FilteredHyperedgeCollection & operator=(FilteredHyperedgeCollection && original) HTD_NOEXCEPT; /** * Equality operator for a hyperedge collection. * * @param[in] rhs The hyperedge collection at the right-hand side of the operator. * * @return True if the hyperedge collection is equal to the hyperedge collection at the right-hand side of the operator, false otherwise. */ HTD_API bool operator==(const FilteredHyperedgeCollection & rhs) const HTD_NOEXCEPT; /** * Inequality operator for a hyperedge collection. * * @param[in] rhs The hyperedge collection at the right-hand side of the operator. * * @return True if the hyperedge collection is not equal to the hyperedge collection at the right-hand side of the operator, false otherwise. */ HTD_API bool operator!=(const FilteredHyperedgeCollection & rhs) const HTD_NOEXCEPT; /** * Remove all hyperedges from the collection which contain also other vertices than those provided to this method. * * @note The copy will contain only those hyperedges whose endpoints are a subset of the relevant vertices. * * @param[in] vertices The vertices which act as a filter for the hyperedges in the collection. */ HTD_API void restrictTo(const std::vector<htd::vertex_t> & vertices); /** * Create a deep copy of the current hyperedge collection. * * @return A new FilteredHyperedgeCollection object identical to the current hyperedge collection. */ HTD_API FilteredHyperedgeCollection * clone(void) const; /** * Create a deep copy of the current hyperedge collection. * * @note The copy will contain only those hyperedges whose endpoints are a subset of the relevant vertices. * * @param[in] relevantVertices The set of relevant vertices, sorted in strictly ascending order. * * @return A new FilteredHyperedgeCollection object whose content is restricted to the relevant vertices. */ HTD_API FilteredHyperedgeCollection * clone(const std::vector<htd::vertex_t> & relevantVertices) const; /** * Swap the contents of a FilteredHyperedgeCollection object and another. * * @param[in] other The FilteredHyperedgeCollection object which shall be swapped with this object. */ HTD_API void swap(FilteredHyperedgeCollection & other); private: std::shared_ptr<htd::IHyperedgeCollection> baseCollection_; std::shared_ptr<std::vector<htd::index_t>> relevantIndices_; }; } #endif /* HTD_HTD_FILTEREDHYPEREDGECOLLECTION_HPP */
mabseher/htd
include/htd/FilteredHyperedgeCollection.hpp
C++
gpl-3.0
18,218
package cn.edu.jxnu.awesome_campus.ui.home; import android.app.Activity; import android.os.Bundle; import android.text.Html; import android.text.Spanned; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.tendcloud.tenddata.TCAgent; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import cn.edu.jxnu.awesome_campus.Config; import cn.edu.jxnu.awesome_campus.InitApp; import cn.edu.jxnu.awesome_campus.R; import cn.edu.jxnu.awesome_campus.event.EVENT; import cn.edu.jxnu.awesome_campus.event.EventModel; import cn.edu.jxnu.awesome_campus.model.home.CourseInfoModel; import cn.edu.jxnu.awesome_campus.support.theme.ThemeConfig; import cn.edu.jxnu.awesome_campus.support.utils.common.SPUtil; public class CourseDetailsDialog extends Activity { private static final String TAG="CourseDetailsDialog"; private TextView courseName; private TextView courseID; private TextView courseTeacher; private TextView courseClass; private TextView classmateLink; private TextView classForumLink; private ImageButton closeBtn; private CourseInfoModel model; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TCAgent.onPageStart(InitApp.AppContext, TAG); setTheme(ThemeConfig.themeDialogStyle[Config.themeSelected]); setContentView(R.layout.dialog_course_info); EventBus.getDefault().register(this); } private void initView(){ courseName = (TextView) findViewById(R.id.course_name); courseID = (TextView) findViewById(R.id.course_id); courseTeacher = (TextView) findViewById(R.id.course_teacher); courseClass = (TextView) findViewById(R.id.course_class); classmateLink = (TextView) findViewById(R.id.classmate_list_link); classForumLink = (TextView) findViewById(R.id.class_forum_link); closeBtn = (ImageButton)findViewById(R.id.btn_close); courseName.setText(model.getCourseName()); courseID.setText(model.getCourseID()); courseTeacher.setText(model.getCourseTeacher()); courseClass.setText(model.getCourseClass()); closeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // classmateLink.setText(buildHtmlLink("Classmates", Urlconfig.Education_Classmate_Base_URL+model.getClassmateListLink())); // classForumLink.setText(buildHtmlLink("Forum",Urlconfig.Education_CourseForum_Base_URL+model.getClassForumLink())); // classmateLink.setMovementMethod(LinkMovementMethod.getInstance()); // classForumLink.setMovementMethod(LinkMovementMethod.getInstance()); /* classmateLink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(Urlconfig.Education_Classmate_Base_URL+model.getClassmateListLink())); Bundle bundle = new Bundle(); SPUtil sp=new SPUtil(CourseDetailsDialog.this); bundle.putString("Cookie", "_ga=GA1.3.609810117.1451115712;ASP.NET_SessionId=" + sp.getStringSP(EducationStaticKey.SP_FILE_NAME, EducationStaticKey.BASE_COOKIE) + ";JwOAUserSettingNew="+sp.getStringSP(EducationStaticKey.SP_FILE_NAME, EducationStaticKey.SPECIAL_COOKIE)); i.putExtra(Browser.EXTRA_HEADERS, bundle); startActivity(i); } });*/ } private Spanned buildHtmlLink(String text, String link){ return Html.fromHtml("<a href='"+link+"'>"+text+"</a>"); } @Override protected void onDestroy() { EventBus.getDefault().unregister(this); TCAgent.onPageEnd(InitApp.AppContext, TAG); super.onDestroy(); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1) public void onEventMainThread(EventModel eventModel) { if(eventModel.getEventCode() == EVENT.SEND_MODEL_DETAIL){ model = (CourseInfoModel) eventModel.getData(); initView(); } } }
MummyDing/Awesome-Campus
app/src/main/java/cn/edu/jxnu/awesome_campus/ui/home/CourseDetailsDialog.java
Java
gpl-3.0
4,332
/* Copyright 2016, 2017, 2018, 2019 Alexander Kuperman This file is part of TestDataFramework. TestDataFramework is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TestDataFramework is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with TestDataFramework. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using TestDataFramework.Populator.Concrete; namespace IntegrationTests.CommonIntegrationTests { public static class Helpers { public static void Dump<T>(IEnumerable<RecordReference<T>> recordReference) { recordReference.ToList().ForEach(r => Helpers.Dump(r.RecordObject)); } public static void Dump(object target) { Console.WriteLine(); Console.WriteLine(target.GetType().Name); target.GetType().GetProperties().ToList().ForEach(p => { try { Console.WriteLine(p.Name + " = " + p.GetValue(target)); } catch (Exception ex) { Console.WriteLine(p.Name + ": " + Helpers.GetMessage(ex)); } }); Console.WriteLine(); } private static string GetMessage(Exception ex) { if (ex.InnerException != null) return Helpers.GetMessage(ex.InnerException); return ex.Message; } } }
SashaKuperman1973/TestDataFramework
IntegrationTests/CommonIntegrationTests/Helpers.cs
C#
gpl-3.0
1,956
/* * Tomdroid * Tomboy on Android * http://www.launchpad.net/tomdroid * * Copyright 2010 Olivier Bilodeau <olivier@bottomlesspit.org> * * This file is part of Tomdroid. * * Tomdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Tomdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Tomdroid. If not, see <http://www.gnu.org/licenses/>. */ // Portions of this file are covered under APL 2 and taken from // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/text/util/Linkify.java // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/text/util/Regex.java /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.privatenotes.util; import java.util.regex.Pattern; import android.text.util.Linkify.MatchFilter; /** * Statics useful for Linkify to create a better phone handler than android's default one * Fixes bugs like lp:512204 */ public class LinkifyPhone { /** * Don't treat anything with fewer than this many digits as a * phone number. */ private static final int PHONE_NUMBER_MINIMUM_DIGITS = 5; public static final Pattern PHONE_PATTERN = Pattern.compile( // sdd = space, dot, or dash "(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>* + "(\\([0-9]+\\)[\\- \\.]*)?" // (<digits>)<sdd>* + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit> /** * Filters out URL matches that: * - the character before the match is not a whitespace * - don't have enough digits to be a phone number */ public static final MatchFilter sPhoneNumberMatchFilter = new MatchFilter() { public final boolean acceptMatch(CharSequence s, int start, int end) { // make sure there was a whitespace before pattern try { if (!Character.isWhitespace(s.charAt(start - 1))) { return false; } } catch (IndexOutOfBoundsException e) { //Do nothing } // minimum length int digitCount = 0; for (int i = start; i < end; i++) { if (Character.isDigit(s.charAt(i))) { digitCount++; if (digitCount >= PHONE_NUMBER_MINIMUM_DIGITS) { return true; } } } return false; } }; }
rmayr/privatenotes-tomdroid
src/org/privatenotes/util/LinkifyPhone.java
Java
gpl-3.0
3,249
/******************************************************************************* * Copyright 2017, 2018 CNES - CENTRE NATIONAL d'ETUDES SPATIALES * * This file is part of MIZAR. * * MIZAR is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MIZAR is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MIZAR. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ import _ from "underscore"; import AbstractRasterLayer from "./AbstractRasterLayer"; import Utils from "../Utils/Utils"; import Constants from "../Utils/Constants"; import HEALPixTiling from "../Tiling/HEALPixTiling"; import CoordinateSystemFactory from "../Crs/CoordinateSystemFactory"; import HipsMetadata from "./HipsMetadata"; /** * AbstractHipsLayer configuration * @typedef {AbstractLayer.configuration} AbstractHipsLayer.configuration * @property {Crs} [coordinateSystem = CoordinateSystemFactory.create({geoideName: Constants.MappingCrsHips2Mizar[this.hipsMetadata.hips_frame]})] - Coordinate reference system * @property {int} [tilePixelSize = hipsMetadata['hips_tile_width'] - Tiles width in pixels * @property {int} [baseLevel = 2] - min HiPS order * @property {HEALPixTiling} [tiling = new HEALPixTiling(options.baseLevel, {coordinateSystem: options.coordinateSystem})] - Tiling * @property {int} [numberOfLevels = hipsMetadata['hips_order']] - Deepest order min * @property {string} [name = hipsMetadata['obs_title']] - Data set title * @property {string} [attribution = <a href=\"" + this.hipsMetadata['obs_copyright_url'] + "\" target=\"_blank\">" + this.hipsMetadata['obs_copyright'] + "</a>"] - URL to a copyright mention * @property {string} [ack = hipsMetadata['obs_ack']] - Acknowledgment mention * @property {string} [icon = ""] - icon used as metadata representation on the map * @property {string} [description = hipsMetadata['obs_description']] - Data set description * @property {boolean} [visible = false] visibility by default on the map * @property {Object} properties - other metadata * @property {float} [properties.initialRa = undefined] - Initial RA * @property {float} [properties.initialDec = undefined] - Initial DEC * @property {float} [properties.initialFov = undefined] - Initial field of view * @property {float} [properties.mocCoverage = undefined] - Sky fraction coverage * @property {boolean} [pickable = false] - Pickable layer * @property {Array} [availableServices = {}] - List of services related to the layer * @property {Array} [format = hipsMetadata['hips_tile_format']] - List of available tile formats * @property {string} [baseUrl = hipsMetadata['hips_service_url']] - Endpoint service * @property {string} [category = Image] - Default category * @property {boolean} background - Tell if the layer is set as background */ /** * @name AbstractHipsLayer * @class * Abstract class for HIPS * @augments AbstractRasterLayer * @param {HipsMetadata} hipsMetadata * @param {AbstractHipsLayer.configuration} options - AbstractHipsLayer configuration * @see {@link http://www.ivoa.net/documents/HiPS/20170406/index.html Hips standard} * @throws ReferenceError - Some required parameters are missing * @constructor */ var AbstractHipsLayer = function (hipsMetadata, options) { _checkAndSetDefaultOptions.call(this, options); this.hipsMetadata = _createMetadata.call(this, hipsMetadata, options.baseUrl); _overloadHipsMetataByConfiguration.call(this, options, this.hipsMetadata); options.tiling = new HEALPixTiling(options.baseLevel || 2, { coordinateSystem: options.coordinateSystem }); options.icon = options.hasOwnProperty("icon") ? options.icon : options.mizarBaseUrl ? options.mizarBaseUrl + "css/images/star.png" : ""; options.visible = options.hasOwnProperty("visible") ? options.visible : false; options.properties = options.hasOwnProperty("properties") ? options.properties : {}; options.pickable = options.hasOwnProperty("pickable") ? options.pickable : false; options.services = options.hasOwnProperty("services") ? options.services : {}; options.category = options.hasOwnProperty("category") ? options.category : "Image"; //this.hipsMetadata.client_category; if (this.hipsMetadata.hasOwnProperty("moc_access_url")) { options.services.Moc = { baseUrl: this.hipsMetadata.moc_access_url, skyFraction: this.hipsMetadata.moc_sky_fraction }; } //Hack : set Galactic layer as background because only background owns two grids (equetorial and galactic) if (options.coordinateSystem.getGeoideName() === Constants.CRS.Galactic) { options.background = true; } AbstractRasterLayer.prototype.constructor.call(this, Constants.LAYER.Hips, options); this.fitsSupported = _.contains(this.hipsMetadata.hips_tile_format, "fits"); }; /** * Check options. * @param options * @throws ReferenceError - Some required parameters are missing * @private */ function _checkAndSetDefaultOptions(options) { if (!options) { throw new ReferenceError("Some required parameters are missing", "AbstractHipsLayer.js"); } else { options.category = options.category || "Image"; options.pickable = options.pickable || false; } } /** * Creates metadata. * @param hipsMetadata * @param baseUrl * @returns {*} * @private */ function _createMetadata(hipsMetadata, baseUrl) { var metadata = hipsMetadata; if (typeof metadata === "undefined") { var hipsProperties = new HipsMetadata(baseUrl); metadata = hipsProperties.getHipsMetadata(); } return metadata; } /** * * @param options * @param hipsMetadata * @private */ function _overloadHipsMetataByConfiguration(options, hipsMetadata) { options.coordinateSystem = options.hasOwnProperty("coordinateSystem") ? CoordinateSystemFactory.create(options.coordinateSystem) : CoordinateSystemFactory.create({ geoideName: Constants.MappingCrsHips2Mizar[hipsMetadata.hips_frame] }); options.tilePixelSize = options.hasOwnProperty("tilePixelSize") ? options.tilePixelSize : hipsMetadata.hips_tile_width; options.baseLevel = options.hasOwnProperty("baseLevel") ? options.baseLevel : hipsMetadata.hasOwnProperty("hips_order_min") && hipsMetadata.hips_order_min >= 2 ? parseInt(hipsMetadata.hips_order_min) : 2; options.numberOfLevels = options.hasOwnProperty("numberOfLevels") ? options.numberOfLevels : parseInt(hipsMetadata.hips_order); options.name = options.hasOwnProperty("name") ? options.name : hipsMetadata.obs_title; options.attribution = options.hasOwnProperty("attribution") ? options.attribution : '<a href="' + hipsMetadata.obs_copyright_url + '" target="_blank">' + hipsMetadata.obs_copyright + "</a>"; options.copyrightUrl = options.hasOwnProperty("copyrightUrl") ? options.copyrightUrl : hipsMetadata.obs_copyright_url; options.ack = options.hasOwnProperty("ack") ? options.ack : hipsMetadata.obs_ack; options.description = options.hasOwnProperty("description") ? options.description : hipsMetadata.obs_description; options.format = options.hasOwnProperty("format") ? options.format : hipsMetadata.hips_tile_format; options.baseUrl = options.hasOwnProperty("baseUrl") ? options.baseUrl : hipsMetadata.hips_service_url; options.properties = options.hasOwnProperty("properties") ? options.properties : {}; if (hipsMetadata.hasOwnProperty("obs_initial_ra")) { options.properties.initialRa = parseFloat(hipsMetadata.obs_initial_ra); } if (hipsMetadata.hasOwnProperty("obs_initial_dec")) { options.properties.initialDec = parseFloat(hipsMetadata.obs_initial_dec); } if (hipsMetadata.hasOwnProperty("obs_initial_fov")) { options.properties.initialFov = Math.sqrt(((360 * 360) / Math.PI) * parseFloat(hipsMetadata.obs_initial_fov)); } if (hipsMetadata.hasOwnProperty("moc_sky_fraction")) { options.properties.moc_sky_fraction = parseFloat(hipsMetadata.moc_sky_fraction); } } /**************************************************************************************************************/ Utils.inherits(AbstractRasterLayer, AbstractHipsLayer); /**************************************************************************************************************/ /** * Returns the Metadata related to Hips protocol. * @return {Object} * @memberof AbstractHipsLayer# */ AbstractHipsLayer.prototype.getHipsMetadata = function () { return this.hipsMetadata; }; export default AbstractHipsLayer;
MizarWeb/Mizar
src/Layer/AbstractHipsLayer.js
JavaScript
gpl-3.0
8,933
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Automatak.DNP3.Interface { /// <summary> /// Configuration of maximum event counts per event type. /// /// The underlying implementation uses a *preallocated* heap buffer to store events /// until they are transmitted to the master. The size of this buffer is proportional /// to the TotalEvents() method, i.e. the sum of the maximum events for each type. /// Implementations should configure the buffers to store a reasonable number events /// given the polling frequency and memory restrictions of the target platform. /// /// </summary> public class EventBufferConfig { /// <summary> /// All events set to same count /// </summary> public EventBufferConfig(UInt16 count) { this.maxBinaryEvents = count; this.maxDoubleBinaryEvents = count; this.maxAnalogEvents = count; this.maxCounterEvents = count; this.maxFrozenCounterEvents = count; this.maxBinaryOutputStatusEvents = count; this.maxAnalogOutputStatusEvents = count; } /// <summary> /// All events set to 100 /// </summary> public EventBufferConfig() : this(100) { } /// <summary> /// The number of binary events the outstation will buffer before overflowing /// </summary> public System.UInt16 maxBinaryEvents; /// <summary> /// The number of double-bit binary events the outstation will buffer before overflowing /// </summary> public System.UInt16 maxDoubleBinaryEvents; /// <summary> /// The number of analog events the outstation will buffer before overflowing /// </summary> public System.UInt16 maxAnalogEvents; /// <summary> /// The number of counter events the outstation will buffer before overflowing /// </summary> public System.UInt16 maxCounterEvents; /// <summary> /// The number of frozen counter events the outstation will buffer before overflowing /// </summary> public System.UInt16 maxFrozenCounterEvents; /// <summary> /// The number of binary output status events the outstation will buffer before overflowing /// </summary> public System.UInt16 maxBinaryOutputStatusEvents; /// <summary> /// The number of analog output status events the outstation will buffer before overflowing /// </summary> public System.UInt16 maxAnalogOutputStatusEvents; } }
thiagoralves/OpenPLC_v2
dnp3/dotnet/bindings/CLRInterface/config/EventBufferConfig.cs
C#
gpl-3.0
2,739
/* * This file is part of libswitcher. * * libswitcher is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ #include "./information-tree.hpp" #include <algorithm> #include <regex> #include <iostream> namespace switcher { namespace data { Tree::ptr Tree::make() { std::shared_ptr<Tree> tree; //can't use make_shared because ctor is private tree.reset(new Tree()); tree->me_ = tree; return tree; } Tree::ptr Tree::make(const char *data) { return make (std::string(data)); } void Tree::preorder_tree_walk(Tree::ptrc tree, Tree::OnNodeFunction on_visiting_node, Tree::OnNodeFunction on_node_visited) { std::unique_lock<std::mutex> lock(tree->mutex_); if (!tree->childrens_.empty()) { for (auto &it : tree->childrens_) { on_visiting_node(it.first, it.second.get(), tree->is_array_); preorder_tree_walk(it.second.get(), on_visiting_node, on_node_visited); on_node_visited(it.first, it.second.get(), tree->is_array_); } } } Tree::Tree(const Any &data):data_(data) { } bool Tree::is_leaf() const { std::unique_lock<std::mutex> lock(mutex_); return childrens_.empty(); } bool Tree::is_array() const { std::unique_lock<std::mutex> lock(mutex_); return is_array_; } bool Tree::has_data() const { std::unique_lock<std::mutex> lock(mutex_); return !data_.is_null(); } Any Tree::get_data() const{ std::unique_lock<std::mutex> lock(mutex_); return data_; } const Any &Tree::read_data() const { std::unique_lock<std::mutex> lock(mutex_); return data_; } void Tree::set_data(const Any &data) { std::unique_lock<std::mutex> lock(mutex_); data_ = data; } void Tree::set_data(const char *data) { std::unique_lock<std::mutex> lock(mutex_); data_ = std::string(data); } void Tree::set_data(std::nullptr_t ptr) { std::unique_lock<std::mutex> lock(mutex_); data_ = ptr; } bool Tree::branch_is_leaf(const std::string &path) const { std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (!found.first.empty()) return found.second->second->childrens_.empty(); return false; } bool Tree::branch_has_data(const std::string &path) const { std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (!found.first.empty()) return found.second->second->data_.not_null(); return false; } Any Tree::get_data(const std::string &path) const { std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (!found.first.empty()) return found.second->second->data_; Any res; return res; } const Any &Tree::branch_read_data(const std::string &path) const { std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (!found.first.empty()) return found.second->second->data_; static Any any; return any; } bool Tree::set_data(const std::string &path, const Any &data) { std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (!found.first.empty()) { found.second->second->data_ = data; return true; } return false; } bool Tree::set_data(const std::string &path, const char *data) { return set_data(path, std::string(data)); } bool Tree::set_data(const std::string &path, std::nullptr_t ptr) { return set_data(path, Any(ptr)); } Tree::childs_t::iterator Tree::get_child_iterator(const std::string &key) const { return std::find_if(childrens_.begin(), childrens_.end(), [key] (const Tree::child_type &s) { return (0 == s.first.compare(key)); }); } Tree::ptr Tree::prune(const std::string &path) { std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (!found.first.empty()) { Tree::ptr res = found.second->second; found.first.erase(found.second); return res; } Tree::ptr res; return res; } Tree::ptr Tree::get(const std::string &path) { std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (!found.first.empty()) return found.second->second; // not found Tree::ptr res; return res; } Tree::GetNodeReturn Tree::get_node(const std::string &path) const { std::istringstream iss(path); Tree::childs_t child_list; Tree::childs_t::iterator child_iterator; if (get_next(iss, child_list, child_iterator)) { // asking root node child_list.push_back(std::make_pair("__ROOT__", me_.lock())); child_iterator = child_list.begin(); } return std::make_pair(child_list, child_iterator); } bool Tree::get_next(std::istringstream &path, Tree::childs_t &parent_list_result, Tree::childs_t::iterator &iterator_result) const { std::string child_key; if (!std::getline(path, child_key, '.')) return true; if (child_key.empty()) { return this->get_next(path, parent_list_result, iterator_result); } auto it = get_child_iterator(child_key); if (childrens_.end() != it) { if (it->second->get_next(path, parent_list_result, iterator_result)) { iterator_result = it; parent_list_result = childrens_; } return false; } return false; } bool Tree::graft(const std::string &where, Tree::ptr tree) { if (!tree) return false; std::unique_lock<std::mutex> lock(mutex_); std::istringstream iss(where); return !graft_next(iss, this, tree); } bool Tree::graft_next(std::istringstream &path, Tree *tree, Tree::ptr leaf) { std::string child; if (!std::getline(path, child, '.')) return true; if (child.empty()) // in case of two or more consecutive dots return graft_next(path, tree, leaf); auto it = tree->get_child_iterator(child); if (tree->childrens_.end() != it) { if (graft_next(path, it->second.get(), leaf)) // graft on already existing child it->second = leaf; // replacing the previously empy tree with the one to graft } else { Tree::ptr child_node = make(); tree->childrens_.emplace_back(child, child_node); if (graft_next(path, child_node.get(), leaf)) // graft on already existing child { // replacing empty tree for replacement by leaf tree->childrens_.pop_back(); tree->childrens_.emplace_back(child, leaf); } } return false; } bool Tree::tag_as_array(const std::string &path, bool is_array) { Tree::ptr tree = Tree::get(path); if (!(bool) tree) return false; tree->is_array_ = is_array; return true; } std::string Tree::escape_dots(const std::string &str) { // replacing dots in name by __DOT__ std::string escaped = std::string(); std::size_t i = 0; while (std::string::npos != i) { auto found = str.find('.', i); if (i != found) escaped += std::string(str, i, found - i); if (std::string::npos != found) { escaped += "__DOT__"; i = ++found; } else { i = std::string::npos; } } return escaped; } std::string Tree::unescape_dots(const std::string &str) { std::string unescaped = std::string(); std::string esc_char("__DOT__"); std::size_t i = 0; while(std::string::npos != i) { std::size_t found = str.find(esc_char, i); if (i != found) unescaped += std::string(str, i , found - i); if (std::string::npos != found) { unescaped += "."; i = found + esc_char.size(); } else { i = std::string::npos; } } return unescaped; } std::list<std::string> Tree::get_child_keys(const std::string &path) const { std::list<std::string> res; std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (!found.first.empty()) { res.resize(found.second->second->childrens_.size()); std::transform(found.second->second->childrens_.cbegin(), found.second->second->childrens_.cend(), res.begin(), [](const child_type &child) { return child.first; }); } return res; } std::list<std::string> Tree::copy_leaf_values(const std::string &path) const { std::list<std::string> res; Tree::ptr tree; { // finding the node std::unique_lock<std::mutex> lock(mutex_); auto found = get_node(path); if (found.first.empty()) return res; tree = found.second->second; } preorder_tree_walk (tree.get(), [&res](std::string /*key*/, Tree::ptrc node, bool /*is_array_element*/) { if (node->is_leaf()) res.push_back(Any::to_string(node->read_data())); }, [](std::string, Tree::ptrc, bool){}); return res; } Tree::ptrc Tree::get_subtree(Tree::ptrc tree, const std::string &path) { std::unique_lock<std::mutex> lock(tree->mutex_); auto found = tree->get_node(path); return found.second->second.get(); } } // namespace data } // namespace switcher
nicobou/ubuntu-switcher
switcher/information-tree.cpp
C++
gpl-3.0
9,645
<?php /** * WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan * * The PHP page that serves all page requests on WebExploitScan installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All WebExploitScan code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ $NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 720'; $TAGCLEAR='<?(php)?@?preg_replace($_(GET|POST|COOKIE|SERVER|REQUEST)[[^]]+], $_(GET|POST|COOKIE|SERVER|REQUEST)[[^]]+],[\'"][\'"]);?>'; $TAGBASE64='PD8ocGhwKT9AP3ByZWdfcmVwbGFjZSgkXyhHRVR8UE9TVHxDT09LSUV8U0VSVkVSfFJFUVVFU1QpW1teXV0rXSwgJF8oR0VUfFBPU1R8Q09PS0lFfFNFUlZFUnxSRVFVRVNUKVtbXl1dK10sW1wnIl1bXCciXSk7Pz4='; $TAGHEX='3c3f28706870293f403f707265675f7265706c61636528245f284745547c504f53547c434f4f4b49457c5345525645527c52455155455354295b5b5e5d5d2b5d2c20245f284745547c504f53547c434f4f4b49457c5345525645527c52455155455354295b5b5e5d5d2b5d2c5b5c27225d5b5c27225d293b3f3e'; $TAGHEXPHP=''; $TAGURI='%3C%3F%28php%29%3F%40%3Fpreg_replace%28%24_%28GET%7CPOST%7CCOOKIE%7CSERVER%7CREQUEST%29%5B%5B%5E%5D%5D%2B%5D%2C+%24_%28GET%7CPOST%7CCOOKIE%7CSERVER%7CREQUEST%29%5B%5B%5E%5D%5D%2B%5D%2C%5B%5C%27%22%5D%5B%5C%27%22%5D%29%3B%3F%3E'; $TAGCLEAR2=''; $TAGBASE642=''; $TAGHEX2=''; $TAGHEXPHP2=''; $TAGURI2=''; $DATEADD='10/09/2019'; $LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 720 '; $ACTIVED='1'; $VSTATR='malware_signature';
libre/webexploitscan
wes/data/rules/fullscan/10092019-MS-PHP-Antimalware-Scanner-720-malware_signature.php
PHP
gpl-3.0
1,514
package com.jaus.albertogiunta.justintrain_oraritreni.utils.sharedPreferences; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import android.content.Context; import com.jaus.albertogiunta.justintrain_oraritreni.data.PreferredJourney; import com.jaus.albertogiunta.justintrain_oraritreni.data.PreferredStation; import com.jaus.albertogiunta.justintrain_oraritreni.networking.DateTimeAdapter; import com.jaus.albertogiunta.justintrain_oraritreni.networking.PostProcessingEnabler; import com.jaus.albertogiunta.justintrain_oraritreni.utils.constants.ENUM_HOME_HEADER; import org.joda.time.DateTime; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.jaus.albertogiunta.justintrain_oraritreni.utils.constants.CONST_SP_V0.SEPARATOR; import static com.jaus.albertogiunta.justintrain_oraritreni.utils.sharedPreferences.SharedPreferencesHelper.getSharedPreferenceObject; public class StationsPreferences { public static boolean isJourneyAlreadySaved(Context context, ENUM_HOME_HEADER type, String id1, String id2) { return getSharedPreferenceObject(context, buildSavedJourneyId(type, id1, id2)) != null; } public static void setSavedJourney(Context context, ENUM_HOME_HEADER type, PreferredJourney journey) { Gson gson = new GsonBuilder() .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) .registerTypeAdapterFactory(new PostProcessingEnabler()) .create(); SharedPreferencesHelper.setSharedPreferenceObject(context, buildSavedJourneyId(type, journey.getStation1().getStationShortId(), journey.getStation2().getStationShortId()), gson.toJson(journey)); } public static List<PreferredJourney> getAllSavedJourneys(Context context, ENUM_HOME_HEADER type) { Gson gson = new GsonBuilder() .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) .registerTypeAdapterFactory(new PostProcessingEnabler()) .create(); List<PreferredJourney> list = new LinkedList<>(); Map<String, ?> m = SharedPreferencesHelper.getAllMatchingPrefix(context, type.getType()); for (String el : m.keySet()) { PreferredJourney temp = gson.fromJson(((String) m.get(el)), PreferredJourney.class); if (temp.getStation1() != null && temp.getStation2() != null) { list.add(temp); } } if (type == ENUM_HOME_HEADER.FAVOURITES) { Collections.sort(list, (o1, o2) -> { if (o1.getTimestamp() < o2.getTimestamp()) { return -1; } else if (o1.getTimestamp() > o2.getTimestamp()) { return 1; } else { return 0; } }); } else if (type == ENUM_HOME_HEADER.RECENT) { Collections.sort(list, (o1, o2) -> { if (o1.getTimestamp() > o2.getTimestamp()) { return -1; } else if (o1.getTimestamp() < o2.getTimestamp()) { return 1; } else { return 0; } }); } return list; } public static PreferredJourney getSavedJourney(Context context, ENUM_HOME_HEADER type, PreferredJourney journey) { return new GsonBuilder() .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) .registerTypeAdapterFactory(new PostProcessingEnabler()) .create().fromJson(getSharedPreferenceObject(context, buildSavedJourneyId(type, journey)), PreferredJourney.class); } public static String buildSavedJourneyId(ENUM_HOME_HEADER type, PreferredJourney preferredJourney) { return buildSavedJourneyId(type, preferredJourney.getStation1().getStationShortId(), preferredJourney.getStation2().getStationShortId()); } public static String buildSavedJourneyId(ENUM_HOME_HEADER type, PreferredStation departureStation, PreferredStation arrivalStation) { return buildSavedJourneyId(type, departureStation.getStationShortId(), arrivalStation.getStationShortId()); } public static String buildSavedJourneyId(ENUM_HOME_HEADER type, String id1, String id2) { int cod1 = Integer.parseInt(id1); int cod2 = Integer.parseInt(id2); return type.getType() + Math.min(cod1, cod2) + SEPARATOR + Math.max(cod1, cod2); } public static void removeSavedJourney(Context context, ENUM_HOME_HEADER type, String id1, String id2) { SharedPreferencesHelper.removeSharedPreferenceObject(context, buildSavedJourneyId(type, id1, id2)); } }
albertogiunta/justintrain-client-android
app/src/main/java/com/jaus/albertogiunta/justintrain_oraritreni/utils/sharedPreferences/StationsPreferences.java
Java
gpl-3.0
4,793
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtEnginio module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "stdafx.h" #include <QtCloudServices/private/qenginioconnectionobject_p.h> #include <QtCloudServices/private/qenginiodatastorageobject_p.h> QT_BEGIN_NAMESPACE /* ** Private */ QEnginioConnectionObjectPrivate::QEnginioConnectionObjectPrivate() { } QEnginioOperationObject *QEnginioConnectionObjectPrivate::customRequest(const QEnginioRequestObject *aRequest) { QRestOperationObject *restOp; QEnginioOperationObject *engOp; restOp=QRestConnectionObjectPrivate::restRequest(aRequest); engOp=reinterpret_cast<QEnginioOperationObject *>(restOp); return engOp; } QRestOperationObject* QEnginioConnectionObjectPrivate::buildOperationObject() const { return new QEnginioOperationObject(); } /* ** Public */ QEnginioConnectionObject::QEnginioConnectionObject(QObject *aParent) : QRestConnectionObject(*new QEnginioConnectionObjectPrivate(),aParent) { } QEnginioOperationObject *QEnginioConnectionObject::customRequest(const QEnginioRequestObject *aRequest) { Q_D(QEnginioConnectionObject); return d->customRequest(aRequest); } QT_END_NAMESPACE
jotahtin/qtc-sdk-qt
src/cloudservices/qenginioconnectionobject.cpp
C++
gpl-3.0
3,070
/*************************************************************************** * Copyright (C) 2012 by Serge Poltavski * * serge.poltavski@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * ***************************************************************************/ #include "binarizatorfactory.h" #include "oldbinarizator.h" #include "thresholdbinarizator.h" #include "otsubinarizator.h" #include "rimage_debug.h" #include "common/binarizeoptions.h" namespace cf { BinarizatorPtr BinarizatorFactoryImpl::make(const BinarizeOptions& opts) { BinarizatorPtr p; switch(opts.binarizator()) { case BINARIZATOR_KRONROD: p.reset(new OldBinarizator); RIMAGE_DEBUG_FUNC() << "using KRONROD binarizator"; return p; case BINARIZATOR_THRESHOLD: p.reset(new ThresholdBinarizator(opts)); RIMAGE_DEBUG_FUNC() << "using threshold binarizator"; return p; case BINARIZATOR_OTSU: p.reset(new OtsuBinarizator); RIMAGE_DEBUG_FUNC() << "using Otsu binarizator"; return p; default: RIMAGE_ERROR << " unsupported binarizator type: " << opts.binarizator() << "\n"; return p; } } }
uliss/quneiform
src/rimage/binarizatorfactory.cpp
C++
gpl-3.0
2,221
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | WARNING: You MUST set this value! | | If it is not set, then CodeIgniter will try guess the protocol and path | your installation, but due to security concerns the hostname will be set | to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise. | The auto-detection mechanism exists only for convenience during | development and MUST NOT be used in production! | | If you need to allow multiple domains, remember that this file is still | a PHP script and you can easily do that on your own. | */ $config['base_url'] = 'http://alt2600.net'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = 'index.php'; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'REQUEST_URI' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] | | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! */ $config['uri_protocol'] = 'REQUEST_URI'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | https://codeigniter.com/user_guide/general/urls.html | | Note: This option is ignored for CLI requests. */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | | See http://php.net/htmlspecialchars for a list of supported charsets. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | https://codeigniter.com/user_guide/general/core_classes.html | https://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Composer auto-loading |-------------------------------------------------------------------------- | | Enabling this setting will tell CodeIgniter to look for a Composer | package auto-loader script in application/vendor/autoload.php. | | $config['composer_autoload'] = TRUE; | | Or if you have your vendor/ directory located somewhere else, you | can opt to set a specific path as well: | | $config['composer_autoload'] = '/path/to/vendor/autoload.php'; | | For more information about Composer, please visit http://getcomposer.org/ | | Note: This will NOT disable or override the CodeIgniter-specific | autoloading (application/config/autoload.php) */ $config['composer_autoload'] = FALSE; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify which characters are permitted within your URLs. | When someone tries to submit a URL with disallowed characters they will | get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | The configured value is actually a regular expression character group | and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | | Note: This option is ignored for CLI requests. | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | You can also pass an array with threshold levels to show individual error types | | array(2) = Debug Messages, without Error Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ directory. Use a full server path. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Log File Extension |-------------------------------------------------------------------------- | | The default filename extension for log files. The default 'php' allows for | protecting the log files via basic scripting, when they are to be stored | under a publicly accessible directory. | | Note: Leaving it blank will default to 'php'. | */ $config['log_file_extension'] = ''; /* |-------------------------------------------------------------------------- | Log File Permissions |-------------------------------------------------------------------------- | | The file system permissions to be applied on newly created log files. | | IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal | integer notation (i.e. 0700, 0644, etc.) */ $config['log_file_permissions'] = 0644; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Error Views Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/views/errors/ directory. Use a full server path. | */ $config['error_views_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/cache/ directory. Use a full server path. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Include Query String |-------------------------------------------------------------------------- | | Whether to take the URL query string into consideration when generating | output cache files. Valid options are: | | FALSE = Disabled | TRUE = Enabled, take all query parameters into account. | Please be aware that this may result in numerous cache | files generated for the same page over and over again. | array('q') = Enabled, but only take into account the specified list | of query parameters. | */ $config['cache_query_string'] = FALSE; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class, you must set an encryption key. | See the user guide for more info. | | https://codeigniter.com/user_guide/libraries/encryption.html | */ $config['encryption_key'] = ''; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_driver' | | The storage driver to use: files, database, redis, memcached | | 'sess_cookie_name' | | The session cookie name, must contain only [0-9a-z_-] characters | | 'sess_expiration' | | The number of SECONDS you want the session to last. | Setting to 0 (zero) means expire when the browser is closed. | | 'sess_save_path' | | The location to save sessions to, driver dependent. | | For the 'files' driver, it's a path to a writable directory. | WARNING: Only absolute paths are supported! | | For the 'database' driver, it's a table name. | Please read up the manual for the format with other session drivers. | | IMPORTANT: You are REQUIRED to set a valid save path! | | 'sess_match_ip' | | Whether to match the user's IP address when reading the session data. | | WARNING: If you're using the database driver, don't forget to update | your session table's PRIMARY KEY when changing this setting. | | 'sess_time_to_update' | | How many seconds between CI regenerating the session ID. | | 'sess_regenerate_destroy' | | Whether to destroy session data associated with the old session ID | when auto-regenerating the session ID. When set to FALSE, the data | will be later deleted by the garbage collector. | | Other session cookie settings are shared with the rest of the application, | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. | */ $config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = NULL; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. | 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) | | Note: These settings (with the exception of 'cookie_prefix' and | 'cookie_httponly') will also affect sessions. | */ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; $config['cookie_secure'] = FALSE; $config['cookie_httponly'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. | 'csrf_regenerate' = Regenerate token on every submission | 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; $config['csrf_regenerate'] = TRUE; $config['csrf_exclude_uris'] = array(); /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | Only used if zlib.output_compression is turned off in your php.ini. | Please do not use it together with httpd-level output compression. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or any PHP supported timezone. This preference tells | the system whether to use your server's local time as the master 'now' | reference, or convert it to the configured one timezone. See the 'date | helper' page of the user guide for information regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy | IP addresses from which CodeIgniter should trust headers such as | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify | the visitor's IP address. | | You can use both an array or a comma-separated list of proxy addresses, | as well as specifying whole subnets. Here are a few examples: | | Comma-separated: '10.0.1.200,192.168.5.0/24' | Array: array('10.0.1.200', '192.168.5.0/24') */ $config['proxy_ips'] = '';
FatherStorm/PHPMyNetwork
application/config/config.php
PHP
gpl-3.0
16,599
/** * This file is part of vVoteVerifier which is designed to be used as a verifiation tool for the vVote Election System. * Copyright (C) 2014 James Rumble (jerumble@gmail.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.vvote.messages.typed.vote; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.vvote.JSONSchema; import com.vvote.messages.exceptions.JSONMessageInitException; import com.vvote.messages.exceptions.TypedJSONMessageInitException; import com.vvote.messages.exceptions.VoteDataMessageInitException; import com.vvote.messages.fields.MessageFields; import com.vvote.messages.typed.vote.exceptions.BallotReductionException; import com.vvote.thirdparty.json.orgjson.JSONArray; import com.vvote.thirdparty.json.orgjson.JSONException; import com.vvote.thirdparty.json.orgjson.JSONObject; /** * A print on Demand (POD) message includes any ballot reductions a * VoteDataMessage may include. The ballot reductions will provide the details * needed to remove any specific candidate identifiers from the generic ballots * included in ciphers.json which were not used in the specific race. Ballot * reductions also include the randomness values which were used on the * individual candidate identifiers to encrypt the plaintext candidate * identifier to the encrypted candidate identifier included in the generic * ballot * * @author James Rumble * */ public final class PODMessage extends VoteDataMessage { /** * Provides logging for the class */ private static final Logger logger = LoggerFactory.getLogger(PODMessage.class); /** * The ballot reductions in the json message in json form */ private final JSONArray jsonBallotReductions; /** * The ballot reductions in the json message */ private final BallotReductions ballotReductions; /** * Constructor for a PODMessage * * @param json * @throws VoteDataMessageInitException * @throws JSONMessageInitException * @throws TypedJSONMessageInitException */ public PODMessage(JSONObject json) throws VoteDataMessageInitException, TypedJSONMessageInitException, JSONMessageInitException { super(json); try { // get and set the ballot reductions if (json.has(MessageFields.PODMessage.BALLOT_REDUCTIONS)) { this.jsonBallotReductions = json.getJSONArray(MessageFields.PODMessage.BALLOT_REDUCTIONS); try { this.ballotReductions = new BallotReductions(this.jsonBallotReductions); } catch (BallotReductionException e) { logger.error("Unable to create a PODMessage. Error: {}", e); throw new VoteDataMessageInitException("Unable to create a PODMessage.", e); } } else { logger.error("A POD Message must contain ballot reductions"); throw new VoteDataMessageInitException("A POD Message must contain ballot reductions"); } } catch (JSONException e) { logger.error("Unable to create a PODMessage. Error: {}", e); throw new VoteDataMessageInitException("Unable to create a PODMessage.", e); } } /** * Getter for the ballot reductions * * @return ballotReductions */ public final BallotReductions getBallotReductions() { return this.ballotReductions; } @Override public JSONSchema getSchema() { return JSONSchema.POD_SCHEMA; } @Override public String getInternalSignableContent() throws JSONException{ StringBuilder internalSignableContent = new StringBuilder(); internalSignableContent.append(this.getSerialNo()); internalSignableContent.append(this.getDistrict()); internalSignableContent.append(this.jsonBallotReductions.toString()); internalSignableContent.append(this.getCommitTime()); return internalSignableContent.toString(); } }
jerumble/vVoteVerifier
src/com/vvote/messages/typed/vote/PODMessage.java
Java
gpl-3.0
4,300
class Omni::PriceBook < ActiveRecord::Base # METADATA (Start) ==================================================================== self.table_name = :price_books self.primary_key = :price_book_id # METADATA (End) # BEHAVIOR (Start) ==================================================================== supports_fulltext # BEHAVIOR (End) # VALIDATIONS (Start) ================================================================= validates :display, presence: true validates :price_book_id, presence: true validates :price_book_type, lookup: 'PRICE_BOOK_TYPE', allow_nil: true # VALIDATIONS (End) # DEFAULTS (Start) ==================================================================== default :price_book_id, override: false, with: :guid default :is_destroyed, override: false, to: false # DEFAULTS (End) # REFERENCE (Start) =================================================================== reference do display_attribute :display query_attribute :display item_template '{display}' end # REFERENCE (End) # ASSOCIATIONS (Start) ================================================================ has_many :notes, class_name: 'Buildit::Note', foreign_key: 'notable_id', as: :notable has_many :sku_promo_prices, class_name: 'Omni::SkuPromoPrice', foreign_key: 'price_book_id' has_many :sku_prices, class_name: 'Omni::SkuPrice', foreign_key: 'price_book_id' has_many :system_options, class_name: 'Omni::SystemOption', foreign_key: 'price_book_id' has_many :locations, class_name: 'Omni::Location', foreign_key: 'price_book_id' # ASSOCIATIONS (End) # MAPPED ATTRIBUTES (Start) =========================================================== # MAPPED ATTRIBUTES (End) # INDEXING (Start) ==================================================================== searchable do string :display string :description string :price_book_type do |x| Buildit::Lookup::Manager.display_for('PRICE_BOOK_TYPE', x.price_book_type) end string :short_name text :display_fulltext, using: :display text :description_fulltext, using: :description text :price_book_type_fulltext, using: :price_book_type text :short_name_fulltext, using: :short_name end # STATES (Start) ==================================================================== # STATES (End) def display_as self.display end end # class Omni::PriceBook
tunacasserole/omni
app/models/omni/price_book.rb
Ruby
gpl-3.0
2,779
from vsg.rules import token_prefix as Rule from vsg import token lTokens = [] lTokens.append(token.alias_declaration.alias_designator) class rule_600(Rule): ''' This rule checks for valid prefixes on alias designators. Default prefix is *a\_*. |configuring_prefix_and_suffix_rules_link| **Violation** .. code-block:: vhdl alias header is name; alias footer is name; **Fix** .. code-block:: vhdl alias a_header is name; alias a_footer is name; ''' def __init__(self): Rule.__init__(self, 'alias_declaration', '600', lTokens) self.prefixes = ['a_'] self.solution = 'Alias designators'
jeremiah-c-leary/vhdl-style-guide
vsg/rules/alias_declaration/rule_600.py
Python
gpl-3.0
689
using UnityEngine; namespace AnimationOrTween { public enum Trigger { OnClick, OnHover, OnPress, OnHoverTrue, OnHoverFalse, OnPressTrue, OnPressFalse, OnActivate, OnActivateTrue, OnActivateFalse, OnDoubleClick, OnSelect, OnSelectTrue, OnSelectFalse, } public enum Direction { Reverse = -1, Toggle = 0, Forward = 1, } public enum EnableCondition { DoNothing = 0, EnableThenPlay, IgnoreDisabledState, } public enum DisableCondition { DisableAfterReverse = -1, DoNotDisable = 0, DisableAfterForward = 1, } }
mr-kelly/ProjectWeak
Assets/NGUI/Scripts/Internal/AnimationOrTween.cs
C#
gpl-3.0
567
package com.entrepidea.algo.leetcode.easy; import org.junit.Test; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; public class LE349TwoArrayIntersec { //use Java 8's steam APIs, clean and clear code private int[] intersect(int[] input1, int[] input2){ //remove dups in input1 and convert it to a set Set<Integer> s = Arrays.stream(input1).distinct().boxed().collect(Collectors.toSet()); return Arrays.stream(input2).distinct().filter(i->s.contains(i)).toArray(); } @Test public void test(){ int[] rst = intersect(new int[]{1,2,2,1}, new int[]{2,2}); Arrays.stream(rst).forEach(System.out::println); rst = intersect(new int[]{4,9,5}, new int[]{9,4,9,8,4}); Arrays.stream(rst).forEach(System.out::println); } }
entrepidea/projects
java/java.core/src/test/java/com/entrepidea/algo/leetcode/easy/LE349TwoArrayIntersec.java
Java
gpl-3.0
914
// Define specializations for the Traits class template here. char s []="unknown"; char f0 []="apple"; char f1 []="orange"; char f2 []="pear"; char c0 []="red"; char c1 []="green"; char c2 []="orange"; template <> struct Traits<Fruit> { public: static char* name(int a) { if(a>=3 || a<0) return s; else if (a==0) return f0; else if (a==1) return f1; else return f2; } }; template <> struct Traits<Color> { public: static char* name(int a) { if(a>=3 || a<0) return s; else if (a==0) return c0; else if (a==1) return c1; else return c2; } };
shree-shubham/Unitype
C++ Class Template Specialization.cpp
C++
gpl-3.0
747
/* * GNU GENERAL LICENSE * Copyright (C) 2014 - 2021 Lobo Evolution * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * verion 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General License for more details. * * You should have received a copy of the GNU General Public * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact info: ivan.difrancesco@yahoo.it */ /* * Created on Jun 12, 2005 */ package org.loboevolution.net; /** * The Class NameValuePair. * * Author J. H. S. * */ public class NameValuePair extends AbstractBean implements Cloneable { /** The name. */ public String name; /** The value. */ public String value; /** * Instantiates a new name value pair. * * @param name the name * @param value the value */ public NameValuePair(String name, String value) { this.name = name; this.value = value; } /** * Sets the name. * * @param name the new name */ public void setName(String name) { String old = getName(); this.name = name; firePropertyChange("name", old, name); } /** * Gets the name. * * @return the name */ public final String getName() { return name; } /** * Sets the value. * * @param value the new value */ public void setValue(String value) { String old = getValue(); this.value = value; firePropertyChange("value", old, value); } /** * Gets the value. * * @return the value */ public final String getValue() { return value; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ /** {@inheritDoc} */ @Override public String toString() { return name + "=" + value; } }
oswetto/LoboEvolution
LoboCommon/src/main/java/org/loboevolution/net/NameValuePair.java
Java
gpl-3.0
2,008
<?php /********************************************************************* Teacher Copyright 2013 by Sébastien Mabon and Samuel Degoul (sdegoul@gmail.com) This file is part of Teacher. Teacher is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Teacher is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Teacher. If not, see <http://www.gnu.org/licenses/> *********************************************************************/ $title_view = _("Codes couleur de Teacher"); $style[] = 'start_user'; ?> <!-- <p class='return'> <a href='?module=start&action=start_user' class='link'> <img src='<?php echo IMAGE_PATH.'return_row.png'; ?>' alt="return" /> <?php echo _("retour à l'accueil"); ?> </a> </p> --> <h2> <?php echo _("Parcours dans Teacher"); ?> </h2> <div> <div class = 'show_user_color'></div> <p class = 'comment_color'> <?php echo _("cette couleur est en rapport avec votre parcours : auto-évaluations, formation, conducteur médecin pour les séances éducatives,..."); ?> </p> </div> <div> <div class = 'show_patient_color'></div> <p class = 'comment_color'> <?php echo _("cette couleur concerne le parcours de l'enfant."); ?> </p> </div> <h2> <?php echo _("Liens du menu de gauche"); ?> </h2> <p><?php echo _("Les liens en <span class = 'attractive_color'>rouge et gras</span> correspondent aux actions à réaliser."); ?></p> <p><?php echo _("Les liens en <span class = 'active_color'>noir</span> sont actifs et vous permettent en général de visualiser ce qui a déjà été fait."); ?></p> <p><?php echo _("Les liens en <span class = 'inactive_color'>gris</span> sont inactifs et correspondent généralement à des actions qu'il ne sera possible de réaliser qu'à un stade plus avancé dans le parcours."); ?></p> <!-- <h2> <?php echo _("Messages"); ?> </h2> <p><?php echo _("Ces messages apparaissent en haut des pages sur <span class = 'message_bg_color'>fond jaune clair</span>."); ?></p> <p><?php echo _("Les messages en <span class = 'error_color'>rouge et gras</span> indiquent une erreur qui bloque l'action en court et nécessite souvent une(des) correction(s) de votre part."); ?></p> <p><?php echo _("Les messages en <span class = 'warning_color'>orange et gras</span> vous demandent en général la confirmation de votre action."); ?></p> <p><?php echo _("Les messages en <span class = 'advice_color'>bleu et gras</span> comportent des conseils destinés à vous aider dans votre parcours."); ?></p> <p><?php echo _("Enfin, les messages en <span class = 'info_color'>vert</span> vous donnent une simple information."); ?></p> -->
s-degoul/Teacher
modules/start/views/show_color_code.php
PHP
gpl-3.0
3,022
<?php /** * * @package mahara * @subpackage artefact-blog * @author Catalyst IT Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later * @copyright For copyright information on Mahara, please see the README file distributed with this software. * */ defined('INTERNAL') || die(); /** * Users can create blogs and blog posts using this plugin. */ class PluginArtefactBlog extends PluginArtefact { public static function get_artefact_types() { return array( 'blog', 'blogpost', ); } public static function get_block_types() { return array(); } public static function get_plugin_name() { return 'blog'; } public static function admin_menu_items() { $map['manageinstitutions/blogs'] = array( 'path' => 'manageinstitutions/blogs', 'url' => 'artefact/blog/index.php?institution=1', 'title' => get_string('Blogs', 'artefact.blog'), 'weight' => 75, ); $map['configsite/blogs'] = array( 'path' => 'configsite/blogs', 'url' => 'artefact/blog/index.php?institution=mahara', 'title' => get_string('Blogs', 'artefact.blog'), 'weight' => 65, ); if (defined('MENUITEM') && isset($map[MENUITEM])) { $map[MENUITEM]['selected'] = true; } return $map; } public static function institution_menu_items() { return self::admin_menu_items(); } public static function set_blog_nav($institution = false, $institutionname = null, $groupid = null) { if ($institutionname == 'mahara') { define('ADMIN', 1); define('MENUITEM', 'configsite/blogs'); } else if ($institution) { define('INSTITUTIONALADMIN', 1); define('MENUITEM', 'manageinstitutions/blogs'); } else if ($groupid) { define('GROUP', $groupid); define('MENUITEM', 'groups/blogs'); } else { define('MENUITEM', 'content/blogs'); } } public static function is_active() { return get_field('artefact_installed', 'active', 'name', 'blog'); } public static function menu_items() { global $USER; $tab = array( 'path' => 'content/blogs', 'weight' => 40, 'url' => 'artefact/blog/index.php', 'title' => get_string('Blogs', 'artefact.blog'), ); return array('content/blogs' => $tab); } public static function get_cron() { return array(); } public static function get_event_subscriptions() { return array( (object)array( 'plugin' => 'blog', 'event' => 'createuser', 'callfunction' => 'create_default_blog', ), ); } public static function block_advanced_options_element($configdata, $artefacttype) { $strartefacttype = strtolower(get_string($artefacttype, 'artefact.blog')); $options = array('nocopy' => get_string('copynocopy', 'artefact.blog')); if ($artefacttype == 'taggedposts') { $options['tagsonly'] = get_string('copytagsonly', 'artefact.blog', $strartefacttype); } else { $options['reference'] = get_string('copyreference', 'artefact.blog', $strartefacttype); $options['full'] = get_string('copyfull', 'artefact.blog', $strartefacttype); } return array( 'type' => 'fieldset', 'name' => 'advanced', 'class' => 'first last', 'collapsible' => true, 'collapsed' => false, 'legend' => get_string('moreoptions', 'artefact.blog'), 'elements' => array( 'copytype' => array( 'type' => 'select', 'title' => get_string('blockcopypermission', 'view'), 'description' => get_string('blockcopypermissiondesc', 'view'), 'defaultvalue' => isset($configdata['copytype']) ? $configdata['copytype'] : 'nocopy', 'options' => $options, ), ), ); } public static function create_default_blog($event, $user) { $name = display_name($user, null, true); $blog = new ArtefactTypeBlog(0, (object) array( 'title' => get_string('defaultblogtitle', 'artefact.blog', $name), 'owner' => is_object($user) ? $user->id : $user['id'], )); $blog->commit(); } public static function get_artefact_type_content_types() { return array( 'blog' => array('blog'), 'blogpost' => array('blogpost'), ); } public static function progressbar_link($artefacttype) { return 'artefact/blog/view/index.php'; } public static function group_tabs($groupid) { return array( 'blogs' => array( 'path' => 'groups/blogs', 'url' => 'artefact/blog/index.php?group=' . $groupid, 'title' => get_string('Blogs', 'artefact.blog'), 'weight' => 65, ), ); } } /** * A Blog artefact is a collection of BlogPost artefacts. */ class ArtefactTypeBlog extends ArtefactType { /** * This constant gives the per-page pagination for listing blogs. */ const pagination = 10; /** * We override the constructor to fetch the extra data. * * @param integer * @param object */ public function __construct($id = 0, $data = null) { parent::__construct($id, $data); if (empty($this->id)) { $this->container = 1; } } public static function is_allowed_in_progressbar() { return false; } public function display_title($maxlen=null) { global $USER; $title = $this->get('title'); // Check if we are displaying title to anonymous user // And the blog we are showing is the default one named // after the user. if (!$USER->is_logged_in()) { $owner = new User; $owner->find_by_id($this->get('owner')); if (preg_match('/^' . preg_quote($owner->get('firstname') . ' ' . $owner->get('lastname') . '/'), $title)) { $title = get_string('Blog', 'artefact.blog'); } } if ($maxlen) { return str_shorten_text($title, $maxlen, true); } return $title; } public function display_postedby($date, $by) { global $USER; if (!is_numeric($date)) { // convert any formatted dates back to time $date = strtotime($date); } if ($USER->is_logged_in()) { return get_string('postedbyon', 'artefact.blog', $by, format_date($date)); } else { return get_string('postedon', 'artefact.blog') . ' ' . format_date($date); } } /** * This function updates or inserts the artefact. This involves putting * some data in the artefact table (handled by parent::commit()), and then * some data in the artefact_blog_blog table. */ public function commit() { // Just forget the whole thing when we're clean. if (empty($this->dirty)) { return; } // We need to keep track of newness before and after. $new = empty($this->id); // Commit to the artefact table. parent::commit(); $this->dirty = false; } /** * This function extends ArtefactType::delete() by deleting blog-specific * data. */ public function delete() { if (empty($this->id)) { return; } db_begin(); // Delete embedded images in the blog description require_once('embeddedimage.php'); EmbeddedImage::delete_embedded_images('blog', $this->id); // Delete the artefact and all children. parent::delete(); db_commit(); } /** * Checks that the person viewing a personal blog is the owner. * Or the person is an institution admin for an institution blog. * Or a group member if viewing a group blog. * Or a group member with editing permissions if editing a blog. * If not, throws an AccessDeniedException. * Other people see blogs when they are placed in views. */ public function check_permission($editing=false) { global $USER; if (!empty($this->institution)) { if ($this->institution == 'mahara' && !$USER->get('admin')) { throw new AccessDeniedException(get_string('youarenotasiteadmin', 'artefact.blog')); } else if (!$USER->get('admin') && !$USER->is_institutional_admin($this->institution)) { throw new AccessDeniedException(get_string('youarenotanadminof', 'artefact.blog', $this->institution)); } } else if (!empty($this->group)) { $group = get_group_by_id($this->group); $USER->reset_grouproles(); if (!isset($USER->grouproles[$this->group])) { throw new AccessDeniedException(get_string('youarenotamemberof', 'artefact.blog', $group->name)); } require_once('group.php'); if ($editing && !group_role_can_edit_views($this->group, $USER->grouproles[$this->group])) { throw new AccessDeniedException(get_string('youarenotaneditingmemberof', 'artefact.blog', $group->name)); } } else { if ($USER->get('id') != $this->owner) { throw new AccessDeniedException(get_string('youarenottheownerofthisblog', 'artefact.blog')); } } } public function describe_size() { return $this->count_children() . ' ' . get_string('posts', 'artefact.blog'); } /** * Renders a blog. * * @param array Options for rendering * @return array A two key array, 'html' and 'javascript'. */ public function render_self($options) { if (!isset($options['limit'])) { $limit = self::pagination; } else if ($options['limit'] === false) { $limit = null; } else { $limit = (int) $options['limit']; } $offset = isset($options['offset']) ? intval($options['offset']) : 0; if (!isset($options['countcomments'])) { // Count comments if this is a view $options['countcomments'] = (!empty($options['viewid'])); } $posts = ArtefactTypeBlogpost::get_posts($this->id, $limit, $offset, $options); $template = 'artefact:blog:viewposts.tpl'; $baseurl = get_config('wwwroot') . 'artefact/artefact.php?artefact=' . $this->id; if (!empty($options['viewid'])) { $baseurl .= '&view=' . $options['viewid']; } $pagination = array( 'baseurl' => $baseurl, 'id' => 'blogpost_pagination', 'datatable' => 'postlist', 'jsonscript' => 'artefact/blog/posts.json.php', ); ArtefactTypeBlogpost::render_posts($posts, $template, $options, $pagination); $smarty = smarty_core(); if (isset($options['viewid'])) { $smarty->assign('artefacttitle', '<a href="' . get_config('wwwroot') . 'artefact/artefact.php?artefact=' . $this->get('id') . '&view=' . $options['viewid'] . '">' . hsc($this->get('title')) . '</a>'); $smarty->assign('view', $options['viewid']); } else { $smarty->assign('artefacttitle', hsc($this->get('title'))); $smarty->assign('view', null); } if (!empty($options['details']) and get_config('licensemetadata')) { $smarty->assign('license', render_license($this)); } else { $smarty->assign('license', false); } $options['hidetitle'] = true; $smarty->assign('options', $options); $smarty->assign('description', $this->get('description')); $smarty->assign('owner', $this->get('owner')); $smarty->assign('tags', $this->get('tags')); $smarty->assign('posts', $posts); return array('html' => $smarty->fetch('artefact:blog:blog.tpl'), 'javascript' => ''); } public static function get_icon($options=null) { global $THEME; return false; } public static function is_singular() { return false; } public static function collapse_config() { } public function can_have_attachments() { return true; } /** * This function returns a list of the given blogs. * * @param User * @return array (count: integer, data: array) */ public static function get_blog_list($limit, $offset, $institution = null, $group = null) { global $USER; $sql = "SELECT b.id, b.title, b.description, b.locked, COUNT(p.id) AS postcount FROM {artefact} b LEFT JOIN {artefact} p ON (p.parent = b.id AND p.artefacttype = 'blogpost') WHERE b.artefacttype = 'blog'"; if ($institution) { $sql .= ' AND b.institution = ?'; $values = array($institution); $count = (int)get_field('artefact', 'COUNT(*)', 'institution', $institution, 'artefacttype', 'blog'); } else if ($group) { $sql .= ' AND b.group = ?'; $values = array($group); $count = (int)get_field('artefact', 'COUNT(*)', 'group', $group, 'artefacttype', 'blog'); $groupdata = get_group_by_id($group, false, true, true); } else { $sql .= ' AND b.owner = ?'; $values = array($USER->get('id')); $count = (int)get_field('artefact', 'COUNT(*)', 'owner', $USER->get('id'), 'artefacttype', 'blog'); } $sql .= " GROUP BY b.id, b.title, b.description, b.locked ORDER BY b.title"; ($result = get_records_sql_array($sql, $values, $offset, $limit)) || ($result = array()); foreach ($result as &$r) { if (!$r->locked) { $r->deleteform = ArtefactTypeBlog::delete_form($r->id, $r->title); } $r->canedit = (!empty($groupdata) ? $groupdata->canedit : true); } return array($count, $result); } public static function build_blog_list_html(&$blogs) { $smarty = smarty_core(); $smarty->assign('blogs', $blogs); $blogs->tablerows = $smarty->fetch('artefact:blog:bloglist.tpl'); $pagination = build_pagination(array( 'id' => 'bloglist_pagination', 'class' => 'center', 'url' => get_config('wwwroot') . 'artefact/blog/index.php', 'jsonscript' => 'artefact/blog/index.json.php', 'datatable' => 'bloglist', 'count' => $blogs->count, 'limit' => $blogs->limit, 'offset' => $blogs->offset, 'setlimit' => true, 'jumplinks' => 6, 'numbersincludeprevnext' => 2, 'resultcounttextsingular' => get_string('blog', 'artefact.blog'), 'resultcounttextplural' => get_string('blogs', 'artefact.blog'), )); $blogs->pagination = $pagination['html']; $blogs->pagination_js = $pagination['javascript']; } /** * This function creates a new blog. * * @param User or null * @param array */ public static function new_blog($user, array $values) { require_once('embeddedimage.php'); db_begin(); $artefact = new ArtefactTypeBlog(); $artefact->set('title', $values['title']); $artefact->set('description', $values['description']); if (!empty($values['institution'])) { $artefact->set('institution', $values['institution']); } else if (!empty($values['group'])) { $artefact->set('group', $values['group']); } else { $artefact->set('owner', $user->get('id')); } $artefact->set('tags', $values['tags']); if (get_config('licensemetadata')) { $artefact->set('license', $values['license']); $artefact->set('licensor', $values['licensor']); $artefact->set('licensorurl', $values['licensorurl']); } $artefact->commit(); $blogid = $artefact->get('id'); $newdescription = EmbeddedImage::prepare_embedded_images($artefact->get('description'), 'blog', $blogid); $artefact->set('description', $newdescription); db_commit(); } /** * This function updates an existing blog. * * @param User * @param array */ public static function edit_blog(User $user, array $values) { require_once('embeddedimage.php'); if (empty($values['id']) || !is_numeric($values['id'])) { return; } $artefact = new ArtefactTypeBlog($values['id']); $institution = !empty($values['institution']) ? $values['institution'] : null; $group = !empty($values['group']) ? $values['group'] : null; if (!self::can_edit_blog($artefact, $institution, $group)) { return; } $artefact->set('title', $values['title']); $newdescription = EmbeddedImage::prepare_embedded_images($values['description'], 'blog', $values['id']); $artefact->set('description', $newdescription); $artefact->set('tags', $values['tags']); if (get_config('licensemetadata')) { $artefact->set('license', $values['license']); $artefact->set('licensor', $values['licensor']); $artefact->set('licensorurl', $values['licensorurl']); } $artefact->commit(); } public static function get_links($id) { $wwwroot = get_config('wwwroot'); return array( '_default' => $wwwroot . 'artefact/blog/view/index.php?id=' . $id, get_string('blogsettings', 'artefact.blog') => $wwwroot . 'artefact/blog/settings/index.php?id=' . $id, ); } public function copy_extra($new) { $new->set('title', get_string('Copyof', 'mahara', $this->get('title'))); } /** * Returns the number of posts in this blog that have been published. * * The result of this function looked up from the database each time, so * cache it if you know it's safe to do so. * * @return int */ public function count_published_posts() { return (int)get_field_sql(" SELECT COUNT(*) FROM {artefact} a LEFT JOIN {artefact_blog_blogpost} bp ON a.id = bp.blogpost WHERE a.parent = ? AND bp.published = 1", array($this->get('id'))); } public static function delete_form($id, $title = '') { global $THEME; $confirm = get_string('deleteblog?', 'artefact.blog'); $title = hsc($title); // Check if this blog has posts. $postcnt = count_records_sql(" SELECT COUNT(*) FROM {artefact} a INNER JOIN {artefact_blog_blogpost} bp ON a.id = bp.blogpost WHERE a.parent = ? ", array($id)); if ($postcnt > 0) { $confirm = get_string('deletebloghaspost?', 'artefact.blog', $postcnt); // Check if this blog posts used in views. $viewscnt = count_records_sql(" SELECT COUNT(DISTINCT(va.view)) FROM {artefact} a INNER JOIN {view_artefact} va ON a.id = va.artefact WHERE a.parent = ? OR a.id = ? ", array($id, $id)); if ($viewscnt > 0) { $confirm = get_string('deletebloghasview?', 'artefact.blog', $viewscnt); } } return pieform(array( 'name' => 'delete_' . $id, 'successcallback' => 'delete_blog_submit', 'renderer' => 'div', 'class' => 'form-as-button pull-left btn-group-item', 'elements' => array( 'submit' => array( 'type' => 'button', 'usebuttontag' => true, 'class' => 'btn-default btn-sm last', 'alt' => get_string('deletespecific', 'mahara', $title), 'elementtitle' => get_string('delete'), 'confirm' => $confirm, 'value' => '<span class="icon icon-trash icon-lg text-danger" role="presentation" aria-hidden="true"></span><span class="sr-only">' . get_string('deletespecific', 'mahara', $title) . '</span>', ), 'delete' => array( 'type' => 'hidden', 'value' => $id, ), ), )); } public function update_artefact_references(&$view, &$template, &$artefactcopies, $oldid) { parent::update_artefact_references($view, $template, $artefactcopies, $oldid); // Update <img> tags in the blog description to refer to the new image artefacts. $regexp = array(); $replacetext = array(); if (isset($artefactcopies[$oldid]->oldembeds)) { foreach ($artefactcopies[$oldid]->oldembeds as $a) { if (isset($artefactcopies[$a])) { // Change the old image id to the new one $regexp[] = '#<img([^>]+)src="' . get_config('wwwroot') . 'artefact/file/download.php\?file=' . $a . '([^0-9])#'; $replacetext[] = '<img$1src="' . get_config('wwwroot') . 'artefact/file/download.php?file=' . $artefactcopies[$a]->newid . '$2'; } } require_once('embeddedimage.php'); $newdescription = EmbeddedImage::prepare_embedded_images( preg_replace($regexp, $replacetext, $this->get('description')), 'blog', $this->get('id'), $view->get('group') ); $this->set('description', $newdescription); } } /** * During the copying of a view, we might be allowed to copy * blogs. Users need to have multipleblogs enabled for these * to be visible. */ public function default_parent_for_copy(&$view, &$template, $artefactstoignore) { global $USER, $SESSION; $viewid = $view->get('id'); $groupid = $view->get('group'); $institution = $view->get('institution'); if ($groupid || $institution) { $SESSION->add_msg_once(get_string('copiedblogpoststonewjournal', 'collection'), 'ok', true, 'messages'); } else { try { $user = get_user($view->get('owner')); set_account_preference($user->id, 'multipleblogs', 1); $SESSION->add_msg_once(get_string('copiedblogpoststonewjournal', 'collection'), 'ok', true, 'messages'); } catch (Exception $e) { $SESSION->add_error_msg(get_string('unabletosetmultipleblogs', 'error', $user->username, $viewid, get_config('wwwroot') . 'account/index.php'), false); } try { $USER->accountprefs = load_account_preferences($user->id); } catch (Exception $e) { $SESSION->add_error_msg(get_string('pleaseloginforjournals', 'error')); } } return null; } /** * Check to see if the user has permissions to edit the blog * * @param object $blog A blog artefact * @param string $institution Institution name (optional) * * @return boolean */ public static function can_edit_blog($blog, $institution = null, $group = null) { global $USER; require_once('group.php'); $USER->reset_grouproles(); if ( ($institution == 'mahara' && $USER->get('admin')) || ($institution && $institution != 'mahara' && ($USER->get('admin') || $USER->is_institutional_admin($institution))) || ($group && !empty($USER->grouproles[$group]) && group_role_can_edit_views($group, $USER->grouproles[$group])) || ($USER->get('id') == $blog->get('owner')) ) { return true; } return false; } } /** * BlogPost artefacts occur within Blog artefacts */ class ArtefactTypeBlogPost extends ArtefactType { /** * This defines whether the blogpost is published or not. * * @var boolean */ protected $published = false; /** * We override the constructor to fetch the extra data. * * @param integer * @param object */ public function __construct($id = 0, $data = null) { parent::__construct($id, $data); if ($this->id) { if ($bpdata = get_record('artefact_blog_blogpost', 'blogpost', $this->id)) { foreach($bpdata as $name => $value) { if (property_exists($this, $name)) { $this->$name = $value; } } } else { // This should never happen unless the user is playing around with blog post IDs in the location bar or similar throw new ArtefactNotFoundException(get_string('blogpostdoesnotexist', 'artefact.blog')); } } else { $this->allowcomments = 1; // Turn comments on for new posts } } /** * This method extends ArtefactType::commit() by adding additional data * into the artefact_blog_blogpost table. * * This method also works out what blockinstances this blogpost is in, and * informs them that they should re-check what artefacts they have in them. * The post content may now link to different artefacts. See {@link * PluginBlocktypeBlogPost::get_artefacts for more information} */ protected function postcommit_hook($new) { require_once(get_config('docroot') . 'blocktype/lib.php'); require_once(get_config('docroot') . 'artefact/blog/blocktype/taggedposts/lib.php'); $data = (object)array( 'blogpost' => $this->get('id'), 'published' => ($this->get('published') ? 1 : 0) ); if ($new) { insert_record('artefact_blog_blogpost', $data); } else { update_record('artefact_blog_blogpost', $data, 'blogpost'); } // We want to get all blockinstances that may contain this blog post. That is currently: // 1) All blogpost blocktypes with this post in it // 2) All blog blocktypes with this posts's blog in it // 3) All recentposts blocktypes with this post's blog in it // 4) All taggedposts blocktypes with this post's tags $blocks = (array)get_column_sql('SELECT block FROM {view_artefact} WHERE artefact = ? OR artefact = ?', array($this->get('id'), $this->get('parent'))); if (!$blocks) { $blocks = array(); } // Get all "tagged blog entries" blocks that may contain this block // (we'll just check for a single matching tag here, and let each block // instance further down decide whether or not it matches $tags = $this->get('tags'); if ($tags) { $blocks = array_merge($blocks, PluginBlocktypeTaggedposts::find_matching_blocks($tags)); } // Now rebuild the list of which artefacts these blocks contain // in the view_artefacts table. (This is used for watchlist notifications) if ($blocks) { foreach ($blocks as $id) { $instance = new BlockInstance($id); $instance->rebuild_artefact_list(); } } } /** * This function extends ArtefactType::delete() by also deleting anything * that's in blogpost. */ public function delete() { if (empty($this->id)) { return; } require_once('embeddedimage.php'); db_begin(); $this->detach(); // Detach all file attachments delete_records('artefact_blog_blogpost', 'blogpost', $this->id); EmbeddedImage::delete_embedded_images('blogpost', $this->id); parent::delete(); db_commit(); } public static function bulk_delete($artefactids, $log=false) { if (empty($artefactids)) { return; } $idstr = join(',', array_map('intval', $artefactids)); db_begin(); delete_records_select('artefact_blog_blogpost', 'blogpost IN (' . $idstr . ')'); parent::bulk_delete($artefactids); db_commit(); } /** * Checks that the person viewing a personal blog is the owner. * Or the person is an institution admin for an institution blog. * Or a group member if viewing a group blog. * Or a group member with editing permissions if editing a blog. * If not, throws an AccessDeniedException. * Other people see blogs when they are placed in views. */ public function check_permission($editing=true) { global $USER; if (!empty($this->institution)) { if ($this->institution == 'mahara' && !$USER->get('admin')) { throw new AccessDeniedException(get_string('youarenotasiteadmin', 'artefact.blog')); } else if (!$USER->get('admin') && !$USER->is_institutional_admin($this->institution)) { throw new AccessDeniedException(get_string('youarenotanadminof', 'artefact.blog', $this->institution)); } } else if (!empty($this->group)) { $group = get_group_by_id($this->group); $USER->reset_grouproles(); if (!isset($USER->grouproles[$this->group])) { throw new AccessDeniedException(get_string('youarenotamemberof', 'artefact.blog', $group->name)); } require_once('group.php'); if ($editing && !group_role_can_edit_views($this->group, $USER->grouproles[$this->group])) { throw new AccessDeniedException(get_string('youarenotaneditingmemberof', 'artefact.blog', $group->name)); } } else { if ($USER->get('id') != $this->owner) { throw new AccessDeniedException(get_string('youarenottheownerofthisblogpost', 'artefact.blog')); } } } public function describe_size() { return $this->count_attachments() . ' ' . get_string('attachments', 'artefact.blog'); } public function render_self($options) { global $USER; $smarty = smarty_core(); $smarty->assign('published', $this->get('published')); if (!$this->get('published')) { $notpublishedblogpoststr = get_string('notpublishedblogpost', 'artefact.blog'); if ($this->get('owner') == $USER->get('id')) { $notpublishedblogpoststr .= ' <a href="' . get_config('wwwroot') . 'artefact/blog/post.php?id=' . $this->get('id') . '">' . get_string('publishit', 'artefact.blog') . '</a>'; } $smarty->assign('notpublishedblogpost', $notpublishedblogpoststr); } $artefacturl = get_config('wwwroot') . 'artefact/artefact.php?artefact=' . $this->get('id'); if (isset($options['viewid'])) { $artefacturl .= '&view=' . $options['viewid']; } $smarty->assign('artefacturl', $artefacturl); if (empty($options['hidetitle'])) { if (isset($options['viewid'])) { $smarty->assign('artefacttitle', '<a href="' . $artefacturl . '">' . hsc($this->get('title')) . '</a>'); } else { $smarty->assign('artefacttitle', hsc($this->get('title'))); } } // We need to make sure that the images in the post have the right viewid associated with them $postcontent = $this->get('description'); if (isset($options['viewid'])) { safe_require('artefact', 'file'); $postcontent = ArtefactTypeFolder::append_view_url($postcontent, $options['viewid']); } $smarty->assign('artefactdescription', $postcontent); $smarty->assign('artefacttags', $this->get('tags')); $smarty->assign('artefactowner', $this->get('owner')); $smarty->assign('artefactview', (isset($options['viewid']) ? $options['viewid'] : null)); if (!empty($options['details']) and get_config('licensemetadata')) { $smarty->assign('license', render_license($this)); } else { $smarty->assign('license', false); } $attachments = $this->get_attachments(); if ($attachments) { require_once(get_config('docroot') . 'artefact/lib.php'); foreach ($attachments as &$attachment) { $f = artefact_instance_from_id($attachment->id); $attachment->size = $f->describe_size(); $attachment->iconpath = $f->get_icon(array('id' => $attachment->id, 'viewid' => isset($options['viewid']) ? $options['viewid'] : 0)); $attachment->viewpath = get_config('wwwroot') . 'artefact/artefact.php?artefact=' . $attachment->id . '&view=' . (isset($options['viewid']) ? $options['viewid'] : 0); $attachment->downloadpath = get_config('wwwroot') . 'artefact/file/download.php?file=' . $attachment->id; if (isset($options['viewid'])) { $attachment->downloadpath .= '&view=' . $options['viewid']; } } $smarty->assign('attachments', $attachments); if (isset($options['blockid'])) { $smarty->assign('blockid', $options['blockid']); } $smarty->assign('postid', $this->get('id')); } $smarty->assign('postedbyon', ArtefactTypeBlog::display_postedby($this->ctime, display_name($this->owner))); if ($this->ctime != $this->mtime) { $smarty->assign('updatedon', get_string('updatedon', 'artefact.blog') . ' ' . format_date($this->mtime)); } return array('html' => $smarty->fetch('artefact:blog:render/blogpost_renderfull.tpl'), 'javascript' => '', 'attachments' => $attachments); } public function can_have_attachments() { return true; } public static function get_icon($options=null) { global $THEME; return false; } public static function is_singular() { return false; } public static function collapse_config() { } /** * This function returns the blog id and offset for a given post. * * @param integer $postid The id of the required blog post * @return object An object containing the required data */ public static function get_post_data($postid) { $post = new stdClass(); $post->blogid = get_field('artefact', 'parent', 'id', $postid, 'artefacttype', 'blogpost'); if (is_postgres()) { $rownum = get_field_sql("SELECT rownum FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY id DESC) AS rownum FROM {artefact} WHERE parent = ? ORDER BY id DESC) AS posts WHERE id = ?", array($post->blogid, $postid)); } else if (is_mysql()) { $initvar = execute_sql("SET @row_num = 0"); if ($initvar) { $rownum = get_field_sql("SELECT rownum FROM (SELECT id, @row_num := @row_num + 1 AS rownum FROM {artefact} WHERE parent = ? ORDER BY id DESC) AS posts WHERE id = ?", array($post->blogid, $postid)); } } $post->offset = $rownum - 1; return $post; } /** * This function returns a list of posts in a given blog. * * @param integer * @param integer * @param integer * @param array */ public static function get_posts($id, $limit, $offset, $viewoptions=null) { global $USER; $results = array( 'limit' => $limit, 'offset' => $offset, ); // If viewoptions is null, we're getting posts for the my blogs area, // and we should get all posts & show drafts first. Otherwise it's a // blog in a view, and we should only get published posts. $from = " FROM {artefact} a LEFT JOIN {artefact_blog_blogpost} bp ON a.id = bp.blogpost WHERE a.artefacttype = 'blogpost' AND a.parent = ?"; if (!is_null($viewoptions)) { if (isset($viewoptions['before'])) { $from .= " AND a.ctime < '{$viewoptions['before']}'"; } $draftentries = count_records_sql('SELECT COUNT(*) ' . $from, array($id)); $from .= ' AND bp.published = 1'; } $results['count'] = count_records_sql('SELECT COUNT(*) ' . $from, array($id)); //check if all posts are drafts if (isset($draftentries) && $draftentries > 0 && $results['count'] == 0) { $results['alldraftposts'] = true; } $data = get_records_sql_assoc(' SELECT a.id, a.title, a.description, a.author, a.authorname, ' . db_format_tsfield('a.ctime', 'ctime') . ', ' . db_format_tsfield('a.mtime', 'mtime') . ', a.locked, bp.published, a.allowcomments, a.group ' . $from . ' ORDER BY bp.published ASC, a.ctime DESC, a.id DESC', array($id), $offset, $limit ); if (!$data) { $results['data'] = array(); return $results; } // Get the attached files. $postids = array_map(create_function('$a', 'return $a->id;'), $data); $files = ArtefactType::attachments_from_id_list($postids); if ($files) { safe_require('artefact', 'file'); foreach ($files as &$file) { $params = array('id' => $file->attachment); if (!empty($viewoptions['viewid'])) { $params['viewid'] = $viewoptions['viewid']; } $file->icon = call_static_method(generate_artefact_class_name($file->artefacttype), 'get_icon', $params); $data[$file->artefact]->files[] = $file; } } if ($tags = ArtefactType::tags_from_id_list($postids)) { foreach($tags as &$at) { $data[$at->artefact]->tags[] = $at->tag; } } foreach ($data as &$post) { // Format dates properly if (is_null($viewoptions)) { // My Blogs area: create forms for changing post status & deleting posts. $post->changepoststatus = ArtefactTypeBlogpost::changepoststatus_form($post->id, $post->published, $post->title); $post->delete = ArtefactTypeBlogpost::delete_form($post->id, $post->title); } else { $by = $post->author ? display_default_name($post->author) : $post->authorname; $post->postedby = ArtefactTypeBlog::display_postedby($post->ctime, $by); $post->owner = $post->author; // Get comment counts if (!empty($viewoptions['countcomments'])) { safe_require('artefact', 'comment'); require_once(get_config('docroot') . 'lib/view.php'); $view = new View($viewoptions['viewid']); $artefact = artefact_instance_from_id($post->id); list($commentcount, $comments) = ArtefactTypeComment::get_artefact_comments_for_view($artefact, $view, null, false); $post->commentcount = $commentcount; $post->comments = $comments; } } if ($post->ctime != $post->mtime) { $post->lastupdated = format_date($post->mtime, 'strftimedaydatetime'); } $post->ctime = format_date($post->ctime, 'strftimedaydatetime'); $post->mtime = format_date($post->mtime); // Ensure images in the post have the right viewid associated with them if (!empty($viewoptions['viewid'])) { safe_require('artefact', 'file'); $post->description = ArtefactTypeFolder::append_view_url($post->description, $viewoptions['viewid']); } if (isset($post->group)) { $group = get_group_by_id($post->group, false, true, true); } $post->canedit = (isset($group) ? $group->canedit : true); } $results['data'] = array_values($data); return $results; } /** * This function renders a list of posts as html * * @param array posts * @param string template * @param array options * @param array pagination */ public function render_posts(&$posts, $template, $options, $pagination) { $smarty = smarty_core(); $smarty->assign('options', $options); $smarty->assign('posts', $posts['data']); $posts['tablerows'] = $smarty->fetch($template); $setlimit = isset($pagination['setlimit']) ? $pagination['setlimit'] : false; if ($posts['limit'] && $pagination) { $pagination = build_pagination(array( 'id' => $pagination['id'], 'class' => 'center', 'datatable' => $pagination['datatable'], 'url' => $pagination['baseurl'], 'jsonscript' => $pagination['jsonscript'], 'count' => $posts['count'], 'limit' => $posts['limit'], 'setlimit' => $setlimit, 'offset' => $posts['offset'], 'jumplinks' => 6, 'numbersincludeprevnext' => 2, 'resultcounttextsingular' => get_string('post', 'artefact.blog'), 'resultcounttextplural' => get_string('posts', 'artefact.blog'), )); $posts['pagination'] = $pagination['html']; $posts['pagination_js'] = $pagination['javascript']; } } /** * This function creates a new blog post. * * @param User * @param array */ public static function new_post(User $user, array $values) { $artefact = new ArtefactTypeBlogPost(); $artefact->set('title', $values['title']); $artefact->set('description', $values['description']); $artefact->set('published', $values['published']); $artefact->set('owner', $user->get('id')); $artefact->set('parent', $values['parent']); $artefact->commit(); return true; } /** * This function updates an existing blog post. * * @param User * @param array */ public static function edit_post(User $user, array $values) { $artefact = new ArtefactTypeBlogPost($values['id']); if ($user->get('id') != $artefact->get('owner')) { return false; } $artefact->set('title', $values['title']); $artefact->set('description', $values['description']); $artefact->set('published', $values['published']); $artefact->set('tags', $values['tags']); if (get_config('licensemetadata')) { $artefact->set('license', $values['license']); $artefact->set('licensor', $values['licensor']); $artefact->set('licensorurl', $values['licensorurl']); } $artefact->commit(); return true; } public static function changepoststatus_form($id, $published = null, $title = null) { //Get current post status from database if ($published === null || $title === null) { $post = new ArtefactTypeBlogPost($id); $published = empty($published) ? $post->published : $published; $title = empty($title) ? $post->title : $title; } $title = hsc($title); if ($published) { $strchangepoststatus = '<span class="icon icon-times icon-lg left text-danger" role="presentation" aria-hidden="true"></span><span class="sr-only">' . get_string('unpublishspecific', 'artefact.blog', $title) . '</span> ' . get_string('unpublish', 'artefact.blog'); } else { $strchangepoststatus = '<span class="icon icon-check icon-lg left text-success" role="presentation" aria-hidden="true"></span><span class="sr-only"> ' . get_string('publishspecific', 'artefact.blog', $title) . '</span> ' . get_string('publish', 'artefact.blog'); } return pieform(array( 'name' => 'changepoststatus_' . $id, 'jssuccesscallback' => 'changepoststatus_success', 'successcallback' => 'changepoststatus_submit', 'jsform' => true, 'renderer' => 'div', 'elements' => array( 'changepoststatus' => array( 'type' => 'hidden', 'value' => $id, ), 'currentpoststatus' => array( 'type' => 'hidden', 'value' => $published, ),'submit' => array( 'type' => 'button', 'usebuttontag' => true, 'class' => 'btn-default btn-sm publish', 'value' => $strchangepoststatus, ), ), )); } public static function delete_form($id, $title = '') { $title = hsc($title); global $THEME; return pieform(array( 'name' => 'delete_' . $id, 'successcallback' => 'delete_submit', 'jsform' => true, 'jssuccesscallback' => 'delete_success', 'renderer' => 'div', 'class' => 'form-as-button pull-left', 'elements' => array( 'delete' => array( 'type' => 'hidden', 'value' => $id, 'help' => true, ), 'submit' => array( 'type' => 'button', 'usebuttontag' => true, 'class' => 'btn-default btn-sm last', 'elementtitle' => get_string('delete'), 'confirm' => get_string('deleteblogpost?', 'artefact.blog'), 'value' => '<span class="icon icon-trash icon-lg text-danger" role="presentation" aria-hidden="true"></span><span class="sr-only">' . get_string('deletespecific', 'mahara', $title) . '</span>', ), ), )); } /** * This function changes the blog post status. * * @param $newpoststatus: boolean 1=published, 0=draft * @return boolean */ public function changepoststatus($newpoststatus) { if (!$this->id) { return false; } $this->set('published', (int) $newpoststatus); $this->commit(); return true; } public static function get_links($id) { $wwwroot = get_config('wwwroot'); return array( '_default' => $wwwroot . 'artefact/blog/view/index.php?blogpost=' . $id, ); } public function update_artefact_references(&$view, &$template, &$artefactcopies, $oldid) { parent::update_artefact_references($view, $template, $artefactcopies, $oldid); // 1. Attach copies of the files that were attached to the old post. if (isset($artefactcopies[$oldid]->oldattachments)) { foreach ($artefactcopies[$oldid]->oldattachments as $a) { if (isset($artefactcopies[$a])) { $this->attach($artefactcopies[$a]->newid); } } } // 2. Update embedded images in the post body field $regexp = array(); $replacetext = array(); if (isset($artefactcopies[$oldid]->oldembeds)) { foreach ($artefactcopies[$oldid]->oldembeds as $a) { if (isset($artefactcopies[$a])) { // Change the old image id to the new one $regexp[] = '#<img([^>]+)src="' . get_config('wwwroot') . 'artefact/file/download.php\?file=' . $a . '([^0-9])#'; $replacetext[] = '<img$1src="' . get_config('wwwroot') . 'artefact/file/download.php?file=' . $artefactcopies[$a]->newid . '$2'; } } require_once('embeddedimage.php'); $newdescription = EmbeddedImage::prepare_embedded_images( preg_replace($regexp, $replacetext, $this->get('description')), 'blogpost', $this->get('id'), $view->get('group') ); $this->set('description', $newdescription); } } /** * During the copying of a view, we might be allowed to copy * blogposts but not the containing blog. We need to create a new * blog to hold the copied posts. */ public function default_parent_for_copy(&$view, &$template, $artefactstoignore) { static $blogids; global $USER, $SESSION; $viewid = $view->get('id'); if (isset($blogids[$viewid])) { return $blogids[$viewid]; } $blogname = get_string('viewposts', 'artefact.blog', $viewid); $data = (object) array( 'title' => $blogname, 'description' => get_string('postscopiedfromview', 'artefact.blog', $template->get('title')), 'owner' => $view->get('owner'), 'group' => $view->get('group'), 'institution' => $view->get('institution'), ); $blog = new ArtefactTypeBlog(0, $data); $blog->commit(); $blogids[$viewid] = $blog->get('id'); if (!empty($data->group) || !empty($data->institution)) { $SESSION->add_ok_msg(get_string('copiedblogpoststonewjournal', 'collection')); } else { try { $user = get_user($view->get('owner')); set_account_preference($user->id, 'multipleblogs', 1); $SESSION->add_ok_msg(get_string('copiedblogpoststonewjournal', 'collection')); } catch (Exception $e) { $SESSION->add_error_msg(get_string('unabletosetmultipleblogs', 'error', $user->username, $viewid, get_config('wwwroot') . 'account/index.php'), false); } try { $USER->accountprefs = load_account_preferences($user->id); } catch (Exception $e) { $SESSION->add_error_msg(get_string('pleaseloginforjournals', 'error')); } } return $blogids[$viewid]; } /** * Looks through the blog post text for links to download artefacts, and * returns the IDs of those artefacts. */ public function get_referenced_artefacts_from_postbody() { return artefact_get_references_in_html($this->get('description')); } public static function is_countable_progressbar() { return true; } }
tonyjbutler/mahara
htdocs/artefact/blog/lib.php
PHP
gpl-3.0
52,136
/** This file is part of client-side of the CampusTrees Project. It is subject to the license terms in the LICENSE file found in the top-level directory of this distribution. No part of CampusTrees Project, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the LICENSE file.*/ package com.speedacm.treeview; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.Toast; import com.speedacm.treeview.menu.ActivityStarter; import com.speedacm.treeview.menu.DynamicMapStarter; import com.speedacm.treeview.menu.MenuItem; import com.speedacm.treeview.views.AboutActivity; import com.speedacm.treeview.views.CredsActivity; import com.speedacm.treeview.views.DynamicMapActivity; import com.speedacm.treeview.views.NewsActivity; import com.speedacm.treeview.views.PlantFactsActivity; import com.speedacm.treeview.views.ScavHuntMainActivity; import com.speedacm.treeview.views.WildLifeFactsActivity; public class MainMenuActivity extends Activity implements OnItemClickListener { private ArrayList<MenuItem> menuEntries = new ArrayList<MenuItem>(); /* commented out until barcode scanning is actually used // in order for "this" to be accessible to the inner class, define // it here so mScanListener can get a proper pointer to the outer activity private Activity mThisPtr = this; private Pattern mURLPattern = Pattern.compile("^http://treetest/tree/(\\d+)/?$"); private MenuActionListener mScanListener = new MenuActionListener() { @Override public void onMenuAction(MenuItem item) { IntentIntegrator ii = new IntentIntegrator(mThisPtr); ii.initiateScan(); } }; @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { String url = scanResult.getContents(); Matcher m = mURLPattern.matcher(url); if(!m.matches()) { // display error to user showText("Invalid URL: ".concat(url)); return; } // load tree ID and launch info try { // there should be only one group in the regex int id = Integer.parseInt(m.group(1)); Tree t = DataStore.getInstance().getTree(id); if(t == null) { showText("Could not load tree."); return; } Intent i = new Intent(this, TreeInfoActivity.class); i.putExtra("tree", t.getID()); startActivity(i); } catch(Exception e) { showText("Could not find tree ID."); } } } */ private void showText(String text) { Toast.makeText(this, text, Toast.LENGTH_LONG).show(); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mainmenu); addMenuItems(); // bind to our menu items ListView mmenu = (ListView)findViewById(R.id.mainMenuList); mmenu.setOnItemClickListener(this); // Create a customized ArrayAdapter MenuItemArrayAdapter adapter = new MenuItemArrayAdapter( getApplicationContext(), R.layout.menuitem_listitem, menuEntries); ListView lv = (ListView) this.findViewById(R.id.mainMenuList); lv.setAdapter(adapter); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // since each menu entry already has an event handler bound to it, // there is no need to do anything fancy, just call its handler MenuItem entry = (MenuItem)parent.getItemAtPosition(position); entry.action(); } private void addMenuItems() { menuEntries.add(new MenuItem(getString(R.string.mmenu_news), R.drawable.news, new ActivityStarter(this, NewsActivity.class))); menuEntries.add(new MenuItem(getString(R.string.mmenu_treemap), R.drawable.browse_tree_map, new DynamicMapStarter(this, DynamicMapActivity.TREE_MODE))); //menuEntries.add(new MenuItem(getString(R.string.mmenu_sustmap), R.drawable.browse_sustainability_map, // new DynamicMapStarter(this, DynamicMapActivity.SUSTAIN_MODE))); // uncomment this and section at top of file for barcode scanning //menuEntries.add(new MenuItem(getString(R.string.mmenu_scanbarcode), R.drawable.about, mScanListener)); menuEntries.add(new MenuItem(getString(R.string.mmenu_plantfacts), R.drawable.plant_facts, new ActivityStarter(this, PlantFactsActivity.class))); menuEntries.add(new MenuItem(getString(R.string.mmenu_wildfacts), R.drawable.wildlife_facts, new ActivityStarter(this, WildLifeFactsActivity.class))); //menuEntries.add(new MenuItem(getString(R.string.mmenu_scavhunt), R.drawable.scavenger_hunt, // new ActivityStarter(this, ScavHuntMainActivity.class))); menuEntries.add(new MenuItem(getString(R.string.mmenu_about), R.drawable.about, new ActivityStarter(this, AboutActivity.class))); menuEntries.add(new MenuItem(getString(R.string.mmenu_creds), R.drawable.about, new ActivityStarter(this, CredsActivity.class))); } }
felixtheratruns/CampusTrees-client
src/com/speedacm/treeview/MainMenuActivity.java
Java
gpl-3.0
5,291
import json import mailbox import numpy as np from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from sklearn.feature_extraction.text import TfidfVectorizer from lib.analysis.author import ranking from lib.util import custom_stopwords from lib.util.read import * def get_top_authors(top_n, json_filename): """ Gets the top n authors based on the ranking generated from generate_author_ranking in analysis.author.ranking :param top_n: The number of top authors to be returned. :param json_filename: The JSON file from which author scores are generated. :return: Top authors and their indices """ top_authors = set() top_authors_index = dict() author_scores = ranking.get(json_filename, output_filename=None, active_score=2, passive_score=1, write_to_file=False) index = 0 for email_addr, author_score in author_scores: index += 1 top_authors.add(email_addr) top_authors_index[email_addr] = index if index == top_n: break return top_authors, top_authors_index def save_sparse_csr(filename, array): """ This function writes a numpy matrix to a file,given as a parameter, in a sparse format. :param filename: The file to store the matrix. :param array: The numpy array. """ np.savez(filename,data = array.data ,indices=array.indices, indptr =array.indptr, shape=array.shape ) def get_message_body(message): """ Gets the message body of the message passed as a parameter. :param message: The message whose body is to be extracted. :return: The message body from the message. """ msg_body = None if message.is_multipart(): for part in message.walk(): if part.is_multipart(): for subpart in part.walk(): msg_body = subpart.get_payload(decode=False) else: msg_body = part.get_payload(decode=False) else: msg_body = message.get_payload(decode=False) msg_body = msg_body.splitlines() for num in range(len(msg_body)): if msg_body[num]: if msg_body[num] == "---": msg_body = msg_body[:num] break if msg_body[num][0] == '>' or msg_body[num][0] == '+' or msg_body[num][0] == '-' or msg_body[num][0] == '@': msg_body[num] = "" if num > 0: msg_body[num - 1] = "" elif msg_body[num][:3] == "Cc:": msg_body[num] = "" elif msg_body[num][:14] == "Signed-off-by:": msg_body[num] = "" elif msg_body[num][:9] == "Acked-by:": msg_body[num] = "" elif msg_body[num][:5] == "From:": msg_body[num] = "" elif msg_body[num][:10] == "Tested-by:": msg_body[num] = "" elif msg_body[num][:12] == "Reported-by:": msg_body[num] = "" elif msg_body[num][:12] == "Reviewed-by:": msg_body[num] = "" elif msg_body[num][:5] == "Link:": msg_body[num] = "" elif msg_body[num][:13] == "Suggested-by:": msg_body[num] = "" msg_body = [x.strip() for x in msg_body] msg_body = [x for x in msg_body if x != ""] msg_body = '\n'.join(msg_body) return msg_body def generate_keyword_digest(mbox_filename, output_filename, author_uid_filename, json_filename, top_n = None, console_output=True): """ From the .MBOX file, this function extracts the email content is extracted using two predefined classes available in the Python Standard Library: Mailbox and Message. Feature vectors are created for all the authors by obtaining meaningful words from the mail content, after removing the stop words, using NLTK libraries. The words obtained are transformed using stemming or lemmatization before adding these words to the word list of the corresponding authors. A matrix is created out of these word lists such that row set is the union of terms of all the authors and the column set contains the authors. If a term does not appear in a document, the corresponding matrix entry would be zero. The resulting matrix is called term-document matrix. Then tf-idf analysis is performed on the term-document matrix. Finally the top-10 words of each author is listed by their weight values.Each entry corresponds to the tf-idf normalized coefficient of the keyword for a user. If a keyword is not present in the top-10 keywords of a user, then the corresponding matrix entry would be zero. Also returns the feature names. :param mbox_filename: Contains the absolute or relative address of the MBOX file to be opened :return: Term Document Matrix: The columns of the matrix are the users and the rows of the matrix are the keywords. """ english_stopwords = set(stopwords.words('english')) | custom_stopwords.common_words | custom_stopwords.custom_words email_re = re.compile(r'[\w\.-]+@[\w\.-]+') wnl = WordNetLemmatizer() print("Reading messages from MBOX file...") mailbox_obj = mailbox.mbox(mbox_filename) with open(author_uid_filename, 'r') as map_file: author_uid_map = json.load(map_file) map_file.close() if top_n is None: print("Reading author UIDs from JSON file...") keywords_list = [list() for x in range(max(author_uid_map.values())+1)] else: top_n = min(len(author_uid_map), top_n) top_authors, top_authors_index = get_top_authors(top_n, json_filename) keywords_list = [list() for x in range(top_n+1)] i = 0 # Number of emails processed with open(output_filename, 'w') as out_file: for message in mailbox_obj: temp = email_re.search(str(message['From'])) from_addr = temp.group(0) if temp is not None else message['From'] if top_n is not None and from_addr not in top_authors: continue if top_n is None and from_addr not in author_uid_map.keys(): continue msg_body = get_message_body(message) if from_addr is None: from_addr = message['From'] msg_tokens = [x.lower() for x in re.sub('\W+', ' ', msg_body).split() if 2 < len(x) < 30] # Toggle comment below if numbers and underscores should also be removed. # msg_tokens = [x for x in re.sub('[^a-zA-Z]+', ' ', msg_body).split() if 2 < len(x) < 30] msg_tokens = [wnl.lemmatize(x) for x in msg_tokens if not x.isdigit() and x not in from_addr] msg_tokens = [x for x in msg_tokens if x not in english_stopwords] if top_n is None: keywords_list[author_uid_map[from_addr]].extend(msg_tokens) else: keywords_list[top_authors_index[from_addr]].extend(msg_tokens) if not console_output: i += 1 if not i % 10000: print(i, "of", len(mailbox_obj), "messages processed.") for num in range(len(keywords_list)): keywords_list[num] = " ".join(keywords_list[num]) print("Performing tf-idf analysis on the term-document matrix...") vectorizer = TfidfVectorizer(analyzer='word', stop_words=english_stopwords, max_df=0.9, min_df=0.05, use_idf=True, ngram_range=(1, 4)) tfidf_matrix = vectorizer.fit_transform(keywords_list).toarray() feature_names = vectorizer.get_feature_names() if top_n is None: for author_email, author_uid in author_uid_map.items(): if max(tfidf_matrix[author_uid]) > 0 and len(keywords_list[num]) > 99: try: indices = tfidf_matrix[author_uid].argsort()[-20:][::-1] if not console_output: out_file.write(author_email + "\n") author_features = list() for i in indices: author_features.append(feature_names[i]) # author_features.append((feature_names[i], tfidf_matrix[author_uid][i])) author_features.sort(key=lambda x: -1*len(x)) for i2 in range(len(author_features)): overlap_flag = 0 for i1 in range(i2+1, len(author_features)): if author_features[i1] in author_features[i2]: overlap_flag = 1 break if not overlap_flag: out_file.write(author_features[i2] + ", ") else: print("ERROR: Console Output not implemented! Please write to file.") except: pass finally: if console_output: print("\n-----\n") else: out_file.write("\n-----\n") else: term_document_matrix = np.zeros((len(feature_names), top_n), dtype=float) for author_email, author_uid in top_authors_index.items(): if max(tfidf_matrix[author_uid]) > 0 and len(keywords_list[author_uid]) > 99: try: indices = tfidf_matrix[author_uid].argsort()[-20:][::-1] if not console_output: out_file.write(author_email + "\n") author_features = list() for i in indices: author_features.append(feature_names[i]) # author_features.append((feature_names[i], tfidf_matrix[author_uid][i])) author_features.sort(key=lambda x: -1 * len(x)) for i2 in range(len(author_features)): overlap_flag = 0 for i1 in range(i2+1, len(author_features)): if author_features[i1] in author_features[i2]: overlap_flag = 1 break if not overlap_flag: out_file.write(author_features[i2]+", ") else: print("ERROR: Console Output not implemented! Please write to file.") except: pass finally: if console_output: print("\n-----\n") else: out_file.write("\n-----\n") # with open("author_top_index.json", 'w') as json_file: # json.dump(top_authors_index, json_file) # print(feature_names) return top_authors_index, term_document_matrix, feature_names # generate_keyword_digest("lkml.mbox")
prasadtalasila/MailingListParser
lib/input/mbox/keyword_digest.py
Python
gpl-3.0
11,492
#!/usr/bin/env python2 import netsnmp import argparse def getCAM(DestHost, Version = 2, Community='public'): sess = netsnmp.Session(Version = 2, DestHost=DestHost, Community=Community) sess.UseLongNames = 1 sess.UseNumeric = 1 #to have <tags> returned by the 'get' methods untranslated (i.e. dotted-decimal). Best used with UseLongNames Vars1 = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.17.4.3.1')) result = sess.walk(Vars1) #result = sess.getbulk(0, 10, Vars1)#get vars in one req, but dont stop... Vars2 = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.17.1.4.1.2')) result += sess.walk(Vars2) Vars3 = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.2.1.31.1.1.1.1')) result += sess.walk(Vars3) if result == (): raise Exception('Error : ' + sess.ErrorStr + ' ' + str(sess.ErrorNum) + ' ' + str(sess.ErrorInd)) l = {} for v in Vars1: myid = (v.tag + '.' + v.iid)[24:] if v.tag[22] == '1': l[myid] = [v.val] elif v.tag[22] == '2': l[myid] += [v.val] elif v.tag[22] == '3': l[myid] += [v.val] #Get the bridge port to ifIndex mapping, dot1dBasePortIfIndex (.1.3.6.1.2.1.17.1.4.1.2) dot1dBasePortIfIndex = {} for v in Vars2: dot1dBasePortIfIndex[v.iid] = v.val for cle, valeur in l.items(): valeur += [dot1dBasePortIfIndex[valeur[1]]] ifName = {} for v in Vars3: ifName[v.iid] = v.val for cle, valeur in l.items(): valeur += [ifName[valeur[3]]] return l if __name__ == '__main__': parser = argparse.ArgumentParser(description='Describe this program') #parser.add_argument('-v', '--version', dest = 'version', type = int, default = 2, help = 'Version of the protocol. Only v2 is implemented at the moment.') parser.add_argument('desthost', action = 'store', default = 'localhost', help = 'Address of the switch') parser.add_argument('-c', '--community', dest = 'community', action = 'store', default = 'public', help = 'The community string, default is "public".') args = parser.parse_args() try: l = getCAM(Version = 2, DestHost=args.desthost, Community=args.community) except Exception as e: print(e) else: for t in l.values(): print(''.join('%02x:' % ord(b) for b in bytes(t[0]))[:-1] + ' = ' + t[4])
c4ffein/snmp-cam-table-logger
getCAM.py
Python
gpl-3.0
2,240
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import Thumbnail from 'components/Thumbnail'; /* Import Venue Images */ import Harvard from 'static/images/Harvard.jpg'; import Walters from 'static/images/Walters.jpg'; import Auckland from 'static/images/Auckland.jpg'; import Cooper from 'static/images/Cooper.jpg'; import Finnish from 'static/images/Finnish.jpg'; /* Import Interior Images */ import iHarvard from 'static/images/Harvard_interior.jpg'; import iWalters from 'static/images/Walters_interior.jpg'; import iAuckland from 'static/images/Auckland_interior.jpg'; import iCooper from 'static/images/Cooper_interior.jpg'; import iFinnish from 'static/images/Finnish_interior.jpg'; /* Build MUSEUMS Array with corresponding Image and Name The Name will be used as a parameter to search in the FullWorks Page to get all instances of the work in that venue */ const MUSEUMS = [ [Harvard, iHarvard, 'Harvard+Art+Museum'], [Walters, iWalters, 'The+Walters+Art+Museum'], [Auckland, iAuckland, 'Auckland+Museum'], [Cooper, iCooper, 'Cooper+Hewitt,+Smithsonian+Design+Museum'], [Finnish, iFinnish, 'Finnish+National+Gallery'] ]; const PARAMETERS = '&maptype=satellite&zoom=19'; const BASE_URL = 'https://www.google.com/maps/embed/v1/place?key=AIzaSyAEh4yg0EoQBAqs3ieHnEPCD_ENLeYKUwM&q='; class Venue extends Component { constructor() { super(); this.state = { venue: [], works: [] }; this.museum_url = ''; this.imuseum_url = ''; this.map_location = ''; this.museum_name = ''; } /* Fetches the data from our database and parses it accordingly */ componentDidMount() { const venue_id = parseInt(this.props.match.params.number, 10) if(1 <= venue_id && venue_id <= 5) { const museum = MUSEUMS[venue_id - 1] this.museum_url = museum[0]; this.imuseum_url = museum[1]; this.museum_name = museum[2]; } fetch(`http://api.museumary.me/venue/` + venue_id) .then(result=>result.json()) .then(venue=> { this.setState({ venue }) let add = [ // Format Street if there is one, empty otherwise venue.street ? venue.street.replace(/ /g, '+') : '', venue.city, venue.country ]; this.map_location = BASE_URL + add.join(',') + PARAMETERS; for (let i = 0; i < 4; i++) { fetch('http://api.museumary.me/work/' + venue.work_ids[i]) .then(result => result.json()) .then(responseJson => this.setState({works: this.state.works.concat([responseJson])})) } }) } render() { var venue_obj = this.state.venue; var work_list = this.state.works; if(venue_obj && work_list && work_list.length > 0){ // Do all React code within this div. 'Venue_obj' is the object that // associated with this Venue page, you should be able to access it // like any other JSON // Create 4 Work Thumbnails let works = work_list.map(function(obj) { obj.url = '/works/' + obj.id; obj.name = obj.name.substring(0, 25) + (obj.name.length > 25 ? '...': '') obj.details = [obj.name, 'N/A', 'N/A']; return <Thumbnail key={obj.id} {...obj} />; }) return ( <div className="Venue"> {/* Venue Name and Base / Interior Images */} <h1>{venue_obj.name}</h1> <div className="container"> <div className="row"> <div className="col-md-6"> <img src={ this.museum_url } alt="Harvard" className="img-rounded" width="500" height="300"/> </div> <div className="col-md-6"> <img src={ this.imuseum_url } alt="Harvard Interior" className="img-rounded" width="500" height="300"/> </div> </div> </div> {/* 4 Works Gallery and link to FullPage */} <Link to={'/works?venue='+this.museum_name}><h2><strong>Gallery of Works</strong></h2></Link><br/> <div className="container"> <div className="row"> {works} </div> </div> <br /> {/* Map */} <iframe width="800" height="600" frameBorder="0" src={ this.map_location } allowFullScreen align="center"></iframe><br/> <p><strong>Address:</strong> {venue_obj.street} {venue_obj.city} {venue_obj.country}</p><br/><br/> </div> ); } else { return <div className="Venue"></div>; } } } export default Venue;
museumary/Museumary
react/src/components/Models/SinglePages/Venue.js
JavaScript
gpl-3.0
5,180
<?php class managedServicesPlans extends AllFunctions { //function for get Language public function getPricing($id = '') { $condition = ''; if ($id != '') { $condition = array('id' => $id); } return $this->select($this->cfg['db_prefix'].'managed_services_plans', '*', $condition); } function savePlans() { //echo "insert<pre>";print_r($_POST);echo "</pre>";die; if (!isset($_POST['saveButton'])) { return false; } if ($_POST['id'] == '' && $_POST['planType'] != '') { // echo "insert<pre>";print_r($_POST);echo "</pre>";die; if ($this->isUnique($this->cfg['db_prefix'].'managed_services_plans', 'plan_type', $_POST['planType'])) { $fields = array('plan_type' => $_POST['planType'], 'plan_name' => $_POST['planName'], 'silver_price' => $_POST['silverPrice'], 'gold_price' => $_POST['goldPrice'], 'platinum_price' => $_POST['platinumPrice'], 'titanium_price' => $_POST['titaniumPrice'], 'currency_code' => $_POST['currency_code'], 'active' => $_POST['planStatus']); $result = $this->insert($this->cfg['db_prefix'].'managed_services_plans', $fields); } else { return 'Plan already exists'; } } elseif ($_POST['id'] != '' && $_POST['planType'] != '') { // echo "update<pre>";print_r($_POST);echo "</pre>";die; $set_fields = array('plan_type' => $_POST['planType'], 'plan_name' => $_POST['planName'], 'silver_price' => $_POST['silverPrice'], 'gold_price' => $_POST['goldPrice'], 'platinum_price' => $_POST['platinumPrice'], 'titanium_price' => $_POST['titaniumPrice'], 'currency_code' => $_POST['currency_code'], 'active' => $_POST['planStatus']); $where = array('id' => $_POST['id']); $result = $this->update($this->cfg['db_prefix'].'managed_services_plans', $set_fields, $where); } else { return 'Fill Required Fields'; } return isset($result['error']) ? $result['error'] : 'success'; } } ?>
aroramanish63/bulmail_app
Live Backup/adminpanel/functions/mngdServiceFunctions.php
PHP
gpl-3.0
2,132
#define SDL_MAIN_HANDLED #ifdef _WIN32 #include <windows.h> #else #include <dlfcn.h> #endif // _WIN32 #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <iostream> #include <functional> #include <chrono> #include <fstream> #include <string> #include <sstream> #include <databank.h> #ifdef _WIN32 typedef void (__stdcall *f_funci)(databank*); typedef void (__stdcall *f_funco)(databank*, std::vector<std::string>); #else typedef void (*f_funci)(databank*); typedef void (*f_funco)(databank*, std::vector<std::string>); #endif // _WIN32 void SDL_INIT(databank* db) { if (SDL_Init(SDL_INIT_VIDEO) != 0) { exit(-1); } db->setSDL_WINDOW(SDL_CreateWindow("GAME", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, db->getResX(), db->getResY(), SDL_WINDOW_SHOWN)); db->setSDL_RENDERER(SDL_CreateRenderer(db->getSDL_WINDOW(), -1, SDL_RENDERER_ACCELERATED | SDL_WINDOW_OPENGL)); //SDL_SetRenderDrawColor( db->getSDL_RENDERER(), 0, 0, 0, 255 ); db->setCX((-1)*(db->getResX() / db->getCHX() / 2) + db->plx); db->setCY((-1)*(db->getResY() / db->getCHY() / 2) + db->ply); } void loadConfig(databank* db) { std::ifstream infile; infile.open("data/config.txt"); while (!infile.eof()) // To get you all the lines. { std::string obj_l; std::vector<std::string> Obj_V; getline(infile, obj_l); // Saves the line in STRING. std::istringstream ss(obj_l); std::string token; if (obj_l == "") { break; } while (std::getline(ss, token, ';')) { Obj_V.push_back(token); } if (db->vstr(Obj_V, 0) == "controls") { db->setControls(db->vstr(Obj_V, 1)); } else if (db->vstr(Obj_V, 0) == "player") { db->setPlayerMod(db->vstr(Obj_V, 1)); } Obj_V.clear(); } infile.close(); } void loadSave(databank* db) { std::ifstream infile; infile.open("maps/Test/world.txt"); if (infile.is_open() == false) { std::cout << "Failed to open map!" << std::endl; } while (!infile.eof()) // To get you all the lines. { std::string obj_l; std::vector<std::string> Obj_V; getline(infile, obj_l); // Saves the line in STRING. std::istringstream ss(obj_l); std::string token; if (obj_l == "") { break; } while (std::getline(ss, token, ';')) { Obj_V.push_back(token); } for (unsigned i = 0; i < db->svdll.size(); i++) { if (db->svdll.at(i) == db->vstr(Obj_V, 0)) { #ifdef _WIN32 f_funco funci = (f_funco)GetProcAddress(db->hvdll.at(i), "loadObjects"); funci(db, Obj_V); #else f_funco funci = (f_funco)dlsym(db->hvdll.at(i), "loadObjects"); funci(db, Obj_V); #endif // _WIN32 } } Obj_V.clear(); } infile.close(); } void loadMods(databank* db) { std::ifstream file("data/modlist.txt"); std::string str; while (std::getline(file, str)) { #ifdef _WIN32 db->hvdll.push_back(LoadLibrary(("mods/" + str + ".dll").c_str())); db->svdll.push_back(str); f_funci funci = (f_funci)GetProcAddress(db->hvdll.at(db->hvdll.size() - 1), "initMod"); funci(db); #else db->hvdll.push_back(dlopen(("mods/" + str + ".so").c_str(), RTLD_LAZY)); db->svdll.push_back(str); if (db->hvdll.at(db->hvdll.size() - 1) == NULL) { std::cout << dlerror() << std::endl; } f_funci funci = (f_funci)dlsym(db->hvdll.at(db->hvdll.size() - 1), "initMod"); funci(db); #endif // _WIN32 } } void SDL_Events(databank* db) { SDL_PollEvent(db->getSDL_EVENT()); if (db->getSDL_EVENT()->type == SDL_QUIT) { db->safeQuit(); } for(unsigned short int i = 0; i < db->eventEvent.size(); i++) { db->eventEvent.at(i)(db); } } void SDL_Render(databank* db) { SDL_RenderClear(db->getSDL_RENDERER()); for(unsigned short int i = 0; i < db->renderEvent.size(); i++) { db->renderEvent.at(i)(db); } SDL_RenderPresent(db->getSDL_RENDERER()); } bool fpsControl(databank* db) { auto time = std::chrono::system_clock::now(); auto since_epoch = time.time_since_epoch(); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(since_epoch); db->fps_ctime = millis.count(); db->fps_dtime = db->fps_ctime - db->fps_ltime; if (db->fps_dtime >= 20) { return true; } return false; } int main() { databank db; SDL_INIT(&db); loadConfig(&db); loadMods(&db); loadSave(&db); SDL_Render(&db); while (db.shouldQuit() != true) { if (fpsControl(&db) == true) { SDL_Events(&db); SDL_Render(&db); db.fps_ltime = db.fps_ctime; } } db.safeQuit(); }
MagicRB/GAME
src/main.cpp
C++
gpl-3.0
5,123
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Modelo.RecursoDidatico; import Modelo.RecursoDidatico.Midia.Audio; import Modelo.RecursoDidatico.Midia.Video; import java.util.ArrayList; import java.util.Collection; /** * * @author Gustavo Freitas */ public class Palavra implements RecursoDidatico { public static enum CATEGORIA { DISSILABA_SIMPLES(1, "Dissílabas Simples", "Palavra simples que possui duas sílabas"), TRISSILABA_SIMPLES(2, "Trissílabas Simples", "'Palavra simples que possui três silabas."), DIFICULDADE_DA_LINGUA(3, "Dificuldades da Língua", "Palavra composta por encontro consonantal que a faz ser mais complexa que as demais."); int id; String nome; String descricao; CATEGORIA(int id, String nome, String descricao){ this.id = id; this.nome = nome; this.descricao = descricao; } public int getId(){ return (this.id); } public String getNome(){ return (this.nome); } public String getDescricao() { return descricao; } } int id = -1; private String palavra = null; private ArrayList<Silaba> silabas = new ArrayList<>(); private Imagem imagem = null; private Audio audio = null; private Video video = null; private CATEGORIA categoria; public Palavra(String palavra){ this.palavra = palavra; } public Palavra(int id, String palavra){ this.id = id; this.palavra = palavra; } public Palavra(String palavra, CATEGORIA cat, ArrayList<Silaba> silabas, Imagem imagem){ this.palavra = palavra; this.categoria = cat; this.silabas = silabas; this.imagem = imagem; } public Palavra(String palavra, CATEGORIA cat, ArrayList<Silaba> silabas, Imagem imagem, Audio audio, Video video){ this.palavra = palavra; this.categoria = cat; this.silabas = silabas; this.imagem = imagem; this.audio = audio; this.video = video; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPalavra() { return palavra; } public void setPalavra(String palavra) { this.palavra = palavra; } public Collection<Silaba> getSilabas() { return silabas; } public void setSilabas(ArrayList<Silaba> silabas) { this.silabas = silabas; } public Imagem getImagem() { return imagem; } public void setImagem(Imagem imagem) { this.imagem = imagem; } public Audio getAudio() { return audio; } public void setAudio(Audio audio) { this.audio = audio; } public Video getVideo() { return video; } public void setVideo(Video video) { this.video = video; } public CATEGORIA getCategoria() { return categoria; } public void setCategoria(CATEGORIA categoria) { this.categoria = categoria; } @Override public String toString(){ return ("Palavra: " + this.palavra + "\n" + "Silabas: " + this.silabas); } }
gustavofamorim/ensino_individualizado_manager
src/Modelo/RecursoDidatico/Palavra.java
Java
gpl-3.0
3,409
@extends('backend.layouts.index') @section('content') <style> .btn-edit{ background-color: dodgerblue; border: none; border-radius: 3px; height: 25px; } .btn-edit a{ color: ghostwhite; } .btn-delete{ background-color: #e53935; border: none; border-radius: 3px; height: 25px; } .btn-delete a{ color: ghostwhite; } .single-button{ width: 100px; margin-left:auto; margin-right: auto; } .cen{ padding-left: 60px; padding-right: 60px; } </style> <div class="content"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="card"> <div class="card-header" data-background-color="orange"> <h4 class="title" align="center">{{ ucfirst($customize->name) }} | Last modified by: {{ $customize->user->name }}</h4> <p class="category" align="center">Last updated on {{ $customize->updated_at }} </p> </div> <div class="card-content table-responsive"> <p class="cen"><strong>Email:</strong> {{ $customize->email }}</p> <p class="cen"><strong>Contact No:</strong> {{ $customize->contact_no }}</p> <p class="cen"><strong>Itinerary:</strong> {{ $customize->itinerary->title }}</p> <h4 class="cen"><strong>Message</strong></h4> <div class="cen"> <p class="cen">{!! $customize->description !!}</p> </div> <div class="single-button"> <button class="btn-edit"><a href="{{ route('backend.customize.get.update', ['customize_id' => $customize->id]) }}">Edit</a></button> <button class="btn-delete"><a href="{{ route('backend.customize.trash', ['customize_id' => $customize->id]) }}">Delete</a></button> </div> </div> </div> </div> </div> </div> </div> @endsection
chandraknight/YatriNepal
resources/views/backend/customize/single_customize.blade.php
PHP
gpl-3.0
2,513
/* Copyright 2015 This file is part of Thufir the Confessor . Thufir the Confessor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Thufir the Confessor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ package confessor.thufir; import android.content.Context; import android.os.Handler; import android.util.Log; import android.widget.Toast; import confessor.thufir.lib.ClosedException; import confessor.thufir.lib.stream.ErrorHandler; public class AndroidErrorHandler implements ErrorHandler { public static final String LOG="thufir"; private final Context context; private final Handler handler; public AndroidErrorHandler(Context context, Handler handler) { this.context=context; this.handler=handler; } public static void d(String message) { Log.d(LOG, message); } public static void d(String message, Throwable throwable) { Log.d(LOG, message, throwable); } public static void d(Throwable throwable) { Log.d(LOG, "", throwable); } @Override public void error(final Throwable throwable) { d(throwable); if (!(throwable instanceof ClosedException)) { handler.post(new Runnable() { @Override public void run() { Toast.makeText(context, throwable.toString(), Toast.LENGTH_LONG) .show(); } }); } } }
thufirtheconfessor/thufirtheconfessor
src/confessor/thufir/AndroidErrorHandler.java
Java
gpl-3.0
1,777
#castle script for minecraft by joshua cartwright from mcpi import minecraft from mcpi import block import time mc = minecraft.Minecraft.create() #castle pos = mc.player.getPos() #clear mc.setBlocks(pos.x-5,pos.y-1,pos.z-5,pos.x+5,pos.y+50,pos.z+5,block.AIR) #floor mc.setBlocks(pos.x-5,pos.y-1,pos.z-5,pos.x+5,pos.y,pos.z+5,block.COBBLESTONE) #walls mc.setBlocks(pos.x-5,pos.y,pos.z-5,pos.x+5,pos.y+4,pos.z-5,block.COBBLESTONE) mc.setBlocks(pos.x-5,pos.y,pos.z+5,pos.x+5,pos.y+4,pos.z+5,block.COBBLESTONE) mc.setBlocks(pos.x-5,pos.y,pos.z-5,pos.x-5,pos.y+4,pos.z+5,block.COBBLESTONE) mc.setBlocks(pos.x+5,pos.y,pos.z-5,pos.x+5,pos.y+4,pos.z+5,block.COBBLESTONE) #walkway mc.setBlocks(pos.x-4,pos.y+3,pos.z-4,pos.x+4,pos.y+3,pos.z+4,block.COBBLESTONE) mc.setBlocks(pos.x-3,pos.y+3,pos.z-3,pos.x+3,pos.y+3,pos.z+3,block.AIR) #door mc.setBlocks(pos.x+5,pos.y+1,pos.z,pos.x+5,pos.y+2,pos.z,block.AIR) #stairs mc.setBlocks(pos.x+4,pos.y+1,pos.z+3,pos.x+4,pos.y+2,pos.z+3,block.COBBLESTONE) mc.setBlocks(pos.x+3,pos.y+1,pos.z+3,pos.x+3,pos.y+2,pos.z+3,block.COBBLESTONE) mc.setBlock(pos.x+3,pos.y+3,pos.z+3,67,0) mc.setBlock(pos.x+2,pos.y+1,pos.z+3,block.COBBLESTONE) mc.setBlock(pos.x+2,pos.y+2,pos.z+3,67,0) mc.setBlock(pos.x+1,pos.y+1,pos.z+3,67,0) mc.setBlocks(pos.x-3,pos.y+1,pos.z+4,pos.x-3,pos.y+2,pos.z+4,block.COBBLESTONE) mc.setBlocks(pos.x-3,pos.y+1,pos.z+3,pos.x-3,pos.y+2,pos.z+3,block.COBBLESTONE) mc.setBlock(pos.x-3,pos.y+3,pos.z+3,67,2) mc.setBlock(pos.x-3,pos.y+1,pos.z+2,block.COBBLESTONE) mc.setBlock(pos.x-3,pos.y+2,pos.z+2,67,2) mc.setBlock(pos.x-3,pos.y+1,pos.z+1,67,2) mc.setBlocks(pos.x+3,pos.y+1,pos.z-4,pos.x+3,pos.y+2,pos.z-4,block.COBBLESTONE) mc.setBlocks(pos.x+3,pos.y+1,pos.z-3,pos.x+3,pos.y+2,pos.z-3,block.COBBLESTONE) mc.setBlock(pos.x+3,pos.y+3,pos.z-3,67,3) mc.setBlock(pos.x+3,pos.y+1,pos.z-2,block.COBBLESTONE) mc.setBlock(pos.x+3,pos.y+2,pos.z-2,67,3) mc.setBlock(pos.x+3,pos.y+1,pos.z-1,67,3) mc.setBlocks(pos.x-4,pos.y+1,pos.z-3,pos.x-4,pos.y+2,pos.z-3,block.COBBLESTONE) mc.setBlocks(pos.x-3,pos.y+1,pos.z-3,pos.x-3,pos.y+2,pos.z-3,block.COBBLESTONE) mc.setBlock(pos.x-3,pos.y+3,pos.z-3,67,1) mc.setBlock(pos.x-2,pos.y+1,pos.z-3,block.COBBLESTONE) mc.setBlock(pos.x-2,pos.y+2,pos.z-3,67,1) mc.setBlock(pos.x-1,pos.y+1,pos.z-3,67,1) #holes mc.setBlock(pos.x+4,pos.y+2,pos.z+5,block.FENCE) mc.setBlock(pos.x+2,pos.y+2,pos.z+5,block.FENCE) mc.setBlock(pos.x,pos.y+2,pos.z+5,block.FENCE) mc.setBlock(pos.x-2,pos.y+2,pos.z+5,block.FENCE) mc.setBlock(pos.x-4,pos.y+2,pos.z+5,block.FENCE) mc.setBlock(pos.x+4,pos.y+2,pos.z-5,block.FENCE) mc.setBlock(pos.x+2,pos.y+2,pos.z-5,block.FENCE) mc.setBlock(pos.x,pos.y+2,pos.z-5,block.FENCE) mc.setBlock(pos.x-2,pos.y+2,pos.z-5,block.FENCE) mc.setBlock(pos.x-4,pos.y+2,pos.z-5,block.FENCE) mc.setBlock(pos.x+5,pos.y+2,pos.z+4,block.FENCE) mc.setBlock(pos.x+5,pos.y+2,pos.z+2,block.FENCE) mc.setBlock(pos.x+5,pos.y+2,pos.z-2,block.FENCE) mc.setBlock(pos.x+5,pos.y+2,pos.z-4,block.FENCE) mc.setBlock(pos.x-5,pos.y+2,pos.z+4,block.FENCE) mc.setBlock(pos.x-5,pos.y+2,pos.z+2,block.FENCE) mc.setBlock(pos.x-5,pos.y+2,pos.z,block.FENCE) mc.setBlock(pos.x-5,pos.y+2,pos.z-2,block.FENCE) mc.setBlock(pos.x-5,pos.y+2,pos.z-4,block.FENCE) #holes roof mc.setBlock(pos.x+4,pos.y+4,pos.z+5,block.AIR) mc.setBlock(pos.x+2,pos.y+4,pos.z+5,block.AIR) mc.setBlock(pos.x,pos.y+4,pos.z+5,block.AIR) mc.setBlock(pos.x-2,pos.y+4,pos.z+5,block.AIR) mc.setBlock(pos.x-4,pos.y+4,pos.z+5,block.AIR) mc.setBlock(pos.x+4,pos.y+4,pos.z-5,block.AIR) mc.setBlock(pos.x+2,pos.y+4,pos.z-5,block.AIR) mc.setBlock(pos.x,pos.y+4,pos.z-5,block.AIR) mc.setBlock(pos.x-2,pos.y+4,pos.z-5,block.AIR) mc.setBlock(pos.x-4,pos.y+4,pos.z-5,block.AIR) mc.setBlock(pos.x+5,pos.y+4,pos.z+4,block.AIR) mc.setBlock(pos.x+5,pos.y+4,pos.z+2,block.AIR) mc.setBlock(pos.x+5,pos.y+4,pos.z,block.AIR) mc.setBlock(pos.x+5,pos.y+4,pos.z-2,block.AIR) mc.setBlock(pos.x+5,pos.y+4,pos.z-4,block.AIR) mc.setBlock(pos.x-5,pos.y+4,pos.z+4,block.AIR) mc.setBlock(pos.x-5,pos.y+4,pos.z+2,block.AIR) mc.setBlock(pos.x-5,pos.y+4,pos.z,block.AIR) mc.setBlock(pos.x-5,pos.y+4,pos.z-2,block.AIR) mc.setBlock(pos.x-5,pos.y+4,pos.z-4,block.AIR) #well time.sleep(.25) mc.setBlocks(pos.x+1,pos.y+1,pos.z+1,pos.x-1,pos.y+3,pos.z-1,block.COBBLESTONE) mc.setBlocks(pos.x+1,pos.y+2,pos.z,pos.x-1,pos.y+2,pos.z,block.AIR) mc.setBlocks(pos.x,pos.y+2,pos.z-1,pos.x,pos.y+2,pos.z+1,block.AIR) mc.setBlocks(pos.x,pos.y+1,pos.z,pos.x,pos.y+2,pos.z,block.AIR) mc.setBlock(pos.x,pos.y+4,pos.z,block.COBBLESTONE) mc.setBlock(pos.x+1,pos.y+1,pos.z,63,4) #mc.setBlock(pos.x+2,pos.y,pos.z,block.AIR) #bacement time.sleep(.25) mc.setBlocks(pos.x-5,pos.y-2,pos.z-5,pos.x+5,pos.y-6,pos.z+5,block.COBBLESTONE) mc.setBlocks(pos.x-4,pos.y-2,pos.z-4,pos.x+4,pos.y-5,pos.z+4,block.AIR) mc.setBlocks(pos.x-4,pos.y-5,pos.z-4,pos.x+4,pos.y-5,pos.z+4,block.BOOKSHELF) mc.setBlocks(pos.x-3,pos.y-5,pos.z-3,pos.x+3,pos.y-5,pos.z+3,block.AIR) mc.setBlocks(pos.x+1,pos.y-5,pos.z-1,pos.x+3,pos.y-5,pos.z+1,35,2) mc.setBlocks(pos.x+4,pos.y-5,pos.z-1,pos.x+4,pos.y-5,pos.z+1,35,0) mc.setBlock(pos.x+4,pos.y-5,pos.z+4,block.GLOWSTONE_BLOCK) mc.setBlock(pos.x+4,pos.y-5,pos.z-4,block.GLOWSTONE_BLOCK) mc.setBlock(pos.x-4,pos.y-5,pos.z+4,block.GLOWSTONE_BLOCK) mc.setBlock(pos.x-4,pos.y-5,pos.z-4,block.GLOWSTONE_BLOCK) mc.setBlock(pos.x,pos.y-6,pos.z,block.AIR) mc.setBlock(pos.x,pos.y-7,pos.z,block.COBBLESTONE) time.sleep(.25) mc.setBlock(pos.x,pos.y+1,pos.z,block.WATER) time.sleep(.25) mc.setBlocks(pos.x,pos.y,pos.z,pos.x,pos.y-4,pos.z,block.AIR) #set location mc.setBlock(pos.x+6,pos.y,pos.z,block.COBBLESTONE) mc.setBlocks(pos.x+6,pos.y+1,pos.z,pos.x+6,pos.y+2,pos.z,block.AIR) time.sleep(.25) mc.player.setPos(pos.x+6,pos.y+1,pos.z)
UTC-Sheffield/mcpi_ideas
misc/Castle.py
Python
gpl-3.0
5,725
/** * Copyright (c) 2012-2013 Kcchouette on Github * This file is part of nombre_mystere. * nombre_mystere is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * nombre_mystere is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with nombre_mystere. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <iomanip> using namespace std; #include "Decor.h" void afficherAccueil(const char OS[10], const char m[10]) { cout << "\nBienvenue sur la version " << OS << " du programme \"NOMBRE " << m << "\" !\n"<<endl; } void afficherDecor (){ cout << "+" << setfill('-') << setw(79) << "+" << endl << endl; }
Kcchouette/nombre_mystere
Decor.cpp
C++
gpl-3.0
1,101
class ProjectVersion < ActiveRecord::Base unloadable belongs_to :project default_scope { order('created_at DESC') } serialize :user_ids serialize :custom_field def self.observed %w(name status user_ids custom_field) end def previous if persisted? ProjectVersion.where('id < :version_id AND project_id = :project_id', {:version_id => self.id, :project_id => self.project_id}).first else project.project_versions.first end end def first_instance? !previous end def changed_attrs prev_version = previous return { :status => nil } unless prev_version attributes.keys.select{ |k| self.class.observed.include?(k) }. select{ |a| prev_version[a] != send(:[], a) }. inject({}){ |h, key| h[key] = prev_version[key]; h }.symbolize_keys end def same_as_previous? last = previous return false unless last self.class.observed.each do |k| return false unless observed_attrs[k] == last.observed_attrs[k] end true end def observed_attrs @observed_attrs ||= attributes.select { |k,_| self.class.observed.include?(k) } end end
efigence/redmine_accounting
app/models/project_version.rb
Ruby
gpl-3.0
1,145
# -*- coding: binary -*- module Rex module Java module Serialization module Model # This class provides a Java classDesc representation class ClassDesc < Element include Rex::Java::Serialization::Model::Contents attr_accessor :description # @param stream [Rex::Java::Serialization::Model::Stream] the stream where it belongs to def initialize(stream = nil) super(stream) self.description = nil end # Deserializes a Rex::Java::Serialization::Model::ClassDesc # # @param io [IO] the io to read from # @return [self] if deserialization succeeds # @raise [Rex::Java::Serialization::DecodeError] if deserialization doesn't succeed def decode(io) content = decode_content(io, stream) allowed_contents = [NullReference, NewClassDesc, Reference, ProxyClassDesc] unless allowed_contents.include?(content.class) raise Rex::Java::Serialization::DecodeError, 'ClassDesc unserialize failed' end self.description = content self end # Serializes the Rex::Java::Serialization::Model::ClassDesc # # @return [String] if serialization succeeds # @raise [Rex::Java::Serialization::EncodeError] if serialization doesn't succeed def encode encoded = '' allowed_contents = [NullReference, NewClassDesc, Reference, ProxyClassDesc] unless allowed_contents.include?(description.class) raise Rex::Java::Serialization::EncodeError, 'Failed to serialize ClassDesc' end encoded << encode_content(description) encoded end # Creates a print-friendly string representation # # @return [String] def to_s print_content(description) end end end end end end
cSploit/android.MSF
lib/rex/java/serialization/model/class_desc.rb
Ruby
gpl-3.0
2,018
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2017.09.08 um 03:06:37 PM CEST // package com.saucecode.packer.xml; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für anonymous complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.saucecode.com/packer/xml}category" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "category" }) @XmlRootElement(name = "categories") public class Categories { @XmlElement(required = true) protected List<String> category; /** * Gets the value of the category property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the category property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCategory().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getCategory() { if (category == null) { category = new ArrayList<String>(); } return this.category; } }
sauce-code/packer
src/main/java/com/saucecode/packer/xml/Categories.java
Java
gpl-3.0
2,306
class CreateUsers < ActiveRecord::Migration def self.up create_table "users", :force => true do |t| t.column :login, :string, :limit => 40 t.column :name, :string, :limit => 100, :default => '', :null => true t.column :email, :string, :limit => 100 t.column :crypted_password, :string, :limit => 40 t.column :salt, :string, :limit => 40 t.column :created_at, :datetime t.column :updated_at, :datetime t.column :remember_token, :string, :limit => 40 t.column :remember_token_expires_at, :datetime # custom settings t.column :icq_im, :string t.column :jabber, :string t.column :telephone, :string t.column :street, :string t.column :house_nr, :string t.column :zip_code, :integer t.column :city, :string t.column :birthdate, :date t.column :comment, :text t.column :is_admin, :boolean, :default => false end add_index :users, :login, :unique => true # create standard admin user u = User.create!(:name => "Adminis Trator", :login => "admin", :password => "password", :password_confirmation => "password", :email => "admin@localhost.com") u.is_admin = true u.save! end def self.down drop_table "users" end end
bakkdoor/projectmanager
db/migrate/20081008200458_create_users.rb
Ruby
gpl-3.0
1,473
/* * Copyright (C) 2014 William Shere * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.quew8.ttg; import java.awt.Desktop; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import javafx.application.Application; import javafx.collections.ListChangeListener; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.ContextMenu; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @author Quew8 */ public class TruthTableGenerator extends Application { public static final boolean DEBUG = false; public static final String VERSION = "1.0"; private TabPane tabPane; @Override public void start(Stage stage) throws IOException { VBox root = new VBox(); tabPane = new TabPane(); final Stage finStage = stage; tabPane.getTabs().addListener(new ListChangeListener<Tab>() { @Override public void onChanged(ListChangeListener.Change<? extends Tab> c) { if(c.getList().isEmpty()) { finStage.close(); } } }); newTab(); root.getChildren().addAll(createMenuBar(), tabPane); Scene scene = new Scene(root); stage.setTitle("Truth Table Generator " + VERSION); stage.setScene(scene); stage.show(); } public void newTab() { try { final Tab t = new Tab("Function"); t.setContent((Node) FXMLLoader.load(getClass().getResource("Main.fxml"))); t.setContextMenu(createTabContextMenu(t)); tabPane.getTabs().add(t); } catch(IOException ex) { throw new RuntimeException(ex); } } public void newStepThroughTab() { try { final Tab t = new Tab("Step"); t.setContent((Node) FXMLLoader.load(getClass().getResource("StepThrough.fxml"))); t.setContextMenu(createTabContextMenu(t)); tabPane.getTabs().add(t); } catch(IOException ex) { throw new RuntimeException(ex); } } private MenuBar createMenuBar() { MenuBar menuBar = new MenuBar(); Menu functions = new Menu("Functions"); functions.getItems().addAll(getCommonFunctionMenus()); Menu help = new Menu("Help"); MenuItem about = new MenuItem("About"); about.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { if(Desktop.isDesktopSupported()) { File tempFile = File.createTempFile("readme", ".txt"); try(BufferedReader reader = new BufferedReader( new InputStreamReader( TruthTableGenerator.class.getResourceAsStream("readme.txt") ) )) { try(BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) { String s; while((s = reader.readLine()) != null) { writer.write(s); writer.newLine(); } Desktop.getDesktop().open(tempFile); } } } } catch(IOException ex) { throw new RuntimeException(ex); } } }); help.getItems().addAll(about); menuBar.getMenus().addAll(functions, help); return menuBar; } private ContextMenu createTabContextMenu(final Tab t) { ContextMenu menu = new ContextMenu(); MenuItem delete = new MenuItem("Delete"); delete.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { tabPane.getTabs().remove(t); } }); menu.getItems().addAll(getCommonFunctionMenus()); menu.getItems().addAll(delete); return menu; } private MenuItem[] getCommonFunctionMenus() { MenuItem addMenuItem = new MenuItem("Add Function"); addMenuItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { newTab(); } }); MenuItem addStepThroughMenuItem = new MenuItem("Add Step Through Function"); addStepThroughMenuItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent evt) { newStepThroughTab(); } }); return new MenuItem[]{addMenuItem, addStepThroughMenuItem}; } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
Quew8/Truth-Table-Generator
src/com/quew8/ttg/TruthTableGenerator.java
Java
gpl-3.0
6,259
#include <iostream> using namespace std; int main() { int N, num, min, min_index, i; cin >> N; min = 999; min_index = 0; for ( i = 1; i <= N; i++ ) { cin >> num; if ( num < min ) { min = num; min_index = i; } } cout << min_index << endl; return 0; }
ProgDan/maratona
URI/URI 1858.cpp
C++
gpl-3.0
309
/* bibf - a simple bibtex pretty printer * * Copyright (C) 2014 Dennis Dast <mail@ddast.de> * * This file is part of bibf. * * bibf is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * bibf is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with bibf. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <sstream> #include <boost/algorithm/string/predicate.hpp> #include "Constants.hpp" #include "DataStructure.hpp" #include "Parser.hpp" #include "Strings.hpp" #include "Bibliography.hpp" namespace bstring = boost::algorithm; std::string Bibliography::clean_key(std::string key) const { // allowed characters in key std::string allowed = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "1234567890:.-"; // delete all not allowed keys while (true) { size_t pos = key.find_first_not_of(allowed); if (pos == std::string::npos) break; key.erase(pos, 1); } return key; } std::string Bibliography::get_lastname(std::string author) const { // get the first author size_t found = author.find(" and "); if (found != std::string::npos) author = author.substr(0, found); // get last name found = author.find(","); if (found != std::string::npos) author = author.substr(0, found); else { std::stringstream author_ss(author); while (author_ss >> author); } if (author.empty()) { std::cerr << Strings::tr(Strings::ERR_EMPTY_AUTHOR) << std::endl; return ""; } // return last name of first author return author; } bool Bibliography::is_numerical(const std::string& s) const { size_t found = s.find_first_not_of("1234567890"); return (found==std::string::npos); } void Bibliography::print_bib(std::ostream &os) const { std::vector<std::string> empty; print_bib(empty, os); } void Bibliography::print_bib(std::vector<std::string> only, std::ostream &os) const { check_consistency(); bool print_all = only.empty(); // convert list to lowercase if (!print_all) for (std::string& s : only) std::transform(s.begin(), s.end(), s.begin(), ::tolower); // iterate over all entries (use copies) for (bibEntry bEn : *bib) { // delete all entries which are not printed if (!print_all) { bEn.element.erase( std::remove_if(bEn.element.begin(), bEn.element.end(), [&] (bibElement bEl) -> bool { std::transform(bEl.field.begin(), bEl.field.end(), bEl.field.begin(), ::tolower); for (const std::string &po : only) { if (po == bEl.field) return false; } return true; }), bEn.element.end()); } // search for longest field name unsigned int longest_field = 0; if (right_aligned) { for (const bibElement &bEl : bEn.element) if (bEl.field.length() > longest_field) longest_field = bEl.field.length(); } // print key os << '@' << bEn.type << '{' << bEn.key; // print elements for (const bibElement& bEl : bEn.element) { os << ",\n"; // Use no field delimiters if value is a numeric bool print_delimiter = true; if (is_numerical(bEl.value)) print_delimiter = false; // Or if the month field uses three-letter abbreviations std::string field = bEl.field; std::transform(field.begin(), field.end(), field.begin(), ::tolower); if ( (field == "month") && Constants::is_valid_month_abbreviation(bEl.value) ) print_delimiter = false; // construct line std::string line; if (right_aligned) { for (unsigned int i = 0, end = longest_field-field.length(); i < end; ++i) line.push_back(' '); } line += intend + bEl.field + " = "; std::string intend_after_break; for (unsigned int i = 0, length = line.length(); i < length; ++i) intend_after_break.push_back(' '); if (print_delimiter) line += field_beg + bEl.value + field_end; else line += bEl.value; // break after 'linebreak' characters line = break_string(line, intend_after_break); os << line; } // finish entry os << "\n}\n" << std::endl; } } std::string Bibliography::break_string(std::string str, const std::string &intend) const { std::vector<std::string> lines; bool unbreakable = false; size_t minlen = intend.size(); while ((str.length() > linebreak) && !unbreakable) { for (unsigned int i = linebreak; i >= minlen; --i) { if (str[i] == ' ') { str[i] = '\n'; lines.push_back(str.substr(0, i+1)); str.erase(0, i+1); str = intend + str; break; } if ( i == minlen ) { size_t found = str.find(' ', linebreak); if (found == std::string::npos) { unbreakable = true; break; } str[found] = '\n'; lines.push_back(str.substr(0, found+1)); str.erase(0, found+1); str = intend + str; break; } } } std::string result(""); for (const std::string &l: lines) result += l; result += str; return result; } Bibliography::Bibliography() : intend(" "), linebreak(79), field_beg('{'), field_end('}'), right_aligned(true) { bib = new std::vector<bibEntry>; } Bibliography::~Bibliography() { delete bib; } void Bibliography::add(std::istream &is) { // create parsing object Parser parser; // add the stream to the bibliography parser.add(is, *bib); delete_redundant_entries(); } void Bibliography::create_entry() { // create new bibEntry bibEntry bEn; // ask for key std::cerr << Strings::tr(Strings::OUT_CREATE_ENTRY_KEY); std::string key; std::getline(std::cin, key); bEn.key = key; // ask for type std::cerr << Strings::tr(Strings::OUT_CREATE_ENTRY_TYPE); std::string type; std::getline(std::cin, type); if (type.empty()) { std::cerr << Strings::tr(Strings::ERR_CREATE_ENTRY_TYPE_NEEDED); return; } bEn.type = type; // get list of required and optional fields for the given type std::vector<std::string> required = Constants::get_required_values(type); std::vector<std::string> optional = Constants::get_optional_values(type); // add required fields if (!required.empty()) { std::cerr << Strings::tr(Strings::OUT_CREATE_ENTRY_REQ); ask_for_fields(bEn, required); } // ask if optional fields should be added if (!optional.empty()) { std::cerr << Strings::tr(Strings::OUT_CREATE_ENTRY_OPT); std::string input; std::getline(std::cin, input); if (input != "n") { ask_for_fields(bEn, optional); } } else if (required.empty()) { std::cerr << Strings::tr(Strings::OUT_CREATE_ENTRY_UNKNOWN); } // ask for arbitrary entries until empty input std::cerr << Strings::tr(Strings::OUT_CREATE_ENTRY_ARB); while (true) { std::string field; std::getline(std::cin, field); if (field.empty()) break; std::cerr << field << ": "; std::string value; std::getline(std::cin, value); if (value.empty()) break; bibElement bEl; bEl.field = field; bEl.value = value; bEn.element.push_back(bEl); } // add newly created entry to bibliography bib->push_back(bEn); } void Bibliography::ask_for_fields(bibEntry &bEn, const std::vector<std::string> &fields) const { // iterate over all entries for (const std::string &field : fields) { // check for alternative values auto found = field.find(" "); if (found != std::string::npos) { std::stringstream alt_ss(field); std::string alt1, alt2; alt_ss >> alt1 >> alt2; std::cerr << alt1 << Strings::tr(Strings::OUT_CREATE_ENTRY_ALT1) << alt2 << Strings::tr(Strings::OUT_CREATE_ENTRY_ALT2); std::vector<std::string> alt_fields = {alt1, alt2}; ask_for_fields(bEn, alt_fields); continue; } // ask user if no alternative value is possible std::cerr << field << ": "; std::string input; std::getline(std::cin, input); // skip if no input was given if (input.empty()) continue; // else add new bibElement bibElement bEl; bEl.field = field; bEl.value = input; bEn.element.push_back(bEl); } } void Bibliography::check_consistency() const { if (bib->empty()) { std::cerr << Strings::tr(Strings::ERR_EMPTY_BIB); return; } // check if keys are empty for (const bibEntry& bEn : *bib) { if (bEn.key.empty()) { std::cerr << Strings::tr(Strings::ERR_EMPTY_KEY) << get_field_value(bEn, "title") << "\"\n"; } } // check if every key is unique for (auto it1 = bib->begin(), end = bib->end(); it1 != end-1; ++it1) { for (auto it2 = it1+1; it2 != end; ++it2) { if (it1->key == it2->key) { std::cerr << Strings::tr(Strings::ERR_DOUBLE_KEY_1) << it1->key << Strings::tr(Strings::ERR_DOUBLE_KEY_2); } } } } std::string Bibliography::get_field_value(const bibEntry &bE, std::string field) const { // transform to lower case std::transform(field.begin(), field.end(), field.begin(), ::tolower); // search for entry for (const bibElement& bEl : bE.element) { std::string current = bEl.field; std::transform(current.begin(), current.end(), current.begin(), ::tolower); if (current == field) return bEl.value; } // return empty string if field was not found return ""; } void Bibliography::create_keys() { // iterate over all entries in the bibliography for (auto it = bib->begin(), end = bib->end(); it != end; ++it) { // get lastname std::string author = get_lastname(get_field_value(*it, "author")); // get the last two digits of the year std::string year = get_field_value(*it, "year"); if (year.length() >= 2) year = year.substr(year.length()-2, 2); // key is author plus year it->key = author + year; // add identifier (a,b,c...) to the key char id = 'a'; for (auto it2 = bib->begin(); it2 != it; ++it2) if (it->key == it2->key.substr(0,it2->key.length()-1)) ++id; if (id > 'z') { std::cerr << Strings::tr(Strings::ERR_RAN_OUT_OF_IDS_1) << author << Strings::tr(Strings::ERR_RAN_OUT_OF_IDS_2) << year << Strings::tr(Strings::ERR_RAN_OUT_OF_IDS_3) << std::endl; break; } it->key += id; // clean all not allowed characters it->key = clean_key(it->key); } } void Bibliography::change_case(const char case_t, const char case_f) { // operation for the types int (*touplo_t)(int); if (case_t == 'U') touplo_t= &std::toupper; else if (case_t == 'L') touplo_t= &std::tolower; else if (case_t == 'S') touplo_t= &std::tolower; else { std::cerr << Strings::tr(Strings::ERR_UNKNOWN_CHANGE_CASE_T) << case_t << std::endl; return; } // operation for the fields int (*touplo_f)(int); if (case_f == 'U') touplo_f= &std::toupper; else if (case_f == 'L') touplo_f= &std::tolower; else if (case_f == 'S') touplo_f= &std::tolower; else { std::cerr << Strings::tr(Strings::ERR_UNKNOWN_CHANGE_CASE_F) << case_f << std::endl; return; } for (bibEntry& bEn : *bib) { std::transform(bEn.type.begin(), bEn.type.end(), bEn.type.begin(), touplo_t); if (case_t == 'S') bEn.type[0] = toupper(bEn.type[0]); for (bibElement& bEl : bEn.element) { std::transform(bEl.field.begin(), bEl.field.end(), bEl.field.begin(), touplo_f); if (case_f == 'S') bEl.field[0] = toupper(bEl.field[0]); } } } void Bibliography::erase_field(std::string field) { std::transform(field.begin(), field.end(), field.begin(), ::tolower); auto compare = [&] (bibElement& el) -> bool { std::string cur = el.field; std::transform(cur.begin(), cur.end(), cur.begin(), ::tolower); if (cur == field) return true; else return false; }; for (bibEntry& bEn : *bib) bEn.element.erase( std::remove_if(bEn.element.begin(), bEn.element.end(), compare), bEn.element.end() ); } void Bibliography::sort_bib(std::vector<std::string> criteria) { // check if 'bE1' is smaller than 'bE2' using the given criteria auto cmp_after_criteria = [&] (const bibEntry& bE1, const bibEntry& bE2) -> bool { for (std::string& cur_crit : criteria) { std::transform(cur_crit.begin(), cur_crit.end(), cur_crit.begin(), ::tolower); std::string str1(""); std::string str2(""); if (cur_crit == "type") { str1 = bE1.type; str2 = bE2.type; } else if (cur_crit == "key") { str1 = bE1.key; str2 = bE2.key; } else if (cur_crit == "firstauthor") { str1 = get_field_value(bE1, "author"); str1 = get_lastname(str1); str2 = get_field_value(bE2, "author"); str2 = get_lastname(str2); } else { str1 = get_field_value(bE1, cur_crit); str2 = get_field_value(bE2, cur_crit); } if (bstring::iequals(str1, str2)) { continue; } return bstring::ilexicographical_compare(str1, str2); } return false; }; // sort bibliography stable std::stable_sort(bib->begin(), bib->end(), cmp_after_criteria); } void Bibliography::sort_elements() { // define compare function auto compare_field = [] (const bibElement& bEl1, const bibElement& bEl2) -> bool { if (bEl1.field < bEl2.field) return true; return false; }; // sort elements in each entry for (bibEntry& bEn : *bib) { std::sort(bEn.element.begin(), bEn.element.end(), compare_field); } } void Bibliography::set_intendation(const std::string& str) { // check for consitency and set intendation intend = str; if (intend.length()+1 >= linebreak) linebreak = intend.length()+1; } void Bibliography::set_linebreak(unsigned int i) { // check for consistency and set linebreak if (i > 0) linebreak = i > intend.length() ? i : intend.length()+1; else linebreak = 0; } void Bibliography::set_alignment(bool _right_aligned) { right_aligned = _right_aligned; } void Bibliography::set_field_delimiter(char beg, char end) { // only {} and '' are valid delimiters but always set the delimiters field_beg = beg; field_end = end; if (!( (beg == '{') || (beg == '"') )) std::cerr << Strings::tr(Strings::ERR_ILLEGAL_FIELD_DELIMITER_BEG) << beg << std::endl; if (!( (end == '}') || (end == '"') )) std::cerr << Strings::tr(Strings::ERR_ILLEGAL_FIELD_DELIMITER_END) << beg << std::endl; } void Bibliography::show_missing_fields(bool only_required) const { // check for missing required fields for (const bibEntry& bEn : *bib) { std::vector<std::string> required = Constants::get_required_values(bEn.type); for (const std::string& current : required) { bool has_required_field = false; std::istringstream current_ss(current); for (std::string _current; std::getline(current_ss, _current, ' '); ) if (!(get_field_value(bEn, _current).empty())) has_required_field = true; if (!has_required_field) std::cerr << bEn.key << Strings::tr(Strings::OUT_MISSES_REQUIRED) << current << "\"" << std::endl; } if (only_required) continue; // check for missing optional fields std::vector<std::string> optional = Constants::get_optional_values(bEn.type); for (const std::string& current : optional) { bool has_optional_field = false; std::istringstream current_ss(current); for (std::string _current; std::getline(current_ss, _current, ' '); ) if (!(get_field_value(bEn, _current).empty())) has_optional_field = true; if (!has_optional_field) std::cerr << bEn.key << Strings::tr(Strings::OUT_MISSES_OPTIONAL) << current << "\"" << std::endl; } } } void Bibliography::show_missing_fields(std::vector<std::string> fields) const { for (const bibEntry& bEn : *bib) { for (std::string& current : fields) { if (get_field_value(bEn, current).empty()) std::cerr << bEn.key << Strings::tr(Strings::OUT_MISSING_FIELD) << current << "\"" << std::endl; } } } void Bibliography::abbreviate_month() { // try to find the correct abbreviation for (bibEntry& bEn : *bib) { for (bibElement& bEl : bEn.element) { std::string field = bEl.field; std::transform(field.begin(), field.end(), field.begin(), ::tolower); if (field == "month") bEl.value = Constants::find_month_abbreviation(bEl.value); } } } void Bibliography::delete_redundant_entries() { for (bibEntry &bEn: *bib) { for (const bibEntry &cmp : *bib) { // do not compare to itself if (&bEn == &cmp) { continue; } // do not compare to smaller entries (greater is allowed) if (cmp.element.size() < bEn.element.size()) { continue; } // compare elements, continue if mismatch bool field_mismatch = false; for (const bibElement &bEl : bEn.element) { if (bEl.value != get_field_value(cmp, bEl.field)) { field_mismatch = true; break; } } if (field_mismatch) { continue; } // compare types std::string type1(bEn.type), type2(cmp.type); std::transform(type1.begin(), type1.end(), type1.begin(), ::tolower); std::transform(type2.begin(), type2.end(), type2.begin(), ::tolower); if (type1 != type2) { continue; } // if we are still here, bEn is a subset of an other entry // clear element vector of redundant entries bEn.element.clear(); std::cerr << Strings::tr(Strings::ERR_REDUNDANT_ENTRY_1) << bEn.key << Strings::tr(Strings::ERR_REDUNDANT_ENTRY_2); break; } // no match was found } //delete entries with empty element vector bib->erase( std::remove_if(bib->begin(), bib->end(), // check if bEn is empty [](const bibEntry &bEn) -> bool { return bEn.element.empty(); } ), bib->end() ); }
ddast/bibf
src/Bibliography.cpp
C++
gpl-3.0
18,748
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; public class Student { public readonly int nr; public readonly string name; public readonly int group; public readonly string githubId; public Student(int nr, String name, int group, string githubId) { this.nr = nr; this.name = name; this.group = group; this.githubId = githubId; } public override String ToString() { return String.Format("{0} {1} ({2}, {3})", nr, name, group, githubId); } public void Print() { Console.WriteLine(this.ToString()); } public static Student Parse(object src){ string [] words = src.ToString().Split('|'); return new Student( int.Parse(words[0]), words[1], int.Parse(words[2]), words[3]); } } static class App { static List<String> Lines(string path) { string line; List<string> res = new List<string>(); using (StreamReader file = new StreamReader(path, Encoding.UTF8)) // <=> try-with resources do Java >= 7 { while ((line = file.ReadLine()) != null) { res.Add(line); } } return res; } static IEnumerable Convert(IEnumerable src, Mapping transf) { return new EnumerableConverter(src, transf); } static IEnumerable Filter(IEnumerable src, Predicate p) { return new EnumerableFilter(src, p); } static IEnumerable Distinct(IEnumerable src) { return new EnumerableDistinct(src); } static void Print(string label) { Console.WriteLine(label); } static void Main() { IEnumerable names = Distinct( Convert( Filter( Filter( Convert( Lines("i41n.txt"), line => Student.Parse(line)), s => ((Student) s).nr > 38000), s => ((Student) s).name.StartsWith("A")), s => ((Student) s).name.Split(' ')[0] ) ); foreach(object l in names) Console.WriteLine(l); } } delegate object Mapping(object item); delegate bool Predicate(object data); class EnumerableConverter : IEnumerable{ readonly IEnumerable src; readonly Mapping transf; public EnumerableConverter(IEnumerable src, Mapping transf) { this.src = src; this.transf = transf; } public IEnumerator GetEnumerator() { return new EnumeratorConverter(src.GetEnumerator(), transf); } } class EnumeratorConverter : IEnumerator{ readonly IEnumerator src; readonly Mapping transf; public EnumeratorConverter(IEnumerator src, Mapping transf) { this.src = src; this.transf = transf; } public bool MoveNext() { return src.MoveNext(); } public object Current { get{ return transf(src.Current); } } public void Reset() { src.Reset(); } } class EnumerableFilter : IEnumerable{ readonly IEnumerable src; readonly Predicate p; public EnumerableFilter(IEnumerable src, Predicate p) { this.src = src; this.p = p; } public IEnumerator GetEnumerator() { return new EnumeratorFilter(src.GetEnumerator(), p); } } class EnumeratorFilter : IEnumerator{ readonly IEnumerator src; readonly Predicate p; object curr; public EnumeratorFilter(IEnumerator src, Predicate p) { this.src = src; this.p = p; } public bool MoveNext() { while (src.MoveNext()) { curr = src.Current; if(p(curr)) return true; else curr = null; } return false; } public object Current { get{ return curr; } } public void Reset() { src.Reset(); } } class EnumerableDistinct : IEnumerable{ readonly IEnumerable src; public EnumerableDistinct(IEnumerable src) { this.src = src; } public IEnumerator GetEnumerator() { return new EnumeratorDistinct(src.GetEnumerator()); } } class EnumeratorDistinct : IEnumerator{ readonly IEnumerator src; readonly IList selected = new ArrayList(); object curr; public EnumeratorDistinct(IEnumerator src) { this.src = src; } public bool MoveNext() { while (src.MoveNext()) { curr = src.Current; if(!selected.Contains(curr)) { selected.Add(curr); return true; } } return false; } public object Current { get{ return curr; } } public void Reset() { src.Reset(); } }
isel-leic-ave/ave-2016-17-sem1-i41n
aula30-delegates-utils-generics/Queries3.cs
C#
gpl-3.0
5,191
void page2() { if (millis() - lastmillis >= 10000) { //Only do this every 10s if (newpage == 1) { //If we just started tft.fill(rgb(0, 0, 0)); //Clear the LCD newpage = 0; sensor = strtof (temp1, NULL); //Do this just in case they're empty sensor *= 100; xmax = float(scrmax) / 100; //Axis labels xmin = float(scrmin) / 100; xmid = (xmax + xmin) / 2; } lastmillis = millis(); // Update lastmillis tft.fill(rgb(0, 0, 0)); //Blank the screen tft.setTextSize(1); //Smallest text size tft.setTextColor(GREY, BLACK); tft.setCursor(105, 0); //Print axis labels tft.print(xmax); tft.setCursor(105,60); tft.print(xmid); tft.setCursor(105,120); tft.print(xmin); tft.setTextColor(RED, BLACK); //Print temp and last update time tft.setCursor(1, 3); tft.print(temp1); tft.setCursor(27, 3); tft.print("C "); tft.print(time1); tft.drawLine(0,64,105,64,GREY); //Draw axis lines tft.drawLine(0,0,105,0,GREY); tft.drawLine(0,127,105,127,GREY); for (int i = 1; i<103; i++) //drawArray is raw temp readings, we need to scale to LCD height { scaleddrawArray[i] = map(drawArray[i], scrmin, scrmax, 0, 128); } for (int i = 2; i<103; i++) { tft.drawLine (i-1, 128-scaleddrawArray[i-1], i, 128-scaleddrawArray[i], RED ); //Draw that fucker } tft.copy_buffer(); //LCD doesn't do nuffin till this } } /*This is in the setup section:*/ Particle.subscribe("Temperature", tempHandler, MY_DEVICES); /*And this all works, even if I go to a different "page" on the LCD for a few minutes, because this runs any time the other Photon sends a new temperature value:*/ void tempHandler(const char *event, const char *data) //Particle.subscribe events { detachInterrupt(D5); //Stop listening for button presses cause they'll break things strcpy (temp1, data); //Assign the data we got from the new temp info to "temp1" as a string strcpy (time1, (Time.format(Time.now(), "%l:%M:%S %p"))); //Time1 is the last time we got an update sensor = strtof (temp1, NULL); //"sensor" is a float version of temp1 sensor *= 100; //Multiply it by 100 because reasons if (scrmax == 0) {scrmax = sensor + 100;} //If this is the first time, set the graph ranges to + or - 1C if (scrmin == 0) {scrmin = sensor - 100;} if (sensor > scrmax) { scrmax = sensor; } //Auto-ranging of the graph y axis if (sensor < scrmin) { scrmin = sensor; } xmax = float(scrmax) / 100; //Graph axis labels xmin = float(scrmin) / 100; xmid = (xmax + xmin) / 2; if (firstvalue == 1) //If this is the first time { for(int i(0); i < 105; ++i) { drawArray[i] = sensor; //Fill the whole array with the current temp value so we start off with one straight line } firstvalue = 0; } drawArray[104] = sensor; //Set the newest value in the array to the current temp for(int i(0); i < 105; ++i) { tempArray[i-1] = drawArray[i]; //Then shift that array one to the left, for the scrolling effect } for(int i(0); i < 105; ++i) { drawArray[i] = tempArray[i]; //Then make a note of it } attachInterrupt(D5, btnpush, FALLING); //And now we can start listening for button presses again }
jhpolsky/arduinoScrollingGraph
graph.cpp
C++
gpl-3.0
3,364
/* * This file is part of myPlan. * * Plan is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * Plan is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with myPlan. If not, see <http://www.gnu.org/licenses/>. */ package com.conzebit.myplan.ext.es.vodafone.particulares.tallas; import java.util.ArrayList; import com.conzebit.myplan.core.Chargeable; import com.conzebit.myplan.core.call.Call; import com.conzebit.myplan.core.message.ChargeableMessage; import com.conzebit.myplan.core.msisdn.MsisdnType; import com.conzebit.myplan.core.plan.PlanChargeable; import com.conzebit.myplan.core.plan.PlanSummary; import com.conzebit.myplan.core.sms.Sms; import com.conzebit.myplan.ext.es.vodafone.ESVodafone; /** * Vodafone XS8. * * @author sanz */ public class ESVodafoneXS8 extends ESVodafone { private double minimumMonthFee = 8; private double initialPrice = 0.15; private double pricePerMinute = 0.08; private double smsPrice = 0.08; public String getPlanName() { return "XS 8"; } public String getPlanURL() { return "http://www.vodafone.es/static/microsites/contratohablardescripcion/legales-hablar2.html?hideNavs=yes"; } public PlanSummary process(ArrayList<Chargeable> data) { double globalPrice = 0; PlanSummary ret = new PlanSummary(this); for (Chargeable chargeable : data) { if (chargeable.getChargeableType() == Chargeable.CHARGEABLE_TYPE_CALL) { Call call = (Call) chargeable; if (call.getType() != Call.CALL_TYPE_SENT) { continue; } double callPrice = 0; if (call.getContact().getMsisdnType() == MsisdnType.ES_SPECIAL_ZER0) { callPrice = 0; } else { callPrice = initialPrice + (call.getDuration() * (pricePerMinute / 60)); } globalPrice += callPrice; ret.addPlanCall(new PlanChargeable(call, callPrice, this.getCurrency())); } else if (chargeable.getChargeableType() == Chargeable.CHARGEABLE_TYPE_SMS) { Sms sms = (Sms) chargeable; if (sms.getType() == Sms.SMS_TYPE_RECEIVED) { continue; } globalPrice += smsPrice; ret.addPlanCall(new PlanChargeable(chargeable, smsPrice, this.getCurrency())); } } if (globalPrice < minimumMonthFee) { ret.addPlanCall(new PlanChargeable(new ChargeableMessage(ChargeableMessage.MESSAGE_MINIMUM_MONTH_FEE), minimumMonthFee - globalPrice, this.getCurrency())); } return ret; } }
jmsanzg/myPlan
src/com/conzebit/myplan/ext/es/vodafone/particulares/tallas/ESVodafoneXS8.java
Java
gpl-3.0
2,811
/* * SLD Editor - The Open Source Java SLD Editor * * Copyright (C) 2017, SCISYS UK Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sldeditor.test.unit.tool.batchupdatefont; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.sldeditor.common.data.SLDData; import com.sldeditor.common.data.SelectedSymbol; import com.sldeditor.common.data.StyleWrapper; import com.sldeditor.common.defaultsymbol.DefaultSymbols; import com.sldeditor.common.localisation.Localisation; import com.sldeditor.common.output.SLDWriterInterface; import com.sldeditor.common.output.impl.SLDWriterFactory; import com.sldeditor.datasource.SLDEditorFile; import com.sldeditor.tool.batchupdatefont.BatchUpdateFontData; import com.sldeditor.tool.batchupdatefont.BatchUpdateFontModel; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.JTable; import org.geotools.factory.CommonFactoryFinder; import org.geotools.styling.FeatureTypeStyle; import org.geotools.styling.Font; import org.geotools.styling.NamedLayer; import org.geotools.styling.Rule; import org.geotools.styling.Style; import org.geotools.styling.StyleFactoryImpl; import org.geotools.styling.StyledLayerDescriptor; import org.geotools.styling.TextSymbolizer; import org.junit.jupiter.api.Test; import org.opengis.filter.FilterFactory; /** * The unit test for BatchUpdateFontData. * * <p>{@link com.sldeditor.tool.batchupdatefont.BatchUpdateFontModel} * * @author Robert Ward (SCISYS) */ public class BatchUpdateFontModelTest { /** * Test method for {@link * com.sldeditor.tool.batchupdatefont.BatchUpdateFontModel#loadData(java.util.List)}. */ @Test public void testLoadData() { StyledLayerDescriptor sld = DefaultSymbols.createNewSLD(); NamedLayer namedLayer = DefaultSymbols.createNewNamedLayer(); sld.layers().add(namedLayer); String expectedNamedLayer = "namedLayer"; namedLayer.setName(expectedNamedLayer); Style style = DefaultSymbols.createNewStyle(); String expectedStyleLayer = "style"; style.setName(expectedStyleLayer); namedLayer.addStyle(style); FeatureTypeStyle fts = DefaultSymbols.createNewFeatureTypeStyle(); String expectedFeatureTypeStyleLayer = "feature type style"; fts.setName(expectedFeatureTypeStyleLayer); style.featureTypeStyles().add(fts); Rule rule = DefaultSymbols.createNewRule(); fts.rules().add(rule); String expectedRule = "rule"; rule.setName(expectedRule); String expectedSymbolizer = "text symbolizer"; TextSymbolizer symbolizer = DefaultSymbols.createDefaultTextSymbolizer(); symbolizer.setName(expectedSymbolizer); rule.symbolizers().add(symbolizer); StyleFactoryImpl styleFactory = (StyleFactoryImpl) CommonFactoryFinder.getStyleFactory(); FilterFactory ff = CommonFactoryFinder.getFilterFactory(); Font font = styleFactory.createFont( ff.literal("abc"), ff.literal("normal"), ff.literal("normal"), ff.literal(10)); symbolizer.setFont(font); SLDWriterInterface sldWriter = SLDWriterFactory.createWriter(null); String sldContents = sldWriter.encodeSLD(null, sld); String expectedWorkspace = "workspace"; String expectedStyle = "layer.sld"; StyleWrapper styleWrapper = new StyleWrapper(expectedWorkspace, expectedStyle); SLDData data = new SLDData(styleWrapper, sldContents); File testFile = new File("test.sld"); data.setSLDFile(testFile); SLDEditorFile.getInstance().setSldFile(testFile); SLDEditorFile.getInstance().setSLDData(data); BatchUpdateFontData testObj = new BatchUpdateFontData(sld, data); SelectedSymbol.getInstance().setSld(sld); testObj.setNamedLayer(expectedNamedLayer); testObj.setStyle(expectedStyleLayer); testObj.setFeatureTypeStyle(expectedFeatureTypeStyleLayer); testObj.setRule(rule); testObj.setSymbolizer(symbolizer); testObj.setFont(font); List<BatchUpdateFontData> dataList = new ArrayList<BatchUpdateFontData>(); dataList.add(testObj); BatchUpdateFontModel model = new BatchUpdateFontModel(); model.loadData(dataList); for (int col = 0; col < model.getColumnCount(); col++) { assertFalse(model.hasValueBeenUpdated(0, col)); } assertFalse(model.anyChanges()); assertFalse(model.saveData(null)); List<Font> actualFontlist = model.getFontEntries(new int[] {0}); assertEquals(1, actualFontlist.size()); assertEquals(1, model.getRowCount()); // Update font String originalFontname = "New Font"; String originalFontStyle = "italic"; String originalFontWeight = "bold"; int originalFontSize = 16; font = styleFactory.createFont( ff.literal(originalFontname), ff.literal(originalFontStyle), ff.literal(originalFontWeight), ff.literal(originalFontSize)); model.applyData(new int[] {0}, font); assertTrue(model.hasValueBeenUpdated(0, 7)); assertTrue(model.hasValueBeenUpdated(0, 8)); assertTrue(model.hasValueBeenUpdated(0, 9)); assertTrue(model.hasValueBeenUpdated(0, 10)); assertTrue(model.anyChanges()); assertEquals(originalFontname, model.getValueAt(0, 7)); assertEquals(originalFontStyle, model.getValueAt(0, 8)); assertEquals(originalFontWeight, model.getValueAt(0, 9)); assertEquals(String.valueOf(originalFontSize), model.getValueAt(0, 10)); model.revertData(); assertFalse(model.anyChanges()); int expectedFontSize = 99; model.applyData(new int[] {0}, expectedFontSize); assertTrue(model.hasValueBeenUpdated(0, 10)); // Font size assertEquals(expectedWorkspace, model.getValueAt(0, 0)); assertEquals(expectedStyle, model.getValueAt(0, 1)); assertEquals(expectedNamedLayer, model.getValueAt(0, 2)); assertEquals(expectedStyleLayer, model.getValueAt(0, 3)); assertEquals(expectedFeatureTypeStyleLayer, model.getValueAt(0, 4)); assertEquals(expectedRule, model.getValueAt(0, 5)); assertEquals(expectedSymbolizer, model.getValueAt(0, 6)); assertEquals("abc", model.getValueAt(0, 7)); assertEquals("normal", model.getValueAt(0, 8)); assertEquals("normal", model.getValueAt(0, 9)); assertEquals(String.valueOf(10 + expectedFontSize), model.getValueAt(0, 10)); assertNull(model.getValueAt(0, 42)); assertTrue(model.saveData(null)); SelectedSymbol.destroyInstance(); SLDEditorFile.destroyInstance(); model.setColumnRenderer(null); JTable table = new JTable(); table.setModel(model); model.setColumnRenderer(table.getColumnModel()); assertFalse(model.isCellEditable(0, 0)); assertEquals( Localisation.getString( BatchUpdateFontModel.class, "BatchUpdateFontModel.workspace"), model.getColumnName(0)); } }
robward-scisys/sldeditor
modules/application/src/test/java/com/sldeditor/test/unit/tool/batchupdatefont/BatchUpdateFontModelTest.java
Java
gpl-3.0
8,178
#include <windows.h> #include <stdio.h> // DisplayText() ÇÔ¼ö »ç¿ëÀ» À§ÇØ ÇÊ¿äÇÑ Çì´õÆÄÀÏ // À©µµ¿ì ÇÁ·Î½ÃÀú LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // ÆíÁý ÄÁÆ®·Ñ Ãâ·Â ÇÔ¼ö void DisplayText(char *fmt, ...); // printf() ÇÔ¼ö¿Í °°Àº ±â´É HINSTANCE hInst; // ÀνºÅϽº ÇÚµé Àü¿ªº¯¼ö·Î ¼±¾ð HWND hEdit; // ÆíÁý ÄÁÆ®·Ñ Àü¿ªº¯¼ö·Î ¼±¾ð int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { hInst = hInstance; // ÀνºÅϽº ÇÚµéÀ» Àü¿ª º¯¼ö¿¡ ÀúÀå // À©µµ¿ì Ŭ·¡½º µî·Ï WNDCLASS wndclass; wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = "MyWndClass"; if(!RegisterClass(&wndclass)) return 1; // À©µµ¿ì »ý¼º HWND hWnd = CreateWindow("MyWndClass", "WinApp", WS_OVERLAPPEDWINDOW, 0, 0, 600, 200, NULL, NULL, hInstance, NULL); if(hWnd == NULL) return 1; ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); // ¸Þ½ÃÁö ·çÇÁ MSG msg; while(GetMessage(&msg, 0, 0, 0) > 0){ TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } // À©µµ¿ì ÇÁ·Î½ÃÀú LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg){ case WM_CREATE: // ¸ÞÀÎ À©µµ¿ì »ý¼º hEdit = CreateWindow("edit", NULL, WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_MULTILINE, 0, 0, 0, 0, hWnd, (HMENU)100, hInst, NULL); DisplayText("°£´ÜÇÑ GUI ÀÀ¿ë ÇÁ·Î±×·¥ÀÔ´Ï´Ù.\r\n"); DisplayText("ÀνºÅϽº Çڵ鰪Àº %#xÀÔ´Ï´Ù.\r\n", hInst); return 0; case WM_SIZE: MoveWindow(hEdit, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE); // Sleep(3000); return 0; case WM_SETFOCUS: // ¸ÞÀÎ À©µµ¿ì Űº¸µå Æ÷Ä¿½º¸¦ ¾òÀ½. SetFocus(hEdit); return 0; case WM_DESTROY: // ¸ÞÀÎ À©µµ¿ì¸¦ ´ÝÀ½. µ¿Àû¸Þ¸ð¸® ÇØÁ¦, ÆÄÀÏ ´Ý±âµî ¼öÇà PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } // ÆíÁý ÄÁÆ®·Ñ Ãâ·Â ÇÔ¼ö void DisplayText(char *fmt, ...) { va_list arg; va_start(arg, fmt); char cbuf[256]; vsprintf(cbuf, fmt, arg); int nLength = GetWindowTextLength(hEdit); // ÆíÁý ÄÁÆ®·Ñ¿¡ ¹®ÀÚ¿­À» Ãß°¡ SendMessage(hEdit, EM_SETSEL, nLength, nLength); SendMessage(hEdit, EM_REPLACESEL, FALSE, (LPARAM)cbuf); va_end(arg); }
aw15/GSE_2_2013184043
수업자료/Chapter09/WinApp.cpp
C++
gpl-3.0
2,541
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using Eto.Drawing; using Eto.Forms; namespace MonoGame.Tools.Pipeline { partial class ReferenceDialog : DialogBase { DynamicLayout layout1; StackLayout stack1; GridView grid1; Button buttonAdd, buttonRemove; private void InitializeComponent() { Title = "Reference Editor"; Resizable = true; Width = 500; Height = 400; layout1 = new DynamicLayout(); layout1.DefaultSpacing = new Size(4, 4); layout1.BeginHorizontal(); grid1 = new GridView(); grid1.Style = "GridView"; layout1.Add(grid1, true, true); stack1 = new StackLayout(); stack1.Orientation = Orientation.Vertical; stack1.Spacing = 4; buttonAdd = new Button(); buttonAdd.Text = "Add"; stack1.Items.Add(new StackLayoutItem(buttonAdd, false)); buttonRemove = new Button(); buttonRemove.Text = "Remove"; stack1.Items.Add(new StackLayoutItem(buttonRemove, false)); layout1.Add(stack1, false, true); CreateContent(layout1); grid1.SelectionChanged += Grid1_SelectionChanged; grid1.KeyDown += Grid1_KeyDown; buttonAdd.Click += ButtonAdd_Click; buttonRemove.Click += ButtonRemove_Click; } } }
Blucky87/Otiose2D
src/libs/MonoGame/Tools/Pipeline/Dialogs/ReferenceDialog.eto.cs
C#
gpl-3.0
1,597
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class scnCinematicAnimSetSRRef : CVariable { [Ordinal(0)] [RED("asyncAnimSet")] public raRef<animAnimSet> AsyncAnimSet { get; set; } [Ordinal(1)] [RED("priority")] public CUInt8 Priority { get; set; } [Ordinal(2)] [RED("isOverride")] public CBool IsOverride { get; set; } public scnCinematicAnimSetSRRef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/scnCinematicAnimSetSRRef.cs
C#
gpl-3.0
526